Changeset - r3765:c9eaea3d3f78
[Not reviewed]
master
0 6 0
peter1138 - 18 years ago 2006-05-06 21:46:26
peter1138@openttd.org
(svn r4757) - Newstations: add saveload support for custom station speclists
6 files changed with 53 insertions and 2 deletions:
0 comments (0 inline, 0 general)
newgrf_station.c
Show inline comments
 
/* $Id$ */
 

	
 
/** @file newgrf_station.c Functions for dealing with station classes and custom stations. */
 

	
 
#include "stdafx.h"
 
#include "openttd.h"
 
#include "variables.h"
 
#include "functions.h"
 
#include "debug.h"
 
#include "sprite.h"
 
#include "table/sprites.h"
 
#include "table/strings.h"
 
#include "station.h"
 
#include "station_map.h"
 
#include "newgrf_callbacks.h"
 
#include "newgrf_station.h"
 
#include "newgrf_spritegroup.h"
 

	
 
static StationClass station_classes[STAT_CLASS_MAX];
 

	
 
/**
 
 * Reset station classes to their default state.
 
 * This includes initialising the Default and Waypoint classes with an empty
 
 * entry, for standard stations and waypoints.
 
 */
 
void ResetStationClasses(void)
 
{
 
	StationClassID i;
 
	for (i = 0; i < STAT_CLASS_MAX; i++) {
 
		station_classes[i].id = 0;
 
		station_classes[i].name = STR_EMPTY;
 
		station_classes[i].stations = 0;
 

	
 
		free(station_classes[i].spec);
 
		station_classes[i].spec = NULL;
 
	}
 

	
 
	// Set up initial data
 
	station_classes[0].id = 'DFLT';
 
	station_classes[0].name = STR_STAT_CLASS_DFLT;
 
	station_classes[0].stations = 1;
 
	station_classes[0].spec = malloc(sizeof(*station_classes[0].spec));
 
	station_classes[0].spec[0] = NULL;
 

	
 
	station_classes[1].id = 'WAYP';
 
	station_classes[1].name = STR_STAT_CLASS_WAYP;
 
	station_classes[1].stations = 1;
 
	station_classes[1].spec = malloc(sizeof(*station_classes[1].spec));
 
	station_classes[1].spec[0] = NULL;
 
}
 

	
 
/**
 
 * Allocate a station class for the given class id.
 
 * @param classid A 32 bit value identifying the class.
 
 * @return Index into station_classes of allocated class.
 
 */
 
StationClassID AllocateStationClass(uint32 class)
 
{
 
	StationClassID i;
 

	
 
	for (i = 0; i < STAT_CLASS_MAX; i++) {
 
		if (station_classes[i].id == class) {
 
			// ClassID is already allocated, so reuse it.
 
			return i;
 
		} else if (station_classes[i].id == 0) {
 
			// This class is empty, so allocate it to the ClassID.
 
			station_classes[i].id = class;
 
			return i;
 
		}
 
	}
 

	
 
	DEBUG(grf, 2)("StationClassAllocate: Already allocated %d classes, using default.", STAT_CLASS_MAX);
 
	return STAT_CLASS_DFLT;
 
}
 

	
 
/** Set the name of a custom station class */
 
void SetStationClassName(StationClassID sclass, StringID name)
 
{
 
	assert(sclass < STAT_CLASS_MAX);
 
	station_classes[sclass].name = name;
 
}
 

	
 
/** Retrieve the name of a custom station class */
 
StringID GetStationClassName(StationClassID sclass)
 
{
 
	assert(sclass < STAT_CLASS_MAX);
 
	return station_classes[sclass].name;
 
}
 

	
 
/** Build a list of station class name StringIDs to use in a dropdown list
 
 * @return Pointer to a (static) array of StringIDs
 
 */
 
StringID *BuildStationClassDropdown(void)
 
{
 
	/* Allow room for all station classes, plus a terminator entry */
 
	static StringID names[STAT_CLASS_MAX + 1];
 
	uint i;
 

	
 
	/* Add each name */
 
	for (i = 0; i < STAT_CLASS_MAX && station_classes[i].id != 0; i++) {
 
		names[i] = station_classes[i].name;
 
	}
 
	/* Terminate the list */
 
	names[i] = INVALID_STRING_ID;
 

	
 
	return names;
 
}
 

	
 
/**
 
 * Get the number of station classes in use.
 
 * @return Number of station classes.
 
 */
 
uint GetNumStationClasses(void)
 
{
 
	uint i;
 
	for (i = 0; i < STAT_CLASS_MAX && station_classes[i].id != 0; i++);
 
	return i;
 
}
 

	
 
/**
 
 * Return the number of stations for the given station class.
 
 * @param sclass Index of the station class.
 
 * @return Number of stations in the class.
 
 */
 
uint GetNumCustomStations(StationClassID sclass)
 
{
 
	assert(sclass < STAT_CLASS_MAX);
 
	return station_classes[sclass].stations;
 
}
 

	
 
/**
 
 * Tie a station spec to its station class.
 
 * @param spec The station spec.
 
 */
 
void SetCustomStationSpec(StationSpec *statspec)
 
{
 
	StationClass *station_class;
 
	int i;
 

	
 
	assert(statspec->sclass < STAT_CLASS_MAX);
 
	station_class = &station_classes[statspec->sclass];
 

	
 
	i = station_class->stations++;
 
	station_class->spec = realloc(station_class->spec, station_class->stations * sizeof(*station_class->spec));
 

	
 
	station_class->spec[i] = statspec;
 
}
 

	
 
/**
 
 * Retrieve a station spec from a class.
 
 * @param sclass Index of the station class.
 
 * @param station The station index with the class.
 
 * @return The station spec.
 
 */
 
const StationSpec *GetCustomStationSpec(StationClassID sclass, uint station)
 
{
 
	assert(sclass < STAT_CLASS_MAX);
 
	if (station < station_classes[sclass].stations)
 
		return station_classes[sclass].spec[station];
 

	
 
	// If the custom station isn't defined any more, then the GRF file
 
	// probably was not loaded.
 
	return NULL;
 
}
 

	
 

	
 
const StationSpec *GetCustomStationSpecByGrf(uint32 grfid, byte localidx)
 
{
 
	StationClassID i;
 
	uint j;
 

	
 
	for (i = STAT_CLASS_DFLT; i < STAT_CLASS_MAX; i++) {
 
		for (j = 0; j < station_classes[i].stations; j++) {
 
			const StationSpec *statspec = station_classes[i].spec[j];
 
			if (statspec == NULL) continue;
 
			if (statspec->grfid == grfid && statspec->localidx == localidx) return statspec;
 
		}
 
	}
 

	
 
	return NULL;
 
}
 

	
 

	
 
/* Evaluate a tile's position within a station, and return the result a bitstuffed format.
 
 * if not centred: .TNLcCpP, if centred: .TNL..CP
 
 * T = Tile layout number (GetStationGfx), N = Number of platforms, L = Length of platforms
 
 * C = Current platform number from start, c = from end
 
 * P = Position along platform from start, p = from end
 
 * if centred, C/P start from the centre and c/p are not available.
 
 */
 
uint32 GetPlatformInfo(Axis axis, byte tile, int platforms, int length, int x, int y, bool centred)
 
{
 
	uint32 retval = 0;
 

	
 
	if (axis == AXIS_X) {
 
		intswap(platforms, length);
 
		intswap(x, y);
 
	}
 

	
 
	/* Limit our sizes to 4 bits */
 
	platforms = min(15, platforms);
 
	length    = min(15, length);
 
	x = min(15, x);
 
	y = min(15, y);
 
	if (centred) {
 
		x -= platforms / 2;
 
		y -= length / 2;
 
		SB(retval,  0, 4, clamp(y, -8, 7));
 
		SB(retval,  4, 4, clamp(x, -8, 7));
 
	} else {
 
		SB(retval,  0, 4, y);
 
		SB(retval,  4, 4, length - y - 1);
 
		SB(retval,  8, 4, x);
 
		SB(retval, 12, 4, platforms - x - 1);
 
	}
 
	SB(retval, 16, 4, length);
 
	SB(retval, 20, 4, platforms);
 
	SB(retval, 24, 4, tile);
 

	
 
	return retval;
 
}
 

	
 

	
 
/* Find the end of a railway station, from the tile, in the direction of delta.
 
 * If check_type is set, we stop if the custom station type changes.
 
 * If check_axis is set, we stop if the station direction changes.
 
 */
 
static TileIndex FindRailStationEnd(TileIndex tile, TileIndexDiff delta, bool check_type, bool check_axis)
 
{
 
	bool waypoint;
 
	byte orig_type = 0;
 
	Axis orig_axis = AXIS_X;
 

	
 
	waypoint = IsTileType(tile, MP_RAILWAY);
 

	
 
	if (waypoint) {
 
		if (check_axis) orig_axis = GetWaypointAxis(tile);
 
	} else {
 
		if (check_type) orig_type = GetCustomStationSpecIndex(tile);
 
		if (check_axis) orig_axis = GetRailStationAxis(tile);
 
	}
 

	
 
	while (true) {
 
		TileIndex new_tile = TILE_ADD(tile, delta);
 

	
 
		if (waypoint) {
 
			if (!IsTileType(new_tile, MP_RAILWAY)) break;
 
			if (GetRailTileType(new_tile) != RAIL_TYPE_DEPOT_WAYPOINT) break;
 
			if (GetRailTileSubtype(new_tile) != RAIL_SUBTYPE_WAYPOINT) break;
 
			if (check_axis && GetWaypointAxis(new_tile) != orig_axis) break;
 
		} else {
 
			if (!IsRailwayStationTile(new_tile)) break;
 
			if (check_type && GetCustomStationSpecIndex(new_tile) != orig_type) break;
 
			if (check_axis && GetRailStationAxis(new_tile) != orig_axis) break;
 
		}
 

	
 
		tile = new_tile;
 
	}
 
	return tile;
 
}
 

	
 

	
 
static uint32 GetPlatformInfoHelper(TileIndex tile, bool check_type, bool check_axis, bool centred)
 
{
 
	int tx = TileX(tile);
 
	int ty = TileY(tile);
 
	int sx = TileX(FindRailStationEnd(tile, TileDiffXY(-1,  0), check_type, check_axis));
 
	int sy = TileY(FindRailStationEnd(tile, TileDiffXY( 0, -1), check_type, check_axis));
 
	int ex = TileX(FindRailStationEnd(tile, TileDiffXY( 1,  0), check_type, check_axis)) + 1;
 
	int ey = TileY(FindRailStationEnd(tile, TileDiffXY( 0,  1), check_type, check_axis)) + 1;
 
	Axis axis = IsTileType(tile, MP_RAILWAY) ? GetWaypointAxis(tile) : GetRailStationAxis(tile);
 

	
 
	tx -= sx; ex -= sx;
 
	ty -= sy; ey -= sy;
 

	
 
	return GetPlatformInfo(axis, IsTileType(tile, MP_RAILWAY) ? 2 : GetStationGfx(tile), ex, ey, tx, ty, centred);
 
}
 

	
 

	
 
/* Station Resolver Functions */
 
static uint32 StationGetRandomBits(const ResolverObject *object)
 
{
 
	const Station *st = object->u.station.st;
 
	const TileIndex tile = object->u.station.tile;
 
	return (st == NULL ? 0 : st->random_bits) | (tile == INVALID_TILE ? 0 : GetStationTileRandomBits(tile) << 16);
 
}
 

	
 

	
 
static uint32 StationGetTriggers(const ResolverObject *object)
 
{
 
	const Station *st = object->u.station.st;
 
	return st == NULL ? 0 : st->waiting_triggers;
 
}
 

	
 

	
 
static void StationSetTriggers(const ResolverObject *object, int triggers)
 
{
 
	Station *st = (Station*)object->u.station.st;
 
	assert(st != NULL);
 
	st->waiting_triggers = triggers;
 
}
 

	
 

	
 
static uint32 StationGetVariable(const ResolverObject *object, byte variable, byte parameter)
 
{
 
	const Station *st = object->u.station.st;
 
	TileIndex tile = object->u.station.tile;
 

	
 
	if (st == NULL) {
 
		/* Station does not exist, so we're in a purchase list */
 
		switch (variable) {
 
			case 0x40:
 
			case 0x41:
 
			case 0x46:
 
			case 0x47:
 
			case 0x49: return 0x2110000;       /* Platforms, tracks & position */
 
			case 0x42: return 0;               /* Rail type (XXX Get current type from GUI?) */
 
			case 0x43: return _current_player; /* Station owner */
 
			case 0x44: return 2;               /* PBS status */
 
			case 0xFA: return _date;           /* Build date */
 
			default:   return -1;
 
		}
 
	}
 

	
 
	switch (variable) {
 
		/* Calculated station variables */
 
		case 0x40: return GetPlatformInfoHelper(tile, false, false, false);
 
		case 0x41: return GetPlatformInfoHelper(tile, true,  false, false);
 
		case 0x42: /* Terrain and rail type */
 
			return ((_opt.landscape == LT_HILLY && GetTileZ(tile) > _opt.snow_line) ? 4 : 0) |
 
			       (GetRailType(tile) << 8);
 
		case 0x43: return st->owner; /* Station owner */
 
		case 0x44: return 2;         /* PBS status */
 
		case 0x46: return GetPlatformInfoHelper(tile, false, false, true);
 
		case 0x47: return GetPlatformInfoHelper(tile, true,  false, true);
 
		case 0x48: { /* Accepted cargo types */
 
			CargoID cargo_type;
 
			uint32 value = 0;
 

	
 
			for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
 
				if (HASBIT(st->goods[cargo_type].waiting_acceptance, 15)) SETBIT(value, cargo_type);
 
			}
 
			return value;
 
		}
 
		case 0x49: return GetPlatformInfoHelper(tile, false, true, false);
 

	
 
		/* Variables which use the parameter */
 
		case 0x60: return GB(st->goods[parameter].waiting_acceptance, 0, 12);
 
		case 0x61: return st->goods[parameter].days_since_pickup;
 
		case 0x62: return st->goods[parameter].rating;
 
		case 0x63: return st->goods[parameter].enroute_time;
 
		case 0x64: return st->goods[parameter].last_speed | (st->goods[parameter].last_age << 8);
 

	
 
		/* General station properties */
 
		case 0x82: return 50;
 
		case 0x84: return st->string_id;
 
		case 0x86: return 0;
 
		case 0x8A: return st->had_vehicle_of_type;
 
		case 0xF0: return st->facilities;
 
		case 0xF1: return st->airport_type;
 
		case 0xF2: return st->truck_stops->status;
 
		case 0xF3: return st->bus_stops->status;
 
		case 0xF6: return st->airport_flags;
 
		case 0xF7: return st->airport_flags & 0xFF;
 
		case 0xFA: return st->build_date;
 
	}
 

	
 
	/* Handle cargo variables (deprecated) */
 
	if (variable >= 0x8C && variable <= 0xEC) {
 
		const GoodsEntry *g = &st->goods[GB(variable - 0x8C, 3, 4)];
 
		switch (GB(variable - 0x8C, 0, 3)) {
 
			case 0: return g->waiting_acceptance;
 
			case 1: return g->waiting_acceptance & 0xFF;
 
			case 2: return g->days_since_pickup;
 
			case 3: return g->rating;
 
			case 4: return g->enroute_from;
 
			case 5: return g->enroute_time;
 
			case 6: return g->last_speed;
 
			case 7: return g->last_age;
 
		}
 
	}
 

	
 
	DEBUG(grf, 1)("Unhandled station property 0x%X", variable);
 

	
 
	return -1;
 
}
 

	
 

	
 
static const SpriteGroup *StationResolveReal(const ResolverObject *object, const SpriteGroup *group)
 
{
 
	const Station *st = object->u.station.st;
 
	const StationSpec *statspec = object->u.station.statspec;
 
	uint set;
 

	
 
	uint cargo = 0;
 
	CargoID cargo_type = CT_INVALID; /* XXX Pick the correct cargo type */
 

	
 
	if (st == NULL || statspec->sclass == STAT_CLASS_WAYP) {
 
		return group->g.real.loading[0];
 
	}
 

	
 
	if (cargo_type == CT_INVALID) {
 
		for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
 
			cargo += GB(st->goods[cargo_type].waiting_acceptance, 0, 12);
 
		}
 
	} else {
 
		cargo = GB(st->goods[cargo_type].waiting_acceptance, 0, 12);
 
	}
 

	
 
	if (HASBIT(statspec->flags, 1)) cargo /= (st->trainst_w + st->trainst_h);
 
	cargo = min(0xfff, cargo);
 

	
 
	if (cargo > statspec->cargo_threshold) {
 
		if (group->g.real.num_loading > 0) {
 
			set = ((cargo - statspec->cargo_threshold) * group->g.real.num_loading) / (0xfff - statspec->cargo_threshold);
 
			return group->g.real.loading[set];
 
		}
 
	} else {
 
		if (group->g.real.num_loaded > 0) {
 
			set = (cargo * group->g.real.num_loaded) / (statspec->cargo_threshold + 1);
 
			return group->g.real.loaded[set];
 
		}
 
	}
 

	
 
	return group->g.real.loading[0];
 
}
 

	
 

	
 
static void NewStationResolver(ResolverObject *res, const StationSpec *statspec, const Station *st, TileIndex tile)
 
{
 
	res->GetRandomBits = StationGetRandomBits;
 
	res->GetTriggers   = StationGetTriggers;
 
	res->SetTriggers   = StationSetTriggers;
 
	res->GetVariable   = StationGetVariable;
 
	res->ResolveReal   = StationResolveReal;
 

	
 
	res->u.station.st       = st;
 
	res->u.station.statspec = statspec;
 
	res->u.station.tile     = tile;
 

	
 
	res->callback        = 0;
 
	res->callback_param1 = 0;
 
	res->callback_param2 = 0;
 
	res->last_value      = 0;
 
	res->trigger         = 0;
 
	res->reseed          = 0;
 
}
 

	
 

	
 
SpriteID GetCustomStationRelocation(const StationSpec *statspec, const Station *st, TileIndex tile)
 
{
 
	const SpriteGroup *group;
 
	ResolverObject object;
 
	CargoID ctype = (st == NULL) ? GC_PURCHASE : GC_DEFAULT_NA;
 

	
 
	NewStationResolver(&object, statspec, st, tile);
 

	
 
	group = Resolve(statspec->spritegroup[ctype], &object);
 
	if ((group == NULL || group->type != SGT_RESULT) && ctype != GC_DEFAULT_NA) {
 
		group = Resolve(statspec->spritegroup[GC_DEFAULT_NA], &object);
 
	}
 
	if ((group == NULL || group->type != SGT_RESULT) && ctype != GC_DEFAULT) {
 
		group = Resolve(statspec->spritegroup[GC_DEFAULT], &object);
 
	}
 

	
 
	if (group == NULL || group->type != SGT_RESULT) return 0;
 

	
 
	return group->g.result.sprite;
 
}
 

	
 

	
 
uint16 GetStationCallback(uint16 callback, uint32 param1, uint32 param2, const StationSpec *statspec, const Station *st, TileIndex tile)
 
{
 
	const SpriteGroup *group;
 
	ResolverObject object;
 
	CargoID ctype = (st == NULL) ? GC_PURCHASE : GC_DEFAULT_NA;
 

	
 
	NewStationResolver(&object, statspec, st, tile);
 

	
 
	object.callback        = callback;
 
	object.callback_param1 = param1;
 
	object.callback_param2 = param2;
 

	
 
	group = Resolve(statspec->spritegroup[ctype], &object);
 
	if ((group == NULL || group->type != SGT_CALLBACK) && ctype != GC_DEFAULT_NA) {
 
		group = Resolve(statspec->spritegroup[GC_DEFAULT_NA], &object);
 
	}
 
	if ((group == NULL || group->type != SGT_CALLBACK) && ctype != GC_DEFAULT) {
 
		group = Resolve(statspec->spritegroup[GC_DEFAULT], &object);
 
	}
 

	
 
	if (group == NULL || group->type != SGT_CALLBACK) return CALLBACK_FAILED;
 

	
 
	return group->g.callback.result;
 
}
 

	
 

	
 
/**
 
 * Allocate a StationSpec to a Station. This is called once per build operation.
 
 * @param spec StationSpec to allocate.
 
 * @param st Station to allocate it to.
 
 * @param exec Whether to actually allocate the spec.
 
 * @return Index within the Station's spec list, or -1 if the allocation failed.
 
 */
 
int AllocateSpecToStation(const StationSpec *statspec, Station *st, bool exec)
 
{
 
	uint i;
 

	
 
	if (statspec == NULL) return 0;
 

	
 
	/* Check if this spec has already been allocated */
 
	for (i = 1; i < st->num_specs && i < 256; i++) {
 
		if (st->speclist[i].spec == statspec) return i;
 
	}
 

	
 
	for (i = 1; i < st->num_specs && i < 256; i++) {
 
		if (st->speclist[i].spec == NULL && st->speclist[i].grfid == 0) break;
 
	}
 

	
 
	if (i == 256) return -1;
 

	
 
	if (exec) {
 
		if (i >= st->num_specs) {
 
			st->num_specs = i + 1;
 
			st->speclist = realloc(st->speclist, st->num_specs * sizeof(*st->speclist));
 

	
 
			if (st->num_specs == 2) {
 
				/* Initial allocation */
 
				st->speclist[0].spec     = NULL;
 
				st->speclist[0].grfid    = 0;
 
				st->speclist[0].localidx = 0;
 
			}
 
		}
 

	
 
		st->speclist[i].spec     = statspec;
 
		st->speclist[i].grfid    = statspec->grfid;
 
		st->speclist[i].localidx = statspec->localidx;
 
	}
 

	
 
	return i;
 
}
 

	
 

	
 
/** Deallocate a StationSpec from a Station. Called when removing a single station tile.
 
 * @param st Station to work with.
 
 * @param specindex Index of the custom station within the Station's spec list.
 
 * @return Indicates whether the StationSpec was deallocated.
 
 */
 
bool DeallocateSpecFromStation(Station *st, byte specindex)
 
{
 
	bool freeable = true;
 

	
 
	/* specindex of 0 (default) is never freeable */
 
	if (specindex == 0) return false;
 

	
 
	/* Check all tiles over the station to check if the specindex is still in use */
 
	BEGIN_TILE_LOOP(tile, st->trainst_w, st->trainst_h, st->train_tile) {
 
		if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st->index && IsRailwayStation(tile) && GetCustomStationSpecIndex(tile) == specindex) {
 
			freeable = false;
 
			break;
 
		}
 
	} END_TILE_LOOP(tile, st->trainst_w, st->trainst_h, st->train_tile)
 

	
 
	if (freeable) {
 
		/* This specindex is no longer in use, so deallocate it */
 
		st->speclist[specindex].spec     = NULL;
 
		st->speclist[specindex].grfid    = 0;
newgrf_station.h
Show inline comments
 
/* $Id$ */
 

	
 
/** @file newgrf_station.h Header file for NewGRF stations */
 

	
 
#ifndef NEWGRF_STATION_H
 
#define NEWGRF_STATION_H
 

	
 
#include "engine.h"
 

	
 
typedef enum {
 
	STAT_CLASS_DFLT,     ///< Default station class.
 
	STAT_CLASS_WAYP,     ///< Waypoint class.
 
	STAT_CLASS_MAX = 16, ///< Maximum number of classes.
 
} StationClassID;
 

	
 
/* Station layout for given dimensions - it is a two-dimensional array
 
 * where index is computed as (x * platforms) + platform. */
 
typedef byte *StationLayout;
 

	
 
typedef struct StationSpec {
 
	uint32 grfid; ///< ID of GRF file station belongs to.
 
	int localidx; ///< Index within GRF file of station.
 

	
 
	StationClassID sclass; ///< The class to which this spec belongs.
 
	StringID name; ///< Name of this station.
 

	
 
	/**
 
	 * Bitmask of number of platforms available for the station.
 
	 * 0..6 correpsond to 1..7, while bit 7 corresponds to >7 platforms.
 
	 */
 
	byte disallowed_platforms;
 
	/**
 
	 * Bitmask of platform lengths available for the station.
 
	 * 0..6 correpsond to 1..7, while bit 7 corresponds to >7 tiles long.
 
	 */
 
	byte disallowed_lengths;
 

	
 
	/** Number of tile layouts.
 
	 * A minimum of 8 is required is required for stations.
 
	 * 0-1 = plain platform
 
	 * 2-3 = platform with building
 
	 * 4-5 = platform with roof, left side
 
	 * 6-7 = platform with roof, right side
 
	 */
 
	uint tiles;
 
	DrawTileSprites *renderdata; ///< Array of tile layouts.
 
	bool copied_renderdata;
 

	
 
	/** Cargo threshold for choosing between little and lots of cargo
 
	 * @note little/lots are equivalent to the moving/loading states for vehicles
 
	 */
 
	uint16 cargo_threshold;
 

	
 
	uint32 cargo_triggers; ///< Bitmask of cargo types which cause trigger re-randomizing
 

	
 
	byte callbackmask; ///< Bitmask of callbacks to use, @see newgrf_callbacks.h
 

	
 
	byte flags; ///< Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size
 

	
 
	byte pylons;  ///< Bitmask of base tiles (0 - 7) which should contain elrail pylons
 
	byte wires;   ///< Bitmask of base tiles (0 - 7) which should contain elrail wires
 
	byte blocked; ///< Bitmask of base tiles (0 - 7) which are blocked to trains
 

	
 
	byte lengths;
 
	byte *platforms;
 
	StationLayout **layouts;
 

	
 
	/**
 
	 * NUM_GLOBAL_CID sprite groups.
 
	 * Used for obtaining the sprite offset of custom sprites, and for
 
	 * evaluating callbacks.
 
	 */
 
	SpriteGroup *spritegroup[NUM_GLOBAL_CID];
 
} StationSpec;
 

	
 
/**
 
 * Struct containing information relating to station classes.
 
 */
 
typedef struct StationClass {
 
	uint32 id;          ///< ID of this class, e.g. 'DFLT', 'WAYP', etc.
 
	StringID name;      ///< Name of this class.
 
	uint stations;      ///< Number of stations in this class.
 
	StationSpec **spec; ///< Array of station specifications.
 
} StationClass;
 

	
 
void ResetStationClasses(void);
 
StationClassID AllocateStationClass(uint32 class);
 
void SetStationClassName(StationClassID sclass, StringID name);
 
StringID GetStationClassName(StationClassID sclass);
 
StringID *BuildStationClassDropdown(void);
 

	
 
uint GetNumStationClasses(void);
 
uint GetNumCustomStations(StationClassID sclass);
 

	
 
void SetCustomStationSpec(StationSpec *statspec);
 
const StationSpec *GetCustomStationSpec(StationClassID sclass, uint station);
 
const StationSpec *GetCustomStationSpecByGrf(uint32 grfid, byte localidx);
 

	
 
/* Get sprite offset for a given custom station and station structure (may be
 
 * NULL - that means we are in a build dialog). The station structure is used
 
 * for variational sprite groups. */
 
SpriteID GetCustomStationRelocation(const StationSpec *statspec, const Station *st, TileIndex tile);
 
uint16 GetStationCallback(uint16 callback, uint32 param1, uint32 param2, const StationSpec *statspec, const Station *st, TileIndex tile);
 

	
 
/* Allocate a StationSpec to a Station. This is called once per build operation. */
 
int AllocateSpecToStation(const StationSpec *statspec, Station *st, bool exec);
 

	
 
/* Deallocate a StationSpec from a Station. Called when removing a single station tile. */
 
bool DeallocateSpecFromStation(Station *st, byte specindex);
 

	
 
/* Draw representation of a station tile for GUI purposes. */
 
bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID sclass, uint station);
 

	
 
#endif /* NEWGRF_STATION_H */
openttd.c
Show inline comments
 
@@ -1045,386 +1045,388 @@ static void UpdateExclusiveRights(void)
 
			1.) Go through all stations
 
					Build an array town_blocked[ town_id ][ player_id ]
 
				 that stores if at least one station in that town is blocked for a player
 
			2.) Go through that array, if you find a town that is not blocked for
 
					one player, but for all others, then give him exclusivity.
 
	*/
 
}
 

	
 
static const byte convert_currency[] = {
 
	 0,  1, 12,  8,  3,
 
	10, 14, 19,  4,  5,
 
	 9, 11, 13,  6, 17,
 
	16, 22, 21,  7, 15,
 
	18,  2, 20, };
 

	
 
// since savegame version 4.2 the currencies are arranged differently
 
static void UpdateCurrencies(void)
 
{
 
	_opt.currency = convert_currency[_opt.currency];
 
}
 

	
 
/* Up to revision 1413 the invisible tiles at the southern border have not been
 
 * MP_VOID, even though they should have. This is fixed by this function
 
 */
 
static void UpdateVoidTiles(void)
 
{
 
	uint i;
 

	
 
	for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
 
	for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
 
}
 

	
 
// since savegame version 6.0 each sign has an "owner", signs without owner (from old games are set to 255)
 
static void UpdateSignOwner(void)
 
{
 
	SignStruct *ss;
 

	
 
	FOR_ALL_SIGNS(ss) ss->owner = OWNER_NONE;
 
}
 

	
 
extern void UpdateOldAircraft( void );
 
extern void UpdateOilRig( void );
 

	
 

	
 
static inline RailType UpdateRailType(RailType rt, RailType min)
 
{
 
	return rt >= min ? (RailType)(rt + 1): rt;
 
}
 

	
 

	
 
bool AfterLoadGame(void)
 
{
 
	Window *w;
 
	ViewPort *vp;
 
	Player *p;
 

	
 
	// in version 2.1 of the savegame, town owner was unified.
 
	if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
 

	
 
	// from version 4.1 of the savegame, exclusive rights are stored at towns
 
	if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
 

	
 
	// from version 4.2 of the savegame, currencies are in a different order
 
	if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
 

	
 
	// from version 6.1 of the savegame, signs have an "owner"
 
	if (CheckSavegameVersionOldStyle(6, 1)) UpdateSignOwner();
 

	
 
	/* In old version there seems to be a problem that water is owned by
 
	    OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
 
	    (4.3) version, so I just check when versions are older, and then
 
	    walk through the whole map.. */
 
	if (CheckSavegameVersionOldStyle(4, 3)) {
 
		TileIndex tile = TileXY(0, 0);
 
		uint w = MapSizeX();
 
		uint h = MapSizeY();
 

	
 
		BEGIN_TILE_LOOP(tile_cur, w, h, tile)
 
			if (IsTileType(tile_cur, MP_WATER) && GetTileOwner(tile_cur) >= MAX_PLAYERS)
 
				SetTileOwner(tile_cur, OWNER_WATER);
 
		END_TILE_LOOP(tile_cur, w, h, tile)
 
	}
 

	
 
	// convert road side to my format.
 
	if (_opt.road_side) _opt.road_side = 1;
 

	
 
	// Load the sprites
 
	GfxLoadSprites();
 

	
 
	/* Connect front and rear engines of multiheaded trains and converts
 
	 * subtype to the new format */
 
	if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
 

	
 
	/* Connect front and rear engines of multiheaded trains */
 
	ConnectMultiheadedTrains();
 

	
 
	// Update current year
 
	SetDate(_date);
 

	
 
	// reinit the landscape variables (landscape might have changed)
 
	InitializeLandscapeVariables(true);
 

	
 
	// Update all vehicles
 
	AfterLoadVehicles();
 

	
 
	// Update all waypoints
 
	if (CheckSavegameVersion(12)) FixOldWaypoints();
 

	
 
	UpdateAllWaypointSigns();
 

	
 
	// in version 2.2 of the savegame, we have new airports
 
	if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
 

	
 
	UpdateAllStationVirtCoord();
 

	
 
	// Setup town coords
 
	AfterLoadTown();
 
	UpdateAllSignVirtCoords();
 

	
 
	// make sure there is a town in the game
 
	if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) {
 
		_error_message = STR_NO_TOWN_IN_SCENARIO;
 
		return false;
 
	}
 

	
 
	// Initialize windows
 
	ResetWindowSystem();
 
	SetupColorsAndInitialWindow();
 

	
 
	w = FindWindowById(WC_MAIN_WINDOW, 0);
 

	
 
	WP(w,vp_d).scrollpos_x = _saved_scrollpos_x;
 
	WP(w,vp_d).scrollpos_y = _saved_scrollpos_y;
 

	
 
	vp = w->viewport;
 
	vp->zoom = _saved_scrollpos_zoom;
 
	vp->virtual_width = vp->width << vp->zoom;
 
	vp->virtual_height = vp->height << vp->zoom;
 

	
 
	// in version 4.1 of the savegame, is_active was introduced to determine
 
	// if a player does exist, rather then checking name_1
 
	if (CheckSavegameVersionOldStyle(4, 1)) CheckIsPlayerActive();
 

	
 
	// the void tiles on the southern border used to belong to a wrong class (pre 4.3).
 
	if (CheckSavegameVersionOldStyle(4, 3)) UpdateVoidTiles();
 

	
 
	// If Load Scenario / New (Scenario) Game is used,
 
	//  a player does not exist yet. So create one here.
 
	// 1 exeption: network-games. Those can have 0 players
 
	//   But this exeption is not true for network_servers!
 
	if (!_players[0].is_active && (!_networking || (_networking && _network_server)))
 
		DoStartupNewPlayer(false);
 

	
 
	DoZoomInOutWindow(ZOOM_NONE, w); // update button status
 
	MarkWholeScreenDirty();
 

	
 
	// In 5.1, Oilrigs have been moved (again)
 
	if (CheckSavegameVersionOldStyle(5, 1)) UpdateOilRig();
 

	
 
	/* In version 6.1 we put the town index in the map-array. To do this, we need
 
	 *  to use m2 (16bit big), so we need to clean m2, and that is where this is
 
	 *  all about ;) */
 
	if (CheckSavegameVersionOldStyle(6, 1)) {
 
		BEGIN_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0) {
 
			if (IsTileType(tile, MP_HOUSE)) {
 
				_m[tile].m4 = _m[tile].m2;
 
				//XXX magic
 
				SetTileType(tile, MP_VOID);
 
				_m[tile].m2 = ClosestTownFromTile(tile,(uint)-1)->index;
 
				SetTileType(tile, MP_HOUSE);
 
			} else if (IsTileType(tile, MP_STREET)) {
 
				//XXX magic
 
				_m[tile].m4 |= (_m[tile].m2 << 4);
 
				if (IsTileOwner(tile, OWNER_TOWN)) {
 
					SetTileType(tile, MP_VOID);
 
					_m[tile].m2 = ClosestTownFromTile(tile,(uint)-1)->index;
 
					SetTileType(tile, MP_STREET);
 
				} else {
 
					SetTownIndex(tile, 0);
 
				}
 
			}
 
		} END_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0);
 
	}
 

	
 
	/* From version 9.0, we update the max passengers of a town (was sometimes negative
 
	 *  before that. */
 
	if (CheckSavegameVersion(9)) {
 
		Town *t;
 
		FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
 
	}
 

	
 
	/* From version 16.0, we included autorenew on engines, which are now saved, but
 
	 *  of course, we do need to initialize them for older savegames. */
 
	if (CheckSavegameVersion(16)) {
 
		FOR_ALL_PLAYERS(p) {
 
			p->engine_renew_list = NULL;
 
			p->engine_renew = false;
 
			p->engine_renew_months = -6;
 
			p->engine_renew_money = 100000;
 
		}
 
		if (_local_player < MAX_PLAYERS) {
 
			// Set the human controlled player to the patch settings
 
			// Scenario editor do not have any companies
 
			p = GetPlayer(_local_player);
 
			p->engine_renew = _patches.autorenew;
 
			p->engine_renew_months = _patches.autorenew_months;
 
			p->engine_renew_money = _patches.autorenew_money;
 
		}
 
	}
 

	
 
	/* Elrails got added in rev 24 */
 
	if (CheckSavegameVersion(24)) {
 
		Vehicle* v;
 
		uint i;
 
		TileIndex t;
 
		RailType min_rail = RAILTYPE_ELECTRIC;
 

	
 
		for (i = 0; i < lengthof(_engines); i++) {
 
			Engine* e = GetEngine(i);
 
			if (e->type == VEH_Train &&
 
					(e->railtype != RAILTYPE_RAIL || RailVehInfo(i)->engclass == 2)) {
 
				e->railtype++;
 
			}
 
		}
 

	
 
		FOR_ALL_VEHICLES(v) {
 
			if (v->type == VEH_Train) {
 
				RailType rt = GetEngine(v->engine_type)->railtype;
 

	
 
				v->u.rail.railtype = rt;
 
				if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
 
			}
 
		}
 

	
 
		/* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
 
		for (t = 0; t < MapSize(); t++) {
 
			switch (GetTileType(t)) {
 
				case MP_RAILWAY:
 
					SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
 
					break;
 

	
 
				case MP_STREET:
 
					if (IsLevelCrossing(t)) {
 
						SetRailTypeCrossing(t, UpdateRailType(GetRailTypeCrossing(t), min_rail));
 
					}
 
					break;
 

	
 
				case MP_STATION:
 
					if (IsRailwayStation(t))  {
 
						SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
 
					}
 
					break;
 

	
 
				case MP_TUNNELBRIDGE:
 
					if (IsTunnel(t)) {
 
						if (GetTunnelTransportType(t) == TRANSPORT_RAIL) {
 
							SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
 
						}
 
					} else {
 
						if (GetBridgeTransportType(t) == TRANSPORT_RAIL) {
 
							if (IsBridgeRamp(t)) {
 
								SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
 
							} else {
 
								SetRailTypeOnBridge(t, UpdateRailType(GetRailTypeOnBridge(t), min_rail));
 
							}
 
						}
 
						if (IsBridgeMiddle(t) &&
 
								IsTransportUnderBridge(t) &&
 
								GetTransportTypeUnderBridge(t) == TRANSPORT_RAIL) {
 
							SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
 
						}
 
					}
 
					break;
 

	
 
				default:
 
					break;
 
			}
 
		}
 

	
 
		FOR_ALL_VEHICLES(v) {
 
			if (v->type == VEH_Train && (IsFrontEngine(v) || IsFreeWagon(v))) TrainConsistChanged(v);
 
		}
 

	
 
	}
 

	
 
	/* In version 16.1 of the savegame a player can decide if trains, which get
 
	 * replaced, shall keep their old length. In all prior versions, just default
 
	 * to false */
 
	if (CheckSavegameVersionOldStyle(16, 1)) {
 
		FOR_ALL_PLAYERS(p) {
 
			p->renew_keep_length = false;
 
		}
 
	}
 

	
 
	/* In version 17, ground type is moved from m2 to m4 for depots and
 
	 * waypoints to make way for storing the index in m2. The custom graphics
 
	 * id which was stored in m4 is now saved as a grf/id reference in the
 
	 * waypoint struct. */
 
	if (CheckSavegameVersion(17)) {
 
		Waypoint *wp;
 

	
 
		FOR_ALL_WAYPOINTS(wp) {
 
			if (wp->xy != 0 && wp->deleted == 0) {
 
				const StationSpec *statspec = NULL;
 

	
 
				if (HASBIT(_m[wp->xy].m3, 4))
 
					statspec = GetCustomStationSpec(STAT_CLASS_WAYP, _m[wp->xy].m4 + 1);
 

	
 
				if (statspec != NULL) {
 
					wp->stat_id = _m[wp->xy].m4 + 1;
 
					wp->grfid = statspec->grfid;
 
					wp->localidx = statspec->localidx;
 
				} else {
 
					// No custom graphics set, so set to default.
 
					wp->stat_id = 0;
 
					wp->grfid = 0;
 
					wp->localidx = 0;
 
				}
 

	
 
				// Move ground type bits from m2 to m4.
 
				_m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
 
				// Store waypoint index in the tile.
 
				_m[wp->xy].m2 = wp->index;
 
			}
 
		}
 
	} else {
 
		/* As of version 17, we recalculate the custom graphic ID of waypoints
 
		 * from the GRF ID / station index. */
 
		UpdateAllWaypointCustomGraphics();
 
	}
 

	
 
	/* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
 
	 *  room for PBS. Now in version 21 move it back :P. */
 
	if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
 
		BEGIN_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0) {
 
			if (IsTileType(tile, MP_RAILWAY)) {
 
				// Clear PBS signals, move back sempahore bit to 2
 
				if (HasSignals(tile)) {
 
					// convert PBS signals to combo-signals
 
					if (HASBIT(_m[tile].m4, 2)) SB(_m[tile].m4, 0, 2, 3);
 

	
 
					SB(_m[tile].m4, 2, 2, HASBIT(_m[tile].m4, 3));
 
					CLRBIT(_m[tile].m4, 3);
 
				}
 

	
 
				// Clear PBS reservation on track
 
				if (!IsTileDepotType(tile, TRANSPORT_RAIL))
 
					SB(_m[tile].m4, 4, 4, 0);
 
				else
 
					CLRBIT(_m[tile].m3, 6);
 
			}
 

	
 
			// Clear PBS reservation on crossing
 
			if (IsTileType(tile, MP_STREET) && IsLevelCrossing(tile))
 
				CLRBIT(_m[tile].m5, 0);
 

	
 
			// Clear PBS reservation on station
 
			if (IsTileType(tile, MP_STATION))
 
				CLRBIT(_m[tile].m3, 6);
 
		} END_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0);
 
	}
 

	
 
	if (CheckSavegameVersion(22))  UpdatePatches();
 

	
 
	if (CheckSavegameVersion(25)) {
 
		Vehicle *v;
 
		FOR_ALL_VEHICLES(v) {
 
			if (v->type == VEH_Road) {
 
				v->vehstatus &= ~0x40;
 
				v->u.road.slot = NULL;
 
				v->u.road.slot_age = 0;
 
			}
 
		}
 
	}
 

	
 
	if (CheckSavegameVersion(26)) {
 
		Station *st;
 
		FOR_ALL_STATIONS(st) {
 
			st->last_vehicle_type = VEH_Invalid;
 
		}
 
	}
 

	
 
	FOR_ALL_PLAYERS(p) p->avail_railtypes = GetPlayerRailtypes(p->index);
 

	
 
	if (!CheckSavegameVersion(27)) AfterLoadStations();
 

	
 
	return true;
 
}
saveload.c
Show inline comments
 
/* $Id$ */
 

	
 
/** @file
 
 * All actions handling saving and loading goes on in this file. The general actions
 
 * are as follows for saving a game (loading is analogous):
 
 * <ol>
 
 * <li>initialize the writer by creating a temporary memory-buffer for it
 
 * <li>go through all to-be saved elements, each 'chunk' (ChunkHandler) prefixed by a label
 
 * <li>use their description array (SaveLoad) to know what elements to save and in what version
 
 *    of the game it was active (used when loading)
 
 * <li>write all data byte-by-byte to the temporary buffer so it is endian-safe
 
 * <li>when the buffer is full; flush it to the output (eg save to file) (_sl.buf, _sl.bufp, _sl.bufe)
 
 * <li>repeat this until everything is done, and flush any remaining output to file
 
 * </ol>
 
 * @see ChunkHandler
 
 * @see SaveLoad
 
 */
 
#include "stdafx.h"
 
#include "openttd.h"
 
#include "debug.h"
 
#include "functions.h"
 
#include "hal.h"
 
#include "vehicle.h"
 
#include "station.h"
 
#include "thread.h"
 
#include "town.h"
 
#include "player.h"
 
#include "saveload.h"
 
#include "network.h"
 
#include "variables.h"
 
#include <setjmp.h>
 

	
 
const uint16 SAVEGAME_VERSION = 26;
 
const uint16 SAVEGAME_VERSION = 27;
 
uint16 _sl_version;       /// the major savegame version identifier
 
byte   _sl_minor_version; /// the minor savegame version, DO NOT USE!
 

	
 
typedef void WriterProc(uint len);
 
typedef uint ReaderProc(void);
 

	
 
typedef uint ReferenceToIntProc(const void *obj, SLRefType rt);
 
typedef void *IntToReferenceProc(uint index, SLRefType rt);
 

	
 
/** The saveload struct, containing reader-writer functions, bufffer, version, etc. */
 
static struct {
 
	bool save;                           /// are we doing a save or a load atm. True when saving
 
	byte need_length;                    /// ???
 
	byte block_mode;                     /// ???
 
	bool error;                          /// did an error occur or not
 

	
 
	int obj_len;                         /// the length of the current object we are busy with
 
	int array_index, last_array_index;   /// in the case of an array, the current and last positions
 

	
 
	uint32 offs_base;                    /// the offset in number of bytes since we started writing data (eg uncompressed savegame size)
 

	
 
	WriterProc *write_bytes;             /// savegame writer function
 
	ReaderProc *read_bytes;              /// savegame loader function
 

	
 
	ReferenceToIntProc *ref_to_int_proc; /// function to convert pointers to numbers when saving a game
 
	IntToReferenceProc *int_to_ref_proc; /// function to convert numbers to pointers when loading a game
 

	
 
	const ChunkHandler* const *chs;      /// the chunk of data that is being processed atm (vehicles, signs, etc.)
 
	const SaveLoad* const *includes;     /// the internal layouf of the given chunk
 

	
 
	/** When saving/loading savegames, they are always saved to a temporary memory-place
 
	 * to be flushed to file (save) or to final place (load) when full. */
 
	byte *bufp, *bufe;                   /// bufp(ointer) gives the current position in the buffer bufe(nd) gives the end of the buffer
 

	
 
	// these 3 may be used by compressor/decompressors.
 
	byte *buf;                           /// pointer to temporary memory to read/write, initialized by SaveLoadFormat->initread/write
 
	byte *buf_ori;                       /// pointer to the original memory location of buf, used to free it afterwards
 
	uint bufsize;                        /// the size of the temporary memory *buf
 
	FILE *fh;                            /// the file from which is read or written to
 

	
 
	void (*excpt_uninit)(void);          /// the function to execute on any encountered error
 
	const char *excpt_msg;               /// the error message
 
	jmp_buf excpt;                       /// @todo used to jump to "exception handler";  really ugly
 
} _sl;
 

	
 

	
 
enum NeedLengthValues {NL_NONE = 0, NL_WANTLENGTH = 1, NL_CALCLENGTH = 2};
 

	
 
/**
 
 * Fill the input buffer by reading from the file with the given reader
 
 */
 
static void SlReadFill(void)
 
{
 
	uint len = _sl.read_bytes();
 
	assert(len != 0);
 

	
 
	_sl.bufp = _sl.buf;
 
	_sl.bufe = _sl.buf + len;
 
	_sl.offs_base += len;
 
}
 

	
 
static inline uint32 SlGetOffs(void) {return _sl.offs_base - (_sl.bufe - _sl.bufp);}
 

	
 
/** Return the size in bytes of a certain type of normal/atomic variable
 
 * as it appears in memory. @see VarTypes
 
 * @param conv @VarType type of variable that is used for calculating the size
 
 * @return Return the size of this type in bytes */
 
static inline byte SlCalcConvMemLen(VarType conv)
 
{
 
	static const byte conv_mem_size[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
 
	byte length = GB(conv, 4, 4);
 
	assert(length < lengthof(conv_mem_size));
 
	return conv_mem_size[length];
 
}
 

	
 
/** Return the size in bytes of a certain type of normal/atomic variable
 
 * as it appears in a saved game. @see VarTypes
 
 * @param conv @VarType type of variable that is used for calculating the size
 
 * @return Return the size of this type in bytes */
 
static inline byte SlCalcConvFileLen(VarType conv)
 
{
 
	static const byte conv_file_size[] = {1, 1, 2, 2, 4, 4, 8, 8, 2};
 
	byte length = GB(conv, 0, 4);
 
	assert(length < lengthof(conv_file_size));
 
	return conv_file_size[length];
 
}
 

	
 
/* Return the size in bytes of a reference (pointer) */
 
static inline size_t SlCalcRefLen(void) {return 2;}
 

	
 
/** Flush the output buffer by writing to disk with the given reader.
 
 * If the buffer pointer has not yet been set up, set it up now. Usually
 
 * only called when the buffer is full, or there is no more data to be processed
 
 */
 
static void SlWriteFill(void)
 
{
 
	// flush the buffer to disk (the writer)
 
	if (_sl.bufp != NULL) {
 
		uint len = _sl.bufp - _sl.buf;
 
		_sl.offs_base += len;
 
		if (len) _sl.write_bytes(len);
 
	}
 

	
 
	/* All the data from the buffer has been written away, rewind to the beginning
 
	* to start reading in more data */
 
	_sl.bufp = _sl.buf;
 
	_sl.bufe = _sl.buf + _sl.bufsize;
 
}
 

	
 
/** Error handler, calls longjmp to simulate an exception.
 
 * @todo this was used to have a central place to handle errors, but it is
 
 * pretty ugly, and seriously interferes with any multithreaded approaches */
 
static void NORETURN SlError(const char *msg)
 
{
 
	_sl.excpt_msg = msg;
 
	longjmp(_sl.excpt, 0);
 
}
 

	
 
/** Read in a single byte from file. If the temporary buffer is full,
 
 * flush it to its final destination
 
 * @return return the read byte from file
 
 */
 
static inline byte SlReadByteInternal(void)
 
{
 
	if (_sl.bufp == _sl.bufe) SlReadFill();
 
	return *_sl.bufp++;
 
}
 

	
 
/** Wrapper for SlReadByteInternal */
 
byte SlReadByte(void) {return SlReadByteInternal();}
 

	
 
/** Write away a single byte from memory. If the temporary buffer is full,
 
 * flush it to its destination (file)
 
 * @param b the byte that is currently written
 
 */
 
static inline void SlWriteByteInternal(byte b)
 
{
 
	if (_sl.bufp == _sl.bufe) SlWriteFill();
 
	*_sl.bufp++ = b;
 
}
 

	
 
/** Wrapper for SlWriteByteInternal */
 
void SlWriteByte(byte b) {SlWriteByteInternal(b);}
 

	
 
static inline int SlReadUint16(void)
 
{
 
	int x = SlReadByte() << 8;
 
	return x | SlReadByte();
 
}
 

	
 
static inline uint32 SlReadUint32(void)
 
{
 
	uint32 x = SlReadUint16() << 16;
 
	return x | SlReadUint16();
 
}
 

	
 
static inline uint64 SlReadUint64(void)
 
{
 
	uint32 x = SlReadUint32();
 
	uint32 y = SlReadUint32();
 
	return (uint64)x << 32 | y;
 
}
 

	
 
static inline void SlWriteUint16(uint16 v)
 
{
 
	SlWriteByte(GB(v, 8, 8));
 
	SlWriteByte(GB(v, 0, 8));
 
}
 

	
 
static inline void SlWriteUint32(uint32 v)
 
{
 
	SlWriteUint16(GB(v, 16, 16));
 
	SlWriteUint16(GB(v,  0, 16));
 
}
 

	
 
static inline void SlWriteUint64(uint64 x)
 
{
 
	SlWriteUint32((uint32)(x >> 32));
 
	SlWriteUint32((uint32)x);
 
}
 

	
 
/**
 
 * Read in the header descriptor of an object or an array.
 
 * If the highest bit is set (7), then the index is bigger than 127
 
 * elements, so use the next byte to read in the real value.
 
 * The actual value is then both bytes added with the first shifted
 
 * 8 bits to the left, and dropping the highest bit (which only indicated a big index).
 
 * x = ((x & 0x7F) << 8) + SlReadByte();
 
 * @return Return the value of the index
 
 */
 
static uint SlReadSimpleGamma(void)
 
{
 
	uint i = SlReadByte();
 
	if (HASBIT(i, 7)) {
 
		i &= ~0x80;
 
		if (HASBIT(i, 6)) {
 
			i &= ~0x40;
 
			if (HASBIT(i, 5)) {
 
				i &= ~0x20;
 
				if (HASBIT(i, 4))
 
					SlError("Unsupported gamma");
 
				i = (i << 8) | SlReadByte();
 
			}
 
			i = (i << 8) | SlReadByte();
 
		}
 
		i = (i << 8) | SlReadByte();
 
	}
 
	return i;
 
}
 

	
 
/**
 
 * Write the header descriptor of an object or an array.
 
 * If the element is bigger than 127, use 2 bytes for saving
 
 * and use the highest byte of the first written one as a notice
 
 * that the length consists of 2 bytes, etc.. like this:
 
 * 0xxxxxxx
 
 * 10xxxxxx xxxxxxxx
 
 * 110xxxxx xxxxxxxx xxxxxxxx
 
 * 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
 
 * @param i Index being written
 
 */
 

	
 
static void SlWriteSimpleGamma(uint i)
 
{
 
	if (i >= (1 << 7)) {
 
		if (i >= (1 << 14)) {
 
			if (i >= (1 << 21)) {
 
				assert(i < (1 << 28));
 
				SlWriteByte((byte)0xE0 | (i>>24));
 
				SlWriteByte((byte)(i>>16));
 
			} else {
 
				SlWriteByte((byte)0xC0 | (i>>16));
 
			}
 
			SlWriteByte((byte)(i>>8));
 
		} else {
 
			SlWriteByte((byte)(0x80 | (i>>8)));
 
		}
 
	}
 
	SlWriteByte(i);
 
}
 

	
 
/** Return how many bytes used to encode a gamma value */
 
static inline uint SlGetGammaLength(uint i) {
 
	return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21));
 
}
 

	
 
static inline uint SlReadSparseIndex(void) {return SlReadSimpleGamma();}
 
static inline void SlWriteSparseIndex(uint index) {SlWriteSimpleGamma(index);}
 

	
 
static inline uint SlReadArrayLength(void) {return SlReadSimpleGamma();}
 
static inline void SlWriteArrayLength(uint length) {SlWriteSimpleGamma(length);}
 
static inline uint SlGetArrayLength(uint length) {return SlGetGammaLength(length);}
 

	
 
void SlSetArrayIndex(uint index)
 
{
 
	_sl.need_length = NL_WANTLENGTH;
 
	_sl.array_index = index;
 
}
 

	
 
/**
 
 * Iterate through the elements of an array and read the whole thing
 
 * @return The index of the object, or -1 if we have reached the end of current block
 
 */
 
int SlIterateArray(void)
 
{
 
	int index;
 
	static uint32 next_offs;
 

	
 
	/* After reading in the whole array inside the loop
 
	 * we must have read in all the data, so we must be at end of current block. */
 
	assert(next_offs == 0 || SlGetOffs() == next_offs);
 

	
 
	while (true) {
 
		uint length = SlReadArrayLength();
 
		if (length == 0) {
 
			next_offs = 0;
 
			return -1;
 
		}
 

	
 
		_sl.obj_len = --length;
 
		next_offs = SlGetOffs() + length;
 

	
 
		switch (_sl.block_mode) {
 
		case CH_SPARSE_ARRAY: index = (int)SlReadSparseIndex(); break;
 
		case CH_ARRAY:        index = _sl.array_index++; break;
 
		default:
 
			DEBUG(misc, 0) ("[Sl] SlIterateArray: error");
 
			return -1; // error
 
		}
 

	
 
		if (length != 0) return index;
 
	}
 
}
 

	
 
/**
 
 * Sets the length of either a RIFF object or the number of items in an array.
 
 * This lets us load an object or an array of arbitrary size
 
 * @param length The length of the sought object/array
 
 */
 
void SlSetLength(size_t length)
 
{
 
	assert(_sl.save);
 

	
 
	switch (_sl.need_length) {
 
	case NL_WANTLENGTH:
 
		_sl.need_length = NL_NONE;
 
		switch (_sl.block_mode) {
 
		case CH_RIFF:
 
			// Ugly encoding of >16M RIFF chunks
 
			// The lower 24 bits are normal
 
			// The uppermost 4 bits are bits 24:27
 
			assert(length < (1<<28));
 
			SlWriteUint32((length & 0xFFFFFF) | ((length >> 24) << 28));
 
			break;
 
		case CH_ARRAY:
 
			assert(_sl.last_array_index <= _sl.array_index);
 
			while (++_sl.last_array_index <= _sl.array_index)
 
				SlWriteArrayLength(1);
 
			SlWriteArrayLength(length + 1);
 
			break;
 
		case CH_SPARSE_ARRAY:
 
			SlWriteArrayLength(length + 1 + SlGetArrayLength(_sl.array_index)); // Also include length of sparse index.
 
			SlWriteSparseIndex(_sl.array_index);
 
			break;
 
		default: NOT_REACHED();
 
		} break;
 
	case NL_CALCLENGTH:
 
		_sl.obj_len += length;
 
		break;
 
	}
 
}
 

	
 
/**
 
 * Save/Load bytes. These do not need to be converted to Little/Big Endian
 
 * so directly write them or read them to/from file
 
 * @param ptr The source or destination of the object being manipulated
 
 * @param length number of bytes this fast CopyBytes lasts
 
 */
 
static void SlCopyBytes(void *ptr, size_t length)
 
{
 
	byte *p = (byte*)ptr;
 

	
 
	if (_sl.save) {
 
		for (; length != 0; length--) {SlWriteByteInternal(*p++);}
 
	} else {
 
		for (; length != 0; length--) {*p++ = SlReadByteInternal();}
 
	}
 
}
 

	
 
/** Read in bytes from the file/data structure but don't do
 
 * anything with them, discarding them in effect
 
 * @param length The amount of bytes that is being treated this way
 
 */
 
static inline void SlSkipBytes(size_t length)
 
{
 
	for (; length != 0; length--) SlReadByte();
 
}
 

	
 
/* Get the length of the current object */
 
uint SlGetFieldLength(void) {return _sl.obj_len;}
 

	
 
/** Return a signed-long version of the value of a setting
 
 * @param ptr pointer to the variable
 
 * @param conv type of variable, can be a non-clean
 
 * type, eg one with other flags because it is parsed
 
 * @return returns the value of the pointer-setting */
 
int64 ReadValue(const void *ptr, VarType conv)
 
{
 
	switch (GetVarMemType(conv)) {
 
	case SLE_VAR_BL:  return (*(bool*)ptr != 0);
 
	case SLE_VAR_I8:  return *(int8*  )ptr;
 
	case SLE_VAR_U8:  return *(byte*  )ptr;
 
	case SLE_VAR_I16: return *(int16* )ptr;
 
	case SLE_VAR_U16: return *(uint16*)ptr;
 
	case SLE_VAR_I32: return *(int32* )ptr;
 
	case SLE_VAR_U32: return *(uint32*)ptr;
 
	case SLE_VAR_I64: return *(int64* )ptr;
 
	case SLE_VAR_U64: return *(uint64*)ptr;
 
	case SLE_VAR_NULL:return 0;
 
	default: NOT_REACHED();
 
	}
 

	
 
	/* useless, but avoids compiler warning this way */
 
	return 0;
station.h
Show inline comments
 
/* $Id$ */
 

	
 
#ifndef STATION_H
 
#define STATION_H
 

	
 
#include "player.h"
 
#include "pool.h"
 
#include "sprite.h"
 
#include "tile.h"
 
#include "newgrf_station.h"
 

	
 
typedef struct GoodsEntry {
 
	uint16 waiting_acceptance;
 
	byte days_since_pickup;
 
	byte rating;
 
	StationID enroute_from;
 
	byte enroute_time;
 
	byte last_speed;
 
	byte last_age;
 
	int32 feeder_profit;
 
} GoodsEntry;
 

	
 
typedef enum RoadStopType {
 
	RS_BUS,
 
	RS_TRUCK
 
} RoadStopType;
 

	
 
enum {
 
	INVALID_STATION = 0xFFFF,
 
	ROAD_STOP_LIMIT = 16,
 
};
 

	
 
typedef struct RoadStop {
 
	TileIndex xy;
 
	bool used;
 
	byte status;
 
	uint32 index;
 
	byte num_vehicles;
 
	StationID station;
 
	struct RoadStop *next;
 
	struct RoadStop *prev;
 
} RoadStop;
 

	
 
typedef struct StationSpecList {
 
	const StationSpec *spec;
 
	uint32 grfid;      /// GRF ID of this custom station
 
	uint8  localidx;   /// Station ID within GRF of station
 
} StationSpecList;
 

	
 
struct Station {
 
	TileIndex xy;
 
	RoadStop *bus_stops;
 
	RoadStop *truck_stops;
 
	TileIndex train_tile;
 
	TileIndex airport_tile;
 
	TileIndex dock_tile;
 
	Town *town;
 
	uint16 string_id;
 

	
 
	ViewportSign sign;
 

	
 
	uint16 had_vehicle_of_type;
 

	
 
	byte time_since_load;
 
	byte time_since_unload;
 
	byte delete_ctr;
 
	PlayerID owner;
 
	byte facilities;
 
	byte airport_type;
 

	
 
	// trainstation width/height
 
	byte trainst_w, trainst_h;
 

	
 
	/** List of custom stations (StationSpecs) allocated to the station */
 
	uint num_specs;
 
	StationSpecList *speclist;
 

	
 
	uint16 build_date;
 

	
 
	//uint16 airport_flags;
 
	uint32 airport_flags;
 
	StationID index;
 

	
 
	byte last_vehicle_type;
 
	GoodsEntry goods[NUM_CARGO];
 

	
 
	uint16 random_bits;
 
	byte waiting_triggers;
 

	
 
	/* Stuff that is no longer used, but needed for conversion */
 
	TileIndex bus_tile_obsolete;
 
	TileIndex lorry_tile_obsolete;
 

	
 
	byte truck_stop_status_obsolete;
 
	byte bus_stop_status_obsolete;
 
	byte blocked_months_obsolete;
 
};
 

	
 
enum {
 
	FACIL_TRAIN = 1,
 
	FACIL_TRUCK_STOP = 2,
 
	FACIL_BUS_STOP = 4,
 
	FACIL_AIRPORT = 8,
 
	FACIL_DOCK = 0x10,
 
};
 

	
 
enum {
 
//	HVOT_PENDING_DELETE = 1<<0, // not needed anymore
 
	HVOT_TRAIN    = 1 << 1,
 
	HVOT_BUS      = 1 << 2,
 
	HVOT_TRUCK    = 1 << 3,
 
	HVOT_AIRCRAFT = 1 << 4,
 
	HVOT_SHIP     = 1 << 5,
 
	/* This bit is used to mark stations. No, it does not belong here, but what
 
	 * can we do? ;-) */
 
	HVOT_BUOY     = 1 << 6
 
};
 

	
 
enum {
 
	CA_BUS = 3,
 
	CA_TRUCK = 3,
 
	CA_AIR_OILPAD = 3,
 
	CA_TRAIN = 4,
 
	CA_AIR_HELIPORT = 4,
 
	CA_AIR_SMALL = 4,
 
	CA_AIR_LARGE = 5,
 
	CA_DOCK = 5,
 
	CA_AIR_METRO = 6,
 
	CA_AIR_INTER = 8,
 
};
 

	
 
void ModifyStationRatingAround(TileIndex tile, PlayerID owner, int amount, uint radius);
 

	
 
TileIndex GetStationTileForVehicle(const Vehicle *v, const Station *st);
 

	
 
void ShowStationViewWindow(StationID station);
 
void UpdateAllStationVirtCoord(void);
 

	
 
VARDEF SortStruct *_station_sort;
 

	
 
extern MemoryPool _station_pool;
 

	
 
/**
 
 * Get the pointer to the station with index 'index'
 
 */
 
static inline Station *GetStation(StationID index)
 
{
 
	return (Station*)GetItemFromPool(&_station_pool, index);
 
}
 

	
 
/**
 
 * Get the current size of the StationPool
 
 */
 
static inline uint16 GetStationPoolSize(void)
 
{
 
	return _station_pool.total_items;
 
}
 

	
 
static inline bool IsStationIndex(StationID index)
 
{
 
	return index < GetStationPoolSize();
 
}
 

	
 
#define FOR_ALL_STATIONS_FROM(st, start) for (st = GetStation(start); st != NULL; st = (st->index + 1 < GetStationPoolSize()) ? GetStation(st->index + 1) : NULL)
 
#define FOR_ALL_STATIONS(st) FOR_ALL_STATIONS_FROM(st, 0)
 

	
 

	
 
/* Stuff for ROADSTOPS */
 

	
 
extern MemoryPool _roadstop_pool;
 

	
 
/**
 
 * Get the pointer to the roadstop with index 'index'
 
 */
 
static inline RoadStop *GetRoadStop(uint index)
 
{
 
	return (RoadStop*)GetItemFromPool(&_roadstop_pool, index);
 
}
 

	
 
/**
 
 * Get the current size of the RoadStoptPool
 
 */
 
static inline uint16 GetRoadStopPoolSize(void)
 
{
 
	return _roadstop_pool.total_items;
 
}
 

	
 
#define FOR_ALL_ROADSTOPS_FROM(rs, start) for (rs = GetRoadStop(start); rs != NULL; rs = (rs->index + 1 < GetRoadStopPoolSize()) ? GetRoadStop(rs->index + 1) : NULL)
 
#define FOR_ALL_ROADSTOPS(rs) FOR_ALL_ROADSTOPS_FROM(rs, 0)
 

	
 
/* End of stuff for ROADSTOPS */
 

	
 

	
 
VARDEF bool _station_sort_dirty[MAX_PLAYERS];
 
VARDEF bool _global_station_sort_dirty;
 

	
 
void AfterLoadStations(void);
 
void GetProductionAroundTiles(AcceptedCargo produced, TileIndex tile, int w, int h, int rad);
 
void GetAcceptanceAroundTiles(AcceptedCargo accepts, TileIndex tile, int w, int h, int rad);
 
uint GetStationPlatforms(const Station *st, TileIndex tile);
 

	
 

	
 
const DrawTileSprites *GetStationTileLayout(byte gfx);
 
void StationPickerDrawSprite(int x, int y, RailType railtype, int image);
 

	
 
RoadStop * GetRoadStopByTile(TileIndex tile, RoadStopType type);
 
RoadStop * GetPrimaryRoadStop(const Station *st, RoadStopType type);
 
uint GetNumRoadStops(const Station* st, RoadStopType type);
 
RoadStop * AllocateRoadStop( void );
 
void ClearSlot(Vehicle *v);
 

	
 
/**
 
 * Check if a station really exists.
 
 */
 
static inline bool IsValidStation(const Station *st)
 
{
 
	return st->xy != 0; /* XXX: Replace by INVALID_TILE someday */
 
}
 

	
 
static inline bool IsBuoy(const Station* st)
 
{
 
	return st->had_vehicle_of_type & HVOT_BUOY; /* XXX: We should really ditch this ugly coding and switch to something sane... */
 
}
 

	
 
#endif /* STATION_H */
station_cmd.c
Show inline comments
 
@@ -2440,600 +2440,630 @@ static void UpdateStationRating(Station 
 
				if (waiting_changed) SB(ge->waiting_acceptance, 0, 12, waiting);
 
			}
 
		}
 
	} while (++ge != endof(st->goods));
 

	
 
	index = st->index;
 

	
 
	if (waiting_changed)
 
		InvalidateWindow(WC_STATION_VIEW, index);
 
	else
 
		InvalidateWindowWidget(WC_STATION_VIEW, index, 5);
 
}
 

	
 
/* called for every station each tick */
 
static void StationHandleSmallTick(Station *st)
 
{
 
	byte b;
 

	
 
	if (st->facilities == 0) return;
 

	
 
	b = st->delete_ctr + 1;
 
	if (b >= 185) b = 0;
 
	st->delete_ctr = b;
 

	
 
	if (b == 0) UpdateStationRating(st);
 
}
 

	
 
void OnTick_Station(void)
 
{
 
	uint i;
 
	Station *st;
 

	
 
	if (_game_mode == GM_EDITOR) return;
 

	
 
	i = _station_tick_ctr;
 
	if (++_station_tick_ctr == GetStationPoolSize()) _station_tick_ctr = 0;
 

	
 
	st = GetStation(i);
 
	if (st->xy != 0) StationHandleBigTick(st);
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->xy != 0) StationHandleSmallTick(st);
 
	}
 
}
 

	
 
void StationMonthlyLoop(void)
 
{
 
}
 

	
 

	
 
void ModifyStationRatingAround(TileIndex tile, PlayerID owner, int amount, uint radius)
 
{
 
	Station *st;
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->xy != 0 && st->owner == owner &&
 
				DistanceManhattan(tile, st->xy) <= radius) {
 
			uint i;
 

	
 
			for (i = 0; i != NUM_CARGO; i++) {
 
				GoodsEntry* ge = &st->goods[i];
 

	
 
				if (ge->enroute_from != INVALID_STATION) {
 
					ge->rating = clamp(ge->rating + amount, 0, 255);
 
				}
 
			}
 
		}
 
	}
 
}
 

	
 
static void UpdateStationWaiting(Station *st, int type, uint amount)
 
{
 
	SB(st->goods[type].waiting_acceptance, 0, 12,
 
		min(0xFFF, GB(st->goods[type].waiting_acceptance, 0, 12) + amount)
 
	);
 

	
 
	st->goods[type].enroute_time = 0;
 
	st->goods[type].enroute_from = st->index;
 
	InvalidateWindow(WC_STATION_VIEW, st->index);
 
}
 

	
 
/** Rename a station
 
 * @param tile unused
 
 * @param p1 station ID that is to be renamed
 
 * @param p2 unused
 
 */
 
int32 CmdRenameStation(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	StringID str;
 
	Station *st;
 

	
 
	if (!IsStationIndex(p1) || _cmd_text[0] == '\0') return CMD_ERROR;
 
	st = GetStation(p1);
 

	
 
	if (!IsValidStation(st) || !CheckOwnership(st->owner)) return CMD_ERROR;
 

	
 
	str = AllocateNameUnique(_cmd_text, 6);
 
	if (str == 0) return CMD_ERROR;
 

	
 
	if (flags & DC_EXEC) {
 
		StringID old_str = st->string_id;
 

	
 
		st->string_id = str;
 
		UpdateStationVirtCoord(st);
 
		DeleteName(old_str);
 
		_station_sort_dirty[st->owner] = true; // rename a station
 
		MarkWholeScreenDirty();
 
	} else {
 
		DeleteName(str);
 
	}
 

	
 
	return 0;
 
}
 

	
 

	
 
uint MoveGoodsToStation(TileIndex tile, int w, int h, int type, uint amount)
 
{
 
	Station* around[8];
 
	uint i;
 
	uint moved;
 
	uint best_rating, best_rating2;
 
	Station *st1, *st2;
 
	uint t;
 
	int rad = 0;
 
	int w_prod; //width and height of the "producer" of the cargo
 
	int h_prod;
 
	int max_rad;
 

	
 
	for (i = 0; i < lengthof(around); i++) around[i] = NULL;
 

	
 
	if (_patches.modified_catchment) {
 
		w_prod = w;
 
		h_prod = h;
 
		w += 16;
 
		h += 16;
 
		max_rad = 8;
 
	} else {
 
		w_prod = 0;
 
		h_prod = 0;
 
		w += 8;
 
		h += 8;
 
		max_rad = 4;
 
	}
 

	
 
	BEGIN_TILE_LOOP(cur_tile, w, h, tile - TileDiffXY(max_rad, max_rad))
 
		Station* st;
 

	
 
		cur_tile = TILE_MASK(cur_tile);
 
		if (!IsTileType(cur_tile, MP_STATION)) continue;
 

	
 
		st = GetStationByTile(cur_tile);
 

	
 
		for (i = 0; i != lengthof(around); i++) {
 
			if (around[i] == NULL) {
 
				if (!IsBuoy(st) &&
 
						(st->town->exclusive_counter == 0 || st->town->exclusivity == st->owner) && // check exclusive transport rights
 
						st->goods[type].rating != 0 &&
 
						(!_patches.selectgoods || st->goods[type].last_speed > 0) && // if last_speed is 0, no vehicle has been there.
 
						((st->facilities & ~FACIL_BUS_STOP)   != 0 || type == CT_PASSENGERS) && // if we have other fac. than a bus stop, or the cargo is passengers
 
						((st->facilities & ~FACIL_TRUCK_STOP) != 0 || type != CT_PASSENGERS)) { // if we have other fac. than a cargo bay or the cargo is not passengers
 
					int x_dist;
 
					int y_dist;
 

	
 
					if (_patches.modified_catchment) {
 
						// min and max coordinates of the producer relative
 
						const int x_min_prod = 9;
 
						const int x_max_prod = 8 + w_prod;
 
						const int y_min_prod = 9;
 
						const int y_max_prod = 8 + h_prod;
 

	
 
						rad = FindCatchmentRadius(st);
 

	
 
						x_dist = min(w_cur - x_min_prod, x_max_prod - w_cur);
 
						if (w_cur < x_min_prod) {
 
							x_dist = x_min_prod - w_cur;
 
						} else if (w_cur > x_max_prod) {
 
							x_dist = w_cur - x_max_prod;
 
						}
 

	
 
						y_dist = min(h_cur - y_min_prod, y_max_prod - h_cur);
 
						if (h_cur < y_min_prod) {
 
							y_dist = y_min_prod - h_cur;
 
						} else if (h_cur > y_max_prod) {
 
							y_dist = h_cur - y_max_prod;
 
						}
 
					} else {
 
						x_dist = 0;
 
						y_dist = 0;
 
					}
 

	
 
					if (x_dist <= rad && y_dist <= rad) around[i] = st;
 
				}
 
				break;
 
			} else if (around[i] == st) {
 
				break;
 
			}
 
		}
 
	END_TILE_LOOP(cur_tile, w, h, tile - TileDiffXY(max_rad, max_rad))
 

	
 
	/* no stations around at all? */
 
	if (around[0] == NULL) return 0;
 

	
 
	if (around[1] == NULL) {
 
		/* only one station around */
 
		moved = (amount * around[0]->goods[type].rating >> 8) + 1;
 
		UpdateStationWaiting(around[0], type, moved);
 
		return moved;
 
	}
 

	
 
	/* several stations around, find the two with the highest rating */
 
	st2 = st1 = NULL;
 
	best_rating = best_rating2 = 0;
 

	
 
	for (i = 0; i != lengthof(around) && around[i] != NULL; i++) {
 
		if (around[i]->goods[type].rating >= best_rating) {
 
			best_rating2 = best_rating;
 
			st2 = st1;
 

	
 
			best_rating = around[i]->goods[type].rating;
 
			st1 = around[i];
 
		} else if (around[i]->goods[type].rating >= best_rating2) {
 
			best_rating2 = around[i]->goods[type].rating;
 
			st2 = around[i];
 
		}
 
	}
 

	
 
	assert(st1 != NULL);
 
	assert(st2 != NULL);
 
	assert(best_rating != 0 || best_rating2 != 0);
 

	
 
	/* the 2nd highest one gets a penalty */
 
	best_rating2 >>= 1;
 

	
 
	/* amount given to station 1 */
 
	t = (best_rating * (amount + 1)) / (best_rating + best_rating2);
 

	
 
	moved = 0;
 
	if (t != 0) {
 
		moved = t * best_rating / 256 + 1;
 
		amount -= t;
 
		UpdateStationWaiting(st1, type, moved);
 
	}
 

	
 
	if (amount != 0) {
 
		amount = amount * best_rating2 / 256 + 1;
 
		moved += amount;
 
		UpdateStationWaiting(st2, type, amount);
 
	}
 

	
 
	return moved;
 
}
 

	
 
void BuildOilRig(TileIndex tile)
 
{
 
	uint j;
 
	Station *st = AllocateStation();
 

	
 
	if (st == NULL) {
 
		DEBUG(misc, 0) ("Couldn't allocate station for oilrig at 0x%X, reverting to oilrig only...", tile);
 
		return;
 
	}
 
	if (!GenerateStationName(st, tile, 2)) {
 
		DEBUG(misc, 0) ("Couldn't allocate station-name for oilrig at 0x%X, reverting to oilrig only...", tile);
 
		return;
 
	}
 

	
 
	st->town = ClosestTownFromTile(tile, (uint)-1);
 
	st->sign.width_1 = 0;
 

	
 
	MakeOilrig(tile, st->index);
 

	
 
	st->owner = OWNER_NONE;
 
	st->airport_flags = 0;
 
	st->airport_type = AT_OILRIG;
 
	st->xy = tile;
 
	st->bus_stops = NULL;
 
	st->truck_stops = NULL;
 
	st->airport_tile = tile;
 
	st->dock_tile = tile;
 
	st->train_tile = 0;
 
	st->had_vehicle_of_type = 0;
 
	st->time_since_load = 255;
 
	st->time_since_unload = 255;
 
	st->delete_ctr = 0;
 
	st->last_vehicle_type = VEH_Invalid;
 
	st->facilities = FACIL_AIRPORT | FACIL_DOCK;
 
	st->build_date = _date;
 

	
 
	for (j = 0; j != NUM_CARGO; j++) {
 
		st->goods[j].waiting_acceptance = 0;
 
		st->goods[j].days_since_pickup = 0;
 
		st->goods[j].enroute_from = INVALID_STATION;
 
		st->goods[j].rating = 175;
 
		st->goods[j].last_speed = 0;
 
		st->goods[j].last_age = 255;
 
	}
 

	
 
	UpdateStationVirtCoordDirty(st);
 
	UpdateStationAcceptance(st, false);
 
}
 

	
 
void DeleteOilRig(TileIndex tile)
 
{
 
	Station* st = GetStationByTile(tile);
 

	
 
	DoClearSquare(tile);
 

	
 
	st->dock_tile = 0;
 
	st->airport_tile = 0;
 
	st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
 
	st->airport_flags = 0;
 
	UpdateStationVirtCoordDirty(st);
 
	DeleteStation(st);
 
}
 

	
 
static void ChangeTileOwner_Station(TileIndex tile, PlayerID old_player, PlayerID new_player)
 
{
 
	if (!IsTileOwner(tile, old_player)) return;
 

	
 
	if (new_player != OWNER_SPECTATOR) {
 
		Station* st = GetStationByTile(tile);
 

	
 
		SetTileOwner(tile, new_player);
 
		st->owner = new_player;
 
		_global_station_sort_dirty = true; // transfer ownership of station to another player
 
		InvalidateWindowClasses(WC_STATION_LIST);
 
	} else {
 
		DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
 
	}
 
}
 

	
 
static int32 ClearTile_Station(TileIndex tile, byte flags)
 
{
 
	Station *st;
 

	
 
	if (flags & DC_AUTO) {
 
		switch (GetStationType(tile)) {
 
			case STATION_RAIL:    return_cmd_error(STR_300B_MUST_DEMOLISH_RAILROAD);
 
			case STATION_HANGAR:
 
			case STATION_AIRPORT: return_cmd_error(STR_300E_MUST_DEMOLISH_AIRPORT_FIRST);
 
			case STATION_TRUCK:   return_cmd_error(STR_3047_MUST_DEMOLISH_TRUCK_STATION);
 
			case STATION_BUS:     return_cmd_error(STR_3046_MUST_DEMOLISH_BUS_STATION);
 
			case STATION_BUOY:    return_cmd_error(STR_306A_BUOY_IN_THE_WAY);
 
			case STATION_DOCK:    return_cmd_error(STR_304D_MUST_DEMOLISH_DOCK_FIRST);
 
			case STATION_OILRIG:
 
				SetDParam(0, STR_4807_OIL_RIG);
 
				return_cmd_error(STR_4800_IN_THE_WAY);
 
		}
 
	}
 

	
 
	st = GetStationByTile(tile);
 

	
 
	switch (GetStationType(tile)) {
 
		case STATION_RAIL:    return RemoveRailroadStation(st, tile, flags);
 
		case STATION_HANGAR:
 
		case STATION_AIRPORT: return RemoveAirport(st, flags);
 
		case STATION_TRUCK:
 
		case STATION_BUS:     return RemoveRoadStop(st, flags, tile);
 
		case STATION_BUOY:    return RemoveBuoy(st, flags);
 
		case STATION_DOCK:    return RemoveDock(st, flags);
 
		default: break;
 
	}
 

	
 
	return CMD_ERROR;
 
}
 

	
 
void InitializeStations(void)
 
{
 
	/* Clean the station pool and create 1 block in it */
 
	CleanPool(&_station_pool);
 
	AddBlockToPool(&_station_pool);
 

	
 
	/* Clean the roadstop pool and create 1 block in it */
 
	CleanPool(&_roadstop_pool);
 
	AddBlockToPool(&_roadstop_pool);
 

	
 
	_station_tick_ctr = 0;
 

	
 
	// set stations to be sorted on load of savegame
 
	memset(_station_sort_dirty, true, sizeof(_station_sort_dirty));
 
	_global_station_sort_dirty = true; // load of savegame
 
}
 

	
 

	
 
void AfterLoadStations(void)
 
{
 
	Station *st;
 
	uint i;
 

	
 
	/* Update the speclists of all stations to point to the currently loaded custom stations. */
 
	FOR_ALL_STATIONS(st) {
 
		for (i = 0; i < st->num_specs; i++) {
 
			if (st->speclist[i].grfid == 0) continue;
 

	
 
			st->speclist[i].spec = GetCustomStationSpecByGrf(st->speclist[i].grfid, st->speclist[i].localidx);
 
		}
 
	}
 
}
 

	
 

	
 
const TileTypeProcs _tile_type_station_procs = {
 
	DrawTile_Station,           /* draw_tile_proc */
 
	GetSlopeZ_Station,          /* get_slope_z_proc */
 
	ClearTile_Station,          /* clear_tile_proc */
 
	GetAcceptedCargo_Station,   /* get_accepted_cargo_proc */
 
	GetTileDesc_Station,        /* get_tile_desc_proc */
 
	GetTileTrackStatus_Station, /* get_tile_track_status_proc */
 
	ClickTile_Station,          /* click_tile_proc */
 
	AnimateTile_Station,        /* animate_tile_proc */
 
	TileLoop_Station,           /* tile_loop_clear */
 
	ChangeTileOwner_Station,    /* change_tile_owner_clear */
 
	NULL,                       /* get_produced_cargo_proc */
 
	VehicleEnter_Station,       /* vehicle_enter_tile_proc */
 
	GetSlopeTileh_Station,      /* get_slope_tileh_proc */
 
};
 

	
 
static const SaveLoad _roadstop_desc[] = {
 
	SLE_VAR(RoadStop,xy,           SLE_UINT32),
 
	SLE_VAR(RoadStop,used,         SLE_UINT8),
 
	SLE_VAR(RoadStop,status,       SLE_UINT8),
 
	/* Index was saved in some versions, but this is not needed */
 
	SLE_CONDNULL(4, 0, 8),
 
	SLE_VAR(RoadStop,station,      SLE_UINT16),
 
	SLE_CONDNULL(1, 0, 25),
 

	
 
	SLE_REF(RoadStop,next,         REF_ROADSTOPS),
 
	SLE_REF(RoadStop,prev,         REF_ROADSTOPS),
 

	
 
	SLE_CONDNULL(4, 0, 24),
 
	SLE_CONDNULL(1, 25, 25),
 

	
 
	SLE_END()
 
};
 

	
 
static const SaveLoad _station_desc[] = {
 
	SLE_CONDVAR(Station, xy,                  SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
 
	SLE_CONDVAR(Station, xy,                  SLE_UINT32, 6, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station, bus_tile_obsolete,   SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
 
	SLE_CONDVAR(Station, lorry_tile_obsolete, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
 
	SLE_CONDVAR(Station, train_tile,          SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
 
	SLE_CONDVAR(Station, train_tile,          SLE_UINT32, 6, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station, airport_tile,        SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
 
	SLE_CONDVAR(Station, airport_tile,        SLE_UINT32, 6, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station, dock_tile,           SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
 
	SLE_CONDVAR(Station, dock_tile,           SLE_UINT32, 6, SL_MAX_VERSION),
 
	SLE_REF(Station,     town,                REF_TOWN),
 
	SLE_VAR(Station,     trainst_w,           SLE_UINT8),
 
	SLE_CONDVAR(Station, trainst_h,           SLE_UINT8,  2, SL_MAX_VERSION),
 

	
 
	// alpha_order was stored here in savegame format 0 - 3
 
	SLE_CONDNULL(1, 0, 3),
 

	
 
	SLE_VAR(Station,string_id,          SLE_STRINGID),
 
	SLE_VAR(Station,had_vehicle_of_type,SLE_UINT16),
 

	
 
	SLE_VAR(Station,time_since_load,    SLE_UINT8),
 
	SLE_VAR(Station,time_since_unload,  SLE_UINT8),
 
	SLE_VAR(Station,delete_ctr,         SLE_UINT8),
 
	SLE_VAR(Station,owner,              SLE_UINT8),
 
	SLE_VAR(Station,facilities,         SLE_UINT8),
 
	SLE_VAR(Station,airport_type,       SLE_UINT8),
 

	
 
	// truck/bus_stop_status was stored here in savegame format 0 - 6
 
	SLE_CONDVAR(Station,truck_stop_status_obsolete, SLE_UINT8, 0, 5),
 
	SLE_CONDVAR(Station,bus_stop_status_obsolete,   SLE_UINT8, 0, 5),
 

	
 
	// blocked_months was stored here in savegame format 0 - 4.0
 
	SLE_CONDVAR(Station,blocked_months_obsolete,    SLE_UINT8, 0, 4),
 

	
 
	SLE_CONDVAR(Station,airport_flags,     SLE_VAR_U32 | SLE_FILE_U16, 0, 2),
 
	SLE_CONDVAR(Station,airport_flags,     SLE_UINT32, 3, SL_MAX_VERSION),
 

	
 
	SLE_CONDNULL(2, 0, 25), /* Ex last-vehicle */
 
	SLE_CONDVAR(Station,last_vehicle_type,          SLE_UINT8 , 26, SL_MAX_VERSION),
 

	
 
	// Was custom station class and id
 
	SLE_CONDNULL(2, 3, 25),
 
	SLE_CONDVAR(Station,build_date,        SLE_UINT16, 3, SL_MAX_VERSION),
 

	
 
	SLE_CONDREF(Station,bus_stops,         REF_ROADSTOPS, 6, SL_MAX_VERSION),
 
	SLE_CONDREF(Station,truck_stops,       REF_ROADSTOPS, 6, SL_MAX_VERSION),
 

	
 
	/* Used by newstations for graphic variations */
 
	SLE_CONDVAR(Station,random_bits,       SLE_UINT16, 27, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station,waiting_triggers,  SLE_UINT8,  27, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station,num_specs,         SLE_UINT8,  27, SL_MAX_VERSION),
 

	
 
	// reserve extra space in savegame here. (currently 32 bytes)
 
	SLE_CONDNULL(32, 2, SL_MAX_VERSION),
 

	
 
	SLE_END()
 
};
 

	
 
static const SaveLoad _goods_desc[] = {
 
	SLE_VAR(GoodsEntry,waiting_acceptance, SLE_UINT16),
 
	SLE_VAR(GoodsEntry,days_since_pickup,  SLE_UINT8),
 
	SLE_VAR(GoodsEntry,rating,             SLE_UINT8),
 
	SLE_CONDVAR(GoodsEntry,enroute_from,   SLE_FILE_U8 | SLE_VAR_U16, 0, 6),
 
	SLE_CONDVAR(GoodsEntry,enroute_from,   SLE_UINT16, 7, SL_MAX_VERSION),
 
	SLE_VAR(GoodsEntry,enroute_time,       SLE_UINT8),
 
	SLE_VAR(GoodsEntry,last_speed,         SLE_UINT8),
 
	SLE_VAR(GoodsEntry,last_age,           SLE_UINT8),
 
	SLE_CONDVAR(GoodsEntry,feeder_profit,  SLE_INT32, 14, SL_MAX_VERSION),
 

	
 
	SLE_END()
 
};
 

	
 
static const SaveLoad _station_speclist_desc[] = {
 
	SLE_CONDVAR(StationSpecList, grfid,    SLE_UINT32, 27, SL_MAX_VERSION),
 
	SLE_CONDVAR(StationSpecList, localidx, SLE_UINT8,  27, SL_MAX_VERSION),
 

	
 
	SLE_END()
 
};
 

	
 

	
 
static void SaveLoad_STNS(Station *st)
 
{
 
	int i;
 
	uint i;
 

	
 
	SlObject(st, _station_desc);
 
	for (i = 0; i != NUM_CARGO; i++) {
 
		SlObject(&st->goods[i], _goods_desc);
 

	
 
		/* In older versions, enroute_from had 0xFF as INVALID_STATION, is now 0xFFFF */
 
		if (CheckSavegameVersion(7) && st->goods[i].enroute_from == 0xFF) {
 
			st->goods[i].enroute_from = INVALID_STATION;
 
		}
 
	}
 

	
 
	if (st->num_specs != 0) {
 
		/* Allocate speclist memory when loading a game */
 
		if (st->speclist == NULL) st->speclist = calloc(st->num_specs, sizeof(*st->speclist));
 
		for (i = 0; i < st->num_specs; i++) SlObject(&st->speclist[i], _station_speclist_desc);
 
	}
 
}
 

	
 
static void Save_STNS(void)
 
{
 
	Station *st;
 
	// Write the stations
 
	FOR_ALL_STATIONS(st) {
 
		if (st->xy != 0) {
 
			SlSetArrayIndex(st->index);
 
			SlAutolength((AutolengthProc*)SaveLoad_STNS, st);
 
		}
 
	}
 
}
 

	
 
static void Load_STNS(void)
 
{
 
	int index;
 
	while ((index = SlIterateArray()) != -1) {
 
		Station *st;
 

	
 
		if (!AddBlockIfNeeded(&_station_pool, index))
 
			error("Stations: failed loading savegame: too many stations");
 

	
 
		st = GetStation(index);
 
		SaveLoad_STNS(st);
 

	
 
		// this means it's an oldstyle savegame without support for nonuniform stations
 
		if (st->train_tile != 0 && st->trainst_h == 0) {
 
			uint w = GB(st->trainst_w, 4, 4);
 
			uint h = GB(st->trainst_w, 0, 4);
 

	
 
			if (GetRailStationAxis(st->train_tile) == AXIS_Y) uintswap(w, h);
 
			st->trainst_w = w;
 
			st->trainst_h = h;
 
		}
 

	
 
		/* In older versions, we had just 1 tile for a bus/lorry, now we have more..
 
		 *  convert, if needed */
 
		if (CheckSavegameVersion(6)) {
 
			if (st->bus_tile_obsolete != 0) {
 
				st->bus_stops = AllocateRoadStop();
 
				if (st->bus_stops == NULL)
 
					error("Station: too many busstations in savegame");
 

	
 
				InitializeRoadStop(st->bus_stops, NULL, st->bus_tile_obsolete, st->index);
 
			}
 
			if (st->lorry_tile_obsolete != 0) {
 
				st->truck_stops = AllocateRoadStop();
 
				if (st->truck_stops == NULL)
 
					error("Station: too many truckstations in savegame");
 

	
 
				InitializeRoadStop(st->truck_stops, NULL, st->lorry_tile_obsolete, st->index);
 
			}
 
		}
 
	}
 

	
 
	/* This is to ensure all pointers are within the limits of _stations_size */
 
	if (_station_tick_ctr > GetStationPoolSize()) _station_tick_ctr = 0;
 
}
 

	
 
static void Save_ROADSTOP(void)
 
{
 
	RoadStop *rs;
 

	
 
	FOR_ALL_ROADSTOPS(rs) {
 
		if (rs->used) {
 
			SlSetArrayIndex(rs->index);
 
			SlObject(rs, _roadstop_desc);
 
		}
 
	}
 
}
 

	
 
static void Load_ROADSTOP(void)
 
{
 
	int index;
 
	Vehicle *v;
 

	
 
	while ((index = SlIterateArray()) != -1) {
 
		RoadStop *rs;
 

	
 
		if (!AddBlockIfNeeded(&_roadstop_pool, index))
 
			error("RoadStops: failed loading savegame: too many RoadStops");
 

	
 
		rs = GetRoadStop(index);
 
		SlObject(rs, _roadstop_desc);
 
	}
 

	
 
	FOR_ALL_VEHICLES(v) {
 
		if (v->type == VEH_Road && v->u.road.slot != NULL) v->u.road.slot->num_vehicles++;
 
	}
 
}
 

	
 
const ChunkHandler _station_chunk_handlers[] = {
 
	{ 'STNS', Save_STNS,      Load_STNS,      CH_ARRAY },
 
	{ 'ROAD', Save_ROADSTOP,  Load_ROADSTOP,  CH_ARRAY | CH_LAST},
 
};
0 comments (0 inline, 0 general)