id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,539,001
|
newgrf_townname.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_townname.cpp
|
/* $Id$ */
/** @file newgrf_townname.cpp
* Implementation of Action 0F "universal holder" structure and functions.
* This file implements a linked-lists of townname generators,
* holding everything that the newgrf action 0F will send over to OpenTTD.
*/
#include "stdafx.h"
#include "newgrf_townname.h"
#include "core/alloc_func.hpp"
#include "string_func.h"
static GRFTownName *_grf_townnames = NULL;
GRFTownName *GetGRFTownName(uint32 grfid)
{
GRFTownName *t = _grf_townnames;
for (; t != NULL; t = t->next) {
if (t->grfid == grfid) return t;
}
return NULL;
}
GRFTownName *AddGRFTownName(uint32 grfid)
{
GRFTownName *t = GetGRFTownName(grfid);
if (t == NULL) {
t = CallocT<GRFTownName>(1);
t->grfid = grfid;
t->next = _grf_townnames;
_grf_townnames = t;
}
return t;
}
void DelGRFTownName(uint32 grfid)
{
GRFTownName *t = _grf_townnames;
GRFTownName *p = NULL;
for (;t != NULL; p = t, t = t->next) if (t->grfid == grfid) break;
if (t != NULL) {
for (int i = 0; i < 128; i++) {
for (int j = 0; j < t->nbparts[i]; j++) {
for (int k = 0; k < t->partlist[i][j].partcount; k++) {
if (!HasBit(t->partlist[i][j].parts[k].prob, 7)) free(t->partlist[i][j].parts[k].data.text);
}
free(t->partlist[i][j].parts);
}
free(t->partlist[i]);
}
if (p != NULL) {
p->next = t->next;
} else {
_grf_townnames = t->next;
}
free(t);
}
}
static char *RandomPart(char *buf, GRFTownName *t, uint32 seed, byte id, const char *last)
{
assert(t != NULL);
for (int i = 0; i < t->nbparts[id]; i++) {
byte count = t->partlist[id][i].bitcount;
uint16 maxprob = t->partlist[id][i].maxprob;
uint32 r = (GB(seed, t->partlist[id][i].bitstart, count) * maxprob) >> count;
for (int j = 0; j < t->partlist[id][i].partcount; j++) {
byte prob = t->partlist[id][i].parts[j].prob;
maxprob -= GB(prob, 0, 7);
if (maxprob > r) continue;
if (HasBit(prob, 7)) {
buf = RandomPart(buf, t, seed, t->partlist[id][i].parts[j].data.id, last);
} else {
buf = strecat(buf, t->partlist[id][i].parts[j].data.text, last);
}
break;
}
}
return buf;
}
char *GRFTownNameGenerate(char *buf, uint32 grfid, uint16 gen, uint32 seed, const char *last)
{
strecpy(buf, "", last);
for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) {
if (t->grfid == grfid) {
assert(gen < t->nb_gen);
buf = RandomPart(buf, t, seed, t->id[gen], last);
break;
}
}
return buf;
}
StringID *GetGRFTownNameList()
{
int nb_names = 0, n = 0;
for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) nb_names += t->nb_gen;
StringID *list = MallocT<StringID>(nb_names + 1);
for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) {
for (int j = 0; j < t->nb_gen; j++) list[n++] = t->name[j];
}
list[n] = INVALID_STRING_ID;
return list;
}
void CleanUpGRFTownNames()
{
while (_grf_townnames != NULL) DelGRFTownName(_grf_townnames->grfid);
}
uint32 GetGRFTownNameId(int gen)
{
for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) {
if (gen < t->nb_gen) return t->grfid;
gen -= t->nb_gen;
}
/* Fallback to no NewGRF */
return 0;
}
uint16 GetGRFTownNameType(int gen)
{
for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) {
if (gen < t->nb_gen) return gen;
gen -= t->nb_gen;
}
/* Fallback to english original */
return SPECSTR_TOWNNAME_ENGLISH;
}
| 3,354
|
C++
|
.cpp
| 119
| 25.764706
| 97
| 0.635743
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
1,539,002
|
newgrf_commons.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_commons.cpp
|
/* $Id$ */
/** @file newgrf_commons.cpp Implementation of the class OverrideManagerBase
* and its descendance, present and futur
*/
#include "stdafx.h"
#include "landscape.h"
#include "town.h"
#include "industry.h"
#include "newgrf.h"
#include "newgrf_commons.h"
#include "station_map.h"
#include "tree_map.h"
/** Constructor of generic class
* @param offset end of original data for this entity. i.e: houses = 110
* @param maximum of entities this manager can deal with. i.e: houses = 512
* @param invalid is the ID used to identify an invalid entity id
*/
OverrideManagerBase::OverrideManagerBase(uint16 offset, uint16 maximum, uint16 invalid)
{
max_offset = offset;
max_new_entities = maximum;
invalid_ID = invalid;
mapping_ID = CallocT<EntityIDMapping>(max_new_entities);
entity_overrides = MallocT<uint16>(max_offset);
for (size_t i = 0; i < max_offset; i++) entity_overrides[i] = invalid;
grfid_overrides = CallocT<uint32>(max_offset);
}
/** Destructor of the generic class.
* Frees allocated memory of constructor
*/
OverrideManagerBase::~OverrideManagerBase()
{
free(mapping_ID);
free(entity_overrides);
free(grfid_overrides);
}
/** Since the entity IDs defined by the GRF file does not necessarily correlate
* to those used by the game, the IDs used for overriding old entities must be
* translated when the entity spec is set.
* @param local_id ID in grf file
* @param grfid ID of the grf file
* @param entity_type original entity type
*/
void OverrideManagerBase::Add(uint8 local_id, uint32 grfid, uint entity_type)
{
assert(entity_type < max_offset);
/* An override can be set only once */
if (entity_overrides[entity_type] != invalid_ID) return;
entity_overrides[entity_type] = local_id;
grfid_overrides[entity_type] = grfid;
}
/** Resets the mapping, which is used while initializing game */
void OverrideManagerBase::ResetMapping()
{
memset(mapping_ID, 0, (max_new_entities - 1) * sizeof(EntityIDMapping));
}
/** Resets the override, which is used while initializing game */
void OverrideManagerBase::ResetOverride()
{
for (uint16 i = 0; i < max_offset; i++) {
entity_overrides[i] = invalid_ID;
grfid_overrides[i] = 0;
}
}
/** Return the ID (if ever available) of a previously inserted entity.
* @param grf_local_id ID of this enity withing the grfID
* @param grfid ID of the grf file
* @return the ID of the candidate, of the Invalid flag item ID
*/
uint16 OverrideManagerBase::GetID(uint8 grf_local_id, uint32 grfid)
{
const EntityIDMapping *map;
for (uint16 id = 0; id < max_new_entities; id++) {
map = &mapping_ID[id];
if (map->entity_id == grf_local_id && map->grfid == grfid) {
return id;
}
}
return invalid_ID;
}
/** Reserves a place in the mapping array for an entity to be installed
* @param grf_local_id is an arbitrary id given by the grf's author. Also known as setid
* @param grfid is the id of the grf file itself
* @param substitute_id is the original entity from which data is copied for the new one
* @return the proper usable slot id, or invalid marker if none is found
*/
uint16 OverrideManagerBase::AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id)
{
uint16 id = this->GetID(grf_local_id, grfid);
EntityIDMapping *map;
/* Look to see if this entity has already been added. This is done
* separately from the loop below in case a GRF has been deleted, and there
* are any gaps in the array.
*/
if (id != invalid_ID) {
return id;
}
/* This entity hasn't been defined before, so give it an ID now. */
for (id = max_offset; id < max_new_entities; id++) {
map = &mapping_ID[id];
if (CheckValidNewID(id) && map->entity_id == 0 && map->grfid == 0) {
map->entity_id = grf_local_id;
map->grfid = grfid;
map->substitute_id = substitute_id;
return id;
}
}
return invalid_ID;
}
/** Gives the substitute of the entity, as specified by the grf file
* @param entity_id of the entity being queried
* @return mapped id
*/
uint16 OverrideManagerBase::GetSubstituteID(byte entity_id)
{
return mapping_ID[entity_id].substitute_id;
}
/** Install the specs into the HouseSpecs array
* It will find itself the proper slot onwhich it will go
* @param hs HouseSpec read from the grf file, ready for inclusion
*/
void HouseOverrideManager::SetEntitySpec(const HouseSpec *hs)
{
HouseID house_id = this->AddEntityID(hs->local_id, hs->grffile->grfid, hs->substitute_id);
if (house_id == invalid_ID) {
grfmsg(1, "House.SetEntitySpec: Too many houses allocated. Ignoring.");
return;
}
memcpy(&_house_specs[house_id], hs, sizeof(*hs));
/* Now add the overrides. */
for (int i = 0; i != max_offset; i++) {
HouseSpec *overridden_hs = GetHouseSpecs(i);
if (entity_overrides[i] != hs->local_id || grfid_overrides[i] != hs->grffile->grfid) continue;
overridden_hs->override = house_id;
entity_overrides[i] = invalid_ID;
grfid_overrides[i] = 0;
}
}
/** Return the ID (if ever available) of a previously inserted entity.
* @param grf_local_id ID of this enity withing the grfID
* @param grfid ID of the grf file
* @return the ID of the candidate, of the Invalid flag item ID
*/
uint16 IndustryOverrideManager::GetID(uint8 grf_local_id, uint32 grfid)
{
uint16 id = OverrideManagerBase::GetID(grf_local_id, grfid);
if (id != invalid_ID) return id;
/* No mapping found, try the overrides */
for (id = 0; id < max_offset; id++) {
if (entity_overrides[id] == grf_local_id && grfid_overrides[id] == grfid) return id;
}
return invalid_ID;
}
/** Method to find an entity ID and to mark it as reserved for the Industry to be included.
* @param grf_local_id ID used by the grf file for pre-installation work (equivalent of TTDPatch's setid
* @param grfid ID of the current grf file
* @param substitute_id industry from which data has been copied
* @return a free entity id (slotid) if ever one has been found, or Invalid_ID marker otherwise
*/
uint16 IndustryOverrideManager::AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id)
{
/* This entity hasn't been defined before, so give it an ID now. */
for (uint16 id = 0; id < max_new_entities; id++) {
/* Skip overriden industries */
if (id < max_offset && entity_overrides[id] != invalid_ID) continue;
/* Get the real live industry */
const IndustrySpec *inds = GetIndustrySpec(id);
/* This industry must be one that is not available(enabled), mostly because of climate.
* And it must not already be used by a grf (grffile == NULL).
* So reseve this slot here, as it is the chosen one */
if (!inds->enabled && inds->grf_prop.grffile == NULL) {
EntityIDMapping *map = &mapping_ID[id];
if (map->entity_id == 0 && map->grfid == 0) {
/* winning slot, mark it as been used */
map->entity_id = grf_local_id;
map->grfid = grfid;
map->substitute_id = substitute_id;
return id;
}
}
}
return invalid_ID;
}
/** Method to install the new indistry data in its proper slot
* The slot assigment is internal of this method, since it requires
* checking what is available
* @param inds Industryspec that comes from the grf decoding process
*/
void IndustryOverrideManager::SetEntitySpec(IndustrySpec *inds)
{
/* First step : We need to find if this industry is already specified in the savegame data */
IndustryType ind_id = this->GetID(inds->grf_prop.local_id, inds->grf_prop.grffile->grfid);
if (ind_id == invalid_ID) {
/* Not found.
* Or it has already been overriden, so you've lost your place old boy.
* Or it is a simple substitute.
* We need to find a free available slot */
ind_id = this->AddEntityID(inds->grf_prop.local_id, inds->grf_prop.grffile->grfid, inds->grf_prop.subst_id);
inds->grf_prop.override = invalid_ID; // make sure it will not be detected as overriden
}
if (ind_id == invalid_ID) {
grfmsg(1, "Industry.SetEntitySpec: Too many industries allocated. Ignoring.");
return;
}
/* Now that we know we can use the given id, copy the spech to its final destination*/
memcpy(&_industry_specs[ind_id], inds, sizeof(*inds));
/* and mark it as usable*/
_industry_specs[ind_id].enabled = true;
}
void IndustryTileOverrideManager::SetEntitySpec(const IndustryTileSpec *its)
{
IndustryGfx indt_id = this->AddEntityID(its->grf_prop.local_id, its->grf_prop.grffile->grfid, its->grf_prop.subst_id);
if (indt_id == invalid_ID) {
grfmsg(1, "IndustryTile.SetEntitySpec: Too many industry tiles allocated. Ignoring.");
return;
}
memcpy(&_industry_tile_specs[indt_id], its, sizeof(*its));
/* Now add the overrides. */
for (int i = 0; i < max_offset; i++) {
IndustryTileSpec *overridden_its = &_industry_tile_specs[i];
if (entity_overrides[i] != its->grf_prop.local_id || grfid_overrides[i] != its->grf_prop.grffile->grfid) continue;
overridden_its->grf_prop.override = indt_id;
overridden_its->enabled = false;
entity_overrides[i] = invalid_ID;
grfid_overrides[i] = 0;
}
}
/** Function used by houses (and soon industries) to get information
* on type of "terrain" the tile it is queries sits on.
* @param tile TileIndex of the tile been queried
* @return value corresponding to the grf expected format:
* Terrain type: 0 normal, 1 desert, 2 rainforest, 4 on or above snowline */
uint32 GetTerrainType(TileIndex tile)
{
switch (_settings_game.game_creation.landscape) {
case LT_TROPIC: return GetTropicZone(tile);
case LT_ARCTIC: return GetTileZ(tile) > GetSnowLine() ? 4 : 0;
default: return 0;
}
}
TileIndex GetNearbyTile(byte parameter, TileIndex tile)
{
int8 x = GB(parameter, 0, 4);
int8 y = GB(parameter, 4, 4);
if (x >= 8) x -= 16;
if (y >= 8) y -= 16;
/* Swap width and height depending on axis for railway stations */
if (IsRailwayStationTile(tile) && GetRailStationAxis(tile) == AXIS_Y) Swap(x, y);
/* Make sure we never roam outside of the map, better wrap in that case */
return TILE_MASK(tile + TileDiffXY(x, y));
}
/**
* Common part of station var 0x67 , house var 0x62, indtile var 0x60, industry var 0x62.
*
* @param tile the tile of interest.
* @return 0czzbbss: c = TileType; zz = TileZ; bb: 7-3 zero, 4-2 TerrainType, 1 water/shore, 0 zero; ss = TileSlope
*/
uint32 GetNearbyTileInformation(TileIndex tile)
{
TileType tile_type = GetTileType(tile);
/* Fake tile type for trees on shore */
if (IsTileType(tile, MP_TREES) && GetTreeGround(tile) == TREE_GROUND_SHORE) tile_type = MP_WATER;
uint z;
Slope tileh = GetTileSlope(tile, &z);
byte terrain_type = GetTerrainType(tile) << 2 | (tile_type == MP_WATER ? 1 : 0) << 1;
return tile_type << 24 | z << 16 | terrain_type << 8 | tileh;
}
| 10,620
|
C++
|
.cpp
| 267
| 37.546816
| 119
| 0.717294
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,003
|
depot_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/depot_gui.cpp
|
/* $Id$ */
/** @file depot_gui.cpp The GUI for depots. */
#include "train.h"
#include "ship.h"
#include "aircraft.h"
#include "gui.h"
#include "textbuf_gui.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "command_func.h"
#include "depot_base.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "spritecache.h"
#include "strings_func.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "company_func.h"
#include "tilehighlight_func.h"
#include "window_gui.h"
#include "vehiclelist.h"
#include "table/strings.h"
#include "table/sprites.h"
/*
* Since all depot window sizes aren't the same, we need to modify sizes a little.
* It's done with the following arrays of widget indexes. Each of them tells if a widget side should be moved and in what direction.
* How long they should be moved and for what window types are controlled in ShowDepotWindow()
*/
/* Names of the widgets. Keep them in the same order as in the widget array */
enum DepotWindowWidgets {
DEPOT_WIDGET_CLOSEBOX = 0,
DEPOT_WIDGET_CAPTION,
DEPOT_WIDGET_STICKY,
DEPOT_WIDGET_SELL,
DEPOT_WIDGET_SELL_CHAIN,
DEPOT_WIDGET_SELL_ALL,
DEPOT_WIDGET_AUTOREPLACE,
DEPOT_WIDGET_MATRIX,
DEPOT_WIDGET_V_SCROLL, ///< Vertical scrollbar
DEPOT_WIDGET_H_SCROLL, ///< Horizontal scrollbar
DEPOT_WIDGET_BUILD,
DEPOT_WIDGET_CLONE,
DEPOT_WIDGET_LOCATION,
DEPOT_WIDGET_VEHICLE_LIST,
DEPOT_WIDGET_STOP_ALL,
DEPOT_WIDGET_START_ALL,
DEPOT_WIDGET_RESIZE,
};
/* Widget array for all depot windows.
* If a widget is needed in some windows only (like train specific), add it for all windows
* and use HideWindowWidget in ShowDepotWindow() to remove it in the windows where it should not be
* Keep the widget numbers in sync with the enum or really bad stuff will happen!!! */
/* When adding widgets, place them as you would place them for the ship depot and define how you want it to move in widget_moves[]
* If you want a widget for one window only, set it to be hidden in ShowDepotWindow() for the windows where you don't want it
* NOTE: the train only widgets are moved/resized in ShowDepotWindow() so they follow certain other widgets if they are moved to ensure that they stick together.
* Changing the size of those here will not have an effect at all. It should be done in ShowDepotWindow()
*/
/*
* Some of the widgets are placed outside the window (negative coordinates).
* The reason is that they are placed relatively to the matrix and the matrix is just one pixel (in 0, 14).
* The matrix and the rest of the window will be resized when the size of the boxes is set and then all the widgets will be inside the window.
*/
static const Widget _depot_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // DEPOT_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 23, 0, 13, 0x0, STR_018C_WINDOW_TITLE_DRAG_THIS}, // DEPOT_WIDGET_CAPTION
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 24, 35, 0, 13, 0x0, STR_STICKY_BUTTON}, // DEPOT_WIDGET_STICKY
/* Widgets are set up run-time */
{ WWT_IMGBTN, RESIZE_LRB, COLOUR_GREY, 1, 23, 14, -32, 0x0, STR_NULL}, // DEPOT_WIDGET_SELL
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_GREY, 1, 23, -55, -32, SPR_SELL_CHAIN_TRAIN,STR_DRAG_WHOLE_TRAIN_TO_SELL_TIP}, // DEPOT_WIDGET_SELL_CHAIN, trains only
{ WWT_PUSHIMGBTN, RESIZE_LRTB, COLOUR_GREY, 1, 23, -31, -9, 0x0, STR_NULL}, // DEPOT_WIDGET_SELL_ALL
{ WWT_PUSHIMGBTN, RESIZE_LRTB, COLOUR_GREY, 1, 23, -8, 14, 0x0, STR_NULL}, // DEPOT_WIDGET_AUTOREPLACE
{ WWT_MATRIX, RESIZE_RB, COLOUR_GREY, 0, 0, 14, 14, 0x0, STR_NULL}, // DEPOT_WIDGET_MATRIX
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 24, 35, 14, 14, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // DEPOT_WIDGET_V_SCROLL
{ WWT_HSCROLLBAR, RESIZE_RTB, COLOUR_GREY, 0, 0, 3, 14, 0x0, STR_HSCROLL_BAR_SCROLLS_LIST}, // DEPOT_WIDGET_H_SCROLL, trains only
/* The buttons in the bottom of the window. left and right is not important as they are later resized to be equal in size
* This calculation is based on right in DEPOT_WIDGET_LOCATION and it presumes left of DEPOT_WIDGET_BUILD is 0 */
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 0, 15, 26, 0x0, STR_NULL}, // DEPOT_WIDGET_BUILD
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 0, 0, 15, 26, 0x0, STR_NULL}, // DEPOT_WIDGET_CLONE
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_GREY, 0, -12, 15, 26, STR_00E4_LOCATION, STR_NULL}, // DEPOT_WIDGET_LOCATION
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_GREY, -11, 0, 15, 26, 0x0, STR_NULL}, // DEPOT_WIDGET_VEHICLE_LIST
{ WWT_PUSHIMGBTN, RESIZE_LRTB, COLOUR_GREY, 1, 11, 15, 26, SPR_FLAG_VEH_STOPPED,STR_NULL}, // DEPOT_WIDGET_STOP_ALL
{ WWT_PUSHIMGBTN, RESIZE_LRTB, COLOUR_GREY, 12, 23, 15, 26, SPR_FLAG_VEH_RUNNING,STR_NULL}, // DEPOT_WIDGET_START_ALL
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 24, 35, 15, 26, 0x0, STR_RESIZE_BUTTON}, // DEPOT_WIDGET_RESIZE
{ WIDGETS_END},
};
static const WindowDesc _train_depot_desc(
WDP_AUTO, WDP_AUTO, 36, 27, 362, 123,
WC_VEHICLE_DEPOT, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_depot_widgets
);
static const WindowDesc _road_depot_desc(
WDP_AUTO, WDP_AUTO, 36, 27, 316, 97,
WC_VEHICLE_DEPOT, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_depot_widgets
);
static const WindowDesc _ship_depot_desc(
WDP_AUTO, WDP_AUTO, 36, 27, 306, 99,
WC_VEHICLE_DEPOT, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_depot_widgets
);
static const WindowDesc _aircraft_depot_desc(
WDP_AUTO, WDP_AUTO, 36, 27, 332, 99,
WC_VEHICLE_DEPOT, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_depot_widgets
);
extern int WagonLengthToPixels(int len);
extern void DepotSortList(VehicleList *list);
/**
* This is the Callback method after the cloning attempt of a vehicle
* @param success indicates completion (or not) of the operation
* @param tile unused
* @param p1 unused
* @param p2 unused
*/
void CcCloneVehicle(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (!success) return;
const Vehicle *v = GetVehicle(_new_vehicle_id);
ShowVehicleViewWindow(v);
}
static void TrainDepotMoveVehicle(const Vehicle *wagon, VehicleID sel, const Vehicle *head)
{
const Vehicle *v = GetVehicle(sel);
if (v == wagon) return;
if (wagon == NULL) {
if (head != NULL) wagon = GetLastVehicleInChain(head);
} else {
wagon = wagon->Previous();
if (wagon == NULL) return;
}
if (wagon == v) return;
DoCommandP(v->tile, v->index + ((wagon == NULL ? INVALID_VEHICLE : wagon->index) << 16), _ctrl_pressed ? 1 : 0, CMD_MOVE_RAIL_VEHICLE | CMD_MSG(STR_8837_CAN_T_MOVE_VEHICLE));
}
/* Array to hold the block sizes
* First part is the vehicle type, while the last is 0 = x, 1 = y */
uint _block_sizes[4][2];
/* Array to hold the default resize capacities
* First part is the vehicle type, while the last is 0 = x, 1 = y */
const uint _resize_cap[][2] = {
/* VEH_TRAIN */ {6, 10 * 29},
/* VEH_ROAD */ {5, 5},
/* VEH_SHIP */ {3, 3},
/* VEH_AIRCRAFT */ {3, 4},
};
static void ResizeDefaultWindowSizeForTrains()
{
_block_sizes[VEH_TRAIN][0] = 1;
_block_sizes[VEH_TRAIN][1] = GetVehicleListHeight(VEH_TRAIN);
}
static void ResizeDefaultWindowSizeForRoadVehicles()
{
_block_sizes[VEH_ROAD][0] = 56;
_block_sizes[VEH_ROAD][1] = GetVehicleListHeight(VEH_ROAD);
}
static void ResizeDefaultWindowSize(VehicleType type)
{
uint max_width = 0;
uint max_height = 0;
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, type) {
EngineID eid = e->index;
uint x, y;
switch (type) {
default: NOT_REACHED();
case VEH_SHIP: GetShipSpriteSize( eid, x, y); break;
case VEH_AIRCRAFT: GetAircraftSpriteSize(eid, x, y); break;
}
if (x > max_width) max_width = x;
if (y > max_height) max_height = y;
}
switch (type) {
default: NOT_REACHED();
case VEH_SHIP:
_block_sizes[VEH_SHIP][0] = max(90U, max_width + 20); // we need 20 pixels from the right edge to the sprite
break;
case VEH_AIRCRAFT:
_block_sizes[VEH_AIRCRAFT][0] = max(74U, max_width);
break;
}
_block_sizes[type][1] = max(GetVehicleListHeight(type), max_height);
}
/* Set the size of the blocks in the window so we can be sure that they are big enough for the vehicle sprites in the current game
* We will only need to call this once for each game */
void InitDepotWindowBlockSizes()
{
ResizeDefaultWindowSizeForTrains();
ResizeDefaultWindowSizeForRoadVehicles();
ResizeDefaultWindowSize(VEH_SHIP);
ResizeDefaultWindowSize(VEH_AIRCRAFT);
}
static void DepotSellAllConfirmationCallback(Window *w, bool confirmed);
const Sprite *GetAircraftSprite(EngineID engine);
struct DepotWindow : Window {
VehicleID sel;
VehicleType type;
bool generate_list;
VehicleList vehicle_list;
VehicleList wagon_list;
DepotWindow(const WindowDesc *desc, TileIndex tile, VehicleType type) : Window(desc, tile)
{
this->sel = INVALID_VEHICLE;
this->generate_list = true;
this->owner = GetTileOwner(tile);
this->CreateDepotListWindow(type);
this->FindWindowPlacementAndResize(desc);
}
~DepotWindow()
{
DeleteWindowById(WC_BUILD_VEHICLE, this->window_number);
}
/** Draw a vehicle in the depot window in the box with the top left corner at x,y
* @param *w Window to draw in
* @param *v Vehicle to draw
* @param x Left side of the box to draw in
* @param y Top of the box to draw in
*/
void DrawVehicleInDepot(Window *w, const Vehicle *v, int x, int y)
{
byte diff_x = 0, diff_y = 0;
int sprite_y = y + this->resize.step_height - GetVehicleListHeight(v->type);
switch (v->type) {
case VEH_TRAIN:
DrawTrainImage(v, x + 21, sprite_y, this->sel, this->hscroll.cap + 4, this->hscroll.pos);
/* Number of wagons relative to a standard length wagon (rounded up) */
SetDParam(0, (v->u.rail.cached_total_length + 7) / 8);
DrawStringRightAligned(this->widget[DEPOT_WIDGET_MATRIX].right - 1, y + 4, STR_TINY_BLACK, TC_FROMSTRING); // Draw the counter
break;
case VEH_ROAD: DrawRoadVehImage( v, x + 24, sprite_y, this->sel, 1); break;
case VEH_SHIP: DrawShipImage( v, x + 19, sprite_y - 1, this->sel); break;
case VEH_AIRCRAFT: {
const Sprite *spr = GetSprite(v->GetImage(DIR_W), ST_NORMAL);
DrawAircraftImage(v, x + 12,
y + max(spr->height + spr->y_offs - 14, 0), // tall sprites needs an y offset
this->sel);
} break;
default: NOT_REACHED();
}
if (this->resize.step_height == 14) {
/* VEH_TRAIN and VEH_ROAD, which are low */
diff_x = 15;
} else {
/* VEH_SHIP and VEH_AIRCRAFT, which are tall */
diff_y = 12;
}
DrawSprite((v->vehstatus & VS_STOPPED) ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING, PAL_NONE, x + diff_x, y + diff_y);
SetDParam(0, v->unitnumber);
DrawString(x, y + 2, (uint16)(v->max_age - DAYS_IN_LEAP_YEAR) >= v->age ? STR_00E2 : STR_00E3, TC_FROMSTRING);
}
void DrawDepotWindow(Window *w)
{
TileIndex tile = this->window_number;
int x, y, i, maxval;
uint16 hnum;
/* Set the row and number of boxes in each row based on the number of boxes drawn in the matrix */
uint16 rows_in_display = this->widget[DEPOT_WIDGET_MATRIX].data >> 8;
uint16 boxes_in_each_row = this->widget[DEPOT_WIDGET_MATRIX].data & 0xFF;
/* setup disabled buttons */
this->SetWidgetsDisabledState(!IsTileOwner(tile, _local_company),
DEPOT_WIDGET_STOP_ALL,
DEPOT_WIDGET_START_ALL,
DEPOT_WIDGET_SELL,
DEPOT_WIDGET_SELL_CHAIN,
DEPOT_WIDGET_SELL_ALL,
DEPOT_WIDGET_BUILD,
DEPOT_WIDGET_CLONE,
DEPOT_WIDGET_AUTOREPLACE,
WIDGET_LIST_END);
/* determine amount of items for scroller */
if (this->type == VEH_TRAIN) {
hnum = 8;
for (uint num = 0; num < this->vehicle_list.Length(); num++) {
const Vehicle *v = this->vehicle_list[num];
hnum = max(hnum, v->u.rail.cached_total_length);
}
/* Always have 1 empty row, so people can change the setting of the train */
SetVScrollCount(w, this->vehicle_list.Length() + this->wagon_list.Length() + 1);
SetHScrollCount(w, WagonLengthToPixels(hnum));
} else {
SetVScrollCount(w, (this->vehicle_list.Length() + this->hscroll.cap - 1) / this->hscroll.cap);
}
/* locate the depot struct */
if (this->type == VEH_AIRCRAFT) {
SetDParam(0, GetStationIndex(tile)); // Airport name
} else {
Depot *depot = GetDepotByTile(tile);
assert(depot != NULL);
SetDParam(0, depot->town_index);
}
w->DrawWidgets();
uint16 num = this->vscroll.pos * boxes_in_each_row;
maxval = min(this->vehicle_list.Length(), num + (rows_in_display * boxes_in_each_row));
for (x = 2, y = 15; num < maxval; y += this->resize.step_height, x = 2) { // Draw the rows
byte i;
for (i = 0; i < boxes_in_each_row && num < maxval; i++, num++, x += this->resize.step_width) {
/* Draw all vehicles in the current row */
const Vehicle *v = this->vehicle_list[num];
DrawVehicleInDepot(w, v, x, y);
}
}
maxval = min(this->vehicle_list.Length() + this->wagon_list.Length(), (this->vscroll.pos * boxes_in_each_row) + (rows_in_display * boxes_in_each_row));
/* draw the train wagons, that do not have an engine in front */
for (; num < maxval; num++, y += 14) {
const Vehicle *v = this->wagon_list[num - this->vehicle_list.Length()];
const Vehicle *u;
DrawTrainImage(v, x + 50, y, this->sel, this->hscroll.cap - 29, 0);
DrawString(x, y + 2, STR_8816, TC_FROMSTRING);
/* Draw the train counter */
i = 0;
u = v;
do i++; while ((u = u->Next()) != NULL); // Determine length of train
SetDParam(0, i); // Set the counter
DrawStringRightAligned(this->widget[DEPOT_WIDGET_MATRIX].right - 1, y + 4, STR_TINY_BLACK, TC_FROMSTRING); // Draw the counter
}
}
struct GetDepotVehiclePtData {
const Vehicle *head;
const Vehicle *wagon;
};
enum DepotGUIAction {
MODE_ERROR,
MODE_DRAG_VEHICLE,
MODE_SHOW_VEHICLE,
MODE_START_STOP,
};
DepotGUIAction GetVehicleFromDepotWndPt(int x, int y, const Vehicle **veh, GetDepotVehiclePtData *d) const
{
uint xt, row, xm = 0, ym = 0;
int pos, skip = 0;
uint16 boxes_in_each_row = this->widget[DEPOT_WIDGET_MATRIX].data & 0xFF;
if (this->type == VEH_TRAIN) {
xt = 0;
x -= 23;
} else {
xt = x / this->resize.step_width;
xm = x % this->resize.step_width;
if (xt >= this->hscroll.cap) return MODE_ERROR;
ym = (y - 14) % this->resize.step_height;
}
row = (y - 14) / this->resize.step_height;
if (row >= this->vscroll.cap) return MODE_ERROR;
pos = ((row + this->vscroll.pos) * boxes_in_each_row) + xt;
if ((int)(this->vehicle_list.Length() + this->wagon_list.Length()) <= pos) {
if (this->type == VEH_TRAIN) {
d->head = NULL;
d->wagon = NULL;
return MODE_DRAG_VEHICLE;
} else {
return MODE_ERROR; // empty block, so no vehicle is selected
}
}
if ((int)this->vehicle_list.Length() > pos) {
*veh = this->vehicle_list[pos];
skip = this->hscroll.pos;
} else {
pos -= this->vehicle_list.Length();
*veh = this->wagon_list[pos];
/* free wagons don't have an initial loco. */
x -= _traininfo_vehicle_width;
}
switch (this->type) {
case VEH_TRAIN: {
const Vehicle *v = *veh;
d->head = d->wagon = v;
/* either pressed the flag or the number, but only when it's a loco */
if (x < 0 && IsFrontEngine(v)) return (x >= -10) ? MODE_START_STOP : MODE_SHOW_VEHICLE;
skip = (skip * 8) / _traininfo_vehicle_width;
x = (x * 8) / _traininfo_vehicle_width;
/* Skip vehicles that are scrolled off the list */
x += skip;
/* find the vehicle in this row that was clicked */
while (v != NULL && (x -= v->u.rail.cached_veh_length) >= 0) v = v->Next();
/* if an articulated part was selected, find its parent */
while (v != NULL && IsArticulatedPart(v)) v = v->Previous();
d->wagon = v;
return MODE_DRAG_VEHICLE;
}
break;
case VEH_ROAD:
if (xm >= 24) return MODE_DRAG_VEHICLE;
if (xm <= 16) return MODE_SHOW_VEHICLE;
break;
case VEH_SHIP:
if (xm >= 19) return MODE_DRAG_VEHICLE;
if (ym <= 10) return MODE_SHOW_VEHICLE;
break;
case VEH_AIRCRAFT:
if (xm >= 12) return MODE_DRAG_VEHICLE;
if (ym <= 12) return MODE_SHOW_VEHICLE;
break;
default: NOT_REACHED();
}
return MODE_START_STOP;
}
void DepotClick(int x, int y)
{
GetDepotVehiclePtData gdvp = { NULL, NULL };
const Vehicle *v = NULL;
DepotGUIAction mode = this->GetVehicleFromDepotWndPt(x, y, &v, &gdvp);
/* share / copy orders */
if (_thd.place_mode != VHM_NONE && mode != MODE_ERROR) {
_place_clicked_vehicle = (this->type == VEH_TRAIN ? gdvp.head : v);
return;
}
if (this->type == VEH_TRAIN) v = gdvp.wagon;
switch (mode) {
case MODE_ERROR: // invalid
return;
case MODE_DRAG_VEHICLE: { // start dragging of vehicle
VehicleID sel = this->sel;
if (this->type == VEH_TRAIN && sel != INVALID_VEHICLE) {
this->sel = INVALID_VEHICLE;
TrainDepotMoveVehicle(v, sel, gdvp.head);
} else if (v != NULL) {
int image = v->GetImage(DIR_W);
this->sel = v->index;
this->SetDirty();
SetObjectToPlaceWnd(image, GetVehiclePalette(v), VHM_DRAG, this);
switch (v->type) {
case VEH_TRAIN:
_cursor.short_vehicle_offset = 16 - v->u.rail.cached_veh_length * 2;
break;
case VEH_ROAD:
_cursor.short_vehicle_offset = 16 - v->u.road.cached_veh_length * 2;
break;
default:
_cursor.short_vehicle_offset = 0;
break;
}
_cursor.vehchain = _ctrl_pressed;
}
} break;
case MODE_SHOW_VEHICLE: // show info window
ShowVehicleViewWindow(v);
break;
case MODE_START_STOP: { // click start/stop flag
uint command;
switch (this->type) {
case VEH_TRAIN: command = CMD_START_STOP_VEHICLE | CMD_MSG(STR_883B_CAN_T_STOP_START_TRAIN); break;
case VEH_ROAD: command = CMD_START_STOP_VEHICLE | CMD_MSG(STR_9015_CAN_T_STOP_START_ROAD_VEHICLE); break;
case VEH_SHIP: command = CMD_START_STOP_VEHICLE | CMD_MSG(STR_9818_CAN_T_STOP_START_SHIP); break;
case VEH_AIRCRAFT: command = CMD_START_STOP_VEHICLE | CMD_MSG(STR_A016_CAN_T_STOP_START_AIRCRAFT); break;
default: NOT_REACHED(); command = 0;
}
DoCommandP(v->tile, v->index, 0, command);
} break;
default: NOT_REACHED();
}
}
/**
* Clones a vehicle
* @param *v is the original vehicle to clone
* @param *w is the window of the depot where the clone is build
*/
void HandleCloneVehClick(const Vehicle *v, const Window *w)
{
uint error_str;
if (v == NULL) return;
if (!v->IsPrimaryVehicle()) {
v = v->First();
/* Do nothing when clicking on a train in depot with no loc attached */
if (v->type == VEH_TRAIN && !IsFrontEngine(v)) return;
}
switch (v->type) {
case VEH_TRAIN: error_str = CMD_MSG(STR_882B_CAN_T_BUILD_RAILROAD_VEHICLE); break;
case VEH_ROAD: error_str = CMD_MSG(STR_9009_CAN_T_BUILD_ROAD_VEHICLE); break;
case VEH_SHIP: error_str = CMD_MSG(STR_980D_CAN_T_BUILD_SHIP); break;
case VEH_AIRCRAFT: error_str = CMD_MSG(STR_A008_CAN_T_BUILD_AIRCRAFT); break;
default: return;
}
DoCommandP(this->window_number, v->index, _ctrl_pressed ? 1 : 0, CMD_CLONE_VEHICLE | error_str, CcCloneVehicle);
ResetObjectToPlace();
}
void ResizeDepotButtons(Window *w)
{
ResizeButtons(w, DEPOT_WIDGET_BUILD, DEPOT_WIDGET_LOCATION);
if (this->type == VEH_TRAIN) {
/* Divide the size of DEPOT_WIDGET_SELL into two equally big buttons so DEPOT_WIDGET_SELL and DEPOT_WIDGET_SELL_CHAIN will get the same size.
* This way it will stay the same even if DEPOT_WIDGET_SELL_CHAIN is resized for some reason */
this->widget[DEPOT_WIDGET_SELL_CHAIN].top = ((this->widget[DEPOT_WIDGET_SELL_CHAIN].bottom - this->widget[DEPOT_WIDGET_SELL].top) / 2) + this->widget[DEPOT_WIDGET_SELL].top;
this->widget[DEPOT_WIDGET_SELL].bottom = this->widget[DEPOT_WIDGET_SELL_CHAIN].top - 1;
}
}
/* Function to set up vehicle specific sprites and strings
* Only use this if it's the same widget, that's used for more than one vehicle type and it needs different text/sprites
* Vehicle specific text/sprites, that's in a widget, that's only shown for one vehicle type (like sell whole train) is set in the widget array
*/
void SetupStringsForDepotWindow(VehicleType type)
{
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN:
this->widget[DEPOT_WIDGET_CAPTION].data = STR_8800_TRAIN_DEPOT;
this->widget[DEPOT_WIDGET_STOP_ALL].tooltips = STR_MASS_STOP_DEPOT_TRAIN_TIP;
this->widget[DEPOT_WIDGET_START_ALL].tooltips= STR_MASS_START_DEPOT_TRAIN_TIP;
this->widget[DEPOT_WIDGET_SELL].tooltips = STR_8841_DRAG_TRAIN_VEHICLE_TO_HERE;
this->widget[DEPOT_WIDGET_SELL_ALL].tooltips = STR_DEPOT_SELL_ALL_BUTTON_TRAIN_TIP;
this->widget[DEPOT_WIDGET_BUILD].data = STR_8815_NEW_VEHICLES;
this->widget[DEPOT_WIDGET_BUILD].tooltips = STR_8840_BUILD_NEW_TRAIN_VEHICLE;
this->widget[DEPOT_WIDGET_CLONE].data = STR_CLONE_TRAIN;
this->widget[DEPOT_WIDGET_CLONE].tooltips = STR_CLONE_TRAIN_DEPOT_INFO;
this->widget[DEPOT_WIDGET_LOCATION].tooltips = STR_8842_CENTER_MAIN_VIEW_ON_TRAIN;
this->widget[DEPOT_WIDGET_VEHICLE_LIST].data = STR_TRAIN;
this->widget[DEPOT_WIDGET_VEHICLE_LIST].tooltips = STR_DEPOT_VEHICLE_ORDER_LIST_TRAIN_TIP;
this->widget[DEPOT_WIDGET_AUTOREPLACE].tooltips = STR_DEPOT_AUTOREPLACE_TRAIN_TIP;
/* Sprites */
this->widget[DEPOT_WIDGET_SELL].data = SPR_SELL_TRAIN;
this->widget[DEPOT_WIDGET_SELL_ALL].data = SPR_SELL_ALL_TRAIN;
this->widget[DEPOT_WIDGET_AUTOREPLACE].data = SPR_REPLACE_TRAIN;
break;
case VEH_ROAD:
this->widget[DEPOT_WIDGET_CAPTION].data = STR_9003_ROAD_VEHICLE_DEPOT;
this->widget[DEPOT_WIDGET_STOP_ALL].tooltips = STR_MASS_STOP_DEPOT_ROADVEH_TIP;
this->widget[DEPOT_WIDGET_START_ALL].tooltips= STR_MASS_START_DEPOT_ROADVEH_TIP;
this->widget[DEPOT_WIDGET_SELL].tooltips = STR_9024_DRAG_ROAD_VEHICLE_TO_HERE;
this->widget[DEPOT_WIDGET_SELL_ALL].tooltips = STR_DEPOT_SELL_ALL_BUTTON_ROADVEH_TIP;
this->widget[DEPOT_WIDGET_BUILD].data = STR_9004_NEW_VEHICLES;
this->widget[DEPOT_WIDGET_BUILD].tooltips = STR_9023_BUILD_NEW_ROAD_VEHICLE;
this->widget[DEPOT_WIDGET_CLONE].data = STR_CLONE_ROAD_VEHICLE;
this->widget[DEPOT_WIDGET_CLONE].tooltips = STR_CLONE_ROAD_VEHICLE_DEPOT_INFO;
this->widget[DEPOT_WIDGET_LOCATION].tooltips = STR_9025_CENTER_MAIN_VIEW_ON_ROAD;
this->widget[DEPOT_WIDGET_VEHICLE_LIST].data = STR_LORRY;
this->widget[DEPOT_WIDGET_VEHICLE_LIST].tooltips = STR_DEPOT_VEHICLE_ORDER_LIST_ROADVEH_TIP;
this->widget[DEPOT_WIDGET_AUTOREPLACE].tooltips = STR_DEPOT_AUTOREPLACE_ROADVEH_TIP;
/* Sprites */
this->widget[DEPOT_WIDGET_SELL].data = SPR_SELL_ROADVEH;
this->widget[DEPOT_WIDGET_SELL_ALL].data = SPR_SELL_ALL_ROADVEH;
this->widget[DEPOT_WIDGET_AUTOREPLACE].data = SPR_REPLACE_ROADVEH;
break;
case VEH_SHIP:
this->widget[DEPOT_WIDGET_CAPTION].data = STR_9803_SHIP_DEPOT;
this->widget[DEPOT_WIDGET_STOP_ALL].tooltips = STR_MASS_STOP_DEPOT_SHIP_TIP;
this->widget[DEPOT_WIDGET_START_ALL].tooltips= STR_MASS_START_DEPOT_SHIP_TIP;
this->widget[DEPOT_WIDGET_SELL].tooltips = STR_9821_DRAG_SHIP_TO_HERE_TO_SELL;
this->widget[DEPOT_WIDGET_SELL_ALL].tooltips = STR_DEPOT_SELL_ALL_BUTTON_SHIP_TIP;
this->widget[DEPOT_WIDGET_BUILD].data = STR_9804_NEW_SHIPS;
this->widget[DEPOT_WIDGET_BUILD].tooltips = STR_9820_BUILD_NEW_SHIP;
this->widget[DEPOT_WIDGET_CLONE].data = STR_CLONE_SHIP;
this->widget[DEPOT_WIDGET_CLONE].tooltips = STR_CLONE_SHIP_DEPOT_INFO;
this->widget[DEPOT_WIDGET_LOCATION].tooltips = STR_9822_CENTER_MAIN_VIEW_ON_SHIP;
this->widget[DEPOT_WIDGET_VEHICLE_LIST].data = STR_SHIP;
this->widget[DEPOT_WIDGET_VEHICLE_LIST].tooltips = STR_DEPOT_VEHICLE_ORDER_LIST_SHIP_TIP;
this->widget[DEPOT_WIDGET_AUTOREPLACE].tooltips = STR_DEPOT_AUTOREPLACE_SHIP_TIP;
/* Sprites */
this->widget[DEPOT_WIDGET_SELL].data = SPR_SELL_SHIP;
this->widget[DEPOT_WIDGET_SELL_ALL].data = SPR_SELL_ALL_SHIP;
this->widget[DEPOT_WIDGET_AUTOREPLACE].data = SPR_REPLACE_SHIP;
break;
case VEH_AIRCRAFT:
this->widget[DEPOT_WIDGET_CAPTION].data = STR_A002_AIRCRAFT_HANGAR;
this->widget[DEPOT_WIDGET_STOP_ALL].tooltips = STR_MASS_STOP_HANGAR_TIP;
this->widget[DEPOT_WIDGET_START_ALL].tooltips= STR_MASS_START_HANGAR_TIP;
this->widget[DEPOT_WIDGET_SELL].tooltips = STR_A023_DRAG_AIRCRAFT_TO_HERE_TO;
this->widget[DEPOT_WIDGET_SELL_ALL].tooltips = STR_DEPOT_SELL_ALL_BUTTON_AIRCRAFT_TIP;
this->widget[DEPOT_WIDGET_BUILD].data = STR_A003_NEW_AIRCRAFT;
this->widget[DEPOT_WIDGET_BUILD].tooltips = STR_A022_BUILD_NEW_AIRCRAFT;
this->widget[DEPOT_WIDGET_CLONE].data = STR_CLONE_AIRCRAFT;
this->widget[DEPOT_WIDGET_CLONE].tooltips = STR_CLONE_AIRCRAFT_INFO_HANGAR_WINDOW;
this->widget[DEPOT_WIDGET_LOCATION].tooltips = STR_A024_CENTER_MAIN_VIEW_ON_HANGAR;
this->widget[DEPOT_WIDGET_VEHICLE_LIST].data = STR_PLANE;
this->widget[DEPOT_WIDGET_VEHICLE_LIST].tooltips = STR_DEPOT_VEHICLE_ORDER_LIST_AIRCRAFT_TIP;
this->widget[DEPOT_WIDGET_AUTOREPLACE].tooltips = STR_DEPOT_AUTOREPLACE_AIRCRAFT_TIP;
/* Sprites */
this->widget[DEPOT_WIDGET_SELL].data = SPR_SELL_AIRCRAFT;
this->widget[DEPOT_WIDGET_SELL_ALL].data = SPR_SELL_ALL_AIRCRAFT;
this->widget[DEPOT_WIDGET_AUTOREPLACE].data = SPR_REPLACE_AIRCRAFT;
break;
}
}
void CreateDepotListWindow(VehicleType type)
{
this->type = type;
_backup_orders_tile = 0;
assert(IsCompanyBuildableVehicleType(type)); // ensure that we make the call with a valid type
/* Resize the window according to the vehicle type */
/* Set the number of blocks in each direction */
this->vscroll.cap = _resize_cap[type][0];
this->hscroll.cap = _resize_cap[type][1];
/* Set the block size */
this->resize.step_width = _block_sizes[type][0];
this->resize.step_height = _block_sizes[type][1];
/* Enlarge the window to fit with the selected number of blocks of the selected size */
ResizeWindow(this,
_block_sizes[type][0] * this->hscroll.cap,
_block_sizes[type][1] * this->vscroll.cap);
if (type == VEH_TRAIN) {
/* Make space for the horizontal scrollbar vertically, and the unit
* number, flag, and length counter horizontally. */
ResizeWindow(this, 36, 12);
/* substract the newly added space from the matrix since it was meant for the scrollbar */
this->widget[DEPOT_WIDGET_MATRIX].bottom -= 12;
}
/* Set the minimum window size to the current window size */
this->resize.width = this->width;
this->resize.height = this->height;
this->SetupStringsForDepotWindow(type);
this->widget[DEPOT_WIDGET_MATRIX].data =
(this->vscroll.cap * 0x100) // number of rows to draw on the background
+ (type == VEH_TRAIN ? 1 : this->hscroll.cap); // number of boxes in each row. Trains always have just one
this->SetWidgetsHiddenState(type != VEH_TRAIN,
DEPOT_WIDGET_H_SCROLL,
DEPOT_WIDGET_SELL_CHAIN,
WIDGET_LIST_END);
ResizeDepotButtons(this);
}
virtual void OnInvalidateData(int data)
{
this->generate_list = true;
}
virtual void OnPaint()
{
if (this->generate_list) {
/* Generate the vehicle list
* It's ok to use the wagon pointers for non-trains as they will be ignored */
BuildDepotVehicleList(this->type, this->window_number, &this->vehicle_list, &this->wagon_list);
this->generate_list = false;
DepotSortList(&this->vehicle_list);
}
DrawDepotWindow(this);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case DEPOT_WIDGET_MATRIX: // List
this->DepotClick(pt.x, pt.y);
break;
case DEPOT_WIDGET_BUILD: // Build vehicle
ResetObjectToPlace();
ShowBuildVehicleWindow(this->window_number, this->type);
break;
case DEPOT_WIDGET_CLONE: // Clone button
this->InvalidateWidget(DEPOT_WIDGET_CLONE);
this->ToggleWidgetLoweredState(DEPOT_WIDGET_CLONE);
if (this->IsWidgetLowered(DEPOT_WIDGET_CLONE)) {
static const CursorID clone_icons[] = {
SPR_CURSOR_CLONE_TRAIN, SPR_CURSOR_CLONE_ROADVEH,
SPR_CURSOR_CLONE_SHIP, SPR_CURSOR_CLONE_AIRPLANE
};
_place_clicked_vehicle = NULL;
SetObjectToPlaceWnd(clone_icons[this->type], PAL_NONE, VHM_RECT, this);
} else {
ResetObjectToPlace();
}
break;
case DEPOT_WIDGET_LOCATION:
if (_ctrl_pressed) {
ShowExtraViewPortWindow(this->window_number);
} else {
ScrollMainWindowToTile(this->window_number);
}
break;
case DEPOT_WIDGET_STOP_ALL:
case DEPOT_WIDGET_START_ALL:
DoCommandP(this->window_number, 0, this->type | (widget == DEPOT_WIDGET_START_ALL ? (1 << 5) : 0), CMD_MASS_START_STOP);
break;
case DEPOT_WIDGET_SELL_ALL:
/* Only open the confimation window if there are anything to sell */
if (this->vehicle_list.Length() != 0 || this->wagon_list.Length() != 0) {
static const StringID confirm_captions[] = {
STR_8800_TRAIN_DEPOT,
STR_9003_ROAD_VEHICLE_DEPOT,
STR_9803_SHIP_DEPOT,
STR_A002_AIRCRAFT_HANGAR
};
TileIndex tile = this->window_number;
byte vehtype = this->type;
SetDParam(0, (vehtype == VEH_AIRCRAFT) ? GetStationIndex(tile) : GetDepotByTile(tile)->town_index);
ShowQuery(
confirm_captions[vehtype],
STR_DEPOT_SELL_CONFIRMATION_TEXT,
this,
DepotSellAllConfirmationCallback
);
}
break;
case DEPOT_WIDGET_VEHICLE_LIST:
ShowVehicleListWindow(GetTileOwner(this->window_number), this->type, (TileIndex)this->window_number);
break;
case DEPOT_WIDGET_AUTOREPLACE:
DoCommandP(this->window_number, this->type, 0, CMD_DEPOT_MASS_AUTOREPLACE);
break;
}
}
virtual void OnRightClick(Point pt, int widget)
{
if (widget != DEPOT_WIDGET_MATRIX) return;
GetDepotVehiclePtData gdvp = { NULL, NULL };
const Vehicle *v = NULL;
DepotGUIAction mode = this->GetVehicleFromDepotWndPt(pt.x, pt.y, &v, &gdvp);
if (this->type == VEH_TRAIN) v = gdvp.wagon;
if (v != NULL && mode == MODE_DRAG_VEHICLE) {
AcceptedCargo capacity, loaded;
memset(capacity, 0, sizeof(capacity));
memset(loaded, 0, sizeof(loaded));
/* Display info for single (articulated) vehicle, or for whole chain starting with selected vehicle */
bool whole_chain = (this->type == VEH_TRAIN && _ctrl_pressed);
/* loop through vehicle chain and collect cargos */
uint num = 0;
for (const Vehicle *w = v; w != NULL; w = w->Next()) {
if (w->cargo_cap > 0 && w->cargo_type < NUM_CARGO) {
capacity[w->cargo_type] += w->cargo_cap;
loaded [w->cargo_type] += w->cargo.Count();
}
if (w->type == VEH_TRAIN && !EngineHasArticPart(w)) {
num++;
if (!whole_chain) break;
}
}
/* Build tooltipstring */
static char details[1024];
details[0] = '\0';
char *pos = details;
for (CargoID cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
if (capacity[cargo_type] == 0) continue;
SetDParam(0, cargo_type); // {CARGO} #1
SetDParam(1, loaded[cargo_type]); // {CARGO} #2
SetDParam(2, cargo_type); // {SHORTCARGO} #1
SetDParam(3, capacity[cargo_type]); // {SHORTCARGO} #2
pos = GetString(pos, STR_DEPOT_VEHICLE_TOOLTIP_CARGO, lastof(details));
}
/* Show tooltip window */
uint64 args[2];
args[0] = (whole_chain ? num : v->engine_type);
args[1] = (uint64)(size_t)details;
GuiShowTooltips(whole_chain ? STR_DEPOT_VEHICLE_TOOLTIP_CHAIN : STR_DEPOT_VEHICLE_TOOLTIP, 2, args);
} else {
/* Show tooltip help */
StringID tooltip = INVALID_STRING_ID;
switch (this->type) {
case VEH_TRAIN: tooltip = STR_883F_TRAINS_CLICK_ON_TRAIN_FOR; break;
case VEH_ROAD: tooltip = STR_9022_VEHICLES_CLICK_ON_VEHICLE; break;
case VEH_SHIP: tooltip = STR_981F_SHIPS_CLICK_ON_SHIP_FOR; break;
case VEH_AIRCRAFT: tooltip = STR_A021_AIRCRAFT_CLICK_ON_AIRCRAFT;break;
default: NOT_REACHED();
}
GuiShowTooltips(tooltip);
}
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
const Vehicle *v = CheckMouseOverVehicle();
if (v != NULL) HandleCloneVehClick(v, this);
}
virtual void OnPlaceObjectAbort()
{
/* abort clone */
this->RaiseWidget(DEPOT_WIDGET_CLONE);
this->InvalidateWidget(DEPOT_WIDGET_CLONE);
/* abort drag & drop */
this->sel = INVALID_VEHICLE;
this->InvalidateWidget(DEPOT_WIDGET_MATRIX);
};
/* check if a vehicle in a depot was clicked.. */
virtual void OnMouseLoop()
{
const Vehicle *v = _place_clicked_vehicle;
/* since OTTD checks all open depot windows, we will make sure that it triggers the one with a clicked clone button */
if (v != NULL && this->IsWidgetLowered(DEPOT_WIDGET_CLONE)) {
_place_clicked_vehicle = NULL;
HandleCloneVehClick(v, this);
}
}
virtual void OnDragDrop(Point pt, int widget)
{
switch (widget) {
case DEPOT_WIDGET_MATRIX: {
const Vehicle *v = NULL;
VehicleID sel = this->sel;
this->sel = INVALID_VEHICLE;
this->SetDirty();
if (this->type == VEH_TRAIN) {
GetDepotVehiclePtData gdvp = { NULL, NULL };
if (this->GetVehicleFromDepotWndPt(pt.x, pt.y, &v, &gdvp) == MODE_DRAG_VEHICLE &&
sel != INVALID_VEHICLE) {
if (gdvp.wagon != NULL && gdvp.wagon->index == sel && _ctrl_pressed) {
DoCommandP(GetVehicle(sel)->tile, GetVehicle(sel)->index, true, CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_9033_CAN_T_MAKE_VEHICLE_TURN));
} else if (gdvp.wagon == NULL || gdvp.wagon->index != sel) {
TrainDepotMoveVehicle(gdvp.wagon, sel, gdvp.head);
} else if (gdvp.head != NULL && IsFrontEngine(gdvp.head)) {
ShowVehicleViewWindow(gdvp.head);
}
}
} else if (this->GetVehicleFromDepotWndPt(pt.x, pt.y, &v, NULL) == MODE_DRAG_VEHICLE &&
v != NULL &&
sel == v->index) {
ShowVehicleViewWindow(v);
}
} break;
case DEPOT_WIDGET_SELL: case DEPOT_WIDGET_SELL_CHAIN:
if (!this->IsWidgetDisabled(DEPOT_WIDGET_SELL) &&
this->sel != INVALID_VEHICLE) {
uint command;
if (this->IsWidgetDisabled(widget)) return;
if (this->sel == INVALID_VEHICLE) return;
this->HandleButtonClick(widget);
const Vehicle *v = GetVehicle(this->sel);
this->sel = INVALID_VEHICLE;
this->SetDirty();
int sell_cmd = (v->type == VEH_TRAIN && (widget == DEPOT_WIDGET_SELL_CHAIN || _ctrl_pressed)) ? 1 : 0;
bool is_engine = (!(v->type == VEH_TRAIN && !IsFrontEngine(v)));
if (is_engine) {
_backup_orders_tile = v->tile;
BackupVehicleOrders(v);
}
switch (v->type) {
case VEH_TRAIN: command = CMD_SELL_RAIL_WAGON | CMD_MSG(STR_8839_CAN_T_SELL_RAILROAD_VEHICLE); break;
case VEH_ROAD: command = CMD_SELL_ROAD_VEH | CMD_MSG(STR_9014_CAN_T_SELL_ROAD_VEHICLE); break;
case VEH_SHIP: command = CMD_SELL_SHIP | CMD_MSG(STR_980C_CAN_T_SELL_SHIP); break;
case VEH_AIRCRAFT: command = CMD_SELL_AIRCRAFT | CMD_MSG(STR_A01C_CAN_T_SELL_AIRCRAFT); break;
default: NOT_REACHED(); command = 0;
}
if (!DoCommandP(v->tile, v->index, sell_cmd, command) && is_engine) _backup_orders_tile = 0;
}
break;
default:
this->sel = INVALID_VEHICLE;
this->SetDirty();
}
_cursor.vehchain = false;
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->hscroll.cap += delta.x / (int)this->resize.step_width;
this->widget[DEPOT_WIDGET_MATRIX].data = (this->vscroll.cap << 8) + (this->type == VEH_TRAIN ? 1 : this->hscroll.cap);
ResizeDepotButtons(this);
}
virtual EventState OnCTRLStateChange()
{
if (this->sel != INVALID_VEHICLE) {
_cursor.vehchain = _ctrl_pressed;
this->InvalidateWidget(DEPOT_WIDGET_MATRIX);
return ES_HANDLED;
}
return ES_NOT_HANDLED;
}
};
static void DepotSellAllConfirmationCallback(Window *win, bool confirmed)
{
if (confirmed) {
DepotWindow *w = (DepotWindow*)win;
TileIndex tile = w->window_number;
byte vehtype = w->type;
DoCommandP(tile, vehtype, 0, CMD_DEPOT_SELL_ALL_VEHICLES);
}
}
/** Opens a depot window
* @param tile The tile where the depot/hangar is located
* @param type The type of vehicles in the depot
*/
void ShowDepotWindow(TileIndex tile, VehicleType type)
{
if (BringWindowToFrontById(WC_VEHICLE_DEPOT, tile) != NULL) return;
const WindowDesc *desc;
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN: desc = &_train_depot_desc; break;
case VEH_ROAD: desc = &_road_depot_desc; break;
case VEH_SHIP: desc = &_ship_depot_desc; break;
case VEH_AIRCRAFT: desc = &_aircraft_depot_desc; break;
}
new DepotWindow(desc, tile, type);
}
/** Removes the highlight of a vehicle in a depot window
* @param *v Vehicle to remove all highlights from
*/
void DeleteDepotHighlightOfVehicle(const Vehicle *v)
{
DepotWindow *w;
/* If we haven't got any vehicles on the mouse pointer, we haven't got any highlighted in any depots either
* If that is the case, we can skip looping though the windows and save time
*/
if (_special_mouse_mode != WSM_DRAGDROP) return;
w = dynamic_cast<DepotWindow*>(FindWindowById(WC_VEHICLE_DEPOT, v->tile));
if (w != NULL) {
if (w->sel == v->index) ResetObjectToPlace();
}
}
| 38,622
|
C++
|
.cpp
| 881
| 40.090806
| 179
| 0.670945
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,004
|
strings.cpp
|
EnergeticBark_OpenTTD-3DS/src/strings.cpp
|
/* $Id$ */
/** @file strings.cpp Handling of translated strings. */
#include "stdafx.h"
#include "openttd.h"
#include "currency.h"
#include "spritecache.h"
#include "namegen_func.h"
#include "station_base.h"
#include "town.h"
#include "screenshot.h"
#include "waypoint.h"
#include "industry.h"
#include "newgrf_text.h"
#include "music.h"
#include "fileio_func.h"
#include "group.h"
#include "newgrf_townname.h"
#include "signs_base.h"
#include "cargotype.h"
#include "fontcache.h"
#include "gui.h"
#include "strings_func.h"
#include "rev.h"
#include "core/endian_func.hpp"
#include "date_func.h"
#include "vehicle_base.h"
#include "company_func.h"
#include "video/video_driver.hpp"
#include "engine_base.h"
#include "strgen/strgen.h"
#include "gfx_func.h"
#include "table/strings.h"
#include "table/control_codes.h"
DynamicLanguages _dynlang;
uint64 _decode_parameters[20];
static char *StationGetSpecialString(char *buff, int x, const char *last);
static char *GetSpecialTownNameString(char *buff, int ind, uint32 seed, const char *last);
static char *GetSpecialNameString(char *buff, int ind, const int64 *argv, const char *last);
static char *FormatString(char *buff, const char *str, const int64 *argv, uint casei, const char *last);
struct LanguagePack : public LanguagePackHeader {
char data[VARARRAY_SIZE]; // list of strings
};
static char **_langpack_offs;
static LanguagePack *_langpack;
static uint _langtab_num[32]; // Offset into langpack offs
static uint _langtab_start[32]; // Offset into langpack offs
/** Read an int64 from the argv array. */
static inline int64 GetInt64(const int64 **argv)
{
assert(argv);
return *(*argv)++;
}
/** Read an int32 from the argv array. */
static inline int32 GetInt32(const int64 **argv)
{
return (int32)GetInt64(argv);
}
/** Read an array from the argv array. */
static inline const int64 *GetArgvPtr(const int64 **argv, int n)
{
const int64 *result;
assert(*argv);
result = *argv;
(*argv) += n;
return result;
}
const char *GetStringPtr(StringID string)
{
switch (GB(string, 11, 5)) {
case 28: return GetGRFStringPtr(GB(string, 0, 11));
case 29: return GetGRFStringPtr(GB(string, 0, 11) + 0x0800);
case 30: return GetGRFStringPtr(GB(string, 0, 11) + 0x1000);
default: return _langpack_offs[_langtab_start[string >> 11] + (string & 0x7FF)];
}
}
/** The highest 8 bits of string contain the "case index".
* These 8 bits will only be set when FormatString wants to print
* the string in a different case. No one else except FormatString
* should set those bits, therefore string CANNOT be StringID, but uint32.
* @param buffr
* @param string
* @param argv
* @param last
* @return a formatted string of char
*/
static char *GetStringWithArgs(char *buffr, uint string, const int64 *argv, const char *last)
{
if (GB(string, 0, 16) == 0) return GetStringWithArgs(buffr, STR_UNDEFINED, argv, last);
uint index = GB(string, 0, 11);
uint tab = GB(string, 11, 5);
switch (tab) {
case 4:
if (index >= 0xC0)
return GetSpecialTownNameString(buffr, index - 0xC0, GetInt32(&argv), last);
break;
case 14:
if (index >= 0xE4)
return GetSpecialNameString(buffr, index - 0xE4, argv, last);
break;
case 15:
/* Old table for custom names. This is no longer used */
error("Incorrect conversion of custom name string.");
case 26:
/* Include string within newgrf text (format code 81) */
if (HasBit(index, 10)) {
StringID string = GetGRFStringID(0, 0xD000 + GB(index, 0, 10));
return GetStringWithArgs(buffr, string, argv, last);
}
break;
case 28:
return FormatString(buffr, GetGRFStringPtr(index), argv, 0, last);
case 29:
return FormatString(buffr, GetGRFStringPtr(index + 0x0800), argv, 0, last);
case 30:
return FormatString(buffr, GetGRFStringPtr(index + 0x1000), argv, 0, last);
case 31:
NOT_REACHED();
}
if (index >= _langtab_num[tab]) {
error(
"String 0x%X is invalid. "
"Probably because an old version of the .lng file.\n", string
);
}
return FormatString(buffr, GetStringPtr(GB(string, 0, 16)), argv, GB(string, 24, 8), last);
}
char *GetString(char *buffr, StringID string, const char *last)
{
return GetStringWithArgs(buffr, string, (int64*)_decode_parameters, last);
}
char *InlineString(char *buf, StringID string)
{
buf += Utf8Encode(buf, SCC_STRING_ID);
buf += Utf8Encode(buf, string);
return buf;
}
/** This function is used to "bind" a C string to a OpenTTD dparam slot.
* @param n slot of the string
* @param str string to bind
*/
void SetDParamStr(uint n, const char *str)
{
SetDParam(n, (uint64)(size_t)str);
}
void InjectDParam(uint amount)
{
assert((uint)amount < lengthof(_decode_parameters));
memmove(_decode_parameters + amount, _decode_parameters, sizeof(_decode_parameters) - amount * sizeof(uint64));
}
/* TODO */
static char *FormatCommaNumber(char *buff, int64 number, const char *last)
{
uint64 divisor = 10000000000000000000ULL;
uint64 quot;
int i;
uint64 tot;
uint64 num;
if (number < 0) {
*buff++ = '-';
number = -number;
}
num = number;
tot = 0;
for (i = 0; i < 20; i++) {
quot = 0;
if (num >= divisor) {
quot = num / divisor;
num = num % divisor;
}
if (tot |= quot || i == 19) {
*buff++ = '0' + quot;
if ((i % 3) == 1 && i != 19) *buff++ = ',';
}
divisor /= 10;
}
*buff = '\0';
return buff;
}
/* TODO */
static char *FormatNoCommaNumber(char *buff, int64 number, const char *last)
{
uint64 divisor = 10000000000000000000ULL;
uint64 quot;
int i;
uint64 tot;
uint64 num;
if (number < 0) {
buff = strecpy(buff, "-", last);
number = -number;
}
num = number;
tot = 0;
for (i = 0; i < 20; i++) {
quot = 0;
if (num >= divisor) {
quot = num / divisor;
num = num % divisor;
}
if (tot |= quot || i == 19) {
*buff++ = '0' + quot;
}
divisor /= 10;
}
*buff = '\0';
return buff;
}
static char *FormatHexNumber(char *buff, int64 number, const char *last)
{
return buff + seprintf(buff, last, "0x%x", (uint32)number);
}
/**
* Format a given number as a number of bytes with the SI prefix.
* @param buff the buffer to write to
* @param number the number of bytes to write down
* @param last the last element in the buffer
* @return till where we wrote
*/
static char *FormatBytes(char *buff, int64 number, const char *last)
{
assert(number >= 0);
/* 0 2^10 2^20 2^30 2^40 2^50 2^60 */
const char *siUnits[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" };
uint id = 1;
while (number >= 1024 * 1024) {
number /= 1024;
id++;
}
if (number < 1024) {
id = 0;
buff += seprintf(buff, last, "%i", (int)number);
} else if (number < 1024 * 10) {
buff += seprintf(buff, last, "%i.%02i", (int)number / 1024, (int)(number % 1024) * 100 / 1024);
} else if (number < 1024 * 100) {
buff += seprintf(buff, last, "%i.%01i", (int)number / 1024, (int)(number % 1024) * 10 / 1024);
} else {
assert(number < 1024 * 1024);
buff += seprintf(buff, last, "%i", (int)number / 1024);
}
assert(id < lengthof(siUnits));
buff += seprintf(buff, last, " %s", siUnits[id]);
return buff;
}
static char *FormatYmdString(char *buff, Date date, const char *last)
{
YearMonthDay ymd;
ConvertDateToYMD(date, &ymd);
int64 args[3] = { ymd.day + STR_01AC_1ST - 1, STR_0162_JAN + ymd.month, ymd.year };
return FormatString(buff, GetStringPtr(STR_DATE_LONG), args, 0, last);
}
static char *FormatMonthAndYear(char *buff, Date date, const char *last)
{
YearMonthDay ymd;
ConvertDateToYMD(date, &ymd);
int64 args[2] = { STR_MONTH_JAN + ymd.month, ymd.year };
return FormatString(buff, GetStringPtr(STR_DATE_SHORT), args, 0, last);
}
static char *FormatTinyOrISODate(char *buff, Date date, StringID str, const char *last)
{
YearMonthDay ymd;
ConvertDateToYMD(date, &ymd);
char day[3];
char month[3];
/* We want to zero-pad the days and months */
snprintf(day, lengthof(day), "%02i", ymd.day);
snprintf(month, lengthof(month), "%02i", ymd.month + 1);
int64 args[3] = { (int64)(size_t)day, (int64)(size_t)month, ymd.year };
return FormatString(buff, GetStringPtr(str), args, 0, last);
}
static char *FormatGenericCurrency(char *buff, const CurrencySpec *spec, Money number, bool compact, const char *last)
{
/* We are going to make number absolute for printing, so
* keep this piece of data as we need it later on */
bool negative = number < 0;
const char *multiplier = "";
char buf[40];
char *p;
int j;
number *= spec->rate;
/* convert from negative */
if (number < 0) {
if (buff + Utf8CharLen(SCC_RED) > last) return buff;
buff += Utf8Encode(buff, SCC_RED);
buff = strecpy(buff, "-", last);
number = -number;
}
/* Add prefix part, folowing symbol_pos specification.
* Here, it can can be either 0 (prefix) or 2 (both prefix anf suffix).
* The only remaining value is 1 (suffix), so everything that is not 1 */
if (spec->symbol_pos != 1) buff = strecpy(buff, spec->prefix, last);
/* for huge numbers, compact the number into k or M */
if (compact) {
if (number >= 1000000000) {
number = (number + 500000) / 1000000;
multiplier = "M";
} else if (number >= 1000000) {
number = (number + 500) / 1000;
multiplier = "k";
}
}
/* convert to ascii number and add commas */
p = endof(buf);
*--p = '\0';
j = 4;
do {
if (--j == 0) {
*--p = spec->separator;
j = 3;
}
*--p = '0' + (char)(number % 10);
} while ((number /= 10) != 0);
buff = strecpy(buff, p, last);
buff = strecpy(buff, multiplier, last);
/* Add suffix part, folowing symbol_pos specification.
* Here, it can can be either 1 (suffix) or 2 (both prefix anf suffix).
* The only remaining value is 1 (prefix), so everything that is not 0 */
if (spec->symbol_pos != 0) buff = strecpy(buff, spec->suffix, last);
if (negative) {
if (buff + Utf8CharLen(SCC_PREVIOUS_COLOUR) > last) return buff;
buff += Utf8Encode(buff, SCC_PREVIOUS_COLOUR);
*buff = '\0';
}
return buff;
}
static int DeterminePluralForm(int64 count)
{
/* The absolute value determines plurality */
uint64 n = abs(count);
switch (_langpack->plural_form) {
default:
NOT_REACHED();
/* Two forms, singular used for one only
* Used in:
* Danish, Dutch, English, German, Norwegian, Swedish, Estonian, Finnish,
* Greek, Hebrew, Italian, Portuguese, Spanish, Esperanto */
case 0:
return n != 1;
/* Only one form
* Used in:
* Hungarian, Japanese, Korean, Turkish */
case 1:
return 0;
/* Two forms, singular used for zero and one
* Used in:
* French, Brazilian Portuguese */
case 2:
return n > 1;
/* Three forms, special case for zero
* Used in:
* Latvian */
case 3:
return n % 10 == 1 && n % 100 != 11 ? 0 : n != 0 ? 1 : 2;
/* Three forms, special case for one and two
* Used in:
* Gaelige (Irish) */
case 4:
return n == 1 ? 0 : n == 2 ? 1 : 2;
/* Three forms, special case for numbers ending in 1[2-9]
* Used in:
* Lithuanian */
case 5:
return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
/* Three forms, special cases for numbers ending in 1 and 2, 3, 4, except those ending in 1[1-4]
* Used in:
* Croatian, Czech, Russian, Slovak, Ukrainian */
case 6:
return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
/* Three forms, special case for one and some numbers ending in 2, 3, or 4
* Used in:
* Polish */
case 7:
return n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
/* Four forms, special case for one and all numbers ending in 02, 03, or 04
* Used in:
* Slovenian */
case 8:
return n % 100 == 1 ? 0 : n % 100 == 2 ? 1 : n % 100 == 3 || n % 100 == 4 ? 2 : 3;
/* Two forms; singular used for everything ending in 1 but not in 11.
* Used in:
* Icelandic */
case 9:
return n % 10 == 1 && n % 100 != 11 ? 0 : 1;
}
}
static const char *ParseStringChoice(const char *b, uint form, char *dst, int *dstlen)
{
/* <NUM> {Length of each string} {each string} */
uint n = (byte)*b++;
uint pos, i, mylen = 0, mypos = 0;
for (i = pos = 0; i != n; i++) {
uint len = (byte)*b++;
if (i == form) {
mypos = pos;
mylen = len;
}
pos += len;
}
*dstlen = mylen;
memcpy(dst, b + mypos, mylen);
return b + pos;
}
struct Units {
int s_m; ///< Multiplier for velocity
int s_s; ///< Shift for velocity
StringID velocity; ///< String for velocity
int p_m; ///< Multiplier for power
int p_s; ///< Shift for power
StringID power; ///< String for velocity
int w_m; ///< Multiplier for weight
int w_s; ///< Shift for weight
StringID s_weight; ///< Short string for weight
StringID l_weight; ///< Long string for weight
int v_m; ///< Multiplier for volume
int v_s; ///< Shift for volume
StringID s_volume; ///< Short string for volume
StringID l_volume; ///< Long string for volume
int f_m; ///< Multiplier for force
int f_s; ///< Shift for force
StringID force; ///< String for force
};
/* Unit conversions */
static const Units units[] = {
{ // Imperial (Original, mph, hp, metric ton, litre, kN)
1, 0, STR_UNITS_VELOCITY_IMPERIAL,
1, 0, STR_UNITS_POWER_IMPERIAL,
1, 0, STR_UNITS_WEIGHT_SHORT_METRIC, STR_UNITS_WEIGHT_LONG_METRIC,
1000, 0, STR_UNITS_VOLUME_SHORT_METRIC, STR_UNITS_VOLUME_LONG_METRIC,
1, 0, STR_UNITS_FORCE_SI,
},
{ // Metric (km/h, hp, metric ton, litre, kN)
103, 6, STR_UNITS_VELOCITY_METRIC,
1, 0, STR_UNITS_POWER_METRIC,
1, 0, STR_UNITS_WEIGHT_SHORT_METRIC, STR_UNITS_WEIGHT_LONG_METRIC,
1000, 0, STR_UNITS_VOLUME_SHORT_METRIC, STR_UNITS_VOLUME_LONG_METRIC,
1, 0, STR_UNITS_FORCE_SI,
},
{ // SI (m/s, kilowatt, kilogram, cubic metres, kilonewton)
1831, 12, STR_UNITS_VELOCITY_SI,
764, 10, STR_UNITS_POWER_SI,
1000, 0, STR_UNITS_WEIGHT_SHORT_SI, STR_UNITS_WEIGHT_LONG_SI,
1, 0, STR_UNITS_VOLUME_SHORT_SI, STR_UNITS_VOLUME_LONG_SI,
1, 0, STR_UNITS_FORCE_SI,
},
};
/**
* Convert the given (internal) speed to the display speed.
* @param speed the speed to convert
* @return the converted speed.
*/
uint ConvertSpeedToDisplaySpeed(uint speed)
{
return (speed * units[_settings_game.locale.units].s_m) >> units[_settings_game.locale.units].s_s;
}
/**
* Convert the given display speed to the (internal) speed.
* @param speed the speed to convert
* @return the converted speed.
*/
uint ConvertDisplaySpeedToSpeed(uint speed)
{
return ((speed << units[_settings_game.locale.units].s_s) + units[_settings_game.locale.units].s_m / 2) / units[_settings_game.locale.units].s_m;
}
static char *FormatString(char *buff, const char *str, const int64 *argv, uint casei, const char *last)
{
WChar b;
const int64 *argv_orig = argv;
uint modifier = 0;
while ((b = Utf8Consume(&str)) != '\0') {
if (SCC_NEWGRF_FIRST <= b && b <= SCC_NEWGRF_LAST) {
/* We need to pass some stuff as it might be modified; oh boy. */
b = RemapNewGRFStringControlCode(b, &buff, &str, (int64*)argv);
if (b == 0) continue;
}
switch (b) {
case SCC_SETX: // {SETX}
if (buff + Utf8CharLen(SCC_SETX) + 1 < last) {
buff += Utf8Encode(buff, SCC_SETX);
*buff++ = *str++;
}
break;
case SCC_SETXY: // {SETXY}
if (buff + Utf8CharLen(SCC_SETXY) + 2 < last) {
buff += Utf8Encode(buff, SCC_SETXY);
*buff++ = *str++;
*buff++ = *str++;
}
break;
case SCC_STRING_ID: // {STRINL}
buff = GetStringWithArgs(buff, Utf8Consume(&str), argv, last);
break;
case SCC_RAW_STRING_POINTER: { // {RAW_STRING}
const char *str = (const char*)(size_t)GetInt64(&argv);
buff = FormatString(buff, str, argv, casei, last);
break;
}
case SCC_DATE_LONG: // {DATE_LONG}
buff = FormatYmdString(buff, GetInt32(&argv), last);
break;
case SCC_DATE_SHORT: // {DATE_SHORT}
buff = FormatMonthAndYear(buff, GetInt32(&argv), last);
break;
case SCC_VELOCITY: {// {VELOCITY}
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = ConvertSpeedToDisplaySpeed(GetInt32(&argv) * 10 / 16);
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].velocity), args, modifier >> 24, last);
modifier = 0;
break;
}
case SCC_CURRENCY_COMPACT: // {CURRCOMPACT}
buff = FormatGenericCurrency(buff, _currency, GetInt64(&argv), true, last);
break;
case SCC_REVISION: // {REV}
buff = strecpy(buff, _openttd_revision, last);
break;
case SCC_CARGO_SHORT: { // {SHORTCARGO}
/* Short description of cargotypes. Layout:
* 8-bit = cargo type
* 16-bit = cargo count */
StringID cargo_str = GetCargo(GetInt32(&argv))->units_volume;
switch (cargo_str) {
case STR_TONS: {
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = GetInt32(&argv) * units[_settings_game.locale.units].w_m >> units[_settings_game.locale.units].w_s;
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].l_weight), args, modifier >> 24, last);
modifier = 0;
break;
}
case STR_LITERS: {
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = GetInt32(&argv) * units[_settings_game.locale.units].v_m >> units[_settings_game.locale.units].v_s;
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].l_volume), args, modifier >> 24, last);
modifier = 0;
break;
}
default:
if (cargo_str >= 0xE000 && cargo_str < 0xF800) {
/* NewGRF strings from Action 4 use a different format here,
* of e.g. "x tonnes of coal", so process accordingly. */
buff = GetStringWithArgs(buff, cargo_str, argv++, last);
} else {
buff = FormatCommaNumber(buff, GetInt32(&argv), last);
buff = strecpy(buff, " ", last);
buff = strecpy(buff, GetStringPtr(cargo_str), last);
}
break;
}
} break;
case SCC_STRING1: { // {STRING1}
/* String that consumes ONE argument */
uint str = modifier + GetInt32(&argv);
buff = GetStringWithArgs(buff, str, GetArgvPtr(&argv, 1), last);
modifier = 0;
break;
}
case SCC_STRING2: { // {STRING2}
/* String that consumes TWO arguments */
uint str = modifier + GetInt32(&argv);
buff = GetStringWithArgs(buff, str, GetArgvPtr(&argv, 2), last);
modifier = 0;
break;
}
case SCC_STRING3: { // {STRING3}
/* String that consumes THREE arguments */
uint str = modifier + GetInt32(&argv);
buff = GetStringWithArgs(buff, str, GetArgvPtr(&argv, 3), last);
modifier = 0;
break;
}
case SCC_STRING4: { // {STRING4}
/* String that consumes FOUR arguments */
uint str = modifier + GetInt32(&argv);
buff = GetStringWithArgs(buff, str, GetArgvPtr(&argv, 4), last);
modifier = 0;
break;
}
case SCC_STRING5: { // {STRING5}
/* String that consumes FIVE arguments */
uint str = modifier + GetInt32(&argv);
buff = GetStringWithArgs(buff, str, GetArgvPtr(&argv, 5), last);
modifier = 0;
break;
}
case SCC_STATION_FEATURES: { // {STATIONFEATURES}
buff = StationGetSpecialString(buff, GetInt32(&argv), last);
break;
}
case SCC_INDUSTRY_NAME: { // {INDUSTRY}
const Industry *i = GetIndustry(GetInt32(&argv));
int64 args[2];
/* industry not valid anymore? */
if (!i->IsValid()) break;
/* First print the town name and the industry type name. */
args[0] = i->town->index;
args[1] = GetIndustrySpec(i->type)->name;
buff = FormatString(buff, GetStringPtr(STR_INDUSTRY_FORMAT), args, modifier >> 24, last);
modifier = 0;
break;
}
case SCC_VOLUME: { // {VOLUME}
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = GetInt32(&argv) * units[_settings_game.locale.units].v_m >> units[_settings_game.locale.units].v_s;
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].l_volume), args, modifier >> 24, last);
modifier = 0;
break;
}
case SCC_GENDER_LIST: { // {G 0 Der Die Das}
const char *s = GetStringPtr(argv_orig[(byte)*str++]); // contains the string that determines gender.
int len;
int gender = 0;
if (s != NULL) {
wchar_t c = Utf8Consume(&s);
/* Switch case is always put before genders, so remove those bits */
if (c == SCC_SWITCH_CASE) {
/* Skip to the last (i.e. default) case */
for (uint num = (byte)*s++; num != 0; num--) s += 3 + (s[1] << 8) + s[2];
c = Utf8Consume(&s);
}
/* Does this string have a gender, if so, set it */
if (c == SCC_GENDER_INDEX) gender = (byte)s[0];
}
str = ParseStringChoice(str, gender, buff, &len);
buff += len;
break;
}
case SCC_DATE_TINY: { // {DATE_TINY}
buff = FormatTinyOrISODate(buff, GetInt32(&argv), STR_DATE_TINY, last);
break;
}
case SCC_DATE_ISO: { // {DATE_ISO}
buff = FormatTinyOrISODate(buff, GetInt32(&argv), STR_DATE_ISO, last);
break;
}
case SCC_CARGO: { // {CARGO}
/* Layout now is:
* 8bit - cargo type
* 16-bit - cargo count */
CargoID cargo = GetInt32(&argv);
StringID cargo_str = (cargo == CT_INVALID) ? STR_8838_N_A : GetCargo(cargo)->quantifier;
buff = GetStringWithArgs(buff, cargo_str, argv++, last);
break;
}
case SCC_POWER: { // {POWER}
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = GetInt32(&argv) * units[_settings_game.locale.units].p_m >> units[_settings_game.locale.units].p_s;
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].power), args, modifier >> 24, last);
modifier = 0;
break;
}
case SCC_VOLUME_SHORT: { // {VOLUME_S}
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = GetInt32(&argv) * units[_settings_game.locale.units].v_m >> units[_settings_game.locale.units].v_s;
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].s_volume), args, modifier >> 24, last);
modifier = 0;
break;
}
case SCC_WEIGHT: { // {WEIGHT}
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = GetInt32(&argv) * units[_settings_game.locale.units].w_m >> units[_settings_game.locale.units].w_s;
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].l_weight), args, modifier >> 24, last);
modifier = 0;
break;
}
case SCC_WEIGHT_SHORT: { // {WEIGHT_S}
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = GetInt32(&argv) * units[_settings_game.locale.units].w_m >> units[_settings_game.locale.units].w_s;
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].s_weight), args, modifier >> 24, last);
modifier = 0;
break;
}
case SCC_FORCE: { // {FORCE}
int64 args[1];
assert(_settings_game.locale.units < lengthof(units));
args[0] = GetInt32(&argv) * units[_settings_game.locale.units].f_m >> units[_settings_game.locale.units].f_s;
buff = FormatString(buff, GetStringPtr(units[_settings_game.locale.units].force), args, modifier >> 24, last);
modifier = 0;
break;
}
case SCC_SKIP: // {SKIP}
argv++;
break;
/* This sets up the gender for the string.
* We just ignore this one. It's used in {G 0 Der Die Das} to determine the case. */
case SCC_GENDER_INDEX: // {GENDER 0}
str++;
break;
case SCC_STRING: {// {STRING}
uint str = modifier + GetInt32(&argv);
/* WARNING. It's prohibited for the included string to consume any arguments.
* For included strings that consume argument, you should use STRING1, STRING2 etc.
* To debug stuff you can set argv to NULL and it will tell you */
buff = GetStringWithArgs(buff, str, argv, last);
modifier = 0;
break;
}
case SCC_COMMA: // {COMMA}
buff = FormatCommaNumber(buff, GetInt64(&argv), last);
break;
case SCC_ARG_INDEX: // Move argument pointer
argv = argv_orig + (byte)*str++;
break;
case SCC_PLURAL_LIST: { // {P}
int64 v = argv_orig[(byte)*str++]; // contains the number that determines plural
int len;
str = ParseStringChoice(str, DeterminePluralForm(v), buff, &len);
buff += len;
break;
}
case SCC_NUM: // {NUM}
buff = FormatNoCommaNumber(buff, GetInt64(&argv), last);
break;
case SCC_HEX: // {HEX}
buff = FormatHexNumber(buff, GetInt64(&argv), last);
break;
case SCC_BYTES: // {BYTES}
buff = FormatBytes(buff, GetInt64(&argv), last);
break;
case SCC_CURRENCY: // {CURRENCY}
buff = FormatGenericCurrency(buff, _currency, GetInt64(&argv), false, last);
break;
case SCC_WAYPOINT_NAME: { // {WAYPOINT}
Waypoint *wp = GetWaypoint(GetInt32(&argv));
assert(wp->IsValid());
if (wp->name != NULL) {
buff = strecpy(buff, wp->name, last);
} else {
int64 temp[2];
temp[0] = wp->town_index;
temp[1] = wp->town_cn + 1;
StringID str = wp->town_cn == 0 ? STR_WAYPOINTNAME_CITY : STR_WAYPOINTNAME_CITY_SERIAL;
buff = GetStringWithArgs(buff, str, temp, last);
}
break;
}
case SCC_STATION_NAME: { // {STATION}
StationID sid = GetInt32(&argv);
if (!IsValidStationID(sid)) {
/* The station doesn't exist anymore. The only place where we might
* be "drawing" an invalid station is in the case of cargo that is
* in transit. */
buff = GetStringWithArgs(buff, STR_UNKNOWN_STATION, NULL, last);
break;
}
const Station *st = GetStation(sid);
if (st->name != NULL) {
buff = strecpy(buff, st->name, last);
} else {
StringID str = st->string_id;
if (st->indtype != IT_INVALID) {
/* Special case where the industry provides the name for the station */
const IndustrySpec *indsp = GetIndustrySpec(st->indtype);
/* Industry GRFs can change which might remove the station name and
* thus cause very strange things. Here we check for that before we
* actually set the station name. */
if (indsp->station_name != STR_NULL && indsp->station_name != STR_UNDEFINED) {
str = indsp->station_name;
}
}
int64 temp[3];
temp[0] = STR_TOWN;
temp[1] = st->town->index;
temp[2] = st->index;
buff = GetStringWithArgs(buff, str, temp, last);
}
break;
}
case SCC_TOWN_NAME: { // {TOWN}
const Town *t = GetTown(GetInt32(&argv));
int64 temp[1];
assert(t->IsValid());
temp[0] = t->townnameparts;
uint32 grfid = t->townnamegrfid;
if (t->name != NULL) {
buff = strecpy(buff, t->name, last);
} else if (grfid == 0) {
/* Original town name */
buff = GetStringWithArgs(buff, t->townnametype, temp, last);
} else {
/* Newgrf town name */
if (GetGRFTownName(grfid) != NULL) {
/* The grf is loaded */
buff = GRFTownNameGenerate(buff, t->townnamegrfid, t->townnametype, t->townnameparts, last);
} else {
/* Fallback to english original */
buff = GetStringWithArgs(buff, SPECSTR_TOWNNAME_ENGLISH, temp, last);
}
}
break;
}
case SCC_GROUP_NAME: { // {GROUP}
const Group *g = GetGroup(GetInt32(&argv));
assert(g->IsValid());
if (g->name != NULL) {
buff = strecpy(buff, g->name, last);
} else {
int64 args[1];
args[0] = g->index;
buff = GetStringWithArgs(buff, STR_GROUP_NAME_FORMAT, args, last);
}
break;
}
case SCC_ENGINE_NAME: { // {ENGINE}
EngineID engine = (EngineID)GetInt32(&argv);
const Engine *e = GetEngine(engine);
if (e->name != NULL) {
buff = strecpy(buff, e->name, last);
} else {
buff = GetStringWithArgs(buff, e->info.string_id, NULL, last);
}
break;
}
case SCC_VEHICLE_NAME: { // {VEHICLE}
const Vehicle *v = GetVehicle(GetInt32(&argv));
if (v->name != NULL) {
buff = strecpy(buff, v->name, last);
} else {
int64 args[1];
args[0] = v->unitnumber;
StringID str;
switch (v->type) {
default: NOT_REACHED();
case VEH_TRAIN: str = STR_SV_TRAIN_NAME; break;
case VEH_ROAD: str = STR_SV_ROADVEH_NAME; break;
case VEH_SHIP: str = STR_SV_SHIP_NAME; break;
case VEH_AIRCRAFT: str = STR_SV_AIRCRAFT_NAME; break;
}
buff = GetStringWithArgs(buff, str, args, last);
}
break;
}
case SCC_SIGN_NAME: { // {SIGN}
const Sign *si = GetSign(GetInt32(&argv));
if (si->name != NULL) {
buff = strecpy(buff, si->name, last);
} else {
buff = GetStringWithArgs(buff, STR_280A_SIGN, NULL, last);
}
break;
}
case SCC_COMPANY_NAME: { // {COMPANY}
const Company *c = GetCompany((CompanyID)GetInt32(&argv));
if (c->name != NULL) {
buff = strecpy(buff, c->name, last);
} else {
int64 args[1];
args[0] = c->name_2;
buff = GetStringWithArgs(buff, c->name_1, args, last);
}
break;
}
case SCC_COMPANY_NUM: { // {COMPANYNUM}
CompanyID company = (CompanyID)GetInt32(&argv);
/* Nothing is added for AI or inactive companies */
if (IsValidCompanyID(company) && IsHumanCompany(company)) {
int64 args[1];
args[0] = company + 1;
buff = GetStringWithArgs(buff, STR_7002_COMPANY, args, last);
}
break;
}
case SCC_PRESIDENT_NAME: { // {PRESIDENTNAME}
const Company *c = GetCompany((CompanyID)GetInt32(&argv));
if (c->president_name != NULL) {
buff = strecpy(buff, c->president_name, last);
} else {
int64 args[1];
args[0] = c->president_name_2;
buff = GetStringWithArgs(buff, c->president_name_1, args, last);
}
break;
}
case SCC_SETCASE: { // {SETCASE}
/* This is a pseudo command, it's outputted when someone does {STRING.ack}
* The modifier is added to all subsequent GetStringWithArgs that accept the modifier. */
modifier = (byte)*str++ << 24;
break;
}
case SCC_SWITCH_CASE: { // {Used to implement case switching}
/* <0x9E> <NUM CASES> <CASE1> <LEN1> <STRING1> <CASE2> <LEN2> <STRING2> <CASE3> <LEN3> <STRING3> <STRINGDEFAULT>
* Each LEN is printed using 2 bytes in big endian order. */
uint num = (byte)*str++;
while (num) {
if ((byte)str[0] == casei) {
/* Found the case, adjust str pointer and continue */
str += 3;
break;
}
/* Otherwise skip to the next case */
str += 3 + (str[1] << 8) + str[2];
num--;
}
break;
}
default:
if (buff + Utf8CharLen(b) < last) buff += Utf8Encode(buff, b);
break;
}
}
*buff = '\0';
return buff;
}
static char *StationGetSpecialString(char *buff, int x, const char *last)
{
if ((x & FACIL_TRAIN) && (buff + Utf8CharLen(SCC_TRAIN) < last)) buff += Utf8Encode(buff, SCC_TRAIN);
if ((x & FACIL_TRUCK_STOP) && (buff + Utf8CharLen(SCC_LORRY) < last)) buff += Utf8Encode(buff, SCC_LORRY);
if ((x & FACIL_BUS_STOP) && (buff + Utf8CharLen(SCC_BUS) < last)) buff += Utf8Encode(buff, SCC_BUS);
if ((x & FACIL_AIRPORT) && (buff + Utf8CharLen(SCC_PLANE) < last)) buff += Utf8Encode(buff, SCC_PLANE);
if ((x & FACIL_DOCK) && (buff + Utf8CharLen(SCC_SHIP) < last)) buff += Utf8Encode(buff, SCC_SHIP);
*buff = '\0';
return buff;
}
static char *GetSpecialTownNameString(char *buff, int ind, uint32 seed, const char *last)
{
char name[512];
_town_name_generators[ind](name, seed, lastof(name));
return strecpy(buff, name, last);
}
static const char * const _silly_company_names[] = {
"Bloggs Brothers",
"Tiny Transport Ltd.",
"Express Travel",
"Comfy-Coach & Co.",
"Crush & Bump Ltd.",
"Broken & Late Ltd.",
"Sam Speedy & Son",
"Supersonic Travel",
"Mike's Motors",
"Lightning International",
"Pannik & Loozit Ltd.",
"Inter-City Transport",
"Getout & Pushit Ltd."
};
static const char * const _surname_list[] = {
"Adams",
"Allan",
"Baker",
"Bigwig",
"Black",
"Bloggs",
"Brown",
"Campbell",
"Gordon",
"Hamilton",
"Hawthorn",
"Higgins",
"Green",
"Gribble",
"Jones",
"McAlpine",
"MacDonald",
"McIntosh",
"Muir",
"Murphy",
"Nelson",
"O'Donnell",
"Parker",
"Phillips",
"Pilkington",
"Quigley",
"Sharkey",
"Thomson",
"Watkins"
};
static const char * const _silly_surname_list[] = {
"Grumpy",
"Dozy",
"Speedy",
"Nosey",
"Dribble",
"Mushroom",
"Cabbage",
"Sniffle",
"Fishy",
"Swindle",
"Sneaky",
"Nutkins"
};
static const char _initial_name_letters[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W',
};
static char *GenAndCoName(char *buff, uint32 arg, const char *last)
{
const char * const *base;
uint num;
if (_settings_game.game_creation.landscape == LT_TOYLAND) {
base = _silly_surname_list;
num = lengthof(_silly_surname_list);
} else {
base = _surname_list;
num = lengthof(_surname_list);
}
buff = strecpy(buff, base[num * GB(arg, 16, 8) >> 8], last);
buff = strecpy(buff, " & Co.", last);
return buff;
}
static char *GenPresidentName(char *buff, uint32 x, const char *last)
{
char initial[] = "?. ";
const char * const *base;
uint num;
uint i;
initial[0] = _initial_name_letters[sizeof(_initial_name_letters) * GB(x, 0, 8) >> 8];
buff = strecpy(buff, initial, last);
i = (sizeof(_initial_name_letters) + 35) * GB(x, 8, 8) >> 8;
if (i < sizeof(_initial_name_letters)) {
initial[0] = _initial_name_letters[i];
buff = strecpy(buff, initial, last);
}
if (_settings_game.game_creation.landscape == LT_TOYLAND) {
base = _silly_surname_list;
num = lengthof(_silly_surname_list);
} else {
base = _surname_list;
num = lengthof(_surname_list);
}
buff = strecpy(buff, base[num * GB(x, 16, 8) >> 8], last);
return buff;
}
static char *GetSpecialNameString(char *buff, int ind, const int64 *argv, const char *last)
{
switch (ind) {
case 1: // not used
return strecpy(buff, _silly_company_names[GetInt32(&argv) & 0xFFFF], last);
case 2: // used for Foobar & Co company names
return GenAndCoName(buff, GetInt32(&argv), last);
case 3: // President name
return GenPresidentName(buff, GetInt32(&argv), last);
case 4: // song names
return strecpy(buff, _origin_songs_specs[GetInt32(&argv) - 1].song_name, last);
}
/* town name? */
if (IsInsideMM(ind - 6, 0, SPECSTR_TOWNNAME_LAST - SPECSTR_TOWNNAME_START + 1)) {
buff = GetSpecialTownNameString(buff, ind - 6, GetInt32(&argv), last);
return strecpy(buff, " Transport", last);
}
/* language name? */
if (IsInsideMM(ind, (SPECSTR_LANGUAGE_START - 0x70E4), (SPECSTR_LANGUAGE_END - 0x70E4) + 1)) {
int i = ind - (SPECSTR_LANGUAGE_START - 0x70E4);
return strecpy(buff,
i == _dynlang.curr ? _langpack->own_name : _dynlang.ent[i].name, last);
}
/* resolution size? */
if (IsInsideMM(ind, (SPECSTR_RESOLUTION_START - 0x70E4), (SPECSTR_RESOLUTION_END - 0x70E4) + 1)) {
int i = ind - (SPECSTR_RESOLUTION_START - 0x70E4);
buff += seprintf(
buff, last, "%dx%d", _resolutions[i].width, _resolutions[i].height
);
return buff;
}
/* screenshot format name? */
if (IsInsideMM(ind, (SPECSTR_SCREENSHOT_START - 0x70E4), (SPECSTR_SCREENSHOT_END - 0x70E4) + 1)) {
int i = ind - (SPECSTR_SCREENSHOT_START - 0x70E4);
return strecpy(buff, GetScreenshotFormatDesc(i), last);
}
assert(0);
return NULL;
}
#ifdef ENABLE_NETWORK
extern void SortNetworkLanguages();
#else /* ENABLE_NETWORK */
static inline void SortNetworkLanguages() {}
#endif /* ENABLE_NETWORK */
bool ReadLanguagePack(int lang_index)
{
int tot_count, i;
size_t len;
char **langpack_offs;
char *s;
LanguagePack *lang_pack = (LanguagePack*)ReadFileToMem(_dynlang.ent[lang_index].file, &len, 200000);
if (lang_pack == NULL) return false;
if (len < sizeof(LanguagePack) ||
lang_pack->ident != TO_LE32(LANGUAGE_PACK_IDENT) ||
lang_pack->version != TO_LE32(LANGUAGE_PACK_VERSION)) {
free(lang_pack);
return false;
}
#if TTD_ENDIAN == TTD_BIG_ENDIAN
for (i = 0; i != 32; i++) {
lang_pack->offsets[i] = ReadLE16Aligned(&lang_pack->offsets[i]);
}
#endif /* TTD_ENDIAN == TTD_BIG_ENDIAN */
tot_count = 0;
for (i = 0; i != 32; i++) {
uint num = lang_pack->offsets[i];
_langtab_start[i] = tot_count;
_langtab_num[i] = num;
tot_count += num;
}
/* Allocate offsets */
langpack_offs = MallocT<char*>(tot_count);
/* Fill offsets */
s = lang_pack->data;
for (i = 0; i != tot_count; i++) {
len = (byte)*s;
*s++ = '\0'; // zero terminate the string before.
if (len >= 0xC0) len = ((len & 0x3F) << 8) + (byte)*s++;
langpack_offs[i] = s;
s += len;
}
free(_langpack);
_langpack = lang_pack;
free(_langpack_offs);
_langpack_offs = langpack_offs;
const char *c_file = strrchr(_dynlang.ent[lang_index].file, PATHSEPCHAR) + 1;
strecpy(_dynlang.curr_file, c_file, lastof(_dynlang.curr_file));
_dynlang.curr = lang_index;
_dynlang.text_dir = (TextDirection)lang_pack->text_dir;
SetCurrentGrfLangID(_langpack->newgrflangid);
SortNetworkLanguages();
return true;
}
/* Win32 implementation in win32.cpp.
* OS X implementation in os/macosx/macos.mm. */
#if !(defined(WIN32) || defined(__APPLE__))
/** Determine the current charset based on the environment
* First check some default values, after this one we passed ourselves
* and if none exist return the value for $LANG
* @param param environment variable to check conditionally if default ones are not
* set. Pass NULL if you don't want additional checks.
* @return return string containing current charset, or NULL if not-determinable */
const char *GetCurrentLocale(const char *param)
{
const char *env;
env = getenv("LANGUAGE");
if (env != NULL) return env;
env = getenv("LC_ALL");
if (env != NULL) return env;
if (param != NULL) {
env = getenv(param);
if (env != NULL) return env;
}
return getenv("LANG");
}
#else
const char *GetCurrentLocale(const char *param);
#endif /* !(defined(WIN32) || defined(__APPLE__)) */
int CDECL StringIDSorter(const void *a, const void *b)
{
const StringID va = *(const StringID*)a;
const StringID vb = *(const StringID*)b;
char stra[512];
char strb[512];
GetString(stra, va, lastof(stra));
GetString(strb, vb, lastof(strb));
return strcmp(stra, strb);
}
/**
* Checks whether the given language is already found.
* @param langs languages we've found so fa
* @param max the length of the language list
* @param language name of the language to check
* @return true if and only if a language file with the same name has not been found
*/
static bool UniqueLanguageFile(const Language *langs, uint max, const char *language)
{
for (uint i = 0; i < max; i++) {
const char *f_name = strrchr(langs[i].file, PATHSEPCHAR) + 1;
if (strcmp(f_name, language) == 0) return false; // duplicates
}
return true;
}
/**
* Reads the language file header and checks compatability.
* @param file the file to read
* @param hdr the place to write the header information to
* @return true if and only if the language file is of a compatible version
*/
static bool GetLanguageFileHeader(const char *file, LanguagePack *hdr)
{
FILE *f = fopen(file, "rb");
if (f == NULL) return false;
size_t read = fread(hdr, sizeof(*hdr), 1, f);
fclose(f);
bool ret = read == 1 &&
hdr->ident == TO_LE32(LANGUAGE_PACK_IDENT) &&
hdr->version == TO_LE32(LANGUAGE_PACK_VERSION);
/* Convert endianness for the windows language ID */
if (ret) hdr->winlangid = FROM_LE16(hdr->winlangid);
return ret;
}
/**
* Gets a list of languages from the given directory.
* @param langs the list to write to
* @param start the initial offset in the list
* @param max the length of the language list
* @param path the base directory to search in
* @return the number of added languages
*/
static int GetLanguageList(Language *langs, int start, int max, const char *path)
{
int i = start;
DIR *dir = ttd_opendir(path);
if (dir != NULL) {
struct dirent *dirent;
while ((dirent = readdir(dir)) != NULL && i < max) {
const char *d_name = FS2OTTD(dirent->d_name);
const char *extension = strrchr(d_name, '.');
/* Not a language file */
if (extension == NULL || strcmp(extension, ".lng") != 0) continue;
/* Filter any duplicate language-files, first-come first-serve */
if (!UniqueLanguageFile(langs, i, d_name)) continue;
langs[i].file = str_fmt("%s%s", path, d_name);
/* Check whether the file is of the correct version */
LanguagePack hdr;
if (!GetLanguageFileHeader(langs[i].file, &hdr)) {
free(langs[i].file);
continue;
}
i++;
}
closedir(dir);
}
return i - start;
}
/**
* Make a list of the available language packs. put the data in
* _dynlang struct.
*/
void InitializeLanguagePacks()
{
Searchpath sp;
Language files[MAX_LANG];
uint language_count = 0;
FOR_ALL_SEARCHPATHS(sp) {
char path[MAX_PATH];
FioAppendDirectory(path, lengthof(path), sp, LANG_DIR);
language_count += GetLanguageList(files, language_count, lengthof(files), path);
}
if (language_count == 0) usererror("No available language packs (invalid versions?)");
/* Acquire the locale of the current system */
const char *lang = GetCurrentLocale("LC_MESSAGES");
if (lang == NULL) lang = "en_GB";
int chosen_language = -1; ///< Matching the language in the configuartion file or the current locale
int language_fallback = -1; ///< Using pt_PT for pt_BR locale when pt_BR is not available
int en_GB_fallback = 0; ///< Fallback when no locale-matching language has been found
DynamicLanguages *dl = &_dynlang;
dl->num = 0;
/* Fill the dynamic languages structures */
for (uint i = 0; i < language_count; i++) {
/* File read the language header */
LanguagePack hdr;
if (!GetLanguageFileHeader(files[i].file, &hdr)) continue;
dl->ent[dl->num].file = files[i].file;
dl->ent[dl->num].name = strdup(hdr.name);
/* We are trying to find a default language. The priority is by
* configuration file, local environment and last, if nothing found,
* english. If def equals -1, we have not picked a default language */
const char *lang_file = strrchr(dl->ent[dl->num].file, PATHSEPCHAR) + 1;
if (strcmp(lang_file, dl->curr_file) == 0) chosen_language = dl->num;
if (chosen_language == -1) {
if (strcmp (hdr.isocode, "en_GB") == 0) en_GB_fallback = dl->num;
if (strncmp(hdr.isocode, lang, 5) == 0) chosen_language = dl->num;
if (strncmp(hdr.isocode, lang, 2) == 0) language_fallback = dl->num;
}
dl->num++;
}
if (dl->num == 0) usererror("Invalid version of language packs");
/* We haven't found the language in the config nor the one in the locale.
* Now we set it to one of the fallback languages */
if (chosen_language == -1) {
chosen_language = (language_fallback != -1) ? language_fallback : en_GB_fallback;
}
if (!ReadLanguagePack(chosen_language)) usererror("Can't read language pack '%s'", dl->ent[chosen_language].file);
}
/**
* Check whether the currently loaded language pack
* uses characters that the currently loaded font
* does not support. If this is the case an error
* message will be shown in English. The error
* message will not be localized because that would
* mean it might use characters that are not in the
* font, which is the whole reason this check has
* been added.
*/
void CheckForMissingGlyphsInLoadedLanguagePack()
{
#ifdef WITH_FREETYPE
/* Reset to the original state; switching languages might cause us to
* automatically choose another font. This resets that choice. */
UninitFreeType();
InitFreeType();
bool retry = false;
#endif
for (;;) {
const Sprite *question_mark = GetGlyph(FS_NORMAL, '?');
for (uint i = 0; i != 32; i++) {
for (uint j = 0; j < _langtab_num[i]; j++) {
const char *string = _langpack_offs[_langtab_start[i] + j];
WChar c;
while ((c = Utf8Consume(&string)) != '\0') {
if (c == SCC_SETX) {
/*
* SetX is, together with SetXY as special character that
* uses the next (two) characters as data points. We have
* to skip those, otherwise the UTF8 reading will go
* haywire.
*/
string++;
} else if (c == SCC_SETXY) {
string += 2;
} else if (IsPrintable(c) && c != '?' && GetGlyph(FS_NORMAL, c) == question_mark) {
#ifdef WITH_FREETYPE
if (!retry) {
/* We found an unprintable character... lets try whether we can
* find a fallback font that can print the characters in the
* current language. */
retry = true;
FreeTypeSettings backup;
memcpy(&backup, &_freetype, sizeof(backup));
bool success = SetFallbackFont(&_freetype, _langpack->isocode, _langpack->winlangid);
if (success) {
UninitFreeType();
InitFreeType();
}
memcpy(&_freetype, &backup, sizeof(backup));
if (success) continue;
} else {
/* Our fallback font does miss characters too, so keep the
* user chosen font as that is more likely to be any good than
* the wild guess we made */
UninitFreeType();
InitFreeType();
}
#endif
/*
* The character is printable, but not in the normal font.
* This is the case we were testing for. In this case we
* have to show the error. As we do not want the string to
* be translated by the translators, we 'force' it into the
* binary and 'load' it via a BindCString. To do this
* properly we have to set the colour of the string,
* otherwise we end up with a lot of artefacts. The colour
* 'character' might change in the future, so for safety
* we just Utf8 Encode it into the string, which takes
* exactly three characters, so it replaces the "XXX" with
* the colour marker.
*/
static char *err_str = strdup("XXXThe current font is missing some of the characters used in the texts for this language. Read the readme to see how to solve this.");
Utf8Encode(err_str, SCC_YELLOW);
SetDParamStr(0, err_str);
ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
/* Reset the font width */
LoadStringWidthTable();
return;
}
}
}
}
break;
}
/* Update the font with cache */
LoadStringWidthTable();
#if !defined(WITH_ICU)
/*
* For right-to-left languages we need the ICU library. If
* we do not have support for that library we warn the user
* about it with a message. As we do not want the string to
* be translated by the translators, we 'force' it into the
* binary and 'load' it via a BindCString. To do this
* properly we have to set the colour of the string,
* otherwise we end up with a lot of artefacts. The colour
* 'character' might change in the future, so for safety
* we just Utf8 Encode it into the string, which takes
* exactly three characters, so it replaces the "XXX" with
* the colour marker.
*/
if (_dynlang.text_dir != TD_LTR) {
static char *err_str = strdup("XXXThis version of OpenTTD does not support right-to-left languages. Recompile with icu enabled.");
Utf8Encode(err_str, SCC_YELLOW);
SetDParamStr(0, err_str);
ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
}
#endif
}
| 47,406
|
C++
|
.cpp
| 1,381
| 30.75887
| 172
| 0.652097
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,005
|
disaster_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/disaster_cmd.cpp
|
/* $Id$ */
/** @file disaster_cmd.cpp
* All disaster/easter egg vehicles are handled here.
* The general flow of control for the disaster vehicles is as follows:
* <ol>
* <li>Initialize the disaster in a disaster specific way (eg start position,
* possible target, etc.) Disaster_XXX_Init() function
* <li>Add a subtype to a disaster, which is an index into the function array
* that handles the vehicle's ticks.
* <li>Run the disaster vehicles each tick until their target has been reached,
* this happens in the DisasterTick_XXX() functions. In here, a vehicle's
* state is kept by v->current_order.dest variable. Each achieved sub-target
* will increase this value, and the last one will remove the disaster itself
* </ol>
*/
#include "stdafx.h"
#include "landscape.h"
#include "industry_map.h"
#include "station_map.h"
#include "command_func.h"
#include "news_func.h"
#include "town.h"
#include "company_func.h"
#include "variables.h"
#include "strings_func.h"
#include "date_func.h"
#include "functions.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "effectvehicle_func.h"
#include "roadveh.h"
#include "ai/ai.hpp"
#include "table/strings.h"
#include "table/sprites.h"
enum DisasterSubType {
ST_ZEPPELINER,
ST_ZEPPELINER_SHADOW,
ST_SMALL_UFO,
ST_SMALL_UFO_SHADOW,
ST_AIRPLANE,
ST_AIRPLANE_SHADOW,
ST_HELICOPTER,
ST_HELICOPTER_SHADOW,
ST_HELICOPTER_ROTORS,
ST_BIG_UFO,
ST_BIG_UFO_SHADOW,
ST_BIG_UFO_DESTROYER,
ST_BIG_UFO_DESTROYER_SHADOW,
ST_SMALL_SUBMARINE,
ST_BIG_SUBMARINE,
};
static void DisasterClearSquare(TileIndex tile)
{
if (!EnsureNoVehicleOnGround(tile)) return;
switch (GetTileType(tile)) {
case MP_RAILWAY:
if (IsHumanCompany(GetTileOwner(tile)) && !IsRailWaypoint(tile)) {
CompanyID old_company = _current_company;
_current_company = OWNER_WATER;
DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
_current_company = old_company;
/* update signals in buffer */
UpdateSignalsInBuffer();
}
break;
case MP_HOUSE: {
CompanyID old_company = _current_company;
_current_company = OWNER_NONE;
DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
_current_company = old_company;
break;
}
case MP_TREES:
case MP_CLEAR:
DoClearSquare(tile);
break;
default:
break;
}
}
static const SpriteID _disaster_images_1[] = {SPR_BLIMP, SPR_BLIMP, SPR_BLIMP, SPR_BLIMP, SPR_BLIMP, SPR_BLIMP, SPR_BLIMP, SPR_BLIMP};
static const SpriteID _disaster_images_2[] = {SPR_UFO_SMALL_SCOUT, SPR_UFO_SMALL_SCOUT, SPR_UFO_SMALL_SCOUT, SPR_UFO_SMALL_SCOUT, SPR_UFO_SMALL_SCOUT, SPR_UFO_SMALL_SCOUT, SPR_UFO_SMALL_SCOUT, SPR_UFO_SMALL_SCOUT};
static const SpriteID _disaster_images_3[] = {SPR_F_15, SPR_F_15, SPR_F_15, SPR_F_15, SPR_F_15, SPR_F_15, SPR_F_15, SPR_F_15};
static const SpriteID _disaster_images_4[] = {SPR_SUB_SMALL_NE, SPR_SUB_SMALL_NE, SPR_SUB_SMALL_SE, SPR_SUB_SMALL_SE, SPR_SUB_SMALL_SW, SPR_SUB_SMALL_SW, SPR_SUB_SMALL_NW, SPR_SUB_SMALL_NW};
static const SpriteID _disaster_images_5[] = {SPR_SUB_LARGE_NE, SPR_SUB_LARGE_NE, SPR_SUB_LARGE_SE, SPR_SUB_LARGE_SE, SPR_SUB_LARGE_SW, SPR_SUB_LARGE_SW, SPR_SUB_LARGE_NW, SPR_SUB_LARGE_NW};
static const SpriteID _disaster_images_6[] = {SPR_UFO_HARVESTER, SPR_UFO_HARVESTER, SPR_UFO_HARVESTER, SPR_UFO_HARVESTER, SPR_UFO_HARVESTER, SPR_UFO_HARVESTER, SPR_UFO_HARVESTER, SPR_UFO_HARVESTER};
static const SpriteID _disaster_images_7[] = {SPR_XCOM_SKYRANGER, SPR_XCOM_SKYRANGER, SPR_XCOM_SKYRANGER, SPR_XCOM_SKYRANGER, SPR_XCOM_SKYRANGER, SPR_XCOM_SKYRANGER, SPR_XCOM_SKYRANGER, SPR_XCOM_SKYRANGER};
static const SpriteID _disaster_images_8[] = {SPR_AH_64A, SPR_AH_64A, SPR_AH_64A, SPR_AH_64A, SPR_AH_64A, SPR_AH_64A, SPR_AH_64A, SPR_AH_64A};
static const SpriteID _disaster_images_9[] = {SPR_ROTOR_MOVING_1, SPR_ROTOR_MOVING_1, SPR_ROTOR_MOVING_1, SPR_ROTOR_MOVING_1, SPR_ROTOR_MOVING_1, SPR_ROTOR_MOVING_1, SPR_ROTOR_MOVING_1, SPR_ROTOR_MOVING_1};
static const SpriteID * const _disaster_images[] = {
_disaster_images_1, _disaster_images_1, ///< zeppeliner and zeppeliner shadow
_disaster_images_2, _disaster_images_2, ///< small ufo and small ufo shadow
_disaster_images_3, _disaster_images_3, ///< combat aircraft and shadow
_disaster_images_8, _disaster_images_8, _disaster_images_9, ///< combat helicopter, shadow and rotor
_disaster_images_6, _disaster_images_6, ///< big ufo and shadow
_disaster_images_7, _disaster_images_7, ///< skyranger and shadow
_disaster_images_4, _disaster_images_5, ///< small and big submarine sprites
};
static void DisasterVehicleUpdateImage(Vehicle *v)
{
SpriteID img = v->u.disaster.image_override;
if (img == 0) img = _disaster_images[v->subtype][v->direction];
v->cur_image = img;
}
/** Initialize a disaster vehicle. These vehicles are of type VEH_DISASTER, are unclickable
* and owned by nobody */
static void InitializeDisasterVehicle(Vehicle *v, int x, int y, byte z, Direction direction, byte subtype)
{
v->x_pos = x;
v->y_pos = y;
v->z_pos = z;
v->tile = TileVirtXY(x, y);
v->direction = direction;
v->subtype = subtype;
v->UpdateDeltaXY(INVALID_DIR);
v->owner = OWNER_NONE;
v->vehstatus = VS_UNCLICKABLE;
v->u.disaster.image_override = 0;
v->current_order.Free();
DisasterVehicleUpdateImage(v);
VehicleMove(v, false);
MarkSingleVehicleDirty(v);
}
static void SetDisasterVehiclePos(Vehicle *v, int x, int y, byte z)
{
Vehicle *u;
v->x_pos = x;
v->y_pos = y;
v->z_pos = z;
v->tile = TileVirtXY(x, y);
DisasterVehicleUpdateImage(v);
VehicleMove(v, true);
if ((u = v->Next()) != NULL) {
int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
u->x_pos = x;
u->y_pos = y - 1 - (max(z - GetSlopeZ(safe_x, safe_y), 0U) >> 3);
safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
u->z_pos = GetSlopeZ(safe_x, safe_y);
u->direction = v->direction;
DisasterVehicleUpdateImage(u);
VehicleMove(u, true);
if ((u = u->Next()) != NULL) {
u->x_pos = x;
u->y_pos = y;
u->z_pos = z + 5;
VehicleMove(u, true);
}
}
}
/**
* Zeppeliner handling, v->current_order.dest states:
* 0: Zeppeliner initialization has found a small airport, go there and crash
* 1: Create crash and animate falling down for extra dramatic effect
* 2: Create more smoke and leave debris on ground
* 2: Clear the runway after some time and remove crashed zeppeliner
* If not airport was found, only state 0 is reached until zeppeliner leaves map
*/
static void DisasterTick_Zeppeliner(Vehicle *v)
{
Station *st;
int x, y;
byte z;
TileIndex tile;
v->tick_counter++;
if (v->current_order.GetDestination() < 2) {
if (HasBit(v->tick_counter, 0)) return;
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
if (v->current_order.GetDestination() == 1) {
if (++v->age == 38) {
v->current_order.SetDestination(2);
v->age = 0;
}
if (GB(v->tick_counter, 0, 3) == 0) CreateEffectVehicleRel(v, 0, -17, 2, EV_SMOKE);
} else if (v->current_order.GetDestination() == 0) {
tile = v->tile;
if (IsValidTile(tile) &&
IsTileType(tile, MP_STATION) &&
IsAirport(tile)) {
v->current_order.SetDestination(1);
v->age = 0;
SetDParam(0, GetStationIndex(tile));
AddNewsItem(STR_B000_ZEPPELIN_DISASTER_AT,
NS_ACCIDENT_VEHICLE,
v->index,
0);
AI::NewEvent(GetTileOwner(tile), new AIEventDisasterZeppelinerCrashed(GetStationIndex(tile)));
}
}
if (v->y_pos >= ((int)MapSizeY() + 9) * TILE_SIZE - 1) delete v;
return;
}
if (v->current_order.GetDestination() > 2) {
if (++v->age <= 13320) return;
tile = v->tile;
if (IsValidTile(tile) &&
IsTileType(tile, MP_STATION) &&
IsAirport(tile)) {
st = GetStationByTile(tile);
CLRBITS(st->airport_flags, RUNWAY_IN_block);
AI::NewEvent(GetTileOwner(tile), new AIEventDisasterZeppelinerCleared(st->index));
}
SetDisasterVehiclePos(v, v->x_pos, v->y_pos, v->z_pos);
delete v;
return;
}
x = v->x_pos;
y = v->y_pos;
z = GetSlopeZ(x, y);
if (z < v->z_pos) z = v->z_pos - 1;
SetDisasterVehiclePos(v, x, y, z);
if (++v->age == 1) {
CreateEffectVehicleRel(v, 0, 7, 8, EV_EXPLOSION_LARGE);
SndPlayVehicleFx(SND_12_EXPLOSION, v);
v->u.disaster.image_override = SPR_BLIMP_CRASHING;
} else if (v->age == 70) {
v->u.disaster.image_override = SPR_BLIMP_CRASHED;
} else if (v->age <= 300) {
if (GB(v->tick_counter, 0, 3) == 0) {
uint32 r = Random();
CreateEffectVehicleRel(v,
GB(r, 0, 4) - 7,
GB(r, 4, 4) - 7,
GB(r, 8, 3) + 5,
EV_EXPLOSION_SMALL);
}
} else if (v->age == 350) {
v->current_order.SetDestination(3);
v->age = 0;
}
tile = v->tile;
if (IsValidTile(tile) &&
IsTileType(tile, MP_STATION) &&
IsAirport(tile)) {
st = GetStationByTile(tile);
SETBITS(st->airport_flags, RUNWAY_IN_block);
}
}
/**
* (Small) Ufo handling, v->current_order.dest states:
* 0: Fly around to the middle of the map, then randomly, after a while target a road vehicle
* 1: Home in on a road vehicle and crash it >:)
* If not road vehicle was found, only state 0 is used and Ufo disappears after a while
*/
static void DisasterTick_Ufo(Vehicle *v)
{
Vehicle *u;
uint dist;
byte z;
v->u.disaster.image_override = (HasBit(++v->tick_counter, 3)) ? SPR_UFO_SMALL_SCOUT_DARKER : SPR_UFO_SMALL_SCOUT;
if (v->current_order.GetDestination() == 0) {
/* Fly around randomly */
int x = TileX(v->dest_tile) * TILE_SIZE;
int y = TileY(v->dest_tile) * TILE_SIZE;
if (Delta(x, v->x_pos) + Delta(y, v->y_pos) >= TILE_SIZE) {
v->direction = GetDirectionTowards(v, x, y);
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
return;
}
if (++v->age < 6) {
v->dest_tile = RandomTile();
return;
}
v->current_order.SetDestination(1);
FOR_ALL_VEHICLES(u) {
if (u->type == VEH_ROAD && IsRoadVehFront(u)) {
v->dest_tile = u->index;
v->age = 0;
return;
}
}
delete v;
} else {
/* Target a vehicle */
u = GetVehicle(v->dest_tile);
if (u->type != VEH_ROAD || !IsRoadVehFront(u)) {
delete v;
return;
}
dist = Delta(v->x_pos, u->x_pos) + Delta(v->y_pos, u->y_pos);
if (dist < TILE_SIZE && !(u->vehstatus & VS_HIDDEN) && u->breakdown_ctr == 0) {
u->breakdown_ctr = 3;
u->breakdown_delay = 140;
}
v->direction = GetDirectionTowards(v, u->x_pos, u->y_pos);
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
z = v->z_pos;
if (dist <= TILE_SIZE && z > u->z_pos) z--;
SetDisasterVehiclePos(v, gp.x, gp.y, z);
if (z <= u->z_pos && (u->vehstatus & VS_HIDDEN) == 0) {
v->age++;
if (u->u.road.crashed_ctr == 0) {
u->u.road.crashed_ctr++;
AddNewsItem(STR_B001_ROAD_VEHICLE_DESTROYED,
NS_ACCIDENT_VEHICLE,
u->index,
0);
AI::NewEvent(u->owner, new AIEventVehicleCrashed(u->index, u->tile, AIEventVehicleCrashed::CRASH_RV_UFO));
for (Vehicle *w = u; w != NULL; w = w->Next()) {
w->vehstatus |= VS_CRASHED;
MarkSingleVehicleDirty(w);
}
}
}
/* Destroy? */
if (v->age > 50) {
CreateEffectVehicleRel(v, 0, 7, 8, EV_EXPLOSION_LARGE);
SndPlayVehicleFx(SND_12_EXPLOSION, v);
delete v;
}
}
}
static void DestructIndustry(Industry *i)
{
TileIndex tile;
for (tile = 0; tile != MapSize(); tile++) {
if (IsTileType(tile, MP_INDUSTRY) && GetIndustryIndex(tile) == i->index) {
ResetIndustryConstructionStage(tile);
MarkTileDirtyByTile(tile);
}
}
}
/**
* Airplane handling, v->current_order.dest states:
* 0: Fly towards the targetted oil refinery
* 1: If within 15 tiles, fire away rockets and destroy industry
* 2: Refinery explosions
* 3: Fly out of the map
* If the industry was removed in the meantime just fly to the end of the map
*/
static void DisasterTick_Airplane(Vehicle *v)
{
v->tick_counter++;
v->u.disaster.image_override =
(v->current_order.GetDestination() == 1 && HasBit(v->tick_counter, 2)) ? SPR_F_15_FIRING : 0;
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
if (gp.x < (-10 * TILE_SIZE)) {
delete v;
return;
}
if (v->current_order.GetDestination() == 2) {
if (GB(v->tick_counter, 0, 2) == 0) {
Industry *i = GetIndustry(v->dest_tile);
int x = TileX(i->xy) * TILE_SIZE;
int y = TileY(i->xy) * TILE_SIZE;
uint32 r = Random();
CreateEffectVehicleAbove(
GB(r, 0, 6) + x,
GB(r, 6, 6) + y,
GB(r, 12, 4),
EV_EXPLOSION_SMALL);
if (++v->age >= 55) v->current_order.SetDestination(3);
}
} else if (v->current_order.GetDestination() == 1) {
if (++v->age == 112) {
Industry *i;
v->current_order.SetDestination(2);
v->age = 0;
i = GetIndustry(v->dest_tile);
DestructIndustry(i);
SetDParam(0, i->town->index);
AddNewsItem(STR_B002_OIL_REFINERY_EXPLOSION, NS_ACCIDENT_TILE, i->xy, 0);
SndPlayTileFx(SND_12_EXPLOSION, i->xy);
}
} else if (v->current_order.GetDestination() == 0) {
int x, y;
TileIndex tile;
uint ind;
x = v->x_pos - (15 * TILE_SIZE);
y = v->y_pos;
if ( (uint)x > MapMaxX() * TILE_SIZE - 1) return;
tile = TileVirtXY(x, y);
if (!IsTileType(tile, MP_INDUSTRY)) return;
ind = GetIndustryIndex(tile);
v->dest_tile = ind;
if (GetIndustrySpec(GetIndustry(ind)->type)->behaviour & INDUSTRYBEH_AIRPLANE_ATTACKS) {
v->current_order.SetDestination(1);
v->age = 0;
}
}
}
/**
* Helicopter handling, v->current_order.dest states:
* 0: Fly towards the targetted factory
* 1: If within 15 tiles, fire away rockets and destroy industry
* 2: Factory explosions
* 3: Fly out of the map
*/
static void DisasterTick_Helicopter(Vehicle *v)
{
v->tick_counter++;
v->u.disaster.image_override =
(v->current_order.GetDestination() == 1 && HasBit(v->tick_counter, 2)) ? SPR_AH_64A_FIRING : 0;
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
if (gp.x > (int)MapSizeX() * TILE_SIZE + 9 * TILE_SIZE - 1) {
delete v;
return;
}
if (v->current_order.GetDestination() == 2) {
if (GB(v->tick_counter, 0, 2) == 0) {
Industry *i = GetIndustry(v->dest_tile);
int x = TileX(i->xy) * TILE_SIZE;
int y = TileY(i->xy) * TILE_SIZE;
uint32 r = Random();
CreateEffectVehicleAbove(
GB(r, 0, 6) + x,
GB(r, 6, 6) + y,
GB(r, 12, 4),
EV_EXPLOSION_SMALL);
if (++v->age >= 55) v->current_order.SetDestination(3);
}
} else if (v->current_order.GetDestination() == 1) {
if (++v->age == 112) {
Industry *i;
v->current_order.SetDestination(2);
v->age = 0;
i = GetIndustry(v->dest_tile);
DestructIndustry(i);
SetDParam(0, i->town->index);
AddNewsItem(STR_B003_FACTORY_DESTROYED_IN_SUSPICIOUS, NS_ACCIDENT_TILE, i->xy, 0);
SndPlayTileFx(SND_12_EXPLOSION, i->xy);
}
} else if (v->current_order.GetDestination() == 0) {
int x, y;
TileIndex tile;
uint ind;
x = v->x_pos + (15 * TILE_SIZE);
y = v->y_pos;
if ( (uint)x > MapMaxX() * TILE_SIZE - 1) return;
tile = TileVirtXY(x, y);
if (!IsTileType(tile, MP_INDUSTRY)) return;
ind = GetIndustryIndex(tile);
v->dest_tile = ind;
if (GetIndustrySpec(GetIndustry(ind)->type)->behaviour & INDUSTRYBEH_CHOPPER_ATTACKS) {
v->current_order.SetDestination(1);
v->age = 0;
}
}
}
/** Helicopter rotor blades; keep these spinning */
static void DisasterTick_Helicopter_Rotors(Vehicle *v)
{
v->tick_counter++;
if (HasBit(v->tick_counter, 0)) return;
if (++v->cur_image > SPR_ROTOR_MOVING_3) v->cur_image = SPR_ROTOR_MOVING_1;
VehicleMove(v, true);
}
/**
* (Big) Ufo handling, v->current_order.dest states:
* 0: Fly around to the middle of the map, then randomly for a while and home in on a piece of rail
* 1: Land there and breakdown all trains in a radius of 12 tiles; and now we wait...
* because as soon as the Ufo lands, a fighter jet, a Skyranger, is called to clear up the mess
*/
static void DisasterTick_Big_Ufo(Vehicle *v)
{
byte z;
Town *t;
TileIndex tile;
TileIndex tile_org;
v->tick_counter++;
if (v->current_order.GetDestination() == 1) {
int x = TileX(v->dest_tile) * TILE_SIZE + TILE_SIZE / 2;
int y = TileY(v->dest_tile) * TILE_SIZE + TILE_SIZE / 2;
if (Delta(v->x_pos, x) + Delta(v->y_pos, y) >= 8) {
v->direction = GetDirectionTowards(v, x, y);
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
return;
}
if (!IsValidTile(v->dest_tile)) {
/* Make sure we don't land outside the map. */
delete v;
return;
}
z = GetSlopeZ(v->x_pos, v->y_pos);
if (z < v->z_pos) {
SetDisasterVehiclePos(v, v->x_pos, v->y_pos, v->z_pos - 1);
return;
}
v->current_order.SetDestination(2);
Vehicle *u;
FOR_ALL_VEHICLES(u) {
if (u->type == VEH_TRAIN || u->type == VEH_ROAD) {
if (Delta(u->x_pos, v->x_pos) + Delta(u->y_pos, v->y_pos) <= 12 * TILE_SIZE) {
u->breakdown_ctr = 5;
u->breakdown_delay = 0xF0;
}
}
}
t = ClosestTownFromTile(v->dest_tile, UINT_MAX);
SetDParam(0, t->index);
AddNewsItem(STR_B004_UFO_LANDS_NEAR,
NS_ACCIDENT_TILE,
v->tile,
0);
if (!Vehicle::CanAllocateItem(2)) {
delete v;
return;
}
u = new DisasterVehicle();
InitializeDisasterVehicle(u, -6 * TILE_SIZE, v->y_pos, 135, DIR_SW, ST_BIG_UFO_DESTROYER);
u->u.disaster.big_ufo_destroyer_target = v->index;
Vehicle *w = new DisasterVehicle();
u->SetNext(w);
InitializeDisasterVehicle(w, -6 * TILE_SIZE, v->y_pos, 0, DIR_SW, ST_BIG_UFO_DESTROYER_SHADOW);
w->vehstatus |= VS_SHADOW;
} else if (v->current_order.GetDestination() == 0) {
int x = TileX(v->dest_tile) * TILE_SIZE;
int y = TileY(v->dest_tile) * TILE_SIZE;
if (Delta(x, v->x_pos) + Delta(y, v->y_pos) >= TILE_SIZE) {
v->direction = GetDirectionTowards(v, x, y);
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
return;
}
if (++v->age < 6) {
v->dest_tile = RandomTile();
return;
}
v->current_order.SetDestination(1);
tile_org = tile = RandomTile();
do {
if (IsTileType(tile, MP_RAILWAY) &&
IsPlainRailTile(tile) &&
IsHumanCompany(GetTileOwner(tile))) {
break;
}
tile = TILE_MASK(tile + 1);
} while (tile != tile_org);
v->dest_tile = tile;
v->age = 0;
} else {
return;
}
}
/**
* Skyranger destroying (Big) Ufo handling, v->current_order.dest states:
* 0: Home in on landed Ufo and shoot it down
*/
static void DisasterTick_Big_Ufo_Destroyer(Vehicle *v)
{
Vehicle *u;
int i;
v->tick_counter++;
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
if (gp.x > (int)MapSizeX() * TILE_SIZE + 9 * TILE_SIZE - 1) {
delete v;
return;
}
if (v->current_order.GetDestination() == 0) {
u = GetVehicle(v->u.disaster.big_ufo_destroyer_target);
if (Delta(v->x_pos, u->x_pos) > TILE_SIZE) return;
v->current_order.SetDestination(1);
CreateEffectVehicleRel(u, 0, 7, 8, EV_EXPLOSION_LARGE);
SndPlayVehicleFx(SND_12_EXPLOSION, u);
delete u;
for (i = 0; i != 80; i++) {
uint32 r = Random();
CreateEffectVehicleAbove(
GB(r, 0, 6) + v->x_pos - 32,
GB(r, 5, 6) + v->y_pos - 32,
0,
EV_EXPLOSION_SMALL);
}
for (int dy = -3; dy < 3; dy++) {
for (int dx = -3; dx < 3; dx++) {
TileIndex tile = TileAddWrap(v->tile, dx, dy);
if (tile != INVALID_TILE) DisasterClearSquare(tile);
}
}
}
}
/**
* Submarine, v->current_order.dest states:
* Unused, just float around aimlessly and pop up at different places, turning around
*/
static void DisasterTick_Submarine(Vehicle *v)
{
TileIndex tile;
v->tick_counter++;
if (++v->age > 8880) {
delete v;
return;
}
if (!HasBit(v->tick_counter, 0)) return;
tile = v->tile + TileOffsByDiagDir(DirToDiagDir(v->direction));
if (IsValidTile(tile)) {
TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
if (trackbits == TRACK_BIT_ALL && !Chance16(1, 90)) {
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
return;
}
}
v->direction = ChangeDir(v->direction, GB(Random(), 0, 1) ? DIRDIFF_90RIGHT : DIRDIFF_90LEFT);
}
static void DisasterTick_NULL(Vehicle *v) {}
typedef void DisasterVehicleTickProc(Vehicle *v);
static DisasterVehicleTickProc * const _disastervehicle_tick_procs[] = {
DisasterTick_Zeppeliner, DisasterTick_NULL,
DisasterTick_Ufo, DisasterTick_NULL,
DisasterTick_Airplane, DisasterTick_NULL,
DisasterTick_Helicopter, DisasterTick_NULL, DisasterTick_Helicopter_Rotors,
DisasterTick_Big_Ufo, DisasterTick_NULL, DisasterTick_Big_Ufo_Destroyer,
DisasterTick_NULL,
DisasterTick_Submarine,
DisasterTick_Submarine,
};
void DisasterVehicle::Tick()
{
_disastervehicle_tick_procs[this->subtype](this);
}
typedef void DisasterInitProc();
/** Zeppeliner which crashes on a small airport if one found,
* otherwise crashes on a random tile */
static void Disaster_Zeppeliner_Init()
{
if (!Vehicle::CanAllocateItem(2)) return;
Vehicle *v = new DisasterVehicle();
Station *st;
/* Pick a random place, unless we find a small airport */
int x = TileX(Random()) * TILE_SIZE + TILE_SIZE / 2;
FOR_ALL_STATIONS(st) {
if (st->airport_tile != INVALID_TILE && (st->airport_type == AT_SMALL || st->airport_type == AT_LARGE)) {
x = (TileX(st->airport_tile) + 2) * TILE_SIZE;
break;
}
}
InitializeDisasterVehicle(v, x, 0, 135, DIR_SE, ST_ZEPPELINER);
/* Allocate shadow */
Vehicle *u = new DisasterVehicle();
v->SetNext(u);
InitializeDisasterVehicle(u, x, 0, 0, DIR_SE, ST_ZEPPELINER_SHADOW);
u->vehstatus |= VS_SHADOW;
}
/** Ufo which flies around aimlessly from the middle of the map a bit
* until it locates a road vehicle which it targets and then destroys */
static void Disaster_Small_Ufo_Init()
{
if (!Vehicle::CanAllocateItem(2)) return;
Vehicle *v = new DisasterVehicle();
int x = TileX(Random()) * TILE_SIZE + TILE_SIZE / 2;
InitializeDisasterVehicle(v, x, 0, 135, DIR_SE, ST_SMALL_UFO);
v->dest_tile = TileXY(MapSizeX() / 2, MapSizeY() / 2);
v->age = 0;
/* Allocate shadow */
Vehicle *u = new DisasterVehicle();
v->SetNext(u);
InitializeDisasterVehicle(u, x, 0, 0, DIR_SE, ST_SMALL_UFO_SHADOW);
u->vehstatus |= VS_SHADOW;
}
/* Combat airplane which destroys an oil refinery */
static void Disaster_Airplane_Init()
{
if (!Vehicle::CanAllocateItem(2)) return;
Industry *i, *found = NULL;
FOR_ALL_INDUSTRIES(i) {
if ((GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_AIRPLANE_ATTACKS) &&
(found == NULL || Chance16(1, 2))) {
found = i;
}
}
if (found == NULL) return;
Vehicle *v = new DisasterVehicle();
/* Start from the bottom (south side) of the map */
int x = (MapSizeX() + 9) * TILE_SIZE - 1;
int y = TileY(found->xy) * TILE_SIZE + 37;
InitializeDisasterVehicle(v, x, y, 135, DIR_NE, ST_AIRPLANE);
Vehicle *u = new DisasterVehicle();
v->SetNext(u);
InitializeDisasterVehicle(u, x, y, 0, DIR_SE, ST_AIRPLANE_SHADOW);
u->vehstatus |= VS_SHADOW;
}
/** Combat helicopter that destroys a factory */
static void Disaster_Helicopter_Init()
{
if (!Vehicle::CanAllocateItem(3)) return;
Industry *i, *found = NULL;
FOR_ALL_INDUSTRIES(i) {
if ((GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_CHOPPER_ATTACKS) &&
(found == NULL || Chance16(1, 2))) {
found = i;
}
}
if (found == NULL) return;
Vehicle *v = new DisasterVehicle();
int x = -16 * TILE_SIZE;
int y = TileY(found->xy) * TILE_SIZE + 37;
InitializeDisasterVehicle(v, x, y, 135, DIR_SW, ST_HELICOPTER);
Vehicle *u = new DisasterVehicle();
v->SetNext(u);
InitializeDisasterVehicle(u, x, y, 0, DIR_SW, ST_HELICOPTER_SHADOW);
u->vehstatus |= VS_SHADOW;
Vehicle *w = new DisasterVehicle();
u->SetNext(w);
InitializeDisasterVehicle(w, x, y, 140, DIR_SW, ST_HELICOPTER_ROTORS);
}
/* Big Ufo which lands on a piece of rail and will consequently be shot
* down by a combat airplane, destroying the surroundings */
static void Disaster_Big_Ufo_Init()
{
if (!Vehicle::CanAllocateItem(2)) return;
Vehicle *v = new DisasterVehicle();
int x = TileX(Random()) * TILE_SIZE + TILE_SIZE / 2;
int y = MapMaxX() * TILE_SIZE - 1;
InitializeDisasterVehicle(v, x, y, 135, DIR_NW, ST_BIG_UFO);
v->dest_tile = TileXY(MapSizeX() / 2, MapSizeY() / 2);
v->age = 0;
/* Allocate shadow */
Vehicle *u = new DisasterVehicle();
v->SetNext(u);
InitializeDisasterVehicle(u, x, y, 0, DIR_NW, ST_BIG_UFO_SHADOW);
u->vehstatus |= VS_SHADOW;
}
static void Disaster_Submarine_Init(DisasterSubType subtype)
{
if (!Vehicle::CanAllocateItem()) return;
int y;
Direction dir;
uint32 r = Random();
int x = TileX(r) * TILE_SIZE + TILE_SIZE / 2;
if (HasBit(r, 31)) {
y = MapMaxY() * TILE_SIZE - TILE_SIZE / 2 - 1;
dir = DIR_NW;
} else {
y = TILE_SIZE / 2;
if (_settings_game.construction.freeform_edges) y += TILE_SIZE;
dir = DIR_SE;
}
if (!IsWaterTile(TileVirtXY(x, y))) return;
Vehicle *v = new DisasterVehicle();
InitializeDisasterVehicle(v, x, y, 0, dir, subtype);
v->age = 0;
}
/* Curious submarine #1, just floats around */
static void Disaster_Small_Submarine_Init()
{
Disaster_Submarine_Init(ST_SMALL_SUBMARINE);
}
/* Curious submarine #2, just floats around */
static void Disaster_Big_Submarine_Init()
{
Disaster_Submarine_Init(ST_BIG_SUBMARINE);
}
/** Coal mine catastrophe, destroys a stretch of 30 tiles of
* land in a certain direction */
static void Disaster_CoalMine_Init()
{
int index = GB(Random(), 0, 4);
uint m;
for (m = 0; m < 15; m++) {
const Industry *i;
FOR_ALL_INDUSTRIES(i) {
if ((GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_CAN_SUBSIDENCE) && --index < 0) {
SetDParam(0, i->town->index);
AddNewsItem(STR_B005_COAL_MINE_SUBSIDENCE_LEAVES,
NS_ACCIDENT_TILE, i->xy + TileDiffXY(1, 1), 0);
{
TileIndex tile = i->xy;
TileIndexDiff step = TileOffsByDiagDir((DiagDirection)GB(Random(), 0, 2));
for (uint n = 0; n < 30; n++) {
DisasterClearSquare(tile);
tile += step;
if (!IsValidTile(tile)) break;
}
}
return;
}
}
}
}
static DisasterInitProc * const _disaster_initprocs[] = {
Disaster_Zeppeliner_Init,
Disaster_Small_Ufo_Init,
Disaster_Airplane_Init,
Disaster_Helicopter_Init,
Disaster_Big_Ufo_Init,
Disaster_Small_Submarine_Init,
Disaster_Big_Submarine_Init,
Disaster_CoalMine_Init,
};
static const struct {
Year min;
Year max;
} _dis_years[] = {
{ 1930, 1955 }, ///< zeppeliner
{ 1940, 1970 }, ///< ufo (small)
{ 1960, 1990 }, ///< airplane
{ 1970, 2000 }, ///< helicopter
{ 2000, 2100 }, ///< ufo (big)
{ 1940, 1965 }, ///< submarine (small)
{ 1975, 2010 }, ///< submarine (big)
{ 1950, 1985 } ///< coalmine
};
static void DoDisaster()
{
byte buf[lengthof(_dis_years)];
uint i;
uint j;
j = 0;
for (i = 0; i != lengthof(_dis_years); i++) {
if (_cur_year >= _dis_years[i].min && _cur_year < _dis_years[i].max) buf[j++] = i;
}
if (j == 0) return;
_disaster_initprocs[buf[RandomRange(j)]]();
}
static void ResetDisasterDelay()
{
_disaster_delay = GB(Random(), 0, 9) + 730;
}
void DisasterDailyLoop()
{
if (--_disaster_delay != 0) return;
ResetDisasterDelay();
if (_settings_game.difficulty.disasters != 0) DoDisaster();
}
void StartupDisasters()
{
ResetDisasterDelay();
}
/** Marks all disasters targeting this industry in such a way
* they won't call GetIndustry(v->dest_tile) on invalid industry anymore.
* @param i deleted industry
*/
void ReleaseDisastersTargetingIndustry(IndustryID i)
{
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* primary disaster vehicles that have chosen target */
if (v->type == VEH_DISASTER && (v->subtype == ST_AIRPLANE || v->subtype == ST_HELICOPTER)) {
/* if it has chosen target, and it is this industry (yes, dest_tile is IndustryID here), set order to "leaving map peacefully" */
if (v->current_order.GetDestination() > 0 && v->dest_tile == i) v->current_order.SetDestination(3);
}
}
}
void DisasterVehicle::UpdateDeltaXY(Direction direction)
{
this->x_offs = -1;
this->y_offs = -1;
this->x_extent = 2;
this->y_extent = 2;
this->z_extent = 5;
}
| 28,285
|
C++
|
.cpp
| 848
| 30.518868
| 214
| 0.672612
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,006
|
graph_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/graph_gui.cpp
|
/* $Id$ */
/** @file graph_gui.cpp GUI that shows performance graphs. */
#include "stdafx.h"
#include "openttd.h"
#include "gui.h"
#include "window_gui.h"
#include "company_base.h"
#include "company_gui.h"
#include "economy_func.h"
#include "cargotype.h"
#include "strings_func.h"
#include "window_func.h"
#include "date_func.h"
#include "gfx_func.h"
#include "sortlist_type.h"
#include "table/strings.h"
/* Bitmasks of company and cargo indices that shouldn't be drawn. */
static uint _legend_excluded_companies;
static uint _legend_excluded_cargo;
/* Apparently these don't play well with enums. */
static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX); // Value used for a datapoint that shouldn't be drawn.
static const uint INVALID_DATAPOINT_POS = UINT_MAX; // Used to determine if the previous point was drawn.
/****************/
/* GRAPH LEGEND */
/****************/
struct GraphLegendWindow : Window {
GraphLegendWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
for (uint i = 3; i < this->widget_count; i++) {
if (!HasBit(_legend_excluded_companies, i - 3)) this->LowerWidget(i);
}
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (IsValidCompanyID(c)) continue;
SetBit(_legend_excluded_companies, c);
this->RaiseWidget(c + 3);
}
this->DrawWidgets();
const Company *c;
FOR_ALL_COMPANIES(c) {
DrawCompanyIcon(c->index, 4, 18 + c->index * 12);
SetDParam(0, c->index);
SetDParam(1, c->index);
DrawString(21, 17 + c->index * 12, STR_7021, HasBit(_legend_excluded_companies, c->index) ? TC_BLACK : TC_WHITE);
}
}
virtual void OnClick(Point pt, int widget)
{
if (!IsInsideMM(widget, 3, MAX_COMPANIES + 3)) return;
ToggleBit(_legend_excluded_companies, widget - 3);
this->ToggleWidgetLoweredState(widget);
this->SetDirty();
InvalidateWindow(WC_INCOME_GRAPH, 0);
InvalidateWindow(WC_OPERATING_PROFIT, 0);
InvalidateWindow(WC_DELIVERED_CARGO, 0);
InvalidateWindow(WC_PERFORMANCE_HISTORY, 0);
InvalidateWindow(WC_COMPANY_VALUE, 0);
}
};
static const Widget _graph_legend_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 249, 0, 13, STR_704E_KEY_TO_COMPANY_GRAPHS, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 249, 14, 195, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 16, 27, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 28, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 40, 51, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 52, 63, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 64, 75, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 76, 87, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 88, 99, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 100, 111, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 112, 123, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 124, 135, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 136, 147, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 148, 159, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 160, 171, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 172, 183, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 247, 184, 195, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WIDGETS_END},
};
static const WindowDesc _graph_legend_desc(
WDP_AUTO, WDP_AUTO, 250, 198, 250, 198,
WC_GRAPH_LEGEND, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_graph_legend_widgets
);
static void ShowGraphLegend()
{
AllocateWindowDescFront<GraphLegendWindow>(&_graph_legend_desc, 0);
}
/******************/
/* BASE OF GRAPHS */
/*****************/
struct BaseGraphWindow : Window {
protected:
enum {
GRAPH_MAX_DATASETS = 32,
GRAPH_AXIS_LINE_COLOUR = 215,
GRAPH_X_POSITION_BEGINNING = 44, ///< Start the graph 44 pixels from gd_left
GRAPH_X_POSITION_SEPARATION = 22, ///< There are 22 pixels between each X value
GRAPH_NUM_LINES_Y = 9, ///< How many horizontal lines to draw.
/* 9 is convenient as that means the distance between them is the gd_height of the graph / 8,
* which is the same
* as height >> 3. */
};
uint excluded_data; ///< bitmask of the datasets that shouldn't be displayed.
byte num_dataset;
byte num_on_x_axis;
bool has_negative_values;
byte num_vert_lines;
static const TextColour graph_axis_label_colour = TC_BLACK; ///< colour of the graph axis label.
/* The starting month and year that values are plotted against. If month is
* 0xFF, use x_values_start and x_values_increment below instead. */
byte month;
Year year;
/* These values are used if the graph is being plotted against values
* rather than the dates specified by month and year. */
uint16 x_values_start;
uint16 x_values_increment;
int gd_left, gd_top; ///< Where to start drawing the graph, in pixels.
uint gd_height; ///< The height of the graph in pixels.
StringID format_str_y_axis;
byte colours[GRAPH_MAX_DATASETS];
OverflowSafeInt64 cost[GRAPH_MAX_DATASETS][24]; ///< last 2 years
void DrawGraph() const
{
uint x, y; ///< Reused whenever x and y coordinates are needed.
OverflowSafeInt64 highest_value; ///< Highest value to be drawn.
int x_axis_offset; ///< Distance from the top of the graph to the x axis.
/* the colours and cost array of GraphDrawer must accomodate
* both values for cargo and companies. So if any are higher, quit */
assert(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES);
assert(this->num_vert_lines > 0);
byte grid_colour = _colour_gradient[COLOUR_GREY][4];
/* The coordinates of the opposite edges of the graph. */
int bottom = this->gd_top + this->gd_height - 1;
int right = this->gd_left + GRAPH_X_POSITION_BEGINNING + this->num_vert_lines * GRAPH_X_POSITION_SEPARATION - 1;
/* Draw the vertical grid lines. */
/* Don't draw the first line, as that's where the axis will be. */
x = this->gd_left + GRAPH_X_POSITION_BEGINNING + GRAPH_X_POSITION_SEPARATION;
for (int i = 0; i < this->num_vert_lines; i++) {
GfxFillRect(x, this->gd_top, x, bottom, grid_colour);
x += GRAPH_X_POSITION_SEPARATION;
}
/* Draw the horizontal grid lines. */
x = this->gd_left + GRAPH_X_POSITION_BEGINNING;
y = this->gd_height + this->gd_top;
for (int i = 0; i < GRAPH_NUM_LINES_Y; i++) {
GfxFillRect(x, y, right, y, grid_colour);
y -= (this->gd_height / (GRAPH_NUM_LINES_Y - 1));
}
/* Draw the y axis. */
GfxFillRect(x, this->gd_top, x, bottom, GRAPH_AXIS_LINE_COLOUR);
/* Find the distance from the gd_top of the graph to the x axis. */
x_axis_offset = this->gd_height;
/* The graph is currently symmetrical about the x axis. */
if (this->has_negative_values) x_axis_offset /= 2;
/* Draw the x axis. */
y = x_axis_offset + this->gd_top;
GfxFillRect(x, y, right, y, GRAPH_AXIS_LINE_COLOUR);
/* Find the largest value that will be drawn. */
if (this->num_on_x_axis == 0)
return;
assert(this->num_on_x_axis > 0);
assert(this->num_dataset > 0);
/* Start of with a value of twice the gd_height of the graph in pixels. It's a
* bit arbitrary, but it makes the cargo payment graph look a little nicer,
* and prevents division by zero when calculating where the datapoint
* should be drawn. */
highest_value = x_axis_offset * 2;
for (int i = 0; i < this->num_dataset; i++) {
if (!HasBit(this->excluded_data, i)) {
for (int j = 0; j < this->num_on_x_axis; j++) {
OverflowSafeInt64 datapoint = this->cost[i][j];
if (datapoint != INVALID_DATAPOINT) {
/* For now, if the graph has negative values the scaling is
* symmetrical about the x axis, so take the absolute value
* of each data point. */
highest_value = max(highest_value, abs(datapoint));
}
}
}
}
/* Round up highest_value so that it will divide cleanly into the number of
* axis labels used. */
int round_val = highest_value % (GRAPH_NUM_LINES_Y - 1);
if (round_val != 0) highest_value += (GRAPH_NUM_LINES_Y - 1 - round_val);
/* draw text strings on the y axis */
int64 y_label = highest_value;
int64 y_label_separation = highest_value / (GRAPH_NUM_LINES_Y - 1);
/* If there are negative values, the graph goes from highest_value to
* -highest_value, not highest_value to 0. */
if (this->has_negative_values) y_label_separation *= 2;
x = this->gd_left + GRAPH_X_POSITION_BEGINNING + 1;
y = this->gd_top - 3;
for (int i = 0; i < GRAPH_NUM_LINES_Y; i++) {
SetDParam(0, this->format_str_y_axis);
SetDParam(1, y_label);
DrawStringRightAligned(x, y, STR_0170, graph_axis_label_colour);
y_label -= y_label_separation;
y += (this->gd_height / (GRAPH_NUM_LINES_Y - 1));
}
/* draw strings on the x axis */
if (this->month != 0xFF) {
x = this->gd_left + GRAPH_X_POSITION_BEGINNING;
y = this->gd_top + this->gd_height + 1;
byte month = this->month;
Year year = this->year;
for (int i = 0; i < this->num_on_x_axis; i++) {
SetDParam(0, month + STR_0162_JAN);
SetDParam(1, month + STR_0162_JAN + 2);
SetDParam(2, year);
DrawString(x, y, month == 0 ? STR_016F : STR_016E, graph_axis_label_colour);
month += 3;
if (month >= 12) {
month = 0;
year++;
}
x += GRAPH_X_POSITION_SEPARATION;
}
} else {
/* Draw the label under the data point rather than on the grid line. */
x = this->gd_left + GRAPH_X_POSITION_BEGINNING + (GRAPH_X_POSITION_SEPARATION / 2) + 1;
y = this->gd_top + this->gd_height + 1;
uint16 label = this->x_values_start;
for (int i = 0; i < this->num_on_x_axis; i++) {
SetDParam(0, label);
DrawStringCentered(x, y, STR_01CB, graph_axis_label_colour);
label += this->x_values_increment;
x += GRAPH_X_POSITION_SEPARATION;
}
}
/* draw lines and dots */
for (int i = 0; i < this->num_dataset; i++) {
if (!HasBit(this->excluded_data, i)) {
/* Centre the dot between the grid lines. */
x = this->gd_left + GRAPH_X_POSITION_BEGINNING + (GRAPH_X_POSITION_SEPARATION / 2);
byte colour = this->colours[i];
uint prev_x = INVALID_DATAPOINT_POS;
uint prev_y = INVALID_DATAPOINT_POS;
for (int j = 0; j < this->num_on_x_axis; j++) {
OverflowSafeInt64 datapoint = this->cost[i][j];
if (datapoint != INVALID_DATAPOINT) {
/*
* Check whether we need to reduce the 'accuracy' of the
* datapoint value and the highest value to splut overflows.
* And when 'drawing' 'one million' or 'one million and one'
* there is no significant difference, so the least
* significant bits can just be removed.
*
* If there are more bits needed than would fit in a 32 bits
* integer, so at about 31 bits because of the sign bit, the
* least significant bits are removed.
*/
int mult_range = FindLastBit(x_axis_offset) + FindLastBit(abs(datapoint));
int reduce_range = max(mult_range - 31, 0);
/* Handle negative values differently (don't shift sign) */
if (datapoint < 0) {
datapoint = -(abs(datapoint) >> reduce_range);
} else {
datapoint >>= reduce_range;
}
y = this->gd_top + x_axis_offset - (x_axis_offset * datapoint) / (highest_value >> reduce_range);
/* Draw the point. */
GfxFillRect(x - 1, y - 1, x + 1, y + 1, colour);
/* Draw the line connected to the previous point. */
if (prev_x != INVALID_DATAPOINT_POS) GfxDrawLine(prev_x, prev_y, x, y, colour);
prev_x = x;
prev_y = y;
} else {
prev_x = INVALID_DATAPOINT_POS;
prev_y = INVALID_DATAPOINT_POS;
}
x += GRAPH_X_POSITION_SEPARATION;
}
}
}
}
BaseGraphWindow(const WindowDesc *desc, WindowNumber window_number, int left,
int top, int height, bool has_negative_values, StringID format_str_y_axis) :
Window(desc, window_number), has_negative_values(has_negative_values),
gd_left(left), gd_top(top), gd_height(height), format_str_y_axis(format_str_y_axis)
{
InvalidateWindow(WC_GRAPH_LEGEND, 0);
}
public:
virtual void OnPaint()
{
this->DrawWidgets();
uint excluded_companies = _legend_excluded_companies;
/* Exclude the companies which aren't valid */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (!IsValidCompanyID(c)) SetBit(excluded_companies, c);
}
this->excluded_data = excluded_companies;
this->num_vert_lines = 24;
byte nums = 0;
const Company *c;
FOR_ALL_COMPANIES(c) {
nums = max(nums, c->num_valid_stat_ent);
}
this->num_on_x_axis = min(nums, 24);
int mo = (_cur_month / 3 - nums) * 3;
int yr = _cur_year;
while (mo < 0) {
yr--;
mo += 12;
}
this->year = yr;
this->month = mo;
int numd = 0;
for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; k++) {
if (IsValidCompanyID(k)) {
c = GetCompany(k);
this->colours[numd] = _colour_gradient[c->colour][6];
for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
this->cost[numd][i] = (j >= c->num_valid_stat_ent) ? INVALID_DATAPOINT : GetGraphData(c, j);
i++;
}
}
numd++;
}
this->num_dataset = numd;
this->DrawGraph();
}
virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
{
return INVALID_DATAPOINT;
}
virtual void OnClick(Point pt, int widget)
{
/* Clicked on legend? */
if (widget == 2) ShowGraphLegend();
}
};
/********************/
/* OPERATING PROFIT */
/********************/
struct OperatingProfitGraphWindow : BaseGraphWindow {
OperatingProfitGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
BaseGraphWindow(desc, window_number, 2, 18, 136, true, STR_CURRCOMPACT)
{
this->FindWindowPlacementAndResize(desc);
}
virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
{
return c->old_economy[j].income + c->old_economy[j].expenses;
}
};
static const Widget _operating_profit_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 525, 0, 13, STR_7025_OPERATING_PROFIT_GRAPH, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 526, 575, 0, 13, STR_704C_KEY, STR_704D_SHOW_KEY_TO_GRAPHS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 575, 14, 173, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _operating_profit_desc(
WDP_AUTO, WDP_AUTO, 576, 174, 576, 174,
WC_OPERATING_PROFIT, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_operating_profit_widgets
);
void ShowOperatingProfitGraph()
{
AllocateWindowDescFront<OperatingProfitGraphWindow>(&_operating_profit_desc, 0);
}
/****************/
/* INCOME GRAPH */
/****************/
struct IncomeGraphWindow : BaseGraphWindow {
IncomeGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
BaseGraphWindow(desc, window_number, 2, 18, 104, false, STR_CURRCOMPACT)
{
this->FindWindowPlacementAndResize(desc);
}
virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
{
return c->old_economy[j].income;
}
};
static const Widget _income_graph_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 525, 0, 13, STR_7022_INCOME_GRAPH, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 526, 575, 0, 13, STR_704C_KEY, STR_704D_SHOW_KEY_TO_GRAPHS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 575, 14, 141, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _income_graph_desc(
WDP_AUTO, WDP_AUTO, 576, 142, 576, 142,
WC_INCOME_GRAPH, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_income_graph_widgets
);
void ShowIncomeGraph()
{
AllocateWindowDescFront<IncomeGraphWindow>(&_income_graph_desc, 0);
}
/*******************/
/* DELIVERED CARGO */
/*******************/
struct DeliveredCargoGraphWindow : BaseGraphWindow {
DeliveredCargoGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
BaseGraphWindow(desc, window_number, 2, 18, 104, false, STR_7024)
{
this->FindWindowPlacementAndResize(desc);
}
virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
{
return c->old_economy[j].delivered_cargo;
}
};
static const Widget _delivered_cargo_graph_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 525, 0, 13, STR_7050_UNITS_OF_CARGO_DELIVERED, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 526, 575, 0, 13, STR_704C_KEY, STR_704D_SHOW_KEY_TO_GRAPHS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 575, 14, 141, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _delivered_cargo_graph_desc(
WDP_AUTO, WDP_AUTO, 576, 142, 576, 142,
WC_DELIVERED_CARGO, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_delivered_cargo_graph_widgets
);
void ShowDeliveredCargoGraph()
{
AllocateWindowDescFront<DeliveredCargoGraphWindow>(&_delivered_cargo_graph_desc, 0);
}
/***********************/
/* PERFORMANCE HISTORY */
/***********************/
struct PerformanceHistoryGraphWindow : BaseGraphWindow {
PerformanceHistoryGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
BaseGraphWindow(desc, window_number, 2, 18, 200, false, STR_7024)
{
this->FindWindowPlacementAndResize(desc);
}
virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
{
return c->old_economy[j].performance_history;
}
virtual void OnClick(Point pt, int widget)
{
if (widget == 3) ShowPerformanceRatingDetail();
this->BaseGraphWindow::OnClick(pt, widget);
}
};
static const Widget _performance_history_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 475, 0, 13, STR_7051_COMPANY_PERFORMANCE_RATINGS, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 526, 575, 0, 13, STR_704C_KEY, STR_704D_SHOW_KEY_TO_GRAPHS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 476, 525, 0, 13, STR_PERFORMANCE_DETAIL_KEY, STR_704D_SHOW_KEY_TO_GRAPHS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 575, 14, 237, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _performance_history_desc(
WDP_AUTO, WDP_AUTO, 576, 238, 576, 238,
WC_PERFORMANCE_HISTORY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_performance_history_widgets
);
void ShowPerformanceHistoryGraph()
{
AllocateWindowDescFront<PerformanceHistoryGraphWindow>(&_performance_history_desc, 0);
}
/*****************/
/* COMPANY VALUE */
/*****************/
struct CompanyValueGraphWindow : BaseGraphWindow {
CompanyValueGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
BaseGraphWindow(desc, window_number, 2, 18, 200, false, STR_CURRCOMPACT)
{
this->FindWindowPlacementAndResize(desc);
}
virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
{
return c->old_economy[j].company_value;
}
};
static const Widget _company_value_graph_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 525, 0, 13, STR_7052_COMPANY_VALUES, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 526, 575, 0, 13, STR_704C_KEY, STR_704D_SHOW_KEY_TO_GRAPHS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 575, 14, 237, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _company_value_graph_desc(
WDP_AUTO, WDP_AUTO, 576, 238, 576, 238,
WC_COMPANY_VALUE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_company_value_graph_widgets
);
void ShowCompanyValueGraph()
{
AllocateWindowDescFront<CompanyValueGraphWindow>(&_company_value_graph_desc, 0);
}
/*****************/
/* PAYMENT RATES */
/*****************/
struct PaymentRatesGraphWindow : BaseGraphWindow {
PaymentRatesGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
BaseGraphWindow(desc, window_number, 2, 24, 200, false, STR_CURRCOMPACT)
{
uint num_active = 0;
for (CargoID c = 0; c < NUM_CARGO; c++) {
if (GetCargo(c)->IsValid()) num_active++;
}
/* Resize the window to fit the cargo types */
ResizeWindow(this, 0, max(num_active, 12U) * 8);
/* Add widgets for each cargo type */
this->widget_count += num_active;
this->widget = ReallocT(this->widget, this->widget_count + 1);
this->widget[this->widget_count].type = WWT_LAST;
/* Set the properties of each widget */
for (uint i = 0; i != num_active; i++) {
Widget *wi = &this->widget[3 + i];
wi->type = WWT_PANEL;
wi->display_flags = RESIZE_NONE;
wi->colour = COLOUR_ORANGE;
wi->left = 493;
wi->right = 562;
wi->top = 24 + i * 8;
wi->bottom = wi->top + 7;
wi->data = 0;
wi->tooltips = STR_7064_TOGGLE_GRAPH_FOR_CARGO;
if (!HasBit(_legend_excluded_cargo, i)) this->LowerWidget(i + 3);
}
this->SetDirty();
this->gd_height = this->height - 38;
this->num_on_x_axis = 20;
this->num_vert_lines = 20;
this->month = 0xFF;
this->x_values_start = 10;
this->x_values_increment = 10;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
this->excluded_data = _legend_excluded_cargo;
int x = 495;
int y = 24;
uint i = 0;
for (CargoID c = 0; c < NUM_CARGO; c++) {
const CargoSpec *cs = GetCargo(c);
if (!cs->IsValid()) continue;
/* Only draw labels for widgets that exist. If the widget doesn't
* exist then the local company has used the climate cheat or
* changed the NewGRF configuration with this window open. */
if (i + 3 < this->widget_count) {
/* Since the buttons have no text, no images,
* both the text and the coloured box have to be manually painted.
* clk_dif will move one pixel down and one pixel to the right
* when the button is clicked */
byte clk_dif = this->IsWidgetLowered(i + 3) ? 1 : 0;
GfxFillRect(x + clk_dif, y + clk_dif, x + 8 + clk_dif, y + 5 + clk_dif, 0);
GfxFillRect(x + 1 + clk_dif, y + 1 + clk_dif, x + 7 + clk_dif, y + 4 + clk_dif, cs->legend_colour);
SetDParam(0, cs->name);
DrawString(x + 14 + clk_dif, y + clk_dif, STR_7065, TC_FROMSTRING);
y += 8;
}
this->colours[i] = cs->legend_colour;
for (uint j = 0; j != 20; j++) {
this->cost[i][j] = GetTransportedGoodsIncome(10, 20, j * 4 + 4, c);
}
i++;
}
this->num_dataset = i;
this->DrawGraph();
DrawString(2 + 46, 24 + this->gd_height + 7, STR_7062_DAYS_IN_TRANSIT, TC_FROMSTRING);
DrawString(2 + 84, 24 - 9, STR_7063_PAYMENT_FOR_DELIVERING, TC_FROMSTRING);
}
virtual void OnClick(Point pt, int widget)
{
if (widget >= 3) {
ToggleBit(_legend_excluded_cargo, widget - 3);
this->ToggleWidgetLoweredState(widget);
this->SetDirty();
}
}
};
static const Widget _cargo_payment_rates_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 567, 0, 13, STR_7061_CARGO_PAYMENT_RATES, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_BOTTOM, COLOUR_GREY, 0, 567, 14, 45, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _cargo_payment_rates_desc(
WDP_AUTO, WDP_AUTO, 568, 46, 568, 46,
WC_PAYMENT_RATES, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_cargo_payment_rates_widgets
);
void ShowCargoPaymentRates()
{
AllocateWindowDescFront<PaymentRatesGraphWindow>(&_cargo_payment_rates_desc, 0);
}
/************************/
/* COMPANY LEAGUE TABLE */
/************************/
static const StringID _performance_titles[] = {
STR_7066_ENGINEER,
STR_7066_ENGINEER,
STR_7067_TRAFFIC_MANAGER,
STR_7067_TRAFFIC_MANAGER,
STR_7068_TRANSPORT_COORDINATOR,
STR_7068_TRANSPORT_COORDINATOR,
STR_7069_ROUTE_SUPERVISOR,
STR_7069_ROUTE_SUPERVISOR,
STR_706A_DIRECTOR,
STR_706A_DIRECTOR,
STR_706B_CHIEF_EXECUTIVE,
STR_706B_CHIEF_EXECUTIVE,
STR_706C_CHAIRMAN,
STR_706C_CHAIRMAN,
STR_706D_PRESIDENT,
STR_706E_TYCOON,
};
static inline StringID GetPerformanceTitleFromValue(uint value)
{
return _performance_titles[minu(value, 1000) >> 6];
}
class CompanyLeagueWindow : public Window {
private:
GUIList<const Company*> companies;
/**
* (Re)Build the company league list
*/
void BuildCompanyList()
{
if (!this->companies.NeedRebuild()) return;
this->companies.Clear();
const Company *c;
FOR_ALL_COMPANIES(c) {
*this->companies.Append() = c;
}
this->companies.Compact();
this->companies.RebuildDone();
}
/** Sort the company league by performance history */
static int CDECL PerformanceSorter(const Company * const *c1, const Company * const *c2)
{
return (*c2)->old_economy[1].performance_history - (*c1)->old_economy[1].performance_history;
}
public:
CompanyLeagueWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->companies.ForceRebuild();
this->companies.NeedResort();
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->BuildCompanyList();
this->companies.Sort(&PerformanceSorter);
this->DrawWidgets();
for (uint i = 0; i != this->companies.Length(); i++) {
const Company *c = this->companies[i];
SetDParam(0, i + STR_01AC_1ST);
SetDParam(1, c->index);
SetDParam(2, c->index);
SetDParam(3, GetPerformanceTitleFromValue(c->old_economy[1].performance_history));
DrawString(2, 15 + i * 10, i == 0 ? STR_7054 : STR_7055, TC_FROMSTRING);
DrawCompanyIcon(c->index, 27, 16 + i * 10);
}
}
virtual void OnTick()
{
if (this->companies.NeedResort()) {
this->SetDirty();
}
}
virtual void OnInvalidateData(int data)
{
if (data == 0) {
this->companies.ForceRebuild();
} else {
this->companies.ForceResort();
}
}
};
static const Widget _company_league_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 387, 0, 13, STR_7053_COMPANY_LEAGUE_TABLE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_GREY, 388, 399, 0, 13, STR_NULL, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 399, 14, 166, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _company_league_desc(
WDP_AUTO, WDP_AUTO, 400, 167, 400, 167,
WC_COMPANY_LEAGUE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
_company_league_widgets
);
void ShowCompanyLeagueTable()
{
AllocateWindowDescFront<CompanyLeagueWindow>(&_company_league_desc, 0);
}
/*****************************/
/* PERFORMANCE RATING DETAIL */
/*****************************/
struct PerformanceRatingDetailWindow : Window {
private:
enum PerformanteRatingWidgets {
PRW_COMPANY_FIRST = 13,
PRW_COMPANY_LAST = PRW_COMPANY_FIRST + MAX_COMPANIES - 1,
};
public:
static CompanyID company;
int timeout;
PerformanceRatingDetailWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
/* Disable the companies who are not active */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
this->SetWidgetDisabledState(i + PRW_COMPANY_FIRST, !IsValidCompanyID(i));
}
this->UpdateCompanyStats();
if (company != INVALID_COMPANY) this->LowerWidget(company + PRW_COMPANY_FIRST);
this->FindWindowPlacementAndResize(desc);
}
void UpdateCompanyStats()
{
/* Update all company stats with the current data
* (this is because _score_info is not saved to a savegame) */
Company *c;
FOR_ALL_COMPANIES(c) {
UpdateCompanyRatingAndValue(c, false);
}
this->timeout = DAY_TICKS * 5;
}
virtual void OnPaint()
{
byte x;
uint16 y = 27;
int total_score = 0;
int colour_done, colour_notdone;
/* Draw standard stuff */
this->DrawWidgets();
/* Check if the currently selected company is still active. */
if (company == INVALID_COMPANY || !IsValidCompanyID(company)) {
if (company != INVALID_COMPANY) {
/* Raise and disable the widget for the previous selection. */
this->RaiseWidget(company + PRW_COMPANY_FIRST);
this->DisableWidget(company + PRW_COMPANY_FIRST);
this->SetDirty();
company = INVALID_COMPANY;
}
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
if (IsValidCompanyID(i)) {
/* Lower the widget corresponding to this company. */
this->LowerWidget(i + PRW_COMPANY_FIRST);
this->SetDirty();
company = i;
break;
}
}
}
/* If there are no active companies, don't display anything else. */
if (company == INVALID_COMPANY) return;
/* Paint the company icons */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
if (!IsValidCompanyID(i)) {
/* Check if we have the company as an active company */
if (!this->IsWidgetDisabled(i + PRW_COMPANY_FIRST)) {
/* Bah, company gone :( */
this->DisableWidget(i + PRW_COMPANY_FIRST);
/* We need a repaint */
this->SetDirty();
}
continue;
}
/* Check if we have the company marked as inactive */
if (this->IsWidgetDisabled(i + PRW_COMPANY_FIRST)) {
/* New company! Yippie :p */
this->EnableWidget(i + PRW_COMPANY_FIRST);
/* We need a repaint */
this->SetDirty();
}
x = (i == company) ? 1 : 0;
DrawCompanyIcon(i, (i % 8) * 37 + 13 + x, (i < 8 ? 0 : 13) + 16 + x);
}
/* The colours used to show how the progress is going */
colour_done = _colour_gradient[COLOUR_GREEN][4];
colour_notdone = _colour_gradient[COLOUR_RED][4];
/* Draw all the score parts */
for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
int val = _score_part[company][i];
int needed = _score_info[i].needed;
int score = _score_info[i].score;
y += 20;
/* SCORE_TOTAL has his own rulez ;) */
if (i == SCORE_TOTAL) {
needed = total_score;
score = SCORE_MAX;
} else {
total_score += score;
}
DrawString(7, y, STR_PERFORMANCE_DETAIL_VEHICLES + i, TC_FROMSTRING);
/* Draw the score */
SetDParam(0, score);
DrawStringRightAligned(107, y, STR_PERFORMANCE_DETAIL_INT, TC_FROMSTRING);
/* Calculate the %-bar */
x = Clamp(val, 0, needed) * 50 / needed;
/* SCORE_LOAN is inversed */
if (val < 0 && i == SCORE_LOAN) x = 0;
/* Draw the bar */
if (x != 0) GfxFillRect(112, y - 2, 112 + x, y + 10, colour_done);
if (x != 50) GfxFillRect(112 + x, y - 2, 112 + 50, y + 10, colour_notdone);
/* Calculate the % */
x = Clamp(val, 0, needed) * 100 / needed;
/* SCORE_LOAN is inversed */
if (val < 0 && i == SCORE_LOAN) x = 0;
/* Draw it */
SetDParam(0, x);
DrawStringCentered(137, y, STR_PERFORMANCE_DETAIL_PERCENT, TC_FROMSTRING);
/* SCORE_LOAN is inversed */
if (i == SCORE_LOAN) val = needed - val;
/* Draw the amount we have against what is needed
* For some of them it is in currency format */
SetDParam(0, val);
SetDParam(1, needed);
switch (i) {
case SCORE_MIN_PROFIT:
case SCORE_MIN_INCOME:
case SCORE_MAX_INCOME:
case SCORE_MONEY:
case SCORE_LOAN:
DrawString(167, y, STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY, TC_FROMSTRING);
break;
default:
DrawString(167, y, STR_PERFORMANCE_DETAIL_AMOUNT_INT, TC_FROMSTRING);
}
}
}
virtual void OnClick(Point pt, int widget)
{
/* Check which button is clicked */
if (IsInsideMM(widget, PRW_COMPANY_FIRST, PRW_COMPANY_LAST + 1)) {
/* Is it no on disable? */
if (!this->IsWidgetDisabled(widget)) {
this->RaiseWidget(company + PRW_COMPANY_FIRST);
company = (CompanyID)(widget - PRW_COMPANY_FIRST);
this->LowerWidget(company + PRW_COMPANY_FIRST);
this->SetDirty();
}
}
}
virtual void OnTick()
{
if (_pause_game != 0) return;
/* Update the company score every 5 days */
if (--this->timeout == 0) {
this->UpdateCompanyStats();
this->SetDirty();
}
}
};
CompanyID PerformanceRatingDetailWindow::company = INVALID_COMPANY;
static const Widget _performance_rating_detail_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 298, 0, 13, STR_PERFORMANCE_DETAIL, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 14, 40, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 41, 60, 0x0, STR_PERFORMANCE_DETAIL_VEHICLES_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 61, 80, 0x0, STR_PERFORMANCE_DETAIL_STATIONS_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 81, 100, 0x0, STR_PERFORMANCE_DETAIL_MIN_PROFIT_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 101, 120, 0x0, STR_PERFORMANCE_DETAIL_MIN_INCOME_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 121, 140, 0x0, STR_PERFORMANCE_DETAIL_MAX_INCOME_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 141, 160, 0x0, STR_PERFORMANCE_DETAIL_DELIVERED_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 161, 180, 0x0, STR_PERFORMANCE_DETAIL_CARGO_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 181, 200, 0x0, STR_PERFORMANCE_DETAIL_MONEY_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 201, 220, 0x0, STR_PERFORMANCE_DETAIL_LOAN_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 298, 221, 240, 0x0, STR_PERFORMANCE_DETAIL_TOTAL_TIP},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 38, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 39, 75, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 76, 112, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 113, 149, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 150, 186, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 187, 223, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 224, 260, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 261, 297, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 38, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 39, 75, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 76, 112, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 113, 149, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 150, 186, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 187, 223, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 224, 260, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WIDGETS_END},
};
static const WindowDesc _performance_rating_detail_desc(
WDP_AUTO, WDP_AUTO, 299, 241, 299, 241,
WC_PERFORMANCE_DETAIL, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_performance_rating_detail_widgets
);
void ShowPerformanceRatingDetail()
{
AllocateWindowDescFront<PerformanceRatingDetailWindow>(&_performance_rating_detail_desc, 0);
}
| 38,772
|
C++
|
.cpp
| 902
| 39.924612
| 146
| 0.633564
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,008
|
rail.cpp
|
EnergeticBark_OpenTTD-3DS/src/rail.cpp
|
/* $Id$ */
/** @file rail.cpp Implementation of rail specific functions. */
#include "stdafx.h"
#include "station_map.h"
#include "tunnelbridge_map.h"
#include "date_func.h"
#include "company_func.h"
#include "company_base.h"
#include "engine_base.h"
#include "settings_type.h"
/* XXX: Below 3 tables store duplicate data. Maybe remove some? */
/* Maps a trackdir to the bit that stores its status in the map arrays, in the
* direction along with the trackdir */
extern const byte _signal_along_trackdir[TRACKDIR_END] = {
0x8, 0x8, 0x8, 0x2, 0x4, 0x1, 0, 0,
0x4, 0x4, 0x4, 0x1, 0x8, 0x2
};
/* Maps a trackdir to the bit that stores its status in the map arrays, in the
* direction against the trackdir */
extern const byte _signal_against_trackdir[TRACKDIR_END] = {
0x4, 0x4, 0x4, 0x1, 0x8, 0x2, 0, 0,
0x8, 0x8, 0x8, 0x2, 0x4, 0x1
};
/* Maps a Track to the bits that store the status of the two signals that can
* be present on the given track */
extern const byte _signal_on_track[] = {
0xC, 0xC, 0xC, 0x3, 0xC, 0x3
};
/* Maps a diagonal direction to the all trackdirs that are connected to any
* track entering in this direction (including those making 90 degree turns)
*/
extern const TrackdirBits _exitdir_reaches_trackdirs[] = {
TRACKDIR_BIT_X_NE | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_LEFT_N, // DIAGDIR_NE
TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_UPPER_E, // DIAGDIR_SE
TRACKDIR_BIT_X_SW | TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_RIGHT_S, // DIAGDIR_SW
TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_W // DIAGDIR_NW
};
extern const Trackdir _next_trackdir[TRACKDIR_END] = {
TRACKDIR_X_NE, TRACKDIR_Y_SE, TRACKDIR_LOWER_E, TRACKDIR_UPPER_E, TRACKDIR_RIGHT_S, TRACKDIR_LEFT_S, INVALID_TRACKDIR, INVALID_TRACKDIR,
TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_LOWER_W, TRACKDIR_UPPER_W, TRACKDIR_RIGHT_N, TRACKDIR_LEFT_N
};
/* Maps a trackdir to all trackdirs that make 90 deg turns with it. */
extern const TrackdirBits _track_crosses_trackdirs[TRACKDIR_END] = {
TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_Y_NW, // TRACK_X
TRACKDIR_BIT_X_NE | TRACKDIR_BIT_X_SW, // TRACK_Y
TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_LEFT_S, // TRACK_UPPER
TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_LEFT_S, // TRACK_LOWER
TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_UPPER_E | TRACKDIR_BIT_LOWER_W | TRACKDIR_BIT_LOWER_E, // TRACK_LEFT
TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_UPPER_E | TRACKDIR_BIT_LOWER_W | TRACKDIR_BIT_LOWER_E // TRACK_RIGHT
};
/* Maps a track to all tracks that make 90 deg turns with it. */
extern const TrackBits _track_crosses_tracks[] = {
TRACK_BIT_Y, // TRACK_X
TRACK_BIT_X, // TRACK_Y
TRACK_BIT_VERT, // TRACK_UPPER
TRACK_BIT_VERT, // TRACK_LOWER
TRACK_BIT_HORZ, // TRACK_LEFT
TRACK_BIT_HORZ // TRACK_RIGHT
};
/* Maps a trackdir to the (4-way) direction the tile is exited when following
* that trackdir */
extern const DiagDirection _trackdir_to_exitdir[TRACKDIR_END] = {
DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_NE,
DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE,
};
extern const Trackdir _track_exitdir_to_trackdir[][DIAGDIR_END] = {
{TRACKDIR_X_NE, INVALID_TRACKDIR, TRACKDIR_X_SW, INVALID_TRACKDIR},
{INVALID_TRACKDIR, TRACKDIR_Y_SE, INVALID_TRACKDIR, TRACKDIR_Y_NW},
{TRACKDIR_UPPER_E, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_UPPER_W},
{INVALID_TRACKDIR, TRACKDIR_LOWER_E, TRACKDIR_LOWER_W, INVALID_TRACKDIR},
{INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_LEFT_S, TRACKDIR_LEFT_N},
{TRACKDIR_RIGHT_N, TRACKDIR_RIGHT_S, INVALID_TRACKDIR, INVALID_TRACKDIR}
};
extern const Trackdir _track_enterdir_to_trackdir[][DIAGDIR_END] = {
{TRACKDIR_X_NE, INVALID_TRACKDIR, TRACKDIR_X_SW, INVALID_TRACKDIR},
{INVALID_TRACKDIR, TRACKDIR_Y_SE, INVALID_TRACKDIR, TRACKDIR_Y_NW},
{INVALID_TRACKDIR, TRACKDIR_UPPER_E, TRACKDIR_UPPER_W, INVALID_TRACKDIR},
{TRACKDIR_LOWER_E, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_LOWER_W},
{TRACKDIR_LEFT_N, TRACKDIR_LEFT_S, INVALID_TRACKDIR, INVALID_TRACKDIR},
{INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_RIGHT_S, TRACKDIR_RIGHT_N}
};
extern const Trackdir _track_direction_to_trackdir[][DIR_END] = {
{INVALID_TRACKDIR, TRACKDIR_X_NE, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_X_SW, INVALID_TRACKDIR, INVALID_TRACKDIR},
{INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_Y_SE, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_Y_NW},
{INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_UPPER_E, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_UPPER_W, INVALID_TRACKDIR},
{INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_LOWER_E, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_LOWER_W, INVALID_TRACKDIR},
{TRACKDIR_LEFT_N, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_LEFT_S, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR},
{TRACKDIR_RIGHT_N, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_RIGHT_S, INVALID_TRACKDIR, INVALID_TRACKDIR, INVALID_TRACKDIR}
};
extern const Trackdir _dir_to_diag_trackdir[] = {
TRACKDIR_X_NE, TRACKDIR_Y_SE, TRACKDIR_X_SW, TRACKDIR_Y_NW,
};
extern const TrackBits _corner_to_trackbits[] = {
TRACK_BIT_LEFT, TRACK_BIT_LOWER, TRACK_BIT_RIGHT, TRACK_BIT_UPPER,
};
extern const TrackdirBits _uphill_trackdirs[] = {
TRACKDIR_BIT_NONE , ///< 0 SLOPE_FLAT
TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW, ///< 1 SLOPE_W -> inclined for diagonal track
TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_SE, ///< 2 SLOPE_S -> inclined for diagonal track
TRACKDIR_BIT_X_SW , ///< 3 SLOPE_SW
TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE, ///< 4 SLOPE_E -> inclined for diagonal track
TRACKDIR_BIT_NONE , ///< 5 SLOPE_EW
TRACKDIR_BIT_Y_SE , ///< 6 SLOPE_SE
TRACKDIR_BIT_NONE , ///< 7 SLOPE_WSE -> leveled
TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_NW, ///< 8 SLOPE_N -> inclined for diagonal track
TRACKDIR_BIT_Y_NW , ///< 9 SLOPE_NW
TRACKDIR_BIT_NONE , ///< 10 SLOPE_NS
TRACKDIR_BIT_NONE , ///< 11 SLOPE_NWS -> leveled
TRACKDIR_BIT_X_NE , ///< 12 SLOPE_NE
TRACKDIR_BIT_NONE , ///< 13 SLOPE_ENW -> leveled
TRACKDIR_BIT_NONE , ///< 14 SLOPE_SEN -> leveled
TRACKDIR_BIT_NONE , ///< 15 invalid
TRACKDIR_BIT_NONE , ///< 16 invalid
TRACKDIR_BIT_NONE , ///< 17 invalid
TRACKDIR_BIT_NONE , ///< 18 invalid
TRACKDIR_BIT_NONE , ///< 19 invalid
TRACKDIR_BIT_NONE , ///< 20 invalid
TRACKDIR_BIT_NONE , ///< 21 invalid
TRACKDIR_BIT_NONE , ///< 22 invalid
TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_SE, ///< 23 SLOPE_STEEP_S -> inclined for diagonal track
TRACKDIR_BIT_NONE , ///< 24 invalid
TRACKDIR_BIT_NONE , ///< 25 invalid
TRACKDIR_BIT_NONE , ///< 26 invalid
TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW, ///< 27 SLOPE_STEEP_W -> inclined for diagonal track
TRACKDIR_BIT_NONE , ///< 28 invalid
TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_NW, ///< 29 SLOPE_STEEP_N -> inclined for diagonal track
TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE, ///< 30 SLOPE_STEEP_E -> inclined for diagonal track
};
RailType GetTileRailType(TileIndex tile)
{
switch (GetTileType(tile)) {
case MP_RAILWAY:
return GetRailType(tile);
case MP_ROAD:
/* rail/road crossing */
if (IsLevelCrossing(tile)) return GetRailType(tile);
break;
case MP_STATION:
if (IsRailwayStationTile(tile)) return GetRailType(tile);
break;
case MP_TUNNELBRIDGE:
if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) return GetRailType(tile);
break;
default:
break;
}
return INVALID_RAILTYPE;
}
bool HasRailtypeAvail(const CompanyID company, const RailType railtype)
{
return HasBit(GetCompany(company)->avail_railtypes, railtype);
}
bool ValParamRailtype(const RailType rail)
{
return HasRailtypeAvail(_current_company, rail);
}
RailType GetBestRailtype(const CompanyID company)
{
if (HasRailtypeAvail(company, RAILTYPE_MAGLEV)) return RAILTYPE_MAGLEV;
if (HasRailtypeAvail(company, RAILTYPE_MONO)) return RAILTYPE_MONO;
if (HasRailtypeAvail(company, RAILTYPE_ELECTRIC)) return RAILTYPE_ELECTRIC;
return RAILTYPE_RAIL;
}
RailTypes GetCompanyRailtypes(CompanyID company)
{
RailTypes rt = RAILTYPES_NONE;
Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
const EngineInfo *ei = &e->info;
if (HasBit(ei->climates, _settings_game.game_creation.landscape) &&
(HasBit(e->company_avail, company) || _date >= e->intro_date + DAYS_IN_YEAR)) {
const RailVehicleInfo *rvi = &e->u.rail;
if (rvi->railveh_type != RAILVEH_WAGON) {
assert(rvi->railtype < RAILTYPE_END);
SetBit(rt, rvi->railtype);
}
}
}
return rt;
}
RailType GetRailTypeByLabel(RailTypeLabel label)
{
/* Loop through each rail type until the label is found */
for (RailType r = RAILTYPE_BEGIN; r != RAILTYPE_END; r++) {
const RailtypeInfo *rti = GetRailTypeInfo(r);
if (rti->label == label) return r;
}
/* No matching label was found, so it is invalid */
return INVALID_RAILTYPE;
}
| 9,607
|
C++
|
.cpp
| 190
| 48.510526
| 149
| 0.683678
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,009
|
command.cpp
|
EnergeticBark_OpenTTD-3DS/src/command.cpp
|
/* $Id$ */
/** @file command.cpp Handling of commands. */
#include "stdafx.h"
#include "openttd.h"
#include "landscape.h"
#include "tile_map.h"
#include "gui.h"
#include "command_func.h"
#include "network/network.h"
#include "genworld.h"
#include "newgrf_storage.h"
#include "strings_func.h"
#include "gfx_func.h"
#include "functions.h"
#include "town.h"
#include "date_func.h"
#include "debug.h"
#include "company_func.h"
#include "company_base.h"
#include "signal_func.h"
#include "table/strings.h"
StringID _error_message;
/**
* Helper macro to define the header of all command handler macros.
*
* This macro create the function header for a given command handler function, as
* all command handler functions got the parameters from the #CommandProc callback
* type.
*
* @param yyyy The desired function name of the new command handler function.
*/
#define DEF_COMMAND(yyyy) CommandCost yyyy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
DEF_COMMAND(CmdBuildRailroadTrack);
DEF_COMMAND(CmdRemoveRailroadTrack);
DEF_COMMAND(CmdBuildSingleRail);
DEF_COMMAND(CmdRemoveSingleRail);
DEF_COMMAND(CmdLandscapeClear);
DEF_COMMAND(CmdBuildBridge);
DEF_COMMAND(CmdBuildRailroadStation);
DEF_COMMAND(CmdRemoveFromRailroadStation);
DEF_COMMAND(CmdConvertRail);
DEF_COMMAND(CmdBuildSingleSignal);
DEF_COMMAND(CmdRemoveSingleSignal);
DEF_COMMAND(CmdTerraformLand);
DEF_COMMAND(CmdPurchaseLandArea);
DEF_COMMAND(CmdSellLandArea);
DEF_COMMAND(CmdBuildTunnel);
DEF_COMMAND(CmdBuildTrainDepot);
DEF_COMMAND(CmdBuildTrainWaypoint);
DEF_COMMAND(CmdRenameWaypoint);
DEF_COMMAND(CmdRemoveTrainWaypoint);
DEF_COMMAND(CmdBuildRoadStop);
DEF_COMMAND(CmdRemoveRoadStop);
DEF_COMMAND(CmdBuildLongRoad);
DEF_COMMAND(CmdRemoveLongRoad);
DEF_COMMAND(CmdBuildRoad);
DEF_COMMAND(CmdRemoveRoad);
DEF_COMMAND(CmdBuildRoadDepot);
DEF_COMMAND(CmdBuildAirport);
DEF_COMMAND(CmdBuildDock);
DEF_COMMAND(CmdBuildShipDepot);
DEF_COMMAND(CmdBuildBuoy);
DEF_COMMAND(CmdPlantTree);
DEF_COMMAND(CmdBuildRailVehicle);
DEF_COMMAND(CmdMoveRailVehicle);
DEF_COMMAND(CmdSellRailWagon);
DEF_COMMAND(CmdSendTrainToDepot);
DEF_COMMAND(CmdForceTrainProceed);
DEF_COMMAND(CmdReverseTrainDirection);
DEF_COMMAND(CmdModifyOrder);
DEF_COMMAND(CmdSkipToOrder);
DEF_COMMAND(CmdDeleteOrder);
DEF_COMMAND(CmdInsertOrder);
DEF_COMMAND(CmdChangeServiceInt);
DEF_COMMAND(CmdRestoreOrderIndex);
DEF_COMMAND(CmdBuildIndustry);
DEF_COMMAND(CmdBuildCompanyHQ);
DEF_COMMAND(CmdSetCompanyManagerFace);
DEF_COMMAND(CmdSetCompanyColour);
DEF_COMMAND(CmdIncreaseLoan);
DEF_COMMAND(CmdDecreaseLoan);
DEF_COMMAND(CmdWantEnginePreview);
DEF_COMMAND(CmdRenameVehicle);
DEF_COMMAND(CmdRenameEngine);
DEF_COMMAND(CmdRenameCompany);
DEF_COMMAND(CmdRenamePresident);
DEF_COMMAND(CmdRenameStation);
DEF_COMMAND(CmdSellAircraft);
DEF_COMMAND(CmdBuildAircraft);
DEF_COMMAND(CmdSendAircraftToHangar);
DEF_COMMAND(CmdRefitAircraft);
DEF_COMMAND(CmdPlaceSign);
DEF_COMMAND(CmdRenameSign);
DEF_COMMAND(CmdBuildRoadVeh);
DEF_COMMAND(CmdSellRoadVeh);
DEF_COMMAND(CmdSendRoadVehToDepot);
DEF_COMMAND(CmdTurnRoadVeh);
DEF_COMMAND(CmdRefitRoadVeh);
DEF_COMMAND(CmdPause);
DEF_COMMAND(CmdBuyShareInCompany);
DEF_COMMAND(CmdSellShareInCompany);
DEF_COMMAND(CmdBuyCompany);
DEF_COMMAND(CmdBuildTown);
DEF_COMMAND(CmdRenameTown);
DEF_COMMAND(CmdDoTownAction);
DEF_COMMAND(CmdChangeSetting);
DEF_COMMAND(CmdSellShip);
DEF_COMMAND(CmdBuildShip);
DEF_COMMAND(CmdSendShipToDepot);
DEF_COMMAND(CmdRefitShip);
DEF_COMMAND(CmdOrderRefit);
DEF_COMMAND(CmdCloneOrder);
DEF_COMMAND(CmdClearArea);
DEF_COMMAND(CmdGiveMoney);
DEF_COMMAND(CmdMoneyCheat);
DEF_COMMAND(CmdBuildCanal);
DEF_COMMAND(CmdBuildLock);
DEF_COMMAND(CmdCompanyCtrl);
DEF_COMMAND(CmdLevelLand);
DEF_COMMAND(CmdRefitRailVehicle);
DEF_COMMAND(CmdBuildSignalTrack);
DEF_COMMAND(CmdRemoveSignalTrack);
DEF_COMMAND(CmdSetAutoReplace);
DEF_COMMAND(CmdCloneVehicle);
DEF_COMMAND(CmdStartStopVehicle);
DEF_COMMAND(CmdMassStartStopVehicle);
DEF_COMMAND(CmdAutoreplaceVehicle);
DEF_COMMAND(CmdDepotSellAllVehicles);
DEF_COMMAND(CmdDepotMassAutoReplace);
DEF_COMMAND(CmdCreateGroup);
DEF_COMMAND(CmdRenameGroup);
DEF_COMMAND(CmdDeleteGroup);
DEF_COMMAND(CmdAddVehicleGroup);
DEF_COMMAND(CmdAddSharedVehicleGroup);
DEF_COMMAND(CmdRemoveAllVehiclesGroup);
DEF_COMMAND(CmdSetGroupReplaceProtection);
DEF_COMMAND(CmdMoveOrder);
DEF_COMMAND(CmdChangeTimetable);
DEF_COMMAND(CmdSetVehicleOnTime);
DEF_COMMAND(CmdAutofillTimetable);
#undef DEF_COMMAND
/**
* The master command table
*
* This table contains all possible CommandProc functions with
* the flags which belongs to it. The indizes are the same
* as the value from the CMD_* enums.
*/
static const Command _command_proc_table[] = {
{CmdBuildRailroadTrack, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_RAILROAD_TRACK
{CmdRemoveRailroadTrack, CMD_AUTO}, // CMD_REMOVE_RAILROAD_TRACK
{CmdBuildSingleRail, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_SINGLE_RAIL
{CmdRemoveSingleRail, CMD_AUTO}, // CMD_REMOVE_SINGLE_RAIL
{CmdLandscapeClear, 0}, // CMD_LANDSCAPE_CLEAR
{CmdBuildBridge, CMD_AUTO}, // CMD_BUILD_BRIDGE
{CmdBuildRailroadStation, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_RAILROAD_STATION
{CmdBuildTrainDepot, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_TRAIN_DEPOT
{CmdBuildSingleSignal, CMD_AUTO}, // CMD_BUILD_SIGNALS
{CmdRemoveSingleSignal, CMD_AUTO}, // CMD_REMOVE_SIGNALS
{CmdTerraformLand, CMD_ALL_TILES | CMD_AUTO}, // CMD_TERRAFORM_LAND
{CmdPurchaseLandArea, CMD_NO_WATER | CMD_AUTO}, // CMD_PURCHASE_LAND_AREA
{CmdSellLandArea, 0}, // CMD_SELL_LAND_AREA
{CmdBuildTunnel, CMD_AUTO}, // CMD_BUILD_TUNNEL
{CmdRemoveFromRailroadStation, 0}, // CMD_REMOVE_FROM_RAILROAD_STATION
{CmdConvertRail, 0}, // CMD_CONVERT_RAILD
{CmdBuildTrainWaypoint, 0}, // CMD_BUILD_TRAIN_WAYPOINT
{CmdRenameWaypoint, 0}, // CMD_RENAME_WAYPOINT
{CmdRemoveTrainWaypoint, 0}, // CMD_REMOVE_TRAIN_WAYPOINT
{CmdBuildRoadStop, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_ROAD_STOP
{CmdRemoveRoadStop, 0}, // CMD_REMOVE_ROAD_STOP
{CmdBuildLongRoad, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_LONG_ROAD
{CmdRemoveLongRoad, CMD_NO_TEST | CMD_AUTO}, // CMD_REMOVE_LONG_ROAD; towns may disallow removing road bits (as they are connected) in test, but in exec they're removed and thus removing is allowed.
{CmdBuildRoad, 0}, // CMD_BUILD_ROAD
{CmdRemoveRoad, 0}, // CMD_REMOVE_ROAD
{CmdBuildRoadDepot, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_ROAD_DEPOT
{CmdBuildAirport, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_AIRPORT
{CmdBuildDock, CMD_AUTO}, // CMD_BUILD_DOCK
{CmdBuildShipDepot, CMD_AUTO}, // CMD_BUILD_SHIP_DEPOT
{CmdBuildBuoy, CMD_AUTO}, // CMD_BUILD_BUOY
{CmdPlantTree, CMD_AUTO}, // CMD_PLANT_TREE
{CmdBuildRailVehicle, 0}, // CMD_BUILD_RAIL_VEHICLE
{CmdMoveRailVehicle, 0}, // CMD_MOVE_RAIL_VEHICLE
{CmdSellRailWagon, 0}, // CMD_SELL_RAIL_WAGON
{CmdSendTrainToDepot, 0}, // CMD_SEND_TRAIN_TO_DEPOT
{CmdForceTrainProceed, 0}, // CMD_FORCE_TRAIN_PROCEED
{CmdReverseTrainDirection, 0}, // CMD_REVERSE_TRAIN_DIRECTION
{CmdModifyOrder, 0}, // CMD_MODIFY_ORDER
{CmdSkipToOrder, 0}, // CMD_SKIP_TO_ORDER
{CmdDeleteOrder, 0}, // CMD_DELETE_ORDER
{CmdInsertOrder, 0}, // CMD_INSERT_ORDER
{CmdChangeServiceInt, 0}, // CMD_CHANGE_SERVICE_INT
{CmdBuildIndustry, 0}, // CMD_BUILD_INDUSTRY
{CmdBuildCompanyHQ, CMD_NO_WATER | CMD_AUTO}, // CMD_BUILD_COMPANY_HQ
{CmdSetCompanyManagerFace, 0}, // CMD_SET_COMPANY_MANAGER_FACE
{CmdSetCompanyColour, 0}, // CMD_SET_COMPANY_COLOUR
{CmdIncreaseLoan, 0}, // CMD_INCREASE_LOAN
{CmdDecreaseLoan, 0}, // CMD_DECREASE_LOAN
{CmdWantEnginePreview, 0}, // CMD_WANT_ENGINE_PREVIEW
{CmdRenameVehicle, 0}, // CMD_RENAME_VEHICLE
{CmdRenameEngine, 0}, // CMD_RENAME_ENGINE
{CmdRenameCompany, 0}, // CMD_RENAME_COMPANY
{CmdRenamePresident, 0}, // CMD_RENAME_PRESIDENT
{CmdRenameStation, 0}, // CMD_RENAME_STATION
{CmdSellAircraft, 0}, // CMD_SELL_AIRCRAFT
{CmdBuildAircraft, 0}, // CMD_BUILD_AIRCRAFT
{CmdSendAircraftToHangar, 0}, // CMD_SEND_AIRCRAFT_TO_HANGAR
{CmdRefitAircraft, 0}, // CMD_REFIT_AIRCRAFT
{CmdPlaceSign, 0}, // CMD_PLACE_SIGN
{CmdRenameSign, 0}, // CMD_RENAME_SIGN
{CmdBuildRoadVeh, 0}, // CMD_BUILD_ROAD_VEH
{CmdSellRoadVeh, 0}, // CMD_SELL_ROAD_VEH
{CmdSendRoadVehToDepot, 0}, // CMD_SEND_ROADVEH_TO_DEPOT
{CmdTurnRoadVeh, 0}, // CMD_TURN_ROADVEH
{CmdRefitRoadVeh, 0}, // CMD_REFIT_ROAD_VEH
{CmdPause, CMD_SERVER}, // CMD_PAUSE
{CmdBuyShareInCompany, 0}, // CMD_BUY_SHARE_IN_COMPANY
{CmdSellShareInCompany, 0}, // CMD_SELL_SHARE_IN_COMPANY
{CmdBuyCompany, 0}, // CMD_BUY_COMANY
{CmdBuildTown, CMD_OFFLINE}, // CMD_BUILD_TOWN
{CmdRenameTown, CMD_SERVER}, // CMD_RENAME_TOWN
{CmdDoTownAction, 0}, // CMD_DO_TOWN_ACTION
{CmdSellShip, 0}, // CMD_SELL_SHIP
{CmdBuildShip, 0}, // CMD_BUILD_SHIP
{CmdSendShipToDepot, 0}, // CMD_SEND_SHIP_TO_DEPOT
{CmdRefitShip, 0}, // CMD_REFIT_SHIP
{CmdOrderRefit, 0}, // CMD_ORDER_REFIT
{CmdCloneOrder, 0}, // CMD_CLONE_ORDER
{CmdClearArea, CMD_NO_TEST}, // CMD_CLEAR_AREA; destroying multi-tile houses makes town rating differ between test and execution
{CmdMoneyCheat, CMD_OFFLINE}, // CMD_MONEY_CHEAT
{CmdBuildCanal, CMD_AUTO}, // CMD_BUILD_CANAL
{CmdCompanyCtrl, CMD_SPECTATOR}, // CMD_COMPANY_CTRL
{CmdLevelLand, CMD_ALL_TILES | CMD_NO_TEST | CMD_AUTO}, // CMD_LEVEL_LAND; test run might clear tiles multiple times, in execution that only happens once
{CmdRefitRailVehicle, 0}, // CMD_REFIT_RAIL_VEHICLE
{CmdRestoreOrderIndex, 0}, // CMD_RESTORE_ORDER_INDEX
{CmdBuildLock, CMD_AUTO}, // CMD_BUILD_LOCK
{CmdBuildSignalTrack, CMD_AUTO}, // CMD_BUILD_SIGNAL_TRACK
{CmdRemoveSignalTrack, CMD_AUTO}, // CMD_REMOVE_SIGNAL_TRACK
{CmdGiveMoney, 0}, // CMD_GIVE_MONEY
{CmdChangeSetting, CMD_SERVER}, // CMD_CHANGE_SETTING
{CmdSetAutoReplace, 0}, // CMD_SET_AUTOREPLACE
{CmdCloneVehicle, CMD_NO_TEST}, // CMD_CLONE_VEHICLE; NewGRF callbacks influence building and refitting making it impossible to correctly estimate the cost
{CmdStartStopVehicle, 0}, // CMD_START_STOP_VEHICLE
{CmdMassStartStopVehicle, 0}, // CMD_MASS_START_STOP
{CmdAutoreplaceVehicle, 0}, // CMD_AUTOREPLACE_VEHICLE
{CmdDepotSellAllVehicles, 0}, // CMD_DEPOT_SELL_ALL_VEHICLES
{CmdDepotMassAutoReplace, 0}, // CMD_DEPOT_MASS_AUTOREPLACE
{CmdCreateGroup, 0}, // CMD_CREATE_GROUP
{CmdDeleteGroup, 0}, // CMD_DELETE_GROUP
{CmdRenameGroup, 0}, // CMD_RENAME_GROUP
{CmdAddVehicleGroup, 0}, // CMD_ADD_VEHICLE_GROUP
{CmdAddSharedVehicleGroup, 0}, // CMD_ADD_SHARE_VEHICLE_GROUP
{CmdRemoveAllVehiclesGroup, 0}, // CMD_REMOVE_ALL_VEHICLES_GROUP
{CmdSetGroupReplaceProtection, 0}, // CMD_SET_GROUP_REPLACE_PROTECTION
{CmdMoveOrder, 0}, // CMD_MOVE_ORDER
{CmdChangeTimetable, 0}, // CMD_CHANGE_TIMETABLE
{CmdSetVehicleOnTime, 0}, // CMD_SET_VEHICLE_ON_TIME
{CmdAutofillTimetable, 0}, // CMD_AUTOFILL_TIMETABLE
};
/*!
* This function range-checks a cmd, and checks if the cmd is not NULL
*
* @param cmd The integervalue of a command
* @return true if the command is valid (and got a CommandProc function)
*/
bool IsValidCommand(uint32 cmd)
{
cmd &= CMD_ID_MASK;
return
cmd < lengthof(_command_proc_table) &&
_command_proc_table[cmd].proc != NULL;
}
/*!
* This function mask the parameter with CMD_ID_MASK and returns
* the flags which belongs to the given command.
*
* @param cmd The integer value of the command
* @return The flags for this command
*/
byte GetCommandFlags(uint32 cmd)
{
assert(IsValidCommand(cmd));
return _command_proc_table[cmd & CMD_ID_MASK].flags;
}
static int _docommand_recursive = 0;
/**
* Shorthand for calling the long DoCommand with a container.
*
* @param container Container with (almost) all information
* @param flags Flags for the command and how to execute the command
* @see CommandProc
* @return the cost
*/
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
{
return DoCommand(container->tile, container->p1, container->p2, flags, container->cmd & CMD_ID_MASK, container->text);
}
/*!
* This function executes a given command with the parameters from the #CommandProc parameter list.
* Depending on the flags parameter it execute or test a command.
*
* @param tile The tile to apply the command on (for the #CommandProc)
* @param p1 Additional data for the command (for the #CommandProc)
* @param p2 Additional data for the command (for the #CommandProc)
* @param flags Flags for the command and how to execute the command
* @param cmd The command-id to execute (a value of the CMD_* enums)
* @see CommandProc
* @return the cost
*/
CommandCost DoCommand(TileIndex tile, uint32 p1, uint32 p2, DoCommandFlag flags, uint32 cmd, const char *text)
{
CommandCost res;
/* Do not even think about executing out-of-bounds tile-commands */
if (tile != 0 && (tile >= MapSize() || (!IsValidTile(tile) && (flags & DC_ALL_TILES) == 0))) return CMD_ERROR;
CommandProc *proc = _command_proc_table[cmd].proc;
if (_docommand_recursive == 0) _error_message = INVALID_STRING_ID;
_docommand_recursive++;
/* only execute the test call if it's toplevel, or we're not execing. */
if (_docommand_recursive == 1 || !(flags & DC_EXEC) ) {
SetTownRatingTestMode(true);
res = proc(tile, flags & ~DC_EXEC, p1, p2, text);
SetTownRatingTestMode(false);
if (CmdFailed(res)) {
res.SetGlobalErrorMessage();
goto error;
}
if (_docommand_recursive == 1 &&
!(flags & DC_QUERY_COST) &&
!(flags & DC_BANKRUPT) &&
res.GetCost() != 0 &&
!CheckCompanyHasMoney(res)) {
goto error;
}
if (!(flags & DC_EXEC)) {
_docommand_recursive--;
return res;
}
}
/* Execute the command here. All cost-relevant functions set the expenses type
* themselves to the cost object at some point */
res = proc(tile, flags, p1, p2, text);
if (CmdFailed(res)) {
res.SetGlobalErrorMessage();
error:
_docommand_recursive--;
return CMD_ERROR;
}
/* if toplevel, subtract the money. */
if (--_docommand_recursive == 0 && !(flags & DC_BANKRUPT)) {
SubtractMoneyFromCompany(res);
}
return res;
}
/*!
* This functions returns the money which can be used to execute a command.
* This is either the money of the current company or INT64_MAX if there
* is no such a company "at the moment" like the server itself.
*
* @return The available money of a company or INT64_MAX
*/
Money GetAvailableMoneyForCommand()
{
CompanyID company = _current_company;
if (!IsValidCompanyID(company)) return INT64_MAX;
return GetCompany(company)->money;
}
/**
* Shortcut for the long DoCommandP when having a container with the data.
* @param container the container with information.
* @param my_cmd indicator if the command is from a company or server (to display error messages for a user)
* @return true if the command succeeded, else false
*/
bool DoCommandP(const CommandContainer *container, bool my_cmd)
{
return DoCommandP(container->tile, container->p1, container->p2, container->cmd, container->callback, container->text, my_cmd);
}
/*!
* Toplevel network safe docommand function for the current company. Must not be called recursively.
* The callback is called when the command succeeded or failed. The parameters
* tile, p1 and p2 are from the #CommandProc function. The paramater cmd is the command to execute.
* The parameter my_cmd is used to indicate if the command is from a company or the server.
*
* @param tile The tile to perform a command on (see #CommandProc)
* @param p1 Additional data for the command (see #CommandProc)
* @param p2 Additional data for the command (see #CommandProc)
* @param cmd The command to execute (a CMD_* value)
* @param callback A callback function to call after the command is finished
* @param text The text to pass
* @param my_cmd indicator if the command is from a company or server (to display error messages for a user)
* @return true if the command succeeded, else false
*/
bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, bool my_cmd)
{
assert(_docommand_recursive == 0);
CommandCost res, res2;
int x = TileX(tile) * TILE_SIZE;
int y = TileY(tile) * TILE_SIZE;
_error_message = INVALID_STRING_ID;
StringID error_part1 = GB(cmd, 16, 16);
_additional_cash_required = 0;
CompanyID old_company = _current_company;
/** Spectator has no rights except for the (dedicated) server which
* is/can be a spectator but as the server it can do anything */
#ifndef N3DS /* This check is stupid. Whenever I compile without networking I can't change any options on the title screen. */
if (_current_company == COMPANY_SPECTATOR && !_network_server) {
if (my_cmd) ShowErrorMessage(_error_message, error_part1, x, y);
return false;
}
#endif /* N3DS */
/* get pointer to command handler */
byte cmd_id = cmd & CMD_ID_MASK;
assert(cmd_id < lengthof(_command_proc_table));
CommandProc *proc = _command_proc_table[cmd_id].proc;
if (proc == NULL) return false;
/* Command flags are used internally */
uint cmd_flags = GetCommandFlags(cmd);
/* Flags get send to the DoCommand */
DoCommandFlag flags = CommandFlagsToDCFlags(cmd_flags);
/* Do not even think about executing out-of-bounds tile-commands */
if (tile != 0 && (tile >= MapSize() || (!IsValidTile(tile) && (cmd_flags & CMD_ALL_TILES) == 0))) return false;
/* If the server is a spectator, it may only do server commands! */
if (_current_company == COMPANY_SPECTATOR && (cmd_flags & (CMD_SPECTATOR | CMD_SERVER)) == 0) return false;
bool notest = (cmd_flags & CMD_NO_TEST) != 0;
_docommand_recursive = 1;
/* cost estimation only? */
if (!IsGeneratingWorld() &&
_shift_pressed &&
IsLocalCompany() &&
!(cmd & CMD_NETWORK_COMMAND) &&
cmd_id != CMD_PAUSE) {
/* estimate the cost. */
SetTownRatingTestMode(true);
res = proc(tile, flags, p1, p2, text);
SetTownRatingTestMode(false);
if (CmdFailed(res)) {
res.SetGlobalErrorMessage();
ShowErrorMessage(_error_message, error_part1, x, y);
} else {
ShowEstimatedCostOrIncome(res.GetCost(), x, y);
}
_docommand_recursive = 0;
ClearStorageChanges(false);
return false;
}
if (!((cmd & CMD_NO_TEST_IF_IN_NETWORK) && _networking)) {
/* first test if the command can be executed. */
SetTownRatingTestMode(true);
res = proc(tile, flags, p1, p2, text);
SetTownRatingTestMode(false);
assert(cmd_id == CMD_COMPANY_CTRL || old_company == _current_company);
if (CmdFailed(res)) {
res.SetGlobalErrorMessage();
goto show_error;
}
/* no money? Only check if notest is off */
if (!notest && res.GetCost() != 0 && !CheckCompanyHasMoney(res)) goto show_error;
}
#ifdef ENABLE_NETWORK
/** If we are in network, and the command is not from the network
* send it to the command-queue and abort execution
* If we are a dedicated server temporarily switch local company, otherwise
* the other parties won't be able to execute our command and will desync.
* We also need to do this if the server's company has gone bankrupt
* @todo Rewrite (dedicated) server to something more than a dirty hack!
*/
if (_networking && !(cmd & CMD_NETWORK_COMMAND)) {
CompanyID bck = _local_company;
if (_network_dedicated || (_network_server && bck == COMPANY_SPECTATOR)) _local_company = COMPANY_FIRST;
NetworkSend_Command(tile, p1, p2, cmd & ~CMD_FLAGS_MASK, callback, text);
if (_network_dedicated || (_network_server && bck == COMPANY_SPECTATOR)) _local_company = bck;
_docommand_recursive = 0;
ClearStorageChanges(false);
return true;
}
#endif /* ENABLE_NETWORK */
DEBUG(desync, 1, "cmd: %08x; %08x; %1x; %06x; %08x; %08x; %04x; %s\n", _date, _date_fract, (int)_current_company, tile, p1, p2, cmd & ~CMD_NETWORK_COMMAND, text);
/* update last build coordinate of company. */
if (tile != 0 && IsValidCompanyID(_current_company)) {
GetCompany(_current_company)->last_build_coordinate = tile;
}
/* Actually try and execute the command. If no cost-type is given
* use the construction one */
res2 = proc(tile, flags | DC_EXEC, p1, p2, text);
assert(cmd_id == CMD_COMPANY_CTRL || old_company == _current_company);
/* If notest is on, it means the result of the test can be different than
* the real command.. so ignore the test */
if (!notest && !((cmd & CMD_NO_TEST_IF_IN_NETWORK) && _networking)) {
assert(res.GetCost() == res2.GetCost() && CmdFailed(res) == CmdFailed(res2)); // sanity check
} else {
if (CmdFailed(res2)) {
res.SetGlobalErrorMessage();
goto show_error;
}
}
SubtractMoneyFromCompany(res2);
/* update signals if needed */
UpdateSignalsInBuffer();
if (IsLocalCompany() && _game_mode != GM_EDITOR) {
if (res2.GetCost() != 0 && tile != 0) ShowCostOrIncomeAnimation(x, y, GetSlopeZ(x, y), res2.GetCost());
if (_additional_cash_required != 0) {
SetDParam(0, _additional_cash_required);
if (my_cmd) ShowErrorMessage(STR_0003_NOT_ENOUGH_CASH_REQUIRES, error_part1, x, y);
if (res2.GetCost() == 0) goto callb_err;
}
}
_docommand_recursive = 0;
if (callback) callback(true, tile, p1, p2);
ClearStorageChanges(true);
return true;
show_error:
/* show error message if the command fails? */
if (IsLocalCompany() && error_part1 != 0 && my_cmd) {
ShowErrorMessage(_error_message, error_part1, x, y);
}
callb_err:
_docommand_recursive = 0;
if (callback) callback(false, tile, p1, p2);
ClearStorageChanges(false);
return false;
}
CommandCost CommandCost::AddCost(CommandCost ret)
{
this->AddCost(ret.cost);
if (this->success && !ret.success) {
this->message = ret.message;
this->success = false;
}
return *this;
}
| 24,119
|
C++
|
.cpp
| 528
| 43.545455
| 206
| 0.667988
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,010
|
aircraft_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/aircraft_gui.cpp
|
/* $Id$ */
/** @file aircraft_gui.cpp The GUI of aircraft. */
#include "stdafx.h"
#include "aircraft.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "strings_func.h"
#include "vehicle_func.h"
#include "gfx_func.h"
#include "window_gui.h"
#include "table/sprites.h"
#include "table/strings.h"
/**
* Draw the details for the given vehicle at the position (x, y)
*
* @param v current vehicle
* @param x The x coordinate
* @param y The y coordinate
*/
void DrawAircraftDetails(const Vehicle *v, int x, int y)
{
int y_offset = (v->Next()->cargo_cap != 0) ? -11 : 0;
Money feeder_share = 0;
for (const Vehicle *u = v ; u != NULL ; u = u->Next()) {
if (IsNormalAircraft(u)) {
SetDParam(0, u->engine_type);
SetDParam(1, u->build_year);
SetDParam(2, u->value);
DrawString(x, y, STR_A011_BUILT_VALUE, TC_FROMSTRING);
SetDParam(0, u->cargo_type);
SetDParam(1, u->cargo_cap);
SetDParam(2, u->Next()->cargo_type);
SetDParam(3, u->Next()->cargo_cap);
SetDParam(4, GetCargoSubtypeText(u));
DrawString(x, y + 10, (u->Next()->cargo_cap != 0) ? STR_A019_CAPACITY : STR_A01A_CAPACITY, TC_FROMSTRING);
}
if (u->cargo_cap != 0) {
uint cargo_count = u->cargo.Count();
y_offset += 11;
if (cargo_count != 0) {
/* Cargo names (fix pluralness) */
SetDParam(0, u->cargo_type);
SetDParam(1, cargo_count);
SetDParam(2, u->cargo.Source());
DrawString(x, y + 21 + y_offset, STR_8813_FROM, TC_FROMSTRING);
feeder_share += u->cargo.FeederShare();
}
}
}
SetDParam(0, feeder_share);
DrawString(x, y + 33 + y_offset, STR_FEEDER_CARGO_VALUE, TC_FROMSTRING);
}
void DrawAircraftImage(const Vehicle *v, int x, int y, VehicleID selection)
{
SpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
DrawSprite(v->GetImage(DIR_W), pal, x + 25, y + 10);
if (v->subtype == AIR_HELICOPTER) {
SpriteID rotor_sprite = GetCustomRotorSprite(v, true);
if (rotor_sprite == 0) rotor_sprite = SPR_ROTOR_STOPPED;
DrawSprite(rotor_sprite, PAL_NONE, x + 25, y + 5);
}
if (v->index == selection) {
DrawFrameRect(x - 1, y - 1, x + 58, y + 21, COLOUR_WHITE, FR_BORDERONLY);
}
}
/**
* This is the Callback method after the construction attempt of an aircraft
* @param success indicates completion (or not) of the operation
* @param tile of depot where aircraft is built
* @param p1 unused
* @param p2 unused
*/
void CcBuildAircraft(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
const Vehicle *v = GetVehicle(_new_vehicle_id);
if (v->tile == _backup_orders_tile) {
_backup_orders_tile = 0;
RestoreVehicleOrders(v);
}
ShowVehicleViewWindow(v);
}
}
| 2,686
|
C++
|
.cpp
| 83
| 29.73494
| 109
| 0.673359
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,011
|
widget.cpp
|
EnergeticBark_OpenTTD-3DS/src/widget.cpp
|
/* $Id$ */
/** @file widget.cpp Handling of the default/simple widgets. */
#include "stdafx.h"
#include "company_func.h"
#include "gfx_func.h"
#include "window_gui.h"
#include "table/sprites.h"
#include "table/strings.h"
static const char *UPARROW = "\xEE\x8A\xA0";
static const char *DOWNARROW = "\xEE\x8A\xAA";
/**
* Compute the vertical position of the draggable part of scrollbar
* @param sb Scrollbar list data
* @param top Top position of the scrollbar (top position of the up-button)
* @param bottom Bottom position of the scrollbar (bottom position of the down-button)
* @return A Point, with x containing the top coordinate of the draggable part, and
* y containing the bottom coordinate of the draggable part
*/
static Point HandleScrollbarHittest(const Scrollbar *sb, int top, int bottom)
{
Point pt;
int height, count, pos, cap;
top += 10; // top points to just below the up-button
bottom -= 9; // bottom points to top of the down-button
height = (bottom - top);
pos = sb->pos;
count = sb->count;
cap = sb->cap;
if (count != 0) top += height * pos / count;
if (cap > count) cap = count;
if (count != 0) bottom -= (count - pos - cap) * height / count;
pt.x = top;
pt.y = bottom - 1;
return pt;
}
/** Special handling for the scrollbar widget type.
* Handles the special scrolling buttons and other
* scrolling.
* @param w Window on which a scroll was performed.
* @param wi Pointer to the scrollbar widget.
* @param x The X coordinate of the mouse click.
* @param y The Y coordinate of the mouse click. */
void ScrollbarClickHandler(Window *w, const Widget *wi, int x, int y)
{
int mi, ma, pos;
Scrollbar *sb;
switch (wi->type) {
case WWT_SCROLLBAR:
/* vertical scroller */
w->flags4 &= ~WF_HSCROLL;
w->flags4 &= ~WF_SCROLL2;
mi = wi->top;
ma = wi->bottom;
pos = y;
sb = &w->vscroll;
break;
case WWT_SCROLL2BAR:
/* 2nd vertical scroller */
w->flags4 &= ~WF_HSCROLL;
w->flags4 |= WF_SCROLL2;
mi = wi->top;
ma = wi->bottom;
pos = y;
sb = &w->vscroll2;
break;
case WWT_HSCROLLBAR:
/* horizontal scroller */
w->flags4 &= ~WF_SCROLL2;
w->flags4 |= WF_HSCROLL;
mi = wi->left;
ma = wi->right;
pos = x;
sb = &w->hscroll;
break;
default: NOT_REACHED();
}
if (pos <= mi + 9) {
/* Pressing the upper button? */
w->flags4 |= WF_SCROLL_UP;
if (_scroller_click_timeout == 0) {
_scroller_click_timeout = 6;
if (sb->pos != 0) sb->pos--;
}
_left_button_clicked = false;
} else if (pos >= ma - 10) {
/* Pressing the lower button? */
w->flags4 |= WF_SCROLL_DOWN;
if (_scroller_click_timeout == 0) {
_scroller_click_timeout = 6;
if ((byte)(sb->pos + sb->cap) < sb->count)
sb->pos++;
}
_left_button_clicked = false;
} else {
Point pt = HandleScrollbarHittest(sb, mi, ma);
if (pos < pt.x) {
sb->pos = max(sb->pos - sb->cap, 0);
} else if (pos > pt.y) {
sb->pos = min(
sb->pos + sb->cap,
max(sb->count - sb->cap, 0)
);
} else {
_scrollbar_start_pos = pt.x - mi - 9;
_scrollbar_size = ma - mi - 23;
w->flags4 |= WF_SCROLL_MIDDLE;
_scrolling_scrollbar = true;
_cursorpos_drag_start = _cursor.pos;
}
}
w->SetDirty();
}
/** Returns the index for the widget located at the given position
* relative to the window. It includes all widget-corner pixels as well.
* @param *w Window to look inside
* @param x The Window client X coordinate
* @param y The Window client y coordinate
* @return A widget index, or -1 if no widget was found.
*/
int GetWidgetFromPos(const Window *w, int x, int y)
{
uint index;
int found_index = -1;
/* Go through the widgets and check if we find the widget that the coordinate is
* inside. */
for (index = 0; index < w->widget_count; index++) {
const Widget *wi = &w->widget[index];
if (wi->type == WWT_EMPTY || wi->type == WWT_FRAME) continue;
if (x >= wi->left && x <= wi->right && y >= wi->top && y <= wi->bottom &&
!w->IsWidgetHidden(index)) {
found_index = index;
}
}
return found_index;
}
/**
* Draw frame rectangle.
* @param left Left edge of the frame
* @param top Top edge of the frame
* @param right Right edge of the frame
* @param bottom Bottom edge of the frame
* @param colour Colour table to use. @see _colour_gradient
* @param flags Flags controlling how to draw the frame. @see FrameFlags
*/
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
{
uint dark = _colour_gradient[colour][3];
uint medium_dark = _colour_gradient[colour][5];
uint medium_light = _colour_gradient[colour][6];
uint light = _colour_gradient[colour][7];
if (flags & FR_TRANSPARENT) {
GfxFillRect(left, top, right, bottom, PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR);
} else {
uint interior;
if (flags & FR_LOWERED) {
GfxFillRect(left, top, left, bottom, dark);
GfxFillRect(left + 1, top, right, top, dark);
GfxFillRect(right, top + 1, right, bottom - 1, light);
GfxFillRect(left + 1, bottom, right, bottom, light);
interior = (flags & FR_DARKENED ? medium_dark : medium_light);
} else {
GfxFillRect(left, top, left, bottom - 1, light);
GfxFillRect(left + 1, top, right - 1, top, light);
GfxFillRect(right, top, right, bottom - 1, dark);
GfxFillRect(left, bottom, right, bottom, dark);
interior = medium_dark;
}
if (!(flags & FR_BORDERONLY)) {
GfxFillRect(left + 1, top + 1, right - 1, bottom - 1, interior);
}
}
}
/**
* Paint all widgets of a window.
*/
void Window::DrawWidgets() const
{
const DrawPixelInfo *dpi = _cur_dpi;
for (uint i = 0; i < this->widget_count; i++) {
const Widget *wi = &this->widget[i];
bool clicked = this->IsWidgetLowered(i);
Rect r;
if (dpi->left > (r.right = wi->right) ||
dpi->left + dpi->width <= (r.left = wi->left) ||
dpi->top > (r.bottom = wi->bottom) ||
dpi->top + dpi->height <= (r.top = wi->top) ||
this->IsWidgetHidden(i)) {
continue;
}
switch (wi->type & WWT_MASK) {
case WWT_IMGBTN:
case WWT_IMGBTN_2: {
SpriteID img = wi->data;
assert(img != 0);
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
/* show different image when clicked for WWT_IMGBTN_2 */
if ((wi->type & WWT_MASK) == WWT_IMGBTN_2 && clicked) img++;
DrawSprite(img, PAL_NONE, r.left + 1 + clicked, r.top + 1 + clicked);
break;
}
case WWT_PANEL:
assert(wi->data == 0);
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
break;
case WWT_EDITBOX:
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, FR_LOWERED | FR_DARKENED);
break;
case WWT_TEXTBTN:
case WWT_TEXTBTN_2:
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
/* FALL THROUGH */
case WWT_LABEL: {
StringID str = wi->data;
if ((wi->type & WWT_MASK) == WWT_TEXTBTN_2 && clicked) str++;
DrawStringCentered(((r.left + r.right + 1) >> 1) + clicked, ((r.top + r.bottom + 1) >> 1) - 5 + clicked, str, TC_FROMSTRING);
break;
}
case WWT_TEXT: {
const StringID str = wi->data;
if (str != STR_NULL) DrawStringTruncated(r.left, r.top, str, (TextColour)wi->colour, r.right - r.left);
break;
}
case WWT_INSET: {
const StringID str = wi->data;
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, FR_LOWERED | FR_DARKENED);
if (str != STR_NULL) DrawStringTruncated(r.left + 2, r.top + 1, str, TC_FROMSTRING, r.right - r.left - 10);
break;
}
case WWT_MATRIX: {
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
int c = GB(wi->data, 0, 8);
int amt1 = (wi->right - wi->left + 1) / c;
int d = GB(wi->data, 8, 8);
int amt2 = (wi->bottom - wi->top + 1) / d;
int colour = _colour_gradient[wi->colour & 0xF][6];
int x = r.left;
for (int ctr = c; ctr > 1; ctr--) {
x += amt1;
GfxFillRect(x, r.top + 1, x, r.bottom - 1, colour);
}
x = r.top;
for (int ctr = d; ctr > 1; ctr--) {
x += amt2;
GfxFillRect(r.left + 1, x, r.right - 1, x, colour);
}
colour = _colour_gradient[wi->colour & 0xF][4];
x = r.left - 1;
for (int ctr = c; ctr > 1; ctr--) {
x += amt1;
GfxFillRect(x, r.top + 1, x, r.bottom - 1, colour);
}
x = r.top - 1;
for (int ctr = d; ctr > 1; ctr--) {
x += amt2;
GfxFillRect(r.left + 1, x, r.right - 1, x, colour);
}
break;
}
/* vertical scrollbar */
case WWT_SCROLLBAR: {
assert(wi->data == 0);
assert(r.right - r.left == 11); // To ensure the same sizes are used everywhere!
/* draw up/down buttons */
clicked = ((this->flags4 & (WF_SCROLL_UP | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_UP);
DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
DoDrawString(UPARROW, r.left + 2 + clicked, r.top + clicked, TC_BLACK);
clicked = (((this->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_DOWN));
DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
DoDrawString(DOWNARROW, r.left + 2 + clicked, r.bottom - 9 + clicked, TC_BLACK);
int c1 = _colour_gradient[wi->colour & 0xF][3];
int c2 = _colour_gradient[wi->colour & 0xF][7];
/* draw "shaded" background */
GfxFillRect(r.left, r.top + 10, r.right, r.bottom - 10, c2);
GfxFillRect(r.left, r.top + 10, r.right, r.bottom - 10, c1, FILLRECT_CHECKER);
/* draw shaded lines */
GfxFillRect(r.left + 2, r.top + 10, r.left + 2, r.bottom - 10, c1);
GfxFillRect(r.left + 3, r.top + 10, r.left + 3, r.bottom - 10, c2);
GfxFillRect(r.left + 7, r.top + 10, r.left + 7, r.bottom - 10, c1);
GfxFillRect(r.left + 8, r.top + 10, r.left + 8, r.bottom - 10, c2);
Point pt = HandleScrollbarHittest(&this->vscroll, r.top, r.bottom);
DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->colour, (this->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_MIDDLE ? FR_LOWERED : FR_NONE);
break;
}
case WWT_SCROLL2BAR: {
assert(wi->data == 0);
assert(r.right - r.left == 11); // To ensure the same sizes are used everywhere!
/* draw up/down buttons */
clicked = ((this->flags4 & (WF_SCROLL_UP | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_UP | WF_SCROLL2));
DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
DoDrawString(UPARROW, r.left + 2 + clicked, r.top + clicked, TC_BLACK);
clicked = ((this->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_DOWN | WF_SCROLL2));
DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
DoDrawString(DOWNARROW, r.left + 2 + clicked, r.bottom - 9 + clicked, TC_BLACK);
int c1 = _colour_gradient[wi->colour & 0xF][3];
int c2 = _colour_gradient[wi->colour & 0xF][7];
/* draw "shaded" background */
GfxFillRect(r.left, r.top + 10, r.right, r.bottom - 10, c2);
GfxFillRect(r.left, r.top + 10, r.right, r.bottom - 10, c1, FILLRECT_CHECKER);
/* draw shaded lines */
GfxFillRect(r.left + 2, r.top + 10, r.left + 2, r.bottom - 10, c1);
GfxFillRect(r.left + 3, r.top + 10, r.left + 3, r.bottom - 10, c2);
GfxFillRect(r.left + 7, r.top + 10, r.left + 7, r.bottom - 10, c1);
GfxFillRect(r.left + 8, r.top + 10, r.left + 8, r.bottom - 10, c2);
Point pt = HandleScrollbarHittest(&this->vscroll2, r.top, r.bottom);
DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->colour, (this->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_MIDDLE | WF_SCROLL2) ? FR_LOWERED : FR_NONE);
break;
}
/* horizontal scrollbar */
case WWT_HSCROLLBAR: {
assert(wi->data == 0);
assert(r.bottom - r.top == 11); // To ensure the same sizes are used everywhere!
clicked = ((this->flags4 & (WF_SCROLL_UP | WF_HSCROLL)) == (WF_SCROLL_UP | WF_HSCROLL));
DrawFrameRect(r.left, r.top, r.left + 9, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
DrawSprite(SPR_ARROW_LEFT, PAL_NONE, r.left + 1 + clicked, r.top + 1 + clicked);
clicked = ((this->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL)) == (WF_SCROLL_DOWN | WF_HSCROLL));
DrawFrameRect(r.right - 9, r.top, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
DrawSprite(SPR_ARROW_RIGHT, PAL_NONE, r.right - 8 + clicked, r.top + 1 + clicked);
int c1 = _colour_gradient[wi->colour & 0xF][3];
int c2 = _colour_gradient[wi->colour & 0xF][7];
/* draw "shaded" background */
GfxFillRect(r.left + 10, r.top, r.right - 10, r.bottom, c2);
GfxFillRect(r.left + 10, r.top, r.right - 10, r.bottom, c1, FILLRECT_CHECKER);
/* draw shaded lines */
GfxFillRect(r.left + 10, r.top + 2, r.right - 10, r.top + 2, c1);
GfxFillRect(r.left + 10, r.top + 3, r.right - 10, r.top + 3, c2);
GfxFillRect(r.left + 10, r.top + 7, r.right - 10, r.top + 7, c1);
GfxFillRect(r.left + 10, r.top + 8, r.right - 10, r.top + 8, c2);
/* draw actual scrollbar */
Point pt = HandleScrollbarHittest(&this->hscroll, r.left, r.right);
DrawFrameRect(pt.x, r.top, pt.y, r.bottom, wi->colour, (this->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL)) == (WF_SCROLL_MIDDLE | WF_HSCROLL) ? FR_LOWERED : FR_NONE);
break;
}
case WWT_FRAME: {
const StringID str = wi->data;
int x2 = r.left; // by default the left side is the left side of the widget
if (str != STR_NULL) x2 = DrawString(r.left + 6, r.top, str, TC_FROMSTRING);
int c1 = _colour_gradient[wi->colour][3];
int c2 = _colour_gradient[wi->colour][7];
/* Line from upper left corner to start of text */
GfxFillRect(r.left, r.top + 4, r.left + 4, r.top + 4, c1);
GfxFillRect(r.left + 1, r.top + 5, r.left + 4, r.top + 5, c2);
/* Line from end of text to upper right corner */
GfxFillRect(x2, r.top + 4, r.right - 1, r.top + 4, c1);
GfxFillRect(x2, r.top + 5, r.right - 2, r.top + 5, c2);
/* Line from upper left corner to bottom left corner */
GfxFillRect(r.left, r.top + 5, r.left, r.bottom - 1, c1);
GfxFillRect(r.left + 1, r.top + 6, r.left + 1, r.bottom - 2, c2);
/* Line from upper right corner to bottom right corner */
GfxFillRect(r.right - 1, r.top + 5, r.right - 1, r.bottom - 2, c1);
GfxFillRect(r.right, r.top + 4, r.right, r.bottom - 1, c2);
GfxFillRect(r.left + 1, r.bottom - 1, r.right - 1, r.bottom - 1, c1);
GfxFillRect(r.left, r.bottom, r.right, r.bottom, c2);
break;
}
case WWT_STICKYBOX:
assert(wi->data == 0);
assert(r.right - r.left == 11); // To ensure the same sizes are used everywhere!
clicked = !!(this->flags4 & WF_STICKY);
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
DrawSprite((clicked) ? SPR_PIN_UP : SPR_PIN_DOWN, PAL_NONE, r.left + 2 + clicked, r.top + 3 + clicked);
break;
case WWT_RESIZEBOX:
assert(wi->data == 0);
assert(r.right - r.left == 11); // To ensure the same sizes are used everywhere!
clicked = !!(this->flags4 & WF_SIZING);
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, (clicked) ? FR_LOWERED : FR_NONE);
DrawSprite(SPR_WINDOW_RESIZE, PAL_NONE, r.left + 3 + clicked, r.top + 3 + clicked);
break;
case WWT_CLOSEBOX: {
const StringID str = wi->data;
assert(str == STR_00C5 || str == STR_00C6); // black or silver cross
assert(r.right - r.left == 10); // To ensure the same sizes are used everywhere
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, FR_NONE);
DrawString(r.left + 2, r.top + 2, str, TC_FROMSTRING);
break;
}
case WWT_CAPTION:
assert(r.bottom - r.top == 13); // To ensure the same sizes are used everywhere!
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, FR_BORDERONLY);
DrawFrameRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, wi->colour, (this->owner == INVALID_OWNER) ? FR_LOWERED | FR_DARKENED : FR_LOWERED | FR_DARKENED | FR_BORDERONLY);
if (this->owner != INVALID_OWNER) {
GfxFillRect(r.left + 2, r.top + 2, r.right - 2, r.bottom - 2, _colour_gradient[_company_colours[this->owner]][4]);
}
DrawStringCenteredTruncated(r.left + 2, r.right - 2, r.top + 2, wi->data, TC_FROMSTRING);
break;
case WWT_DROPDOWN: {
assert(r.bottom - r.top == 11); // ensure consistent size
StringID str = wi->data;
DrawFrameRect(r.left, r.top, r.right - 12, r.bottom, wi->colour, FR_NONE);
DrawFrameRect(r.right - 11, r.top, r.right, r.bottom, wi->colour, clicked ? FR_LOWERED : FR_NONE);
DrawString(r.right - (clicked ? 8 : 9), r.top + (clicked ? 2 : 1), STR_0225, TC_BLACK);
if (str != STR_NULL) DrawStringTruncated(r.left + 2, r.top + 1, str, TC_BLACK, r.right - r.left - 12);
break;
}
case WWT_DROPDOWNIN: {
assert(r.bottom - r.top == 11); // ensure consistent size
StringID str = wi->data;
DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->colour, FR_LOWERED | FR_DARKENED);
DrawFrameRect(r.right - 11, r.top + 1, r.right - 1, r.bottom - 1, wi->colour, clicked ? FR_LOWERED : FR_NONE);
DrawString(r.right - (clicked ? 8 : 9), r.top + (clicked ? 2 : 1), STR_0225, TC_BLACK);
if (str != STR_NULL) DrawStringTruncated(r.left + 2, r.top + 2, str, TC_BLACK, r.right - r.left - 12);
break;
}
}
if (this->IsWidgetDisabled(i)) {
GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, _colour_gradient[wi->colour & 0xF][2], FILLRECT_CHECKER);
}
}
if (this->flags4 & WF_WHITE_BORDER_MASK) {
DrawFrameRect(0, 0, this->width - 1, this->height - 1, COLOUR_WHITE, FR_BORDERONLY);
}
}
static void ResizeWidgets(Window *w, byte a, byte b)
{
int16 offset = w->widget[a].left;
int16 length = w->widget[b].right - offset;
w->widget[a].right = (length / 2) + offset;
w->widget[b].left = w->widget[a].right + 1;
}
static void ResizeWidgets(Window *w, byte a, byte b, byte c)
{
int16 offset = w->widget[a].left;
int16 length = w->widget[c].right - offset;
w->widget[a].right = length / 3;
w->widget[b].right = w->widget[a].right * 2;
w->widget[a].right += offset;
w->widget[b].right += offset;
/* Now the right side of the buttons are set. We will now set the left sides next to them */
w->widget[b].left = w->widget[a].right + 1;
w->widget[c].left = w->widget[b].right + 1;
}
/** Evenly distribute some widgets when resizing horizontally (often a button row)
* When only two arguments are given, the widgets are presumed to be on a line and only the ends are given
* @param w Window to modify
* @param left The leftmost widget to resize
* @param right The rightmost widget to resize. Since right side of it is used, remember to set it to RESIZE_RIGHT
*/
void ResizeButtons(Window *w, byte left, byte right)
{
int16 num_widgets = right - left + 1;
if (num_widgets < 2) NOT_REACHED();
switch (num_widgets) {
case 2: ResizeWidgets(w, left, right); break;
case 3: ResizeWidgets(w, left, left + 1, right); break;
default: {
/* Looks like we got more than 3 widgets to resize
* Now we will find the middle of the space desinated for the widgets
* and place half of the widgets on each side of it and call recursively.
* Eventually we will get down to blocks of 2-3 widgets and we got code to handle those cases */
int16 offset = w->widget[left].left;
int16 length = w->widget[right].right - offset;
byte widget = ((num_widgets - 1)/ 2) + left; // rightmost widget of the left side
/* Now we need to find the middle of the widgets.
* It will not always be the middle because if we got an uneven number of widgets,
* we will need it to be 2/5, 3/7 and so on
* To get this, we multiply with num_widgets/num_widgets. Since we calculate in int, we will get:
*
* num_widgets/2 (rounding down)
* ---------------
* num_widgets
*
* as multiplier to length. We just multiply before divide to that we stay in the int area though */
int16 middle = ((length * num_widgets) / (2 * num_widgets)) + offset;
/* Set left and right on the widgets, that's next to our "middle" */
w->widget[widget].right = middle;
w->widget[widget + 1].left = w->widget[widget].right + 1;
/* Now resize the left and right of the middle */
ResizeButtons(w, left, widget);
ResizeButtons(w, widget + 1, right);
}
}
}
/** Resize a widget and shuffle other widgets around to fit. */
void ResizeWindowForWidget(Window *w, uint widget, int delta_x, int delta_y)
{
int right = w->widget[widget].right;
int bottom = w->widget[widget].bottom;
for (uint i = 0; i < w->widget_count; i++) {
if (w->widget[i].left >= right && i != widget) w->widget[i].left += delta_x;
if (w->widget[i].right >= right) w->widget[i].right += delta_x;
if (w->widget[i].top >= bottom && i != widget) w->widget[i].top += delta_y;
if (w->widget[i].bottom >= bottom) w->widget[i].bottom += delta_y;
}
/* A hidden widget has bottom == top or right == left, we need to make it
* one less to fit in its new gap. */
if (right == w->widget[widget].left) w->widget[widget].right--;
if (bottom == w->widget[widget].top) w->widget[widget].bottom--;
if (w->widget[widget].left > w->widget[widget].right) w->widget[widget].right = w->widget[widget].left;
if (w->widget[widget].top > w->widget[widget].bottom) w->widget[widget].bottom = w->widget[widget].top;
w->width += delta_x;
w->height += delta_y;
w->resize.width += delta_x;
w->resize.height += delta_y;
}
/**
* Draw a sort button's up or down arrow symbol.
* @param widget Sort button widget
* @param state State of sort button
*/
void Window::DrawSortButtonState(int widget, SortButtonState state) const
{
if (state == SBS_OFF) return;
int offset = this->IsWidgetLowered(widget) ? 1 : 0;
DoDrawString(state == SBS_DOWN ? DOWNARROW : UPARROW, this->widget[widget].right - 11 + offset, this->widget[widget].top + 1 + offset, TC_BLACK);
}
| 22,008
|
C++
|
.cpp
| 505
| 40.180198
| 181
| 0.639573
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,012
|
timetable_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/timetable_cmd.cpp
|
/* $Id$ */
/** @file timetable_cmd.cpp Commands related to time tabling. */
#include "stdafx.h"
#include "command_func.h"
#include "functions.h"
#include "window_func.h"
#include "vehicle_base.h"
#include "settings_type.h"
#include "table/strings.h"
static void ChangeTimetable(Vehicle *v, VehicleOrderID order_number, uint16 time, bool is_journey)
{
Order *order = GetVehicleOrder(v, order_number);
int delta;
if (is_journey) {
delta = time - order->travel_time;
order->travel_time = time;
} else {
delta = time - order->wait_time;
order->wait_time = time;
}
v->orders.list->UpdateOrderTimetable(delta);
for (v = v->FirstShared(); v != NULL; v = v->NextShared()) {
if (v->cur_order_index == order_number && v->current_order.Equals(*order)) {
if (is_journey) {
v->current_order.travel_time = time;
} else {
v->current_order.wait_time = time;
}
}
InvalidateWindow(WC_VEHICLE_TIMETABLE, v->index);
}
}
/**
* Add or remove waiting times from an order.
* @param tile Not used.
* @param flags Operation to perform.
* @param p1 Various bitstuffed elements
* - p1 = (bit 0-15) - Vehicle with the orders to change.
* - p1 = (bit 16-23) - Order index to modify.
* - p1 = (bit 24) - Whether to change the waiting time or the travelling
* time.
* - p1 = (bit 25) - Whether p2 contains waiting and travelling time.
* @param p2 The amount of time to wait.
* - p2 = (bit 0-15) - Waiting or travelling time as specified by p1 bit 24 if p1 bit 25 is not set,
* Travelling time if p1 bit 25 is set.
* - p2 = (bit 16-31) - Waiting time if p1 bit 25 is set
*/
CommandCost CmdChangeTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!_settings_game.order.timetabling) return CMD_ERROR;
VehicleID veh = GB(p1, 0, 16);
if (!IsValidVehicleID(veh)) return CMD_ERROR;
Vehicle *v = GetVehicle(veh);
if (!CheckOwnership(v->owner)) return CMD_ERROR;
VehicleOrderID order_number = GB(p1, 16, 8);
Order *order = GetVehicleOrder(v, order_number);
if (order == NULL) return CMD_ERROR;
bool packed_time = HasBit(p1, 25);
bool is_journey = HasBit(p1, 24) || packed_time;
int wait_time = order->wait_time;
int travel_time = order->travel_time;
if (packed_time) {
travel_time = GB(p2, 0, 16);
wait_time = GB(p2, 16, 16);;
} else if (is_journey) {
travel_time = GB(p2, 0, 16);
} else {
wait_time = GB(p2, 0, 16);
}
if (wait_time != order->wait_time) {
switch (order->GetType()) {
case OT_GOTO_STATION:
if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return_cmd_error(STR_TIMETABLE_NOT_STOPPING_HERE);
break;
case OT_CONDITIONAL:
break;
default: return_cmd_error(STR_TIMETABLE_ONLY_WAIT_AT_STATIONS);
}
}
if (travel_time != order->travel_time && order->IsType(OT_CONDITIONAL)) return CMD_ERROR;
if (flags & DC_EXEC) {
if (wait_time != order->wait_time) ChangeTimetable(v, order_number, wait_time, false);
if (travel_time != order->travel_time) ChangeTimetable(v, order_number, travel_time, true);
}
return CommandCost();
}
/**
* Clear the lateness counter to make the vehicle on time.
* @param tile Not used.
* @param flags Operation to perform.
* @param p1 Various bitstuffed elements
* - p1 = (bit 0-15) - Vehicle with the orders to change.
*/
CommandCost CmdSetVehicleOnTime(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!_settings_game.order.timetabling) return CMD_ERROR;
VehicleID veh = GB(p1, 0, 16);
if (!IsValidVehicleID(veh)) return CMD_ERROR;
Vehicle *v = GetVehicle(veh);
if (!CheckOwnership(v->owner)) return CMD_ERROR;
if (flags & DC_EXEC) {
v->lateness_counter = 0;
}
return CommandCost();
}
/**
* Start or stop filling the timetable automatically from the time the vehicle
* actually takes to complete it. When starting to autofill the current times
* are cleared and the timetable will start again from scratch.
* @param tile Not used.
* @param flags Operation to perform.
* @param p1 Vehicle index.
* @param p2 Various bitstuffed elements
* - p2 = (bit 0) - Set to 1 to enable, 0 to disable autofill.
* - p2 = (bit 1) - Set to 1 to preserve waiting times in non-destructive mode
*/
CommandCost CmdAutofillTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!_settings_game.order.timetabling) return CMD_ERROR;
VehicleID veh = GB(p1, 0, 16);
if (!IsValidVehicleID(veh)) return CMD_ERROR;
Vehicle *v = GetVehicle(veh);
if (!CheckOwnership(v->owner)) return CMD_ERROR;
if (flags & DC_EXEC) {
if (HasBit(p2, 0)) {
/* Start autofilling the timetable, which clears the
* "timetable has started" bit. Times are not cleared anymore, but are
* overwritten when the order is reached now. */
SetBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
ClrBit(v->vehicle_flags, VF_TIMETABLE_STARTED);
/* Overwrite waiting times only if they got longer */
if (HasBit(p2, 1)) SetBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
v->lateness_counter = 0;
} else {
ClrBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
ClrBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
}
}
for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
if (v2 != v) {
/* Stop autofilling; only one vehicle at a time can perform autofill */
ClrBit(v2->vehicle_flags, VF_AUTOFILL_TIMETABLE);
ClrBit(v2->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
}
InvalidateWindow(WC_VEHICLE_TIMETABLE, v2->index);
}
return CommandCost();
}
void UpdateVehicleTimetable(Vehicle *v, bool travelling)
{
uint timetabled = travelling ? v->current_order.travel_time : v->current_order.wait_time;
uint time_taken = v->current_order_time;
v->current_order_time = 0;
if (!_settings_game.order.timetabling) return;
bool just_started = false;
/* Make sure the timetable only starts when the vehicle reaches the first
* order, not when travelling from the depot to the first station. */
if (v->cur_order_index == 0 && !HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED)) {
SetBit(v->vehicle_flags, VF_TIMETABLE_STARTED);
just_started = true;
}
if (!HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED)) return;
if (HasBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE)) {
if (travelling && !HasBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME)) {
/* Need to clear that now as otherwise we are not able to reduce the wait time */
v->current_order.wait_time = 0;
}
if (just_started) return;
/* Modify station waiting time only if our new value is larger (this is
* always the case when we cleared the timetable). */
if (!v->current_order.IsType(OT_CONDITIONAL) && (travelling || time_taken > v->current_order.wait_time)) {
/* Round the time taken up to the nearest day, as this will avoid
* confusion for people who are timetabling in days, and can be
* adjusted later by people who aren't. */
time_taken = (((time_taken - 1) / DAY_TICKS) + 1) * DAY_TICKS;
ChangeTimetable(v, v->cur_order_index, time_taken, travelling);
}
if (v->cur_order_index == 0 && travelling) {
/* If we just started we would have returned earlier and have not reached
* this code. So obviously, we have completed our round: So turn autofill
* off again. */
ClrBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
ClrBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
}
return;
}
if (just_started) return;
/* Vehicles will wait at stations if they arrive early even if they are not
* timetabled to wait there, so make sure the lateness counter is updated
* when this happens. */
if (timetabled == 0 && (travelling || v->lateness_counter >= 0)) return;
v->lateness_counter -= (timetabled - time_taken);
for (v = v->FirstShared(); v != NULL; v = v->NextShared()) {
InvalidateWindow(WC_VEHICLE_TIMETABLE, v->index);
}
}
| 7,922
|
C++
|
.cpp
| 196
| 37.69898
| 121
| 0.699349
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,014
|
console_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/console_gui.cpp
|
/* $Id$ */
/** @file console_gui.cpp Handling the GUI of the in-game console. */
#include "stdafx.h"
#include "textbuf_gui.h"
#include "window_gui.h"
#include "console_gui.h"
#include "console_internal.h"
#include "window_func.h"
#include "string_func.h"
#include "gfx_func.h"
#include "core/math_func.hpp"
#include "settings_type.h"
#include "rev.h"
#include "table/strings.h"
enum {
ICON_HISTORY_SIZE = 20,
ICON_LINE_HEIGHT = 12,
ICON_RIGHT_BORDERWIDTH = 10,
ICON_BOTTOM_BORDERWIDTH = 12,
};
/**
* Container for a single line of console output
*/
struct IConsoleLine {
static IConsoleLine *front; ///< The front of the console backlog buffer
static int size; ///< The amount of items in the backlog
IConsoleLine *previous; ///< The previous console message.
char *buffer; ///< The data to store.
TextColour colour; ///< The colour of the line.
uint16 time; ///< The amount of time the line is in the backlog.
/**
* Initialize the console line.
* @param buffer the data to print.
* @param colour the colour of the line.
*/
IConsoleLine(char *buffer, TextColour colour) :
previous(IConsoleLine::front),
buffer(buffer),
colour(colour),
time(0)
{
IConsoleLine::front = this;
IConsoleLine::size++;
}
/**
* Clear this console line and any further ones.
*/
~IConsoleLine()
{
IConsoleLine::size--;
free(buffer);
delete previous;
}
/**
* Get the index-ed item in the list.
*/
static const IConsoleLine *Get(uint index)
{
const IConsoleLine *item = IConsoleLine::front;
while (index != 0 && item != NULL) {
index--;
item = item->previous;
}
return item;
}
/**
* Truncate the list removing everything older than/more than the amount
* as specified in the config file.
* As a side effect also increase the time the other lines have been in
* the list.
* @return true if and only if items got removed.
*/
static bool Truncate()
{
IConsoleLine *cur = IConsoleLine::front;
if (cur == NULL) return false;
int count = 1;
for (IConsoleLine *item = cur->previous; item != NULL; count++, cur = item, item = item->previous) {
if (item->time > _settings_client.gui.console_backlog_timeout &&
count > _settings_client.gui.console_backlog_length) {
delete item;
cur->previous = NULL;
return true;
}
if (item->time != MAX_UVALUE(uint16)) item->time++;
}
return false;
}
/**
* Reset the complete console line backlog.
*/
static void Reset()
{
delete IConsoleLine::front;
IConsoleLine::front = NULL;
IConsoleLine::size = 0;
}
};
/* static */ IConsoleLine *IConsoleLine::front = NULL;
/* static */ int IConsoleLine::size = 0;
/* ** main console cmd buffer ** */
static Textbuf _iconsole_cmdline;
static char *_iconsole_history[ICON_HISTORY_SIZE];
static byte _iconsole_historypos;
IConsoleModes _iconsole_mode;
/* *************** *
* end of header *
* *************** */
static void IConsoleClearCommand()
{
memset(_iconsole_cmdline.buf, 0, ICON_CMDLN_SIZE);
_iconsole_cmdline.size = 1; // only terminating zero
_iconsole_cmdline.width = 0;
_iconsole_cmdline.caretpos = 0;
_iconsole_cmdline.caretxoffs = 0;
SetWindowDirty(FindWindowById(WC_CONSOLE, 0));
}
static inline void IConsoleResetHistoryPos() {_iconsole_historypos = ICON_HISTORY_SIZE - 1;}
static void IConsoleHistoryAdd(const char *cmd);
static void IConsoleHistoryNavigate(int direction);
struct IConsoleWindow : Window
{
static int scroll;
IConsoleWindow(const WindowDesc *desc) : Window(desc)
{
_iconsole_mode = ICONSOLE_OPENED;
this->height = _screen.height / 3;
this->width = _screen.width;
}
~IConsoleWindow()
{
_iconsole_mode = ICONSOLE_CLOSED;
}
virtual void OnPaint()
{
int max = (this->height / ICON_LINE_HEIGHT) - 1;
const IConsoleLine *print = IConsoleLine::Get(IConsoleWindow::scroll);
GfxFillRect(this->left, this->top, this->width, this->height - 1, 0);
for (int i = 0; i < max && print != NULL; i++, print = print->previous) {
DoDrawString(print->buffer, 5,
this->height - (2 + i) * ICON_LINE_HEIGHT, print->colour);
}
/* If the text is longer than the window, don't show the starting ']' */
int delta = this->width - 10 - _iconsole_cmdline.width - ICON_RIGHT_BORDERWIDTH;
if (delta > 0) {
DoDrawString("]", 5, this->height - ICON_LINE_HEIGHT, (TextColour)CC_COMMAND);
delta = 0;
}
DoDrawString(_iconsole_cmdline.buf, 10 + delta, this->height - ICON_LINE_HEIGHT, (TextColour)CC_COMMAND);
if (_focused_window == this && _iconsole_cmdline.caret) {
DoDrawString("_", 10 + delta + _iconsole_cmdline.caretxoffs, this->height - ICON_LINE_HEIGHT, TC_WHITE);
}
}
virtual void OnHundredthTick()
{
if (IConsoleLine::Truncate() &&
(IConsoleWindow::scroll > IConsoleLine::size)) {
IConsoleWindow::scroll = max(0, IConsoleLine::size - (this->height / ICON_LINE_HEIGHT) + 1);
this->SetDirty();
}
}
virtual void OnMouseLoop()
{
if (HandleCaret(&_iconsole_cmdline)) this->SetDirty();
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
if (_focused_window != this) return ES_NOT_HANDLED;
const int scroll_height = (this->height / ICON_LINE_HEIGHT) - 1;
switch (keycode) {
case WKC_UP:
IConsoleHistoryNavigate(1);
this->SetDirty();
break;
case WKC_DOWN:
IConsoleHistoryNavigate(-1);
this->SetDirty();
break;
case WKC_SHIFT | WKC_PAGEDOWN:
if (IConsoleWindow::scroll - scroll_height < 0) {
IConsoleWindow::scroll = 0;
} else {
IConsoleWindow::scroll -= scroll_height;
}
this->SetDirty();
break;
case WKC_SHIFT | WKC_PAGEUP:
if (IConsoleWindow::scroll + scroll_height > IConsoleLine::size - scroll_height) {
IConsoleWindow::scroll = IConsoleLine::size - scroll_height;
} else {
IConsoleWindow::scroll += scroll_height;
}
this->SetDirty();
break;
case WKC_SHIFT | WKC_DOWN:
if (IConsoleWindow::scroll <= 0) {
IConsoleWindow::scroll = 0;
} else {
--IConsoleWindow::scroll;
}
this->SetDirty();
break;
case WKC_SHIFT | WKC_UP:
if (IConsoleWindow::scroll >= IConsoleLine::size) {
IConsoleWindow::scroll = IConsoleLine::size;
} else {
++IConsoleWindow::scroll;
}
this->SetDirty();
break;
case WKC_BACKQUOTE:
IConsoleSwitch();
break;
case WKC_RETURN: case WKC_NUM_ENTER:
IConsolePrintF(CC_COMMAND, "] %s", _iconsole_cmdline.buf);
IConsoleHistoryAdd(_iconsole_cmdline.buf);
IConsoleCmdExec(_iconsole_cmdline.buf);
IConsoleClearCommand();
break;
case WKC_CTRL | WKC_RETURN:
_iconsole_mode = (_iconsole_mode == ICONSOLE_FULL) ? ICONSOLE_OPENED : ICONSOLE_FULL;
IConsoleResize(this);
MarkWholeScreenDirty();
break;
case (WKC_CTRL | 'V'):
if (InsertTextBufferClipboard(&_iconsole_cmdline)) {
IConsoleResetHistoryPos();
this->SetDirty();
}
break;
case (WKC_CTRL | 'L'):
IConsoleCmdExec("clear");
break;
case (WKC_CTRL | 'U'):
DeleteTextBufferAll(&_iconsole_cmdline);
this->SetDirty();
break;
case WKC_BACKSPACE: case WKC_DELETE:
if (DeleteTextBufferChar(&_iconsole_cmdline, keycode)) {
IConsoleResetHistoryPos();
this->SetDirty();
}
break;
case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
if (MoveTextBufferPos(&_iconsole_cmdline, keycode)) {
IConsoleResetHistoryPos();
this->SetDirty();
}
break;
default:
if (IsValidChar(key, CS_ALPHANUMERAL)) {
IConsoleWindow::scroll = 0;
InsertTextBufferChar(&_iconsole_cmdline, key);
IConsoleResetHistoryPos();
this->SetDirty();
} else {
return ES_NOT_HANDLED;
}
}
return ES_HANDLED;
}
};
int IConsoleWindow::scroll = 0;
static const Widget _iconsole_window_widgets[] = {
{WIDGETS_END}
};
static const WindowDesc _iconsole_window_desc(
0, 0, 2, 2, 2, 2,
WC_CONSOLE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_iconsole_window_widgets
);
void IConsoleGUIInit()
{
_iconsole_historypos = ICON_HISTORY_SIZE - 1;
_iconsole_mode = ICONSOLE_CLOSED;
IConsoleLine::Reset();
memset(_iconsole_history, 0, sizeof(_iconsole_history));
_iconsole_cmdline.buf = CallocT<char>(ICON_CMDLN_SIZE); // create buffer and zero it
_iconsole_cmdline.maxsize = ICON_CMDLN_SIZE;
IConsolePrintF(CC_WARNING, "OpenTTD Game Console Revision 7 - %s", _openttd_revision);
IConsolePrint(CC_WHITE, "------------------------------------");
IConsolePrint(CC_WHITE, "use \"help\" for more information");
IConsolePrint(CC_WHITE, "");
IConsoleClearCommand();
IConsoleHistoryAdd("");
}
void IConsoleClearBuffer()
{
IConsoleLine::Reset();
}
void IConsoleGUIFree()
{
free(_iconsole_cmdline.buf);
IConsoleClearBuffer();
}
void IConsoleResize(Window *w)
{
switch (_iconsole_mode) {
case ICONSOLE_OPENED:
w->height = _screen.height / 3;
w->width = _screen.width;
break;
case ICONSOLE_FULL:
w->height = _screen.height - ICON_BOTTOM_BORDERWIDTH;
w->width = _screen.width;
break;
default: return;
}
MarkWholeScreenDirty();
}
void IConsoleSwitch()
{
switch (_iconsole_mode) {
case ICONSOLE_CLOSED:
new IConsoleWindow(&_iconsole_window_desc);
break;
case ICONSOLE_OPENED: case ICONSOLE_FULL:
DeleteWindowById(WC_CONSOLE, 0);
break;
}
MarkWholeScreenDirty();
}
void IConsoleClose() {if (_iconsole_mode == ICONSOLE_OPENED) IConsoleSwitch();}
void IConsoleOpen() {if (_iconsole_mode == ICONSOLE_CLOSED) IConsoleSwitch();}
/**
* Add the entered line into the history so you can look it back
* scroll, etc. Put it to the beginning as it is the latest text
* @param cmd Text to be entered into the 'history'
*/
static void IConsoleHistoryAdd(const char *cmd)
{
free(_iconsole_history[ICON_HISTORY_SIZE - 1]);
memmove(&_iconsole_history[1], &_iconsole_history[0], sizeof(_iconsole_history[0]) * (ICON_HISTORY_SIZE - 1));
_iconsole_history[0] = strdup(cmd);
IConsoleResetHistoryPos();
}
/**
* Navigate Up/Down in the history of typed commands
* @param direction Go further back in history (+1), go to recently typed commands (-1)
*/
static void IConsoleHistoryNavigate(int direction)
{
int i = _iconsole_historypos + direction;
/* watch out for overflows, just wrap around */
if (i < 0) i = ICON_HISTORY_SIZE - 1;
if (i >= ICON_HISTORY_SIZE) i = 0;
if (direction > 0) {
if (_iconsole_history[i] == NULL) i = 0;
}
if (direction < 0) {
while (i > 0 && _iconsole_history[i] == NULL) i--;
}
_iconsole_historypos = i;
IConsoleClearCommand();
/* copy history to 'command prompt / bash' */
assert(_iconsole_history[i] != NULL && IsInsideMM(i, 0, ICON_HISTORY_SIZE));
ttd_strlcpy(_iconsole_cmdline.buf, _iconsole_history[i], _iconsole_cmdline.maxsize);
UpdateTextBufferSize(&_iconsole_cmdline);
}
/**
* Handle the printing of text entered into the console or redirected there
* by any other means. Text can be redirected to other clients in a network game
* as well as to a logfile. If the network server is a dedicated server, all activities
* are also logged. All lines to print are added to a temporary buffer which can be
* used as a history to print them onscreen
* @param colour_code the colour of the command. Red in case of errors, etc.
* @param string the message entered or output on the console (notice, error, etc.)
*/
void IConsoleGUIPrint(ConsoleColour colour_code, char *str)
{
new IConsoleLine(str, (TextColour)colour_code);
SetWindowDirty(FindWindowById(WC_CONSOLE, 0));
}
| 11,561
|
C++
|
.cpp
| 374
| 27.828877
| 111
| 0.69336
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,015
|
thread_pthread.cpp
|
EnergeticBark_OpenTTD-3DS/src/thread_pthread.cpp
|
/* $Id$ */
/** @file thread_pthread.cpp POSIX pthread implementation of Threads. */
#include "stdafx.h"
#include "thread.h"
#include <pthread.h>
/**
* POSIX pthread version for ThreadObject.
*/
class ThreadObject_pthread : public ThreadObject {
private:
pthread_t thread; ///< System thread identifier.
OTTDThreadFunc proc; ///< External thread procedure.
void *param; ///< Parameter for the external thread procedure.
bool self_destruct; ///< Free ourselves when done?
public:
/**
* Create a pthread and start it, calling proc(param).
*/
ThreadObject_pthread(OTTDThreadFunc proc, void *param, bool self_destruct) :
thread(0),
proc(proc),
param(param),
self_destruct(self_destruct)
{
pthread_create(&this->thread, NULL, &stThreadProc, this);
}
/* virtual */ bool Exit()
{
assert(pthread_self() == this->thread);
/* For now we terminate by throwing an error, gives much cleaner cleanup */
throw OTTDThreadExitSignal();
}
/* virtual */ void Join()
{
/* You cannot join yourself */
assert(pthread_self() != this->thread);
pthread_join(this->thread, NULL);
this->thread = 0;
}
private:
/**
* On thread creation, this function is called, which calls the real startup
* function. This to get back into the correct instance again.
*/
static void *stThreadProc(void *thr)
{
((ThreadObject_pthread *)thr)->ThreadProc();
pthread_exit(NULL);
}
/**
* A new thread is created, and this function is called. Call the custom
* function of the creator of the thread.
*/
void ThreadProc()
{
/* Call the proc of the creator to continue this thread */
try {
this->proc(this->param);
} catch (OTTDThreadExitSignal e) {
} catch (...) {
NOT_REACHED();
}
if (self_destruct) {
pthread_detach(pthread_self());
delete this;
}
}
};
/* static */ bool ThreadObject::New(OTTDThreadFunc proc, void *param, ThreadObject **thread)
{
ThreadObject *to = new ThreadObject_pthread(proc, param, thread == NULL);
if (thread != NULL) *thread = to;
return true;
}
/**
* POSIX pthread version of ThreadMutex.
*/
class ThreadMutex_pthread : public ThreadMutex {
private:
pthread_mutex_t mutex;
public:
ThreadMutex_pthread()
{
pthread_mutex_init(&this->mutex, NULL);
}
/* virtual */ ~ThreadMutex_pthread()
{
pthread_mutex_destroy(&this->mutex);
}
/* virtual */ void BeginCritical()
{
pthread_mutex_lock(&this->mutex);
}
/* virtual */ void EndCritical()
{
pthread_mutex_unlock(&this->mutex);
}
};
/* static */ ThreadMutex *ThreadMutex::New()
{
return new ThreadMutex_pthread();
}
| 2,584
|
C++
|
.cpp
| 102
| 23
| 92
| 0.698824
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,016
|
rail_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/rail_gui.cpp
|
/* $Id$ */
/** @file rail_gui.cpp File for dealing with rail construction user interface */
#include "stdafx.h"
#include "gui.h"
#include "window_gui.h"
#include "station_gui.h"
#include "terraform_gui.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "command_func.h"
#include "waypoint.h"
#include "newgrf_station.h"
#include "company_base.h"
#include "strings_func.h"
#include "functions.h"
#include "window_func.h"
#include "date_func.h"
#include "sound_func.h"
#include "company_func.h"
#include "widgets/dropdown_type.h"
#include "tunnelbridge.h"
#include "tilehighlight_func.h"
#include "settings_type.h"
#include "station_map.h"
#include "tunnelbridge_map.h"
#include "table/sprites.h"
#include "table/strings.h"
static RailType _cur_railtype; ///< Rail type of the current build-rail toolbar.
static bool _remove_button_clicked; ///< Flag whether 'remove' toggle-button is currently enabled
static DiagDirection _build_depot_direction; ///< Currently selected depot direction
static byte _waypoint_count = 1; ///< Number of waypoint types
static byte _cur_waypoint_type; ///< Currently selected waypoint type
static bool _convert_signal_button; ///< convert signal button in the signal GUI pressed
static SignalVariant _cur_signal_variant; ///< set the signal variant (for signal GUI)
static SignalType _cur_signal_type; ///< set the signal type (for signal GUI)
/* Map the setting: default_signal_type to the corresponding signal type */
static const SignalType _default_signal_type[] = {SIGTYPE_NORMAL, SIGTYPE_PBS, SIGTYPE_PBS_ONEWAY};
struct RailStationGUISettings {
Axis orientation; ///< Currently selected rail station orientation
bool newstations; ///< Are custom station definitions available?
StationClassIDByte station_class; ///< Currently selected custom station class (if newstations is \c true )
byte station_type; ///< Station type within the currently selected custom station class (if newstations is \c true )
byte station_count; ///< Number of custom stations (if newstations is \c true )
};
static RailStationGUISettings _railstation; ///< Settings of the station builder GUI
static void HandleStationPlacement(TileIndex start, TileIndex end);
static void ShowBuildTrainDepotPicker(Window *parent);
static void ShowBuildWaypointPicker(Window *parent);
static void ShowStationBuilder(Window *parent);
static void ShowSignalBuilder(Window *parent);
void CcPlaySound1E(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) SndPlayTileFx(SND_20_SPLAT_2, tile);
}
static void GenericPlaceRail(TileIndex tile, int cmd)
{
DoCommandP(tile, _cur_railtype, cmd,
_remove_button_clicked ?
CMD_REMOVE_SINGLE_RAIL | CMD_MSG(STR_1012_CAN_T_REMOVE_RAILROAD_TRACK) :
CMD_BUILD_SINGLE_RAIL | CMD_MSG(STR_1011_CAN_T_BUILD_RAILROAD_TRACK),
CcPlaySound1E
);
}
static void PlaceRail_N(TileIndex tile)
{
int cmd = _tile_fract_coords.x > _tile_fract_coords.y ? 4 : 5;
GenericPlaceRail(tile, cmd);
}
static void PlaceRail_NE(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_FIX_Y, DDSP_PLACE_RAIL_NE);
}
static void PlaceRail_E(TileIndex tile)
{
int cmd = _tile_fract_coords.x + _tile_fract_coords.y <= 15 ? 2 : 3;
GenericPlaceRail(tile, cmd);
}
static void PlaceRail_NW(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_FIX_X, DDSP_PLACE_RAIL_NW);
}
static void PlaceRail_AutoRail(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_RAILDIRS, DDSP_PLACE_AUTORAIL);
}
/**
* Try to add an additional rail-track at the entrance of a depot
* @param tile Tile to use for adding the rail-track
* @param extra Track to add
* @see CcRailDepot()
*/
static void PlaceExtraDepotRail(TileIndex tile, uint16 extra)
{
if (GetRailTileType(tile) != RAIL_TILE_NORMAL) return;
if ((GetTrackBits(tile) & GB(extra, 8, 8)) == 0) return;
DoCommandP(tile, _cur_railtype, extra & 0xFF, CMD_BUILD_SINGLE_RAIL);
}
/** Additional pieces of track to add at the entrance of a depot. */
static const uint16 _place_depot_extra[12] = {
0x0604, 0x2102, 0x1202, 0x0505, // First additional track for directions 0..3
0x2400, 0x2801, 0x1800, 0x1401, // Second additional track
0x2203, 0x0904, 0x0A05, 0x1103, // Third additional track
};
void CcRailDepot(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
DiagDirection dir = (DiagDirection)p2;
SndPlayTileFx(SND_20_SPLAT_2, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
tile += TileOffsByDiagDir(dir);
if (IsTileType(tile, MP_RAILWAY)) {
PlaceExtraDepotRail(tile, _place_depot_extra[dir]);
PlaceExtraDepotRail(tile, _place_depot_extra[dir + 4]);
PlaceExtraDepotRail(tile, _place_depot_extra[dir + 8]);
}
}
}
static void PlaceRail_Depot(TileIndex tile)
{
DoCommandP(tile, _cur_railtype, _build_depot_direction,
CMD_BUILD_TRAIN_DEPOT | CMD_MSG(STR_100E_CAN_T_BUILD_TRAIN_DEPOT),
CcRailDepot);
}
static void PlaceRail_Waypoint(TileIndex tile)
{
if (_remove_button_clicked) {
DoCommandP(tile, 0, 0, CMD_REMOVE_TRAIN_WAYPOINT | CMD_MSG(STR_CANT_REMOVE_TRAIN_WAYPOINT), CcPlaySound1E);
} else {
DoCommandP(tile, _cur_waypoint_type, 0, CMD_BUILD_TRAIN_WAYPOINT | CMD_MSG(STR_CANT_BUILD_TRAIN_WAYPOINT), CcPlaySound1E);
}
}
void CcStation(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_20_SPLAT_2, tile);
/* Only close the station builder window if the default station and non persistent building is chosen. */
if (_railstation.station_class == STAT_CLASS_DFLT && _railstation.station_type == 0 && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
}
}
static void PlaceRail_Station(TileIndex tile)
{
if (_remove_button_clicked) {
VpStartPlaceSizing(tile, VPM_X_AND_Y_LIMITED, DDSP_REMOVE_STATION);
VpSetPlaceSizingLimit(-1);
} else if (_settings_client.gui.station_dragdrop) {
VpStartPlaceSizing(tile, VPM_X_AND_Y_LIMITED, DDSP_BUILD_STATION);
VpSetPlaceSizingLimit(_settings_game.station.station_spread);
} else {
uint32 p1 = _cur_railtype | _railstation.orientation << 4 | _settings_client.gui.station_numtracks << 8 | _settings_client.gui.station_platlength << 16 | _ctrl_pressed << 24;
uint32 p2 = _railstation.station_class | _railstation.station_type << 8 | INVALID_STATION << 16;
int w = _settings_client.gui.station_numtracks;
int h = _settings_client.gui.station_platlength;
if (!_railstation.orientation) Swap(w, h);
CommandContainer cmdcont = { tile, p1, p2, CMD_BUILD_RAILROAD_STATION | CMD_MSG(STR_100F_CAN_T_BUILD_RAILROAD_STATION), CcStation, "" };
ShowSelectStationIfNeeded(cmdcont, w, h);
}
}
/**
* Build a new signal or edit/remove a present signal, use CmdBuildSingleSignal() or CmdRemoveSingleSignal() in rail_cmd.cpp
*
* @param tile The tile where the signal will build or edit
*/
static void GenericPlaceSignals(TileIndex tile)
{
TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
if (trackbits & TRACK_BIT_VERT) { // N-S direction
trackbits = (_tile_fract_coords.x <= _tile_fract_coords.y) ? TRACK_BIT_RIGHT : TRACK_BIT_LEFT;
}
if (trackbits & TRACK_BIT_HORZ) { // E-W direction
trackbits = (_tile_fract_coords.x + _tile_fract_coords.y <= 15) ? TRACK_BIT_UPPER : TRACK_BIT_LOWER;
}
Track track = FindFirstTrack(trackbits);
if (_remove_button_clicked) {
DoCommandP(tile, track, 0, CMD_REMOVE_SIGNALS | CMD_MSG(STR_1013_CAN_T_REMOVE_SIGNALS_FROM), CcPlaySound1E);
} else {
const Window *w = FindWindowById(WC_BUILD_SIGNAL, 0);
/* Map the setting cycle_signal_types to the lower and upper allowed signal type. */
static const uint cycle_bounds[] = {SIGTYPE_NORMAL | (SIGTYPE_LAST_NOPBS << 3), SIGTYPE_PBS | (SIGTYPE_LAST << 3), SIGTYPE_NORMAL | (SIGTYPE_LAST << 3)};
/* various bitstuffed elements for CmdBuildSingleSignal() */
uint32 p1 = track;
if (w != NULL) {
/* signal GUI is used */
SB(p1, 3, 1, _ctrl_pressed);
SB(p1, 4, 1, _cur_signal_variant);
SB(p1, 5, 3, _cur_signal_type);
SB(p1, 8, 1, _convert_signal_button);
SB(p1, 9, 6, cycle_bounds[_settings_client.gui.cycle_signal_types]);
} else {
SB(p1, 3, 1, _ctrl_pressed);
SB(p1, 4, 1, (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC));
SB(p1, 5, 3, _default_signal_type[_settings_client.gui.default_signal_type]);
SB(p1, 8, 1, 0);
SB(p1, 9, 6, cycle_bounds[_settings_client.gui.cycle_signal_types]);
}
DoCommandP(tile, p1, 0, CMD_BUILD_SIGNALS |
CMD_MSG((w != NULL && _convert_signal_button) ? STR_SIGNAL_CAN_T_CONVERT_SIGNALS_HERE : STR_1010_CAN_T_BUILD_SIGNALS_HERE),
CcPlaySound1E);
}
}
static void PlaceRail_Bridge(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_OR_Y, DDSP_BUILD_BRIDGE);
}
/** Command callback for building a tunnel */
void CcBuildRailTunnel(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_20_SPLAT_2, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
} else {
SetRedErrorSquare(_build_tunnel_endtile);
}
}
static void PlaceRail_Tunnel(TileIndex tile)
{
DoCommandP(tile, _cur_railtype, 0, CMD_BUILD_TUNNEL | CMD_MSG(STR_5016_CAN_T_BUILD_TUNNEL_HERE), CcBuildRailTunnel);
}
static void PlaceRail_ConvertRail(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_CONVERT_RAIL);
}
static void PlaceRail_AutoSignals(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_SIGNALDIRS, DDSP_BUILD_SIGNALS);
}
/** Enum referring to the widgets of the build rail toolbar */
enum RailToolbarWidgets {
RTW_CLOSEBOX = 0,
RTW_CAPTION,
RTW_STICKY,
RTW_SPACER,
RTW_BUILD_NS,
RTW_BUILD_X,
RTW_BUILD_EW,
RTW_BUILD_Y,
RTW_AUTORAIL,
RTW_DEMOLISH,
RTW_BUILD_DEPOT,
RTW_BUILD_WAYPOINT,
RTW_BUILD_STATION,
RTW_BUILD_SIGNALS,
RTW_BUILD_BRIDGE,
RTW_BUILD_TUNNEL,
RTW_REMOVE,
RTW_CONVERT_RAIL,
};
/** Toggles state of the Remove button of Build rail toolbar
* @param w window the button belongs to
*/
static void ToggleRailButton_Remove(Window *w)
{
DeleteWindowById(WC_SELECT_STATION, 0);
w->ToggleWidgetLoweredState(RTW_REMOVE);
w->InvalidateWidget(RTW_REMOVE);
_remove_button_clicked = w->IsWidgetLowered(RTW_REMOVE);
SetSelectionRed(_remove_button_clicked);
}
/** Updates the Remove button because of Ctrl state change
* @param w window the button belongs to
* @return true iff the remove buton was changed
*/
static bool RailToolbar_CtrlChanged(Window *w)
{
if (w->IsWidgetDisabled(RTW_REMOVE)) return false;
/* allow ctrl to switch remove mode only for these widgets */
for (uint i = RTW_BUILD_NS; i <= RTW_BUILD_STATION; i++) {
if ((i <= RTW_AUTORAIL || i >= RTW_BUILD_WAYPOINT) && w->IsWidgetLowered(i)) {
ToggleRailButton_Remove(w);
return true;
}
}
return false;
}
/**
* The "rail N"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_N(Window *w)
{
HandlePlacePushButton(w, RTW_BUILD_NS, GetRailTypeInfo(_cur_railtype)->cursor.rail_ns, VHM_RECT, PlaceRail_N);
}
/**
* The "rail NE"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_NE(Window *w)
{
HandlePlacePushButton(w, RTW_BUILD_X, GetRailTypeInfo(_cur_railtype)->cursor.rail_swne, VHM_RECT, PlaceRail_NE);
}
/**
* The "rail E"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_E(Window *w)
{
HandlePlacePushButton(w, RTW_BUILD_EW, GetRailTypeInfo(_cur_railtype)->cursor.rail_ew, VHM_RECT, PlaceRail_E);
}
/**
* The "rail NW"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_NW(Window *w)
{
HandlePlacePushButton(w, RTW_BUILD_Y, GetRailTypeInfo(_cur_railtype)->cursor.rail_nwse, VHM_RECT, PlaceRail_NW);
}
/**
* The "auto-rail"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_AutoRail(Window *w)
{
HandlePlacePushButton(w, RTW_AUTORAIL, GetRailTypeInfo(_cur_railtype)->cursor.autorail, VHM_RAIL, PlaceRail_AutoRail);
}
/**
* The "demolish"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_Demolish(Window *w)
{
HandlePlacePushButton(w, RTW_DEMOLISH, ANIMCURSOR_DEMOLISH, VHM_RECT, PlaceProc_DemolishArea);
}
/**
* The "build depot"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_Depot(Window *w)
{
if (HandlePlacePushButton(w, RTW_BUILD_DEPOT, GetRailTypeInfo(_cur_railtype)->cursor.depot, VHM_RECT, PlaceRail_Depot)) {
ShowBuildTrainDepotPicker(w);
}
}
/**
* The "build waypoint"-button click proc of the build-rail toolbar.
* If there are newGRF waypoints, also open a window to pick the waypoint type.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_Waypoint(Window *w)
{
_waypoint_count = GetNumCustomStations(STAT_CLASS_WAYP);
if (HandlePlacePushButton(w, RTW_BUILD_WAYPOINT, SPR_CURSOR_WAYPOINT, VHM_RECT, PlaceRail_Waypoint) &&
_waypoint_count > 1) {
ShowBuildWaypointPicker(w);
}
}
/**
* The "build station"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_Station(Window *w)
{
if (HandlePlacePushButton(w, RTW_BUILD_STATION, SPR_CURSOR_RAIL_STATION, VHM_RECT, PlaceRail_Station)) ShowStationBuilder(w);
}
/**
* The "build signal"-button click proc of the build-rail toolbar.
* Start ShowSignalBuilder() and/or HandleAutoSignalPlacement().
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_AutoSignals(Window *w)
{
if (_settings_client.gui.enable_signal_gui != _ctrl_pressed) {
if (HandlePlacePushButton(w, RTW_BUILD_SIGNALS, ANIMCURSOR_BUILDSIGNALS, VHM_RECT, PlaceRail_AutoSignals)) ShowSignalBuilder(w);
} else {
HandlePlacePushButton(w, RTW_BUILD_SIGNALS, ANIMCURSOR_BUILDSIGNALS, VHM_RECT, PlaceRail_AutoSignals);
}
}
/**
* The "build bridge"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_Bridge(Window *w)
{
HandlePlacePushButton(w, RTW_BUILD_BRIDGE, SPR_CURSOR_BRIDGE, VHM_RECT, PlaceRail_Bridge);
}
/**
* The "build tunnel"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_Tunnel(Window *w)
{
HandlePlacePushButton(w, RTW_BUILD_TUNNEL, GetRailTypeInfo(_cur_railtype)->cursor.tunnel, VHM_SPECIAL, PlaceRail_Tunnel);
}
/**
* The "remove"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_Remove(Window *w)
{
if (w->IsWidgetDisabled(RTW_REMOVE)) return;
ToggleRailButton_Remove(w);
SndPlayFx(SND_15_BEEP);
/* handle station builder */
if (w->IsWidgetLowered(RTW_BUILD_STATION)) {
if (_remove_button_clicked) {
/* starting drag & drop remove */
if (!_settings_client.gui.station_dragdrop) {
SetTileSelectSize(1, 1);
} else {
VpSetPlaceSizingLimit(-1);
}
} else {
/* starting station build mode */
if (!_settings_client.gui.station_dragdrop) {
int x = _settings_client.gui.station_numtracks;
int y = _settings_client.gui.station_platlength;
if (_railstation.orientation == 0) Swap(x, y);
SetTileSelectSize(x, y);
} else {
VpSetPlaceSizingLimit(_settings_game.station.station_spread);
}
}
}
}
/**
* The "convert-rail"-button click proc of the build-rail toolbar.
* Switches to 'convert-rail' mode
* @param w Build-rail toolbar window
* @see BuildRailToolbWndProc()
*/
static void BuildRailClick_Convert(Window *w)
{
HandlePlacePushButton(w, RTW_CONVERT_RAIL, GetRailTypeInfo(_cur_railtype)->cursor.convert, VHM_RECT, PlaceRail_ConvertRail);
}
static void DoRailroadTrack(int mode)
{
DoCommandP(TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y), _cur_railtype | (mode << 4),
_remove_button_clicked ?
CMD_REMOVE_RAILROAD_TRACK | CMD_MSG(STR_1012_CAN_T_REMOVE_RAILROAD_TRACK) :
CMD_BUILD_RAILROAD_TRACK | CMD_MSG(STR_1011_CAN_T_BUILD_RAILROAD_TRACK)
);
}
static void HandleAutodirPlacement()
{
TileHighlightData *thd = &_thd;
int trackstat = thd->drawstyle & 0xF; // 0..5
if (thd->drawstyle & HT_RAIL) { // one tile case
GenericPlaceRail(TileVirtXY(thd->selend.x, thd->selend.y), trackstat);
return;
}
DoRailroadTrack(trackstat);
}
/**
* Build new signals or remove signals or (if only one tile marked) edit a signal.
*
* If one tile marked abort and use GenericPlaceSignals()
* else use CmdBuildSingleSignal() or CmdRemoveSingleSignal() in rail_cmd.cpp to build many signals
*/
static void HandleAutoSignalPlacement()
{
TileHighlightData *thd = &_thd;
uint32 p2 = GB(thd->drawstyle, 0, 3); // 0..5
if (thd->drawstyle == HT_RECT) { // one tile case
GenericPlaceSignals(TileVirtXY(thd->selend.x, thd->selend.y));
return;
}
const Window *w = FindWindowById(WC_BUILD_SIGNAL, 0);
if (w != NULL) {
/* signal GUI is used */
SB(p2, 3, 1, 0);
SB(p2, 4, 1, _cur_signal_variant);
SB(p2, 6, 1, _ctrl_pressed);
SB(p2, 7, 3, _cur_signal_type);
SB(p2, 24, 8, _settings_client.gui.drag_signals_density);
} else {
SB(p2, 3, 1, 0);
SB(p2, 4, 1, (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC));
SB(p2, 6, 1, _ctrl_pressed);
SB(p2, 7, 3, _default_signal_type[_settings_client.gui.default_signal_type]);
SB(p2, 24, 8, _settings_client.gui.drag_signals_density);
}
/* _settings_client.gui.drag_signals_density is given as a parameter such that each user
* in a network game can specify his/her own signal density */
DoCommandP(
TileVirtXY(thd->selstart.x, thd->selstart.y),
TileVirtXY(thd->selend.x, thd->selend.y),
p2,
_remove_button_clicked ?
CMD_REMOVE_SIGNAL_TRACK | CMD_MSG(STR_1013_CAN_T_REMOVE_SIGNALS_FROM) :
CMD_BUILD_SIGNAL_TRACK | CMD_MSG(STR_1010_CAN_T_BUILD_SIGNALS_HERE),
CcPlaySound1E);
}
typedef void OnButtonClick(Window *w);
/** Data associated with a push button in the build rail toolbar window */
struct RailBuildingGUIButtonData {
uint16 keycode; ///< Keycode associated with the button
OnButtonClick *click_proc; ///< Procedure to call when button is clicked
};
/**
* GUI rail-building button data constants.
* Offsets match widget order, starting at RTW_BUILD_NS
*/
static const RailBuildingGUIButtonData _rail_build_button_data[] = {
{'1', BuildRailClick_N },
{'2', BuildRailClick_NE },
{'3', BuildRailClick_E },
{'4', BuildRailClick_NW },
{'5', BuildRailClick_AutoRail },
{'6', BuildRailClick_Demolish },
{'7', BuildRailClick_Depot },
{'8', BuildRailClick_Waypoint },
{'9', BuildRailClick_Station },
{'S', BuildRailClick_AutoSignals},
{'B', BuildRailClick_Bridge },
{'T', BuildRailClick_Tunnel },
{'R', BuildRailClick_Remove },
{'C', BuildRailClick_Convert }
};
/**
* Based on the widget clicked, update the status of the 'remove' button.
* @param w Rail toolbar window
* @param clicked_widget Widget clicked in the toolbar
*/
struct BuildRailToolbarWindow : Window {
BuildRailToolbarWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->DisableWidget(RTW_REMOVE);
this->FindWindowPlacementAndResize(desc);
if (_settings_client.gui.link_terraform_toolbar) ShowTerraformToolbar(this);
}
~BuildRailToolbarWindow()
{
if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false);
}
void UpdateRemoveWidgetStatus(int clicked_widget)
{
switch (clicked_widget) {
case RTW_REMOVE:
/* If it is the removal button that has been clicked, do nothing,
* as it is up to the other buttons to drive removal status */
return;
break;
case RTW_BUILD_NS:
case RTW_BUILD_X:
case RTW_BUILD_EW:
case RTW_BUILD_Y:
case RTW_AUTORAIL:
case RTW_BUILD_WAYPOINT:
case RTW_BUILD_STATION:
case RTW_BUILD_SIGNALS:
/* Removal button is enabled only if the rail/signal/waypoint/station
* button is still lowered. Once raised, it has to be disabled */
this->SetWidgetDisabledState(RTW_REMOVE, !this->IsWidgetLowered(clicked_widget));
break;
default:
/* When any other buttons than rail/signal/waypoint/station, raise and
* disable the removal button */
this->DisableWidget(RTW_REMOVE);
this->RaiseWidget(RTW_REMOVE);
break;
}
}
virtual void OnPaint()
{
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
if (widget >= RTW_BUILD_NS) {
_remove_button_clicked = false;
_rail_build_button_data[widget - RTW_BUILD_NS].click_proc(this);
}
this->UpdateRemoveWidgetStatus(widget);
if (_ctrl_pressed) RailToolbar_CtrlChanged(this);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
EventState state = ES_NOT_HANDLED;
for (uint8 i = 0; i != lengthof(_rail_build_button_data); i++) {
if (keycode == _rail_build_button_data[i].keycode) {
_remove_button_clicked = false;
_rail_build_button_data[i].click_proc(this);
this->UpdateRemoveWidgetStatus(i + RTW_BUILD_NS);
if (_ctrl_pressed) RailToolbar_CtrlChanged(this);
state = ES_HANDLED;
break;
}
}
MarkTileDirty(_thd.pos.x, _thd.pos.y); // redraw tile selection
return state;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_place_proc(tile);
}
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
{
/* no dragging if you have pressed the convert button */
if (FindWindowById(WC_BUILD_SIGNAL, 0) != NULL && _convert_signal_button && this->IsWidgetLowered(RTW_BUILD_SIGNALS)) return;
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
{
if (pt.x != -1) {
switch (select_proc) {
default: NOT_REACHED();
case DDSP_BUILD_BRIDGE:
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
ShowBuildBridgeWindow(start_tile, end_tile, TRANSPORT_RAIL, _cur_railtype);
break;
case DDSP_PLACE_AUTORAIL:
HandleAutodirPlacement();
break;
case DDSP_BUILD_SIGNALS:
HandleAutoSignalPlacement();
break;
case DDSP_DEMOLISH_AREA:
GUIPlaceProcDragXY(select_proc, start_tile, end_tile);
break;
case DDSP_CONVERT_RAIL:
DoCommandP(end_tile, start_tile, _cur_railtype, CMD_CONVERT_RAIL | CMD_MSG(STR_CANT_CONVERT_RAIL), CcPlaySound10);
break;
case DDSP_REMOVE_STATION:
case DDSP_BUILD_STATION:
if (_remove_button_clicked) {
DoCommandP(end_tile, start_tile, 0, CMD_REMOVE_FROM_RAILROAD_STATION | CMD_MSG(STR_CANT_REMOVE_PART_OF_STATION), CcPlaySound1E);
break;
}
HandleStationPlacement(start_tile, end_tile);
break;
case DDSP_PLACE_RAIL_NE:
case DDSP_PLACE_RAIL_NW:
DoRailroadTrack(select_proc == DDSP_PLACE_RAIL_NE ? TRACK_X : TRACK_Y);
break;
}
}
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
this->DisableWidget(RTW_REMOVE);
this->InvalidateWidget(RTW_REMOVE);
DeleteWindowById(WC_BUILD_SIGNAL, 0);
DeleteWindowById(WC_BUILD_STATION, 0);
DeleteWindowById(WC_BUILD_DEPOT, 0);
DeleteWindowById(WC_SELECT_STATION, 0);
DeleteWindowById(WC_BUILD_BRIDGE, 0);
}
virtual void OnPlacePresize(Point pt, TileIndex tile)
{
DoCommand(tile, 0, 0, DC_AUTO, CMD_BUILD_TUNNEL);
VpSetPresizeRange(tile, _build_tunnel_endtile == 0 ? tile : _build_tunnel_endtile);
}
virtual EventState OnCTRLStateChange()
{
/* do not toggle Remove button by Ctrl when placing station */
if (!this->IsWidgetLowered(RTW_BUILD_STATION) && RailToolbar_CtrlChanged(this)) return ES_HANDLED;
return ES_NOT_HANDLED;
}
};
/** Widget definition for the rail toolbar */
static const Widget _build_rail_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // RTW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 337, 0, 13, STR_100A_RAILROAD_CONSTRUCTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // RTW_CAPTION
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 338, 349, 0, 13, 0x0, STR_STICKY_BUTTON}, // RTW_STICKY
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 110, 113, 14, 35, 0x0, STR_NULL}, // RTW_SPACER
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 35, SPR_IMG_RAIL_NS, STR_1018_BUILD_RAILROAD_TRACK}, // RTW_BUILD_NS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 35, SPR_IMG_RAIL_NE, STR_1018_BUILD_RAILROAD_TRACK}, // RTW_BUILD_X
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 65, 14, 35, SPR_IMG_RAIL_EW, STR_1018_BUILD_RAILROAD_TRACK}, // RTW_BUILD_EW
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 66, 87, 14, 35, SPR_IMG_RAIL_NW, STR_1018_BUILD_RAILROAD_TRACK}, // RTW_BUILD_Y
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 88, 109, 14, 35, SPR_IMG_AUTORAIL, STR_BUILD_AUTORAIL_TIP}, // RTW_AUTORAIL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 114, 135, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC}, // RTW_DEMOLISH
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 136, 157, 14, 35, SPR_IMG_DEPOT_RAIL, STR_1019_BUILD_TRAIN_DEPOT_FOR_BUILDING}, // RTW_BUILD_DEPOT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 158, 179, 14, 35, SPR_IMG_WAYPOINT, STR_CONVERT_RAIL_TO_WAYPOINT_TIP}, // RTW_BUILD_WAYPOINT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 180, 221, 14, 35, SPR_IMG_RAIL_STATION, STR_101A_BUILD_RAILROAD_STATION}, // RTW_BUILD_STATION
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 222, 243, 14, 35, SPR_IMG_RAIL_SIGNALS, STR_101B_BUILD_RAILROAD_SIGNALS}, // RTW_BUILD_SIGNALS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 244, 285, 14, 35, SPR_IMG_BRIDGE, STR_101C_BUILD_RAILROAD_BRIDGE}, // RTW_BUILD_BRIDGE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 286, 305, 14, 35, SPR_IMG_TUNNEL_RAIL, STR_101D_BUILD_RAILROAD_TUNNEL}, // RTW_BUILD_TUNNEL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 306, 327, 14, 35, SPR_IMG_REMOVE, STR_101E_TOGGLE_BUILD_REMOVE_FOR}, // RTW_REMOVE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 328, 349, 14, 35, SPR_IMG_CONVERT_RAIL, STR_CONVERT_RAIL_TIP}, // RTW_CONVERT_RAIL
{ WIDGETS_END},
};
static const WindowDesc _build_rail_desc(
WDP_ALIGN_TBR, 22, 350, 36, 350, 36,
WC_BUILD_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_build_rail_widgets
);
/** Configures the rail toolbar for railtype given
* @param railtype the railtype to display
* @param w the window to modify
*/
static void SetupRailToolbar(RailType railtype, Window *w)
{
const RailtypeInfo *rti = GetRailTypeInfo(railtype);
assert(railtype < RAILTYPE_END);
w->widget[RTW_CAPTION].data = rti->strings.toolbar_caption;
w->widget[RTW_BUILD_NS].data = rti->gui_sprites.build_ns_rail;
w->widget[RTW_BUILD_X].data = rti->gui_sprites.build_x_rail;
w->widget[RTW_BUILD_EW].data = rti->gui_sprites.build_ew_rail;
w->widget[RTW_BUILD_Y].data = rti->gui_sprites.build_y_rail;
w->widget[RTW_AUTORAIL].data = rti->gui_sprites.auto_rail;
w->widget[RTW_BUILD_DEPOT].data = rti->gui_sprites.build_depot;
w->widget[RTW_CONVERT_RAIL].data = rti->gui_sprites.convert_rail;
w->widget[RTW_BUILD_TUNNEL].data = rti->gui_sprites.build_tunnel;
}
/**
* Open the build rail toolbar window for a specific rail type.
* The window may be opened in the 'normal' way by clicking at the rail icon in
* the main toolbar, or by means of selecting one of the functions of the
* toolbar. In the latter case, the corresponding widget is also selected.
*
* If the terraform toolbar is linked to the toolbar, that window is also opened.
*
* @param railtype Rail type to open the window for
* @param button Widget clicked (\c -1 means no button clicked)
*/
void ShowBuildRailToolbar(RailType railtype, int button)
{
BuildRailToolbarWindow *w;
if (!IsValidCompanyID(_local_company)) return;
if (!ValParamRailtype(railtype)) return;
/* don't recreate the window if we're clicking on a button and the window exists. */
if (button < 0 || !(w = dynamic_cast<BuildRailToolbarWindow*>(FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL)))) {
DeleteWindowByClass(WC_BUILD_TOOLBAR);
_cur_railtype = railtype;
w = AllocateWindowDescFront<BuildRailToolbarWindow>(&_build_rail_desc, TRANSPORT_RAIL);
SetupRailToolbar(railtype, w);
}
_remove_button_clicked = false;
if (w != NULL && button >= RTW_CLOSEBOX) {
_rail_build_button_data[button].click_proc(w);
w->UpdateRemoveWidgetStatus(button + RTW_BUILD_NS);
}
}
/* TODO: For custom stations, respect their allowed platforms/lengths bitmasks!
* --pasky */
static void HandleStationPlacement(TileIndex start, TileIndex end)
{
uint sx = TileX(start);
uint sy = TileY(start);
uint ex = TileX(end);
uint ey = TileY(end);
uint w, h;
if (sx > ex) Swap(sx, ex);
if (sy > ey) Swap(sy, ey);
w = ex - sx + 1;
h = ey - sy + 1;
uint numtracks = w;
uint platlength = h;
if (_railstation.orientation == AXIS_X) Swap(numtracks, platlength);
uint32 p1 = _cur_railtype | _railstation.orientation << 4 | _ctrl_pressed << 24;
uint32 p2 = _railstation.station_class | _railstation.station_type << 8 | INVALID_STATION << 16;
CommandContainer cmdcont = { TileXY(sx, sy), p1 | numtracks << 8 | platlength << 16, p2, CMD_BUILD_RAILROAD_STATION | CMD_MSG(STR_100F_CAN_T_BUILD_RAILROAD_STATION), CcStation, "" };
ShowSelectStationIfNeeded(cmdcont, w, h);
}
struct BuildRailStationWindow : public PickerWindowBase {
private:
/** Enum referring to the widgets of the rail stations window */
enum BuildRailStationWidgets {
BRSW_CLOSEBOX = 0,
BRSW_CAPTION,
BRSW_BACKGROUND,
BRSW_PLATFORM_DIR_X,
BRSW_PLATFORM_DIR_Y,
BRSW_PLATFORM_NUM_BEGIN = BRSW_PLATFORM_DIR_Y,
BRSW_PLATFORM_NUM_1,
BRSW_PLATFORM_NUM_2,
BRSW_PLATFORM_NUM_3,
BRSW_PLATFORM_NUM_4,
BRSW_PLATFORM_NUM_5,
BRSW_PLATFORM_NUM_6,
BRSW_PLATFORM_NUM_7,
BRSW_PLATFORM_LEN_BEGIN = BRSW_PLATFORM_NUM_7,
BRSW_PLATFORM_LEN_1,
BRSW_PLATFORM_LEN_2,
BRSW_PLATFORM_LEN_3,
BRSW_PLATFORM_LEN_4,
BRSW_PLATFORM_LEN_5,
BRSW_PLATFORM_LEN_6,
BRSW_PLATFORM_LEN_7,
BRSW_PLATFORM_DRAG_N_DROP,
BRSW_HIGHLIGHT_OFF,
BRSW_HIGHLIGHT_ON,
BRSW_NEWST_DROPDOWN,
BRSW_NEWST_LIST,
BRSW_NEWST_SCROLL
};
/**
* Verify whether the currently selected station size is allowed after selecting a new station class/type.
* If not, change the station size variables ( _settings_client.gui.station_numtracks and _settings_client.gui.station_platlength ).
* @param statspec Specification of the new station class/type
*/
void CheckSelectedSize(const StationSpec *statspec)
{
if (statspec == NULL || _settings_client.gui.station_dragdrop) return;
/* If current number of tracks is not allowed, make it as big as possible (which is always less than currently selected) */
if (HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
this->RaiseWidget(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN);
_settings_client.gui.station_numtracks = 1;
while (HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
_settings_client.gui.station_numtracks++;
}
this->LowerWidget(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN);
}
if (HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
this->RaiseWidget(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN);
_settings_client.gui.station_platlength = 1;
while (HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
_settings_client.gui.station_platlength++;
}
this->LowerWidget(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN);
}
}
/** Build a dropdown list of available station classes */
static DropDownList *BuildStationClassDropDown()
{
DropDownList *list = new DropDownList();
for (uint i = 0; i < GetNumStationClasses(); i++) {
if (i == STAT_CLASS_WAYP) continue;
list->push_back(new DropDownListStringItem(GetStationClassName((StationClassID)i), i, false));
}
return list;
}
/**
* Window event handler of station build window.
* @param w Staion build window
* @param e Window event to handle
*/
public:
BuildRailStationWindow(const WindowDesc *desc, Window *parent, bool newstation) : PickerWindowBase(desc, parent)
{
this->LowerWidget(_railstation.orientation + BRSW_PLATFORM_DIR_X);
if (_settings_client.gui.station_dragdrop) {
this->LowerWidget(BRSW_PLATFORM_DRAG_N_DROP);
} else {
this->LowerWidget(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN);
this->LowerWidget(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN);
}
this->SetWidgetLoweredState(BRSW_HIGHLIGHT_OFF, !_settings_client.gui.station_show_coverage);
this->SetWidgetLoweredState(BRSW_HIGHLIGHT_ON, _settings_client.gui.station_show_coverage);
this->FindWindowPlacementAndResize(desc);
_railstation.newstations = newstation;
if (newstation) {
_railstation.station_count = GetNumCustomStations(_railstation.station_class);
this->vscroll.count = _railstation.station_count;
this->vscroll.cap = 5;
this->vscroll.pos = Clamp(_railstation.station_type - 2, 0, this->vscroll.count - this->vscroll.cap);
}
}
virtual ~BuildRailStationWindow()
{
DeleteWindowById(WC_SELECT_STATION, 0);
}
virtual void OnPaint()
{
bool newstations = _railstation.newstations;
DrawPixelInfo tmp_dpi, *old_dpi;
const StationSpec *statspec = newstations ? GetCustomStationSpec(_railstation.station_class, _railstation.station_type) : NULL;
if (_settings_client.gui.station_dragdrop) {
SetTileSelectSize(1, 1);
} else {
int x = _settings_client.gui.station_numtracks;
int y = _settings_client.gui.station_platlength;
if (_railstation.orientation == AXIS_X) Swap(x, y);
if (!_remove_button_clicked)
SetTileSelectSize(x, y);
}
int rad = (_settings_game.station.modified_catchment) ? CA_TRAIN : CA_UNMODIFIED;
if (_settings_client.gui.station_show_coverage)
SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
for (uint bits = 0; bits < 7; bits++) {
bool disable = bits >= _settings_game.station.station_spread;
if (statspec == NULL) {
this->SetWidgetDisabledState(bits + BRSW_PLATFORM_NUM_1, disable);
this->SetWidgetDisabledState(bits + BRSW_PLATFORM_LEN_1, disable);
} else {
this->SetWidgetDisabledState(bits + BRSW_PLATFORM_NUM_1, HasBit(statspec->disallowed_platforms, bits) || disable);
this->SetWidgetDisabledState(bits + BRSW_PLATFORM_LEN_1, HasBit(statspec->disallowed_lengths, bits) || disable);
}
}
SetDParam(0, GetStationClassName(_railstation.station_class));
this->DrawWidgets();
int y_offset = newstations ? 90 : 0;
/* Set up a clipping area for the '/' station preview */
if (FillDrawPixelInfo(&tmp_dpi, 7, 26 + y_offset, 66, 48)) {
old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
if (!DrawStationTile(32, 16, _cur_railtype, AXIS_X, _railstation.station_class, _railstation.station_type)) {
StationPickerDrawSprite(32, 16, STATION_RAIL, _cur_railtype, INVALID_ROADTYPE, 2);
}
_cur_dpi = old_dpi;
}
/* Set up a clipping area for the '\' station preview */
if (FillDrawPixelInfo(&tmp_dpi, 75, 26 + y_offset, 66, 48)) {
old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
if (!DrawStationTile(32, 16, _cur_railtype, AXIS_Y, _railstation.station_class, _railstation.station_type)) {
StationPickerDrawSprite(32, 16, STATION_RAIL, _cur_railtype, INVALID_ROADTYPE, 3);
}
_cur_dpi = old_dpi;
}
DrawStringCentered(74, 15 + y_offset, STR_3002_ORIENTATION, TC_FROMSTRING);
DrawStringCentered(74, 76 + y_offset, STR_3003_NUMBER_OF_TRACKS, TC_FROMSTRING);
DrawStringCentered(74, 101 + y_offset, STR_3004_PLATFORM_LENGTH, TC_FROMSTRING);
DrawStringCentered(74, 141 + y_offset, STR_3066_COVERAGE_AREA_HIGHLIGHT, TC_FROMSTRING);
int text_end = DrawStationCoverageAreaText(2, 166 + y_offset, SCT_ALL, rad, false);
text_end = DrawStationCoverageAreaText(2, text_end + 4, SCT_ALL, rad, true) + 4;
if (text_end != this->widget[BRSW_BACKGROUND].bottom) {
this->SetDirty();
ResizeWindowForWidget(this, BRSW_BACKGROUND, 0, text_end - this->widget[BRSW_BACKGROUND].bottom);
this->SetDirty();
}
if (newstations) {
uint y = 35;
for (uint16 i = this->vscroll.pos; i < _railstation.station_count && i < (uint)(this->vscroll.pos + this->vscroll.cap); i++) {
const StationSpec *statspec = GetCustomStationSpec(_railstation.station_class, i);
if (statspec != NULL && statspec->name != 0) {
if (HasBit(statspec->callbackmask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
GfxFillRect(8, y - 2, 127, y + 10, 0, FILLRECT_CHECKER);
}
DrawStringTruncated(9, y, statspec->name, i == _railstation.station_type ? TC_WHITE : TC_BLACK, 118);
} else {
DrawStringTruncated(9, y, STR_STAT_CLASS_DFLT, i == _railstation.station_type ? TC_WHITE : TC_BLACK, 118);
}
y += 14;
}
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BRSW_PLATFORM_DIR_X:
case BRSW_PLATFORM_DIR_Y:
this->RaiseWidget(_railstation.orientation + BRSW_PLATFORM_DIR_X);
_railstation.orientation = (Axis)(widget - BRSW_PLATFORM_DIR_X);
this->LowerWidget(_railstation.orientation + BRSW_PLATFORM_DIR_X);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
case BRSW_PLATFORM_NUM_1:
case BRSW_PLATFORM_NUM_2:
case BRSW_PLATFORM_NUM_3:
case BRSW_PLATFORM_NUM_4:
case BRSW_PLATFORM_NUM_5:
case BRSW_PLATFORM_NUM_6:
case BRSW_PLATFORM_NUM_7: {
this->RaiseWidget(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN);
this->RaiseWidget(BRSW_PLATFORM_DRAG_N_DROP);
_settings_client.gui.station_numtracks = widget - BRSW_PLATFORM_NUM_BEGIN;
_settings_client.gui.station_dragdrop = false;
_settings_client.gui.station_dragdrop = false;
const StationSpec *statspec = _railstation.newstations ? GetCustomStationSpec(_railstation.station_class, _railstation.station_type) : NULL;
if (statspec != NULL && HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
/* The previously selected number of platforms in invalid */
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_lengths, i)) {
this->RaiseWidget(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN);
_settings_client.gui.station_platlength = i + 1;
break;
}
}
}
this->LowerWidget(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN);
this->LowerWidget(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
}
case BRSW_PLATFORM_LEN_1:
case BRSW_PLATFORM_LEN_2:
case BRSW_PLATFORM_LEN_3:
case BRSW_PLATFORM_LEN_4:
case BRSW_PLATFORM_LEN_5:
case BRSW_PLATFORM_LEN_6:
case BRSW_PLATFORM_LEN_7: {
this->RaiseWidget(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN);
this->RaiseWidget(BRSW_PLATFORM_DRAG_N_DROP);
_settings_client.gui.station_platlength = widget - BRSW_PLATFORM_LEN_BEGIN;
_settings_client.gui.station_dragdrop = false;
_settings_client.gui.station_dragdrop = false;
const StationSpec *statspec = _railstation.newstations ? GetCustomStationSpec(_railstation.station_class, _railstation.station_type) : NULL;
if (statspec != NULL && HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
/* The previously selected number of tracks in invalid */
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_platforms, i)) {
this->RaiseWidget(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN);
_settings_client.gui.station_numtracks = i + 1;
break;
}
}
}
this->LowerWidget(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN);
this->LowerWidget(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
}
case BRSW_PLATFORM_DRAG_N_DROP: {
_settings_client.gui.station_dragdrop ^= true;
this->ToggleWidgetLoweredState(BRSW_PLATFORM_DRAG_N_DROP);
/* get the first allowed length/number of platforms */
const StationSpec *statspec = _railstation.newstations ? GetCustomStationSpec(_railstation.station_class, _railstation.station_type) : NULL;
if (statspec != NULL && HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_lengths, i)) {
this->RaiseWidget(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN);
_settings_client.gui.station_platlength = i + 1;
break;
}
}
}
if (statspec != NULL && HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_platforms, i)) {
this->RaiseWidget(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN);
_settings_client.gui.station_numtracks = i + 1;
break;
}
}
}
this->SetWidgetLoweredState(_settings_client.gui.station_numtracks + BRSW_PLATFORM_NUM_BEGIN, !_settings_client.gui.station_dragdrop);
this->SetWidgetLoweredState(_settings_client.gui.station_platlength + BRSW_PLATFORM_LEN_BEGIN, !_settings_client.gui.station_dragdrop);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
} break;
case BRSW_HIGHLIGHT_OFF:
case BRSW_HIGHLIGHT_ON:
_settings_client.gui.station_show_coverage = (widget != BRSW_HIGHLIGHT_OFF);
this->SetWidgetLoweredState(BRSW_HIGHLIGHT_OFF, !_settings_client.gui.station_show_coverage);
this->SetWidgetLoweredState(BRSW_HIGHLIGHT_ON, _settings_client.gui.station_show_coverage);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
case BRSW_NEWST_DROPDOWN:
ShowDropDownList(this, BuildStationClassDropDown(), _railstation.station_class, BRSW_NEWST_DROPDOWN);
break;
case BRSW_NEWST_LIST: {
const StationSpec *statspec;
int y = (pt.y - 32) / 14;
if (y >= this->vscroll.cap) return;
y += this->vscroll.pos;
if (y >= _railstation.station_count) return;
/* Check station availability callback */
statspec = GetCustomStationSpec(_railstation.station_class, y);
if (statspec != NULL &&
HasBit(statspec->callbackmask, CBM_STATION_AVAIL) &&
GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) return;
_railstation.station_type = y;
this->CheckSelectedSize(statspec);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
}
}
}
virtual void OnDropdownSelect(int widget, int index)
{
if (_railstation.station_class != index) {
_railstation.station_class = (StationClassID)index;
_railstation.station_type = 0;
_railstation.station_count = GetNumCustomStations(_railstation.station_class);
this->CheckSelectedSize(GetCustomStationSpec(_railstation.station_class, _railstation.station_type));
this->vscroll.count = _railstation.station_count;
this->vscroll.pos = _railstation.station_type;
}
SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
}
virtual void OnTick()
{
CheckRedrawStationCoverage(this);
}
};
/** Widget definition of the standard build rail station window */
static const Widget _station_builder_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BRSW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 147, 0, 13, STR_3000_RAIL_STATION_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BRSW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 14, 199, 0x0, STR_NULL}, // BRSW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 7, 72, 26, 73, 0x0, STR_304E_SELECT_RAILROAD_STATION}, // BRSW_PLATFORM_DIR_X
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 75, 140, 26, 73, 0x0, STR_304E_SELECT_RAILROAD_STATION}, // BRSW_PLATFORM_DIR_Y
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 22, 36, 87, 98, STR_00CB_1, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_1
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 37, 51, 87, 98, STR_00CC_2, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_2
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 52, 66, 87, 98, STR_00CD_3, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_3
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 67, 81, 87, 98, STR_00CE_4, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_4
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 82, 96, 87, 98, STR_00CF_5, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_5
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 97, 111, 87, 98, STR_6, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_6
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 112, 126, 87, 98, STR_7, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_7
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 22, 36, 112, 123, STR_00CB_1, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_1
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 37, 51, 112, 123, STR_00CC_2, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_2
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 52, 66, 112, 123, STR_00CD_3, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_3
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 67, 81, 112, 123, STR_00CE_4, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_4
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 82, 96, 112, 123, STR_00CF_5, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_5
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 97, 111, 112, 123, STR_6, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_6
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 112, 126, 112, 123, STR_7, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_7
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 37, 111, 126, 137, STR_DRAG_DROP, STR_STATION_DRAG_DROP}, // BRSW_PLATFORM_DRAG_N_DROP
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 14, 73, 152, 163, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE}, // BRSW_HIGHLIGHT_OFF
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 74, 133, 152, 163, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA}, // BRSW_HIGHLIGHT_ON
{ WIDGETS_END},
};
/** Widget definition of the build NewGRF rail station window */
static const Widget _newstation_builder_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BRSW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 147, 0, 13, STR_3000_RAIL_STATION_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BRSW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 14, 289, 0x0, STR_NULL}, // BRSW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 7, 72, 116, 163, 0x0, STR_304E_SELECT_RAILROAD_STATION}, // BRSW_PLATFORM_DIR_X
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 75, 140, 116, 163, 0x0, STR_304E_SELECT_RAILROAD_STATION}, // BRSW_PLATFORM_DIR_Y
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 22, 36, 177, 188, STR_00CB_1, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_1
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 37, 51, 177, 188, STR_00CC_2, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_2
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 52, 66, 177, 188, STR_00CD_3, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_3
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 67, 81, 177, 188, STR_00CE_4, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_4
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 82, 96, 177, 188, STR_00CF_5, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_5
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 97, 111, 177, 188, STR_6, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_6
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 112, 126, 177, 188, STR_7, STR_304F_SELECT_NUMBER_OF_PLATFORMS}, // BRSW_PLATFORM_NUM_7
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 22, 36, 202, 213, STR_00CB_1, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_1
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 37, 51, 202, 213, STR_00CC_2, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_2
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 52, 66, 202, 213, STR_00CD_3, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_3
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 67, 81, 202, 213, STR_00CE_4, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_4
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 82, 96, 202, 213, STR_00CF_5, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_5
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 97, 111, 202, 213, STR_6, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_6
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 112, 126, 202, 213, STR_7, STR_3050_SELECT_LENGTH_OF_RAILROAD}, // BRSW_PLATFORM_LEN_7
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 37, 111, 216, 227, STR_DRAG_DROP, STR_STATION_DRAG_DROP}, // BRSW_PLATFORM_DRAG_N_DROP
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 14, 73, 242, 253, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE}, // BRSW_HIGHLIGHT_OFF
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 74, 133, 242, 253, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA}, // BRSW_HIGHLIGHT_ON
/* newstations gui additions */
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 7, 140, 17, 28, STR_02BD, STR_SELECT_STATION_CLASS_TIP}, // BRSW_NEWST_DROPDOWN
{ WWT_MATRIX, RESIZE_NONE, COLOUR_GREY, 7, 128, 32, 102, 0x501, STR_SELECT_STATION_TYPE_TIP}, // BRSW_NEWST_LIST
{ WWT_SCROLLBAR, RESIZE_NONE, COLOUR_GREY, 129, 140, 32, 102, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // BRSW_NEWST_SCROLL
{ WIDGETS_END},
};
/** High level window description of the default station-build window */
static const WindowDesc _station_builder_desc(
WDP_AUTO, WDP_AUTO, 148, 200, 148, 200,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_station_builder_widgets
);
/** High level window description of the newGRF station-build window */
static const WindowDesc _newstation_builder_desc(
WDP_AUTO, WDP_AUTO, 148, 290, 148, 290,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_newstation_builder_widgets
);
/** Open station build window */
static void ShowStationBuilder(Window *parent)
{
if (GetNumStationClasses() <= 2 && GetNumCustomStations(STAT_CLASS_DFLT) == 1) {
new BuildRailStationWindow(&_station_builder_desc, parent, false);
} else {
new BuildRailStationWindow(&_newstation_builder_desc, parent, true);
}
}
/** Enum referring to the widgets of the signal window */
enum BuildSignalWidgets {
BSW_CLOSEBOX = 0,
BSW_CAPTION,
BSW_SEMAPHORE_NORM,
BSW_SEMAPHORE_ENTRY,
BSW_SEMAPHORE_EXIT,
BSW_SEMAPHORE_COMBO,
BSW_SEMAPHORE_PBS,
BSW_SEMAPHORE_PBS_OWAY,
BSW_ELECTRIC_NORM,
BSW_ELECTRIC_ENTRY,
BSW_ELECTRIC_EXIT,
BSW_ELECTRIC_COMBO,
BSW_ELECTRIC_PBS,
BSW_ELECTRIC_PBS_OWAY,
BSW_CONVERT,
BSW_DRAG_SIGNALS_DENSITY,
BSW_DRAG_SIGNALS_DENSITY_DECREASE,
BSW_DRAG_SIGNALS_DENSITY_INCREASE,
};
struct BuildSignalWindow : public PickerWindowBase {
private:
/**
* Draw dynamic a signal-sprite in a button in the signal GUI
* Draw the sprite +1px to the right and down if the button is lowered and change the sprite to sprite + 1 (red to green light)
*
* @param widget_index index of this widget in the window
* @param image the sprite to draw
* @param xrel the relativ x value of the sprite in the grf
* @param xsize the width of the sprite
*/
void DrawSignalSprite(byte widget_index, SpriteID image, int8 xrel, uint8 xsize)
{
DrawSprite(image + this->IsWidgetLowered(widget_index), PAL_NONE,
this->widget[widget_index].left + (this->widget[widget_index].right - this->widget[widget_index].left) / 2 - xrel - xsize / 2 +
this->IsWidgetLowered(widget_index), this->widget[widget_index].bottom - 3 + this->IsWidgetLowered(widget_index));
}
public:
BuildSignalWindow(const WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->FindWindowPlacementAndResize(desc);
};
virtual void OnPaint()
{
this->LowerWidget((_cur_signal_variant == SIG_ELECTRIC ? BSW_ELECTRIC_NORM : BSW_SEMAPHORE_NORM) + _cur_signal_type);
this->SetWidgetLoweredState(BSW_CONVERT, _convert_signal_button);
this->SetWidgetDisabledState(BSW_DRAG_SIGNALS_DENSITY_DECREASE, _settings_client.gui.drag_signals_density == 1);
this->SetWidgetDisabledState(BSW_DRAG_SIGNALS_DENSITY_INCREASE, _settings_client.gui.drag_signals_density == 20);
this->DrawWidgets();
/* The 'hardcoded' off sets are needed because they are reused sprites. */
this->DrawSignalSprite(BSW_SEMAPHORE_NORM, SPR_IMG_SIGNAL_SEMAPHORE_NORM, 0, 12); // xsize of sprite + 1 == 9
this->DrawSignalSprite(BSW_SEMAPHORE_ENTRY, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY, -1, 13); // xsize of sprite + 1 == 10
this->DrawSignalSprite(BSW_SEMAPHORE_EXIT, SPR_IMG_SIGNAL_SEMAPHORE_EXIT, 0, 12); // xsize of sprite + 1 == 9
this->DrawSignalSprite(BSW_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_COMBO, 0, 12); // xsize of sprite + 1 == 9
this->DrawSignalSprite(BSW_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS, 0, 12); // xsize of sprite + 1 == 9
this->DrawSignalSprite(BSW_SEMAPHORE_PBS_OWAY, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY, -1, 13); // xsize of sprite + 1 == 10
this->DrawSignalSprite(BSW_ELECTRIC_NORM, SPR_IMG_SIGNAL_ELECTRIC_NORM, -1, 4);
this->DrawSignalSprite(BSW_ELECTRIC_ENTRY, SPR_IMG_SIGNAL_ELECTRIC_ENTRY, -2, 6);
this->DrawSignalSprite(BSW_ELECTRIC_EXIT, SPR_IMG_SIGNAL_ELECTRIC_EXIT, -2, 6);
this->DrawSignalSprite(BSW_ELECTRIC_COMBO, SPR_IMG_SIGNAL_ELECTRIC_COMBO, -2, 6);
this->DrawSignalSprite(BSW_ELECTRIC_PBS, SPR_IMG_SIGNAL_ELECTRIC_PBS, -1, 4);
this->DrawSignalSprite(BSW_ELECTRIC_PBS_OWAY,SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY,-2, 6);
/* Draw dragging signal density value in the BSW_DRAG_SIGNALS_DENSITY widget */
SetDParam(0, _settings_client.gui.drag_signals_density);
DrawStringCentered(this->widget[BSW_DRAG_SIGNALS_DENSITY].left + (this->widget[BSW_DRAG_SIGNALS_DENSITY].right -
this->widget[BSW_DRAG_SIGNALS_DENSITY].left) / 2 + 1,
this->widget[BSW_DRAG_SIGNALS_DENSITY].top + 2, STR_JUST_INT, TC_ORANGE);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BSW_SEMAPHORE_NORM:
case BSW_SEMAPHORE_ENTRY:
case BSW_SEMAPHORE_EXIT:
case BSW_SEMAPHORE_COMBO:
case BSW_SEMAPHORE_PBS:
case BSW_SEMAPHORE_PBS_OWAY:
case BSW_ELECTRIC_NORM:
case BSW_ELECTRIC_ENTRY:
case BSW_ELECTRIC_EXIT:
case BSW_ELECTRIC_COMBO:
case BSW_ELECTRIC_PBS:
case BSW_ELECTRIC_PBS_OWAY:
this->RaiseWidget((_cur_signal_variant == SIG_ELECTRIC ? BSW_ELECTRIC_NORM : BSW_SEMAPHORE_NORM) + _cur_signal_type);
_cur_signal_type = (SignalType)((uint)((widget - BSW_SEMAPHORE_NORM) % (SIGTYPE_LAST + 1)));
_cur_signal_variant = widget >= BSW_ELECTRIC_NORM ? SIG_ELECTRIC : SIG_SEMAPHORE;
break;
case BSW_CONVERT:
_convert_signal_button = !_convert_signal_button;
break;
case BSW_DRAG_SIGNALS_DENSITY_DECREASE:
if (_settings_client.gui.drag_signals_density > 1) {
_settings_client.gui.drag_signals_density--;
SetWindowDirty(FindWindowById(WC_GAME_OPTIONS, 0));
}
break;
case BSW_DRAG_SIGNALS_DENSITY_INCREASE:
if (_settings_client.gui.drag_signals_density < 20) {
_settings_client.gui.drag_signals_density++;
SetWindowDirty(FindWindowById(WC_GAME_OPTIONS, 0));
}
break;
default: break;
}
this->SetDirty();
}
};
/** Widget definition of the build signal window */
static const Widget _signal_builder_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BSW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 153, 0, 13, STR_SIGNAL_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BSW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 40, STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_NORM_TIP}, // BSW_SEMAPHORE_NORM
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 40, STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_ENTRY_TIP}, // BSW_SEMAPHORE_ENTRY
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 65, 14, 40, STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_EXIT_TIP}, // BSW_SEMAPHORE_EXIT
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 66, 87, 14, 40, STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_COMBO_TIP}, // BSW_SEMAPHORE_COMBO
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 88, 109, 14, 40, STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_PBS_TIP}, // BSW_SEMAPHORE_PBS
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 110, 131, 14, 40, STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_PBS_OWAY_TIP},// BSW_SEMAPHORE_PBS_OWAY
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 41, 67, STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_NORM_TIP}, // BSW_ELECTRIC_NORM
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 41, 67, STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_ENTRY_TIP}, // BSW_ELECTRIC_ENTRY
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 65, 41, 67, STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_EXIT_TIP}, // BSW_ELECTRIC_EXIT
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 66, 87, 41, 67, STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_COMBO_TIP}, // BSW_ELECTRIC_COMBO
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 88, 109, 41, 67, STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_PBS_TIP}, // BSW_ELECTRIC_PBS
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 110, 131, 41, 67, STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_PBS_OWAY_TIP},// BSW_ELECTRIC_PBS_OWAY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 132, 153, 14, 40, SPR_IMG_SIGNAL_CONVERT, STR_SIGNAL_CONVERT_TIP}, // BSW_CONVERT
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 132, 153, 41, 67, STR_NULL, STR_DRAG_SIGNALS_DENSITY_TIP}, // BSW_DRAG_SIGNALS_DENSITY
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 134, 142, 54, 65, SPR_ARROW_LEFT, STR_DRAG_SIGNALS_DENSITY_DECREASE_TIP}, // BSW_DRAG_SIGNALS_DENSITY_DECREASE
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 143, 151, 54, 65, SPR_ARROW_RIGHT, STR_DRAG_SIGNALS_DENSITY_INCREASE_TIP}, // BSW_DRAG_SIGNALS_DENSITY_INCREASE
{ WIDGETS_END},
};
/** Signal selection window description */
static const WindowDesc _signal_builder_desc(
WDP_AUTO, WDP_AUTO, 154, 68, 154, 68,
WC_BUILD_SIGNAL, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION,
_signal_builder_widgets
);
/**
* Open the signal selection window
*/
static void ShowSignalBuilder(Window *parent)
{
new BuildSignalWindow(&_signal_builder_desc, parent);
}
struct BuildRailDepotWindow : public PickerWindowBase {
private:
/** Enum referring to the widgets of the build rail depot window */
enum BuildRailDepotWidgets {
BRDW_CLOSEBOX = 0,
BRDW_CAPTION,
BRDW_BACKGROUND,
BRDW_DEPOT_NE,
BRDW_DEPOT_SE,
BRDW_DEPOT_SW,
BRDW_DEPOT_NW,
};
public:
BuildRailDepotWindow(const WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->LowerWidget(_build_depot_direction + BRDW_DEPOT_NE);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
DrawTrainDepotSprite(70, 17, DIAGDIR_NE, _cur_railtype);
DrawTrainDepotSprite(70, 69, DIAGDIR_SE, _cur_railtype);
DrawTrainDepotSprite( 2, 69, DIAGDIR_SW, _cur_railtype);
DrawTrainDepotSprite( 2, 17, DIAGDIR_NW, _cur_railtype);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BRDW_DEPOT_NE:
case BRDW_DEPOT_SE:
case BRDW_DEPOT_SW:
case BRDW_DEPOT_NW:
this->RaiseWidget(_build_depot_direction + BRDW_DEPOT_NE);
_build_depot_direction = (DiagDirection)(widget - BRDW_DEPOT_NE);
this->LowerWidget(_build_depot_direction + BRDW_DEPOT_NE);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
}
}
};
/** Widget definition of the build rail depot window */
static const Widget _build_depot_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BRDW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 139, 0, 13, STR_1014_TRAIN_DEPOT_ORIENTATION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BRDW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 139, 14, 121, 0x0, STR_NULL}, // BRDW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 71, 136, 17, 66, 0x0, STR_1020_SELECT_RAILROAD_DEPOT_ORIENTATIO}, // BRDW_DEPOT_NE
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 71, 136, 69, 118, 0x0, STR_1020_SELECT_RAILROAD_DEPOT_ORIENTATIO}, // BRDW_DEPOT_SE
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 3, 68, 69, 118, 0x0, STR_1020_SELECT_RAILROAD_DEPOT_ORIENTATIO}, // BRDW_DEPOT_SW
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 3, 68, 17, 66, 0x0, STR_1020_SELECT_RAILROAD_DEPOT_ORIENTATIO}, // BRDW_DEPOT_NW
{ WIDGETS_END},
};
static const WindowDesc _build_depot_desc(
WDP_AUTO, WDP_AUTO, 140, 122, 140, 122,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_build_depot_widgets
);
static void ShowBuildTrainDepotPicker(Window *parent)
{
new BuildRailDepotWindow(&_build_depot_desc, parent);
}
struct BuildRailWaypointWindow : PickerWindowBase {
private:
/** Enum referring to the widgets of the build NewGRF rail waypoint window */
enum BuildRailWaypointWidgets {
BRWW_CLOSEBOX = 0,
BRWW_CAPTION,
BRWW_BACKGROUND,
BRWW_WAYPOINT_1,
BRWW_WAYPOINT_2,
BRWW_WAYPOINT_3,
BRWW_WAYPOINT_4,
BRWW_WAYPOINT_5,
BRWW_SCROLL,
};
public:
BuildRailWaypointWindow(const WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->hscroll.cap = 5;
this->hscroll.count = _waypoint_count;
this->FindWindowPlacementAndResize(desc);
};
virtual void OnPaint()
{
uint i;
for (i = 0; i < this->hscroll.cap; i++) {
this->SetWidgetLoweredState(i + BRWW_WAYPOINT_1, (this->hscroll.pos + i) == _cur_waypoint_type);
}
this->DrawWidgets();
for (i = 0; i < this->hscroll.cap; i++) {
if (this->hscroll.pos + i < this->hscroll.count) {
const StationSpec *statspec = GetCustomStationSpec(STAT_CLASS_WAYP, this->hscroll.pos + i);
DrawWaypointSprite(2 + i * 68, 25, this->hscroll.pos + i, _cur_railtype);
if (statspec != NULL &&
HasBit(statspec->callbackmask, CBM_STATION_AVAIL) &&
GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
GfxFillRect(4 + i * 68, 18, 67 + i * 68, 75, 0, FILLRECT_CHECKER);
}
}
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BRWW_WAYPOINT_1:
case BRWW_WAYPOINT_2:
case BRWW_WAYPOINT_3:
case BRWW_WAYPOINT_4:
case BRWW_WAYPOINT_5: {
byte type = widget - BRWW_WAYPOINT_1 + this->hscroll.pos;
/* Check station availability callback */
const StationSpec *statspec = GetCustomStationSpec(STAT_CLASS_WAYP, type);
if (statspec != NULL &&
HasBit(statspec->callbackmask, CBM_STATION_AVAIL) &&
GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) return;
_cur_waypoint_type = type;
SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
}
}
}
};
/** Widget definition for the build NewGRF rail waypoint window */
static const Widget _build_waypoint_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BRWW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 343, 0, 13, STR_WAYPOINT, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BRWW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 343, 14, 91, 0x0, STR_NULL}, // BRWW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 3, 68, 17, 76, 0x0, STR_WAYPOINT_GRAPHICS_TIP}, // BRWW_WAYPOINT_1
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 71, 136, 17, 76, 0x0, STR_WAYPOINT_GRAPHICS_TIP}, // BRWW_WAYPOINT_2
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 139, 204, 17, 76, 0x0, STR_WAYPOINT_GRAPHICS_TIP}, // BRWW_WAYPOINT_3
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 207, 272, 17, 76, 0x0, STR_WAYPOINT_GRAPHICS_TIP}, // BRWW_WAYPOINT_4
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 275, 340, 17, 76, 0x0, STR_WAYPOINT_GRAPHICS_TIP}, // BRWW_WAYPOINT_5
{ WWT_HSCROLLBAR, RESIZE_NONE, COLOUR_DARK_GREEN, 1, 343, 80, 91, 0x0, STR_HSCROLL_BAR_SCROLLS_LIST}, // BRWW_SCROLL
{ WIDGETS_END},
};
static const WindowDesc _build_waypoint_desc(
WDP_AUTO, WDP_AUTO, 344, 92, 344, 92,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_build_waypoint_widgets
);
static void ShowBuildWaypointPicker(Window *parent)
{
new BuildRailWaypointWindow(&_build_waypoint_desc, parent);
}
/**
* Initialize rail building GUI settings
*/
void InitializeRailGui()
{
_build_depot_direction = DIAGDIR_NW;
}
/**
* Re-initialize rail-build toolbar after toggling support for electric trains
* @param disable Boolean whether electric trains are disabled (removed from the game)
*/
void ReinitGuiAfterToggleElrail(bool disable)
{
extern RailType _last_built_railtype;
if (disable && _last_built_railtype == RAILTYPE_ELECTRIC) {
Window *w;
_last_built_railtype = _cur_railtype = RAILTYPE_RAIL;
w = FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL);
if (w != NULL) {
SetupRailToolbar(_cur_railtype, w);
w->SetDirty();
}
}
MarkWholeScreenDirty();
}
/** Set the initial (default) railtype to use */
static void SetDefaultRailGui()
{
if (_local_company == COMPANY_SPECTATOR || !IsValidCompanyID(_local_company)) return;
extern RailType _last_built_railtype;
RailType rt = (RailType)_settings_client.gui.default_rail_type;
if (rt >= RAILTYPE_END) {
if (rt == RAILTYPE_END + 2) {
/* Find the most used rail type */
RailType count[RAILTYPE_END];
memset(count, 0, sizeof(count));
for (TileIndex t = 0; t < MapSize(); t++) {
if (IsTileType(t, MP_RAILWAY) || IsLevelCrossingTile(t) || IsRailwayStationTile(t) ||
(IsTileType(t, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL)) {
count[GetRailType(t)]++;
}
}
rt = RAILTYPE_RAIL;
for (RailType r = RAILTYPE_ELECTRIC; r < RAILTYPE_END; r++) {
if (count[r] >= count[rt]) rt = r;
}
/* No rail, just get the first available one */
if (count[rt] == 0) rt = RAILTYPE_END;
}
switch (rt) {
case RAILTYPE_END + 0:
rt = RAILTYPE_RAIL;
while (rt < RAILTYPE_END && !HasRailtypeAvail(_local_company, rt)) rt++;
break;
case RAILTYPE_END + 1:
rt = GetBestRailtype(_local_company);
break;
default:
break;
}
}
_last_built_railtype = _cur_railtype = rt;
Window *w = FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL);
if (w != NULL) {
SetupRailToolbar(_cur_railtype, w);
w->SetDirty();
}
}
/**
* Updates the current signal variant used in the signal GUI
* to the one adequate to current year.
* @param 0 needed to be called when a setting changes
* @return success, needed for settings
*/
bool ResetSignalVariant(int32 = 0)
{
SignalVariant new_variant = (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC);
if (new_variant != _cur_signal_variant) {
Window *w = FindWindowById(WC_BUILD_SIGNAL, 0);
if (w != NULL) {
w->SetDirty();
w->RaiseWidget((_cur_signal_variant == SIG_ELECTRIC ? BSW_ELECTRIC_NORM : BSW_SEMAPHORE_NORM) + _cur_signal_type);
}
_cur_signal_variant = new_variant;
}
return true;
}
/** Resets the rail GUI - sets default railtype to build
* and resets the signal GUI
*/
void InitializeRailGUI()
{
SetDefaultRailGui();
_convert_signal_button = false;
_cur_signal_type = _default_signal_type[_settings_client.gui.default_signal_type];
ResetSignalVariant();
}
| 72,910
|
C++
|
.cpp
| 1,549
| 44.237573
| 183
| 0.6827
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,017
|
main_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/main_gui.cpp
|
/* $Id$ */
/** @file main_gui.cpp Handling of the main viewport. */
#include "stdafx.h"
#include "openttd.h"
#include "currency.h"
#include "spritecache.h"
#include "window_gui.h"
#include "window_func.h"
#include "textbuf_gui.h"
#include "viewport_func.h"
#include "command_func.h"
#include "console_gui.h"
#include "map_func.h"
#include "genworld.h"
#include "transparency_gui.h"
#include "functions.h"
#include "sound_func.h"
#include "transparency.h"
#include "strings_func.h"
#include "zoom_func.h"
#include "company_base.h"
#include "company_func.h"
#include "settings_type.h"
#include "toolbar_gui.h"
#include "statusbar_gui.h"
#include "tilehighlight_func.h"
#include "network/network.h"
#include "network/network_func.h"
#include "network/network_gui.h"
#include "network/network_base.h"
#include "table/sprites.h"
#include "table/strings.h"
static int _rename_id = 1;
static int _rename_what = -1;
void CcGiveMoney(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
#ifdef ENABLE_NETWORK
if (!success || !_settings_game.economy.give_money) return;
/* Inform the company of the action of one of it's clients (controllers). */
char msg[64];
SetDParam(0, p2);
GetString(msg, STR_COMPANY_NAME, lastof(msg));
if (!_network_server) {
NetworkClientSendChat(NETWORK_ACTION_GIVE_MONEY, DESTTYPE_TEAM, p2, msg, p1);
} else {
NetworkServerSendChat(NETWORK_ACTION_GIVE_MONEY, DESTTYPE_TEAM, p2, msg, CLIENT_ID_SERVER, p1);
}
#endif /* ENABLE_NETWORK */
}
void HandleOnEditText(const char *str)
{
switch (_rename_what) {
#ifdef ENABLE_NETWORK
case 3: { // Give money, you can only give money in excess of loan
const Company *c = GetCompany(_local_company);
Money money = min(c->money - c->current_loan, (Money)(atoi(str) / _currency->rate));
uint32 money_c = Clamp(ClampToI32(money), 0, 20000000); // Clamp between 20 million and 0
/* Give 'id' the money, and substract it from ourself */
DoCommandP(0, money_c, _rename_id, CMD_GIVE_MONEY | CMD_MSG(STR_INSUFFICIENT_FUNDS), CcGiveMoney, str);
} break;
#endif /* ENABLE_NETWORK */
default: NOT_REACHED();
}
_rename_id = _rename_what = -1;
}
/**
* This code is shared for the majority of the pushbuttons.
* Handles e.g. the pressing of a button (to build things), playing of click sound and sets certain parameters
*
* @param w Window which called the function
* @param widget ID of the widget (=button) that called this function
* @param cursor How should the cursor image change? E.g. cursor with depot image in it
* @param mode Tile highlighting mode, e.g. drawing a rectangle or a dot on the ground
* @param placeproc Procedure which will be called when someone clicks on the map
* @return true if the button is clicked, false if it's unclicked
*/
bool HandlePlacePushButton(Window *w, int widget, CursorID cursor, ViewportHighlightMode mode, PlaceProc *placeproc)
{
if (w->IsWidgetDisabled(widget)) return false;
SndPlayFx(SND_15_BEEP);
w->SetDirty();
if (w->IsWidgetLowered(widget)) {
ResetObjectToPlace();
return false;
}
SetObjectToPlace(cursor, PAL_NONE, mode, w->window_class, w->window_number);
w->LowerWidget(widget);
_place_proc = placeproc;
return true;
}
void CcPlaySound10(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) SndPlayTileFx(SND_12_EXPLOSION, tile);
}
#ifdef ENABLE_NETWORK
void ShowNetworkGiveMoneyWindow(CompanyID company)
{
_rename_id = company;
_rename_what = 3;
ShowQueryString(STR_EMPTY, STR_NETWORK_GIVE_MONEY_CAPTION, 30, 180, NULL, CS_NUMERAL, QSF_NONE);
}
#endif /* ENABLE_NETWORK */
/* Zooms a viewport in a window in or out
* No button handling or what so ever */
bool DoZoomInOutWindow(int how, Window *w)
{
ViewPort *vp;
assert(w != NULL);
vp = w->viewport;
switch (how) {
case ZOOM_IN:
if (vp->zoom == ZOOM_LVL_MIN) return false;
vp->zoom = (ZoomLevel)((int)vp->zoom - 1);
vp->virtual_width >>= 1;
vp->virtual_height >>= 1;
w->viewport->scrollpos_x += vp->virtual_width >> 1;
w->viewport->scrollpos_y += vp->virtual_height >> 1;
w->viewport->dest_scrollpos_x = w->viewport->scrollpos_x;
w->viewport->dest_scrollpos_y = w->viewport->scrollpos_y;
break;
case ZOOM_OUT:
if (vp->zoom == ZOOM_LVL_MAX) return false;
vp->zoom = (ZoomLevel)((int)vp->zoom + 1);
w->viewport->scrollpos_x -= vp->virtual_width >> 1;
w->viewport->scrollpos_y -= vp->virtual_height >> 1;
w->viewport->dest_scrollpos_x = w->viewport->scrollpos_x;
w->viewport->dest_scrollpos_y = w->viewport->scrollpos_y;
vp->virtual_width <<= 1;
vp->virtual_height <<= 1;
break;
}
if (vp != NULL) { // the vp can be null when how == ZOOM_NONE
vp->virtual_left = w->viewport->scrollpos_x;
vp->virtual_top = w->viewport->scrollpos_y;
}
w->SetDirty();
/* Update the windows that have zoom-buttons to perhaps disable their buttons */
InvalidateThisWindowData(w);
return true;
}
void ZoomInOrOutToCursorWindow(bool in, Window *w)
{
assert(w != NULL);
if (_game_mode != GM_MENU) {
ViewPort *vp = w->viewport;
if ((in && vp->zoom == ZOOM_LVL_MIN) || (!in && vp->zoom == ZOOM_LVL_MAX))
return;
Point pt = GetTileZoomCenterWindow(in, w);
if (pt.x != -1) {
ScrollWindowTo(pt.x, pt.y, -1, w, true);
DoZoomInOutWindow(in ? ZOOM_IN : ZOOM_OUT, w);
}
}
}
extern void UpdateAllStationVirtCoord();
struct MainWindow : Window
{
MainWindow(int width, int height) : Window(0, 0, width, height, WC_MAIN_WINDOW, NULL)
{
InitializeWindowViewport(this, 0, 0, width, height, TileXY(32, 32), ZOOM_LVL_VIEWPORT);
}
virtual void OnPaint()
{
this->DrawViewport();
if (_game_mode == GM_MENU) {
int off_x = _screen.width / 2;
DrawSprite(SPR_OTTD_O, PAL_NONE, off_x - 120, 50);
DrawSprite(SPR_OTTD_P, PAL_NONE, off_x - 86, 50);
DrawSprite(SPR_OTTD_E, PAL_NONE, off_x - 53, 50);
DrawSprite(SPR_OTTD_N, PAL_NONE, off_x - 22, 50);
DrawSprite(SPR_OTTD_T, PAL_NONE, off_x + 34, 50);
DrawSprite(SPR_OTTD_T, PAL_NONE, off_x + 65, 50);
DrawSprite(SPR_OTTD_D, PAL_NONE, off_x + 96, 50);
}
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
switch (keycode) {
case 'Q' | WKC_CTRL:
case 'Q' | WKC_META:
HandleExitGameRequest();
return ES_HANDLED;
}
/* Disable all key shortcuts, except quit shortcuts when
* generating the world, otherwise they create threading
* problem during the generating, resulting in random
* assertions that are hard to trigger and debug */
if (IsGeneratingWorld()) return ES_NOT_HANDLED;
if (keycode == WKC_BACKQUOTE) {
IConsoleSwitch();
return ES_HANDLED;
}
if (keycode == ('B' | WKC_CTRL)) {
extern bool _draw_bounding_boxes;
_draw_bounding_boxes = !_draw_bounding_boxes;
MarkWholeScreenDirty();
return ES_HANDLED;
}
if (_game_mode == GM_MENU) return ES_NOT_HANDLED;
switch (keycode) {
case 'C':
case 'Z': {
Point pt = GetTileBelowCursor();
if (pt.x != -1) {
if (keycode == 'Z') MaxZoomInOut(ZOOM_IN, this);
ScrollMainWindowTo(pt.x, pt.y);
}
break;
}
case WKC_ESC: ResetObjectToPlace(); break;
case WKC_DELETE: DeleteNonVitalWindows(); break;
case WKC_DELETE | WKC_SHIFT: DeleteAllNonVitalWindows(); break;
case 'R' | WKC_CTRL: MarkWholeScreenDirty(); break;
#if defined(_DEBUG)
case '0' | WKC_ALT: // Crash the game
*(byte*)0 = 0;
break;
case '1' | WKC_ALT: // Gimme money
/* Server can not cheat in advertise mode either! */
#ifdef ENABLE_NETWORK
if (!_networking || !_network_server || !_settings_client.network.server_advertise)
#endif /* ENABLE_NETWORK */
DoCommandP(0, 10000000, 0, CMD_MONEY_CHEAT);
break;
case '2' | WKC_ALT: // Update the coordinates of all station signs
UpdateAllStationVirtCoord();
break;
#endif
case '1' | WKC_CTRL:
case '2' | WKC_CTRL:
case '3' | WKC_CTRL:
case '4' | WKC_CTRL:
case '5' | WKC_CTRL:
case '6' | WKC_CTRL:
case '7' | WKC_CTRL:
case '8' | WKC_CTRL:
case '9' | WKC_CTRL:
/* Transparency toggle hot keys */
ToggleTransparency((TransparencyOption)(keycode - ('1' | WKC_CTRL)));
MarkWholeScreenDirty();
break;
case '1' | WKC_CTRL | WKC_SHIFT:
case '2' | WKC_CTRL | WKC_SHIFT:
case '3' | WKC_CTRL | WKC_SHIFT:
case '4' | WKC_CTRL | WKC_SHIFT:
case '5' | WKC_CTRL | WKC_SHIFT:
case '6' | WKC_CTRL | WKC_SHIFT:
case '7' | WKC_CTRL | WKC_SHIFT:
case '8' | WKC_CTRL | WKC_SHIFT:
/* Invisibility toggle hot keys */
ToggleInvisibilityWithTransparency((TransparencyOption)(keycode - ('1' | WKC_CTRL | WKC_SHIFT)));
MarkWholeScreenDirty();
break;
case 'X' | WKC_CTRL:
ShowTransparencyToolbar();
break;
case 'X':
ResetRestoreAllTransparency();
break;
#ifdef ENABLE_NETWORK
case WKC_RETURN: case 'T': // smart chat; send to team if any, otherwise to all
if (_networking) {
const NetworkClientInfo *cio = NetworkFindClientInfoFromClientID(_network_own_client_id);
if (cio == NULL) break;
ShowNetworkChatQueryWindow(NetworkClientPreferTeamChat(cio) ? DESTTYPE_TEAM : DESTTYPE_BROADCAST, cio->client_playas);
}
break;
case WKC_SHIFT | WKC_RETURN: case WKC_SHIFT | 'T': // send text message to all clients
if (_networking) ShowNetworkChatQueryWindow(DESTTYPE_BROADCAST, 0);
break;
case WKC_CTRL | WKC_RETURN: case WKC_CTRL | 'T': // send text to all team mates
if (_networking) {
const NetworkClientInfo *cio = NetworkFindClientInfoFromClientID(_network_own_client_id);
if (cio == NULL) break;
ShowNetworkChatQueryWindow(DESTTYPE_TEAM, cio->client_playas);
}
break;
#endif
default: return ES_NOT_HANDLED;
}
return ES_HANDLED;
}
virtual void OnScroll(Point delta)
{
ViewPort *vp = IsPtInWindowViewport(this, _cursor.pos.x, _cursor.pos.y);
if (vp == NULL) {
_cursor.fix_at = false;
_scrolling_viewport = false;
}
this->viewport->scrollpos_x += ScaleByZoom(delta.x, vp->zoom);
this->viewport->scrollpos_y += ScaleByZoom(delta.y, vp->zoom);
this->viewport->dest_scrollpos_x = this->viewport->scrollpos_x;
this->viewport->dest_scrollpos_y = this->viewport->scrollpos_y;
};
virtual void OnMouseWheel(int wheel)
{
ZoomInOrOutToCursorWindow(wheel < 0, this);
}
virtual void OnInvalidateData(int data)
{
/* Forward the message to the appropiate toolbar (ingame or scenario editor) */
InvalidateWindowData(WC_MAIN_TOOLBAR, 0, data);
}
};
void ShowSelectGameWindow();
void SetupColoursAndInitialWindow()
{
for (uint i = 0; i != 16; i++) {
const byte *b = GetNonSprite(PALETTE_RECOLOUR_START + i, ST_RECOLOUR);
assert(b);
memcpy(_colour_gradient[i], b + 0xC6, sizeof(_colour_gradient[i]));
}
new MainWindow(_screen.width, _screen.height);
/* XXX: these are not done */
switch (_game_mode) {
default: NOT_REACHED();
case GM_MENU:
ShowSelectGameWindow();
break;
case GM_NORMAL:
case GM_EDITOR:
ShowVitalWindows();
break;
}
}
void ShowVitalWindows()
{
AllocateToolbar();
/* Status bad only for normal games */
if (_game_mode == GM_EDITOR) return;
ShowStatusBar();
}
/**
* Size of the application screen changed.
* Adapt the game screen-size, re-allocate the open windows, and repaint everything
*/
void GameSizeChanged()
{
_cur_resolution.width = _screen.width;
_cur_resolution.height = _screen.height;
ScreenSizeChanged();
RelocateAllWindows(_screen.width, _screen.height);
MarkWholeScreenDirty();
}
| 11,451
|
C++
|
.cpp
| 344
| 30.322674
| 123
| 0.697173
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,018
|
viewport.cpp
|
EnergeticBark_OpenTTD-3DS/src/viewport.cpp
|
/* $Id$ */
/** @file viewport.cpp Handling of all viewports.
*
* \verbatim
* The in-game coordinate system looks like this *
* *
* ^ Z *
* | *
* | *
* | *
* | *
* / \ *
* / \ *
* / \ *
* / \ *
* X < > Y *
* \endverbatim
*/
#include "stdafx.h"
#include "openttd.h"
#include "landscape.h"
#include "viewport_func.h"
#include "station_base.h"
#include "town.h"
#include "signs_base.h"
#include "signs_func.h"
#include "variables.h"
#include "vehicle_base.h"
#include "vehicle_gui.h"
#include "blitter/factory.hpp"
#include "transparency.h"
#include "strings_func.h"
#include "zoom_func.h"
#include "vehicle_func.h"
#include "company_func.h"
#include "station_func.h"
#include "window_func.h"
#include "tilehighlight_func.h"
#include "window_gui.h"
#include "table/sprites.h"
#include "table/strings.h"
PlaceProc *_place_proc;
Point _tile_fract_coords;
ZoomLevel _saved_scrollpos_zoom;
struct StringSpriteToDraw {
StringID string;
uint16 colour;
int32 x;
int32 y;
uint64 params[2];
uint16 width;
};
struct TileSpriteToDraw {
SpriteID image;
SpriteID pal;
const SubSprite *sub; ///< only draw a rectangular part of the sprite
int32 x;
int32 y;
byte z;
};
struct ChildScreenSpriteToDraw {
SpriteID image;
SpriteID pal;
const SubSprite *sub; ///< only draw a rectangular part of the sprite
int32 x;
int32 y;
int next; ///< next child to draw (-1 at the end)
};
/** Parent sprite that should be drawn */
struct ParentSpriteToDraw {
SpriteID image; ///< sprite to draw
SpriteID pal; ///< palette to use
const SubSprite *sub; ///< only draw a rectangular part of the sprite
int32 x; ///< screen X coordinate of sprite
int32 y; ///< screen Y coordinate of sprite
int32 left; ///< minimal screen X coordinate of sprite (= x + sprite->x_offs), reference point for child sprites
int32 top; ///< minimal screen Y coordinate of sprite (= y + sprite->y_offs), reference point for child sprites
int32 xmin; ///< minimal world X coordinate of bounding box
int32 xmax; ///< maximal world X coordinate of bounding box
int32 ymin; ///< minimal world Y coordinate of bounding box
int32 ymax; ///< maximal world Y coordinate of bounding box
int zmin; ///< minimal world Z coordinate of bounding box
int zmax; ///< maximal world Z coordinate of bounding box
int first_child; ///< the first child to draw.
bool comparison_done; ///< Used during sprite sorting: true if sprite has been compared with all other sprites
};
/** Enumeration of multi-part foundations */
enum FoundationPart {
FOUNDATION_PART_NONE = 0xFF, ///< Neither foundation nor groundsprite drawn yet.
FOUNDATION_PART_NORMAL = 0, ///< First part (normal foundation or no foundation)
FOUNDATION_PART_HALFTILE = 1, ///< Second part (halftile foundation)
FOUNDATION_PART_END
};
typedef SmallVector<TileSpriteToDraw, 64> TileSpriteToDrawVector;
typedef SmallVector<StringSpriteToDraw, 4> StringSpriteToDrawVector;
typedef SmallVector<ParentSpriteToDraw, 64> ParentSpriteToDrawVector;
typedef SmallVector<ParentSpriteToDraw*, 64> ParentSpriteToSortVector;
typedef SmallVector<ChildScreenSpriteToDraw, 16> ChildScreenSpriteToDrawVector;
/** Data structure storing rendering information */
struct ViewportDrawer {
DrawPixelInfo dpi;
StringSpriteToDrawVector string_sprites_to_draw;
TileSpriteToDrawVector tile_sprites_to_draw;
ParentSpriteToDrawVector parent_sprites_to_draw;
ParentSpriteToSortVector parent_sprites_to_sort; ///< Parent sprite pointer array used for sorting
ChildScreenSpriteToDrawVector child_screen_sprites_to_draw;
int *last_child;
byte combine_sprites;
int foundation[FOUNDATION_PART_END]; ///< Foundation sprites (index into parent_sprites_to_draw).
FoundationPart foundation_part; ///< Currently active foundation for ground sprite drawing.
int *last_foundation_child[FOUNDATION_PART_END]; ///< Tail of ChildSprite list of the foundations. (index into child_screen_sprites_to_draw)
Point foundation_offset[FOUNDATION_PART_END]; ///< Pixeloffset for ground sprites on the foundations.
};
static ViewportDrawer _vd;
TileHighlightData _thd;
static TileInfo *_cur_ti;
bool _draw_bounding_boxes = false;
static Point MapXYZToViewport(const ViewPort *vp, int x, int y, int z)
{
Point p = RemapCoords(x, y, z);
p.x -= vp->virtual_width / 2;
p.y -= vp->virtual_height / 2;
return p;
}
void DeleteWindowViewport(Window *w)
{
free(w->viewport);
w->viewport = NULL;
}
/**
* Initialize viewport of the window for use.
* @param w Window to use/display the viewport in
* @param x Offset of left edge of viewport with respect to left edge window \a w
* @param y Offset of top edge of viewport with respect to top edge window \a w
* @param width Width of the viewport
* @param height Height of the viewport
* @param follow_flags Flags controlling the viewport.
* - If bit 31 is set, the lower 16 bits are the vehicle that the viewport should follow.
* - If bit 31 is clear, it is a tile position.
* @param zoom Zoomlevel to display
*/
void InitializeWindowViewport(Window *w, int x, int y,
int width, int height, uint32 follow_flags, ZoomLevel zoom)
{
assert(w->viewport == NULL);
ViewportData *vp = CallocT<ViewportData>(1);
vp->left = x + w->left;
vp->top = y + w->top;
vp->width = width;
vp->height = height;
vp->zoom = zoom;
vp->virtual_width = ScaleByZoom(width, zoom);
vp->virtual_height = ScaleByZoom(height, zoom);
Point pt;
if (follow_flags & 0x80000000) {
const Vehicle *veh;
vp->follow_vehicle = (VehicleID)(follow_flags & 0xFFFF);
veh = GetVehicle(vp->follow_vehicle);
pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
} else {
uint x = TileX(follow_flags) * TILE_SIZE;
uint y = TileY(follow_flags) * TILE_SIZE;
vp->follow_vehicle = INVALID_VEHICLE;
pt = MapXYZToViewport(vp, x, y, GetSlopeZ(x, y));
}
vp->scrollpos_x = pt.x;
vp->scrollpos_y = pt.y;
vp->dest_scrollpos_x = pt.x;
vp->dest_scrollpos_y = pt.y;
w->viewport = vp;
vp->virtual_left = 0;//pt.x;
vp->virtual_top = 0;//pt.y;
}
static Point _vp_move_offs;
static void DoSetViewportPosition(const Window *w, int left, int top, int width, int height)
{
FOR_ALL_WINDOWS_FROM_BACK_FROM(w, w) {
if (left + width > w->left &&
w->left + w->width > left &&
top + height > w->top &&
w->top + w->height > top) {
if (left < w->left) {
DoSetViewportPosition(w, left, top, w->left - left, height);
DoSetViewportPosition(w, left + (w->left - left), top, width - (w->left - left), height);
return;
}
if (left + width > w->left + w->width) {
DoSetViewportPosition(w, left, top, (w->left + w->width - left), height);
DoSetViewportPosition(w, left + (w->left + w->width - left), top, width - (w->left + w->width - left) , height);
return;
}
if (top < w->top) {
DoSetViewportPosition(w, left, top, width, (w->top - top));
DoSetViewportPosition(w, left, top + (w->top - top), width, height - (w->top - top));
return;
}
if (top + height > w->top + w->height) {
DoSetViewportPosition(w, left, top, width, (w->top + w->height - top));
DoSetViewportPosition(w, left, top + (w->top + w->height - top), width , height - (w->top + w->height - top));
return;
}
return;
}
}
{
int xo = _vp_move_offs.x;
int yo = _vp_move_offs.y;
if (abs(xo) >= width || abs(yo) >= height) {
/* fully_outside */
RedrawScreenRect(left, top, left + width, top + height);
return;
}
GfxScroll(left, top, width, height, xo, yo);
if (xo > 0) {
RedrawScreenRect(left, top, xo + left, top + height);
left += xo;
width -= xo;
} else if (xo < 0) {
RedrawScreenRect(left + width + xo, top, left + width, top + height);
width += xo;
}
if (yo > 0) {
RedrawScreenRect(left, top, width + left, top + yo);
} else if (yo < 0) {
RedrawScreenRect(left, top + height + yo, width + left, top + height);
}
}
}
static void SetViewportPosition(Window *w, int x, int y)
{
ViewPort *vp = w->viewport;
int old_left = vp->virtual_left;
int old_top = vp->virtual_top;
int i;
int left, top, width, height;
vp->virtual_left = x;
vp->virtual_top = y;
/* viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
* else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
*/
old_left = UnScaleByZoomLower(old_left, vp->zoom);
old_top = UnScaleByZoomLower(old_top, vp->zoom);
x = UnScaleByZoomLower(x, vp->zoom);
y = UnScaleByZoomLower(y, vp->zoom);
old_left -= x;
old_top -= y;
if (old_top == 0 && old_left == 0) return;
_vp_move_offs.x = old_left;
_vp_move_offs.y = old_top;
left = vp->left;
top = vp->top;
width = vp->width;
height = vp->height;
if (left < 0) {
width += left;
left = 0;
}
i = left + width - _screen.width;
if (i >= 0) width -= i;
if (width > 0) {
if (top < 0) {
height += top;
top = 0;
}
i = top + height - _screen.height;
if (i >= 0) height -= i;
if (height > 0) DoSetViewportPosition(w->z_front, left, top, width, height);
}
}
/**
* Is a xy position inside the viewport of the window?
* @param w Window to examine its viewport
* @param x X coordinate of the xy position
* @param y Y coordinate of the xy position
* @return Pointer to the viewport if the xy position is in the viewport of the window,
* otherwise \c NULL is returned.
*/
ViewPort *IsPtInWindowViewport(const Window *w, int x, int y)
{
ViewPort *vp = w->viewport;
if (vp != NULL &&
IsInsideMM(x, vp->left, vp->left + vp->width) &&
IsInsideMM(y, vp->top, vp->top + vp->height))
return vp;
return NULL;
}
/**
* Translate screen coordinate in a viewport to a tile coordinate
* @param vp Viewport that contains the (\a x, \a y) screen coordinate
* @param x Screen x coordinate
* @param y Screen y coordinate
* @return Tile coordinate */
static Point TranslateXYToTileCoord(const ViewPort *vp, int x, int y)
{
Point pt;
int a, b;
uint z;
if ( (uint)(x -= vp->left) >= (uint)vp->width ||
(uint)(y -= vp->top) >= (uint)vp->height) {
Point pt = {-1, -1};
return pt;
}
x = (ScaleByZoom(x, vp->zoom) + vp->virtual_left) >> 2;
y = (ScaleByZoom(y, vp->zoom) + vp->virtual_top) >> 1;
a = y - x;
b = y + x;
/* we need to move variables in to the valid range, as the
* GetTileZoomCenterWindow() function can call here with invalid x and/or y,
* when the user tries to zoom out along the sides of the map */
a = Clamp(a, -4 * TILE_SIZE, (int)(MapMaxX() * TILE_SIZE) - 1);
b = Clamp(b, -4 * TILE_SIZE, (int)(MapMaxY() * TILE_SIZE) - 1);
/* (a, b) is the X/Y-world coordinate that belongs to (x,y) if the landscape would be completely flat on height 0.
* Now find the Z-world coordinate by fix point iteration.
* This is a bit tricky because the tile height is non-continuous at foundations.
* The clicked point should be approached from the back, otherwise there are regions that are not clickable.
* (FOUNDATION_HALFTILE_LOWER on SLOPE_STEEP_S hides north halftile completely)
* So give it a z-malus of 4 in the first iterations.
*/
z = 0;
int min_coord = _settings_game.construction.freeform_edges ? TILE_SIZE : 0;
for (int i = 0; i < 5; i++) z = GetSlopeZ(Clamp(a + (int)max(z, 4u) - 4, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + (int)max(z, 4u) - 4, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
for (uint malus = 3; malus > 0; malus--) z = GetSlopeZ(Clamp(a + (int)max(z, malus) - (int)malus, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + (int)max(z, malus) - (int)malus, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
for (int i = 0; i < 5; i++) z = GetSlopeZ(Clamp(a + (int)z, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + (int)z, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
pt.x = Clamp(a + (int)z, min_coord, MapMaxX() * TILE_SIZE - 1);
pt.y = Clamp(b + (int)z, min_coord, MapMaxY() * TILE_SIZE - 1);
return pt;
}
/* When used for zooming, check area below current coordinates (x,y)
* and return the tile of the zoomed out/in position (zoom_x, zoom_y)
* when you just want the tile, make x = zoom_x and y = zoom_y */
static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
{
Window *w;
ViewPort *vp;
Point pt;
if ( (w = FindWindowFromPt(x, y)) != NULL &&
(vp = IsPtInWindowViewport(w, x, y)) != NULL)
return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
pt.y = pt.x = -1;
return pt;
}
Point GetTileBelowCursor()
{
return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
}
Point GetTileZoomCenterWindow(bool in, Window * w)
{
int x, y;
ViewPort *vp = w->viewport;
if (in) {
x = ((_cursor.pos.x - vp->left) >> 1) + (vp->width >> 2);
y = ((_cursor.pos.y - vp->top) >> 1) + (vp->height >> 2);
} else {
x = vp->width - (_cursor.pos.x - vp->left);
y = vp->height - (_cursor.pos.y - vp->top);
}
/* Get the tile below the cursor and center on the zoomed-out center */
return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp->left, y + vp->top);
}
/** Update the status of the zoom-buttons according to the zoom-level
* of the viewport. This will update their status and invalidate accordingly
* @param w Window pointer to the window that has the zoom buttons
* @param vp pointer to the viewport whose zoom-level the buttons represent
* @param widget_zoom_in widget index for window with zoom-in button
* @param widget_zoom_out widget index for window with zoom-out button */
void HandleZoomMessage(Window *w, const ViewPort *vp, byte widget_zoom_in, byte widget_zoom_out)
{
w->SetWidgetDisabledState(widget_zoom_in, vp->zoom == ZOOM_LVL_MIN);
w->InvalidateWidget(widget_zoom_in);
w->SetWidgetDisabledState(widget_zoom_out, vp->zoom == ZOOM_LVL_MAX);
w->InvalidateWidget(widget_zoom_out);
}
/**
* Draws a ground sprite at a specific world-coordinate.
*
* @param image the image to draw.
* @param pal the provided palette.
* @param x position x of the sprite.
* @param y position y of the sprite.
* @param z position z of the sprite.
* @param sub Only draw a part of the sprite.
*
*/
void DrawGroundSpriteAt(SpriteID image, SpriteID pal, int32 x, int32 y, byte z, const SubSprite *sub)
{
assert((image & SPRITE_MASK) < MAX_SPRITES);
TileSpriteToDraw *ts = _vd.tile_sprites_to_draw.Append();
ts->image = image;
ts->pal = pal;
ts->sub = sub;
ts->x = x;
ts->y = y;
ts->z = z;
}
/**
* Adds a child sprite to the active foundation.
*
* The pixel offset of the sprite relative to the ParentSprite is the sum of the offset passed to OffsetGroundSprite() and extra_offs_?.
*
* @param image the image to draw.
* @param pal the provided palette.
* @param sub Only draw a part of the sprite.
* @param foundation_part Foundation part.
* @param extra_offs_x Pixel X offset for the sprite position.
* @param extra_offs_y Pixel Y offset for the sprite position.
*/
static void AddChildSpriteToFoundation(SpriteID image, SpriteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
{
assert(IsInsideMM(foundation_part, 0, FOUNDATION_PART_END));
assert(_vd.foundation[foundation_part] != -1);
Point offs = _vd.foundation_offset[foundation_part];
/* Change the active ChildSprite list to the one of the foundation */
int *old_child = _vd.last_child;
_vd.last_child = _vd.last_foundation_child[foundation_part];
AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub);
/* Switch back to last ChildSprite list */
_vd.last_child = old_child;
}
/**
* Draws a ground sprite for the current tile.
* If the current tile is drawn on top of a foundation the sprite is added as child sprite to the "foundation"-ParentSprite.
*
* @param image the image to draw.
* @param pal the provided palette.
* @param sub Only draw a part of the sprite.
*/
void DrawGroundSprite(SpriteID image, SpriteID pal, const SubSprite *sub)
{
/* Switch to first foundation part, if no foundation was drawn */
if (_vd.foundation_part == FOUNDATION_PART_NONE) _vd.foundation_part = FOUNDATION_PART_NORMAL;
if (_vd.foundation[_vd.foundation_part] != -1) {
AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, 0, 0);
} else {
DrawGroundSpriteAt(image, pal, _cur_ti->x, _cur_ti->y, _cur_ti->z, sub);
}
}
/**
* Called when a foundation has been drawn for the current tile.
* Successive ground sprites for the current tile will be drawn as child sprites of the "foundation"-ParentSprite, not as TileSprites.
*
* @param x sprite x-offset (screen coordinates) of ground sprites relative to the "foundation"-ParentSprite.
* @param y sprite y-offset (screen coordinates) of ground sprites relative to the "foundation"-ParentSprite.
*/
void OffsetGroundSprite(int x, int y)
{
/* Switch to next foundation part */
switch (_vd.foundation_part) {
case FOUNDATION_PART_NONE:
_vd.foundation_part = FOUNDATION_PART_NORMAL;
break;
case FOUNDATION_PART_NORMAL:
_vd.foundation_part = FOUNDATION_PART_HALFTILE;
break;
default: NOT_REACHED();
}
/* _vd.last_child == NULL if foundation sprite was clipped by the viewport bounds */
if (_vd.last_child != NULL) _vd.foundation[_vd.foundation_part] = _vd.parent_sprites_to_draw.Length() - 1;
_vd.foundation_offset[_vd.foundation_part].x = x;
_vd.foundation_offset[_vd.foundation_part].y = y;
_vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
}
/**
* Adds a child sprite to a parent sprite.
* In contrast to "AddChildSpriteScreen()" the sprite position is in world coordinates
*
* @param image the image to draw.
* @param pal the provided palette.
* @param x position x of the sprite.
* @param y position y of the sprite.
* @param z position z of the sprite.
* @param sub Only draw a part of the sprite.
*/
static void AddCombinedSprite(SpriteID image, SpriteID pal, int x, int y, byte z, const SubSprite *sub)
{
Point pt = RemapCoords(x, y, z);
const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
if (pt.x + spr->x_offs >= _vd.dpi.left + _vd.dpi.width ||
pt.x + spr->x_offs + spr->width <= _vd.dpi.left ||
pt.y + spr->y_offs >= _vd.dpi.top + _vd.dpi.height ||
pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
return;
const ParentSpriteToDraw *pstd = _vd.parent_sprites_to_draw.End() - 1;
AddChildSpriteScreen(image, pal, pt.x - pstd->left, pt.y - pstd->top, false, sub);
}
/** Draw a (transparent) sprite at given coordinates with a given bounding box.
* The bounding box extends from (x + bb_offset_x, y + bb_offset_y, z + bb_offset_z) to (x + w - 1, y + h - 1, z + dz - 1), both corners included.
* Bounding boxes with bb_offset_x == w or bb_offset_y == h or bb_offset_z == dz are allowed and produce thin slices.
*
* @note Bounding boxes are normally specified with bb_offset_x = bb_offset_y = bb_offset_z = 0. The extent of the bounding box in negative direction is
* defined by the sprite offset in the grf file.
* However if modifying the sprite offsets is not suitable (e.g. when using existing graphics), the bounding box can be tuned by bb_offset.
*
* @pre w >= bb_offset_x, h >= bb_offset_y, dz >= bb_offset_z. Else w, h or dz are ignored.
*
* @param image the image to combine and draw,
* @param pal the provided palette,
* @param x position X (world) of the sprite,
* @param y position Y (world) of the sprite,
* @param w bounding box extent towards positive X (world),
* @param h bounding box extent towards positive Y (world),
* @param dz bounding box extent towards positive Z (world),
* @param z position Z (world) of the sprite,
* @param transparent if true, switch the palette between the provided palette and the transparent palette,
* @param bb_offset_x bounding box extent towards negative X (world),
* @param bb_offset_y bounding box extent towards negative Y (world),
* @param bb_offset_z bounding box extent towards negative Z (world)
* @param sub Only draw a part of the sprite.
*/
void AddSortableSpriteToDraw(SpriteID image, SpriteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
{
int32 left, right, top, bottom;
assert((image & SPRITE_MASK) < MAX_SPRITES);
/* make the sprites transparent with the right palette */
if (transparent) {
SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
pal = PALETTE_TO_TRANSPARENT;
}
if (_vd.combine_sprites == 2) {
AddCombinedSprite(image, pal, x, y, z, sub);
return;
}
_vd.last_child = NULL;
Point pt = RemapCoords(x, y, z);
int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
/* Compute screen extents of sprite */
if (image == SPR_EMPTY_BOUNDING_BOX) {
left = tmp_left = RemapCoords(x + w , y + bb_offset_y, z + bb_offset_z).x;
right = RemapCoords(x + bb_offset_x, y + h , z + bb_offset_z).x + 1;
top = tmp_top = RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz ).y;
bottom = RemapCoords(x + w , y + h , z + bb_offset_z).y + 1;
} else {
const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
left = tmp_left = (pt.x += spr->x_offs);
right = (pt.x + spr->width );
top = tmp_top = (pt.y += spr->y_offs);
bottom = (pt.y + spr->height);
}
if (_draw_bounding_boxes && (image != SPR_EMPTY_BOUNDING_BOX)) {
/* Compute maximal extents of sprite and it's bounding box */
left = min(left , RemapCoords(x + w , y + bb_offset_y, z + bb_offset_z).x);
right = max(right , RemapCoords(x + bb_offset_x, y + h , z + bb_offset_z).x + 1);
top = min(top , RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz ).y);
bottom = max(bottom, RemapCoords(x + w , y + h , z + bb_offset_z).y + 1);
}
/* Do not add the sprite to the viewport, if it is outside */
if (left >= _vd.dpi.left + _vd.dpi.width ||
right <= _vd.dpi.left ||
top >= _vd.dpi.top + _vd.dpi.height ||
bottom <= _vd.dpi.top) {
return;
}
ParentSpriteToDraw *ps = _vd.parent_sprites_to_draw.Append();
ps->x = tmp_x;
ps->y = tmp_y;
ps->left = tmp_left;
ps->top = tmp_top;
ps->image = image;
ps->pal = pal;
ps->sub = sub;
ps->xmin = x + bb_offset_x;
ps->xmax = x + max(bb_offset_x, w) - 1;
ps->ymin = y + bb_offset_y;
ps->ymax = y + max(bb_offset_y, h) - 1;
ps->zmin = z + bb_offset_z;
ps->zmax = z + max(bb_offset_z, dz) - 1;
ps->comparison_done = false;
ps->first_child = -1;
_vd.last_child = &ps->first_child;
if (_vd.combine_sprites == 1) _vd.combine_sprites = 2;
}
void StartSpriteCombine()
{
_vd.combine_sprites = 1;
}
void EndSpriteCombine()
{
_vd.combine_sprites = 0;
}
/**
* Add a child sprite to a parent sprite.
*
* @param image the image to draw.
* @param pal the provided palette.
* @param x sprite x-offset (screen coordinates) relative to parent sprite.
* @param y sprite y-offset (screen coordinates) relative to parent sprite.
* @param transparent if true, switch the palette between the provided palette and the transparent palette,
* @param sub Only draw a part of the sprite.
*/
void AddChildSpriteScreen(SpriteID image, SpriteID pal, int x, int y, bool transparent, const SubSprite *sub)
{
assert((image & SPRITE_MASK) < MAX_SPRITES);
/* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
if (_vd.last_child == NULL) return;
/* make the sprites transparent with the right palette */
if (transparent) {
SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
pal = PALETTE_TO_TRANSPARENT;
}
*_vd.last_child = _vd.child_screen_sprites_to_draw.Length();
ChildScreenSpriteToDraw *cs = _vd.child_screen_sprites_to_draw.Append();
cs->image = image;
cs->pal = pal;
cs->sub = sub;
cs->x = x;
cs->y = y;
cs->next = -1;
/* Append the sprite to the active ChildSprite list.
* If the active ParentSprite is a foundation, update last_foundation_child as well.
* Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
if (_vd.last_foundation_child[0] == _vd.last_child) _vd.last_foundation_child[0] = &cs->next;
if (_vd.last_foundation_child[1] == _vd.last_child) _vd.last_foundation_child[1] = &cs->next;
_vd.last_child = &cs->next;
}
/* Returns a StringSpriteToDraw */
void AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2, uint16 colour, uint16 width)
{
StringSpriteToDraw *ss = _vd.string_sprites_to_draw.Append();
ss->string = string;
ss->x = x;
ss->y = y;
ss->params[0] = params_1;
ss->params[1] = params_2;
ss->width = width;
ss->colour = colour;
}
/**
* Draws sprites between ground sprite and everything above.
*
* The sprite is either drawn as TileSprite or as ChildSprite of the active foundation.
*
* @param image the image to draw.
* @param pal the provided palette.
* @param ti TileInfo Tile that is being drawn
* @param z_offset Z offset relative to the groundsprite. Only used for the sprite position, not for sprite sorting.
* @param foundation_part Foundation part the sprite belongs to.
*/
static void DrawSelectionSprite(SpriteID image, SpriteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part)
{
/* FIXME: This is not totally valid for some autorail highlights, that extent over the edges of the tile. */
if (_vd.foundation[foundation_part] == -1) {
/* draw on real ground */
DrawGroundSpriteAt(image, pal, ti->x, ti->y, ti->z + z_offset);
} else {
/* draw on top of foundation */
AddChildSpriteToFoundation(image, pal, NULL, foundation_part, 0, -z_offset);
}
}
/**
* Draws a selection rectangle on a tile.
*
* @param ti TileInfo Tile that is being drawn
* @param pal Palette to apply.
*/
static void DrawTileSelectionRect(const TileInfo *ti, SpriteID pal)
{
if (!IsValidTile(ti->tile)) return;
SpriteID sel;
if (IsHalftileSlope(ti->tileh)) {
Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + halftile_corner;
DrawSelectionSprite(sel2, pal, ti, 7 + TILE_HEIGHT, FOUNDATION_PART_HALFTILE);
Corner opposite_corner = OppositeCorner(halftile_corner);
if (IsSteepSlope(ti->tileh)) {
sel = SPR_HALFTILE_SELECTION_DOWN;
} else {
sel = ((ti->tileh & SlopeWithOneCornerRaised(opposite_corner)) != 0 ? SPR_HALFTILE_SELECTION_UP : SPR_HALFTILE_SELECTION_FLAT);
}
sel += opposite_corner;
} else {
sel = SPR_SELECT_TILE + _tileh_to_sprite[ti->tileh];
}
DrawSelectionSprite(sel, pal, ti, 7, FOUNDATION_PART_NORMAL);
}
static bool IsPartOfAutoLine(int px, int py)
{
px -= _thd.selstart.x;
py -= _thd.selstart.y;
if ((_thd.drawstyle & ~HT_DIR_MASK) != HT_LINE) return false;
switch (_thd.drawstyle & HT_DIR_MASK) {
case HT_DIR_X: return py == 0; // x direction
case HT_DIR_Y: return px == 0; // y direction
case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
case HT_DIR_VL: return px == py || px == py + 16; // vertival left
case HT_DIR_VR: return px == py || px == py - 16; // vertical right
default:
NOT_REACHED();
}
}
/* [direction][side] */
static const HighLightStyle _autorail_type[6][2] = {
{ HT_DIR_X, HT_DIR_X },
{ HT_DIR_Y, HT_DIR_Y },
{ HT_DIR_HU, HT_DIR_HL },
{ HT_DIR_HL, HT_DIR_HU },
{ HT_DIR_VL, HT_DIR_VR },
{ HT_DIR_VR, HT_DIR_VL }
};
#include "table/autorail.h"
/**
* Draws autorail highlights.
*
* @param *ti TileInfo Tile that is being drawn
* @param autorail_type Offset into _AutorailTilehSprite[][]
*/
static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
{
SpriteID image;
SpriteID pal;
int offset;
FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
Slope autorail_tileh = RemoveHalftileSlope(ti->tileh);
if (IsHalftileSlope(ti->tileh)) {
static const uint _lower_rail[4] = { 5U, 2U, 4U, 3U };
Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
if (autorail_type != _lower_rail[halftile_corner]) {
foundation_part = FOUNDATION_PART_HALFTILE;
/* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
autorail_tileh = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
}
}
offset = _AutorailTilehSprite[autorail_tileh][autorail_type];
if (offset >= 0) {
image = SPR_AUTORAIL_BASE + offset;
pal = PAL_NONE;
} else {
image = SPR_AUTORAIL_BASE - offset;
pal = PALETTE_SEL_TILE_RED;
}
DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
}
/**
* Checks if the specified tile is selected and if so draws selection using correct selectionstyle.
* @param *ti TileInfo Tile that is being drawn
*/
static void DrawTileSelection(const TileInfo *ti)
{
/* Draw a red error square? */
bool is_redsq = _thd.redsq == ti->tile;
if (is_redsq) DrawTileSelectionRect(ti, PALETTE_TILE_RED_PULSATING);
/* no selection active? */
if (_thd.drawstyle == 0) return;
/* Inside the inner area? */
if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
if (_thd.drawstyle & HT_RECT) {
if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
} else if (_thd.drawstyle & HT_POINT) {
/* Figure out the Z coordinate for the single dot. */
byte z = 0;
FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
if (ti->tileh & SLOPE_N) {
z += TILE_HEIGHT;
if (RemoveHalftileSlope(ti->tileh) == SLOPE_STEEP_N) z += TILE_HEIGHT;
}
if (IsHalftileSlope(ti->tileh)) {
Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
if ((halftile_corner == CORNER_W) || (halftile_corner == CORNER_E)) z += TILE_HEIGHT;
if (halftile_corner != CORNER_S) {
foundation_part = FOUNDATION_PART_HALFTILE;
if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
}
}
DrawSelectionSprite(_cur_dpi->zoom <= ZOOM_LVL_DETAIL ? SPR_DOT : SPR_DOT_SMALL, PAL_NONE, ti, z, foundation_part);
} else if (_thd.drawstyle & HT_RAIL /* && _thd.place_mode == VHM_RAIL*/) {
/* autorail highlight piece under cursor */
uint type = _thd.drawstyle & 0xF;
assert(type <= 5);
DrawAutorailSelection(ti, _autorail_type[type][0]);
} else if (IsPartOfAutoLine(ti->x, ti->y)) {
/* autorail highlighting long line */
int dir = _thd.drawstyle & ~0xF0;
uint side;
if (dir < 2) {
side = 0;
} else {
TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
}
DrawAutorailSelection(ti, _autorail_type[dir][side]);
}
return;
}
/* Check if it's inside the outer area? */
if (!is_redsq && _thd.outersize.x &&
_thd.size.x < _thd.size.x + _thd.outersize.x &&
IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
/* Draw a blue rect. */
DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE);
return;
}
}
static void ViewportAddLandscape()
{
int x, y, width, height;
TileInfo ti;
bool direction;
_cur_ti = &ti;
/* Transform into tile coordinates and round to closest full tile */
x = ((_vd.dpi.top >> 1) - (_vd.dpi.left >> 2)) & ~0xF;
y = ((_vd.dpi.top >> 1) + (_vd.dpi.left >> 2) - 0x10) & ~0xF;
/* determine size of area */
{
Point pt = RemapCoords(x, y, 241);
width = (_vd.dpi.left + _vd.dpi.width - pt.x + 95) >> 6;
height = (_vd.dpi.top + _vd.dpi.height - pt.y) >> 5 << 1;
}
assert(width > 0);
assert(height > 0);
direction = false;
do {
int width_cur = width;
int x_cur = x;
int y_cur = y;
do {
TileType tt = MP_VOID;
ti.x = x_cur;
ti.y = y_cur;
ti.z = 0;
ti.tileh = SLOPE_FLAT;
ti.tile = INVALID_TILE;
if (0 <= x_cur && x_cur < (int)MapMaxX() * TILE_SIZE &&
0 <= y_cur && y_cur < (int)MapMaxY() * TILE_SIZE) {
TileIndex tile = TileVirtXY(x_cur, y_cur);
if (!_settings_game.construction.freeform_edges || (TileX(tile) != 0 && TileY(tile) != 0)) {
if (x_cur == ((int)MapMaxX() - 1) * TILE_SIZE || y_cur == ((int)MapMaxY() - 1) * TILE_SIZE) {
uint maxh = max<uint>(TileHeight(tile), 1);
for (uint h = 0; h < maxh; h++) {
DrawGroundSpriteAt(SPR_SHADOW_CELL, PAL_NONE, ti.x, ti.y, h * TILE_HEIGHT);
}
}
ti.tile = tile;
ti.tileh = GetTileSlope(tile, &ti.z);
tt = GetTileType(tile);
}
}
_vd.foundation_part = FOUNDATION_PART_NONE;
_vd.foundation[0] = -1;
_vd.foundation[1] = -1;
_vd.last_foundation_child[0] = NULL;
_vd.last_foundation_child[1] = NULL;
_tile_type_procs[tt]->draw_tile_proc(&ti);
if ((x_cur == (int)MapMaxX() * TILE_SIZE && IsInsideMM(y_cur, 0, MapMaxY() * TILE_SIZE + 1)) ||
(y_cur == (int)MapMaxY() * TILE_SIZE && IsInsideMM(x_cur, 0, MapMaxX() * TILE_SIZE + 1))) {
TileIndex tile = TileVirtXY(x_cur, y_cur);
ti.tile = tile;
ti.tileh = GetTileSlope(tile, &ti.z);
tt = GetTileType(tile);
}
if (ti.tile != INVALID_TILE) DrawTileSelection(&ti);
y_cur += 0x10;
x_cur -= 0x10;
} while (--width_cur);
if ((direction ^= 1) != 0) {
y += 0x10;
} else {
x += 0x10;
}
} while (--height);
}
static void ViewportAddTownNames(DrawPixelInfo *dpi)
{
Town *t;
int left, top, right, bottom;
if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES) || _game_mode == GM_MENU)
return;
left = dpi->left;
top = dpi->top;
right = left + dpi->width;
bottom = top + dpi->height;
switch (dpi->zoom) {
case ZOOM_LVL_NORMAL:
FOR_ALL_TOWNS(t) {
if (bottom > t->sign.top &&
top < t->sign.top + 12 &&
right > t->sign.left &&
left < t->sign.left + t->sign.width_1) {
AddStringToDraw(t->sign.left + 1, t->sign.top + 1,
_settings_client.gui.population_in_label ? STR_TOWN_LABEL_POP : STR_TOWN_LABEL,
t->index, t->population);
}
}
break;
case ZOOM_LVL_OUT_2X:
right += 2;
bottom += 2;
FOR_ALL_TOWNS(t) {
if (bottom > t->sign.top &&
top < t->sign.top + 24 &&
right > t->sign.left &&
left < t->sign.left + t->sign.width_1 * 2) {
AddStringToDraw(t->sign.left + 1, t->sign.top + 1,
_settings_client.gui.population_in_label ? STR_TOWN_LABEL_POP : STR_TOWN_LABEL,
t->index, t->population);
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
right += ScaleByZoom(1, dpi->zoom);
bottom += ScaleByZoom(1, dpi->zoom) + 1;
FOR_ALL_TOWNS(t) {
if (bottom > t->sign.top &&
top < t->sign.top + ScaleByZoom(12, dpi->zoom) &&
right > t->sign.left &&
left < t->sign.left + ScaleByZoom(t->sign.width_2, dpi->zoom)) {
AddStringToDraw(t->sign.left + 5, t->sign.top + 1, STR_TOWN_LABEL_TINY_BLACK, t->index, 0);
AddStringToDraw(t->sign.left + 1, t->sign.top - 3, STR_TOWN_LABEL_TINY_WHITE, t->index, 0);
}
}
break;
default: NOT_REACHED();
}
}
static void AddStation(const Station *st, StringID str, uint16 width)
{
AddStringToDraw(st->sign.left + 1, st->sign.top + 1, str, st->index, st->facilities, (st->owner == OWNER_NONE || st->facilities == 0) ? 0xE : _company_colours[st->owner], width);
}
static void ViewportAddStationNames(DrawPixelInfo *dpi)
{
int left, top, right, bottom;
const Station *st;
if (!HasBit(_display_opt, DO_SHOW_STATION_NAMES) || _game_mode == GM_MENU)
return;
left = dpi->left;
top = dpi->top;
right = left + dpi->width;
bottom = top + dpi->height;
switch (dpi->zoom) {
case ZOOM_LVL_NORMAL:
FOR_ALL_STATIONS(st) {
if (bottom > st->sign.top &&
top < st->sign.top + 12 &&
right > st->sign.left &&
left < st->sign.left + st->sign.width_1) {
AddStation(st, STR_305C_0, st->sign.width_1);
}
}
break;
case ZOOM_LVL_OUT_2X:
right += 2;
bottom += 2;
FOR_ALL_STATIONS(st) {
if (bottom > st->sign.top &&
top < st->sign.top + 24 &&
right > st->sign.left &&
left < st->sign.left + st->sign.width_1 * 2) {
AddStation(st, STR_305C_0, st->sign.width_1);
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
right += ScaleByZoom(1, dpi->zoom);
bottom += ScaleByZoom(1, dpi->zoom) + 1;
FOR_ALL_STATIONS(st) {
if (bottom > st->sign.top &&
top < st->sign.top + ScaleByZoom(12, dpi->zoom) &&
right > st->sign.left &&
left < st->sign.left + ScaleByZoom(st->sign.width_2, dpi->zoom)) {
AddStation(st, STR_STATION_SIGN_TINY, st->sign.width_2 | 0x8000);
}
}
break;
default: NOT_REACHED();
}
}
static void AddSign(const Sign *si, StringID str, uint16 width)
{
AddStringToDraw(si->sign.left + 1, si->sign.top + 1, str, si->index, 0, (si->owner == OWNER_NONE) ? 14 : _company_colours[si->owner], width);
}
static void ViewportAddSigns(DrawPixelInfo *dpi)
{
const Sign *si;
int left, top, right, bottom;
/* Signs are turned off or are invisible */
if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS)) return;
left = dpi->left;
top = dpi->top;
right = left + dpi->width;
bottom = top + dpi->height;
switch (dpi->zoom) {
case ZOOM_LVL_NORMAL:
FOR_ALL_SIGNS(si) {
if (bottom > si->sign.top &&
top < si->sign.top + 12 &&
right > si->sign.left &&
left < si->sign.left + si->sign.width_1) {
AddSign(si, STR_2806, si->sign.width_1);
}
}
break;
case ZOOM_LVL_OUT_2X:
right += 2;
bottom += 2;
FOR_ALL_SIGNS(si) {
if (bottom > si->sign.top &&
top < si->sign.top + 24 &&
right > si->sign.left &&
left < si->sign.left + si->sign.width_1 * 2) {
AddSign(si, STR_2806, si->sign.width_1);
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
right += ScaleByZoom(1, dpi->zoom);
bottom += ScaleByZoom(1, dpi->zoom) + 1;
FOR_ALL_SIGNS(si) {
if (bottom > si->sign.top &&
top < si->sign.top + ScaleByZoom(12, dpi->zoom) &&
right > si->sign.left &&
left < si->sign.left + ScaleByZoom(si->sign.width_2, dpi->zoom)) {
AddSign(si, IsTransparencySet(TO_SIGNS) ? STR_2002_WHITE : STR_2002, si->sign.width_2 | 0x8000);
}
}
break;
default: NOT_REACHED();
}
}
static void AddWaypoint(const Waypoint *wp, StringID str, uint16 width)
{
AddStringToDraw(wp->sign.left + 1, wp->sign.top + 1, str, wp->index, 0, (wp->deleted ? 0xE : _company_colours[wp->owner]), width);
}
static void ViewportAddWaypoints(DrawPixelInfo *dpi)
{
const Waypoint *wp;
int left, top, right, bottom;
if (!HasBit(_display_opt, DO_WAYPOINTS))
return;
left = dpi->left;
top = dpi->top;
right = left + dpi->width;
bottom = top + dpi->height;
switch (dpi->zoom) {
case ZOOM_LVL_NORMAL:
FOR_ALL_WAYPOINTS(wp) {
if (bottom > wp->sign.top &&
top < wp->sign.top + 12 &&
right > wp->sign.left &&
left < wp->sign.left + wp->sign.width_1) {
AddWaypoint(wp, STR_WAYPOINT_VIEWPORT, wp->sign.width_1);
}
}
break;
case ZOOM_LVL_OUT_2X:
right += 2;
bottom += 2;
FOR_ALL_WAYPOINTS(wp) {
if (bottom > wp->sign.top &&
top < wp->sign.top + 24 &&
right > wp->sign.left &&
left < wp->sign.left + wp->sign.width_1 * 2) {
AddWaypoint(wp, STR_WAYPOINT_VIEWPORT, wp->sign.width_1);
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
right += ScaleByZoom(1, dpi->zoom);
bottom += ScaleByZoom(1, dpi->zoom) + 1;
FOR_ALL_WAYPOINTS(wp) {
if (bottom > wp->sign.top &&
top < wp->sign.top + ScaleByZoom(12, dpi->zoom) &&
right > wp->sign.left &&
left < wp->sign.left + ScaleByZoom(wp->sign.width_2, dpi->zoom)) {
AddWaypoint(wp, STR_WAYPOINT_VIEWPORT_TINY, wp->sign.width_2 | 0x8000);
}
}
break;
default: NOT_REACHED();
}
}
void UpdateViewportSignPos(ViewportSign *sign, int left, int top, StringID str)
{
char buffer[256];
uint w;
sign->top = top;
GetString(buffer, str, lastof(buffer));
w = GetStringBoundingBox(buffer).width + 3;
sign->width_1 = w;
sign->left = left - w / 2;
/* zoomed out version */
_cur_fontsize = FS_SMALL;
w = GetStringBoundingBox(buffer).width + 3;
_cur_fontsize = FS_NORMAL;
sign->width_2 = w;
}
static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
{
const TileSpriteToDraw *tsend = tstdv->End();
for (const TileSpriteToDraw *ts = tstdv->Begin(); ts != tsend; ++ts) {
Point pt = RemapCoords(ts->x, ts->y, ts->z);
DrawSprite(ts->image, ts->pal, pt.x, pt.y, ts->sub);
}
}
/** Sort parent sprites pointer array */
static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
{
ParentSpriteToDraw **psdvend = psdv->End();
ParentSpriteToDraw **psd = psdv->Begin();
while (psd != psdvend) {
ParentSpriteToDraw *ps = *psd;
if (ps->comparison_done) {
psd++;
continue;
}
ps->comparison_done = true;
for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) {
ParentSpriteToDraw *ps2 = *psd2;
if (ps2->comparison_done) continue;
/* Decide which comparator to use, based on whether the bounding
* boxes overlap
*/
if (ps->xmax >= ps2->xmin && ps->xmin <= ps2->xmax && // overlap in X?
ps->ymax >= ps2->ymin && ps->ymin <= ps2->ymax && // overlap in Y?
ps->zmax >= ps2->zmin && ps->zmin <= ps2->zmax) { // overlap in Z?
/* Use X+Y+Z as the sorting order, so sprites closer to the bottom of
* the screen and with higher Z elevation, are drawn in front.
* Here X,Y,Z are the coordinates of the "center of mass" of the sprite,
* i.e. X=(left+right)/2, etc.
* However, since we only care about order, don't actually divide / 2
*/
if (ps->xmin + ps->xmax + ps->ymin + ps->ymax + ps->zmin + ps->zmax <=
ps2->xmin + ps2->xmax + ps2->ymin + ps2->ymax + ps2->zmin + ps2->zmax) {
continue;
}
} else {
/* We only change the order, if it is definite.
* I.e. every single order of X, Y, Z says ps2 is behind ps or they overlap.
* That is: If one partial order says ps behind ps2, do not change the order.
*/
if (ps->xmax < ps2->xmin ||
ps->ymax < ps2->ymin ||
ps->zmax < ps2->zmin) {
continue;
}
}
/* Move ps2 in front of ps */
ParentSpriteToDraw *temp = ps2;
for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) {
*psd3 = *(psd3 - 1);
}
*psd = temp;
}
}
}
static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
{
const ParentSpriteToDraw * const *psd_end = psd->End();
for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
const ParentSpriteToDraw *ps = *it;
if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSprite(ps->image, ps->pal, ps->x, ps->y, ps->sub);
int child_idx = ps->first_child;
while (child_idx >= 0) {
const ChildScreenSpriteToDraw *cs = csstdv->Get(child_idx);
child_idx = cs->next;
DrawSprite(cs->image, cs->pal, ps->left + cs->x, ps->top + cs->y, cs->sub);
}
}
}
/**
* Draws the bounding boxes of all ParentSprites
* @param psd Array of ParentSprites
*/
static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
{
const ParentSpriteToDraw * const *psd_end = psd->End();
for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
const ParentSpriteToDraw *ps = *it;
Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner
Point pt2 = RemapCoords(ps->xmin , ps->ymax + 1, ps->zmax + 1); // top left corner
Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin , ps->zmax + 1); // top right corner
Point pt4 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmin ); // bottom front corner
DrawBox( pt1.x, pt1.y,
pt2.x - pt1.x, pt2.y - pt1.y,
pt3.x - pt1.x, pt3.y - pt1.y,
pt4.x - pt1.x, pt4.y - pt1.y);
}
}
static void ViewportDrawStrings(DrawPixelInfo *dpi, const StringSpriteToDrawVector *sstdv)
{
DrawPixelInfo dp;
ZoomLevel zoom;
_cur_dpi = &dp;
dp = *dpi;
zoom = dp.zoom;
dp.zoom = ZOOM_LVL_NORMAL;
dp.left = UnScaleByZoom(dp.left, zoom);
dp.top = UnScaleByZoom(dp.top, zoom);
dp.width = UnScaleByZoom(dp.width, zoom);
dp.height = UnScaleByZoom(dp.height, zoom);
const StringSpriteToDraw *ssend = sstdv->End();
for (const StringSpriteToDraw *ss = sstdv->Begin(); ss != ssend; ++ss) {
TextColour colour;
if (ss->width != 0) {
/* Do not draw signs nor station names if they are set invisible */
if (IsInvisibilitySet(TO_SIGNS) && ss->string != STR_2806) continue;
int x = UnScaleByZoom(ss->x, zoom) - 1;
int y = UnScaleByZoom(ss->y, zoom) - 1;
int bottom = y + 11;
int w = ss->width;
if (w & 0x8000) {
w &= ~0x8000;
y--;
bottom -= 6;
w -= 3;
}
/* Draw the rectangle if 'tranparent station signs' is off,
* or if we are drawing a general text sign (STR_2806) */
if (!IsTransparencySet(TO_SIGNS) || ss->string == STR_2806) {
DrawFrameRect(
x, y, x + w, bottom, (Colours)ss->colour,
IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE
);
}
}
SetDParam(0, ss->params[0]);
SetDParam(1, ss->params[1]);
/* if we didn't draw a rectangle, or if transparant building is on,
* draw the text in the colour the rectangle would have */
if (IsTransparencySet(TO_SIGNS) && ss->string != STR_2806 && ss->width != 0) {
/* Real colours need the IS_PALETTE_COLOUR flag
* otherwise colours from _string_colourmap are assumed. */
colour = (TextColour)_colour_gradient[ss->colour][6] | IS_PALETTE_COLOUR;
} else {
colour = TC_BLACK;
}
DrawString(
UnScaleByZoom(ss->x, zoom), UnScaleByZoom(ss->y, zoom) - (ss->width & 0x8000 ? 2 : 0),
ss->string, colour
);
}
}
void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom)
{
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &_vd.dpi;
_vd.dpi.zoom = vp->zoom;
int mask = ScaleByZoom(-1, vp->zoom);
_vd.combine_sprites = 0;
_vd.dpi.width = (right - left) & mask;
_vd.dpi.height = (bottom - top) & mask;
_vd.dpi.left = left & mask;
_vd.dpi.top = top & mask;
_vd.dpi.pitch = old_dpi->pitch;
_vd.last_child = NULL;
int x = UnScaleByZoom(_vd.dpi.left - (vp->virtual_left & mask), vp->zoom) + vp->left;
int y = UnScaleByZoom(_vd.dpi.top - (vp->virtual_top & mask), vp->zoom) + vp->top;
_vd.dpi.dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(old_dpi->dst_ptr, x - old_dpi->left, y - old_dpi->top);
ViewportAddLandscape();
ViewportAddVehicles(&_vd.dpi);
ViewportAddTownNames(&_vd.dpi);
ViewportAddStationNames(&_vd.dpi);
ViewportAddSigns(&_vd.dpi);
ViewportAddWaypoints(&_vd.dpi);
DrawTextEffects(&_vd.dpi);
if (_vd.tile_sprites_to_draw.Length() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
ParentSpriteToDraw *psd_end = _vd.parent_sprites_to_draw.End();
for (ParentSpriteToDraw *it = _vd.parent_sprites_to_draw.Begin(); it != psd_end; it++) {
*_vd.parent_sprites_to_sort.Append() = it;
}
ViewportSortParentSprites(&_vd.parent_sprites_to_sort);
ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
if (_vd.string_sprites_to_draw.Length() != 0) ViewportDrawStrings(&_vd.dpi, &_vd.string_sprites_to_draw);
_cur_dpi = old_dpi;
_vd.string_sprites_to_draw.Clear();
_vd.tile_sprites_to_draw.Clear();
_vd.parent_sprites_to_draw.Clear();
_vd.parent_sprites_to_sort.Clear();
_vd.child_screen_sprites_to_draw.Clear();
}
/** Make sure we don't draw a too big area at a time.
* If we do, the sprite memory will overflow. */
static void ViewportDrawChk(const ViewPort *vp, int left, int top, int right, int bottom)
{
if (ScaleByZoom(bottom - top, vp->zoom) * ScaleByZoom(right - left, vp->zoom) > 180000) {
if ((bottom - top) > (right - left)) {
int t = (top + bottom) >> 1;
ViewportDrawChk(vp, left, top, right, t);
ViewportDrawChk(vp, left, t, right, bottom);
} else {
int t = (left + right) >> 1;
ViewportDrawChk(vp, left, top, t, bottom);
ViewportDrawChk(vp, t, top, right, bottom);
}
} else {
ViewportDoDraw(vp,
ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
ScaleByZoom(top - vp->top, vp->zoom) + vp->virtual_top,
ScaleByZoom(right - vp->left, vp->zoom) + vp->virtual_left,
ScaleByZoom(bottom - vp->top, vp->zoom) + vp->virtual_top
);
}
}
static inline void ViewportDraw(const ViewPort *vp, int left, int top, int right, int bottom)
{
if (right <= vp->left || bottom <= vp->top) return;
if (left >= vp->left + vp->width) return;
if (left < vp->left) left = vp->left;
if (right > vp->left + vp->width) right = vp->left + vp->width;
if (top >= vp->top + vp->height) return;
if (top < vp->top) top = vp->top;
if (bottom > vp->top + vp->height) bottom = vp->top + vp->height;
ViewportDrawChk(vp, left, top, right, bottom);
}
/**
* Draw the viewport of this window.
*/
void Window::DrawViewport() const
{
DrawPixelInfo *dpi = _cur_dpi;
dpi->left += this->left;
dpi->top += this->top;
ViewportDraw(this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
dpi->left -= this->left;
dpi->top -= this->top;
}
static inline void ClampViewportToMap(const ViewPort *vp, int &x, int &y)
{
/* Centre of the viewport is hot spot */
x += vp->virtual_width / 2;
y += vp->virtual_height / 2;
/* Convert viewport coordinates to map coordinates
* Calculation is scaled by 4 to avoid rounding errors */
int vx = -x + y * 2;
int vy = x + y * 2;
/* clamp to size of map */
vx = Clamp(vx, 0, MapMaxX() * TILE_SIZE * 4);
vy = Clamp(vy, 0, MapMaxY() * TILE_SIZE * 4);
/* Convert map coordinates to viewport coordinates */
x = (-vx + vy) / 2;
y = ( vx + vy) / 4;
/* Remove centreing */
x -= vp->virtual_width / 2;
y -= vp->virtual_height / 2;
}
void UpdateViewportPosition(Window *w)
{
const ViewPort *vp = w->viewport;
if (w->viewport->follow_vehicle != INVALID_VEHICLE) {
const Vehicle *veh = GetVehicle(w->viewport->follow_vehicle);
Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
w->viewport->scrollpos_x = pt.x;
w->viewport->scrollpos_y = pt.y;
SetViewportPosition(w, pt.x, pt.y);
} else {
/* Ensure the destination location is within the map */
ClampViewportToMap(vp, w->viewport->dest_scrollpos_x, w->viewport->dest_scrollpos_y);
int delta_x = w->viewport->dest_scrollpos_x - w->viewport->scrollpos_x;
int delta_y = w->viewport->dest_scrollpos_y - w->viewport->scrollpos_y;
if (delta_x != 0 || delta_y != 0) {
if (_settings_client.gui.smooth_scroll) {
int max_scroll = ScaleByMapSize1D(512);
/* Not at our desired positon yet... */
w->viewport->scrollpos_x += Clamp(delta_x / 4, -max_scroll, max_scroll);
w->viewport->scrollpos_y += Clamp(delta_y / 4, -max_scroll, max_scroll);
} else {
w->viewport->scrollpos_x = w->viewport->dest_scrollpos_x;
w->viewport->scrollpos_y = w->viewport->dest_scrollpos_y;
}
}
ClampViewportToMap(vp, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
SetViewportPosition(w, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
}
}
/**
* Marks a viewport as dirty for repaint if it displays (a part of) the area the needs to be repainted.
* @param vp The viewport to mark as dirty
* @param left Left edge of area to repaint
* @param top Top edge of area to repaint
* @param right Right edge of area to repaint
* @param bottom Bottom edge of area to repaint
* @ingroup dirty
*/
static void MarkViewportDirty(const ViewPort *vp, int left, int top, int right, int bottom)
{
right -= vp->virtual_left;
if (right <= 0) return;
bottom -= vp->virtual_top;
if (bottom <= 0) return;
left = max(0, left - vp->virtual_left);
if (left >= vp->virtual_width) return;
top = max(0, top - vp->virtual_top);
if (top >= vp->virtual_height) return;
SetDirtyBlocks(
UnScaleByZoomLower(left, vp->zoom) + vp->left,
UnScaleByZoomLower(top, vp->zoom) + vp->top,
UnScaleByZoom(right, vp->zoom) + vp->left + 1,
UnScaleByZoom(bottom, vp->zoom) + vp->top + 1
);
}
/**
* Mark all viewports that display an area as dirty (in need of repaint).
* @param left Left edge of area to repaint
* @param top Top edge of area to repaint
* @param right Right edge of area to repaint
* @param bottom Bottom edge of area to repaint
* @ingroup dirty
*/
void MarkAllViewportsDirty(int left, int top, int right, int bottom)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
ViewPort *vp = w->viewport;
if (vp != NULL) {
assert(vp->width != 0);
MarkViewportDirty(vp, left, top, right, bottom);
}
}
}
void MarkTileDirtyByTile(TileIndex tile)
{
Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, GetTileZ(tile));
MarkAllViewportsDirty(
pt.x - 31,
pt.y - 122,
pt.x - 31 + 67,
pt.y - 122 + 154
);
}
void MarkTileDirty(int x, int y)
{
uint z = 0;
Point pt;
if (IsInsideMM(x, 0, MapSizeX() * TILE_SIZE) &&
IsInsideMM(y, 0, MapSizeY() * TILE_SIZE))
z = GetTileZ(TileVirtXY(x, y));
pt = RemapCoords(x, y, z);
MarkAllViewportsDirty(
pt.x - 31,
pt.y - 122,
pt.x - 31 + 67,
pt.y - 122 + 154
);
}
/**
* Marks the selected tiles as dirty.
*
* This function marks the selected tiles as dirty for repaint
*
* @note Documentation may be wrong (Progman)
* @ingroup dirty
*/
static void SetSelectionTilesDirty()
{
int y_size, x_size;
int x = _thd.pos.x;
int y = _thd.pos.y;
x_size = _thd.size.x;
y_size = _thd.size.y;
if (_thd.outersize.x) {
x_size += _thd.outersize.x;
x += _thd.offs.x;
y_size += _thd.outersize.y;
y += _thd.offs.y;
}
assert(x_size > 0);
assert(y_size > 0);
x_size += x;
y_size += y;
do {
int y_bk = y;
do {
MarkTileDirty(x, y);
} while ( (y += TILE_SIZE) != y_size);
y = y_bk;
} while ( (x += TILE_SIZE) != x_size);
}
void SetSelectionRed(bool b)
{
_thd.make_square_red = b;
SetSelectionTilesDirty();
}
static bool CheckClickOnTown(const ViewPort *vp, int x, int y)
{
const Town *t;
if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES)) return false;
switch (vp->zoom) {
case ZOOM_LVL_NORMAL:
x = x - vp->left + vp->virtual_left;
y = y - vp->top + vp->virtual_top;
FOR_ALL_TOWNS(t) {
if (y >= t->sign.top &&
y < t->sign.top + 12 &&
x >= t->sign.left &&
x < t->sign.left + t->sign.width_1) {
ShowTownViewWindow(t->index);
return true;
}
}
break;
case ZOOM_LVL_OUT_2X:
x = (x - vp->left + 1) * 2 + vp->virtual_left;
y = (y - vp->top + 1) * 2 + vp->virtual_top;
FOR_ALL_TOWNS(t) {
if (y >= t->sign.top &&
y < t->sign.top + 24 &&
x >= t->sign.left &&
x < t->sign.left + t->sign.width_1 * 2) {
ShowTownViewWindow(t->index);
return true;
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
x = ScaleByZoom(x - vp->left + ScaleByZoom(1, vp->zoom) - 1, vp->zoom) + vp->virtual_left;
y = ScaleByZoom(y - vp->top + ScaleByZoom(1, vp->zoom) - 1, vp->zoom) + vp->virtual_top;
FOR_ALL_TOWNS(t) {
if (y >= t->sign.top &&
y < t->sign.top + ScaleByZoom(12, vp->zoom) &&
x >= t->sign.left &&
x < t->sign.left + ScaleByZoom(t->sign.width_2, vp->zoom)) {
ShowTownViewWindow(t->index);
return true;
}
}
break;
default: NOT_REACHED();
}
return false;
}
static bool CheckClickOnStation(const ViewPort *vp, int x, int y)
{
const Station *st;
if (!HasBit(_display_opt, DO_SHOW_STATION_NAMES) || IsInvisibilitySet(TO_SIGNS)) return false;
switch (vp->zoom) {
case ZOOM_LVL_NORMAL:
x = x - vp->left + vp->virtual_left;
y = y - vp->top + vp->virtual_top;
FOR_ALL_STATIONS(st) {
if (y >= st->sign.top &&
y < st->sign.top + 12 &&
x >= st->sign.left &&
x < st->sign.left + st->sign.width_1) {
ShowStationViewWindow(st->index);
return true;
}
}
break;
case ZOOM_LVL_OUT_2X:
x = (x - vp->left + 1) * 2 + vp->virtual_left;
y = (y - vp->top + 1) * 2 + vp->virtual_top;
FOR_ALL_STATIONS(st) {
if (y >= st->sign.top &&
y < st->sign.top + 24 &&
x >= st->sign.left &&
x < st->sign.left + st->sign.width_1 * 2) {
ShowStationViewWindow(st->index);
return true;
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
x = ScaleByZoom(x - vp->left + ScaleByZoom(1, vp->zoom) - 1, vp->zoom) + vp->virtual_left;
y = ScaleByZoom(y - vp->top + ScaleByZoom(1, vp->zoom) - 1, vp->zoom) + vp->virtual_top;
FOR_ALL_STATIONS(st) {
if (y >= st->sign.top &&
y < st->sign.top + ScaleByZoom(12, vp->zoom) &&
x >= st->sign.left &&
x < st->sign.left + ScaleByZoom(st->sign.width_2, vp->zoom)) {
ShowStationViewWindow(st->index);
return true;
}
}
break;
default: NOT_REACHED();
}
return false;
}
static bool CheckClickOnSign(const ViewPort *vp, int x, int y)
{
const Sign *si;
/* Signs are turned off, or they are transparent and invisibility is ON, or company is a spectator */
if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS) || _current_company == COMPANY_SPECTATOR) return false;
switch (vp->zoom) {
case ZOOM_LVL_NORMAL:
x = x - vp->left + vp->virtual_left;
y = y - vp->top + vp->virtual_top;
FOR_ALL_SIGNS(si) {
if (y >= si->sign.top &&
y < si->sign.top + 12 &&
x >= si->sign.left &&
x < si->sign.left + si->sign.width_1) {
HandleClickOnSign(si);
return true;
}
}
break;
case ZOOM_LVL_OUT_2X:
x = (x - vp->left + 1) * 2 + vp->virtual_left;
y = (y - vp->top + 1) * 2 + vp->virtual_top;
FOR_ALL_SIGNS(si) {
if (y >= si->sign.top &&
y < si->sign.top + 24 &&
x >= si->sign.left &&
x < si->sign.left + si->sign.width_1 * 2) {
HandleClickOnSign(si);
return true;
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
x = ScaleByZoom(x - vp->left + ScaleByZoom(1, vp->zoom) - 1, vp->zoom) + vp->virtual_left;
y = ScaleByZoom(y - vp->top + ScaleByZoom(1, vp->zoom) - 1, vp->zoom) + vp->virtual_top;
FOR_ALL_SIGNS(si) {
if (y >= si->sign.top &&
y < si->sign.top + ScaleByZoom(12, vp->zoom) &&
x >= si->sign.left &&
x < si->sign.left + ScaleByZoom(si->sign.width_2, vp->zoom)) {
HandleClickOnSign(si);
return true;
}
}
break;
default: NOT_REACHED();
}
return false;
}
static bool CheckClickOnWaypoint(const ViewPort *vp, int x, int y)
{
const Waypoint *wp;
if (!HasBit(_display_opt, DO_WAYPOINTS) || IsInvisibilitySet(TO_SIGNS)) return false;
switch (vp->zoom) {
case ZOOM_LVL_NORMAL:
x = x - vp->left + vp->virtual_left;
y = y - vp->top + vp->virtual_top;
FOR_ALL_WAYPOINTS(wp) {
if (y >= wp->sign.top &&
y < wp->sign.top + 12 &&
x >= wp->sign.left &&
x < wp->sign.left + wp->sign.width_1) {
ShowWaypointWindow(wp);
return true;
}
}
break;
case ZOOM_LVL_OUT_2X:
x = (x - vp->left + 1) * 2 + vp->virtual_left;
y = (y - vp->top + 1) * 2 + vp->virtual_top;
FOR_ALL_WAYPOINTS(wp) {
if (y >= wp->sign.top &&
y < wp->sign.top + 24 &&
x >= wp->sign.left &&
x < wp->sign.left + wp->sign.width_1 * 2) {
ShowWaypointWindow(wp);
return true;
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
x = ScaleByZoom(x - vp->left + ScaleByZoom(1, vp->zoom) - 1, vp->zoom) + vp->virtual_left;
y = ScaleByZoom(y - vp->top + ScaleByZoom(1, vp->zoom) - 1, vp->zoom) + vp->virtual_top;
FOR_ALL_WAYPOINTS(wp) {
if (y >= wp->sign.top &&
y < wp->sign.top + ScaleByZoom(12, vp->zoom) &&
x >= wp->sign.left &&
x < wp->sign.left + ScaleByZoom(wp->sign.width_2, vp->zoom)) {
ShowWaypointWindow(wp);
return true;
}
}
break;
default: NOT_REACHED();
}
return false;
}
static bool CheckClickOnLandscape(const ViewPort *vp, int x, int y)
{
Point pt = TranslateXYToTileCoord(vp, x, y);
if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
return true;
}
bool HandleViewportClicked(const ViewPort *vp, int x, int y)
{
const Vehicle *v;
if (CheckClickOnTown(vp, x, y)) return true;
if (CheckClickOnStation(vp, x, y)) return true;
if (CheckClickOnSign(vp, x, y)) return true;
if (CheckClickOnWaypoint(vp, x, y)) return true;
CheckClickOnLandscape(vp, x, y);
v = CheckClickOnVehicle(vp, x, y);
if (v != NULL) {
DEBUG(misc, 2, "Vehicle %d (index %d) at %p", v->unitnumber, v->index, v);
if (IsCompanyBuildableVehicleType(v)) ShowVehicleViewWindow(v->First());
return true;
}
return CheckClickOnLandscape(vp, x, y);
}
Vehicle *CheckMouseOverVehicle()
{
const Window *w;
const ViewPort *vp;
int x = _cursor.pos.x;
int y = _cursor.pos.y;
w = FindWindowFromPt(x, y);
if (w == NULL) return NULL;
vp = IsPtInWindowViewport(w, x, y);
return (vp != NULL) ? CheckClickOnVehicle(vp, x, y) : NULL;
}
void PlaceObject()
{
Point pt;
Window *w;
pt = GetTileBelowCursor();
if (pt.x == -1) return;
if (_thd.place_mode == VHM_POINT) {
pt.x += 8;
pt.y += 8;
}
_tile_fract_coords.x = pt.x & 0xF;
_tile_fract_coords.y = pt.y & 0xF;
w = GetCallbackWnd();
if (w != NULL) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
}
/* scrolls the viewport in a window to a given location */
bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
{
/* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
if (z == -1) z = GetSlopeZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
Point pt = MapXYZToViewport(w->viewport, x, y, z);
w->viewport->follow_vehicle = INVALID_VEHICLE;
if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y)
return false;
if (instant) {
w->viewport->scrollpos_x = pt.x;
w->viewport->scrollpos_y = pt.y;
}
w->viewport->dest_scrollpos_x = pt.x;
w->viewport->dest_scrollpos_y = pt.y;
return true;
}
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
{
return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
}
void SetRedErrorSquare(TileIndex tile)
{
TileIndex old;
old = _thd.redsq;
_thd.redsq = tile;
if (tile != old) {
if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
if (old != INVALID_TILE) MarkTileDirtyByTile(old);
}
}
void SetTileSelectSize(int w, int h)
{
_thd.new_size.x = w * TILE_SIZE;
_thd.new_size.y = h * TILE_SIZE;
_thd.new_outersize.x = 0;
_thd.new_outersize.y = 0;
}
void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
{
_thd.offs.x = ox * TILE_SIZE;
_thd.offs.y = oy * TILE_SIZE;
_thd.new_outersize.x = sx * TILE_SIZE;
_thd.new_outersize.y = sy * TILE_SIZE;
}
/** returns the best autorail highlight type from map coordinates */
static HighLightStyle GetAutorailHT(int x, int y)
{
return HT_RAIL | _autorail_piece[x & 0xF][y & 0xF];
}
/**
* Updates tile highlighting for all cases.
* Uses _thd.selstart and _thd.selend and _thd.place_mode (set elsewhere) to determine _thd.pos and _thd.size
* Also drawstyle is determined. Uses _thd.new.* as a buffer and calls SetSelectionTilesDirty() twice,
* Once for the old and once for the new selection.
* _thd is TileHighlightData, found in viewport.h
*/
void UpdateTileSelection()
{
int x1;
int y1;
_thd.new_drawstyle = 0;
if (_thd.place_mode == VHM_SPECIAL) {
x1 = _thd.selend.x;
y1 = _thd.selend.y;
if (x1 != -1) {
int x2 = _thd.selstart.x & ~0xF;
int y2 = _thd.selstart.y & ~0xF;
x1 &= ~0xF;
y1 &= ~0xF;
if (x1 >= x2) Swap(x1, x2);
if (y1 >= y2) Swap(y1, y2);
_thd.new_pos.x = x1;
_thd.new_pos.y = y1;
_thd.new_size.x = x2 - x1 + TILE_SIZE;
_thd.new_size.y = y2 - y1 + TILE_SIZE;
_thd.new_drawstyle = _thd.next_drawstyle;
}
} else if (_thd.place_mode != VHM_NONE) {
Point pt = GetTileBelowCursor();
x1 = pt.x;
y1 = pt.y;
if (x1 != -1) {
switch (_thd.place_mode) {
case VHM_RECT:
_thd.new_drawstyle = HT_RECT;
break;
case VHM_POINT:
_thd.new_drawstyle = HT_POINT;
x1 += 8;
y1 += 8;
break;
case VHM_RAIL:
_thd.new_drawstyle = GetAutorailHT(pt.x, pt.y); // draw one highlighted tile
break;
default:
NOT_REACHED();
break;
}
_thd.new_pos.x = x1 & ~0xF;
_thd.new_pos.y = y1 & ~0xF;
}
}
/* redraw selection */
if (_thd.drawstyle != _thd.new_drawstyle ||
_thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
_thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
_thd.outersize.x != _thd.new_outersize.x ||
_thd.outersize.y != _thd.new_outersize.y) {
/* clear the old selection? */
if (_thd.drawstyle) SetSelectionTilesDirty();
_thd.drawstyle = _thd.new_drawstyle;
_thd.pos = _thd.new_pos;
_thd.size = _thd.new_size;
_thd.outersize = _thd.new_outersize;
_thd.dirty = 0xff;
/* draw the new selection? */
if (_thd.new_drawstyle) SetSelectionTilesDirty();
}
}
/** Displays the measurement tooltips when selecting multiple tiles
* @param str String to be displayed
* @param paramcount number of params to deal with
* @param params (optional) up to 5 pieces of additional information that may be added to a tooltip
*/
static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[])
{
if (!_settings_client.gui.measure_tooltip) return;
GuiShowTooltips(str, paramcount, params, true);
}
/** highlighting tiles while only going over them with the mouse */
void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
{
_thd.select_method = method;
_thd.select_proc = process;
_thd.selend.x = TileX(tile) * TILE_SIZE;
_thd.selstart.x = TileX(tile) * TILE_SIZE;
_thd.selend.y = TileY(tile) * TILE_SIZE;
_thd.selstart.y = TileY(tile) * TILE_SIZE;
/* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
* In effect, placement starts from the centre of a tile
*/
if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
_thd.selend.x += TILE_SIZE / 2;
_thd.selend.y += TILE_SIZE / 2;
_thd.selstart.x += TILE_SIZE / 2;
_thd.selstart.y += TILE_SIZE / 2;
}
if (_thd.place_mode == VHM_RECT) {
_thd.place_mode = VHM_SPECIAL;
_thd.next_drawstyle = HT_RECT;
} else if (_thd.place_mode == VHM_RAIL) { // autorail one piece
_thd.place_mode = VHM_SPECIAL;
_thd.next_drawstyle = _thd.drawstyle;
} else {
_thd.place_mode = VHM_SPECIAL;
_thd.next_drawstyle = HT_POINT;
}
_special_mouse_mode = WSM_SIZING;
}
void VpSetPlaceSizingLimit(int limit)
{
_thd.sizelimit = limit;
}
/**
* Highlights all tiles between a set of two tiles. Used in dock and tunnel placement
* @param from TileIndex of the first tile to highlight
* @param to TileIndex of the last tile to highlight */
void VpSetPresizeRange(TileIndex from, TileIndex to)
{
uint64 distance = DistanceManhattan(from, to) + 1;
_thd.selend.x = TileX(to) * TILE_SIZE;
_thd.selend.y = TileY(to) * TILE_SIZE;
_thd.selstart.x = TileX(from) * TILE_SIZE;
_thd.selstart.y = TileY(from) * TILE_SIZE;
_thd.next_drawstyle = HT_RECT;
/* show measurement only if there is any length to speak of */
if (distance > 1) ShowMeasurementTooltips(STR_MEASURE_LENGTH, 1, &distance);
}
static void VpStartPreSizing()
{
_thd.selend.x = -1;
_special_mouse_mode = WSM_PRESIZE;
}
/** returns information about the 2x1 piece to be build.
* The lower bits (0-3) are the track type. */
static HighLightStyle Check2x1AutoRail(int mode)
{
int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
int sxpy = (_thd.selend.x & 0xF) + (_thd.selend.y & 0xF);
int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
int sxmy = (_thd.selend.x & 0xF) - (_thd.selend.y & 0xF);
switch (mode) {
default: NOT_REACHED();
case 0: // end piece is lower right
if (fxpy >= 20 && sxpy <= 12) { /*SwapSelection(); DoRailroadTrack(0); */return HT_DIR_HL; }
if (fxmy < -3 && sxmy > 3) {/* DoRailroadTrack(0); */return HT_DIR_VR; }
return HT_DIR_Y;
case 1:
if (fxmy > 3 && sxmy < -3) { /*SwapSelection(); DoRailroadTrack(0); */return HT_DIR_VL; }
if (fxpy <= 12 && sxpy >= 20) { /*DoRailroadTrack(0); */return HT_DIR_HU; }
return HT_DIR_Y;
case 2:
if (fxmy > 3 && sxmy < -3) { /*DoRailroadTrack(3);*/ return HT_DIR_VL; }
if (fxpy >= 20 && sxpy <= 12) { /*SwapSelection(); DoRailroadTrack(0); */return HT_DIR_HL; }
return HT_DIR_X;
case 3:
if (fxmy < -3 && sxmy > 3) { /*SwapSelection(); DoRailroadTrack(3);*/ return HT_DIR_VR; }
if (fxpy <= 12 && sxpy >= 20) { /*DoRailroadTrack(0); */return HT_DIR_HU; }
return HT_DIR_X;
}
}
/** Check if the direction of start and end tile should be swapped based on
* the dragging-style. Default directions are:
* in the case of a line (HT_RAIL, HT_LINE): DIR_NE, DIR_NW, DIR_N, DIR_E
* in the case of a rect (HT_RECT, HT_POINT): DIR_S, DIR_E
* For example dragging a rectangle area from south to north should be swapped to
* north-south (DIR_S) to obtain the same results with less code. This is what
* the return value signifies.
* @param style HighLightStyle dragging style
* @param start_tile start tile of drag
* @param end_tile end tile of drag
* @return boolean value which when true means start/end should be swapped */
static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
{
uint start_x = TileX(start_tile);
uint start_y = TileY(start_tile);
uint end_x = TileX(end_tile);
uint end_y = TileY(end_tile);
switch (style & HT_DRAG_MASK) {
case HT_RAIL:
case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
case HT_RECT:
case HT_POINT: return (end_x != start_x && end_y < start_y);
default: NOT_REACHED();
}
return false;
}
/** Calculates height difference between one tile and another
* Multiplies the result to suit the standard given by minimap - 50 meters high
* To correctly get the height difference we need the direction we are dragging
* in, as well as with what kind of tool we are dragging. For example a horizontal
* autorail tool that starts in bottom and ends at the top of a tile will need the
* maximum of SW, S and SE, N corners respectively. This is handled by the lookup table below
* See _tileoffs_by_dir in map.c for the direction enums if you can't figure out
* the values yourself.
* @param style HightlightStyle of drag. This includes direction and style (autorail, rect, etc.)
* @param distance amount of tiles dragged, important for horizontal/vertical drags
* ignored for others
* @param start_tile, end_tile start and end tile of drag operation
* @return height difference between two tiles. Tile measurement tool utilizes
* this value in its tooltips */
static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
{
bool swap = SwapDirection(style, start_tile, end_tile);
byte style_t;
uint h0, h1, ht; // start heigth, end height, and temp variable
if (start_tile == end_tile) return 0;
if (swap) Swap(start_tile, end_tile);
switch (style & HT_DRAG_MASK) {
case HT_RECT: {
static const TileIndexDiffC heightdiff_area_by_dir[] = {
/* Start */ {1, 0}, /* Dragging east */ {0, 0}, // Dragging south
/* End */ {0, 1}, /* Dragging east */ {1, 1} // Dragging south
};
/* In the case of an area we can determine whether we were dragging south or
* east by checking the X-coordinates of the tiles */
style_t = (byte)(TileX(end_tile) > TileX(start_tile));
start_tile = TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_area_by_dir[style_t]));
end_tile = TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_area_by_dir[2 + style_t]));
}
/* Fallthrough */
case HT_POINT:
h0 = TileHeight(start_tile);
h1 = TileHeight(end_tile);
break;
default: { // All other types, this is mostly only line/autorail
static const HighLightStyle flip_style_direction[] = {
HT_DIR_X, HT_DIR_Y, HT_DIR_HL, HT_DIR_HU, HT_DIR_VR, HT_DIR_VL
};
static const TileIndexDiffC heightdiff_line_by_dir[] = {
/* Start */ {1, 0}, {1, 1}, /* HT_DIR_X */ {0, 1}, {1, 1}, // HT_DIR_Y
/* Start */ {1, 0}, {0, 0}, /* HT_DIR_HU */ {1, 0}, {1, 1}, // HT_DIR_HL
/* Start */ {1, 0}, {1, 1}, /* HT_DIR_VL */ {0, 1}, {1, 1}, // HT_DIR_VR
/* Start */ {0, 1}, {0, 0}, /* HT_DIR_X */ {1, 0}, {0, 0}, // HT_DIR_Y
/* End */ {0, 1}, {0, 0}, /* HT_DIR_HU */ {1, 1}, {0, 1}, // HT_DIR_HL
/* End */ {1, 0}, {0, 0}, /* HT_DIR_VL */ {0, 0}, {0, 1}, // HT_DIR_VR
};
distance %= 2; // we're only interested if the distance is even or uneven
style &= HT_DIR_MASK;
/* To handle autorail, we do some magic to be able to use a lookup table.
* Firstly if we drag the other way around, we switch start&end, and if needed
* also flip the drag-position. Eg if it was on the left, and the distance is even
* that means the end, which is now the start is on the right */
if (swap && distance == 0) style = flip_style_direction[style];
/* Use lookup table for start-tile based on HighLightStyle direction */
style_t = style * 2;
assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
h0 = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t])));
ht = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1])));
h0 = max(h0, ht);
/* Use lookup table for end-tile based on HighLightStyle direction
* flip around side (lower/upper, left/right) based on distance */
if (distance == 0) style_t = flip_style_direction[style] * 2;
assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
h1 = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t])));
ht = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1])));
h1 = max(h1, ht);
} break;
}
if (swap) Swap(h0, h1);
/* Minimap shows height in intervals of 50 meters, let's do the same */
return (int)(h1 - h0) * 50;
}
static const StringID measure_strings_length[] = {STR_NULL, STR_MEASURE_LENGTH, STR_MEASURE_LENGTH_HEIGHTDIFF};
/** while dragging */
static void CalcRaildirsDrawstyle(TileHighlightData *thd, int x, int y, int method)
{
HighLightStyle b;
uint w, h;
int dx = thd->selstart.x - (thd->selend.x & ~0xF);
int dy = thd->selstart.y - (thd->selend.y & ~0xF);
w = abs(dx) + 16;
h = abs(dy) + 16;
if (TileVirtXY(thd->selstart.x, thd->selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
if (method == VPM_RAILDIRS) {
b = GetAutorailHT(x, y);
} else { // rect for autosignals on one tile
b = HT_RECT;
}
} else if (h == 16) { // Is this in X direction?
if (dx == 16) { // 2x1 special handling
b = (Check2x1AutoRail(3)) | HT_LINE;
} else if (dx == -16) {
b = (Check2x1AutoRail(2)) | HT_LINE;
} else {
b = HT_LINE | HT_DIR_X;
}
y = thd->selstart.y;
} else if (w == 16) { // Or Y direction?
if (dy == 16) { // 2x1 special handling
b = (Check2x1AutoRail(1)) | HT_LINE;
} else if (dy == -16) { // 2x1 other direction
b = (Check2x1AutoRail(0)) | HT_LINE;
} else {
b = HT_LINE | HT_DIR_Y;
}
x = thd->selstart.x;
} else if (w > h * 2) { // still count as x dir?
b = HT_LINE | HT_DIR_X;
y = thd->selstart.y;
} else if (h > w * 2) { // still count as y dir?
b = HT_LINE | HT_DIR_Y;
x = thd->selstart.x;
} else { // complicated direction
int d = w - h;
thd->selend.x = thd->selend.x & ~0xF;
thd->selend.y = thd->selend.y & ~0xF;
/* four cases. */
if (x > thd->selstart.x) {
if (y > thd->selstart.y) {
/* south */
if (d == 0) {
b = (x & 0xF) > (y & 0xF) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
} else if (d >= 0) {
x = thd->selstart.x + h;
b = HT_LINE | HT_DIR_VL;
// return px == py || px == py + 16;
} else {
y = thd->selstart.y + w;
b = HT_LINE | HT_DIR_VR;
} // return px == py || px == py - 16;
} else {
/* west */
if (d == 0) {
b = (x & 0xF) + (y & 0xF) >= 0x10 ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
} else if (d >= 0) {
x = thd->selstart.x + h;
b = HT_LINE | HT_DIR_HL;
} else {
y = thd->selstart.y - w;
b = HT_LINE | HT_DIR_HU;
}
}
} else {
if (y > thd->selstart.y) {
/* east */
if (d == 0) {
b = (x & 0xF) + (y & 0xF) >= 0x10 ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
} else if (d >= 0) {
x = thd->selstart.x - h;
b = HT_LINE | HT_DIR_HU;
// return px == -py || px == -py - 16;
} else {
y = thd->selstart.y + w;
b = HT_LINE | HT_DIR_HL;
} // return px == -py || px == -py + 16;
} else {
/* north */
if (d == 0) {
b = (x & 0xF) > (y & 0xF) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
} else if (d >= 0) {
x = thd->selstart.x - h;
b = HT_LINE | HT_DIR_VR;
// return px == py || px == py - 16;
} else {
y = thd->selstart.y - w;
b = HT_LINE | HT_DIR_VL;
} // return px == py || px == py + 16;
}
}
}
if (_settings_client.gui.measure_tooltip) {
TileIndex t0 = TileVirtXY(thd->selstart.x, thd->selstart.y);
TileIndex t1 = TileVirtXY(x, y);
uint distance = DistanceManhattan(t0, t1) + 1;
byte index = 0;
uint64 params[2];
if (distance != 1) {
int heightdiff = CalcHeightdiff(b, distance, t0, t1);
/* If we are showing a tooltip for horizontal or vertical drags,
* 2 tiles have a length of 1. To bias towards the ceiling we add
* one before division. It feels more natural to count 3 lengths as 2 */
if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
distance = (distance + 1) / 2;
}
params[index++] = distance;
if (heightdiff != 0) params[index++] = heightdiff;
}
ShowMeasurementTooltips(measure_strings_length[index], index, params);
}
thd->selend.x = x;
thd->selend.y = y;
thd->next_drawstyle = b;
}
/**
* Selects tiles while dragging
* @param x X coordinate of end of selection
* @param y Y coordinate of end of selection
* @param method modifies the way tiles are selected. Possible
* methods are VPM_* in viewport.h */
void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
{
int sx, sy;
HighLightStyle style;
if (x == -1) {
_thd.selend.x = -1;
return;
}
/* Special handling of drag in any (8-way) direction */
if (method == VPM_RAILDIRS || method == VPM_SIGNALDIRS) {
_thd.selend.x = x;
_thd.selend.y = y;
CalcRaildirsDrawstyle(&_thd, x, y, method);
return;
}
/* Needed so level-land is placed correctly */
if (_thd.next_drawstyle == HT_POINT) {
x += TILE_SIZE / 2;
y += TILE_SIZE / 2;
}
sx = _thd.selstart.x;
sy = _thd.selstart.y;
switch (method) {
case VPM_X_OR_Y: // drag in X or Y direction
if (abs(sy - y) < abs(sx - x)) {
y = sy;
style = HT_DIR_X;
} else {
x = sx;
style = HT_DIR_Y;
}
goto calc_heightdiff_single_direction;
case VPM_FIX_X: // drag in Y direction
x = sx;
style = HT_DIR_Y;
goto calc_heightdiff_single_direction;
case VPM_FIX_Y: // drag in X direction
y = sy;
style = HT_DIR_X;
calc_heightdiff_single_direction:;
if (_settings_client.gui.measure_tooltip) {
TileIndex t0 = TileVirtXY(sx, sy);
TileIndex t1 = TileVirtXY(x, y);
uint distance = DistanceManhattan(t0, t1) + 1;
byte index = 0;
uint64 params[2];
if (distance != 1) {
/* With current code passing a HT_LINE style to calculate the height
* difference is enough. However if/when a point-tool is created
* with this method, function should be called with new_style (below)
* instead of HT_LINE | style case HT_POINT is handled specially
* new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
params[index++] = distance;
if (heightdiff != 0) params[index++] = heightdiff;
}
ShowMeasurementTooltips(measure_strings_length[index], index, params);
} break;
case VPM_X_AND_Y_LIMITED: { // drag an X by Y constrained rect area
int limit = (_thd.sizelimit - 1) * TILE_SIZE;
x = sx + Clamp(x - sx, -limit, limit);
y = sy + Clamp(y - sy, -limit, limit);
} // Fallthrough
case VPM_X_AND_Y: { // drag an X by Y area
if (_settings_client.gui.measure_tooltip) {
static const StringID measure_strings_area[] = {
STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
};
TileIndex t0 = TileVirtXY(sx, sy);
TileIndex t1 = TileVirtXY(x, y);
uint dx = Delta(TileX(t0), TileX(t1)) + 1;
uint dy = Delta(TileY(t0), TileY(t1)) + 1;
byte index = 0;
uint64 params[3];
/* If dragging an area (eg dynamite tool) and it is actually a single
* row/column, change the type to 'line' to get proper calculation for height */
style = (HighLightStyle)_thd.next_drawstyle;
if (style & HT_RECT) {
if (dx == 1) {
style = HT_LINE | HT_DIR_Y;
} else if (dy == 1) {
style = HT_LINE | HT_DIR_X;
}
}
if (dx != 1 || dy != 1) {
int heightdiff = CalcHeightdiff(style, 0, t0, t1);
params[index++] = dx;
params[index++] = dy;
if (heightdiff != 0) params[index++] = heightdiff;
}
ShowMeasurementTooltips(measure_strings_area[index], index, params);
}
break;
}
default: NOT_REACHED();
}
_thd.selend.x = x;
_thd.selend.y = y;
}
/**
* Handle the mouse while dragging for placement/resizing.
* @return Boolean whether search for a handler should continue
*/
bool VpHandlePlaceSizingDrag()
{
if (_special_mouse_mode != WSM_SIZING) return true;
/* stop drag mode if the window has been closed */
Window *w = FindWindowById(_thd.window_class, _thd.window_number);
if (w == NULL) {
ResetObjectToPlace();
return false;
}
/* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
if (_left_button_down) {
w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
return false;
}
/* mouse button released..
* keep the selected tool, but reset it to the original mode. */
_special_mouse_mode = WSM_NONE;
if (_thd.next_drawstyle == HT_RECT) {
_thd.place_mode = VHM_RECT;
} else if (_thd.select_method == VPM_SIGNALDIRS) { // some might call this a hack... -- Dominik
_thd.place_mode = VHM_RECT;
} else if (_thd.next_drawstyle & HT_LINE) {
_thd.place_mode = VHM_RAIL;
} else if (_thd.next_drawstyle & HT_RAIL) {
_thd.place_mode = VHM_RAIL;
} else {
_thd.place_mode = VHM_POINT;
}
SetTileSelectSize(1, 1);
w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
return false;
}
void SetObjectToPlaceWnd(CursorID icon, SpriteID pal, ViewportHighlightMode mode, Window *w)
{
SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
}
#include "table/animcursors.h"
void SetObjectToPlace(CursorID icon, SpriteID pal, ViewportHighlightMode mode, WindowClass window_class, WindowNumber window_num)
{
/* undo clicking on button and drag & drop */
if (_thd.place_mode != VHM_NONE || _special_mouse_mode == WSM_DRAGDROP) {
Window *w = FindWindowById(_thd.window_class, _thd.window_number);
if (w != NULL) {
/* Call the abort function, but set the window class to something
* that will never be used to avoid infinite loops. Setting it to
* the 'next' window class must not be done because recursion into
* this function might in some cases reset the newly set object to
* place or not properly reset the original selection. */
_thd.window_class = WC_INVALID;
w->OnPlaceObjectAbort();
}
}
SetTileSelectSize(1, 1);
_thd.make_square_red = false;
if (mode == VHM_DRAG) { // VHM_DRAG is for dragdropping trains in the depot window
mode = VHM_NONE;
_special_mouse_mode = WSM_DRAGDROP;
} else {
_special_mouse_mode = WSM_NONE;
}
_thd.place_mode = mode;
_thd.window_class = window_class;
_thd.window_number = window_num;
if (mode == VHM_SPECIAL) // special tools, like tunnels or docks start with presizing mode
VpStartPreSizing();
if ((int)icon < 0) {
SetAnimatedMouseCursor(_animcursors[~icon]);
} else {
SetMouseCursor(icon, pal);
}
}
void ResetObjectToPlace()
{
SetObjectToPlace(SPR_CURSOR_MOUSE, PAL_NONE, VHM_NONE, WC_MAIN_WINDOW, 0);
}
| 85,457
|
C++
|
.cpp
| 2,340
| 33.414957
| 224
| 0.64975
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,019
|
company_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/company_cmd.cpp
|
/* $Id$ */
/** @file company_cmd.cpp Handling of companies. */
#include "stdafx.h"
#include "openttd.h"
#include "engine_base.h"
#include "company_func.h"
#include "company_gui.h"
#include "town.h"
#include "news_func.h"
#include "command_func.h"
#include "network/network.h"
#include "network/network_func.h"
#include "network/network_base.h"
#include "ai/ai.hpp"
#include "company_manager_face.h"
#include "group.h"
#include "window_func.h"
#include "tile_map.h"
#include "strings_func.h"
#include "gfx_func.h"
#include "date_func.h"
#include "sound_func.h"
#include "autoreplace_func.h"
#include "autoreplace_gui.h"
#include "string_func.h"
#include "road_func.h"
#include "rail.h"
#include "sprite.h"
#include "oldpool_func.h"
#include "table/strings.h"
CompanyByte _local_company;
CompanyByte _current_company;
/* NOSAVE: can be determined from company structs */
Colours _company_colours[MAX_COMPANIES];
CompanyManagerFace _company_manager_face; ///< for company manager face storage in openttd.cfg
uint _next_competitor_start; ///< the number of ticks before the next AI is started
uint _cur_company_tick_index; ///< used to generate a name for one company that doesn't have a name yet per tick
DEFINE_OLD_POOL_GENERIC(Company, Company)
Company::Company(uint16 name_1, bool is_ai) :
name_1(name_1),
location_of_HQ(INVALID_TILE),
is_ai(is_ai)
{
for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
}
Company::~Company()
{
free(this->name);
free(this->president_name);
free(this->num_engines);
if (CleaningPool()) return;
DeleteCompanyWindows(this->index);
this->name_1 = 0;
}
/**
* Sets the local company and updates the settings that are set on a
* per-company basis to reflect the core's state in the GUI.
* @param new_company the new company
* @pre IsValidCompanyID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
*/
void SetLocalCompany(CompanyID new_company)
{
/* company could also be COMPANY_SPECTATOR or OWNER_NONE */
assert(IsValidCompanyID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
_local_company = new_company;
/* Do not update the settings if we are in the intro GUI */
if (IsValidCompanyID(new_company) && _game_mode != GM_MENU) {
const Company *c = GetCompany(new_company);
_settings_client.gui.autorenew = c->engine_renew;
_settings_client.gui.autorenew_months = c->engine_renew_months;
_settings_client.gui.autorenew_money = c->engine_renew_money;
InvalidateWindow(WC_GAME_OPTIONS, 0);
}
/* Delete any construction windows... */
DeleteConstructionWindows();
/* ... and redraw the whole screen. */
MarkWholeScreenDirty();
}
bool IsHumanCompany(CompanyID company)
{
return !GetCompany(company)->is_ai;
}
uint16 GetDrawStringCompanyColour(CompanyID company)
{
/* Get the colour for DrawString-subroutines which matches the colour
* of the company */
if (!IsValidCompanyID(company)) return _colour_gradient[COLOUR_WHITE][4] | IS_PALETTE_COLOUR;
return (_colour_gradient[_company_colours[company]][4]) | IS_PALETTE_COLOUR;
}
void DrawCompanyIcon(CompanyID c, int x, int y)
{
DrawSprite(SPR_PLAYER_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
}
/**
* Checks whether a company manager's face is a valid encoding.
* Unused bits are not enforced to be 0.
* @param cmf the fact to check
* @return true if and only if the face is valid
*/
bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
{
if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0;
bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
switch (cmfv) {
case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
case CMFV_LIPS: // FALL THROUGH
case CMFV_NOSE: if (has_moustache) continue; break;
case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
case CMFV_GLASSES: if (!has_glasses) continue; break;
default: break;
}
if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
}
return true;
}
void InvalidateCompanyWindows(const Company *company)
{
CompanyID cid = company->index;
if (cid == _local_company) InvalidateWindow(WC_STATUS_BAR, 0);
InvalidateWindow(WC_FINANCES, cid);
}
bool CheckCompanyHasMoney(CommandCost cost)
{
if (cost.GetCost() > 0) {
CompanyID company = _current_company;
if (IsValidCompanyID(company) && cost.GetCost() > GetCompany(company)->money) {
SetDParam(0, cost.GetCost());
_error_message = STR_0003_NOT_ENOUGH_CASH_REQUIRES;
return false;
}
}
return true;
}
static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
{
if (cost.GetCost() == 0) return;
assert(cost.GetExpensesType() != INVALID_EXPENSES);
c->money -= cost.GetCost();
c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
if (HasBit(1 << EXPENSES_TRAIN_INC |
1 << EXPENSES_ROADVEH_INC |
1 << EXPENSES_AIRCRAFT_INC |
1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
c->cur_economy.income -= cost.GetCost();
} else if (HasBit(1 << EXPENSES_TRAIN_RUN |
1 << EXPENSES_ROADVEH_RUN |
1 << EXPENSES_AIRCRAFT_RUN |
1 << EXPENSES_SHIP_RUN |
1 << EXPENSES_PROPERTY |
1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
c->cur_economy.expenses -= cost.GetCost();
}
InvalidateCompanyWindows(c);
}
void SubtractMoneyFromCompany(CommandCost cost)
{
CompanyID cid = _current_company;
if (IsValidCompanyID(cid)) SubtractMoneyFromAnyCompany(GetCompany(cid), cost);
}
void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
{
Company *c = GetCompany(company);
byte m = c->money_fraction;
Money cost = cst.GetCost();
c->money_fraction = m - (byte)cost;
cost >>= 8;
if (c->money_fraction > m) cost++;
if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
}
void GetNameOfOwner(Owner owner, TileIndex tile)
{
SetDParam(2, owner);
if (owner != OWNER_TOWN) {
if (!IsValidCompanyID(owner)) {
SetDParam(0, STR_0150_SOMEONE);
} else {
SetDParam(0, STR_COMPANY_NAME);
SetDParam(1, owner);
}
} else {
const Town *t = ClosestTownFromTile(tile, UINT_MAX);
SetDParam(0, STR_TOWN);
SetDParam(1, t->index);
}
}
bool CheckOwnership(Owner owner)
{
assert(owner < OWNER_END);
if (owner == _current_company) return true;
_error_message = STR_013B_OWNED_BY;
GetNameOfOwner(owner, 0);
return false;
}
bool CheckTileOwnership(TileIndex tile)
{
Owner owner = GetTileOwner(tile);
assert(owner < OWNER_END);
if (owner == _current_company) return true;
_error_message = STR_013B_OWNED_BY;
/* no need to get the name of the owner unless we're the local company (saves some time) */
if (IsLocalCompany()) GetNameOfOwner(owner, tile);
return false;
}
static void GenerateCompanyName(Company *c)
{
TileIndex tile;
Town *t;
StringID str;
Company *cc;
uint32 strp;
char buffer[100];
if (c->name_1 != STR_SV_UNNAMED) return;
tile = c->last_build_coordinate;
if (tile == 0) return;
t = ClosestTownFromTile(tile, UINT_MAX);
if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_PLAYERNAME_START;
strp = t->townnameparts;
verify_name:;
/* No companies must have this name already */
FOR_ALL_COMPANIES(cc) {
if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
}
GetString(buffer, str, lastof(buffer));
if (strlen(buffer) >= MAX_LENGTH_COMPANY_NAME_BYTES) goto bad_town_name;
set_name:;
c->name_1 = str;
c->name_2 = strp;
MarkWholeScreenDirty();
if (!IsHumanCompany(c->index)) {
CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
cni->FillData(c);
SetDParam(0, STR_705E_NEW_TRANSPORT_COMPANY_LAUNCHED);
SetDParam(1, STR_705F_STARTS_CONSTRUCTION_NEAR);
SetDParamStr(2, cni->company_name);
SetDParam(3, t->index);
AddNewsItem(STR_02B6, NS_COMPANY_NEW, c->last_build_coordinate, 0, cni);
}
AI::BroadcastNewEvent(new AIEventCompanyNew(c->index), c->index);
return;
}
bad_town_name:;
if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
str = SPECSTR_ANDCO_NAME;
strp = c->president_name_2;
goto set_name;
} else {
str = SPECSTR_ANDCO_NAME;
strp = Random();
goto verify_name;
}
}
static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
static const Colours _similar_colour[COLOUR_END][2] = {
{ COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
{ COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
{ INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
{ COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
{ INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
{ COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
{ COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
{ COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
{ COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
{ COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
{ COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
{ COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
{ COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
{ COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
{ COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
{ COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
};
static Colours GenerateCompanyColour()
{
Colours colours[COLOUR_END];
/* Initialize array */
for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
/* And randomize it */
for (uint i = 0; i < 100; i++) {
uint r = Random();
Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
}
/* Bubble sort it according to the values in table 1 */
for (uint i = 0; i < COLOUR_END; i++) {
for (uint j = 1; j < COLOUR_END; j++) {
if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
Swap(colours[j - 1], colours[j]);
}
}
};
/* Move the colours that look similar to each company's colour to the side */
Company *c;
FOR_ALL_COMPANIES(c) {
Colours pcolour = (Colours)c->colour;
for (uint i = 0; i < COLOUR_END; i++) {
if (colours[i] == pcolour) {
colours[i] = INVALID_COLOUR;
break;
}
}
for (uint j = 0; j < 2; j++) {
Colours similar = _similar_colour[pcolour][j];
if (similar == INVALID_COLOUR) break;
for (uint i = 1; i < COLOUR_END; i++) {
if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
}
}
}
/* Return the first available colour */
for (uint i = 0; i < COLOUR_END; i++) {
if (colours[i] != INVALID_COLOUR) return colours[i];
}
NOT_REACHED();
}
static void GeneratePresidentName(Company *c)
{
for (;;) {
restart:;
c->president_name_2 = Random();
c->president_name_1 = SPECSTR_PRESIDENT_NAME;
char buffer[MAX_LENGTH_PRESIDENT_NAME_BYTES + 1];
SetDParam(0, c->index);
GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
if (strlen(buffer) >= MAX_LENGTH_PRESIDENT_NAME_BYTES) continue;
Company *cc;
FOR_ALL_COMPANIES(cc) {
if (c != cc) {
char buffer2[MAX_LENGTH_PRESIDENT_NAME_BYTES + 2];
SetDParam(0, cc->index);
GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
if (strcmp(buffer2, buffer) == 0) goto restart;
}
}
return;
}
}
void ResetCompanyLivery(Company *c)
{
for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
c->livery[scheme].in_use = false;
c->livery[scheme].colour1 = c->colour;
c->livery[scheme].colour2 = c->colour;
}
}
/**
* Create a new company and sets all company variables default values
*
* @param is_ai is a ai company?
* @return the company struct
*/
Company *DoStartupNewCompany(bool is_ai)
{
if (ActiveCompanyCount() == MAX_COMPANIES || !Company::CanAllocateItem()) return NULL;
/* we have to generate colour before this company is valid */
Colours colour = GenerateCompanyColour();
Company *c = new Company(STR_SV_UNNAMED, is_ai);
c->colour = colour;
ResetCompanyLivery(c);
_company_colours[c->index] = (Colours)c->colour;
c->money = c->current_loan = 100000;
c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
c->avail_railtypes = GetCompanyRailtypes(c->index);
c->avail_roadtypes = GetCompanyRoadtypes(c->index);
c->inaugurated_year = _cur_year;
RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false); // create a random company manager face
/* Engine renewal settings */
c->engine_renew_list = NULL;
c->renew_keep_length = false;
c->engine_renew = _settings_client.gui.autorenew;
c->engine_renew_months = _settings_client.gui.autorenew_months;
c->engine_renew_money = _settings_client.gui.autorenew_money;
GeneratePresidentName(c);
InvalidateWindow(WC_GRAPH_LEGEND, 0);
InvalidateWindow(WC_TOOLBAR_MENU, 0);
InvalidateWindow(WC_CLIENT_LIST, 0);
if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
c->num_engines = CallocT<uint16>(GetEnginePoolSize());
return c;
}
void StartupCompanies()
{
_next_competitor_start = 0;
}
static void MaybeStartNewCompany()
{
#ifdef ENABLE_NETWORK
if (_networking && ActiveCompanyCount() >= _settings_client.network.max_companies) return;
#endif /* ENABLE_NETWORK */
Company *c;
/* count number of competitors */
uint n = 0;
FOR_ALL_COMPANIES(c) {
if (c->is_ai) n++;
}
if (n < (uint)_settings_game.difficulty.max_no_competitors) {
/* Send a command to all clients to start up a new AI.
* Works fine for Multiplayer and Singleplayer */
DoCommandP(0, 1, 0, CMD_COMPANY_CTRL);
}
}
void InitializeCompanies()
{
_Company_pool.CleanPool();
_Company_pool.AddBlockToPool();
_cur_company_tick_index = 0;
}
void OnTick_Companies()
{
if (_game_mode == GM_EDITOR) return;
if (IsValidCompanyID((CompanyID)_cur_company_tick_index)) {
Company *c = GetCompany((CompanyID)_cur_company_tick_index);
if (c->name_1 != 0) GenerateCompanyName(c);
}
if (_next_competitor_start == 0) {
_next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
}
if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
MaybeStartNewCompany();
}
_cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
}
void CompaniesYearlyLoop()
{
Company *c;
/* Copy statistics */
FOR_ALL_COMPANIES(c) {
memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
InvalidateWindow(WC_FINANCES, c->index);
}
if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
ShowCompanyFinances(_local_company);
c = GetCompany(_local_company);
if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
SndPlayFx(SND_01_BAD_YEAR);
} else {
SndPlayFx(SND_00_GOOD_YEAR);
}
}
}
/** Change engine renewal parameters
* @param tile unused
* @param flags operation to perform
* @param p1 bits 0-3 command
* - p1 = 0 - change auto renew bool
* - p1 = 1 - change auto renew months
* - p1 = 2 - change auto renew money
* - p1 = 3 - change auto renew array
* - p1 = 4 - change bool, months & money all together
* - p1 = 5 - change renew_keep_length
* @param p2 value to set
* if p1 = 0, then:
* - p2 = enable engine renewal
* if p1 = 1, then:
* - p2 = months left before engine expires to replace it
* if p1 = 2, then
* - p2 = minimum amount of money available
* if p1 = 3, then:
* - p1 bits 16-31 = engine group
* - p2 bits 0-15 = old engine type
* - p2 bits 16-31 = new engine type
* if p1 = 4, then:
* - p1 bit 15 = enable engine renewal
* - p1 bits 16-31 = months left before engine expires to replace it
* - p2 bits 0-31 = minimum amount of money available
* if p1 = 5, then
* - p2 = enable renew_keep_length
*/
CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidCompanyID(_current_company)) return CMD_ERROR;
Company *c = GetCompany(_current_company);
switch (GB(p1, 0, 3)) {
case 0:
if (c->engine_renew == HasBit(p2, 0)) return CMD_ERROR;
if (flags & DC_EXEC) {
c->engine_renew = HasBit(p2, 0);
if (IsLocalCompany()) {
_settings_client.gui.autorenew = c->engine_renew;
InvalidateWindow(WC_GAME_OPTIONS, 0);
}
}
break;
case 1:
if (Clamp((int16)p2, -12, 12) != (int16)p2) return CMD_ERROR;
if (c->engine_renew_months == (int16)p2) return CMD_ERROR;
if (flags & DC_EXEC) {
c->engine_renew_months = (int16)p2;
if (IsLocalCompany()) {
_settings_client.gui.autorenew_months = c->engine_renew_months;
InvalidateWindow(WC_GAME_OPTIONS, 0);
}
}
break;
case 2:
if (ClampU(p2, 0, 2000000) != p2) return CMD_ERROR;
if (c->engine_renew_money == p2) return CMD_ERROR;
if (flags & DC_EXEC) {
c->engine_renew_money = p2;
if (IsLocalCompany()) {
_settings_client.gui.autorenew_money = c->engine_renew_money;
InvalidateWindow(WC_GAME_OPTIONS, 0);
}
}
break;
case 3: {
EngineID old_engine_type = GB(p2, 0, 16);
EngineID new_engine_type = GB(p2, 16, 16);
GroupID id_g = GB(p1, 16, 16);
CommandCost cost;
if (!IsValidGroupID(id_g) && !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
if (new_engine_type != INVALID_ENGINE) {
if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, flags);
} else {
cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
}
if (IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
return cost;
}
case 4:
if (Clamp((int16)GB(p1, 16, 16), -12, 12) != (int16)GB(p1, 16, 16)) return CMD_ERROR;
if (ClampU(p2, 0, 2000000) != p2) return CMD_ERROR;
if (flags & DC_EXEC) {
c->engine_renew = HasBit(p1, 15);
c->engine_renew_months = (int16)GB(p1, 16, 16);
c->engine_renew_money = p2;
if (IsLocalCompany()) {
_settings_client.gui.autorenew = c->engine_renew;
_settings_client.gui.autorenew_months = c->engine_renew_months;
_settings_client.gui.autorenew_money = c->engine_renew_money;
InvalidateWindow(WC_GAME_OPTIONS, 0);
}
}
break;
case 5:
if (c->renew_keep_length == HasBit(p2, 0)) return CMD_ERROR;
if (flags & DC_EXEC) {
c->renew_keep_length = HasBit(p2, 0);
if (IsLocalCompany()) {
InvalidateWindow(WC_REPLACE_VEHICLE, VEH_TRAIN);
}
}
break;
}
return CommandCost();
}
/**
* Fill the CompanyNewsInformation struct with the required data.
* @param p the current company.
* @param other the other company.
*/
void CompanyNewsInformation::FillData(const Company *c, const Company *other)
{
SetDParam(0, c->index);
GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
if (other == NULL) {
*this->other_company_name = '\0';
} else {
SetDParam(0, other->index);
GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
c = other;
}
SetDParam(0, c->index);
GetString(this->president_name, STR_7058_PRESIDENT, lastof(this->president_name));
this->colour = c->colour;
this->face = c->face;
}
/** Control the companies: add, delete, etc.
* @param tile unused
* @param flags operation to perform
* @param p1 various functionality
* - p1 = 0 - create a new company, Which company (network) it will be is in p2
* - p1 = 1 - create a new AI company
* - p1 = 2 - delete a company. Company is identified by p2
* - p1 = 3 - merge two companies together. merge #1 with #2. Identified by p2
* @param p2 various functionality, dictated by p1
* - p1 = 0 - ClientID of the newly created client
* - p1 = 2 - CompanyID of the that is getting deleted
* - p1 = 3 - #1 p2 = (bit 0-15) - company to merge (p2 & 0xFFFF)
* - #2 p2 = (bit 16-31) - company to be merged into ((p2>>16)&0xFFFF)
* @todo In the case of p1=0, create new company, the clientID of the new client is in parameter
* p2. This parameter is passed in at function DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND)
* on the server itself. First of all this is unbelievably ugly; second of all, well,
* it IS ugly! <b>Someone fix this up :)</b> So where to fix?@n
* @arg - network_server.c:838 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND)@n
* @arg - network_client.c:536 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_MAP) from where the map has been received
*/
CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (flags & DC_EXEC) _current_company = OWNER_NONE;
InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
switch (p1) {
case 0: { // Create a new company
/* This command is only executed in a multiplayer game */
if (!_networking) return CMD_ERROR;
#ifdef ENABLE_NETWORK
/* Joining Client:
* _local_company: COMPANY_SPECTATOR
* _network_playas/cid = requested company/clientid
*
* Other client(s)/server:
* _local_company/_network_playas: what they play as
* cid = requested company/company of joining client */
ClientID cid = (ClientID)p2;
/* Has the network client a correct ClientIndex? */
if (!(flags & DC_EXEC)) return CommandCost();
NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(cid);
if (ci == NULL) return CommandCost();
/* Delete multiplayer progress bar */
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
Company *c = DoStartupNewCompany(false);
/* A new company could not be created, revert to being a spectator */
if (c == NULL) {
if (_network_server) {
ci->client_playas = COMPANY_SPECTATOR;
NetworkUpdateClientInfo(ci->client_id);
} else if (_local_company == COMPANY_SPECTATOR) {
_network_playas = COMPANY_SPECTATOR;
}
break;
}
/* This is the client (or non-dedicated server) who wants a new company */
if (cid == _network_own_client_id) {
assert(_local_company == COMPANY_SPECTATOR);
SetLocalCompany(c->index);
if (!StrEmpty(_settings_client.network.default_company_pass)) {
char *password = _settings_client.network.default_company_pass;
NetworkChangeCompanyPassword(1, &password);
}
_current_company = _local_company;
/* Now that we have a new company, broadcast our autorenew settings to
* all clients so everything is in sync */
NetworkSend_Command(0,
(_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4,
_settings_client.gui.autorenew_money,
CMD_SET_AUTOREPLACE,
NULL,
NULL
);
MarkWholeScreenDirty();
}
if (_network_server) {
/* XXX - UGLY! p2 (pid) is mis-used to fetch the client-id, done at
* server side in network_server.c:838, function
* DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND) */
CompanyID old_playas = ci->client_playas;
ci->client_playas = c->index;
NetworkUpdateClientInfo(ci->client_id);
if (IsValidCompanyID(ci->client_playas)) {
CompanyID company_backup = _local_company;
_network_company_states[c->index].months_empty = 0;
_network_company_states[c->index].password[0] = '\0';
NetworkServerUpdateCompanyPassworded(ci->client_playas, false);
/* XXX - When a client joins, we automatically set its name to the
* client's name (for some reason). As it stands now only the server
* knows the client's name, so it needs to send out a "broadcast" to
* do this. To achieve this we send a network command. However, it
* uses _local_company to execute the command as. To prevent abuse
* (eg. only yourself can change your name/company), we 'cheat' by
* impersonation _local_company as the server. Not the best solution;
* but it works.
* TODO: Perhaps this could be improved by when the client is ready
* with joining to let it send itself the command, and not the server?
* For example in network_client.c:534? */
_local_company = ci->client_playas;
NetworkSend_Command(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name);
_local_company = company_backup;
}
/* Announce new company on network, if the client was a SPECTATOR before */
if (old_playas == COMPANY_SPECTATOR) {
NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, ci->client_playas + 1);
}
}
#endif /* ENABLE_NETWORK */
} break;
case 1: // Make a new AI company
if (!(flags & DC_EXEC)) return CommandCost();
DoStartupNewCompany(true);
break;
case 2: { // Delete a company
Company *c;
if (!IsValidCompanyID((CompanyID)p2)) return CMD_ERROR;
if (!(flags & DC_EXEC)) return CommandCost();
c = GetCompany((CompanyID)p2);
/* Delete any open window of the company */
DeleteCompanyWindows(c->index);
CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
cni->FillData(c);
/* Show the bankrupt news */
SetDParam(0, STR_705C_BANKRUPT);
SetDParam(1, STR_705D_HAS_BEEN_CLOSED_DOWN_BY);
SetDParamStr(2, cni->company_name);
AddNewsItem(STR_02B6, NS_COMPANY_BANKRUPT, 0, 0, cni);
/* Remove the company */
ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
if (!IsHumanCompany(c->index)) AI::Stop(c->index);
CompanyID c_index = c->index;
delete c;
AI::BroadcastNewEvent(new AIEventCompanyBankrupt(c_index));
} break;
case 3: { // Merge a company (#1) into another company (#2), elimination company #1
CompanyID cid_old = (CompanyID)GB(p2, 0, 16);
CompanyID cid_new = (CompanyID)GB(p2, 16, 16);
if (!IsValidCompanyID(cid_old) || !IsValidCompanyID(cid_new)) return CMD_ERROR;
if (!(flags & DC_EXEC)) return CMD_ERROR;
ChangeOwnershipOfCompanyItems(cid_old, cid_new);
delete GetCompany(cid_old);
} break;
default: return CMD_ERROR;
}
return CommandCost();
}
| 26,670
|
C++
|
.cpp
| 717
| 34.06834
| 124
| 0.691589
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,020
|
screenshot.cpp
|
EnergeticBark_OpenTTD-3DS/src/screenshot.cpp
|
/* $Id$ */
/** @file screenshot.cpp The creation of screenshots! */
#include "stdafx.h"
#include "openttd.h"
#include "fileio_func.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "screenshot.h"
#include "variables.h"
#include "blitter/factory.hpp"
#include "zoom_func.h"
#include "core/alloc_func.hpp"
#include "core/endian_func.hpp"
#include "map_func.h"
#include "saveload/saveload.h"
#include "company_func.h"
char _screenshot_format_name[8];
uint _num_screenshot_formats;
uint _cur_screenshot_format;
char _screenshot_name[128];
ScreenshotType current_screenshot_type;
/* called by the ScreenShot proc to generate screenshot lines. */
typedef void ScreenshotCallback(void *userdata, void *buf, uint y, uint pitch, uint n);
typedef bool ScreenshotHandlerProc(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette);
struct ScreenshotFormat {
const char *name;
const char *extension;
ScreenshotHandlerProc *proc;
};
/*************************************************
**** SCREENSHOT CODE FOR WINDOWS BITMAP (.BMP)
*************************************************/
#if defined(_MSC_VER) || defined(__WATCOMC__)
#pragma pack(push, 1)
#endif
struct BitmapFileHeader {
uint16 type;
uint32 size;
uint32 reserved;
uint32 off_bits;
} GCC_PACK;
assert_compile(sizeof(BitmapFileHeader) == 14);
#if defined(_MSC_VER) || defined(__WATCOMC__)
#pragma pack(pop)
#endif
struct BitmapInfoHeader {
uint32 size;
int32 width, height;
uint16 planes, bitcount;
uint32 compression, sizeimage, xpels, ypels, clrused, clrimp;
};
assert_compile(sizeof(BitmapInfoHeader) == 40);
struct RgbQuad {
byte blue, green, red, reserved;
};
assert_compile(sizeof(RgbQuad) == 4);
/* generic .BMP writer */
static bool MakeBmpImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
{
BitmapFileHeader bfh;
BitmapInfoHeader bih;
RgbQuad rq[256];
FILE *f;
uint i, padw;
uint n, maxlines;
uint pal_size = 0;
uint bpp = pixelformat / 8;
/* only implemented for 8bit and 32bit images so far. */
if (pixelformat != 8 && pixelformat != 32) return false;
f = fopen(name, "wb");
if (f == NULL) return false;
/* each scanline must be aligned on a 32bit boundary */
padw = Align(w, 4);
if (pixelformat == 8) pal_size = sizeof(RgbQuad) * 256;
/* setup the file header */
bfh.type = TO_LE16('MB');
bfh.size = TO_LE32(sizeof(bfh) + sizeof(bih) + pal_size + padw * h * bpp);
bfh.reserved = 0;
bfh.off_bits = TO_LE32(sizeof(bfh) + sizeof(bih) + pal_size);
/* setup the info header */
bih.size = TO_LE32(sizeof(BitmapInfoHeader));
bih.width = TO_LE32(w);
bih.height = TO_LE32(h);
bih.planes = TO_LE16(1);
bih.bitcount = TO_LE16(pixelformat);
bih.compression = 0;
bih.sizeimage = 0;
bih.xpels = 0;
bih.ypels = 0;
bih.clrused = 0;
bih.clrimp = 0;
if (pixelformat == 8) {
/* convert the palette to the windows format */
for (i = 0; i != 256; i++) {
rq[i].red = palette[i].r;
rq[i].green = palette[i].g;
rq[i].blue = palette[i].b;
rq[i].reserved = 0;
}
}
/* write file header and info header and palette */
if (fwrite(&bfh, sizeof(bfh), 1, f) != 1) return false;
if (fwrite(&bih, sizeof(bih), 1, f) != 1) return false;
if (pixelformat == 8) if (fwrite(rq, sizeof(rq), 1, f) != 1) return false;
/* use by default 64k temp memory */
maxlines = Clamp(65536 / padw, 16, 128);
/* now generate the bitmap bits */
uint8 *buff = CallocT<uint8>(padw * maxlines * bpp); // by default generate 128 lines at a time.
/* start at the bottom, since bitmaps are stored bottom up. */
do {
/* determine # lines */
n = min(h, maxlines);
h -= n;
/* render the pixels */
callb(userdata, buff, h, padw, n);
/* write each line */
while (n)
if (fwrite(buff + (--n) * padw * bpp, padw * bpp, 1, f) != 1) {
free(buff);
fclose(f);
return false;
}
} while (h != 0);
free(buff);
fclose(f);
return true;
}
/*********************************************************
**** SCREENSHOT CODE FOR PORTABLE NETWORK GRAPHICS (.PNG)
*********************************************************/
#if defined(WITH_PNG)
#include <png.h>
static void PNGAPI png_my_error(png_structp png_ptr, png_const_charp message)
{
DEBUG(misc, 0, "[libpng] error: %s - %s", message, (char *)png_get_error_ptr(png_ptr));
longjmp(png_ptr->jmpbuf, 1);
}
static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
{
DEBUG(misc, 1, "[libpng] warning: %s - %s", message, (char *)png_get_error_ptr(png_ptr));
}
static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
{
png_color rq[256];
FILE *f;
uint i, y, n;
uint maxlines;
uint bpp = pixelformat / 8;
png_structp png_ptr;
png_infop info_ptr;
/* only implemented for 8bit and 32bit images so far. */
if (pixelformat != 8 && pixelformat != 32) return false;
f = fopen(name, "wb");
if (f == NULL) return false;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (char *)name, png_my_error, png_my_warning);
if (png_ptr == NULL) {
fclose(f);
return false;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
fclose(f);
return false;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(f);
return false;
}
png_init_io(png_ptr, f);
png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
png_set_IHDR(png_ptr, info_ptr, w, h, 8, pixelformat == 8 ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (pixelformat == 8) {
/* convert the palette to the .PNG format. */
for (i = 0; i != 256; i++) {
rq[i].red = palette[i].r;
rq[i].green = palette[i].g;
rq[i].blue = palette[i].b;
}
png_set_PLTE(png_ptr, info_ptr, rq, 256);
}
png_write_info(png_ptr, info_ptr);
png_set_flush(png_ptr, 512);
if (pixelformat == 32) {
png_color_8 sig_bit;
/* Save exact colour/alpha resolution */
sig_bit.alpha = 0;
sig_bit.blue = 8;
sig_bit.green = 8;
sig_bit.red = 8;
sig_bit.gray = 8;
png_set_sBIT(png_ptr, info_ptr, &sig_bit);
#if TTD_ENDIAN == TTD_LITTLE_ENDIAN
png_set_bgr(png_ptr);
png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
#else
png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
#endif /* TTD_ENDIAN == TTD_LITTLE_ENDIAN */
}
/* use by default 64k temp memory */
maxlines = Clamp(65536 / w, 16, 128);
/* now generate the bitmap bits */
void *buff = CallocT<uint8>(w * maxlines * bpp); // by default generate 128 lines at a time.
y = 0;
do {
/* determine # lines to write */
n = min(h - y, maxlines);
/* render the pixels into the buffer */
callb(userdata, buff, y, w, n);
y += n;
/* write them to png */
for (i = 0; i != n; i++)
png_write_row(png_ptr, (png_bytep)buff + i * w * bpp);
} while (y != h);
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
free(buff);
fclose(f);
return true;
}
#endif /* WITH_PNG */
/*************************************************
**** SCREENSHOT CODE FOR ZSOFT PAINTBRUSH (.PCX)
*************************************************/
struct PcxHeader {
byte manufacturer;
byte version;
byte rle;
byte bpp;
uint32 unused;
uint16 xmax, ymax;
uint16 hdpi, vdpi;
byte pal_small[16 * 3];
byte reserved;
byte planes;
uint16 pitch;
uint16 cpal;
uint16 width;
uint16 height;
byte filler[54];
};
assert_compile(sizeof(PcxHeader) == 128);
static bool MakePCXImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
{
FILE *f;
uint maxlines;
uint y;
PcxHeader pcx;
bool success;
if (pixelformat == 32) {
DEBUG(misc, 0, "Can't convert a 32bpp screenshot to PCX format. Please pick an other format.");
return false;
}
if (pixelformat != 8 || w == 0)
return false;
f = fopen(name, "wb");
if (f == NULL) return false;
memset(&pcx, 0, sizeof(pcx));
/* setup pcx header */
pcx.manufacturer = 10;
pcx.version = 5;
pcx.rle = 1;
pcx.bpp = 8;
pcx.xmax = TO_LE16(w - 1);
pcx.ymax = TO_LE16(h - 1);
pcx.hdpi = TO_LE16(320);
pcx.vdpi = TO_LE16(320);
pcx.planes = 1;
pcx.cpal = TO_LE16(1);
pcx.width = pcx.pitch = TO_LE16(w);
pcx.height = TO_LE16(h);
/* write pcx header */
if (fwrite(&pcx, sizeof(pcx), 1, f) != 1) {
fclose(f);
return false;
}
/* use by default 64k temp memory */
maxlines = Clamp(65536 / w, 16, 128);
/* now generate the bitmap bits */
uint8 *buff = CallocT<uint8>(w * maxlines); // by default generate 128 lines at a time.
y = 0;
do {
/* determine # lines to write */
uint n = min(h - y, maxlines);
uint i;
/* render the pixels into the buffer */
callb(userdata, buff, y, w, n);
y += n;
/* write them to pcx */
for (i = 0; i != n; i++) {
const uint8 *bufp = buff + i * w;
byte runchar = bufp[0];
uint runcount = 1;
uint j;
/* for each pixel... */
for (j = 1; j < w; j++) {
uint8 ch = bufp[j];
if (ch != runchar || runcount >= 0x3f) {
if (runcount > 1 || (runchar & 0xC0) == 0xC0)
if (fputc(0xC0 | runcount, f) == EOF) {
free(buff);
fclose(f);
return false;
}
if (fputc(runchar, f) == EOF) {
free(buff);
fclose(f);
return false;
}
runcount = 0;
runchar = ch;
}
runcount++;
}
/* write remaining bytes.. */
if (runcount > 1 || (runchar & 0xC0) == 0xC0)
if (fputc(0xC0 | runcount, f) == EOF) {
free(buff);
fclose(f);
return false;
}
if (fputc(runchar, f) == EOF) {
free(buff);
fclose(f);
return false;
}
}
} while (y != h);
free(buff);
/* write 8-bit colour palette */
if (fputc(12, f) == EOF) {
fclose(f);
return false;
}
/* Palette is word-aligned, copy it to a temporary byte array */
byte tmp[256 * 3];
for (uint i = 0; i < 256; i++) {
tmp[i * 3 + 0] = palette[i].r;
tmp[i * 3 + 1] = palette[i].g;
tmp[i * 3 + 2] = palette[i].b;
}
success = fwrite(tmp, sizeof(tmp), 1, f) == 1;
fclose(f);
return success;
}
/*************************************************
**** GENERIC SCREENSHOT CODE
*************************************************/
static const ScreenshotFormat _screenshot_formats[] = {
#if defined(WITH_PNG)
{"PNG", "png", &MakePNGImage},
#endif
{"BMP", "bmp", &MakeBmpImage},
{"PCX", "pcx", &MakePCXImage},
};
void InitializeScreenshotFormats()
{
int i, j;
for (i = 0, j = 0; i != lengthof(_screenshot_formats); i++)
if (!strcmp(_screenshot_format_name, _screenshot_formats[i].extension)) {
j = i;
break;
}
_cur_screenshot_format = j;
_num_screenshot_formats = lengthof(_screenshot_formats);
current_screenshot_type = SC_NONE;
}
const char *GetScreenshotFormatDesc(int i)
{
return _screenshot_formats[i].name;
}
void SetScreenshotFormat(int i)
{
_cur_screenshot_format = i;
strcpy(_screenshot_format_name, _screenshot_formats[i].extension);
}
/* screenshot generator that dumps the current video buffer */
static void CurrentScreenCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
{
Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
void *src = blitter->MoveTo(_screen.dst_ptr, 0, y);
blitter->CopyImageToBuffer(src, buf, _screen.width, n, pitch);
}
/** generate a large piece of the world
* @param userdata Viewport area to draw
* @param buf Videobuffer with same bitdepth as current blitter
* @param y First line to render
* @param pitch Pitch of the videobuffer
* @param n Number of lines to render
*/
static void LargeWorldCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
{
ViewPort *vp = (ViewPort *)userdata;
DrawPixelInfo dpi, *old_dpi;
int wx, left;
/* We are no longer rendering to the screen */
DrawPixelInfo old_screen = _screen;
bool old_disable_anim = _screen_disable_anim;
_screen.dst_ptr = buf;
_screen.width = pitch;
_screen.height = n;
_screen.pitch = pitch;
_screen_disable_anim = true;
old_dpi = _cur_dpi;
_cur_dpi = &dpi;
dpi.dst_ptr = buf;
dpi.height = n;
dpi.width = vp->width;
dpi.pitch = pitch;
dpi.zoom = ZOOM_LVL_WORLD_SCREENSHOT;
dpi.left = 0;
dpi.top = y;
/* Render viewport in blocks of 1600 pixels width */
left = 0;
while (vp->width - left != 0) {
wx = min(vp->width - left, 1600);
left += wx;
ViewportDoDraw(vp,
ScaleByZoom(left - wx - vp->left, vp->zoom) + vp->virtual_left,
ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top,
ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
ScaleByZoom((y + n) - vp->top, vp->zoom) + vp->virtual_top
);
}
_cur_dpi = old_dpi;
/* Switch back to rendering to the screen */
_screen = old_screen;
_screen_disable_anim = old_disable_anim;
}
static char *MakeScreenshotName(const char *ext)
{
static char filename[MAX_PATH];
int serial;
size_t len;
if (_game_mode == GM_EDITOR || _game_mode == GM_MENU || _local_company == COMPANY_SPECTATOR) {
strecpy(_screenshot_name, "screenshot", lastof(_screenshot_name));
} else {
GenerateDefaultSaveName(_screenshot_name, lastof(_screenshot_name));
}
/* Add extension to screenshot file */
len = strlen(_screenshot_name);
snprintf(&_screenshot_name[len], lengthof(_screenshot_name) - len, ".%s", ext);
for (serial = 1;; serial++) {
snprintf(filename, lengthof(filename), "%s%s", _personal_dir, _screenshot_name);
if (!FileExists(filename)) break;
/* If file exists try another one with same name, but just with a higher index */
snprintf(&_screenshot_name[len], lengthof(_screenshot_name) - len, "#%d.%s", serial, ext);
}
return filename;
}
void SetScreenshotType(ScreenshotType t)
{
current_screenshot_type = t;
}
bool IsScreenshotRequested()
{
return (current_screenshot_type != SC_NONE);
}
static bool MakeSmallScreenshot()
{
const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
return sf->proc(MakeScreenshotName(sf->extension), CurrentScreenCallback, NULL, _screen.width, _screen.height, BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth(), _cur_palette);
}
static bool MakeWorldScreenshot()
{
ViewPort vp;
const ScreenshotFormat *sf;
vp.zoom = ZOOM_LVL_WORLD_SCREENSHOT;
vp.left = 0;
vp.top = 0;
vp.virtual_left = -(int)MapMaxX() * TILE_PIXELS;
vp.virtual_top = 0;
vp.virtual_width = (MapMaxX() + MapMaxY()) * TILE_PIXELS;
vp.width = vp.virtual_width;
vp.virtual_height = (MapMaxX() + MapMaxY()) * TILE_PIXELS >> 1;
vp.height = vp.virtual_height;
sf = _screenshot_formats + _cur_screenshot_format;
return sf->proc(MakeScreenshotName(sf->extension), LargeWorldCallback, &vp, vp.width, vp.height, BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth(), _cur_palette);
}
bool MakeScreenshot()
{
switch (current_screenshot_type) {
case SC_VIEWPORT:
UndrawMouseCursor();
DrawDirtyBlocks();
current_screenshot_type = SC_NONE;
return MakeSmallScreenshot();
case SC_WORLD:
current_screenshot_type = SC_NONE;
return MakeWorldScreenshot();
default: return false;
}
}
| 15,165
|
C++
|
.cpp
| 495
| 28.137374
| 185
| 0.658657
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,022
|
vehicle_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/vehicle_cmd.cpp
|
/* $Id$ */
/** @file vehicle_cmd.cpp Commands for vehicles. */
#include "stdafx.h"
#include "roadveh.h"
#include "gfx_func.h"
#include "news_func.h"
#include "command_func.h"
#include "company_func.h"
#include "vehicle_gui.h"
#include "train.h"
#include "newgrf_engine.h"
#include "newgrf_text.h"
#include "functions.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "string_func.h"
#include "depot_map.h"
#include "vehiclelist.h"
#include "table/strings.h"
/* Tables used in vehicle.h to find the right command for a certain vehicle type */
const uint32 _veh_build_proc_table[] = {
CMD_BUILD_RAIL_VEHICLE,
CMD_BUILD_ROAD_VEH,
CMD_BUILD_SHIP,
CMD_BUILD_AIRCRAFT,
};
const uint32 _veh_sell_proc_table[] = {
CMD_SELL_RAIL_WAGON,
CMD_SELL_ROAD_VEH,
CMD_SELL_SHIP,
CMD_SELL_AIRCRAFT,
};
const uint32 _veh_refit_proc_table[] = {
CMD_REFIT_RAIL_VEHICLE,
CMD_REFIT_ROAD_VEH,
CMD_REFIT_SHIP,
CMD_REFIT_AIRCRAFT,
};
const uint32 _send_to_depot_proc_table[] = {
CMD_SEND_TRAIN_TO_DEPOT,
CMD_SEND_ROADVEH_TO_DEPOT,
CMD_SEND_SHIP_TO_DEPOT,
CMD_SEND_AIRCRAFT_TO_HANGAR,
};
/** Start/Stop a vehicle
* @param tile unused
* @param flags type of operation
* @param p1 vehicle to start/stop
* @param p2 bit 0: Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety)
* @return result of operation. Nothing if everything went well
*/
CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
/* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (!CheckOwnership(v->owner)) return CMD_ERROR;
if (!v->IsPrimaryVehicle()) return CMD_ERROR;
switch (v->type) {
case VEH_TRAIN:
if (v->vehstatus & VS_STOPPED && v->u.rail.cached_power == 0) return_cmd_error(STR_TRAIN_START_NO_CATENARY);
break;
case VEH_SHIP:
case VEH_ROAD:
break;
case VEH_AIRCRAFT:
/* cannot stop airplane when in flight, or when taking off / landing */
if (v->u.air.state >= STARTTAKEOFF && v->u.air.state < TERM7) return_cmd_error(STR_A017_AIRCRAFT_IS_IN_FLIGHT);
break;
default: return CMD_ERROR;
}
/* Check if this vehicle can be started/stopped. The callback will fail or
* return 0xFF if it can. */
uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
if (callback != CALLBACK_FAILED && GB(callback, 0, 8) != 0xFF && HasBit(p2, 0)) {
StringID error = GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + callback);
return_cmd_error(error);
}
if (flags & DC_EXEC) {
static const StringID vehicle_waiting_in_depot[] = {
STR_8814_TRAIN_IS_WAITING_IN_DEPOT,
STR_9016_ROAD_VEHICLE_IS_WAITING,
STR_981C_SHIP_IS_WAITING_IN_DEPOT,
STR_A014_AIRCRAFT_IS_WAITING_IN,
};
static const WindowClass vehicle_list[] = {
WC_TRAINS_LIST,
WC_ROADVEH_LIST,
WC_SHIPS_LIST,
WC_AIRCRAFT_LIST,
};
if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, vehicle_waiting_in_depot[v->type]);
v->vehstatus ^= VS_STOPPED;
if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClasses(vehicle_list[v->type]);
}
return CommandCost();
}
/** Starts or stops a lot of vehicles
* @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
* @param flags type of operation
* @param p1 Station/Order/Depot ID (only used for vehicle list windows)
* @param p2 bitmask
* - bit 0-4 Vehicle type
* - bit 5 false = start vehicles, true = stop vehicles
* - bit 6 if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
* - bit 8-11 Vehicle List Window type (ignored unless bit 1 is set)
*/
CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
VehicleList list;
CommandCost return_value = CMD_ERROR;
VehicleType vehicle_type = (VehicleType)GB(p2, 0, 5);
bool start_stop = HasBit(p2, 5);
bool vehicle_list_window = HasBit(p2, 6);
if (vehicle_list_window) {
uint32 id = p1;
uint16 window_type = p2 & VLW_MASK;
GenerateVehicleSortList(&list, vehicle_type, _current_company, id, window_type);
} else {
/* Get the list of vehicles in the depot */
BuildDepotVehicleList(vehicle_type, tile, &list, NULL);
}
for (uint i = 0; i < list.Length(); i++) {
const Vehicle *v = list[i];
if (!!(v->vehstatus & VS_STOPPED) != start_stop) continue;
if (!vehicle_list_window) {
if (vehicle_type == VEH_TRAIN) {
if (CheckTrainInDepot(v, false) == -1) continue;
} else {
if (!(v->vehstatus & VS_HIDDEN)) continue;
}
}
CommandCost ret = DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
if (CmdSucceeded(ret)) {
return_value = CommandCost();
/* We know that the command is valid for at least one vehicle.
* If we haven't set DC_EXEC, then there is no point in continueing because it will be valid */
if (!(flags & DC_EXEC)) break;
}
}
return return_value;
}
/** Sells all vehicles in a depot
* @param tile Tile of the depot where the depot is
* @param flags type of operation
* @param p1 Vehicle type
* @param p2 unused
*/
CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
VehicleList list;
CommandCost cost(EXPENSES_NEW_VEHICLES);
uint sell_command;
VehicleType vehicle_type = (VehicleType)GB(p1, 0, 8);
switch (vehicle_type) {
case VEH_TRAIN: sell_command = CMD_SELL_RAIL_WAGON; break;
case VEH_ROAD: sell_command = CMD_SELL_ROAD_VEH; break;
case VEH_SHIP: sell_command = CMD_SELL_SHIP; break;
case VEH_AIRCRAFT: sell_command = CMD_SELL_AIRCRAFT; break;
default: return CMD_ERROR;
}
/* Get the list of vehicles in the depot */
BuildDepotVehicleList(vehicle_type, tile, &list, &list);
for (uint i = 0; i < list.Length(); i++) {
CommandCost ret = DoCommand(tile, list[i]->index, 1, flags, sell_command);
if (CmdSucceeded(ret)) cost.AddCost(ret);
}
if (cost.GetCost() == 0) return CMD_ERROR; // no vehicles to sell
return cost;
}
/** Autoreplace all vehicles in the depot
* Note: this command can make incorrect cost estimations
* Luckily the final price can only drop, not increase. This is due to the fact that
* estimation can't predict wagon removal so it presumes worst case which is no income from selling wagons.
* @param tile Tile of the depot where the vehicles are
* @param flags type of operation
* @param p1 Type of vehicle
* @param p2 If bit 0 is set, then either replace all or nothing (instead of replacing until money runs out)
*/
CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
VehicleList list;
CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
VehicleType vehicle_type = (VehicleType)GB(p1, 0, 8);
bool all_or_nothing = HasBit(p2, 0);
if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
/* Get the list of vehicles in the depot */
BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
bool did_something = false;
for (uint i = 0; i < list.Length(); i++) {
Vehicle *v = (Vehicle*)list[i];
/* Ensure that the vehicle completely in the depot */
if (!v->IsInDepot()) continue;
CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
if (CmdSucceeded(ret)) {
did_something = true;
cost.AddCost(ret);
} else {
if (ret.GetErrorMessage() != STR_AUTOREPLACE_NOTHING_TO_DO && all_or_nothing) {
/* We failed to replace a vehicle even though we set all or nothing.
* We should never reach this if DC_EXEC is set since then it should
* have failed the estimation guess. */
assert(!(flags & DC_EXEC));
/* Now we will have to return an error. */
return CMD_ERROR;
}
}
}
if (!did_something) {
/* Either we didn't replace anything or something went wrong.
* Either way we want to return an error and not execute this command. */
cost = CMD_ERROR;
}
return cost;
}
/** Test if a name is unique among vehicle names.
* @param name Name to test.
* @return True ifffffff the name is unique.
*/
static bool IsUniqueVehicleName(const char *name)
{
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->name != NULL && strcmp(v->name, name) == 0) return false;
}
return true;
}
/** Clone the custom name of a vehicle, adding or incrementing a number.
* @param src Source vehicle, with a custom name.
* @param dst Destination vehicle.
*/
static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
{
char buf[256];
/* Find the position of the first digit in the last group of digits. */
size_t number_position;
for (number_position = strlen(src->name); number_position > 0; number_position--) {
/* The design of UTF-8 lets this work simply without having to check
* for UTF-8 sequences. */
if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
}
/* Format buffer and determine starting number. */
int num;
if (number_position == strlen(src->name)) {
/* No digit at the end, so start at number 2. */
strecpy(buf, src->name, lastof(buf));
strecat(buf, " ", lastof(buf));
number_position = strlen(buf);
num = 2;
} else {
/* Found digits, parse them and start at the next number. */
strecpy(buf, src->name, lastof(buf));
buf[number_position] = '\0';
num = strtol(&src->name[number_position], NULL, 10) + 1;
}
/* Check if this name is already taken. */
for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
/* Attach the number to the temporary name. */
seprintf(&buf[number_position], lastof(buf), "%d", num);
/* Check the name is unique. */
if (IsUniqueVehicleName(buf)) {
dst->name = strdup(buf);
break;
}
}
/* All done. If we didn't find a name, it'll just use its default. */
}
/** Clone a vehicle. If it is a train, it will clone all the cars too
* @param tile tile of the depot where the cloned vehicle is build
* @param flags type of operation
* @param p1 the original vehicle's index
* @param p2 1 = shared orders, else copied orders
*/
CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CommandCost total_cost(EXPENSES_NEW_VEHICLES);
uint32 build_argument = 2;
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
Vehicle *v_front = v;
Vehicle *w = NULL;
Vehicle *w_front = NULL;
Vehicle *w_rear = NULL;
/*
* v_front is the front engine in the original vehicle
* v is the car/vehicle of the original vehicle, that is currently being copied
* w_front is the front engine of the cloned vehicle
* w is the car/vehicle currently being cloned
* w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
*/
if (!CheckOwnership(v->owner)) return CMD_ERROR;
if (v->type == VEH_TRAIN && (!IsFrontEngine(v) || v->u.rail.crash_anim_pos >= 4400)) return CMD_ERROR;
/* check that we can allocate enough vehicles */
if (!(flags & DC_EXEC)) {
int veh_counter = 0;
do {
veh_counter++;
} while ((v = v->Next()) != NULL);
if (!Vehicle::AllocateList(NULL, veh_counter)) {
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
}
}
v = v_front;
do {
if (v->type == VEH_TRAIN && IsRearDualheaded(v)) {
/* we build the rear ends of multiheaded trains with the front ones */
continue;
}
CommandCost cost = DoCommand(tile, v->engine_type, build_argument, flags, GetCmdBuildVeh(v));
build_argument = 3; // ensure that we only assign a number to the first engine
if (CmdFailed(cost)) return cost;
total_cost.AddCost(cost);
if (flags & DC_EXEC) {
w = GetVehicle(_new_vehicle_id);
if (v->type == VEH_TRAIN && HasBit(v->u.rail.flags, VRF_REVERSE_DIRECTION)) {
SetBit(w->u.rail.flags, VRF_REVERSE_DIRECTION);
}
if (v->type == VEH_TRAIN && !IsFrontEngine(v)) {
/* this s a train car
* add this unit to the end of the train */
CommandCost result = DoCommand(0, (w_rear->index << 16) | w->index, 1, flags, CMD_MOVE_RAIL_VEHICLE);
if (CmdFailed(result)) {
/* The train can't be joined to make the same consist as the original.
* Sell what we already made (clean up) and return an error. */
DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
DoCommand(w_front->tile, w->index, 1, flags, GetCmdSellVeh(w));
return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
}
} else {
/* this is a front engine or not a train. */
w_front = w;
w->service_interval = v->service_interval;
}
w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
}
} while (v->type == VEH_TRAIN && (v = GetNextVehicle(v)) != NULL);
if (flags & DC_EXEC && v_front->type == VEH_TRAIN) {
/* for trains this needs to be the front engine due to the callback function */
_new_vehicle_id = w_front->index;
}
if (flags & DC_EXEC) {
/* Cloned vehicles belong to the same group */
DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
}
/* Take care of refitting. */
w = w_front;
v = v_front;
/* Both building and refitting are influenced by newgrf callbacks, which
* makes it impossible to accurately estimate the cloning costs. In
* particular, it is possible for engines of the same type to be built with
* different numbers of articulated parts, so when refitting we have to
* loop over real vehicles first, and then the articulated parts of those
* vehicles in a different loop. */
do {
do {
if (flags & DC_EXEC) {
assert(w != NULL);
if (w->cargo_type != v->cargo_type || w->cargo_subtype != v->cargo_subtype) {
CommandCost cost = DoCommand(0, w->index, v->cargo_type | (v->cargo_subtype << 8) | 1U << 16 , flags, GetCmdRefitVeh(v));
if (CmdSucceeded(cost)) total_cost.AddCost(cost);
}
if (w->type == VEH_TRAIN && EngineHasArticPart(w)) {
w = GetNextArticPart(w);
} else if (w->type == VEH_ROAD && RoadVehHasArticPart(w)) {
w = w->Next();
} else {
break;
}
} else {
const Engine *e = GetEngine(v->engine_type);
CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
total_cost.AddCost(GetRefitCost(v->engine_type));
}
}
if (v->type == VEH_TRAIN && EngineHasArticPart(v)) {
v = GetNextArticPart(v);
} else if (v->type == VEH_ROAD && RoadVehHasArticPart(v)) {
v = v->Next();
} else {
break;
}
} while (v != NULL);
if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = GetNextVehicle(w);
} while (v->type == VEH_TRAIN && (v = GetNextVehicle(v)) != NULL);
if (flags & DC_EXEC) {
/*
* Set the orders of the vehicle. Cannot do it earlier as we need
* the vehicle refitted before doing this, otherwise the moved
* cargo types might not match (passenger vs non-passenger)
*/
DoCommand(0, (v_front->index << 16) | w_front->index, p2 & 1 ? CO_SHARE : CO_COPY, flags, CMD_CLONE_ORDER);
/* Now clone the vehicle's name, if it has one. */
if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
}
/* Since we can't estimate the cost of cloning a vehicle accurately we must
* check whether the company has enough money manually. */
if (!CheckCompanyHasMoney(total_cost)) {
if (flags & DC_EXEC) {
/* The vehicle has already been bought, so now it must be sold again. */
DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
}
return CMD_ERROR;
}
return total_cost;
}
/**
* Send all vehicles of type to depots
* @param type type of vehicle
* @param flags the flags used for DoCommand()
* @param service should the vehicles only get service in the depots
* @param owner owner of the vehicles to send
* @param vlw_flag tells what kind of list requested the goto depot
* @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
*/
CommandCost SendAllVehiclesToDepot(VehicleType type, DoCommandFlag flags, bool service, Owner owner, uint16 vlw_flag, uint32 id)
{
VehicleList list;
GenerateVehicleSortList(&list, type, owner, id, vlw_flag);
/* Send all the vehicles to a depot */
for (uint i = 0; i < list.Length(); i++) {
const Vehicle *v = list[i];
CommandCost ret = DoCommand(v->tile, v->index, (service ? 1 : 0) | DEPOT_DONT_CANCEL, flags, GetCmdSendToDepot(type));
/* Return 0 if DC_EXEC is not set this is a valid goto depot command)
* In this case we know that at least one vehicle can be sent to a depot
* and we will issue the command. We can now safely quit the loop, knowing
* it will succeed at least once. With DC_EXEC we really need to send them to the depot */
if (CmdSucceeded(ret) && !(flags & DC_EXEC)) {
return CommandCost();
}
}
return (flags & DC_EXEC) ? CommandCost() : CMD_ERROR;
}
/** Give a custom name to your vehicle
* @param tile unused
* @param flags type of operation
* @param p1 vehicle ID to name
* @param p2 unused
*/
CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (!CheckOwnership(v->owner)) return CMD_ERROR;
bool reset = StrEmpty(text);
if (!reset) {
if (strlen(text) >= MAX_LENGTH_VEHICLE_NAME_BYTES) return CMD_ERROR;
if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
}
if (flags & DC_EXEC) {
free(v->name);
v->name = reset ? NULL : strdup(text);
InvalidateWindowClassesData(WC_TRAINS_LIST, 1);
MarkWholeScreenDirty();
}
return CommandCost();
}
/** Change the service interval of a vehicle
* @param tile unused
* @param flags type of operation
* @param p1 vehicle ID that is being service-interval-changed
* @param p2 new service interval
*/
CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
uint16 serv_int = GetServiceIntervalClamped(p2); // Double check the service interval from the user-input
if (serv_int != p2 || !IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (!CheckOwnership(v->owner)) return CMD_ERROR;
if (flags & DC_EXEC) {
v->service_interval = serv_int;
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
}
return CommandCost();
}
| 18,828
|
C++
|
.cpp
| 479
| 36.463466
| 128
| 0.698488
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,025
|
bridge_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/bridge_gui.cpp
|
/* $Id$ */
/** @file bridge_gui.cpp Graphical user interface for bridge construction */
#include "stdafx.h"
#include "gui.h"
#include "window_gui.h"
#include "command_func.h"
#include "economy_func.h"
#include "bridge.h"
#include "strings_func.h"
#include "window_func.h"
#include "sound_func.h"
#include "map_func.h"
#include "gfx_func.h"
#include "tunnelbridge.h"
#include "sortlist_type.h"
#include "widgets/dropdown_func.h"
#include "table/strings.h"
/** The type of the last built rail bridge */
static BridgeType _last_railbridge_type = 0;
/** The type of the last built road bridge */
static BridgeType _last_roadbridge_type = 0;
/**
* Carriage for the data we need if we want to build a bridge
*/
struct BuildBridgeData {
BridgeType index;
const BridgeSpec *spec;
Money cost;
};
typedef GUIList<BuildBridgeData> GUIBridgeList;
/**
* Callback executed after a build Bridge CMD has been called
*
* @param scucess True if the build succeded
* @param tile The tile where the command has been executed
* @param p1 not used
* @param p2 not used
*/
void CcBuildBridge(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) SndPlayTileFx(SND_27_BLACKSMITH_ANVIL, tile);
}
/* Names of the build bridge selection window */
enum BuildBridgeSelectionWidgets {
BBSW_CLOSEBOX = 0,
BBSW_CAPTION,
BBSW_DROPDOWN_ORDER,
BBSW_DROPDOWN_CRITERIA,
BBSW_BRIDGE_LIST,
BBSW_SCROLLBAR,
BBSW_RESIZEBOX
};
class BuildBridgeWindow : public Window {
private:
/* Runtime saved values */
static uint16 last_size;
static Listing last_sorting;
/* Constants for sorting the bridges */
static const StringID sorter_names[];
static GUIBridgeList::SortFunction * const sorter_funcs[];
/* Internal variables */
TileIndex start_tile;
TileIndex end_tile;
uint32 type;
GUIBridgeList *bridges;
/** Sort the bridges by their index */
static int CDECL BridgeIndexSorter(const BuildBridgeData *a, const BuildBridgeData *b)
{
return a->index - b->index;
}
/** Sort the bridges by their price */
static int CDECL BridgePriceSorter(const BuildBridgeData *a, const BuildBridgeData *b)
{
return a->cost - b->cost;
}
/** Sort the bridges by their maximum speed */
static int CDECL BridgeSpeedSorter(const BuildBridgeData *a, const BuildBridgeData *b)
{
return a->spec->speed - b->spec->speed;
}
void BuildBridge(uint8 i)
{
switch ((TransportType)(this->type >> 15)) {
case TRANSPORT_RAIL: _last_railbridge_type = this->bridges->Get(i)->index; break;
case TRANSPORT_ROAD: _last_roadbridge_type = this->bridges->Get(i)->index; break;
default: break;
}
DoCommandP(this->end_tile, this->start_tile, this->type | this->bridges->Get(i)->index,
CMD_BUILD_BRIDGE | CMD_MSG(STR_5015_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
}
/** Sort the builable bridges */
void SortBridgeList()
{
this->bridges->Sort();
/* Display the current sort variant */
this->widget[BBSW_DROPDOWN_CRITERIA].data = this->sorter_names[this->bridges->SortType()];
/* Set the modified widgets dirty */
this->InvalidateWidget(BBSW_DROPDOWN_CRITERIA);
this->InvalidateWidget(BBSW_BRIDGE_LIST);
}
public:
BuildBridgeWindow(const WindowDesc *desc, TileIndex start, TileIndex end, uint32 br_type, GUIBridgeList *bl) : Window(desc),
start_tile(start),
end_tile(end),
type(br_type),
bridges(bl)
{
this->parent = FindWindowById(WC_BUILD_TOOLBAR, GB(this->type, 15, 2));
this->bridges->SetListing(this->last_sorting);
this->bridges->SetSortFuncs(this->sorter_funcs);
this->bridges->NeedResort();
this->SortBridgeList();
/* Change the data, or the caption of the gui. Set it to road or rail, accordingly */
this->widget[BBSW_CAPTION].data = (GB(this->type, 15, 2) == TRANSPORT_ROAD) ? STR_1803_SELECT_ROAD_BRIDGE : STR_100D_SELECT_RAIL_BRIDGE;
this->resize.step_height = 22;
this->vscroll.count = bl->Length();
if (this->last_size <= 4) {
this->vscroll.cap = 4;
} else {
/* Resize the bridge selection window if we used a bigger one the last time */
this->vscroll.cap = min(this->last_size, this->vscroll.count);
ResizeWindow(this, 0, (this->vscroll.cap - 4) * this->resize.step_height);
}
this->FindWindowPlacementAndResize(desc);
}
~BuildBridgeWindow()
{
this->last_sorting = this->bridges->GetListing();
delete bridges;
}
virtual void OnPaint()
{
this->DrawWidgets();
this->DrawSortButtonState(BBSW_DROPDOWN_ORDER, this->bridges->IsDescSortOrder() ? SBS_DOWN : SBS_UP);
uint y = this->widget[BBSW_BRIDGE_LIST].top + 2;
for (int i = this->vscroll.pos; (i < (this->vscroll.cap + this->vscroll.pos)) && (i < (int)this->bridges->Length()); i++) {
const BridgeSpec *b = this->bridges->Get(i)->spec;
SetDParam(2, this->bridges->Get(i)->cost);
SetDParam(1, b->speed);
SetDParam(0, b->material);
DrawSprite(b->sprite, b->pal, 3, y);
DrawString(44, y, STR_500D, TC_FROMSTRING);
y += this->resize.step_height;
}
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
const uint8 i = keycode - '1';
if (i < 9 && i < this->bridges->Length()) {
/* Build the requested bridge */
this->BuildBridge(i);
delete this;
return ES_HANDLED;
}
return ES_NOT_HANDLED;
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
default: break;
case BBSW_BRIDGE_LIST: {
uint i = ((int)pt.y - this->widget[BBSW_BRIDGE_LIST].top) / this->resize.step_height;
if (i < this->vscroll.cap) {
i += this->vscroll.pos;
if (i < this->bridges->Length()) {
this->BuildBridge(i);
delete this;
}
}
} break;
case BBSW_DROPDOWN_ORDER:
this->bridges->ToggleSortOrder();
this->SetDirty();
break;
case BBSW_DROPDOWN_CRITERIA:
ShowDropDownMenu(this, this->sorter_names, this->bridges->SortType(), BBSW_DROPDOWN_CRITERIA, 0, 0);
break;
}
}
virtual void OnDropdownSelect(int widget, int index)
{
if (widget == BBSW_DROPDOWN_CRITERIA && this->bridges->SortType() != index) {
this->bridges->SetSortType(index);
this->SortBridgeList();
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->widget[BBSW_BRIDGE_LIST].data = (this->vscroll.cap << 8) + 1;
SetVScrollCount(this, this->bridges->Length());
this->last_size = max(this->vscroll.cap, this->last_size);
}
};
/* Set the default size of the Build Bridge Window */
uint16 BuildBridgeWindow::last_size = 4;
/* Set the default sorting for the bridges */
Listing BuildBridgeWindow::last_sorting = {false, 0};
/* Availible bridge sorting functions */
GUIBridgeList::SortFunction * const BuildBridgeWindow::sorter_funcs[] = {
&BridgeIndexSorter,
&BridgePriceSorter,
&BridgeSpeedSorter
};
/* Names of the sorting functions */
const StringID BuildBridgeWindow::sorter_names[] = {
STR_SORT_BY_NUMBER,
STR_ENGINE_SORT_COST,
STR_SORT_BY_MAX_SPEED,
INVALID_STRING_ID
};
/* Widget definition for the rail bridge selection window */
static const Widget _build_bridge_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BBSW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 199, 0, 13, STR_100D_SELECT_RAIL_BRIDGE, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BBSW_CAPTION
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 80, 14, 25, STR_SORT_BY, STR_SORT_ORDER_TIP}, // BBSW_DROPDOWN_ORDER
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_DARK_GREEN, 81, 199, 14, 25, 0x0, STR_SORT_CRITERIA_TIP}, // BBSW_DROPDOWN_CRITERIA
{ WWT_MATRIX, RESIZE_BOTTOM, COLOUR_DARK_GREEN, 0, 187, 26, 113, 0x401, STR_101F_BRIDGE_SELECTION_CLICK}, // BBSW_BRIDGE_LIST
{ WWT_SCROLLBAR, RESIZE_BOTTOM, COLOUR_DARK_GREEN, 188, 199, 26, 101, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // BBSW_SCROLLBAR
{ WWT_RESIZEBOX, RESIZE_TB, COLOUR_DARK_GREEN, 188, 199, 102, 113, 0x0, STR_RESIZE_BUTTON}, // BBSW_RESIZEBOX
{ WIDGETS_END},
};
/* Window definition for the rail bridge selection window */
static const WindowDesc _build_bridge_desc(
WDP_AUTO, WDP_AUTO, 200, 114, 200, 114,
WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE | WDF_CONSTRUCTION,
_build_bridge_widgets
);
/**
* Prepare the data for the build a bridge window.
* If we can't build a bridge under the given conditions
* show an error message.
*
* @parma start The start tile of the bridge
* @param end The end tile of the bridge
* @param transport_type The transport type
* @param road_rail_type The road/rail type
*/
void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type)
{
DeleteWindowById(WC_BUILD_BRIDGE, 0);
/* Data type for the bridge.
* Bit 16,15 = transport type,
* 14..8 = road/rail types,
* 7..0 = type of bridge */
uint32 type = (transport_type << 15) | (road_rail_type << 8);
/* The bridge length without ramps. */
const uint bridge_len = GetTunnelBridgeLength(start, end);
/* If Ctrl is being pressed, check wether the last bridge built is available
* If so, return this bridge type. Otherwise continue normally.
* We store bridge types for each transport type, so we have to check for
* the transport type beforehand.
*/
BridgeType last_bridge_type = 0;
switch (transport_type) {
case TRANSPORT_ROAD: last_bridge_type = _last_roadbridge_type; break;
case TRANSPORT_RAIL: last_bridge_type = _last_railbridge_type; break;
default: break; // water ways and air routes don't have bridge types
}
if (_ctrl_pressed && CheckBridge_Stuff(last_bridge_type, bridge_len)) {
DoCommandP(end, start, type | last_bridge_type, CMD_BUILD_BRIDGE | CMD_MSG(STR_5015_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
return;
}
/* only query bridge building possibility once, result is the same for all bridges!
* returns CMD_ERROR on failure, and price on success */
StringID errmsg = INVALID_STRING_ID;
CommandCost ret = DoCommand(end, start, type, DC_AUTO | DC_QUERY_COST, CMD_BUILD_BRIDGE);
GUIBridgeList *bl = NULL;
if (CmdFailed(ret)) {
errmsg = _error_message;
} else {
/* check which bridges can be built */
const uint tot_bridgedata_len = CalcBridgeLenCostFactor(bridge_len + 2);
bl = new GUIBridgeList();
/* loop for all bridgetypes */
for (BridgeType brd_type = 0; brd_type != MAX_BRIDGES; brd_type++) {
if (CheckBridge_Stuff(brd_type, bridge_len)) {
/* bridge is accepted, add to list */
BuildBridgeData *item = bl->Append();
item->index = brd_type;
item->spec = GetBridgeSpec(brd_type);
/* Add to terraforming & bulldozing costs the cost of the
* bridge itself (not computed with DC_QUERY_COST) */
item->cost = ret.GetCost() + (((int64)tot_bridgedata_len * _price.build_bridge * item->spec->price) >> 8);
}
}
}
if (bl != NULL && bl->Length() != 0) {
new BuildBridgeWindow(&_build_bridge_desc, start, end, type, bl);
} else {
if (bl != NULL) delete bl;
ShowErrorMessage(errmsg, STR_5015_CAN_T_BUILD_BRIDGE_HERE, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);
}
}
| 11,288
|
C++
|
.cpp
| 295
| 35.623729
| 162
| 0.698455
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,028
|
texteff.cpp
|
EnergeticBark_OpenTTD-3DS/src/texteff.cpp
|
/* $Id$ */
/** @file texteff.cpp Handling of text effects. */
#include "stdafx.h"
#include "openttd.h"
#include "strings_type.h"
#include "texteff.hpp"
#include "core/bitmath_func.hpp"
#include "transparency.h"
#include "strings_func.h"
#include "core/alloc_func.hpp"
#include "functions.h"
#include "viewport_func.h"
#include "settings_type.h"
enum {
INIT_NUM_TEXT_EFFECTS = 20,
};
struct TextEffect {
StringID string_id;
int32 x;
int32 y;
int32 right;
int32 bottom;
uint16 duration;
uint64 params_1;
uint64 params_2;
TextEffectMode mode;
};
/* used for text effects */
static TextEffect *_text_effect_list = NULL;
static uint16 _num_text_effects = INIT_NUM_TEXT_EFFECTS;
/* Text Effects */
/**
* Mark the area of the text effect as dirty.
*
* This function marks the area of a text effect as dirty for repaint.
*
* @param te The TextEffect to mark the area dirty
* @ingroup dirty
*/
static void MarkTextEffectAreaDirty(TextEffect *te)
{
/* Width and height of the text effect are doubled, so they are correct in both zoom out levels 1x and 2x. */
MarkAllViewportsDirty(
te->x,
te->y - 1,
(te->right - te->x)*2 + te->x + 1,
(te->bottom - (te->y - 1)) * 2 + (te->y - 1) + 1
);
}
TextEffectID AddTextEffect(StringID msg, int x, int y, uint16 duration, TextEffectMode mode)
{
TextEffect *te;
int w;
char buffer[100];
TextEffectID i;
if (_game_mode == GM_MENU) return INVALID_TE_ID;
/* Look for a free spot in the text effect array */
for (i = 0; i < _num_text_effects; i++) {
if (_text_effect_list[i].string_id == INVALID_STRING_ID) break;
}
/* If there is none found, we grow the array */
if (i == _num_text_effects) {
_num_text_effects += 25;
_text_effect_list = ReallocT<TextEffect>(_text_effect_list, _num_text_effects);
for (; i < _num_text_effects; i++) _text_effect_list[i].string_id = INVALID_STRING_ID;
i = _num_text_effects - 1;
}
te = &_text_effect_list[i];
/* Start defining this object */
te->string_id = msg;
te->duration = duration;
te->y = y - 5;
te->bottom = y + 5;
te->params_1 = GetDParam(0);
te->params_2 = GetDParam(4);
te->mode = mode;
GetString(buffer, msg, lastof(buffer));
w = GetStringBoundingBox(buffer).width;
te->x = x - (w >> 1);
te->right = x + (w >> 1) - 1;
MarkTextEffectAreaDirty(te);
return i;
}
void UpdateTextEffect(TextEffectID te_id, StringID msg)
{
assert(te_id < _num_text_effects);
TextEffect *te;
/* Update details */
te = &_text_effect_list[te_id];
te->string_id = msg;
te->params_1 = GetDParam(0);
te->params_2 = GetDParam(4);
/* Update width of text effect */
char buffer[100];
GetString(buffer, msg, lastof(buffer));
int w = GetStringBoundingBox(buffer).width;
/* Only allow to make it broader, so it completely covers the old text. That avoids remnants of the old text. */
int right_new = te->x + w;
if (te->right < right_new) te->right = right_new;
MarkTextEffectAreaDirty(te);
}
void RemoveTextEffect(TextEffectID te_id)
{
assert(te_id < _num_text_effects);
TextEffect *te;
te = &_text_effect_list[te_id];
MarkTextEffectAreaDirty(te);
te->string_id = INVALID_STRING_ID;
}
static void MoveTextEffect(TextEffect *te)
{
/* Never expire for duration of 0xFFFF */
if (te->duration == 0xFFFF) return;
if (te->duration < 8) {
te->string_id = INVALID_STRING_ID;
} else {
te->duration -= 8;
te->y--;
te->bottom--;
}
MarkTextEffectAreaDirty(te);
}
void MoveAllTextEffects()
{
for (TextEffectID i = 0; i < _num_text_effects; i++) {
TextEffect *te = &_text_effect_list[i];
if (te->string_id != INVALID_STRING_ID && te->mode == TE_RISING) MoveTextEffect(te);
}
}
void InitTextEffects()
{
if (_text_effect_list == NULL) _text_effect_list = MallocT<TextEffect>(_num_text_effects);
for (TextEffectID i = 0; i < _num_text_effects; i++) _text_effect_list[i].string_id = INVALID_STRING_ID;
}
void DrawTextEffects(DrawPixelInfo *dpi)
{
switch (dpi->zoom) {
case ZOOM_LVL_NORMAL:
for (TextEffectID i = 0; i < _num_text_effects; i++) {
TextEffect *te = &_text_effect_list[i];
if (te->string_id != INVALID_STRING_ID &&
dpi->left <= te->right &&
dpi->top <= te->bottom &&
dpi->left + dpi->width > te->x &&
dpi->top + dpi->height > te->y) {
if (te->mode == TE_RISING || (_settings_client.gui.loading_indicators && !IsTransparencySet(TO_LOADING))) {
AddStringToDraw(te->x, te->y, te->string_id, te->params_1, te->params_2);
}
}
}
break;
case ZOOM_LVL_OUT_2X:
for (TextEffectID i = 0; i < _num_text_effects; i++) {
TextEffect *te = &_text_effect_list[i];
if (te->string_id != INVALID_STRING_ID &&
dpi->left <= te->right * 2 - te->x &&
dpi->top <= te->bottom * 2 - te->y &&
dpi->left + dpi->width > te->x &&
dpi->top + dpi->height > te->y) {
if (te->mode == TE_RISING || (_settings_client.gui.loading_indicators && !IsTransparencySet(TO_LOADING))) {
AddStringToDraw(te->x, te->y, (StringID)(te->string_id - 1), te->params_1, te->params_2);
}
}
}
break;
case ZOOM_LVL_OUT_4X:
case ZOOM_LVL_OUT_8X:
break;
default: NOT_REACHED();
}
}
| 5,134
|
C++
|
.cpp
| 171
| 27.426901
| 113
| 0.663491
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,032
|
terraform_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/terraform_cmd.cpp
|
/* $Id$ */
/** @file terraform_cmd.cpp Commands related to terraforming. */
#include "stdafx.h"
#include "openttd.h"
#include "command_func.h"
#include "tunnel_map.h"
#include "bridge_map.h"
#include "variables.h"
#include "functions.h"
#include "economy_func.h"
#include "settings_type.h"
#include "table/strings.h"
/*
* In one terraforming command all four corners of a initial tile can be raised/lowered (though this is not available to the player).
* The maximal amount of height modifications is archieved when raising a complete flat land from sea level to MAX_TILE_HEIGHT or vice versa.
* This affects all corners with a manhatten distance smaller than MAX_TILE_HEIGHT to one of the initial 4 corners.
* Their maximal amount is computed to 4 * \sum_{i=1}^{h_max} i = 2 * h_max * (h_max + 1).
*/
static const int TERRAFORMER_MODHEIGHT_SIZE = 2 * MAX_TILE_HEIGHT * (MAX_TILE_HEIGHT + 1);
/*
* The maximal amount of affected tiles (i.e. the tiles that incident with one of the corners above, is computed similiar to
* 1 + 4 * \sum_{i=1}^{h_max} (i+1) = 1 + 2 * h_max + (h_max + 3).
*/
static const int TERRAFORMER_TILE_TABLE_SIZE = 1 + 2 * MAX_TILE_HEIGHT * (MAX_TILE_HEIGHT + 3);
struct TerraformerHeightMod {
TileIndex tile; ///< Referenced tile.
byte height; ///< New TileHeight (height of north corner) of the tile.
};
struct TerraformerState {
int modheight_count; ///< amount of entries in "modheight".
int tile_table_count; ///< amount of entries in "tile_table".
/**
* Dirty tiles, i.e.\ at least one corner changed.
*
* This array contains the tiles which are or will be marked as dirty.
*
* @ingroup dirty
*/
TileIndex tile_table[TERRAFORMER_TILE_TABLE_SIZE];
TerraformerHeightMod modheight[TERRAFORMER_MODHEIGHT_SIZE]; ///< Height modifications.
};
TileIndex _terraform_err_tile; ///< first tile we couldn't terraform
/**
* Gets the TileHeight (height of north corner) of a tile as of current terraforming progress.
*
* @param ts TerraformerState.
* @param tile Tile.
* @return TileHeight.
*/
static int TerraformGetHeightOfTile(const TerraformerState *ts, TileIndex tile)
{
const TerraformerHeightMod *mod = ts->modheight;
for (int count = ts->modheight_count; count != 0; count--, mod++) {
if (mod->tile == tile) return mod->height;
}
/* TileHeight unchanged so far, read value from map. */
return TileHeight(tile);
}
/**
* Stores the TileHeight (height of north corner) of a tile in a TerraformerState.
*
* @param ts TerraformerState.
* @param tile Tile.
* @param height New TileHeight.
*/
static void TerraformSetHeightOfTile(TerraformerState *ts, TileIndex tile, int height)
{
/* Find tile in the "modheight" table.
* Note: In a normal user-terraform command the tile will not be found in the "modheight" table.
* But during house- or industry-construction multiple corners can be terraformed at once. */
TerraformerHeightMod *mod = ts->modheight;
int count = ts->modheight_count;
while ((count > 0) && (mod->tile != tile)) {
mod++;
count--;
}
/* New entry? */
if (count == 0) {
assert(ts->modheight_count < TERRAFORMER_MODHEIGHT_SIZE);
ts->modheight_count++;
}
/* Finally store the new value */
mod->tile = tile;
mod->height = (byte)height;
}
/**
* Adds a tile to the "tile_table" in a TerraformerState.
*
* @param ts TerraformerState.
* @param tile Tile.
* @ingroup dirty
*/
static void TerraformAddDirtyTile(TerraformerState *ts, TileIndex tile)
{
int count = ts->tile_table_count;
for (TileIndex *t = ts->tile_table; count != 0; count--, t++) {
if (*t == tile) return;
}
assert(ts->tile_table_count < TERRAFORMER_TILE_TABLE_SIZE);
ts->tile_table[ts->tile_table_count++] = tile;
}
/**
* Adds all tiles that incident with the north corner of a specific tile to the "tile_table" in a TerraformerState.
*
* @param ts TerraformerState.
* @param tile Tile.
* @ingroup dirty
*/
static void TerraformAddDirtyTileAround(TerraformerState *ts, TileIndex tile)
{
/* Make sure all tiles passed to TerraformAddDirtyTile are within [0, MapSize()] */
if (TileY(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY( 0, -1));
if (TileY(tile) >= 1 && TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, -1));
if (TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, 0));
TerraformAddDirtyTile(ts, tile);
}
/**
* Terraform the north corner of a tile to a specific height.
*
* @param ts TerraformerState.
* @param tile Tile.
* @param height Aimed height.
* @param return Error code or cost.
*/
static CommandCost TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height)
{
assert(tile < MapSize());
/* Check range of destination height */
if (height < 0) return_cmd_error(STR_1003_ALREADY_AT_SEA_LEVEL);
if (height > MAX_TILE_HEIGHT) return_cmd_error(STR_1004_TOO_HIGH);
/*
* Check if the terraforming has any effect.
* This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
* In this case the terraforming should fail. (Don't know why.)
*/
if (height == TerraformGetHeightOfTile(ts, tile)) return CMD_ERROR;
/* Check "too close to edge of map". Only possible when freeform-edges is off. */
uint x = TileX(tile);
uint y = TileY(tile);
if (!_settings_game.construction.freeform_edges && ((x <= 1) || (y <= 1) || (x >= MapMaxX() - 1) || (y >= MapMaxY() - 1))) {
/*
* Determine a sensible error tile
*/
if (x == 1) x = 0;
if (y == 1) y = 0;
_terraform_err_tile = TileXY(x, y);
return_cmd_error(STR_0002_TOO_CLOSE_TO_EDGE_OF_MAP);
}
/* Mark incident tiles, that are involved in the terraforming */
TerraformAddDirtyTileAround(ts, tile);
/* Store the height modification */
TerraformSetHeightOfTile(ts, tile, height);
CommandCost total_cost(EXPENSES_CONSTRUCTION);
/* Increment cost */
total_cost.AddCost(_price.terraform);
/* Recurse to neighboured corners if height difference is larger than 1 */
{
const TileIndexDiffC *ttm;
TileIndex orig_tile = tile;
static const TileIndexDiffC _terraform_tilepos[] = {
{ 1, 0}, // move to tile in SE
{-2, 0}, // undo last move, and move to tile in NW
{ 1, 1}, // undo last move, and move to tile in SW
{ 0, -2} // undo last move, and move to tile in NE
};
for (ttm = _terraform_tilepos; ttm != endof(_terraform_tilepos); ttm++) {
tile += ToTileIndexDiff(*ttm);
if (tile >= MapSize()) continue;
/* Make sure we don't wrap around the map */
if (Delta(TileX(orig_tile), TileX(tile)) == MapSizeX() - 1) continue;
if (Delta(TileY(orig_tile), TileY(tile)) == MapSizeY() - 1) continue;
/* Get TileHeight of neighboured tile as of current terraform progress */
int r = TerraformGetHeightOfTile(ts, tile);
int height_diff = height - r;
/* Is the height difference to the neighboured corner greater than 1? */
if (abs(height_diff) > 1) {
/* Terraform the neighboured corner. The resulting height difference should be 1. */
height_diff += (height_diff < 0 ? 1 : -1);
CommandCost cost = TerraformTileHeight(ts, tile, r + height_diff);
if (CmdFailed(cost)) return cost;
total_cost.AddCost(cost);
}
}
}
return total_cost;
}
/** Terraform land
* @param tile tile to terraform
* @param flags for this command type
* @param p1 corners to terraform (SLOPE_xxx)
* @param p2 direction; eg up (non-zero) or down (zero)
* @return error or cost of terraforming
*/
CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
_terraform_err_tile = INVALID_TILE;
CommandCost total_cost(EXPENSES_CONSTRUCTION);
int direction = (p2 != 0 ? 1 : -1);
TerraformerState ts;
ts.modheight_count = ts.tile_table_count = 0;
/* Compute the costs and the terraforming result in a model of the landscape */
if ((p1 & SLOPE_W) != 0 && tile + TileDiffXY(1, 0) < MapSize()) {
TileIndex t = tile + TileDiffXY(1, 0);
CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
if (CmdFailed(cost)) return cost;
total_cost.AddCost(cost);
}
if ((p1 & SLOPE_S) != 0 && tile + TileDiffXY(1, 1) < MapSize()) {
TileIndex t = tile + TileDiffXY(1, 1);
CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
if (CmdFailed(cost)) return cost;
total_cost.AddCost(cost);
}
if ((p1 & SLOPE_E) != 0 && tile + TileDiffXY(0, 1) < MapSize()) {
TileIndex t = tile + TileDiffXY(0, 1);
CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
if (CmdFailed(cost)) return cost;
total_cost.AddCost(cost);
}
if ((p1 & SLOPE_N) != 0) {
TileIndex t = tile + TileDiffXY(0, 0);
CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
if (CmdFailed(cost)) return cost;
total_cost.AddCost(cost);
}
/* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface */
{
TileIndex *ti = ts.tile_table;
for (int count = ts.tile_table_count; count != 0; count--, ti++) {
TileIndex tile = *ti;
assert(tile < MapSize());
/* MP_VOID tiles can be terraformed but as tunnels and bridges
* cannot go under / over these tiles they don't need checking. */
if (IsTileType(tile, MP_VOID)) continue;
/* Find new heights of tile corners */
uint z_N = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 0));
uint z_W = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 0));
uint z_S = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 1));
uint z_E = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 1));
/* Find min and max height of tile */
uint z_min = min(min(z_N, z_W), min(z_S, z_E));
uint z_max = max(max(z_N, z_W), max(z_S, z_E));
/* Compute tile slope */
Slope tileh = (z_max > z_min + 1 ? SLOPE_STEEP : SLOPE_FLAT);
if (z_W > z_min) tileh |= SLOPE_W;
if (z_S > z_min) tileh |= SLOPE_S;
if (z_E > z_min) tileh |= SLOPE_E;
if (z_N > z_min) tileh |= SLOPE_N;
/* Check if bridge would take damage */
if (direction == 1 && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) &&
GetBridgeHeight(GetSouthernBridgeEnd(tile)) <= z_max * TILE_HEIGHT) {
_terraform_err_tile = tile; // highlight the tile under the bridge
return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
}
/* Check if tunnel would take damage */
if (direction == -1 && IsTunnelInWay(tile, z_min * TILE_HEIGHT)) {
_terraform_err_tile = tile; // highlight the tile above the tunnel
return_cmd_error(STR_1002_EXCAVATION_WOULD_DAMAGE);
}
/* Check tiletype-specific things, and add extra-cost */
const bool curr_gen = _generating_world;
if (_game_mode == GM_EDITOR) _generating_world = true; // used to create green terraformed land
CommandCost cost = _tile_type_procs[GetTileType(tile)]->terraform_tile_proc(tile, flags | DC_AUTO, z_min * TILE_HEIGHT, tileh);
_generating_world = curr_gen;
if (CmdFailed(cost)) {
_terraform_err_tile = tile;
return cost;
}
total_cost.AddCost(cost);
}
}
if (flags & DC_EXEC) {
/* change the height */
{
int count;
TerraformerHeightMod *mod;
mod = ts.modheight;
for (count = ts.modheight_count; count != 0; count--, mod++) {
TileIndex til = mod->tile;
SetTileHeight(til, mod->height);
}
}
/* finally mark the dirty tiles dirty */
{
int count;
TileIndex *ti = ts.tile_table;
for (count = ts.tile_table_count; count != 0; count--, ti++) {
MarkTileDirtyByTile(*ti);
}
}
}
return total_cost;
}
/** Levels a selected (rectangle) area of land
* @param tile end tile of area-drag
* @param flags for this command type
* @param p1 start tile of area drag
* @param p2 height difference; eg raise (+1), lower (-1) or level (0)
* @return error or cost of terraforming
*/
CommandCost CmdLevelLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (p1 >= MapSize()) return CMD_ERROR;
_terraform_err_tile = INVALID_TILE;
/* remember level height */
uint oldh = TileHeight(p1);
/* compute new height */
uint h = oldh + p2;
/* Check range of destination height */
if (h > MAX_TILE_HEIGHT) return_cmd_error((oldh == 0) ? STR_1003_ALREADY_AT_SEA_LEVEL : STR_1004_TOO_HIGH);
if (p2 == 0) _error_message = STR_ALREADY_LEVELLED;
/* make sure sx,sy are smaller than ex,ey */
int ex = TileX(tile);
int ey = TileY(tile);
int sx = TileX(p1);
int sy = TileY(p1);
if (ex < sx) Swap(ex, sx);
if (ey < sy) Swap(ey, sy);
tile = TileXY(sx, sy);
int size_x = ex - sx + 1;
int size_y = ey - sy + 1;
Money money = GetAvailableMoneyForCommand();
CommandCost cost(EXPENSES_CONSTRUCTION);
BEGIN_TILE_LOOP(tile2, size_x, size_y, tile) {
uint curh = TileHeight(tile2);
while (curh != h) {
CommandCost ret = DoCommand(tile2, SLOPE_N, (curh > h) ? 0 : 1, flags & ~DC_EXEC, CMD_TERRAFORM_LAND);
if (CmdFailed(ret)) break;
if (flags & DC_EXEC) {
money -= ret.GetCost();
if (money < 0) {
_additional_cash_required = ret.GetCost();
return cost;
}
DoCommand(tile2, SLOPE_N, (curh > h) ? 0 : 1, flags, CMD_TERRAFORM_LAND);
}
cost.AddCost(ret);
curh += (curh > h) ? -1 : 1;
}
} END_TILE_LOOP(tile2, size_x, size_y, tile)
return (cost.GetCost() == 0) ? CMD_ERROR : cost;
}
| 13,302
|
C++
|
.cpp
| 342
| 36.099415
| 141
| 0.685798
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,033
|
namegen.cpp
|
EnergeticBark_OpenTTD-3DS/src/namegen.cpp
|
/* $Id$ */
/** @file namegen.cpp Town name generators. */
#include "stdafx.h"
#include "namegen_func.h"
#include "string_func.h"
#include "table/namegen.h"
static inline uint32 SeedChance(int shift_by, int max, uint32 seed)
{
return (GB(seed, shift_by, 16) * max) >> 16;
}
static inline uint32 SeedModChance(int shift_by, int max, uint32 seed)
{
/* This actually gives *MUCH* more even distribution of the values
* than SeedChance(), which is absolutely horrible in that. If
* you do not believe me, try with i.e. the Czech town names,
* compare the words (nicely visible on prefixes) generated by
* SeedChance() and SeedModChance(). Do not get dicouraged by the
* never-use-modulo myths, which hold true only for the linear
* congruential generators (and Random() isn't such a generator).
* --pasky
* TODO: Perhaps we should use it for all the name generators? --pasky */
return (seed >> shift_by) % max;
}
static inline int32 SeedChanceBias(int shift_by, int max, uint32 seed, int bias)
{
return SeedChance(shift_by, max + bias, seed) - bias;
}
static void ReplaceWords(const char *org, const char *rep, char *buf)
{
if (strncmp(buf, org, 4) == 0) strncpy(buf, rep, 4); // Safe as the string in buf is always more than 4 characters long.
}
static byte MakeEnglishOriginalTownName(char *buf, uint32 seed, const char *last)
{
int i;
/* null terminates the string for strcat */
strecpy(buf, "", last);
/* optional first segment */
i = SeedChanceBias(0, lengthof(_name_original_english_1), seed, 50);
if (i >= 0)
strecat(buf, _name_original_english_1[i], last);
/* mandatory middle segments */
strecat(buf, _name_original_english_2[SeedChance(4, lengthof(_name_original_english_2), seed)], last);
strecat(buf, _name_original_english_3[SeedChance(7, lengthof(_name_original_english_3), seed)], last);
strecat(buf, _name_original_english_4[SeedChance(10, lengthof(_name_original_english_4), seed)], last);
strecat(buf, _name_original_english_5[SeedChance(13, lengthof(_name_original_english_5), seed)], last);
/* optional last segment */
i = SeedChanceBias(15, lengthof(_name_original_english_6), seed, 60);
if (i >= 0)
strecat(buf, _name_original_english_6[i], last);
if (buf[0] == 'C' && (buf[1] == 'e' || buf[1] == 'i'))
buf[0] = 'K';
ReplaceWords("Cunt", "East", buf);
ReplaceWords("Slag", "Pits", buf);
ReplaceWords("Slut", "Edin", buf);
//ReplaceWords("Fart", "Boot", buf);
ReplaceWords("Drar", "Quar", buf);
ReplaceWords("Dreh", "Bash", buf);
ReplaceWords("Frar", "Shor", buf);
ReplaceWords("Grar", "Aber", buf);
ReplaceWords("Brar", "Over", buf);
ReplaceWords("Wrar", "Inve", buf);
return 0;
}
static byte MakeEnglishAdditionalTownName(char *buf, uint32 seed, const char *last)
{
int i;
/* null terminates the string for strcat */
strecpy(buf, "", last);
/* optional first segment */
i = SeedChanceBias(0, lengthof(_name_additional_english_prefix), seed, 50);
if (i >= 0)
strecat(buf, _name_additional_english_prefix[i], last);
if (SeedChance(3, 20, seed) >= 14) {
strecat(buf, _name_additional_english_1a[SeedChance(6, lengthof(_name_additional_english_1a), seed)], last);
} else {
strecat(buf, _name_additional_english_1b1[SeedChance(6, lengthof(_name_additional_english_1b1), seed)], last);
strecat(buf, _name_additional_english_1b2[SeedChance(9, lengthof(_name_additional_english_1b2), seed)], last);
if (SeedChance(11, 20, seed) >= 4) {
strecat(buf, _name_additional_english_1b3a[SeedChance(12, lengthof(_name_additional_english_1b3a), seed)], last);
} else {
strecat(buf, _name_additional_english_1b3b[SeedChance(12, lengthof(_name_additional_english_1b3b), seed)], last);
}
}
strecat(buf, _name_additional_english_2[SeedChance(14, lengthof(_name_additional_english_2), seed)], last);
/* optional last segment */
i = SeedChanceBias(15, lengthof(_name_additional_english_3), seed, 60);
if (i >= 0)
strecat(buf, _name_additional_english_3[i], last);
ReplaceWords("Cunt", "East", buf);
ReplaceWords("Slag", "Pits", buf);
ReplaceWords("Slut", "Edin", buf);
ReplaceWords("Fart", "Boot", buf);
ReplaceWords("Drar", "Quar", buf);
ReplaceWords("Dreh", "Bash", buf);
ReplaceWords("Frar", "Shor", buf);
ReplaceWords("Grar", "Aber", buf);
ReplaceWords("Brar", "Over", buf);
ReplaceWords("Wrar", "Stan", buf);
return 0;
}
static byte MakeAustrianTownName(char *buf, uint32 seed, const char *last)
{
int i, j = 0;
strecpy(buf, "", last);
/* Bad, Maria, Gross, ... */
i = SeedChanceBias(0, lengthof(_name_austrian_a1), seed, 15);
if (i >= 0) strecat(buf, _name_austrian_a1[i], last);
i = SeedChance(4, 6, seed);
if (i >= 4) {
/* Kaisers-kirchen */
strecat(buf, _name_austrian_a2[SeedChance( 7, lengthof(_name_austrian_a2), seed)], last);
strecat(buf, _name_austrian_a3[SeedChance(13, lengthof(_name_austrian_a3), seed)], last);
} else if (i >= 2) {
/* St. Johann */
strecat(buf, _name_austrian_a5[SeedChance( 7, lengthof(_name_austrian_a5), seed)], last);
strecat(buf, _name_austrian_a6[SeedChance( 9, lengthof(_name_austrian_a6), seed)], last);
j = 1; // More likely to have a " an der " or " am "
} else {
/* Zell */
strecat(buf, _name_austrian_a4[SeedChance( 7, lengthof(_name_austrian_a4), seed)], last);
}
i = SeedChance(1, 6, seed);
if (i >= 4 - j) {
/* an der Donau (rivers) */
strecat(buf, _name_austrian_f1[SeedChance(4, lengthof(_name_austrian_f1), seed)], last);
strecat(buf, _name_austrian_f2[SeedChance(5, lengthof(_name_austrian_f2), seed)], last);
} else if (i >= 2 - j) {
/* am Dachstein (mountains) */
strecat(buf, _name_austrian_b1[SeedChance(4, lengthof(_name_austrian_b1), seed)], last);
strecat(buf, _name_austrian_b2[SeedChance(5, lengthof(_name_austrian_b2), seed)], last);
}
return 0;
}
static byte MakeGermanTownName(char *buf, uint32 seed, const char *last)
{
uint i;
uint seed_derivative;
/* null terminates the string for strcat */
strecpy(buf, "", last);
seed_derivative = SeedChance(7, 28, seed);
/* optional prefix */
if (seed_derivative == 12 || seed_derivative == 19) {
i = SeedChance(2, lengthof(_name_german_pre), seed);
strecat(buf, _name_german_pre[i], last);
}
/* mandatory middle segments including option of hardcoded name */
i = SeedChance(3, lengthof(_name_german_real) + lengthof(_name_german_1), seed);
if (i < lengthof(_name_german_real)) {
strecat(buf, _name_german_real[i], last);
} else {
strecat(buf, _name_german_1[i - lengthof(_name_german_real)], last);
i = SeedChance(5, lengthof(_name_german_2), seed);
strecat(buf, _name_german_2[i], last);
}
/* optional suffix */
if (seed_derivative == 24) {
i = SeedChance(9,
lengthof(_name_german_4_an_der) + lengthof(_name_german_4_am), seed);
if (i < lengthof(_name_german_4_an_der)) {
strecat(buf, _name_german_3_an_der[0], last);
strecat(buf, _name_german_4_an_der[i], last);
} else {
strecat(buf, _name_german_3_am[0], last);
strecat(buf, _name_german_4_am[i - lengthof(_name_german_4_an_der)], last);
}
}
return 0;
}
static byte MakeSpanishTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, _name_spanish_real[SeedChance(0, lengthof(_name_spanish_real), seed)], last);
return 0;
}
static byte MakeFrenchTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, _name_french_real[SeedChance(0, lengthof(_name_french_real), seed)], last);
return 0;
}
static byte MakeSillyTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, _name_silly_1[SeedChance( 0, lengthof(_name_silly_1), seed)], last);
strecat(buf, _name_silly_2[SeedChance(16, lengthof(_name_silly_2), seed)], last);
return 0;
}
static byte MakeSwedishTownName(char *buf, uint32 seed, const char *last)
{
int i;
/* null terminates the string for strcat */
strecpy(buf, "", last);
/* optional first segment */
i = SeedChanceBias(0, lengthof(_name_swedish_1), seed, 50);
if (i >= 0)
strecat(buf, _name_swedish_1[i], last);
/* mandatory middle segments including option of hardcoded name */
if (SeedChance(4, 5, seed) >= 3) {
strecat(buf, _name_swedish_2[SeedChance( 7, lengthof(_name_swedish_2), seed)], last);
} else {
strecat(buf, _name_swedish_2a[SeedChance( 7, lengthof(_name_swedish_2a), seed)], last);
strecat(buf, _name_swedish_2b[SeedChance(10, lengthof(_name_swedish_2b), seed)], last);
strecat(buf, _name_swedish_2c[SeedChance(13, lengthof(_name_swedish_2c), seed)], last);
}
strecat(buf, _name_swedish_3[SeedChance(16, lengthof(_name_swedish_3), seed)], last);
return 0;
}
static byte MakeDutchTownName(char *buf, uint32 seed, const char *last)
{
int i;
/* null terminates the string for strcat */
strecpy(buf, "", last);
/* optional first segment */
i = SeedChanceBias(0, lengthof(_name_dutch_1), seed, 50);
if (i >= 0)
strecat(buf, _name_dutch_1[i], last);
/* mandatory middle segments including option of hardcoded name */
if (SeedChance(6, 9, seed) > 4) {
strecat(buf, _name_dutch_2[SeedChance( 9, lengthof(_name_dutch_2), seed)], last);
} else {
strecat(buf, _name_dutch_3[SeedChance( 9, lengthof(_name_dutch_3), seed)], last);
strecat(buf, _name_dutch_4[SeedChance(12, lengthof(_name_dutch_4), seed)], last);
}
strecat(buf, _name_dutch_5[SeedChance(15, lengthof(_name_dutch_5), seed)], last);
return 0;
}
static byte MakeFinnishTownName(char *buf, uint32 seed, const char *last)
{
/* null terminates the string for strcat */
strecpy(buf, "", last);
/* Select randomly if town name should consists of one or two parts. */
if (SeedChance(0, 15, seed) >= 10) {
strecat(buf, _name_finnish_real[SeedChance(2, lengthof(_name_finnish_real), seed)], last);
} else if (SeedChance(0, 15, seed) >= 5) {
/* A two-part name by combining one of _name_finnish_1 + "la"/"lä"
* The reason for not having the contents of _name_finnish_{1,2} in the same table is
* that the ones in _name_finnish_2 are not good for this purpose. */
uint sel = SeedChance( 0, lengthof(_name_finnish_1), seed);
char *end;
strecat(buf, _name_finnish_1[sel], last);
end = &buf[strlen(buf)-1];
if (*end == 'i')
*end = 'e';
if (strstr(buf, "a") || strstr(buf, "o") || strstr(buf, "u") ||
strstr(buf, "A") || strstr(buf, "O") || strstr(buf, "U"))
{
strecat(buf, "la", last);
} else {
strecat(buf, "l\xC3\xA4", last);
}
} else {
/* A two-part name by combining one of _name_finnish_{1,2} + _name_finnish_3.
* Why aren't _name_finnish_{1,2} just one table? See above. */
uint sel = SeedChance(2,
lengthof(_name_finnish_1) + lengthof(_name_finnish_2), seed);
if (sel >= lengthof(_name_finnish_1)) {
strecat(buf, _name_finnish_2[sel - lengthof(_name_finnish_1)], last);
} else {
strecat(buf, _name_finnish_1[sel], last);
}
strecat(buf, _name_finnish_3[SeedChance(10, lengthof(_name_finnish_3), seed)], last);
}
return 0;
}
static byte MakePolishTownName(char *buf, uint32 seed, const char *last)
{
uint i;
uint j;
/* null terminates the string for strcat */
strecpy(buf, "", last);
/* optional first segment */
i = SeedChance(0,
lengthof(_name_polish_2_o) + lengthof(_name_polish_2_m) +
lengthof(_name_polish_2_f) + lengthof(_name_polish_2_n),
seed);
j = SeedChance(2, 20, seed);
if (i < lengthof(_name_polish_2_o)) {
strecat(buf, _name_polish_2_o[SeedChance(3, lengthof(_name_polish_2_o), seed)], last);
} else if (i < lengthof(_name_polish_2_m) + lengthof(_name_polish_2_o)) {
if (j < 4)
strecat(buf, _name_polish_1_m[SeedChance(5, lengthof(_name_polish_1_m), seed)], last);
strecat(buf, _name_polish_2_m[SeedChance(7, lengthof(_name_polish_2_m), seed)], last);
if (j >= 4 && j < 16)
strecat(buf, _name_polish_3_m[SeedChance(10, lengthof(_name_polish_3_m), seed)], last);
} else if (i < lengthof(_name_polish_2_f) + lengthof(_name_polish_2_m) + lengthof(_name_polish_2_o)) {
if (j < 4)
strecat(buf, _name_polish_1_f[SeedChance(5, lengthof(_name_polish_1_f), seed)], last);
strecat(buf, _name_polish_2_f[SeedChance(7, lengthof(_name_polish_2_f), seed)], last);
if (j >= 4 && j < 16)
strecat(buf, _name_polish_3_f[SeedChance(10, lengthof(_name_polish_3_f), seed)], last);
} else {
if (j < 4)
strecat(buf, _name_polish_1_n[SeedChance(5, lengthof(_name_polish_1_n), seed)], last);
strecat(buf, _name_polish_2_n[SeedChance(7, lengthof(_name_polish_2_n), seed)], last);
if (j >= 4 && j < 16)
strecat(buf, _name_polish_3_n[SeedChance(10, lengthof(_name_polish_3_n), seed)], last);
}
return 0;
}
static byte MakeCzechTownName(char *buf, uint32 seed, const char *last)
{
/* Probability of prefixes/suffixes
* 0..11 prefix, 12..13 prefix+suffix, 14..17 suffix, 18..31 nothing */
int prob_tails;
bool do_prefix, do_suffix, dynamic_subst;
/* IDs of the respective parts */
int prefix = 0, ending = 0, suffix = 0;
uint postfix = 0;
uint stem;
/* The select criteria. */
CzechGender gender;
CzechChoose choose;
CzechAllow allow;
/* 1:3 chance to use a real name. */
if (SeedModChance(0, 4, seed) == 0) {
strecpy(buf, _name_czech_real[SeedModChance(4, lengthof(_name_czech_real), seed)], last);
return 0;
}
/* NUL terminates the string for strcat() */
strecpy(buf, "", last);
prob_tails = SeedModChance(2, 32, seed);
do_prefix = prob_tails < 12;
do_suffix = prob_tails > 11 && prob_tails < 17;
if (do_prefix) prefix = SeedModChance(5, lengthof(_name_czech_adj) * 12, seed) / 12;
if (do_suffix) suffix = SeedModChance(7, lengthof(_name_czech_suffix), seed);
/* 3:1 chance 3:1 to use dynamic substantive */
stem = SeedModChance(9,
lengthof(_name_czech_subst_full) + 3 * lengthof(_name_czech_subst_stem),
seed);
if (stem < lengthof(_name_czech_subst_full)) {
/* That was easy! */
dynamic_subst = false;
gender = _name_czech_subst_full[stem].gender;
choose = _name_czech_subst_full[stem].choose;
allow = _name_czech_subst_full[stem].allow;
} else {
unsigned int map[lengthof(_name_czech_subst_ending)];
int ending_start = -1, ending_stop = -1;
int i;
/* Load the substantive */
dynamic_subst = true;
stem -= lengthof(_name_czech_subst_full);
stem %= lengthof(_name_czech_subst_stem);
gender = _name_czech_subst_stem[stem].gender;
choose = _name_czech_subst_stem[stem].choose;
allow = _name_czech_subst_stem[stem].allow;
/* Load the postfix (1:1 chance that a postfix will be inserted) */
postfix = SeedModChance(14, lengthof(_name_czech_subst_postfix) * 2, seed);
if (choose & CZC_POSTFIX) {
/* Always get a real postfix. */
postfix %= lengthof(_name_czech_subst_postfix);
}
if (choose & CZC_NOPOSTFIX) {
/* Always drop a postfix. */
postfix += lengthof(_name_czech_subst_postfix);
}
if (postfix < lengthof(_name_czech_subst_postfix)) {
choose |= CZC_POSTFIX;
} else {
choose |= CZC_NOPOSTFIX;
}
/* Localize the array segment containing a good gender */
for (ending = 0; ending < (int) lengthof(_name_czech_subst_ending); ending++) {
const CzechNameSubst *e = &_name_czech_subst_ending[ending];
if (gender == CZG_FREE ||
(gender == CZG_NFREE && e->gender != CZG_SNEUT && e->gender != CZG_PNEUT) ||
gender == e->gender) {
if (ending_start < 0)
ending_start = ending;
} else if (ending_start >= 0) {
ending_stop = ending - 1;
break;
}
}
if (ending_stop < 0) {
/* Whoa. All the endings matched. */
ending_stop = ending - 1;
}
/* Make a sequential map of the items with good mask */
i = 0;
for (ending = ending_start; ending <= ending_stop; ending++) {
const CzechNameSubst *e = &_name_czech_subst_ending[ending];
if ((e->choose & choose) == choose && (e->allow & allow) != 0)
map[i++] = ending;
}
assert(i > 0);
/* Load the ending */
ending = map[SeedModChance(16, i, seed)];
/* Override possible CZG_*FREE; this must be a real gender,
* otherwise we get overflow when modifying the adjectivum. */
gender = _name_czech_subst_ending[ending].gender;
assert(gender != CZG_FREE && gender != CZG_NFREE);
}
if (do_prefix && (_name_czech_adj[prefix].choose & choose) != choose) {
/* Throw away non-matching prefix. */
do_prefix = false;
}
/* Now finally construct the name */
if (do_prefix) {
CzechPattern pattern = _name_czech_adj[prefix].pattern;
size_t endpos;
strecat(buf, _name_czech_adj[prefix].name, last);
endpos = strlen(buf) - 1;
/* Find the first character in a UTF-8 sequence */
while (GB(buf[endpos], 6, 2) == 2) endpos--;
if (gender == CZG_SMASC && pattern == CZP_PRIVL) {
/* -ovX -> -uv */
buf[endpos - 2] = 'u';
assert(buf[endpos - 1] == 'v');
buf[endpos] = '\0';
} else {
strecpy(buf + endpos, _name_czech_patmod[gender][pattern], last);
}
strecat(buf, " ", last);
}
if (dynamic_subst) {
strecat(buf, _name_czech_subst_stem[stem].name, last);
if (postfix < lengthof(_name_czech_subst_postfix)) {
const char *poststr = _name_czech_subst_postfix[postfix];
const char *endstr = _name_czech_subst_ending[ending].name;
size_t postlen, endlen;
postlen = strlen(poststr);
endlen = strlen(endstr);
assert(postlen > 0 && endlen > 0);
/* Kill the "avava" and "Jananna"-like cases */
if (postlen < 2 || postlen > endlen || (
(poststr[1] != 'v' || poststr[1] != endstr[1]) &&
poststr[2] != endstr[1])
) {
size_t buflen;
strecat(buf, poststr, last);
buflen = strlen(buf);
/* k-i -> c-i, h-i -> z-i */
if (endstr[0] == 'i') {
switch (buf[buflen - 1]) {
case 'k': buf[buflen - 1] = 'c'; break;
case 'h': buf[buflen - 1] = 'z'; break;
default: break;
}
}
}
}
strecat(buf, _name_czech_subst_ending[ending].name, last);
} else {
strecat(buf, _name_czech_subst_full[stem].name, last);
}
if (do_suffix) {
strecat(buf, " ", last);
strecat(buf, _name_czech_suffix[suffix], last);
}
return 0;
}
static byte MakeRomanianTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, _name_romanian_real[SeedChance(0, lengthof(_name_romanian_real), seed)], last);
return 0;
}
static byte MakeSlovakTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, _name_slovak_real[SeedChance(0, lengthof(_name_slovak_real), seed)], last);
return 0;
}
static byte MakeNorwegianTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, "", last);
/* Use first 4 bit from seed to decide whether or not this town should
* have a real name 3/16 chance. Bit 0-3 */
if (SeedChance(0, 15, seed) < 3) {
/* Use 7bit for the realname table index. Bit 4-10 */
strecat(buf, _name_norwegian_real[SeedChance(4, lengthof(_name_norwegian_real), seed)], last);
} else {
/* Use 7bit for the first fake part. Bit 4-10 */
strecat(buf, _name_norwegian_1[SeedChance(4, lengthof(_name_norwegian_1), seed)], last);
/* Use 7bit for the last fake part. Bit 11-17 */
strecat(buf, _name_norwegian_2[SeedChance(11, lengthof(_name_norwegian_2), seed)], last);
}
return 0;
}
static byte MakeHungarianTownName(char *buf, uint32 seed, const char *last)
{
uint i;
/* null terminates the string for strcat */
strecpy(buf, "", last);
if (SeedChance(12, 15, seed) < 3) {
strecat(buf, _name_hungarian_real[SeedChance(0, lengthof(_name_hungarian_real), seed)], last);
} else {
/* optional first segment */
i = SeedChance(3, lengthof(_name_hungarian_1) * 3, seed);
if (i < lengthof(_name_hungarian_1))
strecat(buf, _name_hungarian_1[i], last);
/* mandatory middle segments */
strecat(buf, _name_hungarian_2[SeedChance(3, lengthof(_name_hungarian_2), seed)], last);
strecat(buf, _name_hungarian_3[SeedChance(6, lengthof(_name_hungarian_3), seed)], last);
/* optional last segment */
i = SeedChance(10, lengthof(_name_hungarian_4) * 3, seed);
if (i < lengthof(_name_hungarian_4)) {
strecat(buf, _name_hungarian_4[i], last);
}
}
return 0;
}
static byte MakeSwissTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, _name_swiss_real[SeedChance(0, lengthof(_name_swiss_real), seed)], last);
return 0;
}
static byte MakeDanishTownName(char *buf, uint32 seed, const char *last)
{
int i;
/* null terminates the string for strcat */
strecpy(buf, "", last);
/* optional first segment */
i = SeedChanceBias(0, lengthof(_name_danish_1), seed, 50);
if (i >= 0)
strecat(buf, _name_danish_1[i], last);
/* middle segments removed as this algorithm seems to create much more realistic names */
strecat(buf, _name_danish_2[SeedChance( 7, lengthof(_name_danish_2), seed)], last);
strecat(buf, _name_danish_3[SeedChance(16, lengthof(_name_danish_3), seed)], last);
return 0;
}
static byte MakeTurkishTownName(char *buf, uint32 seed, const char *last)
{
uint i;
/* null terminates the string for strcat */
strecpy(buf, "", last);
if ((i = SeedModChance(0, 5, seed)) == 0) {
strecat(buf, _name_turkish_prefix[SeedModChance( 2, lengthof(_name_turkish_prefix), seed)], last);
/* middle segment */
strecat(buf, _name_turkish_middle[SeedModChance( 4, lengthof(_name_turkish_middle), seed)], last);
/* optional suffix */
if (SeedModChance(0, 7, seed) == 0) {
strecat(buf, _name_turkish_suffix[SeedModChance( 10, lengthof(_name_turkish_suffix), seed)], last);
}
} else {
if (i == 1 || i == 2) {
strecat(buf, _name_turkish_prefix[SeedModChance( 2, lengthof(_name_turkish_prefix), seed)], last);
strecat(buf, _name_turkish_suffix[SeedModChance( 4, lengthof(_name_turkish_suffix), seed)], last);
} else {
strecat(buf, _name_turkish_real[SeedModChance( 4, lengthof(_name_turkish_real), seed)], last);
}
}
return 0;
}
static const char *mascul_femin_italian[] = {
"o",
"a",
};
static byte MakeItalianTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, "", last);
if (SeedModChance(0, 6, seed) == 0) { // real city names
strecat(buf, _name_italian_real[SeedModChance(4, lengthof(_name_italian_real), seed)], last);
} else {
uint i;
if (SeedModChance(0, 8, seed) == 0) { // prefix
strecat(buf, _name_italian_pref[SeedModChance(11, lengthof(_name_italian_pref), seed)], last);
}
i = SeedChance(0, 2, seed);
if (i == 0) { // masculine form
strecat(buf, _name_italian_1m[SeedModChance(4, lengthof(_name_italian_1m), seed)], last);
} else { // feminine form
strecat(buf, _name_italian_1f[SeedModChance(4, lengthof(_name_italian_1f), seed)], last);
}
if (SeedModChance(3, 3, seed) == 0) {
strecat(buf, _name_italian_2[SeedModChance(11, lengthof(_name_italian_2), seed)], last);
strecat(buf, mascul_femin_italian[i], last);
} else {
strecat(buf, _name_italian_2i[SeedModChance(16, lengthof(_name_italian_2i), seed)], last);
}
if (SeedModChance(15, 4, seed) == 0) {
if (SeedModChance(5, 2, seed) == 0) { // generic suffix
strecat(buf, _name_italian_3[SeedModChance(4, lengthof(_name_italian_3), seed)], last);
} else { // river name suffix
strecat(buf, _name_italian_river1[SeedModChance(4, lengthof(_name_italian_river1), seed)], last);
strecat(buf, _name_italian_river2[SeedModChance(16, lengthof(_name_italian_river2), seed)], last);
}
}
}
return 0;
}
static byte MakeCatalanTownName(char *buf, uint32 seed, const char *last)
{
strecpy(buf, "", last);
if (SeedModChance(0, 3, seed) == 0) { // real city names
strecat(buf, _name_catalan_real[SeedModChance(4, lengthof(_name_catalan_real), seed)], last);
} else {
uint i;
if (SeedModChance(0, 2, seed) == 0) { // prefix
strecat(buf, _name_catalan_pref[SeedModChance(11, lengthof(_name_catalan_pref), seed)], last);
}
i = SeedChance(0, 2, seed);
if (i == 0) { // masculine form
strecat(buf, _name_catalan_1m[SeedModChance(4, lengthof(_name_catalan_1m), seed)], last);
strecat(buf, _name_catalan_2m[SeedModChance(11, lengthof(_name_catalan_2m), seed)], last);
} else { // feminine form
strecat(buf, _name_catalan_1f[SeedModChance(4, lengthof(_name_catalan_1f), seed)], last);
strecat(buf, _name_catalan_2f[SeedModChance(11, lengthof(_name_catalan_2f), seed)], last);
}
if (SeedModChance(15, 5, seed) == 0) {
if (SeedModChance(5, 2, seed) == 0) { // generic suffix
strecat(buf, _name_catalan_3[SeedModChance(4, lengthof(_name_catalan_3), seed)], last);
} else { // river name suffix
strecat(buf, _name_catalan_river1[SeedModChance(4, lengthof(_name_catalan_river1), seed)], last);
}
}
}
return 0;
}
TownNameGenerator * const _town_name_generators[] =
{
MakeEnglishOriginalTownName,
MakeFrenchTownName,
MakeGermanTownName,
MakeEnglishAdditionalTownName,
MakeSpanishTownName,
MakeSillyTownName,
MakeSwedishTownName,
MakeDutchTownName,
MakeFinnishTownName,
MakePolishTownName,
MakeSlovakTownName,
MakeNorwegianTownName,
MakeHungarianTownName,
MakeAustrianTownName,
MakeRomanianTownName,
MakeCzechTownName,
MakeSwissTownName,
MakeDanishTownName,
MakeTurkishTownName,
MakeItalianTownName,
MakeCatalanTownName,
};
| 24,852
|
C++
|
.cpp
| 629
| 36.740859
| 121
| 0.679837
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,036
|
console.cpp
|
EnergeticBark_OpenTTD-3DS/src/console.cpp
|
/* $Id$ */
/** @file console.cpp Handling of the in-game console. */
#include "stdafx.h"
#include "core/alloc_func.hpp"
#include "core/math_func.hpp"
#include "string_func.h"
#include "console_internal.h"
#include "network/network.h"
#include "network/network_func.h"
#include <stdarg.h>
#define ICON_BUFFER 79
#define ICON_HISTORY_SIZE 20
#define ICON_LINE_HEIGHT 12
#define ICON_RIGHT_BORDERWIDTH 10
#define ICON_BOTTOM_BORDERWIDTH 12
#define ICON_MAX_ALIAS_LINES 40
#define ICON_TOKEN_COUNT 20
/* console parser */
IConsoleCmd *_iconsole_cmds; ///< list of registred commands
IConsoleVar *_iconsole_vars; ///< list of registred vars
IConsoleAlias *_iconsole_aliases; ///< list of registred aliases
/* ** stdlib ** */
byte _stdlib_developer = 1;
bool _stdlib_con_developer = false;
FILE *_iconsole_output_file;
void IConsoleInit()
{
_iconsole_output_file = NULL;
#ifdef ENABLE_NETWORK /* Initialize network only variables */
_redirect_console_to_client = INVALID_CLIENT_ID;
#endif
IConsoleGUIInit();
IConsoleStdLibRegister();
}
static void IConsoleWriteToLogFile(const char *string)
{
if (_iconsole_output_file != NULL) {
/* if there is an console output file ... also print it there */
if (fwrite(string, strlen(string), 1, _iconsole_output_file) != 1 ||
fwrite("\n", 1, 1, _iconsole_output_file) != 1) {
fclose(_iconsole_output_file);
_iconsole_output_file = NULL;
IConsolePrintF(CC_DEFAULT, "cannot write to log file");
}
}
}
bool CloseConsoleLogIfActive()
{
if (_iconsole_output_file != NULL) {
IConsolePrintF(CC_DEFAULT, "file output complete");
fclose(_iconsole_output_file);
_iconsole_output_file = NULL;
return true;
}
return false;
}
void IConsoleFree()
{
IConsoleGUIFree();
CloseConsoleLogIfActive();
}
/**
* Handle the printing of text entered into the console or redirected there
* by any other means. Text can be redirected to other clients in a network game
* as well as to a logfile. If the network server is a dedicated server, all activities
* are also logged. All lines to print are added to a temporary buffer which can be
* used as a history to print them onscreen
* @param colour_code the colour of the command. Red in case of errors, etc.
* @param string the message entered or output on the console (notice, error, etc.)
*/
void IConsolePrint(ConsoleColour colour_code, const char *string)
{
char *str;
#ifdef ENABLE_NETWORK
if (_redirect_console_to_client != INVALID_CLIENT_ID) {
/* Redirect the string to the client */
NetworkServerSendRcon(_redirect_console_to_client, colour_code, string);
return;
}
#endif
/* Create a copy of the string, strip if of colours and invalid
* characters and (when applicable) assign it to the console buffer */
str = strdup(string);
str_strip_colours(str);
str_validate(str, str + strlen(str));
if (_network_dedicated) {
fprintf(stdout, "%s\n", str);
fflush(stdout);
IConsoleWriteToLogFile(str);
free(str); // free duplicated string since it's not used anymore
return;
}
IConsoleWriteToLogFile(str);
IConsoleGUIPrint(colour_code, str);
}
/**
* Handle the printing of text entered into the console or redirected there
* by any other means. Uses printf() style format, for more information look
* at IConsolePrint()
*/
void CDECL IConsolePrintF(ConsoleColour colour_code, const char *s, ...)
{
va_list va;
char buf[ICON_MAX_STREAMSIZE];
va_start(va, s);
vsnprintf(buf, sizeof(buf), s, va);
va_end(va);
IConsolePrint(colour_code, buf);
}
/**
* It is possible to print debugging information to the console,
* which is achieved by using this function. Can only be used by
* debug() in debug.cpp. You need at least a level 2 (developer) for debugging
* messages to show up
* @param dbg debugging category
* @param string debugging message
*/
void IConsoleDebug(const char *dbg, const char *string)
{
if (_stdlib_developer > 1)
IConsolePrintF(CC_DEBUG, "dbg: [%s] %s", dbg, string);
}
/**
* It is possible to print warnings to the console. These are mostly
* errors or mishaps, but non-fatal. You need at least a level 1 (developer) for
* debugging messages to show up
*/
void IConsoleWarning(const char *string)
{
if (_stdlib_developer > 0)
IConsolePrintF(CC_WARNING, "WARNING: %s", string);
}
/**
* It is possible to print error information to the console. This can include
* game errors, or errors in general you would want the user to notice
*/
void IConsoleError(const char *string)
{
IConsolePrintF(CC_ERROR, "ERROR: %s", string);
}
/**
* Change a string into its number representation. Supports
* decimal and hexadecimal numbers as well as 'on'/'off' 'true'/'false'
* @param *value the variable a successful conversion will be put in
* @param *arg the string to be converted
* @return Return true on success or false on failure
*/
bool GetArgumentInteger(uint32 *value, const char *arg)
{
char *endptr;
if (strcmp(arg, "on") == 0 || strcmp(arg, "true") == 0) {
*value = 1;
return true;
}
if (strcmp(arg, "off") == 0 || strcmp(arg, "false") == 0) {
*value = 0;
return true;
}
*value = strtoul(arg, &endptr, 0);
return arg != endptr;
}
/* * *************************
* hooking code *
* *************************/
/**
* General internal hooking code that is the same for both commands and variables
* @param hooks IConsoleHooks structure that will be set according to
* @param type type access trigger
* @param proc function called when the hook criteria is met
*/
static void IConsoleHookAdd(IConsoleHooks *hooks, IConsoleHookTypes type, IConsoleHook *proc)
{
if (hooks == NULL || proc == NULL) return;
switch (type) {
case ICONSOLE_HOOK_ACCESS:
hooks->access = proc;
break;
case ICONSOLE_HOOK_PRE_ACTION:
hooks->pre = proc;
break;
case ICONSOLE_HOOK_POST_ACTION:
hooks->post = proc;
break;
default: NOT_REACHED();
}
}
/**
* Handle any special hook triggers. If the hook type is met check if
* there is a function associated with that and if so, execute it
* @param hooks IConsoleHooks structure that will be checked
* @param type type of hook, trigger that needs to be activated
* @return true on a successful execution of the hook command or if there
* is no hook/trigger present at all. False otherwise
*/
static bool IConsoleHookHandle(const IConsoleHooks *hooks, IConsoleHookTypes type)
{
IConsoleHook *proc = NULL;
if (hooks == NULL) return false;
switch (type) {
case ICONSOLE_HOOK_ACCESS:
proc = hooks->access;
break;
case ICONSOLE_HOOK_PRE_ACTION:
proc = hooks->pre;
break;
case ICONSOLE_HOOK_POST_ACTION:
proc = hooks->post;
break;
default: NOT_REACHED();
}
return (proc == NULL) ? true : proc();
}
/**
* Add a hook to a command that will be triggered at certain points
* @param name name of the command that the hook is added to
* @param type type of hook that is added (ACCESS, BEFORE and AFTER change)
* @param proc function called when the hook criteria is met
*/
void IConsoleCmdHookAdd(const char *name, IConsoleHookTypes type, IConsoleHook *proc)
{
IConsoleCmd *cmd = IConsoleCmdGet(name);
if (cmd == NULL) return;
IConsoleHookAdd(&cmd->hook, type, proc);
}
/**
* Add a hook to a variable that will be triggered at certain points
* @param name name of the variable that the hook is added to
* @param type type of hook that is added (ACCESS, BEFORE and AFTER change)
* @param proc function called when the hook criteria is met
*/
void IConsoleVarHookAdd(const char *name, IConsoleHookTypes type, IConsoleHook *proc)
{
IConsoleVar *var = IConsoleVarGet(name);
if (var == NULL) return;
IConsoleHookAdd(&var->hook, type, proc);
}
/**
* Perhaps ugly macro, but this saves us the trouble of writing the same function
* three types, just with different variables. Yes, templates would be handy. It was
* either this define or an even more ugly void* magic function
*/
#define IConsoleAddSorted(_base, item_new, IConsoleType, type) \
{ \
IConsoleType *item, *item_before; \
/* first command */ \
if (_base == NULL) { \
_base = item_new; \
return; \
} \
\
item_before = NULL; \
item = _base; \
\
/* BEGIN - Alphabetically insert the commands into the linked list */ \
while (item != NULL) { \
int i = strcmp(item->name, item_new->name); \
if (i == 0) { \
IConsoleError(type " with this name already exists; insertion aborted"); \
free(item_new); \
return; \
} \
\
if (i > 0) break; /* insert at this position */ \
\
item_before = item; \
item = item->next; \
} \
\
if (item_before == NULL) { \
_base = item_new; \
} else { \
item_before->next = item_new; \
} \
\
item_new->next = item; \
/* END - Alphabetical insert */ \
}
/**
* Register a new command to be used in the console
* @param name name of the command that will be used
* @param proc function that will be called upon execution of command
*/
void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc)
{
char *new_cmd = strdup(name);
IConsoleCmd *item_new = MallocT<IConsoleCmd>(1);
item_new->next = NULL;
item_new->proc = proc;
item_new->name = new_cmd;
item_new->hook.access = NULL;
item_new->hook.pre = NULL;
item_new->hook.post = NULL;
IConsoleAddSorted(_iconsole_cmds, item_new, IConsoleCmd, "a command");
}
/**
* Find the command pointed to by its string
* @param name command to be found
* @return return Cmdstruct of the found command, or NULL on failure
*/
IConsoleCmd *IConsoleCmdGet(const char *name)
{
IConsoleCmd *item;
for (item = _iconsole_cmds; item != NULL; item = item->next) {
if (strcmp(item->name, name) == 0) return item;
}
return NULL;
}
/**
* Register a an alias for an already existing command in the console
* @param name name of the alias that will be used
* @param cmd name of the command that 'name' will be alias of
*/
void IConsoleAliasRegister(const char *name, const char *cmd)
{
char *new_alias = strdup(name);
char *cmd_aliased = strdup(cmd);
IConsoleAlias *item_new = MallocT<IConsoleAlias>(1);
item_new->next = NULL;
item_new->cmdline = cmd_aliased;
item_new->name = new_alias;
IConsoleAddSorted(_iconsole_aliases, item_new, IConsoleAlias, "an alias");
}
/**
* Find the alias pointed to by its string
* @param name alias to be found
* @return return Aliasstruct of the found alias, or NULL on failure
*/
IConsoleAlias *IConsoleAliasGet(const char *name)
{
IConsoleAlias *item;
for (item = _iconsole_aliases; item != NULL; item = item->next) {
if (strcmp(item->name, name) == 0) return item;
}
return NULL;
}
/** copy in an argument into the aliasstream */
static inline int IConsoleCopyInParams(char *dst, const char *src, uint bufpos)
{
/* len is the amount of bytes to add excluding the '\0'-termination */
int len = min(ICON_MAX_STREAMSIZE - bufpos - 1, (uint)strlen(src));
strecpy(dst, src, dst + len);
return len;
}
/**
* An alias is just another name for a command, or for more commands
* Execute it as well.
* @param *alias is the alias of the command
* @param tokencount the number of parameters passed
* @param *tokens are the parameters given to the original command (0 is the first param)
*/
static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT])
{
const char *cmdptr;
char *aliases[ICON_MAX_ALIAS_LINES], aliasstream[ICON_MAX_STREAMSIZE];
uint i;
uint a_index, astream_i;
memset(&aliases, 0, sizeof(aliases));
memset(&aliasstream, 0, sizeof(aliasstream));
if (_stdlib_con_developer)
IConsolePrintF(CC_DEBUG, "condbg: requested command is an alias; parsing...");
aliases[0] = aliasstream;
for (cmdptr = alias->cmdline, a_index = 0, astream_i = 0; *cmdptr != '\0'; cmdptr++) {
if (a_index >= lengthof(aliases) || astream_i >= lengthof(aliasstream)) break;
switch (*cmdptr) {
case '\'': // ' will double for ""
aliasstream[astream_i++] = '"';
break;
case ';': // Cmd seperator, start new command
aliasstream[astream_i] = '\0';
aliases[++a_index] = &aliasstream[++astream_i];
cmdptr++;
break;
case '%': // Some or all parameters
cmdptr++;
switch (*cmdptr) {
case '+': { // All parameters seperated: "[param 1]" "[param 2]"
for (i = 0; i != tokencount; i++) {
aliasstream[astream_i++] = '"';
astream_i += IConsoleCopyInParams(&aliasstream[astream_i], tokens[i], astream_i);
aliasstream[astream_i++] = '"';
aliasstream[astream_i++] = ' ';
}
} break;
case '!': { // Merge the parameters to one: "[param 1] [param 2] [param 3...]"
aliasstream[astream_i++] = '"';
for (i = 0; i != tokencount; i++) {
astream_i += IConsoleCopyInParams(&aliasstream[astream_i], tokens[i], astream_i);
aliasstream[astream_i++] = ' ';
}
aliasstream[astream_i++] = '"';
} break;
default: { // One specific parameter: %A = [param 1] %B = [param 2] ...
int param = *cmdptr - 'A';
if (param < 0 || param >= tokencount) {
IConsoleError("too many or wrong amount of parameters passed to alias, aborting");
IConsolePrintF(CC_WARNING, "Usage of alias '%s': %s", alias->name, alias->cmdline);
return;
}
aliasstream[astream_i++] = '"';
astream_i += IConsoleCopyInParams(&aliasstream[astream_i], tokens[param], astream_i);
aliasstream[astream_i++] = '"';
} break;
} break;
default:
aliasstream[astream_i++] = *cmdptr;
break;
}
}
for (i = 0; i <= a_index; i++) IConsoleCmdExec(aliases[i]); // execute each alias in turn
}
/**
* Special function for adding string-type variables. They in addition
* also need a 'size' value saying how long their string buffer is.
* @param name name of the variable that will be used
* @param addr memory location the variable will point to
* @param size the length of the string buffer
* @param help the help string shown for the variable
* For more information see IConsoleVarRegister()
*/
void IConsoleVarStringRegister(const char *name, void *addr, uint32 size, const char *help)
{
IConsoleVar *var;
IConsoleVarRegister(name, addr, ICONSOLE_VAR_STRING, help);
var = IConsoleVarGet(name);
var->size = size;
}
/**
* Register a new variable to be used in the console
* @param name name of the variable that will be used
* @param addr memory location the variable will point to
* @param help the help string shown for the variable
* @param type the type of the variable (simple atomic) so we know which values it can get
*/
void IConsoleVarRegister(const char *name, void *addr, IConsoleVarTypes type, const char *help)
{
char *new_cmd = strdup(name);
IConsoleVar *item_new = MallocT<IConsoleVar>(1);
item_new->help = (help != NULL) ? strdup(help) : NULL;
item_new->next = NULL;
item_new->name = new_cmd;
item_new->addr = addr;
item_new->proc = NULL;
item_new->type = type;
item_new->hook.access = NULL;
item_new->hook.pre = NULL;
item_new->hook.post = NULL;
IConsoleAddSorted(_iconsole_vars, item_new, IConsoleVar, "a variable");
}
/**
* Find the variable pointed to by its string
* @param name variable to be found
* @return return Varstruct of the found variable, or NULL on failure
*/
IConsoleVar *IConsoleVarGet(const char *name)
{
IConsoleVar *item;
for (item = _iconsole_vars; item != NULL; item = item->next) {
if (strcmp(item->name, name) == 0) return item;
}
return NULL;
}
/**
* Set a new value to a console variable
* @param *var the variable being set/changed
* @param value the new value given to the variable, cast properly
*/
static void IConsoleVarSetValue(const IConsoleVar *var, uint32 value)
{
IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_PRE_ACTION);
switch (var->type) {
case ICONSOLE_VAR_BOOLEAN:
*(bool*)var->addr = (value != 0);
break;
case ICONSOLE_VAR_BYTE:
*(byte*)var->addr = (byte)value;
break;
case ICONSOLE_VAR_UINT16:
*(uint16*)var->addr = (uint16)value;
break;
case ICONSOLE_VAR_INT16:
*(int16*)var->addr = (int16)value;
break;
case ICONSOLE_VAR_UINT32:
*(uint32*)var->addr = (uint32)value;
break;
case ICONSOLE_VAR_INT32:
*(int32*)var->addr = (int32)value;
break;
default: NOT_REACHED();
}
IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_POST_ACTION);
IConsoleVarPrintSetValue(var);
}
/**
* Set a new value to a string-type variable. Basically this
* means to copy the new value over to the container.
* @param *var the variable in question
* @param *value the new value
*/
static void IConsoleVarSetStringvalue(const IConsoleVar *var, const char *value)
{
if (var->type != ICONSOLE_VAR_STRING || var->addr == NULL) return;
IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_PRE_ACTION);
ttd_strlcpy((char*)var->addr, value, var->size);
IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_POST_ACTION);
IConsoleVarPrintSetValue(var); // print out the new value, giving feedback
return;
}
/**
* Query the current value of a variable and return it
* @param *var the variable queried
* @return current value of the variable
*/
static uint32 IConsoleVarGetValue(const IConsoleVar *var)
{
uint32 result = 0;
switch (var->type) {
case ICONSOLE_VAR_BOOLEAN:
result = *(bool*)var->addr;
break;
case ICONSOLE_VAR_BYTE:
result = *(byte*)var->addr;
break;
case ICONSOLE_VAR_UINT16:
result = *(uint16*)var->addr;
break;
case ICONSOLE_VAR_INT16:
result = *(int16*)var->addr;
break;
case ICONSOLE_VAR_UINT32:
result = *(uint32*)var->addr;
break;
case ICONSOLE_VAR_INT32:
result = *(int32*)var->addr;
break;
default: NOT_REACHED();
}
return result;
}
/**
* Get the value of the variable and put it into a printable
* string form so we can use it for printing
*/
static char *IConsoleVarGetStringValue(const IConsoleVar *var)
{
static char tempres[50];
char *value = tempres;
switch (var->type) {
case ICONSOLE_VAR_BOOLEAN:
snprintf(tempres, sizeof(tempres), "%s", (*(bool*)var->addr) ? "on" : "off");
break;
case ICONSOLE_VAR_BYTE:
snprintf(tempres, sizeof(tempres), "%u", *(byte*)var->addr);
break;
case ICONSOLE_VAR_UINT16:
snprintf(tempres, sizeof(tempres), "%u", *(uint16*)var->addr);
break;
case ICONSOLE_VAR_UINT32:
snprintf(tempres, sizeof(tempres), "%u", *(uint32*)var->addr);
break;
case ICONSOLE_VAR_INT16:
snprintf(tempres, sizeof(tempres), "%i", *(int16*)var->addr);
break;
case ICONSOLE_VAR_INT32:
snprintf(tempres, sizeof(tempres), "%i", *(int32*)var->addr);
break;
case ICONSOLE_VAR_STRING:
value = (char*)var->addr;
break;
default: NOT_REACHED();
}
return value;
}
/**
* Print out the value of the variable when asked
*/
void IConsoleVarPrintGetValue(const IConsoleVar *var)
{
char *value;
/* Some variables need really specific handling, handle this in its
* callback function */
if (var->proc != NULL) {
var->proc(0, NULL);
return;
}
value = IConsoleVarGetStringValue(var);
IConsolePrintF(CC_WARNING, "Current value for '%s' is: %s", var->name, value);
}
/**
* Print out the value of the variable after it has been assigned
* a new value, thus giving us feedback on the action
*/
void IConsoleVarPrintSetValue(const IConsoleVar *var)
{
char *value = IConsoleVarGetStringValue(var);
IConsolePrintF(CC_WARNING, "'%s' changed to: %s", var->name, value);
}
/**
* Execute a variable command. Without any parameters, print out its value
* with parameters it assigns a new value to the variable
* @param *var the variable that we will be querying/changing
* @param tokencount how many additional parameters have been given to the commandline
* @param *token the actual parameters the variable was called with
*/
void IConsoleVarExec(const IConsoleVar *var, byte tokencount, char *token[ICON_TOKEN_COUNT])
{
const char *tokenptr = token[0];
byte t_index = tokencount;
uint32 value;
if (_stdlib_con_developer)
IConsolePrintF(CC_DEBUG, "condbg: requested command is a variable");
if (tokencount == 0) { // Just print out value
IConsoleVarPrintGetValue(var);
return;
}
/* Use of assignment sign is not mandatory but supported, so just 'ignore it appropiately' */
if (strcmp(tokenptr, "=") == 0) tokencount--;
if (tokencount == 1) {
/* Some variables need really special handling, handle it in their callback procedure */
if (var->proc != NULL) {
var->proc(tokencount, &token[t_index - tokencount]); // set the new value
return;
}
/* Strings need special processing. No need to convert the argument to
* an integer value, just copy over the argument on a one-by-one basis */
if (var->type == ICONSOLE_VAR_STRING) {
IConsoleVarSetStringvalue(var, token[t_index - tokencount]);
return;
} else if (GetArgumentInteger(&value, token[t_index - tokencount])) {
IConsoleVarSetValue(var, value);
return;
}
/* Increase or decrease the value by one. This of course can only happen to 'number' types */
if (strcmp(tokenptr, "++") == 0 && var->type != ICONSOLE_VAR_STRING) {
IConsoleVarSetValue(var, IConsoleVarGetValue(var) + 1);
return;
}
if (strcmp(tokenptr, "--") == 0 && var->type != ICONSOLE_VAR_STRING) {
IConsoleVarSetValue(var, IConsoleVarGetValue(var) - 1);
return;
}
}
IConsoleError("invalid variable assignment");
}
/**
* Add a callback function to the variable. Some variables need
* very special processing, which can only be done with custom code
* @param name name of the variable the callback function is added to
* @param proc the function called
*/
void IConsoleVarProcAdd(const char *name, IConsoleCmdProc *proc)
{
IConsoleVar *var = IConsoleVarGet(name);
if (var == NULL) return;
var->proc = proc;
}
/**
* Execute a given command passed to us. First chop it up into
* individual tokens (seperated by spaces), then execute it if possible
* @param cmdstr string to be parsed and executed
*/
void IConsoleCmdExec(const char *cmdstr)
{
IConsoleCmd *cmd = NULL;
IConsoleAlias *alias = NULL;
IConsoleVar *var = NULL;
const char *cmdptr;
char *tokens[ICON_TOKEN_COUNT], tokenstream[ICON_MAX_STREAMSIZE];
uint t_index, tstream_i;
bool longtoken = false;
bool foundtoken = false;
if (cmdstr[0] == '#') return; // comments
for (cmdptr = cmdstr; *cmdptr != '\0'; cmdptr++) {
if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
IConsoleError("command contains malformed characters, aborting");
IConsolePrintF(CC_ERROR, "ERROR: command was: '%s'", cmdstr);
return;
}
}
if (_stdlib_con_developer)
IConsolePrintF(CC_DEBUG, "condbg: executing cmdline: '%s'", cmdstr);
memset(&tokens, 0, sizeof(tokens));
memset(&tokenstream, 0, sizeof(tokenstream));
/* 1. Split up commandline into tokens, seperated by spaces, commands
* enclosed in "" are taken as one token. We can only go as far as the amount
* of characters in our stream or the max amount of tokens we can handle */
for (cmdptr = cmdstr, t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
if (t_index >= lengthof(tokens) || tstream_i >= lengthof(tokenstream)) break;
switch (*cmdptr) {
case ' ': // Token seperator
if (!foundtoken) break;
if (longtoken) {
tokenstream[tstream_i] = *cmdptr;
} else {
tokenstream[tstream_i] = '\0';
foundtoken = false;
}
tstream_i++;
break;
case '"': // Tokens enclosed in "" are one token
longtoken = !longtoken;
break;
case '\\': // Escape character for ""
if (cmdptr[1] == '"' && tstream_i + 1 < lengthof(tokenstream)) {
tokenstream[tstream_i++] = *++cmdptr;
break;
}
/* fallthrough */
default: // Normal character
tokenstream[tstream_i++] = *cmdptr;
if (!foundtoken) {
tokens[t_index++] = &tokenstream[tstream_i - 1];
foundtoken = true;
}
break;
}
}
if (_stdlib_con_developer) {
uint i;
for (i = 0; tokens[i] != NULL; i++) {
IConsolePrintF(CC_DEBUG, "condbg: token %d is: '%s'", i, tokens[i]);
}
}
if (tokens[0] == '\0') return; // don't execute empty commands
/* 2. Determine type of command (cmd, alias or variable) and execute
* First try commands, then aliases, and finally variables. Execute
* the found action taking into account its hooking code
*/
cmd = IConsoleCmdGet(tokens[0]);
if (cmd != NULL) {
if (IConsoleHookHandle(&cmd->hook, ICONSOLE_HOOK_ACCESS)) {
IConsoleHookHandle(&cmd->hook, ICONSOLE_HOOK_PRE_ACTION);
if (cmd->proc(t_index, tokens)) { // index started with 0
IConsoleHookHandle(&cmd->hook, ICONSOLE_HOOK_POST_ACTION);
} else {
cmd->proc(0, NULL); // if command failed, give help
}
}
return;
}
t_index--; // ignore the variable-name for comfort for both aliases and variaables
alias = IConsoleAliasGet(tokens[0]);
if (alias != NULL) {
IConsoleAliasExec(alias, t_index, &tokens[1]);
return;
}
var = IConsoleVarGet(tokens[0]);
if (var != NULL) {
if (IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_ACCESS)) {
IConsoleVarExec(var, t_index, &tokens[1]);
}
return;
}
IConsoleError("command or variable not found");
}
| 26,923
|
C++
|
.cpp
| 755
| 32.521854
| 106
| 0.650871
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,037
|
dedicated.cpp
|
EnergeticBark_OpenTTD-3DS/src/dedicated.cpp
|
/* $Id$ */
/** @file dedicated.cpp Forking support for dedicated servers. */
#include "stdafx.h"
#ifdef ENABLE_NETWORK
#if defined(UNIX) && !defined(__MORPHOS__)
#include "variables.h"
#include <unistd.h>
#if defined(SUNOS) && !defined(_LP64) && !defined(_I32LPx)
/* Solaris has, in certain situation, pid_t defined as long, while in other
* cases it has it defined as int... this handles all cases nicely. */
# define PRINTF_PID_T "%ld"
#else
# define PRINTF_PID_T "%d"
#endif
void DedicatedFork()
{
/* Fork the program */
pid_t pid = fork();
switch (pid) {
case -1:
perror("Unable to fork");
exit(1);
case 0: { // We're the child
FILE *f;
/* Open the log-file to log all stuff too */
f = fopen(_log_file, "a");
if (f == NULL) {
perror("Unable to open logfile");
exit(1);
}
/* Redirect stdout and stderr to log-file */
if (dup2(fileno(f), fileno(stdout)) == -1) {
perror("Rerouting stdout");
exit(1);
}
if (dup2(fileno(f), fileno(stderr)) == -1) {
perror("Rerouting stderr");
exit(1);
}
break;
}
default:
/* We're the parent */
printf("Loading dedicated server...\n");
printf(" - Forked to background with pid " PRINTF_PID_T "\n", pid);
exit(0);
}
}
#endif
#else
/** Empty helper function call for NOT(UNIX and not MORPHOS) systems */
void DedicatedFork() {}
#endif /* ENABLE_NETWORK */
| 1,392
|
C++
|
.cpp
| 53
| 23.339623
| 75
| 0.64
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,038
|
cargotype.cpp
|
EnergeticBark_OpenTTD-3DS/src/cargotype.cpp
|
/* $Id$ */
/** @file cargotype.cpp Implementation of cargos. */
#include "stdafx.h"
#include "newgrf_cargo.h"
#include "cargotype.h"
#include "core/bitmath_func.hpp"
#include "table/sprites.h"
#include "table/strings.h"
#include "table/cargo_const.h"
CargoSpec _cargo[NUM_CARGO];
static const byte INVALID_CARGO = 0xFF;
/* Bitmask of cargo types available */
uint32 _cargo_mask;
void SetupCargoForClimate(LandscapeID l)
{
assert(l < lengthof(_default_climate_cargo));
/* Reset and disable all cargo types */
memset(_cargo, 0, sizeof(_cargo));
for (CargoID i = 0; i < lengthof(_cargo); i++) _cargo[i].bitnum = INVALID_CARGO;
_cargo_mask = 0;
for (CargoID i = 0; i < lengthof(_default_climate_cargo[l]); i++) {
CargoLabel cl = _default_climate_cargo[l][i];
/* Bzzt: check if cl is just an index into the cargo table */
if (cl < lengthof(_default_cargo)) {
/* Copy the indexed cargo */
_cargo[i] = _default_cargo[cl];
if (_cargo[i].bitnum != INVALID_CARGO) SetBit(_cargo_mask, i);
continue;
}
/* Loop through each of the default cargo types to see if
* the label matches */
for (uint j = 0; j < lengthof(_default_cargo); j++) {
if (_default_cargo[j].label == cl) {
_cargo[i] = _default_cargo[j];
/* Populate the available cargo mask */
SetBit(_cargo_mask, i);
break;
}
}
}
}
const CargoSpec *GetCargo(CargoID c)
{
assert(c < lengthof(_cargo));
return &_cargo[c];
}
bool CargoSpec::IsValid() const
{
return bitnum != INVALID_CARGO;
}
CargoID GetCargoIDByLabel(CargoLabel cl)
{
for (CargoID c = 0; c < lengthof(_cargo); c++) {
if (_cargo[c].bitnum == INVALID_CARGO) continue;
if (_cargo[c].label == cl) return c;
}
/* No matching label was found, so it is invalid */
return CT_INVALID;
}
/** Find the CargoID of a 'bitnum' value.
* @param bitnum 'bitnum' to find.
* @return First CargoID with the given bitnum, or CT_INVALID if not found.
*/
CargoID GetCargoIDByBitnum(uint8 bitnum)
{
if (bitnum == INVALID_CARGO) return CT_INVALID;
for (CargoID c = 0; c < lengthof(_cargo); c++) {
if (_cargo[c].bitnum == bitnum) return c;
}
/* No matching label was found, so it is invalid */
return CT_INVALID;
}
| 2,199
|
C++
|
.cpp
| 72
| 28.083333
| 81
| 0.682056
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,039
|
newgrf_sound.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_sound.cpp
|
/* $Id$ */
/** @file newgrf_sound.cpp Handling NewGRF provided sounds. */
#include "stdafx.h"
#include "engine_base.h"
#include "newgrf_engine.h"
#include "newgrf_sound.h"
#include "vehicle_base.h"
#include "sound_func.h"
static uint _sound_count = 0;
STATIC_OLD_POOL(SoundInternal, FileEntry, 3, 1000, NULL, NULL)
/* Allocate a new FileEntry */
FileEntry *AllocateFileEntry()
{
if (_sound_count == GetSoundInternalPoolSize()) {
if (!_SoundInternal_pool.AddBlockToPool()) return NULL;
}
return GetSoundInternal(_sound_count++);
}
void InitializeSoundPool()
{
_SoundInternal_pool.CleanPool();
_sound_count = 0;
/* Copy original sound data to the pool */
SndCopyToPool();
}
FileEntry *GetSound(uint index)
{
if (index >= GetNumSounds()) return NULL;
return GetSoundInternal(index);
}
uint GetNumSounds()
{
return _sound_count;
}
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
{
const GRFFile *file = GetEngineGRF(v->engine_type);
uint16 callback;
/* If the engine has no GRF ID associated it can't ever play any new sounds */
if (file == NULL) return false;
/* Check that the vehicle type uses the sound effect callback */
if (!HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_SOUND_EFFECT)) return false;
callback = GetVehicleCallback(CBID_VEHICLE_SOUND_EFFECT, event, 0, v->engine_type, v);
if (callback == CALLBACK_FAILED) return false;
if (callback >= GetNumOriginalSounds()) callback += file->sound_offset - GetNumOriginalSounds();
if (callback < GetNumSounds()) SndPlayVehicleFx((SoundFx)callback, v);
return true;
}
bool PlayTileSound(const GRFFile *file, uint16 sound_id, TileIndex tile)
{
if (sound_id >= GetNumOriginalSounds()) sound_id += file->sound_offset - GetNumOriginalSounds();
if (sound_id < GetNumSounds()) {
SndPlayTileFx((SoundFx)sound_id, tile);
return true;
}
return false;
}
| 1,876
|
C++
|
.cpp
| 57
| 31
| 97
| 0.748053
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,041
|
statusbar_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/statusbar_gui.cpp
|
/* $Id$ */
/** @file statusbar_gui.cpp The GUI for the bottom status bar. */
#include "stdafx.h"
#include "openttd.h"
#include "settings_type.h"
#include "date_func.h"
#include "gfx_func.h"
#include "news_func.h"
#include "company_func.h"
#include "string_func.h"
#include "strings_func.h"
#include "company_base.h"
#include "tilehighlight_func.h"
#include "news_gui.h"
#include "company_gui.h"
#include "window_gui.h"
#include "variables.h"
#include "window_func.h"
#include "statusbar_gui.h"
#include "table/strings.h"
#include "table/sprites.h"
static bool DrawScrollingStatusText(const NewsItem *ni, int pos, int width)
{
CopyInDParam(0, ni->params, lengthof(ni->params));
StringID str = ni->string_id;
char buf[512];
GetString(buf, str, lastof(buf));
const char *s = buf;
char buffer[256];
char *d = buffer;
const char *last = lastof(buffer);
for (;;) {
WChar c = Utf8Consume(&s);
if (c == 0) {
break;
} else if (c == '\n') {
if (d + 4 >= last) break;
d[0] = d[1] = d[2] = d[3] = ' ';
d += 4;
} else if (IsPrintable(c)) {
if (d + Utf8CharLen(c) >= last) break;
d += Utf8Encode(d, c);
}
}
*d = '\0';
DrawPixelInfo tmp_dpi;
if (!FillDrawPixelInfo(&tmp_dpi, 141, 1, width, 11)) return true;
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
int x = DoDrawString(buffer, pos, 0, TC_LIGHT_BLUE);
_cur_dpi = old_dpi;
return x > 0;
}
struct StatusBarWindow : Window {
bool saving;
int ticker_scroll;
int reminder_timeout;
enum {
TICKER_START = 360, ///< initial value of the ticker counter (scrolling news)
TICKER_STOP = -1280, ///< scrolling is finished when counter reaches this value
REMINDER_START = 91, ///< initial value of the reminder counter (right dot on the right)
REMINDER_STOP = 0, ///< reminder disappears when counter reaches this value
COUNTER_STEP = 2, ///< this is subtracted from active counters every tick
};
enum StatusbarWidget {
SBW_LEFT, ///< left part of the statusbar; date is shown there
SBW_MIDDLE, ///< middle part; current news or company name or *** SAVING *** or *** PAUSED ***
SBW_RIGHT, ///< right part; bank balance
};
StatusBarWindow(const WindowDesc *desc) : Window(desc)
{
CLRBITS(this->flags4, WF_WHITE_BORDER_MASK);
this->ticker_scroll = TICKER_STOP;
this->reminder_timeout = REMINDER_STOP;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
const Company *c = (_local_company == COMPANY_SPECTATOR) ? NULL : GetCompany(_local_company);
this->DrawWidgets();
SetDParam(0, _date);
DrawStringCentered(70, 1, (_pause_game || _settings_client.gui.status_long_date) ? STR_00AF : STR_00AE, TC_FROMSTRING);
if (c != NULL) {
/* Draw company money */
SetDParam(0, c->money);
DrawStringCentered(this->widget[SBW_RIGHT].left + 70, 1, STR_0004, TC_FROMSTRING);
}
/* Draw status bar */
if (this->saving) { // true when saving is active
DrawStringCenteredTruncated(this->widget[SBW_MIDDLE].left + 1, this->widget[SBW_MIDDLE].right - 1, 1, STR_SAVING_GAME, TC_FROMSTRING);
} else if (_do_autosave) {
DrawStringCenteredTruncated(this->widget[SBW_MIDDLE].left + 1, this->widget[SBW_MIDDLE].right - 1, 1, STR_032F_AUTOSAVE, TC_FROMSTRING);
} else if (_pause_game) {
DrawStringCenteredTruncated(this->widget[SBW_MIDDLE].left + 1, this->widget[SBW_MIDDLE].right - 1, 1, STR_0319_PAUSED, TC_FROMSTRING);
} else if (this->ticker_scroll > TICKER_STOP && FindWindowById(WC_NEWS_WINDOW, 0) == NULL && _statusbar_news_item.string_id != 0) {
/* Draw the scrolling news text */
if (!DrawScrollingStatusText(&_statusbar_news_item, this->ticker_scroll, this->widget[SBW_MIDDLE].right - this->widget[SBW_MIDDLE].left - 2)) {
this->ticker_scroll = TICKER_STOP;
if (c != NULL) {
/* This is the default text */
SetDParam(0, c->index);
DrawStringCenteredTruncated(this->widget[SBW_MIDDLE].left + 1, this->widget[SBW_MIDDLE].right - 1, 1, STR_02BA, TC_FROMSTRING);
}
}
} else {
if (c != NULL) {
/* This is the default text */
SetDParam(0, c->index);
DrawStringCenteredTruncated(this->widget[SBW_MIDDLE].left + 1, this->widget[SBW_MIDDLE].right - 1, 1, STR_02BA, TC_FROMSTRING);
}
}
if (this->reminder_timeout > 0) DrawSprite(SPR_BLOT, PALETTE_TO_RED, this->widget[SBW_MIDDLE].right - 11, 2);
}
virtual void OnInvalidateData(int data)
{
switch (data) {
default: NOT_REACHED();
case SBI_SAVELOAD_START: this->saving = true; break;
case SBI_SAVELOAD_FINISH: this->saving = false; break;
case SBI_SHOW_TICKER: this->ticker_scroll = TICKER_START; break;
case SBI_SHOW_REMINDER: this->reminder_timeout = REMINDER_START; break;
case SBI_NEWS_DELETED:
this->ticker_scroll = TICKER_STOP; // reset ticker ...
this->reminder_timeout = REMINDER_STOP; // ... and reminder
break;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case SBW_MIDDLE: ShowLastNewsMessage(); break;
case SBW_RIGHT: if (_local_company != COMPANY_SPECTATOR) ShowCompanyFinances(_local_company); break;
default: ResetObjectToPlace();
}
}
virtual void OnTick()
{
if (_pause_game) return;
if (this->ticker_scroll > TICKER_STOP) { // Scrolling text
this->ticker_scroll -= COUNTER_STEP;
this->InvalidateWidget(SBW_MIDDLE);
}
if (this->reminder_timeout > REMINDER_STOP) { // Red blot to show there are new unread newsmessages
this->reminder_timeout -= COUNTER_STEP;
} else if (this->reminder_timeout < REMINDER_STOP) {
this->reminder_timeout = REMINDER_STOP;
this->InvalidateWidget(SBW_MIDDLE);
}
}
};
static const Widget _main_status_widgets[] = {
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 139, 0, 11, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_RIGHT, COLOUR_GREY, 140, 179, 0, 11, 0x0, STR_02B7_SHOW_LAST_MESSAGE_OR_NEWS},
{ WWT_PUSHBTN, RESIZE_LR, COLOUR_GREY, 180, 319, 0, 11, 0x0, STR_NULL},
{ WIDGETS_END},
};
static WindowDesc _main_status_desc(
WDP_CENTER, 0, 320, 12, 640, 12,
WC_STATUS_BAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_NO_FOCUS,
_main_status_widgets
);
/**
* Checks whether the news ticker is currently being used.
*/
bool IsNewsTickerShown()
{
const StatusBarWindow *w = dynamic_cast<StatusBarWindow*>(FindWindowById(WC_STATUS_BAR, 0));
return w != NULL && w->ticker_scroll > StatusBarWindow::TICKER_STOP;
}
void ShowStatusBar()
{
_main_status_desc.top = _screen.height - 12;
new StatusBarWindow(&_main_status_desc);
}
| 6,580
|
C++
|
.cpp
| 175
| 34.851429
| 146
| 0.681725
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,042
|
station_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/station_cmd.cpp
|
/* $Id$ */
/** @file station_cmd.cpp Handling of station tiles. */
#include "stdafx.h"
#include "openttd.h"
#include "aircraft.h"
#include "bridge_map.h"
#include "cmd_helper.h"
#include "landscape.h"
#include "viewport_func.h"
#include "command_func.h"
#include "town.h"
#include "news_func.h"
#include "train.h"
#include "roadveh.h"
#include "industry_map.h"
#include "newgrf_station.h"
#include "newgrf_commons.h"
#include "yapf/yapf.h"
#include "road_internal.h" /* For drawing catenary/checking road removal */
#include "variables.h"
#include "autoslope.h"
#include "water.h"
#include "station_gui.h"
#include "strings_func.h"
#include "functions.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "string_func.h"
#include "oldpool_func.h"
#include "animated_tile_func.h"
#include "elrail_func.h"
#include "table/strings.h"
DEFINE_OLD_POOL_GENERIC(Station, Station)
DEFINE_OLD_POOL_GENERIC(RoadStop, RoadStop)
/**
* Check whether the given tile is a hangar.
* @param t the tile to of whether it is a hangar.
* @pre IsTileType(t, MP_STATION)
* @return true if and only if the tile is a hangar.
*/
bool IsHangar(TileIndex t)
{
assert(IsTileType(t, MP_STATION));
const Station *st = GetStationByTile(t);
const AirportFTAClass *apc = st->Airport();
for (uint i = 0; i < apc->nof_depots; i++) {
if (st->airport_tile + ToTileIndexDiff(apc->airport_depots[i]) == t) return true;
}
return false;
}
RoadStop *GetRoadStopByTile(TileIndex tile, RoadStopType type)
{
const Station *st = GetStationByTile(tile);
for (RoadStop *rs = st->GetPrimaryRoadStop(type);; rs = rs->next) {
if (rs->xy == tile) return rs;
assert(rs->next != NULL);
}
}
static uint GetNumRoadStopsInStation(const Station *st, RoadStopType type)
{
uint num = 0;
assert(st != NULL);
for (const RoadStop *rs = st->GetPrimaryRoadStop(type); rs != NULL; rs = rs->next) {
num++;
}
return num;
}
#define CHECK_STATIONS_ERR ((Station*)-1)
static Station *GetStationAround(TileIndex tile, int w, int h, StationID closest_station)
{
/* check around to see if there's any stations there */
BEGIN_TILE_LOOP(tile_cur, w + 2, h + 2, tile - TileDiffXY(1, 1))
if (IsTileType(tile_cur, MP_STATION)) {
StationID t = GetStationIndex(tile_cur);
if (closest_station == INVALID_STATION) {
closest_station = t;
} else if (closest_station != t) {
_error_message = STR_3006_ADJOINS_MORE_THAN_ONE_EXISTING;
return CHECK_STATIONS_ERR;
}
}
END_TILE_LOOP(tile_cur, w + 2, h + 2, tile - TileDiffXY(1, 1))
return (closest_station == INVALID_STATION) ? NULL : GetStation(closest_station);
}
/**
* Function to check whether the given tile matches some criterion.
* @param tile the tile to check
* @return true if it matches, false otherwise
*/
typedef bool (*CMSAMatcher)(TileIndex tile);
/**
* Counts the numbers of tiles matching a specific type in the area around
* @param tile the center tile of the 'count area'
* @param type the type of tile searched for
* @param industry when type == MP_INDUSTRY, the type of the industry,
* in all other cases this parameter is ignored
* @return the result the noumber of matching tiles around
*/
static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
{
int num = 0;
for (int dx = -3; dx <= 3; dx++) {
for (int dy = -3; dy <= 3; dy++) {
TileIndex t = TileAddWrap(tile, dx, dy);
if (t != INVALID_TILE && cmp(t)) num++;
}
}
return num;
}
/**
* Check whether the tile is a mine.
* @param tile the tile to investigate.
* @return true if and only if the tile is a mine
*/
static bool CMSAMine(TileIndex tile)
{
/* No industry */
if (!IsTileType(tile, MP_INDUSTRY)) return false;
const Industry *ind = GetIndustryByTile(tile);
/* No extractive industry */
if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
/* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine */
if (ind->produced_cargo[i] != CT_INVALID && (GetCargo(ind->produced_cargo[i])->classes & CC_LIQUID) == 0) return true;
}
return false;
}
/**
* Check whether the tile is water.
* @param tile the tile to investigate.
* @return true if and only if the tile is a mine
*/
static bool CMSAWater(TileIndex tile)
{
return IsTileType(tile, MP_WATER) && IsWater(tile);
}
/**
* Check whether the tile is a tree.
* @param tile the tile to investigate.
* @return true if and only if the tile is a mine
*/
static bool CMSATree(TileIndex tile)
{
return IsTileType(tile, MP_TREES);
}
/**
* Check whether the tile is a forest.
* @param tile the tile to investigate.
* @return true if and only if the tile is a mine
*/
static bool CMSAForest(TileIndex tile)
{
/* No industry */
if (!IsTileType(tile, MP_INDUSTRY)) return false;
const Industry *ind = GetIndustryByTile(tile);
/* No extractive industry */
if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
/* The industry produces wood. */
if (ind->produced_cargo[i] != CT_INVALID && GetCargo(ind->produced_cargo[i])->label == 'WOOD') return true;
}
return false;
}
#define M(x) ((x) - STR_SV_STNAME)
enum StationNaming {
STATIONNAMING_RAIL = 0,
STATIONNAMING_ROAD = 0,
STATIONNAMING_AIRPORT,
STATIONNAMING_OILRIG,
STATIONNAMING_DOCK,
STATIONNAMING_BUOY,
STATIONNAMING_HELIPORT,
};
/** Information to handle station action 0 property 24 correctly */
struct StationNameInformation {
uint32 free_names; ///< Current bitset of free names (we can remove names).
bool *indtypes; ///< Array of bools telling whether an industry type has been found.
};
/**
* Find a station action 0 property 24 station name, or reduce the
* free_names if needed.
* @param tile the tile to search
* @param user_data the StationNameInformation to base the search on
* @return true if the tile contains an industry that has not given
* it's name to one of the other stations in town.
*/
static bool FindNearIndustryName(TileIndex tile, void *user_data)
{
/* All already found industry types */
StationNameInformation *sni = (StationNameInformation*)user_data;
if (!IsTileType(tile, MP_INDUSTRY)) return false;
/* If the station name is undefined it means that it doesn't name a station */
IndustryType indtype = GetIndustryType(tile);
if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
/* In all cases if an industry that provides a name is found two of
* the standard names will be disabled. */
sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
return !sni->indtypes[indtype];
}
static StringID GenerateStationName(Station *st, TileIndex tile, int flag)
{
static const uint32 _gen_station_name_bits[] = {
0, // 0
1 << M(STR_SV_STNAME_AIRPORT), // 1
1 << M(STR_SV_STNAME_OILFIELD), // 2
1 << M(STR_SV_STNAME_DOCKS), // 3
0x1FF << M(STR_SV_STNAME_BUOY_1), // 4
1 << M(STR_SV_STNAME_HELIPORT), // 5
};
const Town *t = st->town;
uint32 free_names = UINT32_MAX;
bool indtypes[NUM_INDUSTRYTYPES];
memset(indtypes, 0, sizeof(indtypes));
const Station *s;
FOR_ALL_STATIONS(s) {
if (s != st && s->town == t) {
if (s->indtype != IT_INVALID) {
indtypes[s->indtype] = true;
continue;
}
uint str = M(s->string_id);
if (str <= 0x20) {
if (str == M(STR_SV_STNAME_FOREST)) {
str = M(STR_SV_STNAME_WOODS);
}
ClrBit(free_names, str);
}
}
}
if (flag != STATIONNAMING_BUOY) {
TileIndex indtile = tile;
StationNameInformation sni = { free_names, indtypes };
if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
/* An industry has been found nearby */
IndustryType indtype = GetIndustryType(indtile);
const IndustrySpec *indsp = GetIndustrySpec(indtype);
/* STR_NULL means it only disables oil rig/mines */
if (indsp->station_name != STR_NULL) {
st->indtype = indtype;
return STR_SV_STNAME_FALLBACK;
}
}
/* Oil rigs/mines name could be marked not free by looking for a near by industry. */
free_names = sni.free_names;
}
/* check default names */
uint32 tmp = free_names & _gen_station_name_bits[flag];
if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
/* check mine? */
if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
if (CountMapSquareAround(tile, CMSAMine) >= 2) {
return STR_SV_STNAME_MINES;
}
}
/* check close enough to town to get central as name? */
if (DistanceMax(tile, t->xy) < 8) {
if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
}
/* Check lakeside */
if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
DistanceFromEdge(tile) < 20 &&
CountMapSquareAround(tile, CMSAWater) >= 5) {
return STR_SV_STNAME_LAKESIDE;
}
/* Check woods */
if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
CountMapSquareAround(tile, CMSATree) >= 8 ||
CountMapSquareAround(tile, CMSAForest) >= 2)
) {
return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
}
/* check elevation compared to town */
uint z = GetTileZ(tile);
uint z2 = GetTileZ(t->xy);
if (z < z2) {
if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
} else if (z > z2) {
if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
}
/* check direction compared to town */
static const int8 _direction_and_table[] = {
~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
};
free_names &= _direction_and_table[
(TileX(tile) < TileX(t->xy)) +
(TileY(tile) < TileY(t->xy)) * 2];
tmp = free_names & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
}
#undef M
/**
* Find the closest deleted station of the current company
* @param tile the tile to search from.
* @return the closest station or NULL if too far.
*/
static Station *GetClosestDeletedStation(TileIndex tile)
{
uint threshold = 8;
Station *best_station = NULL;
Station *st;
FOR_ALL_STATIONS(st) {
if (st->facilities == 0 && st->owner == _current_company) {
uint cur_dist = DistanceManhattan(tile, st->xy);
if (cur_dist < threshold) {
threshold = cur_dist;
best_station = st;
}
}
}
return best_station;
}
/** Update the virtual coords needed to draw the station sign.
* @param st Station to update for.
*/
static void UpdateStationVirtCoord(Station *st)
{
Point pt = RemapCoords2(TileX(st->xy) * TILE_SIZE, TileY(st->xy) * TILE_SIZE);
pt.y -= 32;
if (st->facilities & FACIL_AIRPORT && st->airport_type == AT_OILRIG) pt.y -= 16;
SetDParam(0, st->index);
SetDParam(1, st->facilities);
UpdateViewportSignPos(&st->sign, pt.x, pt.y, STR_305C_0);
}
/** Update the virtual coords needed to draw the station sign for all stations. */
void UpdateAllStationVirtCoord()
{
Station *st;
FOR_ALL_STATIONS(st) {
UpdateStationVirtCoord(st);
}
}
/**
* Update the station virt coords while making the modified parts dirty.
*
* This function updates the virt coords and mark the modified parts as dirty
*
* @param st The station to update the virt coords
* @ingroup dirty
*/
static void UpdateStationVirtCoordDirty(Station *st)
{
st->MarkDirty();
UpdateStationVirtCoord(st);
st->MarkDirty();
}
/** Get a mask of the cargo types that the station accepts.
* @param st Station to query
* @return the expected mask
*/
static uint GetAcceptanceMask(const Station *st)
{
uint mask = 0;
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) mask |= 1 << i;
}
return mask;
}
/** Items contains the two cargo names that are to be accepted or rejected.
* msg is the string id of the message to display.
*/
static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
{
for (uint i = 0; i < num_items; i++) {
SetDParam(i + 1, GetCargo(cargo[i])->name);
}
SetDParam(0, st->index);
AddNewsItem(msg, NS_ACCEPTANCE, st->xy, st->index);
}
/**
* Get a list of the cargo types being produced around the tile (in a rectangle).
* @param produced Destination array of produced cargo
* @param tile Northtile of area
* @param w X extent of the area
* @param h Y extent of the area
* @param rad Search radius in addition to the given area
*/
void GetProductionAroundTiles(AcceptedCargo produced, TileIndex tile,
int w, int h, int rad)
{
memset(produced, 0, sizeof(AcceptedCargo)); // sizeof(AcceptedCargo) != sizeof(produced) (== sizeof(uint *))
int x = TileX(tile);
int y = TileY(tile);
/* expand the region by rad tiles on each side
* while making sure that we remain inside the board. */
int x2 = min(x + w + rad, MapSizeX());
int x1 = max(x - rad, 0);
int y2 = min(y + h + rad, MapSizeY());
int y1 = max(y - rad, 0);
assert(x1 < x2);
assert(y1 < y2);
assert(w > 0);
assert(h > 0);
for (int yc = y1; yc != y2; yc++) {
for (int xc = x1; xc != x2; xc++) {
TileIndex tile = TileXY(xc, yc);
if (!IsTileType(tile, MP_STATION)) {
GetProducedCargoProc *gpc = _tile_type_procs[GetTileType(tile)]->get_produced_cargo_proc;
if (gpc != NULL) {
CargoID cargos[256]; // Required for CBID_HOUSE_PRODUCE_CARGO.
memset(cargos, CT_INVALID, sizeof(cargos));
gpc(tile, cargos);
for (uint i = 0; i < lengthof(cargos); ++i) {
if (cargos[i] != CT_INVALID) produced[cargos[i]]++;
}
}
}
}
}
}
/**
* Get a list of the cargo types that are accepted around the tile.
* @param accepts Destination array of accepted cargo
* @param tile Center of the search area
* @param w X extent of area
* @param h Y extent of area
* @param rad Search radius in addition to given area
*/
void GetAcceptanceAroundTiles(AcceptedCargo accepts, TileIndex tile,
int w, int h, int rad)
{
memset(accepts, 0, sizeof(AcceptedCargo)); // sizeof(AcceptedCargo) != sizeof(accepts) (== sizeof(uint *))
int x = TileX(tile);
int y = TileY(tile);
/* expand the region by rad tiles on each side
* while making sure that we remain inside the board. */
int x2 = min(x + w + rad, MapSizeX());
int y2 = min(y + h + rad, MapSizeY());
int x1 = max(x - rad, 0);
int y1 = max(y - rad, 0);
assert(x1 < x2);
assert(y1 < y2);
assert(w > 0);
assert(h > 0);
for (int yc = y1; yc != y2; yc++) {
for (int xc = x1; xc != x2; xc++) {
TileIndex tile = TileXY(xc, yc);
if (!IsTileType(tile, MP_STATION)) {
AcceptedCargo ac;
GetAcceptedCargo(tile, ac);
for (uint i = 0; i < lengthof(ac); ++i) accepts[i] += ac[i];
}
}
}
}
static inline void MergePoint(Rect *rect, TileIndex tile)
{
int x = TileX(tile);
int y = TileY(tile);
if (rect->left > x) rect->left = x;
if (rect->bottom > y) rect->bottom = y;
if (rect->right < x) rect->right = x;
if (rect->top < y) rect->top = y;
}
/** Update the acceptance for a station.
* @param st Station to update
* @param show_msg controls whether to display a message that acceptance was changed.
*/
static void UpdateStationAcceptance(Station *st, bool show_msg)
{
/* Don't update acceptance for a buoy */
if (st->IsBuoy()) return;
Rect rect;
rect.left = MapSizeX();
rect.bottom = MapSizeY();
rect.right = 0;
rect.top = 0;
/* old accepted goods types */
uint old_acc = GetAcceptanceMask(st);
/* Put all the tiles that span an area in the table. */
if (st->train_tile != INVALID_TILE) {
MergePoint(&rect, st->train_tile);
MergePoint(&rect, st->train_tile + TileDiffXY(st->trainst_w - 1, st->trainst_h - 1));
}
if (st->airport_tile != INVALID_TILE) {
const AirportFTAClass *afc = st->Airport();
MergePoint(&rect, st->airport_tile);
MergePoint(&rect, st->airport_tile + TileDiffXY(afc->size_x - 1, afc->size_y - 1));
}
if (st->dock_tile != INVALID_TILE) {
MergePoint(&rect, st->dock_tile);
if (IsDockTile(st->dock_tile)) {
MergePoint(&rect, st->dock_tile + TileOffsByDiagDir(GetDockDirection(st->dock_tile)));
} // else OilRig
}
for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) {
MergePoint(&rect, rs->xy);
}
for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) {
MergePoint(&rect, rs->xy);
}
/* And retrieve the acceptance. */
AcceptedCargo accepts;
assert((rect.right >= rect.left) == !st->rect.IsEmpty());
if (rect.right >= rect.left) {
assert(rect.left == st->rect.left);
assert(rect.top == st->rect.bottom);
assert(rect.right == st->rect.right);
assert(rect.bottom == st->rect.top);
GetAcceptanceAroundTiles(
accepts,
TileXY(rect.left, rect.bottom),
rect.right - rect.left + 1,
rect.top - rect.bottom + 1,
st->GetCatchmentRadius()
);
} else {
memset(accepts, 0, sizeof(accepts));
}
/* Adjust in case our station only accepts fewer kinds of goods */
for (CargoID i = 0; i < NUM_CARGO; i++) {
uint amt = min(accepts[i], 15);
/* Make sure the station can accept the goods type. */
bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
if ((!is_passengers && !(st->facilities & (byte)~FACIL_BUS_STOP)) ||
(is_passengers && !(st->facilities & (byte)~FACIL_TRUCK_STOP))) {
amt = 0;
}
SB(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, amt >= 8);
}
/* Only show a message in case the acceptance was actually changed. */
uint new_acc = GetAcceptanceMask(st);
if (old_acc == new_acc) return;
/* show a message to report that the acceptance was changed? */
if (show_msg && st->owner == _local_company && st->facilities) {
/* List of accept and reject strings for different number of
* cargo types */
static const StringID accept_msg[] = {
STR_3040_NOW_ACCEPTS,
STR_3041_NOW_ACCEPTS_AND,
};
static const StringID reject_msg[] = {
STR_303E_NO_LONGER_ACCEPTS,
STR_303F_NO_LONGER_ACCEPTS_OR,
};
/* Array of accepted and rejected cargo types */
CargoID accepts[2] = { CT_INVALID, CT_INVALID };
CargoID rejects[2] = { CT_INVALID, CT_INVALID };
uint num_acc = 0;
uint num_rej = 0;
/* Test each cargo type to see if its acceptange has changed */
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (HasBit(new_acc, i)) {
if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
/* New cargo is accepted */
accepts[num_acc++] = i;
}
} else {
if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
/* Old cargo is no longer accepted */
rejects[num_rej++] = i;
}
}
}
/* Show news message if there are any changes */
if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
}
/* redraw the station view since acceptance changed */
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_ACCEPTLIST);
}
static void UpdateStationSignCoord(Station *st)
{
const StationRect *r = &st->rect;
if (r->IsEmpty()) return; // no tiles belong to this station
/* clamp sign coord to be inside the station rect */
st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
UpdateStationVirtCoordDirty(st);
}
/** This is called right after a station was deleted.
* It checks if the whole station is free of substations, and if so, the station will be
* deleted after a little while.
* @param st Station
*/
static void DeleteStationIfEmpty(Station *st)
{
if (st->facilities == 0) {
st->delete_ctr = 0;
InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
}
/* station remains but it probably lost some parts - station sign should stay in the station boundaries */
UpdateStationSignCoord(st);
}
static CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
/** Tries to clear the given area.
* @param tile TileIndex to start check
* @param w width of search area
* @param h height of search area
* @param flags operation to perform
* @param invalid_dirs prohibited directions (set of DiagDirections)
* @param station StationID to be queried and returned if available
* @param check_clear if clearing tile should be performed (in wich case, cost will be added)
* @return the cost in case of success, or an error code if it failed.
*/
CommandCost CheckFlatLandBelow(TileIndex tile, uint w, uint h, DoCommandFlag flags, uint invalid_dirs, StationID *station, bool check_clear = true)
{
CommandCost cost(EXPENSES_CONSTRUCTION);
int allowed_z = -1;
BEGIN_TILE_LOOP(tile_cur, w, h, tile) {
if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) {
return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
}
if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;
uint z;
Slope tileh = GetTileSlope(tile_cur, &z);
/* Prohibit building if
* 1) The tile is "steep" (i.e. stretches two height levels)
* 2) The tile is non-flat and the build_on_slopes switch is disabled
*/
if (IsSteepSlope(tileh) ||
((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
}
int flat_z = z;
if (tileh != SLOPE_FLAT) {
/* need to check so the entrance to the station is not pointing at a slope.
* This must be valid for all station tiles, as the user can remove single station tiles. */
if ((HasBit(invalid_dirs, DIAGDIR_NE) && !(tileh & SLOPE_NE)) ||
(HasBit(invalid_dirs, DIAGDIR_SE) && !(tileh & SLOPE_SE)) ||
(HasBit(invalid_dirs, DIAGDIR_SW) && !(tileh & SLOPE_SW)) ||
(HasBit(invalid_dirs, DIAGDIR_NW) && !(tileh & SLOPE_NW))) {
return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
}
cost.AddCost(_price.terraform);
flat_z += TILE_HEIGHT;
}
/* get corresponding flat level and make sure that all parts of the station have the same level. */
if (allowed_z == -1) {
/* first tile */
allowed_z = flat_z;
} else if (allowed_z != flat_z) {
return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
}
/* if station is set, then we have special handling to allow building on top of already existing stations.
* so station points to INVALID_STATION if we can build on any station.
* Or it points to a station if we're only allowed to build on exactly that station. */
if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
if (!IsRailwayStation(tile_cur)) {
return ClearTile_Station(tile_cur, DC_AUTO); // get error message
} else {
StationID st = GetStationIndex(tile_cur);
if (*station == INVALID_STATION) {
*station = st;
} else if (*station != st) {
return_cmd_error(STR_3006_ADJOINS_MORE_THAN_ONE_EXISTING);
}
}
} else if (check_clear) {
CommandCost ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return ret;
cost.AddCost(ret);
}
} END_TILE_LOOP(tile_cur, w, h, tile)
return cost;
}
static bool CanExpandRailroadStation(const Station *st, uint *fin, Axis axis)
{
uint curw = st->trainst_w;
uint curh = st->trainst_h;
TileIndex tile = fin[0];
uint w = fin[1];
uint h = fin[2];
if (_settings_game.station.nonuniform_stations) {
/* determine new size of train station region.. */
int x = min(TileX(st->train_tile), TileX(tile));
int y = min(TileY(st->train_tile), TileY(tile));
curw = max(TileX(st->train_tile) + curw, TileX(tile) + w) - x;
curh = max(TileY(st->train_tile) + curh, TileY(tile) + h) - y;
tile = TileXY(x, y);
} else {
/* do not allow modifying non-uniform stations,
* the uniform-stations code wouldn't handle it well */
BEGIN_TILE_LOOP(t, st->trainst_w, st->trainst_h, st->train_tile)
if (!st->TileBelongsToRailStation(t)) { // there may be adjoined station
_error_message = STR_NONUNIFORM_STATIONS_DISALLOWED;
return false;
}
END_TILE_LOOP(t, st->trainst_w, st->trainst_h, st->train_tile)
/* check so the orientation is the same */
if (GetRailStationAxis(st->train_tile) != axis) {
_error_message = STR_NONUNIFORM_STATIONS_DISALLOWED;
return false;
}
/* check if the new station adjoins the old station in either direction */
if (curw == w && st->train_tile == tile + TileDiffXY(0, h)) {
/* above */
curh += h;
} else if (curw == w && st->train_tile == tile - TileDiffXY(0, curh)) {
/* below */
tile -= TileDiffXY(0, curh);
curh += h;
} else if (curh == h && st->train_tile == tile + TileDiffXY(w, 0)) {
/* to the left */
curw += w;
} else if (curh == h && st->train_tile == tile - TileDiffXY(curw, 0)) {
/* to the right */
tile -= TileDiffXY(curw, 0);
curw += w;
} else {
_error_message = STR_NONUNIFORM_STATIONS_DISALLOWED;
return false;
}
}
/* make sure the final size is not too big. */
if (curw > _settings_game.station.station_spread || curh > _settings_game.station.station_spread) {
_error_message = STR_306C_STATION_TOO_SPREAD_OUT;
return false;
}
/* now tile contains the new value for st->train_tile
* curw, curh contain the new value for width and height */
fin[0] = tile;
fin[1] = curw;
fin[2] = curh;
return true;
}
static inline byte *CreateSingle(byte *layout, int n)
{
int i = n;
do *layout++ = 0; while (--i);
layout[((n - 1) >> 1) - n] = 2;
return layout;
}
static inline byte *CreateMulti(byte *layout, int n, byte b)
{
int i = n;
do *layout++ = b; while (--i);
if (n > 4) {
layout[0 - n] = 0;
layout[n - 1 - n] = 0;
}
return layout;
}
static void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
{
if (statspec != NULL && statspec->lengths >= plat_len &&
statspec->platforms[plat_len - 1] >= numtracks &&
statspec->layouts[plat_len - 1][numtracks - 1]) {
/* Custom layout defined, follow it. */
memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
plat_len * numtracks);
return;
}
if (plat_len == 1) {
CreateSingle(layout, numtracks);
} else {
if (numtracks & 1) layout = CreateSingle(layout, plat_len);
numtracks >>= 1;
while (--numtracks >= 0) {
layout = CreateMulti(layout, plat_len, 4);
layout = CreateMulti(layout, plat_len, 6);
}
}
}
/** Build railroad station
* @param tile_org starting position of station dragging/placement
* @param flags operation to perform
* @param p1 various bitstuffed elements
* - p1 = (bit 0- 3) - railtype (p1 & 0xF)
* - p1 = (bit 4) - orientation (Axis)
* - p1 = (bit 8-15) - number of tracks
* - p1 = (bit 16-23) - platform length
* - p1 = (bit 24) - allow stations directly adjacent to other stations.
* @param p2 various bitstuffed elements
* - p2 = (bit 0- 7) - custom station class
* - p2 = (bit 8-15) - custom station id
* - p2 = (bit 16-31) - station ID to join (INVALID_STATION if build new one)
*/
CommandCost CmdBuildRailroadStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
/* Does the authority allow this? */
if (!CheckIfAuthorityAllowsNewStation(tile_org, flags)) return CMD_ERROR;
if (!ValParamRailtype((RailType)(p1 & 0xF))) return CMD_ERROR;
/* unpack parameters */
Axis axis = Extract<Axis, 4>(p1);
uint numtracks = GB(p1, 8, 8);
uint plat_len = GB(p1, 16, 8);
int w_org, h_org;
if (axis == AXIS_X) {
w_org = plat_len;
h_org = numtracks;
} else {
h_org = plat_len;
w_org = numtracks;
}
StationID station_to_join = GB(p2, 16, 16);
bool distant_join = (station_to_join != INVALID_STATION);
if (distant_join && (!_settings_game.station.distant_join_stations || !IsValidStationID(station_to_join))) return CMD_ERROR;
if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
/* these values are those that will be stored in train_tile and station_platforms */
uint finalvalues[3];
finalvalues[0] = tile_org;
finalvalues[1] = w_org;
finalvalues[2] = h_org;
/* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
StationID est = INVALID_STATION;
/* If DC_EXEC is in flag, do not want to pass it to CheckFlatLandBelow, because of a nice bug
* for detail info, see:
* https://sourceforge.net/tracker/index.php?func=detail&aid=1029064&group_id=103924&atid=636365 */
CommandCost ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags & ~DC_EXEC, 5 << axis, _settings_game.station.nonuniform_stations ? &est : NULL);
if (CmdFailed(ret)) return ret;
CommandCost cost(EXPENSES_CONSTRUCTION, ret.GetCost() + (numtracks * _price.train_station_track + _price.train_station_length) * plat_len);
Station *st = NULL;
bool check_surrounding = true;
if (_settings_game.station.adjacent_stations) {
if (est != INVALID_STATION) {
if (HasBit(p1, 24) && est != station_to_join) {
/* You can't build an adjacent station over the top of one that
* already exists. */
return_cmd_error(STR_MUST_REMOVE_RAILWAY_STATION_FIRST);
} else {
/* Extend the current station, and don't check whether it will
* be near any other stations. */
st = GetStation(est);
check_surrounding = false;
}
} else {
/* There's no station here. Don't check the tiles surrounding this
* one if the company wanted to build an adjacent station. */
if (HasBit(p1, 24)) check_surrounding = false;
}
}
if (check_surrounding) {
/* Make sure there are no similar stations around us. */
st = GetStationAround(tile_org, w_org, h_org, est);
if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
}
/* Distant join */
if (st == NULL && distant_join) st = GetStation(station_to_join);
/* See if there is a deleted station close to us. */
if (st == NULL) st = GetClosestDeletedStation(tile_org);
if (st != NULL) {
/* Reuse an existing station. */
if (st->owner != _current_company)
return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);
if (st->train_tile != INVALID_TILE) {
/* check if we want to expanding an already existing station? */
if (!_settings_game.station.join_stations)
return_cmd_error(STR_3005_TOO_CLOSE_TO_ANOTHER_RAILROAD);
if (!CanExpandRailroadStation(st, finalvalues, axis))
return CMD_ERROR;
}
/* XXX can't we pack this in the "else" part of the if above? */
if (!st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST)) return CMD_ERROR;
} else {
/* allocate and initialize new station */
if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
if (flags & DC_EXEC) {
st = new Station(tile_org);
st->town = ClosestTownFromTile(tile_org, UINT_MAX);
st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
if (IsValidCompanyID(_current_company)) {
SetBit(st->town->have_ratings, _current_company);
}
}
}
/* Check if the given station class is valid */
if (GB(p2, 0, 8) >= GetNumStationClasses()) return CMD_ERROR;
/* Check if we can allocate a custom stationspec to this station */
const StationSpec *statspec = GetCustomStationSpec((StationClassID)GB(p2, 0, 8), GB(p2, 8, 8));
int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
if (specindex == -1) return_cmd_error(STR_TOO_MANY_STATION_SPECS);
if (statspec != NULL) {
/* Perform NewStation checks */
/* Check if the station size is permitted */
if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
return CMD_ERROR;
}
/* Check if the station is buildable */
if (HasBit(statspec->callbackmask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
return CMD_ERROR;
}
}
if (flags & DC_EXEC) {
TileIndexDiff tile_delta;
byte *layout_ptr;
byte numtracks_orig;
Track track;
/* Now really clear the land below the station
* It should never return CMD_ERROR.. but you never know ;)
* (a bit strange function name for it, but it really does clear the land, when DC_EXEC is in flags) */
ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags, 5 << axis, _settings_game.station.nonuniform_stations ? &est : NULL);
if (CmdFailed(ret)) return ret;
st->train_tile = finalvalues[0];
st->AddFacility(FACIL_TRAIN, finalvalues[0]);
st->trainst_w = finalvalues[1];
st->trainst_h = finalvalues[2];
st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
if (statspec != NULL) {
/* Include this station spec's animation trigger bitmask
* in the station's cached copy. */
st->cached_anim_triggers |= statspec->anim_triggers;
}
tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
track = AxisToTrack(axis);
layout_ptr = AllocaM(byte, numtracks * plat_len);
GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
numtracks_orig = numtracks;
SmallVector<Vehicle*, 4> affected_vehicles;
do {
TileIndex tile = tile_org;
int w = plat_len;
do {
byte layout = *layout_ptr++;
if (IsRailwayStationTile(tile) && GetRailwayStationReservation(tile)) {
/* Check for trains having a reservation for this tile. */
Vehicle *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
if (v != NULL) {
FreeTrainTrackReservation(v);
*affected_vehicles.Append() = v;
if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(GetVehicleTrackdir(v)), false);
for (; v->Next() != NULL; v = v->Next()) ;
if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(GetVehicleTrackdir(v))), false);
}
}
byte old_specindex = IsTileType(tile, MP_STATION) ? GetCustomStationSpecIndex(tile) : 0;
MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, (RailType)GB(p1, 0, 4));
/* Free the spec if we overbuild something */
DeallocateSpecFromStation(st, old_specindex);
SetCustomStationSpecIndex(tile, specindex);
SetStationTileRandomBits(tile, GB(Random(), 0, 4));
SetStationAnimationFrame(tile, 0);
if (statspec != NULL) {
/* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
/* As the station is not yet completely finished, the station does not yet exist. */
uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
if (callback != CALLBACK_FAILED && callback < 8) SetStationGfx(tile, (callback & ~1) + axis);
/* Trigger station animation -- after building? */
StationAnimationTrigger(st, tile, STAT_ANIM_BUILT);
}
tile += tile_delta;
} while (--w);
AddTrackToSignalBuffer(tile_org, track, _current_company);
YapfNotifyTrackLayoutChange(tile_org, track);
tile_org += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
} while (--numtracks);
for (uint i = 0; i < affected_vehicles.Length(); ++i) {
/* Restore reservations of trains. */
Vehicle *v = affected_vehicles[i];
if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(GetVehicleTrackdir(v)), true);
TryPathReserve(v, true, true);
for (; v->Next() != NULL; v = v->Next()) ;
if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(GetVehicleTrackdir(v))), true);
}
st->MarkTilesDirty(false);
UpdateStationVirtCoordDirty(st);
UpdateStationAcceptance(st, false);
InvalidateWindowData(WC_SELECT_STATION, 0, 0);
InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_TRAINS);
}
return cost;
}
static void MakeRailwayStationAreaSmaller(Station *st)
{
uint w = st->trainst_w;
uint h = st->trainst_h;
TileIndex tile = st->train_tile;
restart:
/* too small? */
if (w != 0 && h != 0) {
/* check the left side, x = constant, y changes */
for (uint i = 0; !st->TileBelongsToRailStation(tile + TileDiffXY(0, i));) {
/* the left side is unused? */
if (++i == h) {
tile += TileDiffXY(1, 0);
w--;
goto restart;
}
}
/* check the right side, x = constant, y changes */
for (uint i = 0; !st->TileBelongsToRailStation(tile + TileDiffXY(w - 1, i));) {
/* the right side is unused? */
if (++i == h) {
w--;
goto restart;
}
}
/* check the upper side, y = constant, x changes */
for (uint i = 0; !st->TileBelongsToRailStation(tile + TileDiffXY(i, 0));) {
/* the left side is unused? */
if (++i == w) {
tile += TileDiffXY(0, 1);
h--;
goto restart;
}
}
/* check the lower side, y = constant, x changes */
for (uint i = 0; !st->TileBelongsToRailStation(tile + TileDiffXY(i, h - 1));) {
/* the left side is unused? */
if (++i == w) {
h--;
goto restart;
}
}
} else {
tile = INVALID_TILE;
}
st->trainst_w = w;
st->trainst_h = h;
st->train_tile = tile;
}
/** Remove a single tile from a railroad station.
* This allows for custom-built station with holes and weird layouts
* @param tile tile of station piece to remove
* @param flags operation to perform
* @param p1 start_tile
* @param p2 unused
*/
CommandCost CmdRemoveFromRailroadStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
TileIndex start = p1 == 0 ? tile : p1;
/* Count of the number of tiles removed */
int quantity = 0;
if (tile >= MapSize() || start >= MapSize()) return CMD_ERROR;
/* make sure sx,sy are smaller than ex,ey */
int ex = TileX(tile);
int ey = TileY(tile);
int sx = TileX(start);
int sy = TileY(start);
if (ex < sx) Swap(ex, sx);
if (ey < sy) Swap(ey, sy);
tile = TileXY(sx, sy);
int size_x = ex - sx + 1;
int size_y = ey - sy + 1;
/* Do the action for every tile into the area */
BEGIN_TILE_LOOP(tile2, size_x, size_y, tile) {
/* Make sure the specified tile is a railroad station */
if (!IsTileType(tile2, MP_STATION) || !IsRailwayStation(tile2)) {
continue;
}
/* If there is a vehicle on ground, do not allow to remove (flood) the tile */
if (!EnsureNoVehicleOnGround(tile2)) {
continue;
}
/* Check ownership of station */
Station *st = GetStationByTile(tile2);
if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
continue;
}
/* Do not allow removing from stations if non-uniform stations are not enabled
* The check must be here to give correct error message
*/
if (!_settings_game.station.nonuniform_stations) return_cmd_error(STR_NONUNIFORM_STATIONS_DISALLOWED);
/* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
quantity++;
if (flags & DC_EXEC) {
/* read variables before the station tile is removed */
uint specindex = GetCustomStationSpecIndex(tile2);
Track track = GetRailStationTrack(tile2);
Owner owner = GetTileOwner(tile2);
Vehicle *v = NULL;
if (GetRailwayStationReservation(tile2)) {
v = GetTrainForReservation(tile2, track);
if (v != NULL) {
/* Free train reservation. */
FreeTrainTrackReservation(v);
if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(GetVehicleTrackdir(v)), false);
Vehicle *temp = v;
for (; temp->Next() != NULL; temp = temp->Next()) ;
if (IsRailwayStationTile(temp->tile)) SetRailwayStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(GetVehicleTrackdir(temp))), false);
}
}
DoClearSquare(tile2);
st->rect.AfterRemoveTile(st, tile2);
AddTrackToSignalBuffer(tile2, track, owner);
YapfNotifyTrackLayoutChange(tile2, track);
DeallocateSpecFromStation(st, specindex);
/* now we need to make the "spanned" area of the railway station smaller
* if we deleted something at the edges.
* we also need to adjust train_tile. */
MakeRailwayStationAreaSmaller(st);
st->MarkTilesDirty(false);
UpdateStationSignCoord(st);
if (v != NULL) {
/* Restore station reservation. */
if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(GetVehicleTrackdir(v)), true);
TryPathReserve(v, true, true);
for (; v->Next() != NULL; v = v->Next()) ;
if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(GetVehicleTrackdir(v))), true);
}
/* if we deleted the whole station, delete the train facility. */
if (st->train_tile == INVALID_TILE) {
st->facilities &= ~FACIL_TRAIN;
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_TRAINS);
UpdateStationVirtCoordDirty(st);
DeleteStationIfEmpty(st);
}
}
} END_TILE_LOOP(tile2, size_x, size_y, tile)
/* If we've not removed any tiles, give an error */
if (quantity == 0) return CMD_ERROR;
return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_rail_station * quantity);
}
static CommandCost RemoveRailroadStation(Station *st, TileIndex tile, DoCommandFlag flags)
{
/* if there is flooding and non-uniform stations are enabled, remove platforms tile by tile */
if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAILROAD_STATION);
}
/* Current company owns the station? */
if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) return CMD_ERROR;
/* determine width and height of platforms */
tile = st->train_tile;
int w = st->trainst_w;
int h = st->trainst_h;
assert(w != 0 && h != 0);
CommandCost cost(EXPENSES_CONSTRUCTION);
/* clear all areas of the station */
do {
int w_bak = w;
do {
/* for nonuniform stations, only remove tiles that are actually train station tiles */
if (st->TileBelongsToRailStation(tile)) {
if (!EnsureNoVehicleOnGround(tile))
return CMD_ERROR;
cost.AddCost(_price.remove_rail_station);
if (flags & DC_EXEC) {
/* read variables before the station tile is removed */
Track track = GetRailStationTrack(tile);
Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
Vehicle *v = NULL;
if (GetRailwayStationReservation(tile)) {
v = GetTrainForReservation(tile, track);
if (v != NULL) FreeTrainTrackReservation(v);
}
DoClearSquare(tile);
AddTrackToSignalBuffer(tile, track, owner);
YapfNotifyTrackLayoutChange(tile, track);
if (v != NULL) TryPathReserve(v, true);
}
}
tile += TileDiffXY(1, 0);
} while (--w);
w = w_bak;
tile += TileDiffXY(-w, 1);
} while (--h);
if (flags & DC_EXEC) {
st->rect.AfterRemoveRect(st, st->train_tile, st->trainst_w, st->trainst_h);
st->train_tile = INVALID_TILE;
st->trainst_w = st->trainst_h = 0;
st->facilities &= ~FACIL_TRAIN;
free(st->speclist);
st->num_specs = 0;
st->speclist = NULL;
st->cached_anim_triggers = 0;
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_TRAINS);
UpdateStationVirtCoordDirty(st);
DeleteStationIfEmpty(st);
}
return cost;
}
/**
* @param truck_station Determines whether a stop is ROADSTOP_BUS or ROADSTOP_TRUCK
* @param st The Station to do the whole procedure for
* @return a pointer to where to link a new RoadStop*
*/
static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
{
RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
if (*primary_stop == NULL) {
/* we have no roadstop of the type yet, so write a "primary stop" */
return primary_stop;
} else {
/* there are stops already, so append to the end of the list */
RoadStop *stop = *primary_stop;
while (stop->next != NULL) stop = stop->next;
return &stop->next;
}
}
/** Build a bus or truck stop
* @param tile tile to build the stop at
* @param flags operation to perform
* @param p1 entrance direction (DiagDirection)
* @param p2 bit 0: 0 for Bus stops, 1 for truck stops
* bit 1: 0 for normal, 1 for drive-through
* bit 2..3: the roadtypes
* bit 5: allow stations directly adjacent to other stations.
* bit 16..31: station ID to join (INVALID_STATION if build new one)
*/
CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
bool type = HasBit(p2, 0);
bool is_drive_through = HasBit(p2, 1);
bool build_over_road = is_drive_through && IsNormalRoadTile(tile);
RoadTypes rts = (RoadTypes)GB(p2, 2, 2);
StationID station_to_join = GB(p2, 16, 16);
bool distant_join = (station_to_join != INVALID_STATION);
Owner tram_owner = _current_company;
Owner road_owner = _current_company;
if (distant_join && (!_settings_game.station.distant_join_stations || !IsValidStationID(station_to_join))) return CMD_ERROR;
if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
/* Trams only have drive through stops */
if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
/* Saveguard the parameters */
if (!IsValidDiagDirection((DiagDirection)p1)) return CMD_ERROR;
/* If it is a drive-through stop check for valid axis */
if (is_drive_through && !IsValidAxis((Axis)p1)) return CMD_ERROR;
/* Road bits in the wrong direction */
if (build_over_road && (GetAllRoadBits(tile) & ((Axis)p1 == AXIS_X ? ROAD_Y : ROAD_X)) != 0) return_cmd_error(STR_DRIVE_THROUGH_ERROR_DIRECTION);
if (!CheckIfAuthorityAllowsNewStation(tile, flags)) return CMD_ERROR;
RoadTypes cur_rts = IsNormalRoadTile(tile) ? GetRoadTypes(tile) : ROADTYPES_NONE;
uint num_roadbits = 0;
/* Not allowed to build over this road */
if (build_over_road) {
/* there is a road, check if we can build road+tram stop over it */
if (HasBit(cur_rts, ROADTYPE_ROAD)) {
road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
if (road_owner == OWNER_TOWN) {
if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_DRIVE_THROUGH_ERROR_ON_TOWN_ROAD);
} else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE && !CheckOwnership(road_owner)) {
return CMD_ERROR;
}
num_roadbits += CountBits(GetRoadBits(tile, ROADTYPE_ROAD));
}
/* there is a tram, check if we can build road+tram stop over it */
if (HasBit(cur_rts, ROADTYPE_TRAM)) {
tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE && !CheckOwnership(tram_owner)) {
return CMD_ERROR;
}
num_roadbits += CountBits(GetRoadBits(tile, ROADTYPE_TRAM));
}
/* Don't allow building the roadstop when vehicles are already driving on it */
if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
/* Do not remove roadtypes! */
rts |= cur_rts;
}
CommandCost cost = CheckFlatLandBelow(tile, 1, 1, flags, is_drive_through ? 5 << p1 : 1 << p1, NULL, !build_over_road);
if (CmdFailed(cost)) return cost;
uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
cost.AddCost(_price.build_road * roadbits_to_build);
Station *st = NULL;
if (!_settings_game.station.adjacent_stations || !HasBit(p2, 5)) {
st = GetStationAround(tile, 1, 1, INVALID_STATION);
if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
}
/* Distant join */
if (st == NULL && distant_join) st = GetStation(station_to_join);
/* Find a deleted station close to us */
if (st == NULL) st = GetClosestDeletedStation(tile);
/* give us a road stop in the list, and check if something went wrong */
if (!RoadStop::CanAllocateItem()) return_cmd_error(type ? STR_TOO_MANY_TRUCK_STOPS : STR_TOO_MANY_BUS_STOPS);
if (st != NULL &&
GetNumRoadStopsInStation(st, ROADSTOP_BUS) + GetNumRoadStopsInStation(st, ROADSTOP_TRUCK) >= RoadStop::LIMIT) {
return_cmd_error(type ? STR_TOO_MANY_TRUCK_STOPS : STR_TOO_MANY_BUS_STOPS);
}
if (st != NULL) {
if (st->owner != _current_company) {
return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);
}
if (!st->rect.BeforeAddTile(tile, StationRect::ADD_TEST)) return CMD_ERROR;
} else {
/* allocate and initialize new station */
if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
if (flags & DC_EXEC) {
st = new Station(tile);
st->town = ClosestTownFromTile(tile, UINT_MAX);
st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
if (IsValidCompanyID(_current_company)) {
SetBit(st->town->have_ratings, _current_company);
}
st->sign.width_1 = 0;
}
}
cost.AddCost((type) ? _price.build_truck_station : _price.build_bus_station);
if (flags & DC_EXEC) {
RoadStop *road_stop = new RoadStop(tile);
/* Insert into linked list of RoadStops */
RoadStop **currstop = FindRoadStopSpot(type, st);
*currstop = road_stop;
/* initialize an empty station */
st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, tile);
st->rect.BeforeAddTile(tile, StationRect::ADD_TRY);
RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
if (is_drive_through) {
MakeDriveThroughRoadStop(tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts, (Axis)p1);
} else {
MakeRoadStop(tile, st->owner, st->index, rs_type, rts, (DiagDirection)p1);
}
UpdateStationVirtCoordDirty(st);
UpdateStationAcceptance(st, false);
InvalidateWindowData(WC_SELECT_STATION, 0, 0);
InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
}
return cost;
}
static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
{
if (v->type == VEH_ROAD) ClrBit(v->u.road.state, RVS_IN_DT_ROAD_STOP);
return NULL;
}
/** Remove a bus station
* @param st Station to remove
* @param flags operation to perform
* @param tile TileIndex been queried
* @return cost or failure of operation
*/
static CommandCost RemoveRoadStop(Station *st, DoCommandFlag flags, TileIndex tile)
{
if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
return CMD_ERROR;
}
bool is_truck = IsTruckStop(tile);
RoadStop **primary_stop;
RoadStop *cur_stop;
if (is_truck) { // truck stop
primary_stop = &st->truck_stops;
cur_stop = GetRoadStopByTile(tile, ROADSTOP_TRUCK);
} else {
primary_stop = &st->bus_stops;
cur_stop = GetRoadStopByTile(tile, ROADSTOP_BUS);
}
assert(cur_stop != NULL);
/* don't do the check for drive-through road stops when company bankrupts */
if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
/* remove the 'going through road stop' status from all vehicles on that tile */
if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
} else {
if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
}
if (flags & DC_EXEC) {
if (*primary_stop == cur_stop) {
/* removed the first stop in the list */
*primary_stop = cur_stop->next;
/* removed the only stop? */
if (*primary_stop == NULL) {
st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
}
} else {
/* tell the predecessor in the list to skip this stop */
RoadStop *pred = *primary_stop;
while (pred->next != cur_stop) pred = pred->next;
pred->next = cur_stop->next;
}
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
delete cur_stop;
/* Make sure no vehicle is going to the old roadstop */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_ROAD &&
v->First() == v &&
v->current_order.IsType(OT_GOTO_STATION) &&
v->dest_tile == tile) {
v->dest_tile = v->GetOrderStationLocation(st->index);
}
}
DoClearSquare(tile);
st->rect.AfterRemoveTile(st, tile);
UpdateStationVirtCoordDirty(st);
DeleteStationIfEmpty(st);
}
return CommandCost(EXPENSES_CONSTRUCTION, (is_truck) ? _price.remove_truck_station : _price.remove_bus_station);
}
/** Remove a bus or truck stop
* @param tile tile to remove the stop from
* @param flags operation to perform
* @param p1 not used
* @param p2 bit 0: 0 for Bus stops, 1 for truck stops
*/
CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
/* Make sure the specified tile is a road stop of the correct type */
if (!IsTileType(tile, MP_STATION) || !IsRoadStop(tile) || (uint32)GetRoadStopType(tile) != GB(p2, 0, 1)) return CMD_ERROR;
Station *st = GetStationByTile(tile);
/* Save the stop info before it is removed */
bool is_drive_through = IsDriveThroughStopTile(tile);
RoadTypes rts = GetRoadTypes(tile);
RoadBits road_bits = IsDriveThroughStopTile(tile) ?
((GetRoadStopDir(tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
DiagDirToRoadBits(GetRoadStopDir(tile));
Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
CommandCost ret = RemoveRoadStop(st, flags, tile);
/* If the stop was a drive-through stop replace the road */
if ((flags & DC_EXEC) && CmdSucceeded(ret) && is_drive_through) {
/* Rebuild the drive throuhg road stop. As a road stop can only be
* removed by the owner of the roadstop, _current_company is the
* owner of the road stop. */
MakeRoadNormal(tile, road_bits, rts, ClosestTownFromTile(tile, UINT_MAX)->index,
road_owner, tram_owner);
}
return ret;
}
/* FIXME -- need to move to its corresponding Airport variable*/
/* Country Airfield (small) */
static const byte _airport_sections_country[] = {
54, 53, 52, 65,
58, 57, 56, 55,
64, 63, 63, 62
};
/* City Airport (large) */
static const byte _airport_sections_town[] = {
31, 9, 33, 9, 9, 32,
27, 36, 29, 34, 8, 10,
30, 11, 35, 13, 20, 21,
51, 12, 14, 17, 19, 28,
38, 13, 15, 16, 18, 39,
26, 22, 23, 24, 25, 26
};
/* Metropolitain Airport (large) - 2 runways */
static const byte _airport_sections_metropolitan[] = {
31, 9, 33, 9, 9, 32,
27, 36, 29, 34, 8, 10,
30, 11, 35, 13, 20, 21,
102, 8, 8, 8, 8, 28,
83, 84, 84, 84, 84, 83,
26, 23, 23, 23, 23, 26
};
/* International Airport (large) - 2 runways */
static const byte _airport_sections_international[] = {
88, 89, 89, 89, 89, 89, 88,
51, 8, 8, 8, 8, 8, 32,
30, 8, 11, 27, 11, 8, 10,
32, 8, 11, 27, 11, 8, 114,
87, 8, 11, 85, 11, 8, 114,
87, 8, 8, 8, 8, 8, 90,
26, 23, 23, 23, 23, 23, 26
};
/* Intercontinental Airport (vlarge) - 4 runways */
static const byte _airport_sections_intercontinental[] = {
102, 120, 89, 89, 89, 89, 89, 89, 118,
120, 23, 23, 23, 23, 23, 23, 119, 117,
87, 54, 87, 8, 8, 8, 8, 51, 117,
87, 162, 87, 85, 116, 116, 8, 9, 10,
87, 8, 8, 11, 31, 11, 8, 160, 32,
32, 160, 8, 11, 27, 11, 8, 8, 10,
87, 8, 8, 11, 30, 11, 8, 8, 10,
87, 142, 8, 11, 29, 11, 10, 163, 10,
87, 164, 87, 8, 8, 8, 10, 37, 117,
87, 120, 89, 89, 89, 89, 89, 89, 119,
121, 23, 23, 23, 23, 23, 23, 119, 37
};
/* Commuter Airfield (small) */
static const byte _airport_sections_commuter[] = {
85, 30, 115, 115, 32,
87, 8, 8, 8, 10,
87, 11, 11, 11, 10,
26, 23, 23, 23, 26
};
/* Heliport */
static const byte _airport_sections_heliport[] = {
66,
};
/* Helidepot */
static const byte _airport_sections_helidepot[] = {
124, 32,
122, 123
};
/* Helistation */
static const byte _airport_sections_helistation[] = {
32, 134, 159, 158,
161, 142, 142, 157
};
static const byte * const _airport_sections[] = {
_airport_sections_country, // Country Airfield (small)
_airport_sections_town, // City Airport (large)
_airport_sections_heliport, // Heliport
_airport_sections_metropolitan, // Metropolitain Airport (large)
_airport_sections_international, // International Airport (xlarge)
_airport_sections_commuter, // Commuter Airport (small)
_airport_sections_helidepot, // Helidepot
_airport_sections_intercontinental, // Intercontinental Airport (xxlarge)
_airport_sections_helistation // Helistation
};
/**
* Computes the minimal distance from town's xy to any airport's tile.
* @param afc airport's description
* @param town_tile town's tile (t->xy)
* @param airport_tile st->airport_tile
* @return minimal manhattan distance from town_tile to any airport's tile
*/
static uint GetMinimalAirportDistanceToTile(const AirportFTAClass *afc, TileIndex town_tile, TileIndex airport_tile)
{
uint ttx = TileX(town_tile); // X, Y of town
uint tty = TileY(town_tile);
uint atx = TileX(airport_tile); // X, Y of northern airport corner
uint aty = TileY(airport_tile);
uint btx = TileX(airport_tile) + afc->size_x - 1; // X, Y of southern corner
uint bty = TileY(airport_tile) + afc->size_y - 1;
/* if ttx < atx, dx = atx - ttx
* if atx <= ttx <= btx, dx = 0
* else, dx = ttx - btx (similiar for dy) */
uint dx = ttx < atx ? atx - ttx : (ttx <= btx ? 0 : ttx - btx);
uint dy = tty < aty ? aty - tty : (tty <= bty ? 0 : tty - bty);
return dx + dy;
}
/** Get a possible noise reduction factor based on distance from town center.
* The further you get, the less noise you generate.
* So all those folks at city council can now happily slee... work in their offices
* @param afc AirportFTAClass pointer of the class being proposed
* @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
* @param tile TileIndex of northern tile of an airport (present or to-be-built), NOT the station tile
* @return the noise that will be generated, according to distance
*/
uint8 GetAirportNoiseLevelForTown(const AirportFTAClass *afc, TileIndex town_tile, TileIndex tile)
{
/* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
* So no need to go any further*/
if (afc->noise_level < 2) return afc->noise_level;
uint distance = GetMinimalAirportDistanceToTile(afc, town_tile, tile);
/* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
* adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
* Basically, it says that the less tolerant a town is, the bigger the distance before
* an actual decrease can be granted */
uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
/* now, we want to have the distance segmented using the distance judged bareable by town
* This will give us the coefficient of reduction the distance provides. */
uint noise_reduction = distance / town_tolerance_distance;
/* If the noise reduction equals the airport noise itself, don't give it for free.
* Otherwise, simply reduce the airport's level. */
return noise_reduction >= afc->noise_level ? 1 : afc->noise_level - noise_reduction;
}
/**
* Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
* If two towns have the same distance, town with lower index is returned.
* @param afc airport's description
* @param airport_tile st->airport_tile
* @return nearest town to airport
*/
Town *AirportGetNearestTown(const AirportFTAClass *afc, TileIndex airport_tile)
{
Town *t, *nearest = NULL;
uint add = afc->size_x + afc->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
uint mindist = UINT_MAX - add; // prevent overflow
FOR_ALL_TOWNS(t) {
if (DistanceManhattan(t->xy, airport_tile) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
uint dist = GetMinimalAirportDistanceToTile(afc, t->xy, airport_tile);
if (dist < mindist) {
nearest = t;
mindist = dist;
}
}
}
return nearest;
}
/** Recalculate the noise generated by the airports of each town */
void UpdateAirportsNoise()
{
Town *t;
const Station *st;
FOR_ALL_TOWNS(t) t->noise_reached = 0;
FOR_ALL_STATIONS(st) {
if (st->airport_tile != INVALID_TILE) {
const AirportFTAClass *afc = GetAirport(st->airport_type);
Town *nearest = AirportGetNearestTown(afc, st->airport_tile);
nearest->noise_reached += GetAirportNoiseLevelForTown(afc, nearest->xy, st->airport_tile);
}
}
}
/** Place an Airport.
* @param tile tile where airport will be built
* @param flags operation to perform
* @param p1 airport type, @see airport.h
* @param p2 various bitstuffed elements
* - p2 = (bit 0) - allow airports directly adjacent to other airports.
* - p2 = (bit 16-31) - station ID to join (INVALID_STATION if build new one)
*/
CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
bool airport_upgrade = true;
StationID station_to_join = GB(p2, 16, 16);
bool distant_join = (station_to_join != INVALID_STATION);
if (distant_join && (!_settings_game.station.distant_join_stations || !IsValidStationID(station_to_join))) return CMD_ERROR;
/* Check if a valid, buildable airport was chosen for construction */
if (p1 > lengthof(_airport_sections) || !HasBit(GetValidAirports(), p1)) return CMD_ERROR;
if (!CheckIfAuthorityAllowsNewStation(tile, flags)) {
return CMD_ERROR;
}
Town *t = ClosestTownFromTile(tile, UINT_MAX);
const AirportFTAClass *afc = GetAirport(p1);
int w = afc->size_x;
int h = afc->size_y;
Station *st = NULL;
if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
_error_message = STR_306C_STATION_TOO_SPREAD_OUT;
return CMD_ERROR;
}
CommandCost cost = CheckFlatLandBelow(tile, w, h, flags, 0, NULL);
if (CmdFailed(cost)) return cost;
/* Go get the final noise level, that is base noise minus factor from distance to town center */
Town *nearest = AirportGetNearestTown(afc, tile);
uint newnoise_level = GetAirportNoiseLevelForTown(afc, nearest->xy, tile);
/* Check if local auth would allow a new airport */
StringID authority_refuse_message = STR_NULL;
if (_settings_game.economy.station_noise_level) {
/* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
authority_refuse_message = STR_LOCAL_AUTHORITY_REFUSES_NOISE;
}
} else {
uint num = 0;
const Station *st;
FOR_ALL_STATIONS(st) {
if (st->town == t && st->facilities & FACIL_AIRPORT && st->airport_type != AT_OILRIG) num++;
}
if (num >= 2) {
authority_refuse_message = STR_2035_LOCAL_AUTHORITY_REFUSES;
}
}
if (authority_refuse_message != STR_NULL) {
SetDParam(0, t->index);
return_cmd_error(authority_refuse_message);
}
if (!_settings_game.station.adjacent_stations || !HasBit(p2, 0)) {
st = GetStationAround(tile, w, h, INVALID_STATION);
if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
} else {
st = NULL;
}
/* Distant join */
if (st == NULL && distant_join) st = GetStation(station_to_join);
/* Find a deleted station close to us */
if (st == NULL) st = GetClosestDeletedStation(tile);
if (st != NULL) {
if (st->owner != _current_company) {
return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);
}
if (!st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST)) return CMD_ERROR;
if (st->airport_tile != INVALID_TILE) {
return_cmd_error(STR_300D_TOO_CLOSE_TO_ANOTHER_AIRPORT);
}
} else {
airport_upgrade = false;
/* allocate and initialize new station */
if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
if (flags & DC_EXEC) {
st = new Station(tile);
st->town = t;
st->string_id = GenerateStationName(st, tile, !(afc->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
if (IsValidCompanyID(_current_company)) {
SetBit(st->town->have_ratings, _current_company);
}
st->sign.width_1 = 0;
}
}
cost.AddCost(_price.build_airport * w * h);
if (flags & DC_EXEC) {
/* Always add the noise, so there will be no need to recalculate when option toggles */
nearest->noise_reached += newnoise_level;
st->airport_tile = tile;
st->AddFacility(FACIL_AIRPORT, tile);
st->airport_type = (byte)p1;
st->airport_flags = 0;
st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
/* if airport was demolished while planes were en-route to it, the
* positions can no longer be the same (v->u.air.pos), since different
* airports have different indexes. So update all planes en-route to this
* airport. Only update if
* 1. airport is upgraded
* 2. airport is added to existing station (unfortunately unavoideable)
*/
if (airport_upgrade) UpdateAirplanesOnNewStation(st);
{
const byte *b = _airport_sections[p1];
BEGIN_TILE_LOOP(tile_cur, w, h, tile) {
MakeAirport(tile_cur, st->owner, st->index, *b - ((*b < 67) ? 8 : 24));
b++;
} END_TILE_LOOP(tile_cur, w, h, tile)
}
UpdateStationVirtCoordDirty(st);
UpdateStationAcceptance(st, false);
InvalidateWindowData(WC_SELECT_STATION, 0, 0);
InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_PLANES);
if (_settings_game.economy.station_noise_level) {
InvalidateWindow(WC_TOWN_VIEW, st->town->index);
}
}
return cost;
}
static CommandCost RemoveAirport(Station *st, DoCommandFlag flags)
{
if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
return CMD_ERROR;
}
TileIndex tile = st->airport_tile;
const AirportFTAClass *afc = st->Airport();
int w = afc->size_x;
int h = afc->size_y;
CommandCost cost(EXPENSES_CONSTRUCTION, w * h * _price.remove_airport);
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (!(v->type == VEH_AIRCRAFT && IsNormalAircraft(v))) continue;
if (v->u.air.targetairport == st->index && v->u.air.state != FLYING) return CMD_ERROR;
}
BEGIN_TILE_LOOP(tile_cur, w, h, tile) {
if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;
if (flags & DC_EXEC) {
DeleteAnimatedTile(tile_cur);
DoClearSquare(tile_cur);
}
} END_TILE_LOOP(tile_cur, w, h, tile)
if (flags & DC_EXEC) {
for (uint i = 0; i < afc->nof_depots; ++i) {
DeleteWindowById(
WC_VEHICLE_DEPOT, tile + ToTileIndexDiff(afc->airport_depots[i])
);
}
/* Go get the final noise level, that is base noise minus factor from distance to town center.
* And as for construction, always remove it, even if the setting is not set, in order to avoid the
* need of recalculation */
Town *nearest = AirportGetNearestTown(afc, tile);
nearest->noise_reached -= GetAirportNoiseLevelForTown(afc, nearest->xy, tile);
st->rect.AfterRemoveRect(st, tile, w, h);
st->airport_tile = INVALID_TILE;
st->facilities &= ~FACIL_AIRPORT;
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_PLANES);
if (_settings_game.economy.station_noise_level) {
InvalidateWindow(WC_TOWN_VIEW, st->town->index);
}
UpdateStationVirtCoordDirty(st);
DeleteStationIfEmpty(st);
}
return cost;
}
/** Build a buoy.
* @param tile tile where to place the bouy
* @param flags operation to perform
* @param p1 unused
* @param p2 unused
*/
CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsWaterTile(tile) || tile == 0) return_cmd_error(STR_304B_SITE_UNSUITABLE);
if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
if (GetTileSlope(tile, NULL) != SLOPE_FLAT) return_cmd_error(STR_304B_SITE_UNSUITABLE);
/* allocate and initialize new station */
if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
if (flags & DC_EXEC) {
Station *st = new Station(tile);
st->town = ClosestTownFromTile(tile, UINT_MAX);
st->string_id = GenerateStationName(st, tile, STATIONNAMING_BUOY);
if (IsValidCompanyID(_current_company)) {
SetBit(st->town->have_ratings, _current_company);
}
st->sign.width_1 = 0;
st->dock_tile = tile;
st->facilities |= FACIL_DOCK;
/* Buoys are marked in the Station struct by this flag. Yes, it is this
* braindead.. */
st->had_vehicle_of_type |= HVOT_BUOY;
st->owner = OWNER_NONE;
st->build_date = _date;
MakeBuoy(tile, st->index, GetWaterClass(tile));
UpdateStationVirtCoordDirty(st);
UpdateStationAcceptance(st, false);
InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.build_dock);
}
/**
* Tests whether the company's vehicles have this station in orders
* When company == INVALID_COMPANY, then check all vehicles
* @param station station ID
* @param company company ID, INVALID_COMPANY to disable the check
*/
bool HasStationInUse(StationID station, CompanyID company)
{
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (company == INVALID_COMPANY || v->owner == company) {
const Order *order;
FOR_VEHICLE_ORDERS(v, order) {
if (order->IsType(OT_GOTO_STATION) && order->GetDestination() == station) {
return true;
}
}
}
}
return false;
}
static CommandCost RemoveBuoy(Station *st, DoCommandFlag flags)
{
/* XXX: strange stuff */
if (!IsValidCompanyID(_current_company)) return_cmd_error(INVALID_STRING_ID);
TileIndex tile = st->dock_tile;
if (HasStationInUse(st->index, INVALID_COMPANY)) return_cmd_error(STR_BUOY_IS_IN_USE);
/* remove the buoy if there is a ship on tile when company goes bankrupt... */
if (!(flags & DC_BANKRUPT) && !EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
if (flags & DC_EXEC) {
st->dock_tile = INVALID_TILE;
/* Buoys are marked in the Station struct by this flag. Yes, it is this
* braindead.. */
st->facilities &= ~FACIL_DOCK;
st->had_vehicle_of_type &= ~HVOT_BUOY;
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
/* We have to set the water tile's state to the same state as before the
* buoy was placed. Otherwise one could plant a buoy on a canal edge,
* remove it and flood the land (if the canal edge is at level 0) */
MakeWaterKeepingClass(tile, GetTileOwner(tile));
MarkTileDirtyByTile(tile);
UpdateStationVirtCoordDirty(st);
DeleteStationIfEmpty(st);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_truck_station);
}
static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
{-1, 0},
{ 0, 0},
{ 0, 0},
{ 0, -1}
};
static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
/** Build a dock/haven.
* @param tile tile where dock will be built
* @param flags operation to perform
* @param p1 (bit 0) - allow docks directly adjacent to other docks.
* @param p2 bit 16-31: station ID to join (INVALID_STATION if build new one)
*/
CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
StationID station_to_join = GB(p2, 16, 16);
bool distant_join = (station_to_join != INVALID_STATION);
if (distant_join && (!_settings_game.station.distant_join_stations || !IsValidStationID(station_to_join))) return CMD_ERROR;
DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
if (direction == INVALID_DIAGDIR) return_cmd_error(STR_304B_SITE_UNSUITABLE);
direction = ReverseDiagDir(direction);
/* Docks cannot be placed on rapids */
if (IsWaterTile(tile)) return_cmd_error(STR_304B_SITE_UNSUITABLE);
if (!CheckIfAuthorityAllowsNewStation(tile, flags)) return CMD_ERROR;
if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
if (CmdFailed(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR))) return CMD_ERROR;
TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
return_cmd_error(STR_304B_SITE_UNSUITABLE);
}
if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
/* Get the water class of the water tile before it is cleared.*/
WaterClass wc = GetWaterClass(tile_cur);
if (CmdFailed(DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR))) return CMD_ERROR;
tile_cur += TileOffsByDiagDir(direction);
if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
return_cmd_error(STR_304B_SITE_UNSUITABLE);
}
/* middle */
Station *st = NULL;
if (!_settings_game.station.adjacent_stations || !HasBit(p1, 0)) {
st = GetStationAround(
tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
_dock_w_chk[direction], _dock_h_chk[direction], INVALID_STATION);
if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
}
/* Distant join */
if (st == NULL && distant_join) st = GetStation(station_to_join);
/* Find a deleted station close to us */
if (st == NULL) st = GetClosestDeletedStation(tile);
if (st != NULL) {
if (st->owner != _current_company) {
return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);
}
if (!st->rect.BeforeAddRect(
tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
_dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST)) return CMD_ERROR;
if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_304C_TOO_CLOSE_TO_ANOTHER_DOCK);
} else {
/* allocate and initialize new station */
if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
if (flags & DC_EXEC) {
st = new Station(tile);
st->town = ClosestTownFromTile(tile, UINT_MAX);
st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
if (IsValidCompanyID(_current_company)) {
SetBit(st->town->have_ratings, _current_company);
}
}
}
if (flags & DC_EXEC) {
st->dock_tile = tile;
st->AddFacility(FACIL_DOCK, tile);
st->rect.BeforeAddRect(
tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
_dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
MakeDock(tile, st->owner, st->index, direction, wc);
UpdateStationVirtCoordDirty(st);
UpdateStationAcceptance(st, false);
InvalidateWindowData(WC_SELECT_STATION, 0, 0);
InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.build_dock);
}
static CommandCost RemoveDock(Station *st, DoCommandFlag flags)
{
if (!CheckOwnership(st->owner)) return CMD_ERROR;
TileIndex tile1 = st->dock_tile;
TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
if (!EnsureNoVehicleOnGround(tile1)) return CMD_ERROR;
if (!EnsureNoVehicleOnGround(tile2)) return CMD_ERROR;
if (flags & DC_EXEC) {
DoClearSquare(tile1);
MakeWaterKeepingClass(tile2, st->owner);
st->rect.AfterRemoveTile(st, tile1);
st->rect.AfterRemoveTile(st, tile2);
MarkTileDirtyByTile(tile2);
st->dock_tile = INVALID_TILE;
st->facilities &= ~FACIL_DOCK;
InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
UpdateStationVirtCoordDirty(st);
DeleteStationIfEmpty(st);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_dock);
}
#include "table/station_land.h"
const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
{
return &_station_display_datas[st][gfx];
}
static void DrawTile_Station(TileInfo *ti)
{
const DrawTileSprites *t = NULL;
RoadTypes roadtypes;
int32 total_offset;
int32 custom_ground_offset;
if (IsRailwayStation(ti->tile)) {
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
roadtypes = ROADTYPES_NONE;
total_offset = rti->total_offset;
custom_ground_offset = rti->custom_ground_offset;
} else {
roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
total_offset = 0;
custom_ground_offset = 0;
}
uint32 relocation = 0;
const Station *st = NULL;
const StationSpec *statspec = NULL;
Owner owner = GetTileOwner(ti->tile);
SpriteID palette;
if (IsValidCompanyID(owner)) {
palette = COMPANY_SPRITE_COLOUR(owner);
} else {
/* Some stations are not owner by a company, namely oil rigs */
palette = PALETTE_TO_GREY;
}
/* don't show foundation for docks */
if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile))
DrawFoundation(ti, FOUNDATION_LEVELED);
if (IsCustomStationSpecIndex(ti->tile)) {
/* look for customization */
st = GetStationByTile(ti->tile);
statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
if (statspec != NULL) {
uint tile = GetStationGfx(ti->tile);
relocation = GetCustomStationRelocation(statspec, st, ti->tile);
if (HasBit(statspec->callbackmask, CBM_STATION_SPRITE_LAYOUT)) {
uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
}
/* Ensure the chosen tile layout is valid for this custom station */
if (statspec->renderdata != NULL) {
t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
}
}
}
if (t == NULL || t->seq == NULL) t = &_station_display_datas[GetStationType(ti->tile)][GetStationGfx(ti->tile)];
if (IsBuoy(ti->tile) || IsDock(ti->tile) || (IsOilRig(ti->tile) && GetWaterClass(ti->tile) != WATER_CLASS_INVALID)) {
if (ti->tileh == SLOPE_FLAT) {
DrawWaterClassGround(ti);
} else {
assert(IsDock(ti->tile));
TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
WaterClass wc = GetWaterClass(water_tile);
if (wc == WATER_CLASS_SEA) {
DrawShoreTile(ti->tileh);
} else {
DrawClearLandTile(ti, 3);
}
}
} else {
SpriteID image = t->ground.sprite;
SpriteID pal = t->ground.pal;
if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
image += custom_ground_offset;
} else {
image += total_offset;
}
DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
/* PBS debugging, draw reserved tracks darker */
if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && IsRailwayStation(ti->tile) && GetRailwayStationReservation(ti->tile)) {
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_y : rti->base_sprites.single_x, PALETTE_CRASH);
}
}
if (IsRailwayStation(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
if (HasBit(roadtypes, ROADTYPE_TRAM)) {
Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
}
const DrawTileSeqStruct *dtss;
foreach_draw_tile_seq(dtss, t->seq) {
SpriteID image = dtss->image.sprite;
/* Stop drawing sprite sequence once we meet a sprite that doesn't have to be opaque */
if (IsInvisibilitySet(TO_BUILDINGS) && !HasBit(image, SPRITE_MODIFIER_OPAQUE)) return;
if (relocation == 0 || HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
image += total_offset;
} else {
image += relocation;
}
SpriteID pal = SpriteLayoutPaletteTransform(image, dtss->image.pal, palette);
if ((byte)dtss->delta_z != 0x80) {
AddSortableSpriteToDraw(
image, pal,
ti->x + dtss->delta_x, ti->y + dtss->delta_y,
dtss->size_x, dtss->size_y,
dtss->size_z, ti->z + dtss->delta_z,
!HasBit(image, SPRITE_MODIFIER_OPAQUE) && IsTransparencySet(TO_BUILDINGS)
);
} else {
/* For stations and original spritelayouts delta_x and delta_y are signed */
AddChildSpriteScreen(image, pal, dtss->delta_x, dtss->delta_y, !HasBit(image, SPRITE_MODIFIER_OPAQUE) && IsTransparencySet(TO_BUILDINGS));
}
}
}
void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
{
int32 total_offset = 0;
SpriteID pal = COMPANY_SPRITE_COLOUR(_local_company);
const DrawTileSprites *t = &_station_display_datas[st][image];
if (railtype != INVALID_RAILTYPE) {
const RailtypeInfo *rti = GetRailTypeInfo(railtype);
total_offset = rti->total_offset;
}
SpriteID img = t->ground.sprite;
DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
if (roadtype == ROADTYPE_TRAM) {
DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
}
const DrawTileSeqStruct *dtss;
foreach_draw_tile_seq(dtss, t->seq) {
Point pt = RemapCoords(dtss->delta_x, dtss->delta_y, dtss->delta_z);
DrawSprite(dtss->image.sprite + total_offset, pal, x + pt.x, y + pt.y);
}
}
static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
{
return GetTileMaxZ(tile);
}
static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
{
return FlatteningFoundation(tileh);
}
static void GetAcceptedCargo_Station(TileIndex tile, AcceptedCargo ac)
{
/* not used */
}
static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
{
td->owner[0] = GetTileOwner(tile);
if (IsDriveThroughStopTile(tile)) {
Owner road_owner = INVALID_OWNER;
Owner tram_owner = INVALID_OWNER;
RoadTypes rts = GetRoadTypes(tile);
if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
/* Is there a mix of owners? */
if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
(road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
uint i = 1;
if (road_owner != INVALID_OWNER) {
td->owner_type[i] = STR_ROAD_OWNER;
td->owner[i] = road_owner;
i++;
}
if (tram_owner != INVALID_OWNER) {
td->owner_type[i] = STR_TRAM_OWNER;
td->owner[i] = tram_owner;
}
}
}
td->build_date = GetStationByTile(tile)->build_date;
const StationSpec *spec = GetStationSpec(tile);
if (spec != NULL) {
td->station_class = GetStationClassName(spec->sclass);
td->station_name = spec->name;
if (spec->grffile != NULL) {
const GRFConfig *gc = GetGRFConfig(spec->grffile->grfid);
td->grf = gc->name;
}
}
StringID str;
switch (GetStationType(tile)) {
default: NOT_REACHED();
case STATION_RAIL: str = STR_305E_RAILROAD_STATION; break;
case STATION_AIRPORT:
str = (IsHangar(tile) ? STR_305F_AIRCRAFT_HANGAR : STR_3060_AIRPORT);
break;
case STATION_TRUCK: str = STR_3061_TRUCK_LOADING_AREA; break;
case STATION_BUS: str = STR_3062_BUS_STATION; break;
case STATION_OILRIG: str = STR_4807_OIL_RIG; break;
case STATION_DOCK: str = STR_3063_SHIP_DOCK; break;
case STATION_BUOY: str = STR_3069_BUOY; break;
}
td->str = str;
}
static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
{
TrackBits trackbits = TRACK_BIT_NONE;
switch (mode) {
case TRANSPORT_RAIL:
if (IsRailwayStation(tile) && !IsStationTileBlocked(tile)) {
trackbits = TrackToTrackBits(GetRailStationTrack(tile));
}
break;
case TRANSPORT_WATER:
/* buoy is coded as a station, it is always on open water */
if (IsBuoy(tile)) {
trackbits = TRACK_BIT_ALL;
/* remove tracks that connect NE map edge */
if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
/* remove tracks that connect NW map edge */
if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
}
break;
case TRANSPORT_ROAD:
if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
DiagDirection dir = GetRoadStopDir(tile);
Axis axis = DiagDirToAxis(dir);
if (side != INVALID_DIAGDIR) {
if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
}
trackbits = AxisToTrackBits(axis);
}
break;
default:
break;
}
return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
}
static void TileLoop_Station(TileIndex tile)
{
/* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
* hardcoded.....not good */
switch (GetStationType(tile)) {
case STATION_AIRPORT:
switch (GetStationGfx(tile)) {
case GFX_RADAR_LARGE_FIRST:
case GFX_WINDSACK_FIRST : // for small airport
case GFX_RADAR_INTERNATIONAL_FIRST:
case GFX_RADAR_METROPOLITAN_FIRST:
case GFX_RADAR_DISTRICTWE_FIRST: // radar district W-E airport
case GFX_WINDSACK_INTERCON_FIRST : // for intercontinental airport
AddAnimatedTile(tile);
break;
}
break;
case STATION_DOCK:
if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break; // only handle water part
/* FALL THROUGH */
case STATION_OILRIG: //(station part)
case STATION_BUOY:
TileLoop_Water(tile);
break;
default: break;
}
}
static void AnimateTile_Station(TileIndex tile)
{
struct AnimData {
StationGfx from; // first sprite
StationGfx to; // last sprite
byte delay;
};
static const AnimData data[] = {
{ GFX_RADAR_LARGE_FIRST, GFX_RADAR_LARGE_LAST, 3 },
{ GFX_WINDSACK_FIRST, GFX_WINDSACK_LAST, 1 },
{ GFX_RADAR_INTERNATIONAL_FIRST, GFX_RADAR_INTERNATIONAL_LAST, 3 },
{ GFX_RADAR_METROPOLITAN_FIRST, GFX_RADAR_METROPOLITAN_LAST, 3 },
{ GFX_RADAR_DISTRICTWE_FIRST, GFX_RADAR_DISTRICTWE_LAST, 3 },
{ GFX_WINDSACK_INTERCON_FIRST, GFX_WINDSACK_INTERCON_LAST, 1 }
};
if (IsRailwayStation(tile)) {
AnimateStationTile(tile);
return;
}
StationGfx gfx = GetStationGfx(tile);
for (const AnimData *i = data; i != endof(data); i++) {
if (i->from <= gfx && gfx <= i->to) {
if ((_tick_counter & i->delay) == 0) {
SetStationGfx(tile, gfx < i->to ? gfx + 1 : i->from);
MarkTileDirtyByTile(tile);
}
break;
}
}
}
static bool ClickTile_Station(TileIndex tile)
{
if (IsHangar(tile)) {
ShowDepotWindow(tile, VEH_AIRCRAFT);
} else {
ShowStationViewWindow(GetStationIndex(tile));
}
return true;
}
static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
{
StationID station_id = GetStationIndex(tile);
if (v->type == VEH_TRAIN) {
if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
if (IsRailwayStation(tile) && IsFrontEngine(v) &&
!IsCompatibleTrainStationTile(tile + TileOffsByDiagDir(DirToDiagDir(v->direction)), tile)) {
DiagDirection dir = DirToDiagDir(v->direction);
x &= 0xF;
y &= 0xF;
if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
if (y == TILE_SIZE / 2) {
if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
int stop = TILE_SIZE - (v->u.rail.cached_veh_length + 1) / 2;
if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
if (x < stop) {
uint16 spd;
v->vehstatus |= VS_TRAIN_SLOWING;
spd = max(0, (stop - x) * 20 - 15);
if (spd < v->cur_speed) v->cur_speed = spd;
}
}
}
} else if (v->type == VEH_ROAD) {
if (v->u.road.state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)v->u.road.state) && v->u.road.frame == 0) {
if (IsRoadStop(tile) && IsRoadVehFront(v)) {
/* Attempt to allocate a parking bay in a road stop */
RoadStop *rs = GetRoadStopByTile(tile, GetRoadStopType(tile));
if (IsDriveThroughStopTile(tile)) {
if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
/* Vehicles entering a drive-through stop from the 'normal' side use first bay (bay 0). */
byte side = ((DirToDiagDir(v->direction) == ReverseDiagDir(GetRoadStopDir(tile))) == (v->u.road.overtaking == 0)) ? 0 : 1;
if (!rs->IsFreeBay(side)) return VETSB_CANNOT_ENTER;
/* Check if the vehicle is stopping at this road stop */
if (GetRoadStopType(tile) == (IsCargoInClass(v->cargo_type, CC_PASSENGERS) ? ROADSTOP_BUS : ROADSTOP_TRUCK) &&
v->current_order.GetDestination() == GetStationIndex(tile)) {
SetBit(v->u.road.state, RVS_IS_STOPPING);
rs->AllocateDriveThroughBay(side);
}
/* Indicate if vehicle is using second bay. */
if (side == 1) SetBit(v->u.road.state, RVS_USING_SECOND_BAY);
/* Indicate a drive-through stop */
SetBit(v->u.road.state, RVS_IN_DT_ROAD_STOP);
return VETSB_CONTINUE;
}
/* For normal (non drive-through) road stops
* Check if station is busy or if there are no free bays or whether it is a articulated vehicle. */
if (rs->IsEntranceBusy() || !rs->HasFreeBay() || RoadVehHasArticPart(v)) return VETSB_CANNOT_ENTER;
SetBit(v->u.road.state, RVS_IN_ROAD_STOP);
/* Allocate a bay and update the road state */
uint bay_nr = rs->AllocateBay();
SB(v->u.road.state, RVS_USING_SECOND_BAY, 1, bay_nr);
/* Mark the station entrace as busy */
rs->SetEntranceBusy(true);
}
}
}
return VETSB_CONTINUE;
}
/* this function is called for one station each tick */
static void StationHandleBigTick(Station *st)
{
UpdateStationAcceptance(st, true);
if (st->facilities == 0 && ++st->delete_ctr >= 8) delete st;
}
static inline void byte_inc_sat(byte *p)
{
byte b = *p + 1;
if (b != 0) *p = b;
}
static void UpdateStationRating(Station *st)
{
bool waiting_changed = false;
byte_inc_sat(&st->time_since_load);
byte_inc_sat(&st->time_since_unload);
GoodsEntry *ge = st->goods;
do {
/* Slowly increase the rating back to his original level in the case we
* didn't deliver cargo yet to this station. This happens when a bribe
* failed while you didn't moved that cargo yet to a station. */
if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
ge->rating++;
}
/* Only change the rating if we are moving this cargo */
if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
byte_inc_sat(&ge->days_since_pickup);
int rating = 0;
{
int b = ge->last_speed - 85;
if (b >= 0)
rating += b >> 2;
}
{
byte age = ge->last_age;
(age >= 3) ||
(rating += 10, age >= 2) ||
(rating += 10, age >= 1) ||
(rating += 13, true);
}
if (IsValidCompanyID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
{
byte days = ge->days_since_pickup;
if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
(days > 21) ||
(rating += 25, days > 12) ||
(rating += 25, days > 6) ||
(rating += 45, days > 3) ||
(rating += 35, true);
}
uint waiting = ge->cargo.Count();
(rating -= 90, waiting > 1500) ||
(rating += 55, waiting > 1000) ||
(rating += 35, waiting > 600) ||
(rating += 10, waiting > 300) ||
(rating += 20, waiting > 100) ||
(rating += 10, true);
{
int or_ = ge->rating; // old rating
/* only modify rating in steps of -2, -1, 0, 1 or 2 */
ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
/* if rating is <= 64 and more than 200 items waiting,
* remove some random amount of goods from the station */
if (rating <= 64 && waiting >= 200) {
int dec = Random() & 0x1F;
if (waiting < 400) dec &= 7;
waiting -= dec + 1;
waiting_changed = true;
}
/* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
if (rating <= 127 && waiting != 0) {
uint32 r = Random();
if (rating <= (int)GB(r, 0, 7)) {
/* Need to have int, otherwise it will just overflow etc. */
waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
waiting_changed = true;
}
}
/* At some point we really must cap the cargo. Previously this
* was a strict 4095, but now we'll have a less strict, but
* increasingly agressive truncation of the amount of cargo. */
static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
static const uint MAX_WAITING_CARGO = 1 << 15;
if (waiting > WAITING_CARGO_THRESHOLD) {
uint difference = waiting - WAITING_CARGO_THRESHOLD;
waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
waiting = min(waiting, MAX_WAITING_CARGO);
waiting_changed = true;
}
if (waiting_changed) ge->cargo.Truncate(waiting);
}
}
} while (++ge != endof(st->goods));
StationID index = st->index;
if (waiting_changed) {
InvalidateWindow(WC_STATION_VIEW, index); // update whole window
} else {
InvalidateWindowWidget(WC_STATION_VIEW, index, SVW_RATINGLIST); // update only ratings list
}
}
/* called for every station each tick */
static void StationHandleSmallTick(Station *st)
{
if (st->facilities == 0) return;
byte b = st->delete_ctr + 1;
if (b >= 185) b = 0;
st->delete_ctr = b;
if (b == 0) UpdateStationRating(st);
}
void OnTick_Station()
{
if (_game_mode == GM_EDITOR) return;
uint i = _station_tick_ctr;
if (++_station_tick_ctr > GetMaxStationIndex()) _station_tick_ctr = 0;
if (IsValidStationID(i)) StationHandleBigTick(GetStation(i));
Station *st;
FOR_ALL_STATIONS(st) {
StationHandleSmallTick(st);
/* Run 250 tick interval trigger for station animation.
* Station index is included so that triggers are not all done
* at the same time. */
if ((_tick_counter + st->index) % 250 == 0) {
StationAnimationTrigger(st, st->xy, STAT_ANIM_250_TICKS);
}
}
}
void StationMonthlyLoop()
{
/* not used */
}
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
{
Station *st;
FOR_ALL_STATIONS(st) {
if (st->owner == owner &&
DistanceManhattan(tile, st->xy) <= radius) {
for (CargoID i = 0; i < NUM_CARGO; i++) {
GoodsEntry *ge = &st->goods[i];
if (ge->acceptance_pickup != 0) {
ge->rating = Clamp(ge->rating + amount, 0, 255);
}
}
}
}
}
static void UpdateStationWaiting(Station *st, CargoID type, uint amount)
{
st->goods[type].cargo.Append(new CargoPacket(st->index, amount));
SetBit(st->goods[type].acceptance_pickup, GoodsEntry::PICKUP);
StationAnimationTrigger(st, st->xy, STAT_ANIM_NEW_CARGO, type);
InvalidateWindow(WC_STATION_VIEW, st->index);
st->MarkTilesDirty(true);
}
static bool IsUniqueStationName(const char *name)
{
const Station *st;
FOR_ALL_STATIONS(st) {
if (st->name != NULL && strcmp(st->name, name) == 0) return false;
}
return true;
}
/** Rename a station
* @param tile unused
* @param flags operation to perform
* @param p1 station ID that is to be renamed
* @param p2 unused
*/
CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidStationID(p1)) return CMD_ERROR;
Station *st = GetStation(p1);
if (!CheckOwnership(st->owner)) return CMD_ERROR;
bool reset = StrEmpty(text);
if (!reset) {
if (strlen(text) >= MAX_LENGTH_STATION_NAME_BYTES) return CMD_ERROR;
if (!IsUniqueStationName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
}
if (flags & DC_EXEC) {
free(st->name);
st->name = reset ? NULL : strdup(text);
UpdateStationVirtCoord(st);
InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
MarkWholeScreenDirty();
}
return CommandCost();
}
/**
* Find all (non-buoy) stations around a rectangular producer (industry, house, headquarter, ...)
*
* @param tile North tile of producer
* @param w_prod X extent of producer
* @param h_prod Y extent of producer
*
* @return: Set of found stations
*/
void FindStationsAroundTiles(TileIndex tile, int w_prod, int h_prod, StationList *stations)
{
/* area to search = producer plus station catchment radius */
int max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
for (int dy = -max_rad; dy < h_prod + max_rad; dy++) {
for (int dx = -max_rad; dx < w_prod + max_rad; dx++) {
TileIndex cur_tile = TileAddWrap(tile, dx, dy);
if (cur_tile == INVALID_TILE || !IsTileType(cur_tile, MP_STATION)) continue;
Station *st = GetStationByTile(cur_tile);
if (st->IsBuoy()) continue; // bouys don't accept cargo
if (_settings_game.station.modified_catchment) {
int rad = st->GetCatchmentRadius();
if (dx < -rad || dx >= rad + w_prod || dy < -rad || dy >= rad + h_prod) continue;
}
/* Insert the station in the set. This will fail if it has
* already been added.
*/
stations->Include(st);
}
}
}
uint MoveGoodsToStation(TileIndex tile, int w, int h, CargoID type, uint amount)
{
Station *st1 = NULL; // Station with best rating
Station *st2 = NULL; // Second best station
uint best_rating1 = 0; // rating of st1
uint best_rating2 = 0; // rating of st2
StationList all_stations;
FindStationsAroundTiles(tile, w, h, &all_stations);
for (Station **st_iter = all_stations.Begin(); st_iter != all_stations.End(); ++st_iter) {
Station *st = *st_iter;
/* Is the station reserved exclusively for somebody else? */
if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue; // Selectively servicing stations, and not this one
if (IsCargoInClass(type, CC_PASSENGERS)) {
if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
} else {
if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
}
/* This station can be used, add it to st1/st2 */
if (st1 == NULL || st->goods[type].rating >= best_rating1) {
st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
} else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
st2 = st; best_rating2 = st->goods[type].rating;
}
}
/* no stations around at all? */
if (st1 == NULL) return 0;
if (st2 == NULL) {
/* only one station around */
uint moved = amount * best_rating1 / 256 + 1;
UpdateStationWaiting(st1, type, moved);
return moved;
}
/* several stations around, the best two (highest rating) are in st1 and st2 */
assert(st1 != NULL);
assert(st2 != NULL);
assert(best_rating1 != 0 || best_rating2 != 0);
/* the 2nd highest one gets a penalty */
best_rating2 >>= 1;
/* amount given to station 1 */
uint t = (best_rating1 * (amount + 1)) / (best_rating1 + best_rating2);
uint moved = 0;
if (t != 0) {
moved = t * best_rating1 / 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)
{
if (!Station::CanAllocateItem()) {
DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
return;
}
Station *st = new Station(tile);
st->town = ClosestTownFromTile(tile, UINT_MAX);
st->sign.width_1 = 0;
st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
assert(IsTileType(tile, MP_INDUSTRY));
MakeOilrig(tile, st->index, GetWaterClass(tile));
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 = INVALID_TILE;
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;
st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
for (CargoID j = 0; j < NUM_CARGO; j++) {
st->goods[j].acceptance_pickup = 0;
st->goods[j].days_since_pickup = 255;
st->goods[j].rating = INITIAL_STATION_RATING;
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);
MakeWaterKeepingClass(tile, OWNER_NONE);
MarkTileDirtyByTile(tile);
st->dock_tile = INVALID_TILE;
st->airport_tile = INVALID_TILE;
st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
st->airport_flags = 0;
st->rect.AfterRemoveTile(st, tile);
UpdateStationVirtCoordDirty(st);
if (st->facilities == 0) delete st;
}
static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
{
if (IsDriveThroughStopTile(tile)) {
for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
/* Update all roadtypes, no matter if they are present */
if (GetRoadOwner(tile, rt) == old_owner) {
SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
}
}
}
if (!IsTileOwner(tile, old_owner)) return;
if (new_owner != INVALID_OWNER) {
/* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
SetTileOwner(tile, new_owner);
InvalidateWindowClassesData(WC_STATION_LIST, 0);
} else {
if (IsDriveThroughStopTile(tile)) {
/* Remove the drive-through road stop */
DoCommand(tile, 0, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
assert(IsTileType(tile, MP_ROAD));
/* Change owner of tile and all roadtypes */
ChangeTileOwner(tile, old_owner, new_owner);
} else {
DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
/* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
* Update owner of buoy if it was not removed (was in orders).
* Do not update when owned by OWNER_WATER (sea and rivers). */
if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
}
}
}
/**
* Check if a drive-through road stop tile can be cleared.
* Road stops built on town-owned roads check the conditions
* that would allow clearing of the original road.
* @param tile road stop tile to check
* @param flags command flags
* @return true if the road can be cleared
*/
static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
{
Owner road_owner = _current_company;
Owner tram_owner = _current_company;
RoadTypes rts = GetRoadTypes(tile);
if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
if ((road_owner != OWNER_TOWN && !CheckOwnership(road_owner)) || !CheckOwnership(tram_owner)) return false;
return road_owner != OWNER_TOWN || CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags);
}
static CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
{
if (flags & DC_AUTO) {
switch (GetStationType(tile)) {
case STATION_RAIL: return_cmd_error(STR_300B_MUST_DEMOLISH_RAILROAD);
case STATION_AIRPORT: return_cmd_error(STR_300E_MUST_DEMOLISH_AIRPORT_FIRST);
case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_MUST_DEMOLISH_CARGO_TRAM_STATION : STR_3047_MUST_DEMOLISH_TRUCK_STATION);
case STATION_BUS: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_MUST_DEMOLISH_PASSENGER_TRAM_STATION : 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);
}
}
Station *st = GetStationByTile(tile);
switch (GetStationType(tile)) {
case STATION_RAIL: return RemoveRailroadStation(st, tile, flags);
case STATION_AIRPORT: return RemoveAirport(st, flags);
case STATION_TRUCK:
if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags))
return_cmd_error(STR_3047_MUST_DEMOLISH_TRUCK_STATION);
return RemoveRoadStop(st, flags, tile);
case STATION_BUS:
if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags))
return_cmd_error(STR_3046_MUST_DEMOLISH_BUS_STATION);
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()
{
/* Clean the station pool and create 1 block in it */
_Station_pool.CleanPool();
_Station_pool.AddBlockToPool();
/* Clean the roadstop pool and create 1 block in it */
_RoadStop_pool.CleanPool();
_RoadStop_pool.AddBlockToPool();
_station_tick_ctr = 0;
}
static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
{
if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
/* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
* TTDP does not call it.
*/
if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
switch (GetStationType(tile)) {
case STATION_RAIL: {
DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
}
case STATION_AIRPORT:
return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
case STATION_TRUCK:
case STATION_BUS: {
DiagDirection direction = GetRoadStopDir(tile);
if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
if (IsDriveThroughStopTile(tile)) {
if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
}
default: break;
}
}
}
return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
}
extern 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
GetFoundation_Station, // get_foundation_proc
TerraformTile_Station, // terraform_tile_proc
};
| 107,117
|
C++
|
.cpp
| 2,726
| 36.308877
| 161
| 0.692881
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,043
|
terraform_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/terraform_gui.cpp
|
/* $Id$ */
/** @file terraform_gui.cpp GUI related to terraforming the map. */
#include "stdafx.h"
#include "openttd.h"
#include "clear_map.h"
#include "company_func.h"
#include "company_base.h"
#include "gui.h"
#include "window_gui.h"
#include "window_func.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "command_func.h"
#include "signs_func.h"
#include "variables.h"
#include "functions.h"
#include "sound_func.h"
#include "station_base.h"
#include "unmovable_map.h"
#include "textbuf_gui.h"
#include "genworld.h"
#include "tree_map.h"
#include "landscape_type.h"
#include "tilehighlight_func.h"
#include "settings_type.h"
#include "table/sprites.h"
#include "table/strings.h"
void CcTerraform(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_1F_SPLAT, tile);
} else {
extern TileIndex _terraform_err_tile;
SetRedErrorSquare(_terraform_err_tile);
}
}
/** Scenario editor command that generates desert areas */
static void GenerateDesertArea(TileIndex end, TileIndex start)
{
int size_x, size_y;
int sx = TileX(start);
int sy = TileY(start);
int ex = TileX(end);
int ey = TileY(end);
if (_game_mode != GM_EDITOR) return;
if (ex < sx) Swap(ex, sx);
if (ey < sy) Swap(ey, sy);
size_x = (ex - sx) + 1;
size_y = (ey - sy) + 1;
_generating_world = true;
BEGIN_TILE_LOOP(tile, size_x, size_y, TileXY(sx, sy)) {
if (GetTileType(tile) != MP_WATER) {
SetTropicZone(tile, (_ctrl_pressed) ? TROPICZONE_NORMAL : TROPICZONE_DESERT);
DoCommandP(tile, 0, 0, CMD_LANDSCAPE_CLEAR);
MarkTileDirtyByTile(tile);
}
} END_TILE_LOOP(tile, size_x, size_y, 0);
_generating_world = false;
}
/** Scenario editor command that generates rocky areas */
static void GenerateRockyArea(TileIndex end, TileIndex start)
{
int size_x, size_y;
bool success = false;
int sx = TileX(start);
int sy = TileY(start);
int ex = TileX(end);
int ey = TileY(end);
if (_game_mode != GM_EDITOR) return;
if (ex < sx) Swap(ex, sx);
if (ey < sy) Swap(ey, sy);
size_x = (ex - sx) + 1;
size_y = (ey - sy) + 1;
BEGIN_TILE_LOOP(tile, size_x, size_y, TileXY(sx, sy)) {
switch (GetTileType(tile)) {
case MP_TREES:
if (GetTreeGround(tile) == TREE_GROUND_SHORE) continue;
/* FALL THROUGH */
case MP_CLEAR:
MakeClear(tile, CLEAR_ROCKS, 3);
break;
default: continue;
}
MarkTileDirtyByTile(tile);
success = true;
} END_TILE_LOOP(tile, size_x, size_y, 0);
if (success) SndPlayTileFx(SND_1F_SPLAT, end);
}
/**
* A central place to handle all X_AND_Y dragged GUI functions.
* @param e WindowEvent variable holding in its higher bits (excluding the lower
* 4, since that defined the X_Y drag) the type of action to be performed
* @return Returns true if the action was found and handled, and false otherwise. This
* allows for additional implements that are more local. For example X_Y drag
* of convertrail which belongs in rail_gui.cpp and not terraform_gui.cpp
**/
bool GUIPlaceProcDragXY(ViewportDragDropSelectionProcess proc, TileIndex start_tile, TileIndex end_tile)
{
if (!_settings_game.construction.freeform_edges) {
/* When end_tile is MP_VOID, the error tile will not be visible to the
* user. This happens when terraforming at the southern border. */
if (TileX(end_tile) == MapMaxX()) end_tile += TileDiffXY(-1, 0);
if (TileY(end_tile) == MapMaxY()) end_tile += TileDiffXY(0, -1);
}
switch (proc) {
case DDSP_DEMOLISH_AREA:
DoCommandP(end_tile, start_tile, 0, CMD_CLEAR_AREA | CMD_MSG(STR_00B5_CAN_T_CLEAR_THIS_AREA), CcPlaySound10);
break;
case DDSP_RAISE_AND_LEVEL_AREA:
DoCommandP(end_tile, start_tile, 1, CMD_LEVEL_LAND | CMD_MSG(STR_0808_CAN_T_RAISE_LAND_HERE), CcTerraform);
break;
case DDSP_LOWER_AND_LEVEL_AREA:
DoCommandP(end_tile, start_tile, (uint32)-1, CMD_LEVEL_LAND | CMD_MSG(STR_0809_CAN_T_LOWER_LAND_HERE), CcTerraform);
break;
case DDSP_LEVEL_AREA:
DoCommandP(end_tile, start_tile, 0, CMD_LEVEL_LAND | CMD_MSG(STR_CAN_T_LEVEL_LAND_HERE), CcTerraform);
break;
case DDSP_CREATE_ROCKS:
GenerateRockyArea(end_tile, start_tile);
break;
case DDSP_CREATE_DESERT:
GenerateDesertArea(end_tile, start_tile);
break;
default:
return false;
}
return true;
}
typedef void OnButtonClick(Window *w);
static const uint16 _terraform_keycodes[] = {
'Q',
'W',
'E',
'D',
'U',
'I',
'O',
};
void CcPlaySound1E(bool success, TileIndex tile, uint32 p1, uint32 p2);
static void PlaceProc_BuyLand(TileIndex tile)
{
DoCommandP(tile, 0, 0, CMD_PURCHASE_LAND_AREA | CMD_MSG(STR_5806_CAN_T_PURCHASE_THIS_LAND), CcPlaySound1E);
}
void PlaceProc_DemolishArea(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_DEMOLISH_AREA);
}
static void PlaceProc_RaiseLand(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_RAISE_AND_LEVEL_AREA);
}
static void PlaceProc_LowerLand(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_LOWER_AND_LEVEL_AREA);
}
static void PlaceProc_LevelLand(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_LEVEL_AREA);
}
/** Enum referring to the widgets of the terraform toolbar */
enum TerraformToolbarWidgets {
TTW_CLOSEBOX = 0, ///< Close window button
TTW_CAPTION, ///< Window caption
TTW_STICKY, ///< Sticky window button
TTW_SEPERATOR, ///< Thin seperator line between level land button and demolish button
TTW_BUTTONS_START, ///< Start of pushable buttons
TTW_LOWER_LAND = TTW_BUTTONS_START, ///< Lower land button
TTW_RAISE_LAND, ///< Raise land button
TTW_LEVEL_LAND, ///< Level land button
TTW_DEMOLISH, ///< Demolish aka dynamite button
TTW_BUY_LAND, ///< Buy land button
TTW_PLANT_TREES, ///< Plant trees button (note: opens seperate window, no place-push-button)
TTW_PLACE_SIGN, ///< Place sign button
};
static void TerraformClick_Lower(Window *w)
{
HandlePlacePushButton(w, TTW_LOWER_LAND, ANIMCURSOR_LOWERLAND, VHM_POINT, PlaceProc_LowerLand);
}
static void TerraformClick_Raise(Window *w)
{
HandlePlacePushButton(w, TTW_RAISE_LAND, ANIMCURSOR_RAISELAND, VHM_POINT, PlaceProc_RaiseLand);
}
static void TerraformClick_Level(Window *w)
{
HandlePlacePushButton(w, TTW_LEVEL_LAND, SPR_CURSOR_LEVEL_LAND, VHM_POINT, PlaceProc_LevelLand);
}
static void TerraformClick_Dynamite(Window *w)
{
HandlePlacePushButton(w, TTW_DEMOLISH, ANIMCURSOR_DEMOLISH , VHM_RECT, PlaceProc_DemolishArea);
}
static void TerraformClick_BuyLand(Window *w)
{
HandlePlacePushButton(w, TTW_BUY_LAND, SPR_CURSOR_BUY_LAND, VHM_RECT, PlaceProc_BuyLand);
}
static void TerraformClick_Trees(Window *w)
{
/* This button is NOT a place-push-button, so don't treat it as such */
ShowBuildTreesToolbar();
}
static void TerraformClick_PlaceSign(Window *w)
{
HandlePlacePushButton(w, TTW_PLACE_SIGN, SPR_CURSOR_SIGN, VHM_RECT, PlaceProc_Sign);
}
static OnButtonClick * const _terraform_button_proc[] = {
TerraformClick_Lower,
TerraformClick_Raise,
TerraformClick_Level,
TerraformClick_Dynamite,
TerraformClick_BuyLand,
TerraformClick_Trees,
TerraformClick_PlaceSign,
};
struct TerraformToolbarWindow : Window {
TerraformToolbarWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->FindWindowPlacementAndResize(desc);
}
~TerraformToolbarWindow()
{
}
virtual void OnPaint()
{
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
if (widget >= TTW_BUTTONS_START) _terraform_button_proc[widget - TTW_BUTTONS_START](this);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
for (uint i = 0; i != lengthof(_terraform_keycodes); i++) {
if (keycode == _terraform_keycodes[i]) {
_terraform_button_proc[i](this);
return ES_HANDLED;
}
}
return ES_NOT_HANDLED;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_place_proc(tile);
}
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
{
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
{
if (pt.x != -1) {
switch (select_proc) {
default: NOT_REACHED();
case DDSP_DEMOLISH_AREA:
case DDSP_RAISE_AND_LEVEL_AREA:
case DDSP_LOWER_AND_LEVEL_AREA:
case DDSP_LEVEL_AREA:
GUIPlaceProcDragXY(select_proc, start_tile, end_tile);
break;
}
}
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
}
};
static const Widget _terraform_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // TTW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 145, 0, 13, STR_LANDSCAPING_TOOLBAR, STR_018C_WINDOW_TITLE_DRAG_THIS}, // TTW_CAPTION
{WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 146, 157, 0, 13, STR_NULL, STR_STICKY_BUTTON}, // TTW_STICKY
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 66, 69, 14, 35, 0x0, STR_NULL}, // TTW_SEPERATOR
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 35, SPR_IMG_TERRAFORM_DOWN, STR_018E_LOWER_A_CORNER_OF_LAND}, // TTW_LOWER_LAND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 35, SPR_IMG_TERRAFORM_UP, STR_018F_RAISE_A_CORNER_OF_LAND}, // TTW_RAISE_LAND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 65, 14, 35, SPR_IMG_LEVEL_LAND, STR_LEVEL_LAND_TOOLTIP}, // TTW_LEVEL_LAND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 70, 91, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC}, // TTW_DEMOLISH
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 92, 113, 14, 35, SPR_IMG_BUY_LAND, STR_0329_PURCHASE_LAND_FOR_FUTURE}, // TTW_BUY_LAND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 114, 135, 14, 35, SPR_IMG_PLANTTREES, STR_0185_PLANT_TREES_PLACE_SIGNS}, // TTW_PLANT_TREES
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 136, 157, 14, 35, SPR_IMG_SIGN, STR_0289_PLACE_SIGN}, // TTW_PLACE_SIGN
{ WIDGETS_END},
};
static const WindowDesc _terraform_desc(
WDP_ALIGN_TBR, 22 + 36, 158, 36, 158, 36,
WC_SCEN_LAND_GEN, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_terraform_widgets
);
void ShowTerraformToolbar(Window *link)
{
if (!IsValidCompanyID(_local_company)) return;
Window *w = AllocateWindowDescFront<TerraformToolbarWindow>(&_terraform_desc, 0);
if (link == NULL) return;
if (w == NULL) {
w = FindWindowById(WC_SCEN_LAND_GEN, 0);
} else {
w->top = 22;
w->SetDirty();
}
if (w == NULL) return;
/* Align the terraform toolbar under the main toolbar and put the linked
* toolbar to left of it
*/
link->top = w->top;
link->left = w->left - link->width;
link->SetDirty();
}
static byte _terraform_size = 1;
/**
* Raise/Lower a bigger chunk of land at the same time in the editor. When
* raising get the lowest point, when lowering the highest point, and set all
* tiles in the selection to that height.
* @todo : Incorporate into game itself to allow for ingame raising/lowering of
* larger chunks at the same time OR remove altogether, as we have 'level land' ?
* @param tile The top-left tile where the terraforming will start
* @param mode 1 for raising, 0 for lowering land
*/
static void CommonRaiseLowerBigLand(TileIndex tile, int mode)
{
int sizex, sizey;
uint h;
if (_terraform_size == 1) {
StringID msg =
mode ? STR_0808_CAN_T_RAISE_LAND_HERE : STR_0809_CAN_T_LOWER_LAND_HERE;
DoCommandP(tile, SLOPE_N, (uint32)mode, CMD_TERRAFORM_LAND | CMD_MSG(msg), CcTerraform);
} else {
assert(_terraform_size != 0);
/* check out for map overflows */
sizex = min(MapSizeX() - TileX(tile), _terraform_size);
sizey = min(MapSizeY() - TileY(tile), _terraform_size);
if (sizex == 0 || sizey == 0) return;
SndPlayTileFx(SND_1F_SPLAT, tile);
if (mode != 0) {
/* Raise land */
h = 15; // XXX - max height
BEGIN_TILE_LOOP(tile2, sizex, sizey, tile) {
h = min(h, TileHeight(tile2));
} END_TILE_LOOP(tile2, sizex, sizey, tile)
} else {
/* Lower land */
h = 0;
BEGIN_TILE_LOOP(tile2, sizex, sizey, tile) {
h = max(h, TileHeight(tile2));
} END_TILE_LOOP(tile2, sizex, sizey, tile)
}
BEGIN_TILE_LOOP(tile2, sizex, sizey, tile) {
if (TileHeight(tile2) == h) {
DoCommandP(tile2, SLOPE_N, (uint32)mode, CMD_TERRAFORM_LAND);
}
} END_TILE_LOOP(tile2, sizex, sizey, tile)
}
}
static void PlaceProc_RaiseBigLand(TileIndex tile)
{
CommonRaiseLowerBigLand(tile, 1);
}
static void PlaceProc_LowerBigLand(TileIndex tile)
{
CommonRaiseLowerBigLand(tile, 0);
}
static void PlaceProc_RockyArea(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_CREATE_ROCKS);
}
static void PlaceProc_LightHouse(TileIndex tile)
{
/* not flat || not(trees || clear without bridge above) */
if (GetTileSlope(tile, NULL) != SLOPE_FLAT || !(IsTileType(tile, MP_TREES) || (IsTileType(tile, MP_CLEAR) && !IsBridgeAbove(tile)))) {
return;
}
MakeLighthouse(tile);
MarkTileDirtyByTile(tile);
SndPlayTileFx(SND_1F_SPLAT, tile);
}
static void PlaceProc_Transmitter(TileIndex tile)
{
/* not flat || not(trees || clear without bridge above) */
if (GetTileSlope(tile, NULL) != SLOPE_FLAT || !(IsTileType(tile, MP_TREES) || (IsTileType(tile, MP_CLEAR) && !IsBridgeAbove(tile)))) {
return;
}
MakeTransmitter(tile);
MarkTileDirtyByTile(tile);
SndPlayTileFx(SND_1F_SPLAT, tile);
}
static void PlaceProc_DesertArea(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_CREATE_DESERT);
}
static const Widget _scen_edit_land_gen_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // ETTW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 150, 0, 13, STR_0223_LAND_GENERATION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // ETTW_CAPTION
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 151, 162, 0, 13, STR_NULL, STR_STICKY_BUTTON}, // ETTW_STICKY
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 162, 14, 102, 0x0, STR_NULL}, // ETTW_BACKGROUND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 2, 23, 16, 37, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC}, // ETTW_DEMOLISH
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 24, 45, 16, 37, SPR_IMG_TERRAFORM_DOWN, STR_018E_LOWER_A_CORNER_OF_LAND}, // ETTW_LOWER_LAND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 46, 67, 16, 37, SPR_IMG_TERRAFORM_UP, STR_018F_RAISE_A_CORNER_OF_LAND}, // ETTW_RAISE_LAND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 68, 89, 16, 37, SPR_IMG_LEVEL_LAND, STR_LEVEL_LAND_TOOLTIP}, // ETTW_LEVEL_LAND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 90, 111, 16, 37, SPR_IMG_ROCKS, STR_028C_PLACE_ROCKY_AREAS_ON_LANDSCAPE}, // ETTW_PLACE_ROCKS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 112, 133, 16, 37, SPR_IMG_LIGHTHOUSE_DESERT, STR_NULL}, // ETTW_PLACE_DESERT_LIGHTHOUSE XXX - dynamic
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 134, 156, 16, 37, SPR_IMG_TRANSMITTER, STR_028E_PLACE_TRANSMITTER}, // ETTW_PLACE_TRANSMITTER
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 150, 161, 45, 56, SPR_ARROW_UP, STR_0228_INCREASE_SIZE_OF_LAND_AREA}, // ETTW_INCREASE_SIZE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 150, 161, 58, 69, SPR_ARROW_DOWN, STR_0229_DECREASE_SIZE_OF_LAND_AREA}, // ETTW_DECREASE_SIZE
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 161, 76, 87, STR_SE_NEW_WORLD, STR_022A_GENERATE_RANDOM_LAND}, // ETTW_NEW_SCENARIO
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 161, 89, 100, STR_022B_RESET_LANDSCAPE, STR_RESET_LANDSCAPE_TOOLTIP}, // ETTW_RESET_LANDSCAPE
{ WIDGETS_END},
};
static const int8 _multi_terraform_coords[][2] = {
{ 0, -2},
{ 4, 0}, { -4, 0}, { 0, 2},
{ -8, 2}, { -4, 4}, { 0, 6}, { 4, 4}, { 8, 2},
{-12, 0}, { -8, -2}, { -4, -4}, { 0, -6}, { 4, -4}, { 8, -2}, { 12, 0},
{-16, 2}, {-12, 4}, { -8, 6}, { -4, 8}, { 0, 10}, { 4, 8}, { 8, 6}, { 12, 4}, { 16, 2},
{-20, 0}, {-16, -2}, {-12, -4}, { -8, -6}, { -4, -8}, { 0,-10}, { 4, -8}, { 8, -6}, { 12, -4}, { 16, -2}, { 20, 0},
{-24, 2}, {-20, 4}, {-16, 6}, {-12, 8}, { -8, 10}, { -4, 12}, { 0, 14}, { 4, 12}, { 8, 10}, { 12, 8}, { 16, 6}, { 20, 4}, { 24, 2},
{-28, 0}, {-24, -2}, {-20, -4}, {-16, -6}, {-12, -8}, { -8,-10}, { -4,-12}, { 0,-14}, { 4,-12}, { 8,-10}, { 12, -8}, { 16, -6}, { 20, -4}, { 24, -2}, { 28, 0},
};
/** Enum referring to the widgets of the editor terraform toolbar */
enum EditorTerraformToolbarWidgets {
ETTW_START = 0, ///< Used for iterations
ETTW_CLOSEBOX = ETTW_START, ///< Close window button
ETTW_CAPTION, ///< Window caption
ETTW_STICKY, ///< Sticky window button
ETTW_BACKGROUND, ///< Background of the lower part of the window
ETTW_BUTTONS_START, ///< Start of pushable buttons
ETTW_DEMOLISH = ETTW_BUTTONS_START, ///< Demolish aka dynamite button
ETTW_LOWER_LAND, ///< Lower land button
ETTW_RAISE_LAND, ///< Raise land button
ETTW_LEVEL_LAND, ///< Level land button
ETTW_PLACE_ROCKS, ///< Place rocks button
ETTW_PLACE_DESERT_LIGHTHOUSE, ///< Place desert button (in tropical climate) / place lighthouse button (else)
ETTW_PLACE_TRANSMITTER, ///< Place transmitter button
ETTW_BUTTONS_END, ///< End of pushable buttons
ETTW_INCREASE_SIZE = ETTW_BUTTONS_END, ///< Upwards arrow button to increase terraforming size
ETTW_DECREASE_SIZE, ///< Downwards arrow button to decrease terraforming size
ETTW_NEW_SCENARIO, ///< Button for generating a new scenario
ETTW_RESET_LANDSCAPE, ///< Button for removing all company-owned property
};
/**
* @todo Merge with terraform_gui.cpp (move there) after I have cooled down at its braindeadness
* and changed OnButtonClick to include the widget as well in the function declaration. Post 0.4.0 - Darkvater
*/
static void EditorTerraformClick_Dynamite(Window *w)
{
HandlePlacePushButton(w, ETTW_DEMOLISH, ANIMCURSOR_DEMOLISH, VHM_RECT, PlaceProc_DemolishArea);
}
static void EditorTerraformClick_LowerBigLand(Window *w)
{
HandlePlacePushButton(w, ETTW_LOWER_LAND, ANIMCURSOR_LOWERLAND, VHM_POINT, PlaceProc_LowerBigLand);
}
static void EditorTerraformClick_RaiseBigLand(Window *w)
{
HandlePlacePushButton(w, ETTW_RAISE_LAND, ANIMCURSOR_RAISELAND, VHM_POINT, PlaceProc_RaiseBigLand);
}
static void EditorTerraformClick_LevelLand(Window *w)
{
HandlePlacePushButton(w, ETTW_LEVEL_LAND, SPR_CURSOR_LEVEL_LAND, VHM_POINT, PlaceProc_LevelLand);
}
static void EditorTerraformClick_RockyArea(Window *w)
{
HandlePlacePushButton(w, ETTW_PLACE_ROCKS, SPR_CURSOR_ROCKY_AREA, VHM_RECT, PlaceProc_RockyArea);
}
static void EditorTerraformClick_DesertLightHouse(Window *w)
{
HandlePlacePushButton(w, ETTW_PLACE_DESERT_LIGHTHOUSE, SPR_CURSOR_LIGHTHOUSE, VHM_RECT, (_settings_game.game_creation.landscape == LT_TROPIC) ? PlaceProc_DesertArea : PlaceProc_LightHouse);
}
static void EditorTerraformClick_Transmitter(Window *w)
{
HandlePlacePushButton(w, ETTW_PLACE_TRANSMITTER, SPR_CURSOR_TRANSMITTER, VHM_RECT, PlaceProc_Transmitter);
}
static const uint16 _editor_terraform_keycodes[] = {
'D',
'Q',
'W',
'E',
'R',
'T',
'Y'
};
typedef void OnButtonClick(Window *w);
static OnButtonClick * const _editor_terraform_button_proc[] = {
EditorTerraformClick_Dynamite,
EditorTerraformClick_LowerBigLand,
EditorTerraformClick_RaiseBigLand,
EditorTerraformClick_LevelLand,
EditorTerraformClick_RockyArea,
EditorTerraformClick_DesertLightHouse,
EditorTerraformClick_Transmitter
};
/** Callback function for the scenario editor 'reset landscape' confirmation window
* @param w Window unused
* @param confirmed boolean value, true when yes was clicked, false otherwise */
static void ResetLandscapeConfirmationCallback(Window *w, bool confirmed)
{
if (confirmed) {
Company *c;
/* Set generating_world to true to get instant-green grass after removing
* company property. */
_generating_world = true;
/* Delete all stations owned by a company */
Station *st;
FOR_ALL_STATIONS(st) {
if (IsValidCompanyID(st->owner)) delete st;
}
/* Delete all companies */
FOR_ALL_COMPANIES(c) {
ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
delete c;
}
_generating_world = false;
}
}
struct ScenarioEditorLandscapeGenerationWindow : Window {
ScenarioEditorLandscapeGenerationWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->widget[ETTW_PLACE_DESERT_LIGHTHOUSE].tooltips = (_settings_game.game_creation.landscape == LT_TROPIC) ? STR_028F_DEFINE_DESERT_AREA : STR_028D_PLACE_LIGHTHOUSE;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint() {
this->DrawWidgets();
int n = _terraform_size * _terraform_size;
const int8 *coords = &_multi_terraform_coords[0][0];
assert(n != 0);
do {
DrawSprite(SPR_WHITE_POINT, PAL_NONE, 88 + coords[0], 55 + coords[1]);
coords += 2;
} while (--n);
if (this->IsWidgetLowered(ETTW_LOWER_LAND) || this->IsWidgetLowered(ETTW_RAISE_LAND)) { // change area-size if raise/lower corner is selected
SetTileSelectSize(_terraform_size, _terraform_size);
}
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
for (uint i = 0; i != lengthof(_editor_terraform_keycodes); i++) {
if (keycode == _editor_terraform_keycodes[i]) {
_editor_terraform_button_proc[i](this);
return ES_HANDLED;
}
}
return ES_NOT_HANDLED;
}
virtual void OnClick(Point pt, int widget)
{
if (IsInsideMM(widget, ETTW_BUTTONS_START, ETTW_BUTTONS_END)) {
_editor_terraform_button_proc[widget - ETTW_BUTTONS_START](this);
} else {
switch (widget) {
case ETTW_INCREASE_SIZE:
case ETTW_DECREASE_SIZE: { // Increase/Decrease terraform size
int size = (widget == ETTW_INCREASE_SIZE) ? 1 : -1;
this->HandleButtonClick(widget);
size += _terraform_size;
if (!IsInsideMM(size, 1, 8 + 1)) return;
_terraform_size = size;
SndPlayFx(SND_15_BEEP);
this->SetDirty();
} break;
case ETTW_NEW_SCENARIO: // gen random land
this->HandleButtonClick(widget);
ShowCreateScenario();
break;
case ETTW_RESET_LANDSCAPE: // Reset landscape
ShowQuery(
STR_022C_RESET_LANDSCAPE,
STR_RESET_LANDSCAPE_CONFIRMATION_TEXT,
NULL,
ResetLandscapeConfirmationCallback);
break;
}
}
}
virtual void OnTimeout()
{
for (uint i = ETTW_START; i < this->widget_count; i++) {
if (i == ETTW_BUTTONS_START) i = ETTW_BUTTONS_END; // skip the buttons
if (this->IsWidgetLowered(i)) {
this->RaiseWidget(i);
this->InvalidateWidget(i);
}
}
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_place_proc(tile);
}
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
{
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
{
if (pt.x != -1) {
switch (select_proc) {
default: NOT_REACHED();
case DDSP_CREATE_ROCKS:
case DDSP_CREATE_DESERT:
case DDSP_RAISE_AND_LEVEL_AREA:
case DDSP_LOWER_AND_LEVEL_AREA:
case DDSP_LEVEL_AREA:
case DDSP_DEMOLISH_AREA:
GUIPlaceProcDragXY(select_proc, start_tile, end_tile);
break;
}
}
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
this->SetDirty();
}
};
static const WindowDesc _scen_edit_land_gen_desc(
WDP_AUTO, WDP_AUTO, 163, 103, 163, 103,
WC_SCEN_LAND_GEN, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_scen_edit_land_gen_widgets
);
void ShowEditorTerraformToolbar()
{
AllocateWindowDescFront<ScenarioEditorLandscapeGenerationWindow>(&_scen_edit_land_gen_desc, 0);
}
| 25,081
|
C++
|
.cpp
| 617
| 38.209076
| 193
| 0.673877
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,044
|
newgrf_industrytiles.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_industrytiles.cpp
|
/* $Id$ */
/** @file newgrf_industrytiles.cpp NewGRF handling of industry tiles. */
#include "stdafx.h"
#include "openttd.h"
#include "variables.h"
#include "debug.h"
#include "viewport_func.h"
#include "landscape.h"
#include "newgrf.h"
#include "core/random_func.hpp"
#include "newgrf_commons.h"
#include "newgrf_industries.h"
#include "newgrf_industrytiles.h"
#include "newgrf_sound.h"
#include "newgrf_text.h"
#include "industry_map.h"
#include "sprite.h"
#include "transparency.h"
#include "functions.h"
#include "town.h"
#include "command_func.h"
#include "animated_tile_func.h"
#include "water.h"
#include "table/strings.h"
/**
* Based on newhouses equivalent, but adapted for newindustries
* @param parameter from callback. It's in fact a pair of coordinates
* @param tile TileIndex from which the callback was initiated
* @param index of the industry been queried for
* @return a construction of bits obeying the newgrf format
*/
uint32 GetNearbyIndustryTileInformation(byte parameter, TileIndex tile, IndustryID index)
{
if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
bool is_same_industry = (IsTileType(tile, MP_INDUSTRY) && GetIndustryIndex(tile) == index);
return GetNearbyTileInformation(tile) | (is_same_industry ? 1 : 0) << 8;
}
/** This is the position of the tile relative to the northernmost tile of the industry.
* Format: 00yxYYXX
* Variable Content
* x the x offset from the northernmost tile
* XX same, but stored in a byte instead of a nibble
* y the y offset from the northernmost tile
* YY same, but stored in a byte instead of a nibble
* @param tile TileIndex of the tile to evaluate
* @param ind_tile northernmost tile of the industry
*/
static uint32 GetRelativePosition(TileIndex tile, TileIndex ind_tile)
{
byte x = TileX(tile) - TileX(ind_tile);
byte y = TileY(tile) - TileY(ind_tile);
return ((y & 0xF) << 20) | ((x & 0xF) << 16) | (y << 8) | x;
}
static uint32 IndustryTileGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
{
const Industry *inds = object->u.industry.ind;
TileIndex tile = object->u.industry.tile;
if (object->scope == VSG_SCOPE_PARENT) {
return IndustryGetVariable(object, variable, parameter, available);
}
switch (variable) {
/* Construction state of the tile: a value between 0 and 3 */
case 0x40: return (IsTileType(tile, MP_INDUSTRY)) ? GetIndustryConstructionStage(tile) : 0;
/* Terrain type */
case 0x41: return GetTerrainType(tile);
/* Current town zone of the tile in the nearest town */
case 0x42: return GetTownRadiusGroup(ClosestTownFromTile(tile, UINT_MAX), tile);
/* Relative position */
case 0x43: return GetRelativePosition(tile, inds->xy);
/* Animation frame. Like house variable 46 but can contain anything 0..FF. */
case 0x44: return (IsTileType(tile, MP_INDUSTRY)) ? GetIndustryAnimationState(tile) : 0;
/* Land info of nearby tiles */
case 0x60: return GetNearbyIndustryTileInformation(parameter, tile, inds == NULL ? (IndustryID)INVALID_INDUSTRY : inds->index);
/* Animation stage of nearby tiles */
case 0x61:
tile = GetNearbyTile(parameter, tile);
if (IsTileType(tile, MP_INDUSTRY) && GetIndustryByTile(tile) == inds) {
return GetIndustryAnimationState(tile);
}
return UINT_MAX;
/* Get industry tile ID at offset */
case 0x62: return GetIndustryIDAtOffset(GetNearbyTile(parameter, tile), inds);
}
DEBUG(grf, 1, "Unhandled industry tile property 0x%X", variable);
*available = false;
return UINT_MAX;
}
static const SpriteGroup *IndustryTileResolveReal(const ResolverObject *object, const SpriteGroup *group)
{
/* IndustryTile do not have 'real' groups. Or do they?? */
return NULL;
}
static uint32 IndustryTileGetRandomBits(const ResolverObject *object)
{
const TileIndex tile = object->u.industry.tile;
if (tile == INVALID_TILE || !IsTileType(tile, MP_INDUSTRY)) return 0;
return (object->scope == VSG_SCOPE_SELF) ? GetIndustryRandomBits(tile) : GetIndustryByTile(tile)->random;
}
static uint32 IndustryTileGetTriggers(const ResolverObject *object)
{
const TileIndex tile = object->u.industry.tile;
if (tile == INVALID_TILE || !IsTileType(tile, MP_INDUSTRY)) return 0;
return (object->scope == VSG_SCOPE_SELF) ? GetIndustryTriggers(tile) : GetIndustryByTile(tile)->random_triggers;
}
static void IndustryTileSetTriggers(const ResolverObject *object, int triggers)
{
const TileIndex tile = object->u.industry.tile;
if (tile == INVALID_TILE || !IsTileType(tile, MP_INDUSTRY)) return;
if (object->scope == VSG_SCOPE_SELF) {
SetIndustryTriggers(tile, triggers);
} else {
GetIndustryByTile(tile)->random_triggers = triggers;
}
}
static void NewIndustryTileResolver(ResolverObject *res, IndustryGfx gfx, TileIndex tile, Industry *indus)
{
res->GetRandomBits = IndustryTileGetRandomBits;
res->GetTriggers = IndustryTileGetTriggers;
res->SetTriggers = IndustryTileSetTriggers;
res->GetVariable = IndustryTileGetVariable;
res->ResolveReal = IndustryTileResolveReal;
res->psa = &indus->psa;
res->u.industry.tile = tile;
res->u.industry.ind = indus;
res->u.industry.gfx = gfx;
res->u.industry.type = indus->type;
res->callback = CBID_NO_CALLBACK;
res->callback_param1 = 0;
res->callback_param2 = 0;
res->last_value = 0;
res->trigger = 0;
res->reseed = 0;
res->count = 0;
const IndustryTileSpec *its = GetIndustryTileSpec(gfx);
res->grffile = (its != NULL ? its->grf_prop.grffile : NULL);
}
static void IndustryDrawTileLayout(const TileInfo *ti, const SpriteGroup *group, byte rnd_colour, byte stage, IndustryGfx gfx)
{
const DrawTileSprites *dts = group->g.layout.dts;
const DrawTileSeqStruct *dtss;
SpriteID image = dts->ground.sprite;
SpriteID pal = dts->ground.pal;
if (IS_CUSTOM_SPRITE(image)) image += stage;
if (GB(image, 0, SPRITE_WIDTH) != 0) {
/* If the ground sprite is the default flat water sprite, draw also canal/river borders
* Do not do this if the tile's WaterClass is 'land'. */
if (image == SPR_FLAT_WATER_TILE && IsIndustryTileOnWater(ti->tile)) {
DrawWaterClassGround(ti);
} else {
DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, GENERAL_SPRITE_COLOUR(rnd_colour)));
}
}
foreach_draw_tile_seq(dtss, dts->seq) {
if (GB(dtss->image.sprite, 0, SPRITE_WIDTH) == 0) continue;
image = dtss->image.sprite;
pal = dtss->image.pal;
/* Stop drawing sprite sequence once we meet a sprite that doesn't have to be opaque */
if (IsInvisibilitySet(TO_INDUSTRIES) && !HasBit(image, SPRITE_MODIFIER_OPAQUE)) return;
if (IS_CUSTOM_SPRITE(image)) image += stage;
pal = SpriteLayoutPaletteTransform(image, pal, GENERAL_SPRITE_COLOUR(rnd_colour));
if ((byte)dtss->delta_z != 0x80) {
AddSortableSpriteToDraw(
image, pal,
ti->x + dtss->delta_x, ti->y + dtss->delta_y,
dtss->size_x, dtss->size_y,
dtss->size_z, ti->z + dtss->delta_z,
!HasBit(image, SPRITE_MODIFIER_OPAQUE) && IsTransparencySet(TO_INDUSTRIES)
);
} else {
/* For industries and houses delta_x and delta_y are unsigned */
AddChildSpriteScreen(image, pal, (byte)dtss->delta_x, (byte)dtss->delta_y, !HasBit(image, SPRITE_MODIFIER_OPAQUE) && IsTransparencySet(TO_INDUSTRIES));
}
}
}
uint16 GetIndustryTileCallback(CallbackID callback, uint32 param1, uint32 param2, IndustryGfx gfx_id, Industry *industry, TileIndex tile)
{
ResolverObject object;
const SpriteGroup *group;
NewIndustryTileResolver(&object, gfx_id, tile, industry);
object.callback = callback;
object.callback_param1 = param1;
object.callback_param2 = param2;
group = Resolve(GetIndustryTileSpec(gfx_id)->grf_prop.spritegroup, &object);
if (group == NULL || group->type != SGT_CALLBACK) return CALLBACK_FAILED;
return group->g.callback.result;
}
bool DrawNewIndustryTile(TileInfo *ti, Industry *i, IndustryGfx gfx, const IndustryTileSpec *inds)
{
const SpriteGroup *group;
ResolverObject object;
if (ti->tileh != SLOPE_FLAT) {
bool draw_old_one = true;
if (HasBit(inds->callback_flags, CBM_INDT_DRAW_FOUNDATIONS)) {
/* Called to determine the type (if any) of foundation to draw for industry tile */
uint32 callback_res = GetIndustryTileCallback(CBID_INDUSTRY_DRAW_FOUNDATIONS, 0, 0, gfx, i, ti->tile);
draw_old_one = callback_res != 0;
}
if (draw_old_one) DrawFoundation(ti, FOUNDATION_LEVELED);
}
NewIndustryTileResolver(&object, gfx, ti->tile, i);
group = Resolve(inds->grf_prop.spritegroup, &object);
if (group == NULL || group->type != SGT_TILELAYOUT) {
return false;
} else {
/* Limit the building stage to the number of stages supplied. */
byte stage = GetIndustryConstructionStage(ti->tile);
stage = Clamp(stage - 4 + group->g.layout.num_sprites, 0, group->g.layout.num_sprites - 1);
IndustryDrawTileLayout(ti, group, i->random_colour, stage, gfx);
return true;
}
}
extern bool IsSlopeRefused(Slope current, Slope refused);
bool PerformIndustryTileSlopeCheck(TileIndex ind_base_tile, TileIndex ind_tile, const IndustryTileSpec *its, IndustryType type, IndustryGfx gfx, uint itspec_index)
{
Industry ind;
ind.index = INVALID_INDUSTRY;
ind.xy = ind_base_tile;
ind.width = 0;
ind.type = type;
uint16 callback_res = GetIndustryTileCallback(CBID_INDTILE_SHAPE_CHECK, 0, itspec_index, gfx, &ind, ind_tile);
if (callback_res == CALLBACK_FAILED) {
return !IsSlopeRefused(GetTileSlope(ind_tile, NULL), its->slopes_refused);
}
if (its->grf_prop.grffile->grf_version < 7) {
return callback_res != 0;
}
if (callback_res == 0x400) return true;
/* Copy some parameters from the registers to the error message text ref. stack */
SwitchToErrorRefStack();
PrepareTextRefStackUsage(4);
SwitchToNormalRefStack();
switch (callback_res) {
case 0x401: _error_message = STR_0239_SITE_UNSUITABLE; return false;
case 0x402: _error_message = STR_0317_CAN_ONLY_BE_BUILT_IN_RAINFOREST; return false;
case 0x403: _error_message = STR_0318_CAN_ONLY_BE_BUILT_IN_DESERT; return false;
default: _error_message = GetGRFStringID(its->grf_prop.grffile->grfid, 0xD000 + callback_res); return false;
}
}
void AnimateNewIndustryTile(TileIndex tile)
{
Industry *ind = GetIndustryByTile(tile);
IndustryGfx gfx = GetIndustryGfx(tile);
const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
byte animation_speed = itspec->animation_speed;
if (HasBit(itspec->callback_flags, CBM_INDT_ANIM_SPEED)) {
uint16 callback_res = GetIndustryTileCallback(CBID_INDTILE_ANIMATION_SPEED, 0, 0, gfx, ind, tile);
if (callback_res != CALLBACK_FAILED) animation_speed = Clamp(callback_res & 0xFF, 0, 16);
}
/* An animation speed of 2 means the animation frame changes 4 ticks, and
* increasing this value by one doubles the wait. 0 is the minimum value
* allowed for animation_speed, which corresponds to 30ms, and 16 is the
* maximum, corresponding to around 33 minutes. */
if ((_tick_counter % (1 << animation_speed)) != 0) return;
bool frame_set_by_callback = false;
byte frame = GetIndustryAnimationState(tile);
uint16 num_frames = GB(itspec->animation_info, 0, 8);
if (HasBit(itspec->callback_flags, CBM_INDT_ANIM_NEXT_FRAME)) {
uint16 callback_res = GetIndustryTileCallback(CBID_INDTILE_ANIM_NEXT_FRAME, HasBit(itspec->animation_special_flags, 0) ? Random() : 0, 0, gfx, ind, tile);
if (callback_res != CALLBACK_FAILED) {
frame_set_by_callback = true;
switch (callback_res & 0xFF) {
case 0xFF:
DeleteAnimatedTile(tile);
break;
case 0xFE:
/* Carry on as normal. */
frame_set_by_callback = false;
break;
default:
frame = callback_res & 0xFF;
break;
}
/* If the lower 7 bits of the upper byte of the callback
* result are not empty, it is a sound effect. */
if (GB(callback_res, 8, 7) != 0) PlayTileSound(itspec->grf_prop.grffile, GB(callback_res, 8, 7), tile);
}
}
if (!frame_set_by_callback) {
if (frame < num_frames) {
frame++;
} else if (frame == num_frames && GB(itspec->animation_info, 8, 8) == 1) {
/* This animation loops, so start again from the beginning */
frame = 0;
} else {
/* This animation doesn't loop, so stay here */
DeleteAnimatedTile(tile);
}
}
SetIndustryAnimationState(tile, frame);
MarkTileDirtyByTile(tile);
}
static void ChangeIndustryTileAnimationFrame(const IndustryTileSpec *itspec, TileIndex tile, IndustryAnimationTrigger iat, uint32 random_bits, IndustryGfx gfx, Industry *ind)
{
uint16 callback_res = GetIndustryTileCallback(CBID_INDTILE_ANIM_START_STOP, random_bits, iat, gfx, ind, tile);
if (callback_res == CALLBACK_FAILED) return;
switch (callback_res & 0xFF) {
case 0xFD: /* Do nothing. */ break;
case 0xFE: AddAnimatedTile(tile); break;
case 0xFF: DeleteAnimatedTile(tile); break;
default:
SetIndustryAnimationState(tile, callback_res & 0xFF);
AddAnimatedTile(tile);
break;
}
/* If the lower 7 bits of the upper byte of the callback
* result are not empty, it is a sound effect. */
if (GB(callback_res, 8, 7) != 0) PlayTileSound(itspec->grf_prop.grffile, GB(callback_res, 8, 7), tile);
}
bool StartStopIndustryTileAnimation(TileIndex tile, IndustryAnimationTrigger iat, uint32 random)
{
IndustryGfx gfx = GetIndustryGfx(tile);
const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
if (!HasBit(itspec->animation_triggers, iat)) return false;
Industry *ind = GetIndustryByTile(tile);
ChangeIndustryTileAnimationFrame(itspec, tile, iat, random, gfx, ind);
return true;
}
bool StartStopIndustryTileAnimation(const Industry *ind, IndustryAnimationTrigger iat)
{
bool ret = true;
uint32 random = Random();
BEGIN_TILE_LOOP(tile, ind->width, ind->height, ind->xy)
if (IsTileType(tile, MP_INDUSTRY) && GetIndustryIndex(tile) == ind->index) {
if (StartStopIndustryTileAnimation(tile, iat, random)) {
SB(random, 0, 16, Random());
} else {
ret = false;
}
}
END_TILE_LOOP(tile, ind->width, ind->height, ind->xy)
return ret;
}
static void DoTriggerIndustryTile(TileIndex tile, IndustryTileTrigger trigger, Industry *ind)
{
ResolverObject object;
IndustryGfx gfx = GetIndustryGfx(tile);
const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
if (itspec->grf_prop.spritegroup == NULL) return;
NewIndustryTileResolver(&object, gfx, tile, ind);
object.callback = CBID_RANDOM_TRIGGER;
object.trigger = trigger;
const SpriteGroup *group = Resolve(itspec->grf_prop.spritegroup, &object);
if (group == NULL) return;
byte new_random_bits = Random();
byte random_bits = GetIndustryRandomBits(tile);
random_bits &= ~object.reseed;
random_bits |= new_random_bits & object.reseed;
SetIndustryRandomBits(tile, random_bits);
}
void TriggerIndustryTile(TileIndex tile, IndustryTileTrigger trigger)
{
DoTriggerIndustryTile(tile, trigger, GetIndustryByTile(tile));
}
void TriggerIndustry(Industry *ind, IndustryTileTrigger trigger)
{
BEGIN_TILE_LOOP(tile, ind->width, ind->height, ind->xy)
if (IsTileType(tile, MP_INDUSTRY) && GetIndustryIndex(tile) == ind->index) {
DoTriggerIndustryTile(tile, trigger, ind);
}
END_TILE_LOOP(tile, ind->width, ind->height, ind->xy)
}
| 15,221
|
C++
|
.cpp
| 361
| 39.634349
| 174
| 0.735133
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,045
|
train_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/train_gui.cpp
|
/* $Id$ */
/** @file train_gui.cpp GUI for trains. */
#include "stdafx.h"
#include "window_gui.h"
#include "gfx_func.h"
#include "command_func.h"
#include "vehicle_gui.h"
#include "train.h"
#include "newgrf_engine.h"
#include "strings_func.h"
#include "vehicle_func.h"
#include "engine_base.h"
#include "window_func.h"
#include "settings_type.h"
#include "table/sprites.h"
#include "table/strings.h"
void CcBuildWagon(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (!success) return;
/* find a locomotive in the depot. */
const Vehicle *found = NULL;
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN && IsFrontEngine(v) &&
v->tile == tile &&
v->u.rail.track == TRACK_BIT_DEPOT) {
if (found != NULL) return; // must be exactly one.
found = v;
}
}
/* if we found a loco, */
if (found != NULL) {
found = GetLastVehicleInChain(found);
/* put the new wagon at the end of the loco. */
DoCommandP(0, _new_vehicle_id | (found->index << 16), 0, CMD_MOVE_RAIL_VEHICLE);
InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
}
}
void CcBuildLoco(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (!success) return;
const Vehicle *v = GetVehicle(_new_vehicle_id);
if (tile == _backup_orders_tile) {
_backup_orders_tile = 0;
RestoreVehicleOrders(v);
}
ShowVehicleViewWindow(v);
}
/**
* Get the number of pixels for the given wagon length.
* @param len Length measured in 1/8ths of a standard wagon.
* @return Number of pixels across.
*/
int WagonLengthToPixels(int len)
{
return (len * _traininfo_vehicle_width) / 8;
}
void DrawTrainImage(const Vehicle *v, int x, int y, VehicleID selection, int count, int skip)
{
DrawPixelInfo tmp_dpi, *old_dpi;
int dx = -(skip * 8) / _traininfo_vehicle_width;
/* Position of highlight box */
int highlight_l = 0;
int highlight_r = 0;
if (!FillDrawPixelInfo(&tmp_dpi, x - 2, y - 1, count + 1, 14)) return;
count = (count * 8) / _traininfo_vehicle_width;
old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
do {
int width = v->u.rail.cached_veh_length;
if (dx + width > 0) {
if (dx <= count) {
SpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
DrawSprite(v->GetImage(DIR_W), pal, 16 + WagonLengthToPixels(dx), 7 + (is_custom_sprite(RailVehInfo(v->engine_type)->image_index) ? _traininfo_vehicle_pitch : 0));
if (v->index == selection) {
/* Set the highlight position */
highlight_l = WagonLengthToPixels(dx) + 1;
highlight_r = WagonLengthToPixels(dx + width) + 1;
} else if (_cursor.vehchain && highlight_r != 0) {
highlight_r += WagonLengthToPixels(width);
}
}
}
dx += width;
v = v->Next();
} while (dx < count && v != NULL);
if (highlight_l != highlight_r) {
/* Draw the highlight. Now done after drawing all the engines, as
* the next engine after the highlight could overlap it. */
DrawFrameRect(highlight_l, 0, highlight_r, 13, COLOUR_WHITE, FR_BORDERONLY);
}
_cur_dpi = old_dpi;
}
static void TrainDetailsCargoTab(const Vehicle *v, int x, int y)
{
if (v->cargo_cap != 0) {
StringID str = STR_8812_EMPTY;
if (!v->cargo.Empty()) {
SetDParam(0, v->cargo_type);
SetDParam(1, v->cargo.Count());
SetDParam(2, v->cargo.Source());
SetDParam(3, _settings_game.vehicle.freight_trains);
str = FreightWagonMult(v->cargo_type) > 1 ? STR_FROM_MULT : STR_8813_FROM;
}
DrawString(x, y, str, TC_FROMSTRING);
}
}
static void TrainDetailsInfoTab(const Vehicle *v, int x, int y)
{
if (RailVehInfo(v->engine_type)->railveh_type == RAILVEH_WAGON) {
SetDParam(0, v->engine_type);
SetDParam(1, v->value);
DrawString(x, y, STR_882D_VALUE, TC_BLACK);
} else {
SetDParam(0, v->engine_type);
SetDParam(1, v->build_year);
SetDParam(2, v->value);
DrawString(x, y, STR_882C_BUILT_VALUE, TC_BLACK);
}
}
static void TrainDetailsCapacityTab(const Vehicle *v, int x, int y)
{
if (v->cargo_cap != 0) {
SetDParam(0, v->cargo_type);
SetDParam(1, v->cargo_cap);
SetDParam(2, GetCargoSubtypeText(v));
SetDParam(3, _settings_game.vehicle.freight_trains);
DrawString(x, y, FreightWagonMult(v->cargo_type) > 1 ? STR_CAPACITY_MULT : STR_013F_CAPACITY, TC_FROMSTRING);
}
}
int GetTrainDetailsWndVScroll(VehicleID veh_id, byte det_tab)
{
AcceptedCargo act_cargo;
AcceptedCargo max_cargo;
int num = 0;
if (det_tab == 3) { // Total cargo tab
memset(max_cargo, 0, sizeof(max_cargo));
memset(act_cargo, 0, sizeof(act_cargo));
for (const Vehicle *v = GetVehicle(veh_id) ; v != NULL ; v = v->Next()) {
act_cargo[v->cargo_type] += v->cargo.Count();
max_cargo[v->cargo_type] += v->cargo_cap;
}
/* Set scroll-amount seperately from counting, as to not compute num double
* for more carriages of the same type
*/
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (max_cargo[i] > 0) num++; // only count carriages that the train has
}
num++; // needs one more because first line is description string
} else {
for (const Vehicle *v = GetVehicle(veh_id) ; v != NULL ; v = v->Next()) {
if (!IsArticulatedPart(v) || v->cargo_cap != 0) num++;
}
}
return num;
}
void DrawTrainDetails(const Vehicle *v, int x, int y, int vscroll_pos, uint16 vscroll_cap, byte det_tab)
{
/* draw the first 3 details tabs */
if (det_tab != 3) {
const Vehicle *u = v;
x = 1;
for (;;) {
if (--vscroll_pos < 0 && vscroll_pos >= -vscroll_cap) {
int dx = 0;
u = v;
do {
SpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
DrawSprite(u->GetImage(DIR_W), pal, x + WagonLengthToPixels(4 + dx), y + 6 + (is_custom_sprite(RailVehInfo(u->engine_type)->image_index) ? _traininfo_vehicle_pitch : 0));
dx += u->u.rail.cached_veh_length;
u = u->Next();
} while (u != NULL && IsArticulatedPart(u) && u->cargo_cap == 0);
int px = x + WagonLengthToPixels(dx) + 2;
int py = y + 2;
switch (det_tab) {
default: NOT_REACHED();
case 0: TrainDetailsCargoTab( v, px, py); break;
case 1:
/* Only show name and value for the 'real' part */
if (!IsArticulatedPart(v)) {
TrainDetailsInfoTab(v, px, py);
}
break;
case 2: TrainDetailsCapacityTab(v, px, py); break;
}
y += 14;
v = u;
} else {
/* Move to the next line */
do {
v = v->Next();
} while (v != NULL && IsArticulatedPart(v) && v->cargo_cap == 0);
}
if (v == NULL) return;
}
} else {
AcceptedCargo act_cargo;
AcceptedCargo max_cargo;
Money feeder_share = 0;
memset(max_cargo, 0, sizeof(max_cargo));
memset(act_cargo, 0, sizeof(act_cargo));
for (const Vehicle *u = v; u != NULL ; u = u->Next()) {
act_cargo[u->cargo_type] += u->cargo.Count();
max_cargo[u->cargo_type] += u->cargo_cap;
feeder_share += u->cargo.FeederShare();
}
/* draw total cargo tab */
DrawString(x, y + 2, STR_TOTAL_CAPACITY_TEXT, TC_FROMSTRING);
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (max_cargo[i] > 0 && --vscroll_pos < 0 && vscroll_pos > -vscroll_cap) {
y += 14;
SetDParam(0, i); // {CARGO} #1
SetDParam(1, act_cargo[i]); // {CARGO} #2
SetDParam(2, i); // {SHORTCARGO} #1
SetDParam(3, max_cargo[i]); // {SHORTCARGO} #2
SetDParam(4, _settings_game.vehicle.freight_trains);
DrawString(x, y + 2, FreightWagonMult(i) > 1 ? STR_TOTAL_CAPACITY_MULT : STR_TOTAL_CAPACITY, TC_FROMSTRING);
}
}
SetDParam(0, feeder_share);
DrawString(x, y + 15, STR_FEEDER_CARGO_VALUE, TC_FROMSTRING);
}
}
| 7,529
|
C++
|
.cpp
| 223
| 30.609865
| 175
| 0.648377
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,046
|
currency.cpp
|
EnergeticBark_OpenTTD-3DS/src/currency.cpp
|
/* $Id$ */
/** @file currency.cpp Support for different currencies. */
#include "stdafx.h"
#include "currency.h"
#include "news_func.h"
#include "settings_type.h"
#include "date_func.h"
#include "table/strings.h"
/* exchange rate prefix symbol_pos
* | separator | postfix |
* | | Euro year | | | name
* | | | | | | | */
static const CurrencySpec origin_currency_specs[NUM_CURRENCY] = {
{ 1, ',', CF_NOEURO, "\xC2\xA3", "", 0, STR_CURR_GBP }, ///< british pounds
{ 2, ',', CF_NOEURO, "$", "", 0, STR_CURR_USD }, ///< us dollars
{ 2, ',', CF_ISEURO, "\xE2\x82\xAC", "", 0, STR_CURR_EUR }, ///< Euro
{ 220, ',', CF_NOEURO, "\xC2\xA5", "", 0, STR_CURR_YEN }, ///< yen
{ 20, ',', 2002, "", " S.", 1, STR_CURR_ATS }, ///< austrian schilling
{ 59, ',', 2002, "BEF ", "", 0, STR_CURR_BEF }, ///< belgian franc
{ 2, ',', CF_NOEURO, "CHF ", "", 0, STR_CURR_CHF }, ///< swiss franc
{ 41, ',', CF_NOEURO, "", " K\xC4\x8D", 1, STR_CURR_CZK }, ///< czech koruna
{ 3, '.', 2002, "DM ", "", 0, STR_CURR_DEM }, ///< deutsche mark
{ 11, '.', CF_NOEURO, "", " kr", 1, STR_CURR_DKK }, ///< danish krone
{ 245, '.', 2002, "Pts ", "", 0, STR_CURR_ESP }, ///< spanish pesetas
{ 9, ',', 2002, "", " mk", 1, STR_CURR_FIM }, ///< finnish markka
{ 10, '.', 2002, "FF ", "", 0, STR_CURR_FRF }, ///< french francs
{ 500, ',', 2002, "", "Dr.", 1, STR_CURR_GRD }, ///< greek drachma
{ 378, ',', CF_NOEURO, "", " Ft", 1, STR_CURR_HUF }, ///< hungarian forint
{ 130, '.', CF_NOEURO, "", " Kr", 1, STR_CURR_ISK }, ///< icelandic krona
{ 2850, ',', 2002, "", " L.", 1, STR_CURR_ITL }, ///< italian lira
{ 3, ',', 2002, "NLG ", "", 0, STR_CURR_NLG }, ///< dutch gulden
{ 12, '.', CF_NOEURO, "", " Kr", 1, STR_CURR_NOK }, ///< norwegian krone
{ 6, ' ', CF_NOEURO, "", " zl", 1, STR_CURR_PLN }, ///< polish zloty
{ 5, '.', CF_NOEURO, "", " Lei", 1, STR_CURR_ROL }, ///< romanian Lei
{ 50, ' ', CF_NOEURO, "", " p", 1, STR_CURR_RUR }, ///< russian rouble
{ 352, '.', 2007, "", " SIT", 1, STR_CURR_SIT }, ///< slovenian tolar
{ 13, '.', CF_NOEURO, "", " Kr", 1, STR_CURR_SEK }, ///< swedish krona
{ 3, '.', CF_NOEURO, "", " TL", 1, STR_CURR_TRY }, ///< turkish lira
{ 52, ',', 2009, "", " Sk", 1, STR_CURR_SKK }, ///< slovak koruna
{ 4, ',', CF_NOEURO, "R$ ", "", 0, STR_CURR_BRL }, ///< brazil real
{ 20, '.', CF_NOEURO, "", " EEK", 1, STR_CURR_EEK }, ///< estonian krooni
{ 1, ' ', CF_NOEURO, "", "", 2, STR_CURR_CUSTOM }, ///< custom currency
};
/* Array of currencies used by the system */
CurrencySpec _currency_specs[NUM_CURRENCY];
/**
* These enums are only declared in order to make sens
* out of the TTDPatch_To_OTTDIndex array that will follow
* Every currency used by Ottd is there, just in case TTDPatch will
* add those missing in its code
**/
enum {
CURR_GBP,
CURR_USD,
CURR_EUR,
CURR_YEN,
CURR_ATS,
CURR_BEF,
CURR_CHF,
CURR_CZK,
CURR_DEM,
CURR_DKK,
CURR_ESP,
CURR_FIM,
CURR_FRF,
CURR_GRD,
CURR_HUF,
CURR_ISK,
CURR_ITL,
CURR_NLG,
CURR_NOK,
CURR_PLN,
CURR_ROL,
CURR_RUR,
CURR_SIT,
CURR_SEK,
CURR_YTL,
CURR_SKK,
CURR_BRL,
CURR_EEK,
};
/**
* This array represent the position of OpenTTD's currencies,
* compared to TTDPatch's ones.
* When a grf sends currencies, they are based on the order defined by TTDPatch.
* So, we must reindex them to our own order.
**/
const byte TTDPatch_To_OTTDIndex[] =
{
CURR_GBP,
CURR_USD,
CURR_FRF,
CURR_DEM,
CURR_YEN,
CURR_ESP,
CURR_HUF,
CURR_PLN,
CURR_ATS,
CURR_BEF,
CURR_DKK,
CURR_FIM,
CURR_GRD,
CURR_CHF,
CURR_NLG,
CURR_ITL,
CURR_SEK,
CURR_RUR,
CURR_EUR,
};
/**
* Will return the ottd's index correspondance to
* the ttdpatch's id. If the id is bigger than the array,
* it is a grf written for ottd, thus returning the same id.
* Only called from newgrf.cpp
* @param grfcurr_id currency id coming from newgrf
* @return the corrected index
**/
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id)
{
return (grfcurr_id >= lengthof(TTDPatch_To_OTTDIndex)) ? grfcurr_id : TTDPatch_To_OTTDIndex[grfcurr_id];
}
/**
* get a mask of the allowed currencies depending on the year
* @return mask of currencies
*/
uint GetMaskOfAllowedCurrencies()
{
uint mask = 0;
uint i;
for (i = 0; i < NUM_CURRENCY; i++) {
Year to_euro = _currency_specs[i].to_euro;
if (to_euro != CF_NOEURO && to_euro != CF_ISEURO && _cur_year >= to_euro) continue;
if (to_euro == CF_ISEURO && _cur_year < 2000) continue;
mask |= (1 << i);
}
mask |= (1 << CUSTOM_CURRENCY_ID); // always allow custom currency
return mask;
}
/**
* Verify if the currency chosen by the user is about to be converted to Euro
**/
void CheckSwitchToEuro()
{
if (_currency_specs[_settings_game.locale.currency].to_euro != CF_NOEURO &&
_currency_specs[_settings_game.locale.currency].to_euro != CF_ISEURO &&
_cur_year >= _currency_specs[_settings_game.locale.currency].to_euro) {
_settings_game.locale.currency = 2; // this is the index of euro above.
AddNewsItem(STR_EURO_INTRODUCE, NS_ECONOMY, 0, 0);
}
}
/**
* Will fill _currency_specs array with
* default values from origin_currency_specs
* Called only from newgrf.cpp and settings.cpp.
* @param preserve_custom will not reset custom currency (the latest one on the list)
* if ever it is flagged to true. In which case, the total size of the memory to move
* will be one currency spec less, thus preserving the custom curreny from been
* overwritten.
**/
void ResetCurrencies(bool preserve_custom)
{
memcpy(&_currency_specs, &origin_currency_specs, sizeof(origin_currency_specs) - (preserve_custom ? sizeof(_custom_currency) : 0));
}
/**
* Build a list of currency names StringIDs to use in a dropdown list
* @return Pointer to a (static) array of StringIDs
*/
StringID *BuildCurrencyDropdown()
{
/* Allow room for all currencies, plus a terminator entry */
static StringID names[NUM_CURRENCY + 1];
uint i;
/* Add each name */
for (i = 0; i < NUM_CURRENCY; i++) {
names[i] = _currency_specs[i].name;
}
/* Terminate the list */
names[i] = INVALID_STRING_ID;
return names;
}
| 6,915
|
C++
|
.cpp
| 180
| 36.466667
| 132
| 0.55291
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,047
|
autoreplace.cpp
|
EnergeticBark_OpenTTD-3DS/src/autoreplace.cpp
|
/* $Id$ */
/** @file autoreplace.cpp Management of replacement lists. */
#include "stdafx.h"
#include "command_func.h"
#include "group.h"
#include "autoreplace_base.h"
#include "oldpool_func.h"
DEFINE_OLD_POOL_GENERIC(EngineRenew, EngineRenew)
/**
* Retrieves the EngineRenew that specifies the replacement of the given
* engine type from the given renewlist */
static EngineRenew *GetEngineReplacement(EngineRenewList erl, EngineID engine, GroupID group)
{
EngineRenew *er = (EngineRenew *)erl;
while (er) {
if (er->from == engine && er->group_id == group) return er;
er = er->next;
}
return NULL;
}
void RemoveAllEngineReplacement(EngineRenewList *erl)
{
EngineRenew *er = (EngineRenew *)(*erl);
EngineRenew *next;
while (er != NULL) {
next = er->next;
delete er;
er = next;
}
*erl = NULL; // Empty list
}
EngineID EngineReplacement(EngineRenewList erl, EngineID engine, GroupID group)
{
const EngineRenew *er = GetEngineReplacement(erl, engine, group);
if (er == NULL && (group == DEFAULT_GROUP || (IsValidGroupID(group) && !GetGroup(group)->replace_protection))) {
/* We didn't find anything useful in the vehicle's own group so we will try ALL_GROUP */
er = GetEngineReplacement(erl, engine, ALL_GROUP);
}
return er == NULL ? INVALID_ENGINE : er->to;
}
CommandCost AddEngineReplacement(EngineRenewList *erl, EngineID old_engine, EngineID new_engine, GroupID group, DoCommandFlag flags)
{
EngineRenew *er;
/* Check if the old vehicle is already in the list */
er = GetEngineReplacement(*erl, old_engine, group);
if (er != NULL) {
if (flags & DC_EXEC) er->to = new_engine;
return CommandCost();
}
if (!EngineRenew::CanAllocateItem()) return CMD_ERROR;
if (flags & DC_EXEC) {
er = new EngineRenew(old_engine, new_engine);
er->group_id = group;
/* Insert before the first element */
er->next = (EngineRenew *)(*erl);
*erl = (EngineRenewList)er;
}
return CommandCost();
}
CommandCost RemoveEngineReplacement(EngineRenewList *erl, EngineID engine, GroupID group, DoCommandFlag flags)
{
EngineRenew *er = (EngineRenew *)(*erl);
EngineRenew *prev = NULL;
while (er)
{
if (er->from == engine && er->group_id == group) {
if (flags & DC_EXEC) {
if (prev == NULL) { // First element
/* The second becomes the new first element */
*erl = (EngineRenewList)er->next;
} else {
/* Cut this element out */
prev->next = er->next;
}
delete er;
}
return CommandCost();
}
prev = er;
er = er->next;
}
return CMD_ERROR;
}
void InitializeEngineRenews()
{
/* Clean the engine renew pool and create 1 block in it */
_EngineRenew_pool.CleanPool();
_EngineRenew_pool.AddBlockToPool();
}
| 2,695
|
C++
|
.cpp
| 89
| 27.797753
| 132
| 0.705951
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,048
|
callback_table.cpp
|
EnergeticBark_OpenTTD-3DS/src/callback_table.cpp
|
/* $Id$ */
/** @file callback_table.cpp All command callbacks. */
#include "stdafx.h"
#include "callback_table.h"
#include "command_type.h"
/* If you add a callback for DoCommandP, also add the callback in here
* see below for the full list!
* If you don't do it, it won't work across the network!! */
/* aircraft_gui.cpp */
CommandCallback CcBuildAircraft;
/* airport_gui.cpp */
CommandCallback CcBuildAirport;
/* bridge_gui.cpp */
CommandCallback CcBuildBridge;
/* dock_gui.cpp */
CommandCallback CcBuildDocks;
CommandCallback CcBuildCanal;
/* depot_gui.cpp */
CommandCallback CcCloneVehicle;
/* main_gui.cpp */
CommandCallback CcPlaySound10;
CommandCallback CcPlaceSign;
CommandCallback CcTerraform;
CommandCallback CcBuildTown;
CommandCallback CcGiveMoney;
/* rail_gui.cpp */
CommandCallback CcPlaySound1E;
CommandCallback CcRailDepot;
CommandCallback CcStation;
CommandCallback CcBuildRailTunnel;
/* road_gui.cpp */
CommandCallback CcPlaySound1D;
CommandCallback CcBuildRoadTunnel;
CommandCallback CcRoadDepot;
/* roadveh_gui.cpp */
CommandCallback CcBuildRoadVeh;
/* ship_gui.cpp */
CommandCallback CcBuildShip;
/* train_gui.cpp */
CommandCallback CcBuildWagon;
CommandCallback CcBuildLoco;
/* ai/ai_core.cpp */
CommandCallback CcAI;
CommandCallback *_callback_table[] = {
/* 0x00 */ NULL,
/* 0x01 */ CcBuildAircraft,
/* 0x02 */ CcBuildAirport,
/* 0x03 */ CcBuildBridge,
/* 0x04 */ CcBuildCanal,
/* 0x05 */ CcBuildDocks,
/* 0x06 */ CcBuildLoco,
/* 0x07 */ CcBuildRoadVeh,
/* 0x08 */ CcBuildShip,
/* 0x09 */ CcBuildTown,
/* 0x0A */ CcBuildRoadTunnel,
/* 0x0B */ CcBuildRailTunnel,
/* 0x0C */ CcBuildWagon,
/* 0x0D */ CcRoadDepot,
/* 0x0E */ CcRailDepot,
/* 0x0F */ CcPlaceSign,
/* 0x10 */ CcPlaySound10,
/* 0x11 */ CcPlaySound1D,
/* 0x12 */ CcPlaySound1E,
/* 0x13 */ CcStation,
/* 0x14 */ CcTerraform,
/* 0x15 */ CcAI,
/* 0x16 */ CcCloneVehicle,
/* 0x17 */ CcGiveMoney,
};
const int _callback_table_count = lengthof(_callback_table);
| 1,984
|
C++
|
.cpp
| 70
| 26.728571
| 70
| 0.751186
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,049
|
settings.cpp
|
EnergeticBark_OpenTTD-3DS/src/settings.cpp
|
/* $Id$ */
/** @file settings.cpp
* All actions handling saving and loading of the settings/configuration goes on in this file.
* The file consists of four parts:
* <ol>
* <li>Parsing the configuration file (openttd.cfg). This is achieved with the ini_ functions which
* handle various types, such as normal 'key = value' pairs, lists and value combinations of
* lists, strings, integers, 'bit'-masks and element selections.
* <li>Defining the data structures that go into the configuration. These include for example
* the _settings struct, but also network-settings, banlists, newgrf, etc. There are a lot
* of helper macros available for the various types, and also saving/loading of these settings
* in a savegame is handled inside these structures.
* <li>Handle reading and writing to the setting-structures from inside the game either from
* the console for example or through the gui with CMD_ functions.
* <li>Handle saving/loading of the PATS chunk inside the savegame.
* </ol>
* @see SettingDesc
* @see SaveLoad
*/
#include "stdafx.h"
#include "openttd.h"
#include "currency.h"
#include "screenshot.h"
#include "variables.h"
#include "network/network.h"
#include "network/network_func.h"
#include "settings_internal.h"
#include "command_func.h"
#include "console_func.h"
#include "npf.h"
#include "yapf/yapf.h"
#include "genworld.h"
#include "train.h"
#include "news_func.h"
#include "window_func.h"
#include "strings_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "company_func.h"
#include "rev.h"
#ifdef WITH_FREETYPE
#include "fontcache.h"
#endif
#include "textbuf_gui.h"
#include "rail_gui.h"
#include "elrail_func.h"
#include "gui.h"
#include "town.h"
#include "video/video_driver.hpp"
#include "sound/sound_driver.hpp"
#include "music/music_driver.hpp"
#include "blitter/factory.hpp"
#include "gfxinit.h"
#include "gamelog.h"
#include "station_func.h"
#include "settings_func.h"
#include "ini_type.h"
#include "ai/ai_config.hpp"
#include "newgrf.h"
#include "engine_base.h"
#include "void_map.h"
#include "station_base.h"
#include "table/strings.h"
ClientSettings _settings_client;
GameSettings _settings_game;
GameSettings _settings_newgame;
typedef const char *SettingListCallbackProc(const IniItem *item, uint index);
typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
typedef void SettingDescProcList(IniFile *ini, const char *grpname, char **list, uint len, SettingListCallbackProc proc);
static bool IsSignedVarMemType(VarType vt);
/**
* Groups in openttd.cfg that are actually lists.
*/
static const char *_list_group_names[] = {
"bans",
"newgrf",
"servers",
NULL
};
/** Find the index value of a ONEofMANY type in a string seperated by |
* @param many full domain of values the ONEofMANY setting can have
* @param one the current value of the setting for which a value needs found
* @param onelen force calculation of the *one parameter
* @return the integer index of the full-list, or -1 if not found */
static int lookup_oneofmany(const char *many, const char *one, size_t onelen = 0)
{
const char *s;
int idx;
if (onelen == 0) onelen = strlen(one);
/* check if it's an integer */
if (*one >= '0' && *one <= '9')
return strtoul(one, NULL, 0);
idx = 0;
for (;;) {
/* find end of item */
s = many;
while (*s != '|' && *s != 0) s++;
if ((size_t)(s - many) == onelen && !memcmp(one, many, onelen)) return idx;
if (*s == 0) return -1;
many = s + 1;
idx++;
}
}
/** Find the set-integer value MANYofMANY type in a string
* @param many full domain of values the MANYofMANY setting can have
* @param str the current string value of the setting, each individual
* of seperated by a whitespace,tab or | character
* @return the 'fully' set integer, or -1 if a set is not found */
static uint32 lookup_manyofmany(const char *many, const char *str)
{
const char *s;
int r;
uint32 res = 0;
for (;;) {
/* skip "whitespace" */
while (*str == ' ' || *str == '\t' || *str == '|') str++;
if (*str == 0) break;
s = str;
while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
r = lookup_oneofmany(many, str, s - str);
if (r == -1) return (uint32)-1;
SetBit(res, r); // value found, set it
if (*s == 0) break;
str = s + 1;
}
return res;
}
/** Parse an integerlist string and set each found value
* @param p the string to be parsed. Each element in the list is seperated by a
* comma or a space character
* @param items pointer to the integerlist-array that will be filled with values
* @param maxitems the maximum number of elements the integerlist-array has
* @return returns the number of items found, or -1 on an error */
static int parse_intlist(const char *p, int *items, int maxitems)
{
int n = 0, v;
char *end;
for (;;) {
v = strtol(p, &end, 0);
if (p == end || n == maxitems) return -1;
p = end;
items[n++] = v;
if (*p == '\0') break;
if (*p != ',' && *p != ' ') return -1;
p++;
}
return n;
}
/** Load parsed string-values into an integer-array (intlist)
* @param str the string that contains the values (and will be parsed)
* @param array pointer to the integer-arrays that will be filled
* @param nelems the number of elements the array holds. Maximum is 64 elements
* @param type the type of elements the array holds (eg INT8, UINT16, etc.)
* @return return true on success and false on error */
static bool load_intlist(const char *str, void *array, int nelems, VarType type)
{
int items[64];
int i, nitems;
if (str == NULL) {
memset(items, 0, sizeof(items));
nitems = nelems;
} else {
nitems = parse_intlist(str, items, lengthof(items));
if (nitems != nelems) return false;
}
switch (type) {
case SLE_VAR_BL:
case SLE_VAR_I8:
case SLE_VAR_U8:
for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
break;
case SLE_VAR_I16:
case SLE_VAR_U16:
for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
break;
case SLE_VAR_I32:
case SLE_VAR_U32:
for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
break;
default: NOT_REACHED();
}
return true;
}
/** Convert an integer-array (intlist) to a string representation. Each value
* is seperated by a comma or a space character
* @param buf output buffer where the string-representation will be stored
* @param last last item to write to in the output buffer
* @param array pointer to the integer-arrays that is read from
* @param nelems the number of elements the array holds.
* @param type the type of elements the array holds (eg INT8, UINT16, etc.) */
static void make_intlist(char *buf, const char *last, const void *array, int nelems, VarType type)
{
int i, v = 0;
const byte *p = (const byte*)array;
for (i = 0; i != nelems; i++) {
switch (type) {
case SLE_VAR_BL:
case SLE_VAR_I8: v = *(int8*)p; p += 1; break;
case SLE_VAR_U8: v = *(byte*)p; p += 1; break;
case SLE_VAR_I16: v = *(int16*)p; p += 2; break;
case SLE_VAR_U16: v = *(uint16*)p; p += 2; break;
case SLE_VAR_I32: v = *(int32*)p; p += 4; break;
case SLE_VAR_U32: v = *(uint32*)p; p += 4; break;
default: NOT_REACHED();
}
buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
}
}
/** Convert a ONEofMANY structure to a string representation.
* @param buf output buffer where the string-representation will be stored
* @param last last item to write to in the output buffer
* @param many the full-domain string of possible values
* @param id the value of the variable and whose string-representation must be found */
static void make_oneofmany(char *buf, const char *last, const char *many, int id)
{
int orig_id = id;
/* Look for the id'th element */
while (--id >= 0) {
for (; *many != '|'; many++) {
if (*many == '\0') { // not found
seprintf(buf, last, "%d", orig_id);
return;
}
}
many++; // pass the |-character
}
/* copy string until next item (|) or the end of the list if this is the last one */
while (*many != '\0' && *many != '|' && buf < last) *buf++ = *many++;
*buf = '\0';
}
/** Convert a MANYofMANY structure to a string representation.
* @param buf output buffer where the string-representation will be stored
* @param last last item to write to in the output buffer
* @param many the full-domain string of possible values
* @param x the value of the variable and whose string-representation must
* be found in the bitmasked many string */
static void make_manyofmany(char *buf, const char *last, const char *many, uint32 x)
{
const char *start;
int i = 0;
bool init = true;
for (; x != 0; x >>= 1, i++) {
start = many;
while (*many != 0 && *many != '|') many++; // advance to the next element
if (HasBit(x, 0)) { // item found, copy it
if (!init) buf += seprintf(buf, last, "|");
init = false;
if (start == many) {
buf += seprintf(buf, last, "%d", i);
} else {
memcpy(buf, start, many - start);
buf += many - start;
}
}
if (*many == '|') many++;
}
*buf = '\0';
}
/** Convert a string representation (external) of a setting to the internal rep.
* @param desc SettingDesc struct that holds all information about the variable
* @param str input string that will be parsed based on the type of desc
* @return return the parsed value of the setting */
static const void *string_to_val(const SettingDescBase *desc, const char *str)
{
switch (desc->cmd) {
case SDT_NUMX: {
char *end;
unsigned long val = strtoul(str, &end, 0);
if (*end != '\0') ShowInfoF("ini: trailing characters at end of setting '%s'", desc->name);
return (void*)val;
}
case SDT_ONEOFMANY: {
long r = lookup_oneofmany(desc->many, str);
/* if the first attempt of conversion from string to the appropriate value fails,
* look if we have defined a converter from old value to new value. */
if (r == -1 && desc->proc_cnvt != NULL) r = desc->proc_cnvt(str);
if (r != -1) return (void*)r; // and here goes converted value
ShowInfoF("ini: invalid value '%s' for '%s'", str, desc->name); // sorry, we failed
return 0;
}
case SDT_MANYOFMANY: {
unsigned long r = lookup_manyofmany(desc->many, str);
if (r != (unsigned long)-1) return (void*)r;
ShowInfoF("ini: invalid value '%s' for '%s'", str, desc->name);
return 0;
}
case SDT_BOOLX:
if (strcmp(str, "true") == 0 || strcmp(str, "on") == 0 || strcmp(str, "1") == 0)
return (void*)true;
if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0)
return (void*)false;
ShowInfoF("ini: invalid setting value '%s' for '%s'", str, desc->name);
break;
case SDT_STRING:
case SDT_INTLIST: return str;
default: break;
}
return NULL;
}
/** Set the value of a setting and if needed clamp the value to
* the preset minimum and maximum.
* @param ptr the variable itself
* @param sd pointer to the 'information'-database of the variable
* @param val signed long version of the new value
* @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
* SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now */
static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
{
const SettingDescBase *sdb = &sd->desc;
if (sdb->cmd != SDT_BOOLX &&
sdb->cmd != SDT_NUMX &&
sdb->cmd != SDT_ONEOFMANY &&
sdb->cmd != SDT_MANYOFMANY) {
return;
}
/* We cannot know the maximum value of a bitset variable, so just have faith */
if (sdb->cmd != SDT_MANYOFMANY) {
/* We need to take special care of the uint32 type as we receive from the function
* a signed integer. While here also bail out on 64-bit settings as those are not
* supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
* 32-bit variable
* TODO: Support 64-bit settings/variables */
switch (GetVarMemType(sd->save.conv)) {
case SLE_VAR_NULL: return;
case SLE_VAR_BL:
case SLE_VAR_I8:
case SLE_VAR_U8:
case SLE_VAR_I16:
case SLE_VAR_U16:
case SLE_VAR_I32: {
/* Override the minimum value. No value below sdb->min, except special value 0 */
if (!(sdb->flags & SGF_0ISDISABLED) || val != 0) val = Clamp(val, sdb->min, sdb->max);
} break;
case SLE_VAR_U32: {
/* Override the minimum value. No value below sdb->min, except special value 0 */
uint min = ((sdb->flags & SGF_0ISDISABLED) && (uint)val <= (uint)sdb->min) ? 0 : sdb->min;
WriteValue(ptr, SLE_VAR_U32, (int64)ClampU(val, min, sdb->max));
return;
}
case SLE_VAR_I64:
case SLE_VAR_U64:
default: NOT_REACHED(); break;
}
}
WriteValue(ptr, sd->save.conv, (int64)val);
}
/** Load values from a group of an IniFile structure into the internal representation
* @param ini pointer to IniFile structure that holds administrative information
* @param sd pointer to SettingDesc structure whose internally pointed variables will
* be given values
* @param grpname the group of the IniFile to search in for the new values
* @param object pointer to the object been loaded */
static void ini_load_settings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
{
IniGroup *group;
IniGroup *group_def = ini->GetGroup(grpname);
IniItem *item;
const void *p;
void *ptr;
const char *s;
for (; sd->save.cmd != SL_END; sd++) {
const SettingDescBase *sdb = &sd->desc;
const SaveLoad *sld = &sd->save;
if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
/* For settings.xx.yy load the settings from [xx] yy = ? */
s = strchr(sdb->name, '.');
if (s != NULL) {
group = ini->GetGroup(sdb->name, s - sdb->name);
s++;
} else {
s = sdb->name;
group = group_def;
}
item = group->GetItem(s, false);
if (item == NULL && group != group_def) {
/* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
* did not exist (e.g. loading old config files with a [settings] section */
item = group_def->GetItem(s, false);
}
if (item == NULL) {
/* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
* did not exist (e.g. loading old config files with a [yapf] section */
const char *sc = strchr(s, '.');
if (sc != NULL) item = ini->GetGroup(s, sc - s)->GetItem(sc + 1, false);
}
p = (item == NULL) ? sdb->def : string_to_val(sdb, item->value);
ptr = GetVariableAddress(object, sld);
switch (sdb->cmd) {
case SDT_BOOLX: // All four are various types of (integer) numbers
case SDT_NUMX:
case SDT_ONEOFMANY:
case SDT_MANYOFMANY:
Write_ValidateSetting(ptr, sd, (unsigned long)p); break;
case SDT_STRING:
switch (GetVarMemType(sld->conv)) {
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
if (p != NULL) ttd_strlcpy((char*)ptr, (const char*)p, sld->length);
break;
case SLE_VAR_STR:
case SLE_VAR_STRQ:
if (p != NULL) {
free(*(char**)ptr);
*(char**)ptr = strdup((const char*)p);
}
break;
case SLE_VAR_CHAR: *(char*)ptr = *(char*)p; break;
default: NOT_REACHED(); break;
}
break;
case SDT_INTLIST: {
if (!load_intlist((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) {
ShowInfoF("ini: error in array '%s'", sdb->name);
} else if (sd->desc.proc_cnvt != NULL) {
sd->desc.proc_cnvt((const char*)p);
}
break;
}
default: NOT_REACHED(); break;
}
}
}
/** Save the values of settings to the inifile.
* @param ini pointer to IniFile structure
* @param sd read-only SettingDesc structure which contains the unmodified,
* loaded values of the configuration file and various information about it
* @param grpname holds the name of the group (eg. [network]) where these will be saved
* @param object pointer to the object been saved
* The function works as follows: for each item in the SettingDesc structure we
* have a look if the value has changed since we started the game (the original
* values are reloaded when saving). If settings indeed have changed, we get
* these and save them.
*/
static void ini_save_settings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
{
IniGroup *group_def = NULL, *group;
IniItem *item;
char buf[512];
const char *s;
void *ptr;
for (; sd->save.cmd != SL_END; sd++) {
const SettingDescBase *sdb = &sd->desc;
const SaveLoad *sld = &sd->save;
/* If the setting is not saved to the configuration
* file, just continue with the next setting */
if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
if (sld->conv & SLF_CONFIG_NO) continue;
/* XXX - wtf is this?? (group override?) */
s = strchr(sdb->name, '.');
if (s != NULL) {
group = ini->GetGroup(sdb->name, s - sdb->name);
s++;
} else {
if (group_def == NULL) group_def = ini->GetGroup(grpname);
s = sdb->name;
group = group_def;
}
item = group->GetItem(s, true);
ptr = GetVariableAddress(object, sld);
if (item->value != NULL) {
/* check if the value is the same as the old value */
const void *p = string_to_val(sdb, item->value);
/* The main type of a variable/setting is in bytes 8-15
* The subtype (what kind of numbers do we have there) is in 0-7 */
switch (sdb->cmd) {
case SDT_BOOLX:
case SDT_NUMX:
case SDT_ONEOFMANY:
case SDT_MANYOFMANY:
switch (GetVarMemType(sld->conv)) {
case SLE_VAR_BL:
if (*(bool*)ptr == (p != NULL)) continue;
break;
case SLE_VAR_I8:
case SLE_VAR_U8:
if (*(byte*)ptr == (byte)(unsigned long)p) continue;
break;
case SLE_VAR_I16:
case SLE_VAR_U16:
if (*(uint16*)ptr == (uint16)(unsigned long)p) continue;
break;
case SLE_VAR_I32:
case SLE_VAR_U32:
if (*(uint32*)ptr == (uint32)(unsigned long)p) continue;
break;
default: NOT_REACHED();
}
break;
default: break; // Assume the other types are always changed
}
}
/* Value has changed, get the new value and put it into a buffer */
switch (sdb->cmd) {
case SDT_BOOLX:
case SDT_NUMX:
case SDT_ONEOFMANY:
case SDT_MANYOFMANY: {
uint32 i = (uint32)ReadValue(ptr, sld->conv);
switch (sdb->cmd) {
case SDT_BOOLX: strcpy(buf, (i != 0) ? "true" : "false"); break;
case SDT_NUMX: seprintf(buf, lastof(buf), IsSignedVarMemType(sld->conv) ? "%d" : "%u", i); break;
case SDT_ONEOFMANY: make_oneofmany(buf, lastof(buf), sdb->many, i); break;
case SDT_MANYOFMANY: make_manyofmany(buf, lastof(buf), sdb->many, i); break;
default: NOT_REACHED();
}
} break;
case SDT_STRING:
switch (GetVarMemType(sld->conv)) {
case SLE_VAR_STRB: strcpy(buf, (char*)ptr); break;
case SLE_VAR_STRBQ:seprintf(buf, lastof(buf), "\"%s\"", (char*)ptr); break;
case SLE_VAR_STR: strcpy(buf, *(char**)ptr); break;
case SLE_VAR_STRQ:
if (*(char**)ptr == NULL) {
buf[0] = '\0';
} else {
seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
}
break;
case SLE_VAR_CHAR: buf[0] = *(char*)ptr; buf[1] = '\0'; break;
default: NOT_REACHED();
}
break;
case SDT_INTLIST:
make_intlist(buf, lastof(buf), ptr, sld->length, GetVarMemType(sld->conv));
break;
default: NOT_REACHED();
}
/* The value is different, that means we have to write it to the ini */
free(item->value);
item->value = strdup(buf);
}
}
/** Loads all items from a 'grpname' section into a list
* The list parameter can be a NULL pointer, in this case nothing will be
* saved and a callback function should be defined that will take over the
* list-handling and store the data itself somewhere.
* @param ini IniFile handle to the ini file with the source data
* @param grpname character string identifying the section-header of the ini
* file that will be parsed
* @param list pointer to an string(pointer) array that will store the parsed
* entries of the given section
* @param len the maximum number of items available for the above list
* @param proc callback function that can override how the values are stored
* inside the list */
static void ini_load_setting_list(IniFile *ini, const char *grpname, char **list, uint len, SettingListCallbackProc proc)
{
IniGroup *group = ini->GetGroup(grpname);
IniItem *item;
const char *entry;
uint i, j;
if (group == NULL) return;
for (i = j = 0, item = group->item; item != NULL; item = item->next) {
entry = (proc != NULL) ? proc(item, i++) : item->name;
if (entry == NULL || list == NULL) continue;
if (j == len) break;
list[j++] = strdup(entry);
}
}
/** Saves all items from a list into the 'grpname' section
* The list parameter can be a NULL pointer, in this case a callback function
* should be defined that will provide the source data to be saved.
* @param ini IniFile handle to the ini file where the destination data is saved
* @param grpname character string identifying the section-header of the ini file
* @param list pointer to an string(pointer) array that will be used as the
* source to be saved into the relevant ini section
* @param len the maximum number of items available for the above list
* @param proc callback function that can will provide the source data if defined */
static void ini_save_setting_list(IniFile *ini, const char *grpname, char **list, uint len, SettingListCallbackProc proc)
{
IniGroup *group = ini->GetGroup(grpname);
const char *entry;
uint i;
if (proc == NULL && list == NULL) return;
if (group == NULL) return;
group->Clear();
for (i = 0; i != len; i++) {
entry = (proc != NULL) ? proc(NULL, i) : list[i];
if (entry == NULL || *entry == '\0') continue;
group->GetItem(entry, true)->SetValue("");
}
}
/****************************
* OTTD specific INI stuff
****************************/
/** Settings-macro usage:
* The list might look daunting at first, but is in general easy to understand.
* We have two types of list:
* 1. SDTG_something
* 2. SDT_something
* The 'G' stands for global, so this is the one you will use for a
* SettingDescGlobVarList section meaning global variables. The other uses a
* Base/Offset and runtime variable selection mechanism, known from the saveload
* convention (it also has global so it should not be hard).
* Of each type there are again two versions, the normal one and one prefixed
* with 'COND'.
* COND means that the setting is only valid in certain savegame versions
* (since settings are saved to the savegame, this bookkeeping is necessary.
* Now there are a lot of types. Easy ones are:
* - VAR: any number type, 'type' field specifies what number. eg int8 or uint32
* - BOOL: a boolean number type
* - STR: a string or character. 'type' field specifies what string. Normal, string, or quoted
* A bit more difficult to use are MMANY (meaning ManyOfMany) and OMANY (OneOfMany)
* These are actually normal numbers, only bitmasked. In MMANY several bits can
* be set, in the other only one.
* The most complex type is INTLIST. This is basically an array of numbers. If
* the intlist is only valid in certain savegame versions because for example
* it has grown in size its length cannot be automatically be calculated so
* use SDT(G)_CONDLISTO() meaning Old.
* If nothing fits you, you can use the GENERAL macros, but it exposes the
* internal structure somewhat so it needs a little looking. There are _NULL()
* macros as well, these fill up space so you can add more settings there (in
* place) and you DON'T have to increase the savegame version.
*
* While reading values from openttd.cfg, some values may not be converted
* properly, for any kind of reasons. In order to allow a process of self-cleaning
* mechanism, a callback procedure is made available. You will have to supply the function, which
* will work on a string, one function per setting. And of course, enable the callback param
* on the appropriate macro.
*/
#define NSD_GENERAL(name, def, cmd, guiflags, min, max, interval, many, str, proc, load)\
{name, (const void*)(def), {cmd}, {guiflags}, min, max, interval, many, str, proc, load}
/* Macros for various objects to go in the configuration file.
* This section is for global variables */
#define SDTG_GENERAL(name, sdt_cmd, sle_cmd, type, flags, guiflags, var, length, def, min, max, interval, full, str, proc, from, to)\
{NSD_GENERAL(name, def, sdt_cmd, guiflags, min, max, interval, full, str, proc, NULL), SLEG_GENERAL(sle_cmd, var, type | flags, length, from, to)}
#define SDTG_CONDVAR(name, type, flags, guiflags, var, def, min, max, interval, str, proc, from, to)\
SDTG_GENERAL(name, SDT_NUMX, SL_VAR, type, flags, guiflags, var, 0, def, min, max, interval, NULL, str, proc, from, to)
#define SDTG_VAR(name, type, flags, guiflags, var, def, min, max, interval, str, proc)\
SDTG_CONDVAR(name, type, flags, guiflags, var, def, min, max, interval, str, proc, 0, SL_MAX_VERSION)
#define SDTG_CONDBOOL(name, flags, guiflags, var, def, str, proc, from, to)\
SDTG_GENERAL(name, SDT_BOOLX, SL_VAR, SLE_BOOL, flags, guiflags, var, 0, def, 0, 1, 0, NULL, str, proc, from, to)
#define SDTG_BOOL(name, flags, guiflags, var, def, str, proc)\
SDTG_CONDBOOL(name, flags, guiflags, var, def, str, proc, 0, SL_MAX_VERSION)
#define SDTG_CONDLIST(name, type, length, flags, guiflags, var, def, str, proc, from, to)\
SDTG_GENERAL(name, SDT_INTLIST, SL_ARR, type, flags, guiflags, var, length, def, 0, 0, 0, NULL, str, proc, from, to)
#define SDTG_LIST(name, type, flags, guiflags, var, def, str, proc)\
SDTG_GENERAL(name, SDT_INTLIST, SL_ARR, type, flags, guiflags, var, lengthof(var), def, 0, 0, 0, NULL, str, proc, 0, SL_MAX_VERSION)
#define SDTG_CONDSTR(name, type, length, flags, guiflags, var, def, str, proc, from, to)\
SDTG_GENERAL(name, SDT_STRING, SL_STR, type, flags, guiflags, var, length, def, 0, 0, 0, NULL, str, proc, from, to)
#define SDTG_STR(name, type, flags, guiflags, var, def, str, proc)\
SDTG_GENERAL(name, SDT_STRING, SL_STR, type, flags, guiflags, var, lengthof(var), def, 0, 0, 0, NULL, str, proc, 0, SL_MAX_VERSION)
#define SDTG_CONDOMANY(name, type, flags, guiflags, var, def, max, full, str, proc, from, to)\
SDTG_GENERAL(name, SDT_ONEOFMANY, SL_VAR, type, flags, guiflags, var, 0, def, 0, max, 0, full, str, proc, from, to)
#define SDTG_OMANY(name, type, flags, guiflags, var, def, max, full, str, proc)\
SDTG_CONDOMANY(name, type, flags, guiflags, var, def, max, full, str, proc, 0, SL_MAX_VERSION)
#define SDTG_CONDMMANY(name, type, flags, guiflags, var, def, full, str, proc, from, to)\
SDTG_GENERAL(name, SDT_MANYOFMANY, SL_VAR, type, flags, guiflags, var, 0, def, 0, 0, 0, full, str, proc, from, to)
#define SDTG_MMANY(name, type, flags, guiflags, var, def, full, str, proc)\
SDTG_CONDMMANY(name, type, flags, guiflags, var, def, full, str, proc, 0, SL_MAX_VERSION)
#define SDTG_CONDNULL(length, from, to)\
{{"", NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL, NULL}, SLEG_CONDNULL(length, from, to)}
#define SDTG_END() {{NULL, NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL, NULL}, SLEG_END()}
/* Macros for various objects to go in the configuration file.
* This section is for structures where their various members are saved */
#define SDT_GENERAL(name, sdt_cmd, sle_cmd, type, flags, guiflags, base, var, length, def, min, max, interval, full, str, proc, load, from, to)\
{NSD_GENERAL(name, def, sdt_cmd, guiflags, min, max, interval, full, str, proc, load), SLE_GENERAL(sle_cmd, base, var, type | flags, length, from, to)}
#define SDT_CONDVAR(base, var, type, from, to, flags, guiflags, def, min, max, interval, str, proc)\
SDT_GENERAL(#var, SDT_NUMX, SL_VAR, type, flags, guiflags, base, var, 1, def, min, max, interval, NULL, str, proc, NULL, from, to)
#define SDT_VAR(base, var, type, flags, guiflags, def, min, max, interval, str, proc)\
SDT_CONDVAR(base, var, type, 0, SL_MAX_VERSION, flags, guiflags, def, min, max, interval, str, proc)
#define SDT_CONDBOOL(base, var, from, to, flags, guiflags, def, str, proc)\
SDT_GENERAL(#var, SDT_BOOLX, SL_VAR, SLE_BOOL, flags, guiflags, base, var, 1, def, 0, 1, 0, NULL, str, proc, NULL, from, to)
#define SDT_BOOL(base, var, flags, guiflags, def, str, proc)\
SDT_CONDBOOL(base, var, 0, SL_MAX_VERSION, flags, guiflags, def, str, proc)
#define SDT_CONDLIST(base, var, type, from, to, flags, guiflags, def, str, proc)\
SDT_GENERAL(#var, SDT_INTLIST, SL_ARR, type, flags, guiflags, base, var, lengthof(((base*)8)->var), def, 0, 0, 0, NULL, str, proc, NULL, from, to)
#define SDT_LIST(base, var, type, flags, guiflags, def, str, proc)\
SDT_CONDLIST(base, var, type, 0, SL_MAX_VERSION, flags, guiflags, def, str, proc)
#define SDT_CONDLISTO(base, var, length, type, from, to, flags, guiflags, def, str, proc, load)\
SDT_GENERAL(#var, SDT_INTLIST, SL_ARR, type, flags, guiflags, base, var, length, def, 0, 0, 0, NULL, str, proc, load, from, to)
#define SDT_CONDSTR(base, var, type, from, to, flags, guiflags, def, str, proc)\
SDT_GENERAL(#var, SDT_STRING, SL_STR, type, flags, guiflags, base, var, lengthof(((base*)8)->var), def, 0, 0, 0, NULL, str, proc, NULL, from, to)
#define SDT_STR(base, var, type, flags, guiflags, def, str, proc)\
SDT_CONDSTR(base, var, type, 0, SL_MAX_VERSION, flags, guiflags, def, str, proc)
#define SDT_CONDSTRO(base, var, length, type, from, to, flags, def, str, proc)\
SDT_GENERAL(#var, SDT_STRING, SL_STR, type, flags, 0, base, var, length, def, 0, 0, NULL, str, proc, from, to)
#define SDT_CONDCHR(base, var, from, to, flags, guiflags, def, str, proc)\
SDT_GENERAL(#var, SDT_STRING, SL_VAR, SLE_CHAR, flags, guiflags, base, var, 1, def, 0, 0, 0, NULL, str, proc, NULL, from, to)
#define SDT_CHR(base, var, flags, guiflags, def, str, proc)\
SDT_CONDCHR(base, var, 0, SL_MAX_VERSION, flags, guiflags, def, str, proc)
#define SDT_CONDOMANY(base, var, type, from, to, flags, guiflags, def, max, full, str, proc, load)\
SDT_GENERAL(#var, SDT_ONEOFMANY, SL_VAR, type, flags, guiflags, base, var, 1, def, 0, max, 0, full, str, proc, load, from, to)
#define SDT_OMANY(base, var, type, flags, guiflags, def, max, full, str, proc, load)\
SDT_CONDOMANY(base, var, type, 0, SL_MAX_VERSION, flags, guiflags, def, max, full, str, proc, load)
#define SDT_CONDMMANY(base, var, type, from, to, flags, guiflags, def, full, str, proc)\
SDT_GENERAL(#var, SDT_MANYOFMANY, SL_VAR, type, flags, guiflags, base, var, 1, def, 0, 0, 0, full, str, proc, NULL, from, to)
#define SDT_MMANY(base, var, type, flags, guiflags, def, full, str, proc)\
SDT_CONDMMANY(base, var, type, 0, SL_MAX_VERSION, flags, guiflags, def, full, str, proc)
#define SDT_CONDNULL(length, from, to)\
{{"", NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL, NULL}, SLE_CONDNULL(length, from, to)}
#define SDTC_CONDVAR(var, type, from, to, flags, guiflags, def, min, max, interval, str, proc)\
SDTG_GENERAL(#var, SDT_NUMX, SL_VAR, type, flags, guiflags, _settings_client.var, 1, def, min, max, interval, NULL, str, proc, from, to)
#define SDTC_VAR(var, type, flags, guiflags, def, min, max, interval, str, proc)\
SDTC_CONDVAR(var, type, 0, SL_MAX_VERSION, flags, guiflags, def, min, max, interval, str, proc)
#define SDTC_CONDBOOL(var, from, to, flags, guiflags, def, str, proc)\
SDTG_GENERAL(#var, SDT_BOOLX, SL_VAR, SLE_BOOL, flags, guiflags, _settings_client.var, 1, def, 0, 1, 0, NULL, str, proc, from, to)
#define SDTC_BOOL(var, flags, guiflags, def, str, proc)\
SDTC_CONDBOOL(var, 0, SL_MAX_VERSION, flags, guiflags, def, str, proc)
#define SDTC_CONDLIST(var, type, length, flags, guiflags, def, str, proc, from, to)\
SDTG_GENERAL(#var, SDT_INTLIST, SL_ARR, type, flags, guiflags, _settings_client.var, length, def, 0, 0, 0, NULL, str, proc, from, to)
#define SDTC_LIST(var, type, flags, guiflags, def, str, proc)\
SDTG_GENERAL(#var, SDT_INTLIST, SL_ARR, type, flags, guiflags, _settings_client.var, lengthof(_settings_client.var), def, 0, 0, 0, NULL, str, proc, 0, SL_MAX_VERSION)
#define SDTC_CONDSTR(var, type, length, flags, guiflags, def, str, proc, from, to)\
SDTG_GENERAL(#var, SDT_STRING, SL_STR, type, flags, guiflags, _settings_client.var, length, def, 0, 0, 0, NULL, str, proc, from, to)
#define SDTC_STR(var, type, flags, guiflags, def, str, proc)\
SDTG_GENERAL(#var, SDT_STRING, SL_STR, type, flags, guiflags, _settings_client.var, lengthof(_settings_client.var), def, 0, 0, 0, NULL, str, proc, 0, SL_MAX_VERSION)
#define SDTC_CONDOMANY(var, type, from, to, flags, guiflags, def, max, full, str, proc)\
SDTG_GENERAL(#var, SDT_ONEOFMANY, SL_VAR, type, flags, guiflags, _settings_client.var, 1, def, 0, max, 0, full, str, proc, from, to)
#define SDTC_OMANY(var, type, flags, guiflags, def, max, full, str, proc)\
SDTC_CONDOMANY(var, type, 0, SL_MAX_VERSION, flags, guiflags, def, max, full, str, proc)
#define SDT_END() {{NULL, NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL, NULL}, SLE_END()}
/* Shortcuts for macros below. Logically if we don't save the value
* we also don't sync it in a network game */
#define S SLF_SAVE_NO | SLF_NETWORK_NO
#define C SLF_CONFIG_NO
#define N SLF_NETWORK_NO
#define D0 SGF_0ISDISABLED
#define NC SGF_NOCOMMA
#define MS SGF_MULTISTRING
#define NO SGF_NETWORK_ONLY
#define CR SGF_CURRENCY
#define NN SGF_NO_NETWORK
#define NG SGF_NEWGAME_ONLY
/* Begin - Callback Functions for the various settings
* virtual PositionMainToolbar function, calls the right one.*/
static bool v_PositionMainToolbar(int32 p1)
{
if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
return true;
}
static bool PopulationInLabelActive(int32 p1)
{
Town *t;
FOR_ALL_TOWNS(t) UpdateTownVirtCoord(t);
return true;
}
static bool RedrawScreen(int32 p1)
{
MarkWholeScreenDirty();
return true;
}
static bool InvalidateDetailsWindow(int32 p1)
{
InvalidateWindowClasses(WC_VEHICLE_DETAILS);
return true;
}
static bool InvalidateStationBuildWindow(int32 p1)
{
InvalidateWindow(WC_BUILD_STATION, 0);
return true;
}
static bool InvalidateBuildIndustryWindow(int32 p1)
{
InvalidateWindowData(WC_BUILD_INDUSTRY, 0);
return true;
}
static bool CloseSignalGUI(int32 p1)
{
if (p1 == 0) {
DeleteWindowByClass(WC_BUILD_SIGNAL);
}
return true;
}
static bool InvalidateTownViewWindow(int32 p1)
{
InvalidateWindowClassesData(WC_TOWN_VIEW, p1);
return true;
}
static bool DeleteSelectStationWindow(int32 p1)
{
DeleteWindowById(WC_SELECT_STATION, 0);
return true;
}
static bool UpdateConsists(int32 p1)
{
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* Update the consist of all trains so the maximum speed is set correctly. */
if (v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v))) TrainConsistChanged(v, true);
}
return true;
}
/* Check service intervals of vehicles, p1 is value of % or day based servicing */
static bool CheckInterval(int32 p1)
{
VehicleSettings *ptc = (_game_mode == GM_MENU) ? &_settings_newgame.vehicle : &_settings_game.vehicle;
if (p1) {
ptc->servint_trains = 50;
ptc->servint_roadveh = 50;
ptc->servint_aircraft = 50;
ptc->servint_ships = 50;
} else {
ptc->servint_trains = 150;
ptc->servint_roadveh = 150;
ptc->servint_aircraft = 360;
ptc->servint_ships = 100;
}
InvalidateDetailsWindow(0);
return true;
}
static bool EngineRenewUpdate(int32 p1)
{
DoCommandP(0, 0, _settings_client.gui.autorenew, CMD_SET_AUTOREPLACE);
return true;
}
static bool EngineRenewMonthsUpdate(int32 p1)
{
DoCommandP(0, 1, _settings_client.gui.autorenew_months, CMD_SET_AUTOREPLACE);
return true;
}
static bool EngineRenewMoneyUpdate(int32 p1)
{
DoCommandP(0, 2, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
return true;
}
static bool TrainAccelerationModelChanged(int32 p1)
{
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN && IsFrontEngine(v)) UpdateTrainAcceleration(v);
}
return true;
}
static bool DragSignalsDensityChanged(int32)
{
SetWindowDirty(FindWindowById(WC_BUILD_SIGNAL, 0));
return true;
}
/*
* A: competitors
* B: competitor start time. Deprecated since savegame version 110.
* C: town count (3 = high, 0 = very low)
* D: industry count (4 = high, 0 = none)
* E: inital loan (in GBP)
* F: interest rate
* G: running costs (0 = low, 2 = high)
* H: construction speed of competitors (0 = very slow, 4 = very fast)
* I: competitor intelligence. Deprecated since savegame version 110.
* J: breakdowns (0 = off, 2 = normal)
* K: subsidy multiplier (0 = 1.5, 3 = 4.0)
* L: construction cost (0-2)
* M: terrain type (0 = very flat, 3 = mountainous)
* N: amount of water (0 = very low, 3 = high)
* O: economy (0 = steady, 1 = fluctuating)
* P: Train reversing (0 = end of line + stations, 1 = end of line)
* Q: disasters
* R: area restructuring (0 = permissive, 2 = hostile)
* S: the difficulty level
*/
static const DifficultySettings _default_game_diff[3] = { /*
A, C, D, E, F, G, H, J, K, L, M, N, O, P, Q, R, S*/
{2, 2, 4, 300000, 2, 0, 2, 1, 2, 0, 1, 0, 0, 0, 0, 0, 0}, ///< easy
{4, 2, 3, 150000, 3, 1, 3, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1}, ///< medium
{7, 3, 3, 100000, 4, 1, 3, 2, 0, 2, 3, 2, 1, 1, 1, 2, 2}, ///< hard
};
void SetDifficultyLevel(int mode, DifficultySettings *gm_opt)
{
assert(mode <= 3);
if (mode != 3) {
*gm_opt = _default_game_diff[mode];
} else {
gm_opt->diff_level = 3;
}
}
/**
* Checks the difficulty levels read from the configuration and
* forces them to be correct when invalid.
*/
void CheckDifficultyLevels()
{
if (_settings_newgame.difficulty.diff_level != 3) {
SetDifficultyLevel(_settings_newgame.difficulty.diff_level, &_settings_newgame.difficulty);
}
}
static bool DifficultyReset(int32 level)
{
SetDifficultyLevel(level, (_game_mode == GM_MENU) ? &_settings_newgame.difficulty : &_settings_game.difficulty);
return true;
}
static bool DifficultyChange(int32)
{
if (_game_mode == GM_MENU) {
if (_settings_newgame.difficulty.diff_level != 3) {
ShowErrorMessage(INVALID_STRING_ID, STR_DIFFICULTY_TO_CUSTOM, 0, 0);
_settings_newgame.difficulty.diff_level = 3;
}
} else {
_settings_game.difficulty.diff_level = 3;
}
/* If we are a network-client, update the difficult setting (if it is open).
* Use this instead of just dirtying the window because we need to load in
* the new difficulty settings */
if (_networking && FindWindowById(WC_GAME_OPTIONS, 0) != NULL) {
ShowGameDifficulty();
}
return true;
}
static bool DifficultyNoiseChange(int32 i)
{
if (_game_mode == GM_NORMAL) {
UpdateAirportsNoise();
if (_settings_game.economy.station_noise_level) {
InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
}
}
return DifficultyChange(i);
}
/**
* Check whether the road side may be changed.
* @param p1 unused
* @return true if the road side may be changed.
*/
static bool CheckRoadSide(int p1)
{
extern bool RoadVehiclesAreBuilt();
return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
}
/** Conversion callback for _gameopt_settings_game.landscape
* It converts (or try) between old values and the new ones,
* without losing initial setting of the user
* @param value that was read from config file
* @return the "hopefully" converted value
*/
static int32 ConvertLandscape(const char *value)
{
/* try with the old values */
return lookup_oneofmany("normal|hilly|desert|candy", value);
}
/**
* Check for decent values been supplied by the user for the noise tolerance setting.
* The primary idea is to avoid division by zero in game mode.
* The secondary idea is to make it so the values will be somewhat sane and that towns will
* not be overcrowed with airports. It would be easy to abuse such a feature
* So basically, 200, 400, 800 are the lowest allowed values */
static int32 CheckNoiseToleranceLevel(const char *value)
{
GameSettings *s = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;
for (uint16 i = 0; i < lengthof(s->economy.town_noise_population); i++) {
s->economy.town_noise_population[i] = max(uint16(200 * (i + 1)), s->economy.town_noise_population[i]);
}
return 0;
}
static bool CheckFreeformEdges(int32 p1)
{
if (_game_mode == GM_MENU) return true;
if (p1 != 0) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_SHIP && (TileX(v->tile) == 0 || TileY(v->tile) == 0)) {
ShowErrorMessage(INVALID_STRING_ID, STR_CONFIG_SETTING_EDGES_NOT_EMPTY, 0, 0);
return false;
}
}
Station *st;
FOR_ALL_STATIONS(st) {
if (TileX(st->xy) == 0 || TileY(st->xy) == 0) {
ShowErrorMessage(INVALID_STRING_ID, STR_CONFIG_SETTING_EDGES_NOT_EMPTY, 0, 0);
return false;
}
}
for (uint i = 0; i < MapSizeX(); i++) MakeVoid(TileXY(i, 0));
for (uint i = 0; i < MapSizeY(); i++) MakeVoid(TileXY(0, i));
} else {
for (uint i = 0; i < MapMaxX(); i++) {
if (TileHeight(TileXY(i, 1)) != 0) {
ShowErrorMessage(INVALID_STRING_ID, STR_CONFIG_SETTING_EDGES_NOT_WATER, 0, 0);
return false;
}
}
for (uint i = 1; i < MapMaxX(); i++) {
if (!IsTileType(TileXY(i, MapMaxY() - 1), MP_WATER) || TileHeight(TileXY(1, MapMaxY())) != 0) {
ShowErrorMessage(INVALID_STRING_ID, STR_CONFIG_SETTING_EDGES_NOT_WATER, 0, 0);
return false;
}
}
for (uint i = 0; i < MapMaxY(); i++) {
if (TileHeight(TileXY(1, i)) != 0) {
ShowErrorMessage(INVALID_STRING_ID, STR_CONFIG_SETTING_EDGES_NOT_WATER, 0, 0);
return false;
}
}
for (uint i = 1; i < MapMaxY(); i++) {
if (!IsTileType(TileXY(MapMaxX() - 1, i), MP_WATER) || TileHeight(TileXY(MapMaxX(), i)) != 0) {
ShowErrorMessage(INVALID_STRING_ID, STR_CONFIG_SETTING_EDGES_NOT_WATER, 0, 0);
return false;
}
}
/* Make tiles at the border water again. */
for (uint i = 0; i < MapMaxX(); i++) {
SetTileHeight(TileXY(i, 0), 0);
SetTileType(TileXY(i, 0), MP_WATER);
}
for (uint i = 0; i < MapMaxY(); i++) {
SetTileHeight(TileXY(0, i), 0);
SetTileType(TileXY(0, i), MP_WATER);
}
}
MarkWholeScreenDirty();
return true;
}
/**
* Changing the setting "allow multiple NewGRF sets" is not allowed
* if there are vehicles.
*/
static bool ChangeDynamicEngines(int32 p1)
{
if (_game_mode == GM_MENU) return true;
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (IsCompanyBuildableVehicleType(v)) {
ShowErrorMessage(INVALID_STRING_ID, STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, 0, 0);
return false;
}
}
/* Reset the engines, they will get new EngineIDs */
_engine_mngr.ResetToDefaultMapping();
ReloadNewGRFData();
return true;
}
#ifdef ENABLE_NETWORK
static bool UpdateClientName(int32 p1)
{
NetworkUpdateClientName();
return true;
}
static bool UpdateServerPassword(int32 p1)
{
if (strcmp(_settings_client.network.server_password, "*") == 0) {
_settings_client.network.server_password[0] = '\0';
}
return true;
}
static bool UpdateRconPassword(int32 p1)
{
if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
_settings_client.network.rcon_password[0] = '\0';
}
return true;
}
static bool UpdateClientConfigValues(int32 p1)
{
if (_network_server) NetworkServerSendConfigUpdate();
return true;
}
#endif /* ENABLE_NETWORK */
/* End - Callback Functions */
static const SettingDesc _music_settings[] = {
SDT_VAR(MusicFileSettings, playlist, SLE_UINT8, S, 0, 0, 0, 5, 1, STR_NULL, NULL),
SDT_VAR(MusicFileSettings, music_vol, SLE_UINT8, S, 0, 127, 0, 127, 1, STR_NULL, NULL),
SDT_VAR(MusicFileSettings, effect_vol, SLE_UINT8, S, 0, 127, 0, 127, 1, STR_NULL, NULL),
SDT_LIST(MusicFileSettings, custom_1, SLE_UINT8, S, 0, NULL, STR_NULL, NULL),
SDT_LIST(MusicFileSettings, custom_2, SLE_UINT8, S, 0, NULL, STR_NULL, NULL),
SDT_BOOL(MusicFileSettings, playing, S, 0, true, STR_NULL, NULL),
SDT_BOOL(MusicFileSettings, shuffle, S, 0, false, STR_NULL, NULL),
SDT_END()
};
/* win32_v.cpp only settings */
#if defined(WIN32) && !defined(DEDICATED)
extern bool _force_full_redraw, _window_maximize;
extern uint _display_hz, _fullscreen_bpp;
static const SettingDescGlobVarList _win32_settings[] = {
SDTG_VAR("display_hz", SLE_UINT, S, 0, _display_hz, 0, 0, 120, 0, STR_NULL, NULL),
SDTG_BOOL("force_full_redraw", S, 0, _force_full_redraw,false, STR_NULL, NULL),
SDTG_VAR("fullscreen_bpp", SLE_UINT, S, 0, _fullscreen_bpp, 8, 8, 32, 0, STR_NULL, NULL),
SDTG_BOOL("window_maximize", S, 0, _window_maximize, false, STR_NULL, NULL),
SDTG_END()
};
#endif /* WIN32 */
static const SettingDescGlobVarList _misc_settings[] = {
SDTG_MMANY("display_opt", SLE_UINT8, S, 0, _display_opt, (1 << DO_SHOW_TOWN_NAMES | 1 << DO_SHOW_STATION_NAMES | 1 << DO_SHOW_SIGNS | 1 << DO_FULL_ANIMATION | 1 << DO_FULL_DETAIL | 1 << DO_WAYPOINTS), "SHOW_TOWN_NAMES|SHOW_STATION_NAMES|SHOW_SIGNS|FULL_ANIMATION||FULL_DETAIL|WAYPOINTS", STR_NULL, NULL),
SDTG_BOOL("news_ticker_sound", S, 0, _news_ticker_sound, true, STR_NULL, NULL),
SDTG_BOOL("fullscreen", S, 0, _fullscreen, false, STR_NULL, NULL),
SDTG_STR("graphicsset", SLE_STRQ, S, 0, _ini_graphics_set, NULL, STR_NULL, NULL),
SDTG_STR("videodriver", SLE_STRQ, S, 0, _ini_videodriver, NULL, STR_NULL, NULL),
SDTG_STR("musicdriver", SLE_STRQ, S, 0, _ini_musicdriver, NULL, STR_NULL, NULL),
SDTG_STR("sounddriver", SLE_STRQ, S, 0, _ini_sounddriver, NULL, STR_NULL, NULL),
SDTG_STR("blitter", SLE_STRQ, S, 0, _ini_blitter, NULL, STR_NULL, NULL),
SDTG_STR("language", SLE_STRB, S, 0, _dynlang.curr_file, NULL, STR_NULL, NULL),
#ifdef N3DS
SDTG_CONDLIST("resolution", SLE_INT, 2, S, 0, _cur_resolution, "320,240", STR_NULL, NULL, 0, SL_MAX_VERSION), // workaround for implicit lengthof() in SDTG_LIST
#else
SDTG_CONDLIST("resolution", SLE_INT, 2, S, 0, _cur_resolution, "640,480", STR_NULL, NULL, 0, SL_MAX_VERSION), // workaround for implicit lengthof() in SDTG_LIST
#endif
SDTG_STR("screenshot_format",SLE_STRB, S, 0, _screenshot_format_name,NULL, STR_NULL, NULL),
SDTG_STR("savegame_format", SLE_STRB, S, 0, _savegame_format, NULL, STR_NULL, NULL),
SDTG_BOOL("rightclick_emulate", S, 0, _rightclick_emulate, false, STR_NULL, NULL),
#ifdef WITH_FREETYPE
SDTG_STR("small_font", SLE_STRB, S, 0, _freetype.small_font, NULL, STR_NULL, NULL),
SDTG_STR("medium_font", SLE_STRB, S, 0, _freetype.medium_font, NULL, STR_NULL, NULL),
SDTG_STR("large_font", SLE_STRB, S, 0, _freetype.large_font, NULL, STR_NULL, NULL),
SDTG_VAR("small_size", SLE_UINT, S, 0, _freetype.small_size, 6, 0, 72, 0, STR_NULL, NULL),
SDTG_VAR("medium_size", SLE_UINT, S, 0, _freetype.medium_size, 10, 0, 72, 0, STR_NULL, NULL),
SDTG_VAR("large_size", SLE_UINT, S, 0, _freetype.large_size, 16, 0, 72, 0, STR_NULL, NULL),
SDTG_BOOL("small_aa", S, 0, _freetype.small_aa, false, STR_NULL, NULL),
SDTG_BOOL("medium_aa", S, 0, _freetype.medium_aa, false, STR_NULL, NULL),
SDTG_BOOL("large_aa", S, 0, _freetype.large_aa, false, STR_NULL, NULL),
#endif
SDTG_VAR("sprite_cache_size",SLE_UINT, S, 0, _sprite_cache_size, 4, 1, 64, 0, STR_NULL, NULL),
SDTG_VAR("player_face", SLE_UINT32, S, 0, _company_manager_face,0,0,0xFFFFFFFF,0, STR_NULL, NULL),
SDTG_VAR("transparency_options", SLE_UINT, S, 0, _transparency_opt, 0,0,0x1FF,0, STR_NULL, NULL),
SDTG_VAR("transparency_locks", SLE_UINT, S, 0, _transparency_lock, 0,0,0x1FF,0, STR_NULL, NULL),
SDTG_VAR("invisibility_options", SLE_UINT, S, 0, _invisibility_opt, 0,0, 0xFF,0, STR_NULL, NULL),
SDTG_STR("keyboard", SLE_STRB, S, 0, _keyboard_opt[0], NULL, STR_NULL, NULL),
SDTG_STR("keyboard_caps", SLE_STRB, S, 0, _keyboard_opt[1], NULL, STR_NULL, NULL),
SDTG_END()
};
static const uint GAME_DIFFICULTY_NUM = 18;
uint16 _old_diff_custom[GAME_DIFFICULTY_NUM];
static const SettingDesc _gameopt_settings[] = {
/* In version 4 a new difficulty setting has been added to the difficulty settings,
* town attitude towards demolishing. Needs special handling because some dimwit thought
* it funny to have the GameDifficulty struct be an array while it is a struct of
* same-sized members
* XXX - To save file-space and since values are never bigger than about 10? only
* save the first 16 bits in the savegame. Question is why the values are still int32
* and why not byte for example?
* 'SLE_FILE_I16 | SLE_VAR_U16' in "diff_custom" is needed to get around SlArray() hack
* for savegames version 0 - though it is an array, it has to go through the byteswap process */
SDTG_GENERAL("diff_custom", SDT_INTLIST, SL_ARR, SLE_FILE_I16 | SLE_VAR_U16, C, 0, _old_diff_custom, 17, 0, 0, 0, 0, NULL, STR_NULL, NULL, 0, 3),
SDTG_GENERAL("diff_custom", SDT_INTLIST, SL_ARR, SLE_UINT16, C, 0, _old_diff_custom, 18, 0, 0, 0, 0, NULL, STR_NULL, NULL, 4, SL_MAX_VERSION),
SDT_VAR(GameSettings, difficulty.diff_level, SLE_UINT8, 0, 0, 0, 0, 3, 0, STR_NULL, NULL),
SDT_OMANY(GameSettings, locale.currency, SLE_UINT8, N, 0, 0, CUSTOM_CURRENCY_ID, "GBP|USD|EUR|YEN|ATS|BEF|CHF|CZK|DEM|DKK|ESP|FIM|FRF|GRD|HUF|ISK|ITL|NLG|NOK|PLN|ROL|RUR|SIT|SEK|YTL|SKK|BRL|EEK|custom", STR_NULL, NULL, NULL),
SDT_OMANY(GameSettings, locale.units, SLE_UINT8, N, 0, 1, 2, "imperial|metric|si", STR_NULL, NULL, NULL),
/* There are only 21 predefined town_name values (0-20), but you can have more with newgrf action F so allow these bigger values (21-255). Invalid values will fallback to english on use and (undefined string) in GUI. */
SDT_OMANY(GameSettings, game_creation.town_name, SLE_UINT8, 0, 0, 0, 255, "english|french|german|american|latin|silly|swedish|dutch|finnish|polish|slovakish|norwegian|hungarian|austrian|romanian|czech|swiss|danish|turkish|italian|catalan", STR_NULL, NULL, NULL),
SDT_OMANY(GameSettings, game_creation.landscape, SLE_UINT8, 0, 0, 0, 3, "temperate|arctic|tropic|toyland", STR_NULL, NULL, ConvertLandscape),
SDT_VAR(GameSettings, game_creation.snow_line, SLE_UINT8, 0, 0, 7 * TILE_HEIGHT, 2 * TILE_HEIGHT, 13 * TILE_HEIGHT, 0, STR_NULL, NULL),
SDT_CONDNULL( 1, 0, 22),
SDTC_CONDOMANY( gui.autosave, SLE_UINT8, 23, SL_MAX_VERSION, S, 0, 1, 4, "off|monthly|quarterly|half year|yearly", STR_NULL, NULL),
SDT_OMANY(GameSettings, vehicle.road_side, SLE_UINT8, 0, 0, 1, 1, "left|right", STR_NULL, NULL, NULL),
SDT_END()
};
/* Some settings do not need to be synchronised when playing in multiplayer.
* These include for example the GUI settings and will not be saved with the
* savegame.
* It is also a bit tricky since you would think that service_interval
* for example doesn't need to be synched. Every client assigns the
* service_interval value to the v->service_interval, meaning that every client
* assigns his value. If the setting was company-based, that would mean that
* vehicles could decide on different moments that they are heading back to a
* service depot, causing desyncs on a massive scale. */
const SettingDesc _settings[] = {
/***************************************************************************/
/* Saved settings variables. */
/* Do not ADD or REMOVE something in this "difficulty.XXX" table or before it. It breaks savegame compatability. */
SDT_CONDVAR(GameSettings, difficulty.max_no_competitors, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 2,0,MAX_COMPANIES-1,1,STR_NULL, DifficultyChange),
SDT_CONDNULL( 1, 97, 109),
SDT_CONDVAR(GameSettings, difficulty.number_towns, SLE_UINT8, 97, SL_MAX_VERSION, 0,NG, 2, 0, 4, 1, STR_NUM_VERY_LOW, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.number_industries, SLE_UINT8, 97, SL_MAX_VERSION, 0,NG, 4, 0, 4, 1, STR_NONE, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.max_loan, SLE_UINT32, 97, SL_MAX_VERSION, 0,NG|CR,300000,100000,500000,50000,STR_NULL, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.initial_interest, SLE_UINT8, 97, SL_MAX_VERSION, 0,NG, 2, 2, 4, 1, STR_NULL, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.vehicle_costs, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 0, 0, 2, 1, STR_6820_LOW, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.competitor_speed, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 2, 0, 4, 1, STR_681B_VERY_SLOW, DifficultyChange),
SDT_CONDNULL( 1, 97, 109),
SDT_CONDVAR(GameSettings, difficulty.vehicle_breakdowns, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 1, 0, 2, 1, STR_6823_NONE, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.subsidy_multiplier, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 2, 0, 3, 1, STR_6826_X1_5, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.construction_cost, SLE_UINT8, 97, SL_MAX_VERSION, 0,NG, 0, 0, 2, 1, STR_6820_LOW, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.terrain_type, SLE_UINT8, 97, SL_MAX_VERSION, 0,NG, 1, 0, 3, 1, STR_682A_VERY_FLAT, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.quantity_sea_lakes, SLE_UINT8, 97, SL_MAX_VERSION, 0,NG, 0, 0, 3, 1, STR_VERY_LOW, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.economy, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 0, 0, 1, 1, STR_682E_STEADY, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.line_reverse_mode, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 0, 0, 1, 1, STR_6834_AT_END_OF_LINE_AND_AT_STATIONS, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.disasters, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 0, 0, 1, 1, STR_6836_OFF, DifficultyChange),
SDT_CONDVAR(GameSettings, difficulty.town_council_tolerance, SLE_UINT8, 97, SL_MAX_VERSION, 0, 0, 0, 0, 2, 1, STR_PERMISSIVE, DifficultyNoiseChange),
SDT_CONDVAR(GameSettings, difficulty.diff_level, SLE_UINT8, 97, SL_MAX_VERSION, 0,NG, 0, 0, 3, 0, STR_NULL, DifficultyReset),
/* There are only 21 predefined town_name values (0-20), but you can have more with newgrf action F so allow these bigger values (21-255). Invalid values will fallback to english on use and (undefined string) in GUI. */
SDT_CONDOMANY(GameSettings, game_creation.town_name, SLE_UINT8, 97, SL_MAX_VERSION, 0,NN, 0, 255, "english|french|german|american|latin|silly|swedish|dutch|finnish|polish|slovakish|norwegian|hungarian|austrian|romanian|czech|swiss|danish|turkish|italian|catalan", STR_NULL, NULL, NULL),
SDT_CONDOMANY(GameSettings, game_creation.landscape, SLE_UINT8, 97, SL_MAX_VERSION, 0,NN, 0, 3, "temperate|arctic|tropic|toyland", STR_NULL, NULL, ConvertLandscape),
SDT_CONDVAR(GameSettings, game_creation.snow_line, SLE_UINT8, 97, SL_MAX_VERSION, 0,NN, 7 * TILE_HEIGHT, 2 * TILE_HEIGHT, 13 * TILE_HEIGHT, 0, STR_NULL, NULL),
SDT_CONDOMANY(GameSettings, vehicle.road_side, SLE_UINT8, 97, SL_MAX_VERSION, 0,NN, 1, 1, "left|right", STR_NULL, CheckRoadSide, NULL),
SDT_BOOL(GameSettings, construction.build_on_slopes, 0,NN, true, STR_CONFIG_SETTING_BUILDONSLOPES, NULL),
SDT_CONDBOOL(GameSettings, construction.autoslope, 75, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_AUTOSLOPE, NULL),
SDT_BOOL(GameSettings, construction.extra_dynamite, 0, 0, false, STR_CONFIG_SETTING_EXTRADYNAMITE, NULL),
SDT_BOOL(GameSettings, construction.longbridges, 0,NN, true, STR_CONFIG_SETTING_LONGBRIDGES, NULL),
SDT_BOOL(GameSettings, construction.signal_side, N,NN, true, STR_CONFIG_SETTING_SIGNALSIDE, RedrawScreen),
SDT_BOOL(GameSettings, station.always_small_airport, 0,NN, false, STR_CONFIG_SETTING_SMALL_AIRPORTS, NULL),
SDT_CONDVAR(GameSettings, economy.town_layout, SLE_UINT8, 59, SL_MAX_VERSION, 0,MS,TL_ORIGINAL,TL_BEGIN,NUM_TLS-1,1, STR_CONFIG_SETTING_TOWN_LAYOUT, NULL),
SDT_CONDBOOL(GameSettings, economy.allow_town_roads, 113, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_ALLOW_TOWN_ROADS, NULL),
SDT_VAR(GameSettings, vehicle.train_acceleration_model, SLE_UINT8, 0,MS, 0, 0, 1, 1, STR_CONFIG_SETTING_TRAIN_ACCELERATION_MODEL, TrainAccelerationModelChanged),
SDT_BOOL(GameSettings, pf.forbid_90_deg, 0, 0, false, STR_CONFIG_SETTING_FORBID_90_DEG, NULL),
SDT_BOOL(GameSettings, vehicle.mammoth_trains, 0,NN, true, STR_CONFIG_SETTING_MAMMOTHTRAINS, NULL),
SDT_BOOL(GameSettings, order.gotodepot, 0, 0, true, STR_CONFIG_SETTING_GOTODEPOT, NULL),
SDT_BOOL(GameSettings, pf.roadveh_queue, 0, 0, true, STR_CONFIG_SETTING_ROADVEH_QUEUE, NULL),
SDT_CONDBOOL(GameSettings, pf.new_pathfinding_all, 0, 86, 0, 0, false, STR_NULL, NULL),
SDT_CONDBOOL(GameSettings, pf.yapf.ship_use_yapf, 28, 86, 0, 0, false, STR_NULL, NULL),
SDT_CONDBOOL(GameSettings, pf.yapf.road_use_yapf, 28, 86, 0, 0, true, STR_NULL, NULL),
SDT_CONDBOOL(GameSettings, pf.yapf.rail_use_yapf, 28, 86, 0, 0, true, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.pathfinder_for_trains, SLE_UINT8, 87, SL_MAX_VERSION, 0, MS, 2, 0, 2, 1, STR_CONFIG_SETTING_PATHFINDER_FOR_TRAINS, NULL),
SDT_CONDVAR(GameSettings, pf.pathfinder_for_roadvehs, SLE_UINT8, 87, SL_MAX_VERSION, 0, MS, 2, 0, 2, 1, STR_CONFIG_SETTING_PATHFINDER_FOR_ROADVEH, NULL),
SDT_CONDVAR(GameSettings, pf.pathfinder_for_ships, SLE_UINT8, 87, SL_MAX_VERSION, 0, MS, 0, 0, 2, 1, STR_CONFIG_SETTING_PATHFINDER_FOR_SHIPS, NULL),
SDT_BOOL(GameSettings, vehicle.never_expire_vehicles, 0,NN, false, STR_CONFIG_SETTING_NEVER_EXPIRE_VEHICLES, NULL),
SDT_VAR(GameSettings, vehicle.max_trains, SLE_UINT16, 0, 0, 500, 0, 5000, 0, STR_CONFIG_SETTING_MAX_TRAINS, RedrawScreen),
SDT_VAR(GameSettings, vehicle.max_roadveh, SLE_UINT16, 0, 0, 500, 0, 5000, 0, STR_CONFIG_SETTING_MAX_ROADVEH, RedrawScreen),
SDT_VAR(GameSettings, vehicle.max_aircraft, SLE_UINT16, 0, 0, 200, 0, 5000, 0, STR_CONFIG_SETTING_MAX_AIRCRAFT, RedrawScreen),
SDT_VAR(GameSettings, vehicle.max_ships, SLE_UINT16, 0, 0, 300, 0, 5000, 0, STR_CONFIG_SETTING_MAX_SHIPS, RedrawScreen),
SDT_BOOL(GameSettings, vehicle.servint_ispercent, 0,NN, false, STR_CONFIG_SETTING_SERVINT_ISPERCENT, CheckInterval),
SDT_VAR(GameSettings, vehicle.servint_trains, SLE_UINT16, 0,D0, 150, 5, 800, 0, STR_CONFIG_SETTING_SERVINT_TRAINS, InvalidateDetailsWindow),
SDT_VAR(GameSettings, vehicle.servint_roadveh, SLE_UINT16, 0,D0, 150, 5, 800, 0, STR_CONFIG_SETTING_SERVINT_ROADVEH, InvalidateDetailsWindow),
SDT_VAR(GameSettings, vehicle.servint_ships, SLE_UINT16, 0,D0, 360, 5, 800, 0, STR_CONFIG_SETTING_SERVINT_SHIPS, InvalidateDetailsWindow),
SDT_VAR(GameSettings, vehicle.servint_aircraft, SLE_UINT16, 0,D0, 100, 5, 800, 0, STR_CONFIG_SETTING_SERVINT_AIRCRAFT, InvalidateDetailsWindow),
SDT_BOOL(GameSettings, order.no_servicing_if_no_breakdowns, 0, 0, false, STR_CONFIG_SETTING_NOSERVICE, NULL),
SDT_BOOL(GameSettings, vehicle.wagon_speed_limits, 0,NN, true, STR_CONFIG_SETTING_WAGONSPEEDLIMITS, UpdateConsists),
SDT_CONDBOOL(GameSettings, vehicle.disable_elrails, 38, SL_MAX_VERSION, 0,NN, false, STR_CONFIG_SETTING_DISABLE_ELRAILS, SettingsDisableElrail),
SDT_CONDVAR(GameSettings, vehicle.freight_trains, SLE_UINT8, 39, SL_MAX_VERSION, 0,NN, 1, 1, 255, 1, STR_CONFIG_SETTING_FREIGHT_TRAINS, NULL),
SDT_CONDBOOL(GameSettings, order.timetabling, 67, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_TIMETABLE_ALLOW, NULL),
SDT_CONDVAR(GameSettings, vehicle.plane_speed, SLE_UINT8, 90, SL_MAX_VERSION, 0, 0, 4, 1, 4, 0, STR_CONFIG_SETTING_PLANE_SPEED, NULL),
SDT_CONDBOOL(GameSettings, vehicle.dynamic_engines, 95, SL_MAX_VERSION, 0,NN, false, STR_CONFIG_SETTING_DYNAMIC_ENGINES, ChangeDynamicEngines),
SDT_BOOL(GameSettings, station.join_stations, 0, 0, true, STR_CONFIG_SETTING_JOINSTATIONS, NULL),
SDTC_CONDBOOL( gui.sg_full_load_any, 22, 92, 0, 0, true, STR_NULL, NULL),
SDT_BOOL(GameSettings, order.improved_load, 0,NN, true, STR_CONFIG_SETTING_IMPROVEDLOAD, NULL),
SDT_BOOL(GameSettings, order.selectgoods, 0, 0, true, STR_CONFIG_SETTING_SELECTGOODS, NULL),
SDTC_CONDBOOL( gui.sg_new_nonstop, 22, 92, 0, 0, false, STR_NULL, NULL),
SDT_BOOL(GameSettings, station.nonuniform_stations, 0,NN, true, STR_CONFIG_SETTING_NONUNIFORM_STATIONS, NULL),
SDT_VAR(GameSettings, station.station_spread, SLE_UINT8, 0, 0, 12, 4, 64, 0, STR_CONFIG_SETTING_STATION_SPREAD, InvalidateStationBuildWindow),
SDT_BOOL(GameSettings, order.serviceathelipad, 0, 0, true, STR_CONFIG_SETTING_SERVICEATHELIPAD, NULL),
SDT_BOOL(GameSettings, station.modified_catchment, 0, 0, true, STR_CONFIG_SETTING_CATCHMENT, NULL),
SDT_CONDBOOL(GameSettings, order.gradual_loading, 40, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_GRADUAL_LOADING, NULL),
SDT_CONDBOOL(GameSettings, construction.road_stop_on_town_road, 47, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_STOP_ON_TOWN_ROAD, NULL),
SDT_CONDBOOL(GameSettings, construction.road_stop_on_competitor_road, 114, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_STOP_ON_COMPETITOR_ROAD,NULL),
SDT_CONDBOOL(GameSettings, station.adjacent_stations, 62, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_ADJACENT_STATIONS, NULL),
SDT_CONDBOOL(GameSettings, economy.station_noise_level, 96, SL_MAX_VERSION, 0, 0, false, STR_CONFIG_SETTING_NOISE_LEVEL, InvalidateTownViewWindow),
SDT_CONDBOOL(GameSettings, station.distant_join_stations, 106, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_DISTANT_JOIN_STATIONS, DeleteSelectStationWindow),
SDT_BOOL(GameSettings, economy.inflation, 0, 0, true, STR_CONFIG_SETTING_INFLATION, NULL),
SDT_VAR(GameSettings, construction.raw_industry_construction, SLE_UINT8, 0,MS, 0, 0, 2, 0, STR_CONFIG_SETTING_RAW_INDUSTRY_CONSTRUCTION_METHOD, InvalidateBuildIndustryWindow),
SDT_BOOL(GameSettings, economy.multiple_industry_per_town, 0, 0, false, STR_CONFIG_SETTING_MULTIPINDTOWN, NULL),
SDT_BOOL(GameSettings, economy.same_industry_close, 0, 0, false, STR_CONFIG_SETTING_SAMEINDCLOSE, NULL),
SDT_BOOL(GameSettings, economy.bribe, 0, 0, true, STR_CONFIG_SETTING_BRIBE, NULL),
SDT_CONDBOOL(GameSettings, economy.exclusive_rights, 79, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_ALLOW_EXCLUSIVE, NULL),
SDT_CONDBOOL(GameSettings, economy.give_money, 79, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_ALLOW_GIVE_MONEY, NULL),
SDT_VAR(GameSettings, game_creation.snow_line_height, SLE_UINT8, 0, 0, 7, 2, 13, 0, STR_CONFIG_SETTING_SNOWLINE_HEIGHT, NULL),
SDTC_VAR( gui.coloured_news_year, SLE_INT32, 0,NC, 2000,MIN_YEAR,MAX_YEAR,1,STR_CONFIG_SETTING_COLOURED_NEWS_YEAR, NULL),
SDT_VAR(GameSettings, game_creation.starting_year, SLE_INT32, 0,NC, 1950,MIN_YEAR,MAX_YEAR,1,STR_CONFIG_SETTING_STARTING_YEAR, NULL),
SDT_CONDNULL( 4, 0, 104),
SDT_BOOL(GameSettings, economy.smooth_economy, 0, 0, true, STR_CONFIG_SETTING_SMOOTH_ECONOMY, NULL),
SDT_BOOL(GameSettings, economy.allow_shares, 0, 0, false, STR_CONFIG_SETTING_ALLOW_SHARES, NULL),
SDT_CONDVAR(GameSettings, economy.town_growth_rate, SLE_UINT8, 54, SL_MAX_VERSION, 0, MS, 2, 0, 4, 0, STR_CONFIG_SETTING_TOWN_GROWTH, NULL),
SDT_CONDVAR(GameSettings, economy.larger_towns, SLE_UINT8, 54, SL_MAX_VERSION, 0, D0, 4, 0, 255, 1, STR_CONFIG_SETTING_LARGER_TOWNS, NULL),
SDT_CONDVAR(GameSettings, economy.initial_city_size, SLE_UINT8, 56, SL_MAX_VERSION, 0, 0, 2, 1, 10, 1, STR_CONFIG_SETTING_CITY_SIZE_MULTIPLIER, NULL),
SDT_CONDBOOL(GameSettings, economy.mod_road_rebuild, 77, SL_MAX_VERSION, 0, 0, false, STR_CONFIG_SETTING_MODIFIED_ROAD_REBUILD, NULL),
SDT_CONDNULL(1, 0, 106), // previously ai-new setting.
SDT_BOOL(GameSettings, ai.ai_in_multiplayer, 0, 0, true, STR_CONFIG_SETTING_AI_IN_MULTIPLAYER, NULL),
SDT_BOOL(GameSettings, ai.ai_disable_veh_train, 0, 0, false, STR_CONFIG_SETTING_AI_BUILDS_TRAINS, NULL),
SDT_BOOL(GameSettings, ai.ai_disable_veh_roadveh, 0, 0, false, STR_CONFIG_SETTING_AI_BUILDS_ROADVEH, NULL),
SDT_BOOL(GameSettings, ai.ai_disable_veh_aircraft, 0, 0, false, STR_CONFIG_SETTING_AI_BUILDS_AIRCRAFT, NULL),
SDT_BOOL(GameSettings, ai.ai_disable_veh_ship, 0, 0, false, STR_CONFIG_SETTING_AI_BUILDS_SHIPS, NULL),
SDT_CONDVAR(GameSettings, ai.ai_max_opcode_till_suspend, SLE_UINT32,107, SL_MAX_VERSION, 0, NG, 10000, 5000,250000,2500, STR_CONFIG_SETTING_AI_MAX_OPCODES, NULL),
SDT_VAR(GameSettings, vehicle.extend_vehicle_life, SLE_UINT8, 0, 0, 0, 0, 100, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, economy.dist_local_authority, SLE_UINT8, 0, 0, 20, 5, 60, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.wait_oneway_signal, SLE_UINT8, 0, 0, 15, 2, 255, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.wait_twoway_signal, SLE_UINT8, 0, 0, 41, 2, 255, 0, STR_NULL, NULL),
SDT_CONDLISTO(GameSettings, economy.town_noise_population, 3, SLE_UINT16, 96, SL_MAX_VERSION, 0,D0, "800,2000,4000", STR_NULL, NULL, CheckNoiseToleranceLevel),
SDT_CONDVAR(GameSettings, pf.wait_for_pbs_path, SLE_UINT8,100, SL_MAX_VERSION, 0, 0, 30, 2, 255, 0, STR_NULL, NULL),
SDT_CONDBOOL(GameSettings, pf.reserve_paths, 100, SL_MAX_VERSION, 0, 0, false, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.path_backoff_interval, SLE_UINT8,100, SL_MAX_VERSION, 0, 0, 20, 1, 255, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.opf.pf_maxlength, SLE_UINT16, 0, 0, 4096, 64, 65535, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.opf.pf_maxdepth, SLE_UINT8, 0, 0, 48, 4, 255, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_max_search_nodes, SLE_UINT, 0, 0, 10000, 500, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_rail_firstred_penalty, SLE_UINT, 0, 0, ( 10 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_rail_firstred_exit_penalty, SLE_UINT, 0, 0, (100 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_rail_lastred_penalty, SLE_UINT, 0, 0, ( 10 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_rail_station_penalty, SLE_UINT, 0, 0, ( 1 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_rail_slope_penalty, SLE_UINT, 0, 0, ( 1 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_rail_curve_penalty, SLE_UINT, 0, 0, 1, 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_rail_depot_reverse_penalty, SLE_UINT, 0, 0, ( 50 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.npf.npf_rail_pbs_cross_penalty, SLE_UINT,100, SL_MAX_VERSION, 0, 0, ( 3 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.npf.npf_rail_pbs_signal_back_penalty, SLE_UINT,100, SL_MAX_VERSION, 0, 0, ( 15 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_buoy_penalty, SLE_UINT, 0, 0, ( 2 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_water_curve_penalty, SLE_UINT, 0, 0, (NPF_TILE_LENGTH / 4), 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_road_curve_penalty, SLE_UINT, 0, 0, 1, 0, 100000, 0, STR_NULL, NULL),
SDT_VAR(GameSettings, pf.npf.npf_crossing_penalty, SLE_UINT, 0, 0, ( 3 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.npf.npf_road_drive_through_penalty, SLE_UINT, 47, SL_MAX_VERSION, 0, 0, ( 8 * NPF_TILE_LENGTH), 0, 100000, 0, STR_NULL, NULL),
SDT_CONDBOOL(GameSettings, pf.yapf.disable_node_optimization, 28, SL_MAX_VERSION, 0, 0, false, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.max_search_nodes, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 10000, 500, 1000000, 0, STR_NULL, NULL),
SDT_CONDBOOL(GameSettings, pf.yapf.rail_firstred_twoway_eol, 28, SL_MAX_VERSION, 0, 0, true, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_firstred_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 10 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_firstred_exit_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 100 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_lastred_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 10 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_lastred_exit_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 100 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_station_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 10 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_slope_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 2 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_curve45_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 3 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_curve90_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 6 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_depot_reverse_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 50 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_crossing_penalty, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 3 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_look_ahead_max_signals, SLE_UINT, 28, SL_MAX_VERSION, 0, 0, 10, 1, 100, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_look_ahead_signal_p0, SLE_INT, 28, SL_MAX_VERSION, 0, 0, 500, -1000000, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_look_ahead_signal_p1, SLE_INT, 28, SL_MAX_VERSION, 0, 0, -100, -1000000, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_look_ahead_signal_p2, SLE_INT, 28, SL_MAX_VERSION, 0, 0, 5, -1000000, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_pbs_cross_penalty, SLE_UINT,100, SL_MAX_VERSION, 0, 0, 3 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_pbs_station_penalty, SLE_UINT,100, SL_MAX_VERSION, 0, 0, 8 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_pbs_signal_back_penalty, SLE_UINT,100, SL_MAX_VERSION, 0, 0, 15 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_doubleslip_penalty, SLE_UINT,100, SL_MAX_VERSION, 0, 0, 1 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_longer_platform_penalty, SLE_UINT, 33, SL_MAX_VERSION, 0, 0, 8 * YAPF_TILE_LENGTH, 0, 20000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_longer_platform_per_tile_penalty, SLE_UINT, 33, SL_MAX_VERSION, 0, 0, 0 * YAPF_TILE_LENGTH, 0, 20000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_shorter_platform_penalty, SLE_UINT, 33, SL_MAX_VERSION, 0, 0, 40 * YAPF_TILE_LENGTH, 0, 20000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.rail_shorter_platform_per_tile_penalty, SLE_UINT, 33, SL_MAX_VERSION, 0, 0, 0 * YAPF_TILE_LENGTH, 0, 20000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.road_slope_penalty, SLE_UINT, 33, SL_MAX_VERSION, 0, 0, 2 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.road_curve_penalty, SLE_UINT, 33, SL_MAX_VERSION, 0, 0, 1 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.road_crossing_penalty, SLE_UINT, 33, SL_MAX_VERSION, 0, 0, 3 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, pf.yapf.road_stop_penalty, SLE_UINT, 47, SL_MAX_VERSION, 0, 0, 8 * YAPF_TILE_LENGTH, 0, 1000000, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, game_creation.land_generator, SLE_UINT8, 30, SL_MAX_VERSION, 0,MS, 1, 0, 1, 0, STR_CONFIG_SETTING_LAND_GENERATOR, NULL),
SDT_CONDVAR(GameSettings, game_creation.oil_refinery_limit, SLE_UINT8, 30, SL_MAX_VERSION, 0, 0, 32, 12, 48, 0, STR_CONFIG_SETTING_OIL_REF_EDGE_DISTANCE, NULL),
SDT_CONDVAR(GameSettings, game_creation.tgen_smoothness, SLE_UINT8, 30, SL_MAX_VERSION, 0,MS, 1, 0, 3, 0, STR_CONFIG_SETTING_ROUGHNESS_OF_TERRAIN, NULL),
SDT_CONDVAR(GameSettings, game_creation.generation_seed, SLE_UINT32, 30, SL_MAX_VERSION, 0, 0, GENERATE_NEW_SEED, 0, UINT32_MAX, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, game_creation.tree_placer, SLE_UINT8, 30, SL_MAX_VERSION, 0,MS, 2, 0, 2, 0, STR_CONFIG_SETTING_TREE_PLACER, NULL),
SDT_VAR(GameSettings, game_creation.heightmap_rotation, SLE_UINT8, S,MS, 0, 0, 1, 0, STR_CONFIG_SETTING_HEIGHTMAP_ROTATION, NULL),
SDT_VAR(GameSettings, game_creation.se_flat_world_height, SLE_UINT8, S, 0, 1, 0, 15, 0, STR_CONFIG_SETTING_SE_FLAT_WORLD_HEIGHT, NULL),
SDT_VAR(GameSettings, game_creation.map_x, SLE_UINT8, S, 0, 8, 6, 11, 0, STR_CONFIG_SETTING_MAP_X, NULL),
SDT_VAR(GameSettings, game_creation.map_y, SLE_UINT8, S, 0, 8, 6, 11, 0, STR_CONFIG_SETTING_MAP_Y, NULL),
SDT_CONDBOOL(GameSettings, construction.freeform_edges, 111, SL_MAX_VERSION, 0, 0, true, STR_CONFIG_SETTING_ENABLE_FREEFORM_EDGES, CheckFreeformEdges),
SDT_CONDVAR(GameSettings, game_creation.water_borders, SLE_UINT8,111, SL_MAX_VERSION, 0, 0, 15, 0, 16, 0, STR_NULL, NULL),
SDT_CONDVAR(GameSettings, game_creation.custom_town_number, SLE_UINT16,115, SL_MAX_VERSION, 0, 0, 1, 1, 5000, 0, STR_NULL, NULL),
SDT_CONDOMANY(GameSettings, locale.currency, SLE_UINT8, 97, SL_MAX_VERSION, N, 0, 0, CUSTOM_CURRENCY_ID, "GBP|USD|EUR|YEN|ATS|BEF|CHF|CZK|DEM|DKK|ESP|FIM|FRF|GRD|HUF|ISK|ITL|NLG|NOK|PLN|ROL|RUR|SIT|SEK|YTL|SKK|BRR|custom", STR_NULL, NULL, NULL),
SDT_CONDOMANY(GameSettings, locale.units, SLE_UINT8, 97, SL_MAX_VERSION, N, 0, 1, 2, "imperial|metric|si", STR_NULL, NULL, NULL),
/***************************************************************************/
/* Unsaved setting variables. */
SDTC_OMANY(gui.autosave, SLE_UINT8, S, 0, 1, 4, "off|monthly|quarterly|half year|yearly", STR_NULL, NULL),
SDTC_OMANY(gui.date_format_in_default_names,SLE_UINT8,S,MS, 0, 2, "long|short|iso", STR_CONFIG_SETTING_DATE_FORMAT_IN_SAVE_NAMES, NULL),
SDTC_BOOL(gui.vehicle_speed, S, 0, true, STR_CONFIG_SETTING_VEHICLESPEED, NULL),
SDTC_BOOL(gui.status_long_date, S, 0, true, STR_CONFIG_SETTING_LONGDATE, NULL),
SDTC_BOOL(gui.show_finances, S, 0, true, STR_CONFIG_SETTING_SHOWFINANCES, NULL),
SDTC_BOOL(gui.autoscroll, S, 0, false, STR_CONFIG_SETTING_AUTOSCROLL, NULL),
SDTC_BOOL(gui.reverse_scroll, S, 0, false, STR_CONFIG_SETTING_REVERSE_SCROLLING, NULL),
SDTC_BOOL(gui.smooth_scroll, S, 0, false, STR_CONFIG_SETTING_SMOOTH_SCROLLING, NULL),
SDTC_BOOL(gui.left_mouse_btn_scrolling, S, 0, false, STR_CONFIG_SETTING_LEFT_MOUSE_BTN_SCROLLING, NULL),
SDTC_BOOL(gui.measure_tooltip, S, 0, true, STR_CONFIG_SETTING_MEASURE_TOOLTIP, NULL),
SDTC_VAR(gui.errmsg_duration, SLE_UINT8, S, 0, 5, 0, 20, 0, STR_CONFIG_SETTING_ERRMSG_DURATION, NULL),
SDTC_VAR(gui.toolbar_pos, SLE_UINT8, S, MS, 0, 0, 2, 0, STR_CONFIG_SETTING_TOOLBAR_POS, v_PositionMainToolbar),
SDTC_VAR(gui.window_snap_radius, SLE_UINT8, S, D0, 10, 1, 32, 0, STR_CONFIG_SETTING_SNAP_RADIUS, NULL),
SDTC_VAR(gui.window_soft_limit, SLE_UINT8, S, D0, 20, 5, 255, 1, STR_CONFIG_SETTING_SOFT_LIMIT, NULL),
SDTC_BOOL(gui.population_in_label, S, 0, true, STR_CONFIG_SETTING_POPULATION_IN_LABEL, PopulationInLabelActive),
SDTC_BOOL(gui.link_terraform_toolbar, S, 0, false, STR_CONFIG_SETTING_LINK_TERRAFORM_TOOLBAR, NULL),
SDTC_VAR(gui.liveries, SLE_UINT8, S, MS, 2, 0, 2, 0, STR_CONFIG_SETTING_LIVERIES, RedrawScreen),
SDTC_BOOL(gui.prefer_teamchat, S, 0, false, STR_CONFIG_SETTING_PREFER_TEAMCHAT, NULL),
SDTC_VAR(gui.scrollwheel_scrolling, SLE_UINT8, S, MS, 0, 0, 2, 0, STR_CONFIG_SETTING_SCROLLWHEEL_SCROLLING, NULL),
SDTC_VAR(gui.scrollwheel_multiplier, SLE_UINT8, S, 0, 5, 1, 15, 1, STR_CONFIG_SETTING_SCROLLWHEEL_MULTIPLIER, NULL),
SDTC_BOOL(gui.pause_on_newgame, S, 0, false, STR_CONFIG_SETTING_PAUSE_ON_NEW_GAME, NULL),
SDTC_VAR(gui.advanced_vehicle_list, SLE_UINT8, S, MS, 1, 0, 2, 0, STR_CONFIG_SETTING_ADVANCED_VEHICLE_LISTS, NULL),
SDTC_BOOL(gui.timetable_in_ticks, S, 0, false, STR_CONFIG_SETTING_TIMETABLE_IN_TICKS, NULL),
SDTC_BOOL(gui.quick_goto, S, 0, false, STR_CONFIG_SETTING_QUICKGOTO, NULL),
SDTC_VAR(gui.loading_indicators, SLE_UINT8, S, MS, 1, 0, 2, 0, STR_CONFIG_SETTING_LOADING_INDICATORS, RedrawScreen),
SDTC_VAR(gui.default_rail_type, SLE_UINT8, S, MS, 4, 0, 6, 0, STR_CONFIG_SETTING_DEFAULT_RAIL_TYPE, NULL),
SDTC_BOOL(gui.enable_signal_gui, S, 0, true, STR_CONFIG_SETTING_ENABLE_SIGNAL_GUI, CloseSignalGUI),
SDTC_VAR(gui.drag_signals_density, SLE_UINT8, S, 0, 4, 1, 20, 0, STR_CONFIG_SETTING_DRAG_SIGNALS_DENSITY, DragSignalsDensityChanged),
SDTC_VAR(gui.semaphore_build_before, SLE_INT32, S, NC, 1975, MIN_YEAR, MAX_YEAR, 1, STR_CONFIG_SETTING_SEMAPHORE_BUILD_BEFORE_DATE, ResetSignalVariant),
SDTC_BOOL(gui.vehicle_income_warn, S, 0, true, STR_CONFIG_SETTING_WARN_INCOME_LESS, NULL),
SDTC_VAR(gui.order_review_system, SLE_UINT8, S, MS, 2, 0, 2, 0, STR_CONFIG_SETTING_ORDER_REVIEW, NULL),
SDTC_BOOL(gui.lost_train_warn, S, 0, true, STR_CONFIG_SETTING_WARN_LOST_TRAIN, NULL),
SDTC_BOOL(gui.autorenew, S, 0, false, STR_CONFIG_SETTING_AUTORENEW_VEHICLE, EngineRenewUpdate),
SDTC_VAR(gui.autorenew_months, SLE_INT16, S, 0, 6, -12, 12, 0, STR_CONFIG_SETTING_AUTORENEW_MONTHS, EngineRenewMonthsUpdate),
SDTC_VAR(gui.autorenew_money, SLE_UINT, S, CR,100000, 0, 2000000, 0, STR_CONFIG_SETTING_AUTORENEW_MONEY, EngineRenewMoneyUpdate),
SDTC_BOOL(gui.always_build_infrastructure, S, 0, false, STR_CONFIG_SETTING_ALWAYS_BUILD_INFRASTRUCTURE, RedrawScreen),
SDTC_BOOL(gui.new_nonstop, S, 0, false, STR_CONFIG_SETTING_NONSTOP_BY_DEFAULT, NULL),
SDTC_BOOL(gui.keep_all_autosave, S, 0, false, STR_NULL, NULL),
SDTC_BOOL(gui.autosave_on_exit, S, 0, false, STR_NULL, NULL),
SDTC_VAR(gui.max_num_autosaves, SLE_UINT8, S, 0, 16, 0, 255, 0, STR_NULL, NULL),
SDTC_BOOL(gui.bridge_pillars, S, 0, true, STR_NULL, NULL),
SDTC_BOOL(gui.auto_euro, S, 0, true, STR_NULL, NULL),
SDTC_VAR(gui.news_message_timeout, SLE_UINT8, S, 0, 2, 1, 255, 0, STR_NULL, NULL),
SDTC_BOOL(gui.show_track_reservation, S, 0, false, STR_CONFIG_SETTING_SHOW_TRACK_RESERVATION, RedrawScreen),
SDTC_VAR(gui.default_signal_type, SLE_UINT8, S, MS, 0, 0, 2, 1, STR_CONFIG_SETTING_DEFAULT_SIGNAL_TYPE, NULL),
SDTC_VAR(gui.cycle_signal_types, SLE_UINT8, S, MS, 2, 0, 2, 1, STR_CONFIG_SETTING_CYCLE_SIGNAL_TYPES, NULL),
SDTC_VAR(gui.station_numtracks, SLE_UINT8, S, 0, 1, 1, 7, 0, STR_NULL, NULL),
SDTC_VAR(gui.station_platlength, SLE_UINT8, S, 0, 5, 1, 7, 0, STR_NULL, NULL),
SDTC_BOOL(gui.station_dragdrop, S, 0, true, STR_NULL, NULL),
SDTC_BOOL(gui.station_show_coverage, S, 0, false, STR_NULL, NULL),
SDTC_BOOL(gui.persistent_buildingtools, S, 0, false, STR_CONFIG_SETTING_PERSISTENT_BUILDINGTOOLS, NULL),
SDTC_BOOL(gui.expenses_layout, S, 0, false, STR_CONFIG_SETTING_EXPENSES_LAYOUT, RedrawScreen),
SDTC_VAR(gui.console_backlog_timeout, SLE_UINT16, S, 0, 100, 10, 65500, 0, STR_NULL, NULL),
SDTC_VAR(gui.console_backlog_length, SLE_UINT16, S, 0, 100, 10, 65500, 0, STR_NULL, NULL),
#ifdef ENABLE_NETWORK
SDTC_VAR(gui.network_chat_box_width, SLE_UINT16, S, 0, 700, 200, 65535, 0, STR_NULL, NULL),
SDTC_VAR(gui.network_chat_box_height, SLE_UINT8, S, 0, 25, 5, 255, 0, STR_NULL, NULL),
SDTC_VAR(network.sync_freq, SLE_UINT16,C|S,NO, 100, 0, 100, 0, STR_NULL, NULL),
SDTC_VAR(network.frame_freq, SLE_UINT8,C|S,NO, 0, 0, 100, 0, STR_NULL, NULL),
SDTC_VAR(network.max_join_time, SLE_UINT16, S, NO, 500, 0, 32000, 0, STR_NULL, NULL),
SDTC_BOOL(network.pause_on_join, S, NO, true, STR_NULL, NULL),
SDTC_STR(network.server_bind_ip, SLE_STRB, S, NO, "0.0.0.0", STR_NULL, NULL),
SDTC_VAR(network.server_port, SLE_UINT16, S, NO,NETWORK_DEFAULT_PORT,0,65535,0,STR_NULL, NULL),
SDTC_BOOL(network.server_advertise, S, NO, false, STR_NULL, NULL),
SDTC_VAR(network.lan_internet, SLE_UINT8, S, NO, 0, 0, 1, 0, STR_NULL, NULL),
SDTC_STR(network.client_name, SLE_STRB, S, 0, NULL, STR_NULL, UpdateClientName),
SDTC_STR(network.server_password, SLE_STRB, S, NO, NULL, STR_NULL, UpdateServerPassword),
SDTC_STR(network.rcon_password, SLE_STRB, S, NO, NULL, STR_NULL, UpdateRconPassword),
SDTC_STR(network.default_company_pass, SLE_STRB, S, 0, NULL, STR_NULL, NULL),
SDTC_STR(network.server_name, SLE_STRB, S, NO, NULL, STR_NULL, NULL),
SDTC_STR(network.connect_to_ip, SLE_STRB, S, 0, NULL, STR_NULL, NULL),
SDTC_STR(network.network_id, SLE_STRB, S, NO, NULL, STR_NULL, NULL),
SDTC_BOOL(network.autoclean_companies, S, NO, false, STR_NULL, NULL),
SDTC_VAR(network.autoclean_unprotected, SLE_UINT8, S,D0|NO, 12, 0, 240, 0, STR_NULL, NULL),
SDTC_VAR(network.autoclean_protected, SLE_UINT8, S,D0|NO, 36, 0, 240, 0, STR_NULL, NULL),
SDTC_VAR(network.autoclean_novehicles, SLE_UINT8, S,D0|NO, 0, 0, 240, 0, STR_NULL, NULL),
SDTC_VAR(network.max_companies, SLE_UINT8, S, NO, 8, 1,MAX_COMPANIES,0, STR_NULL, UpdateClientConfigValues),
SDTC_VAR(network.max_clients, SLE_UINT8, S, NO, 16, 2, MAX_CLIENTS, 0, STR_NULL, NULL),
SDTC_VAR(network.max_spectators, SLE_UINT8, S, NO, 8, 0, MAX_CLIENTS, 0, STR_NULL, UpdateClientConfigValues),
SDTC_VAR(network.restart_game_year, SLE_INT32, S,D0|NO|NC,0, MIN_YEAR, MAX_YEAR, 1, STR_NULL, NULL),
SDTC_VAR(network.min_active_clients, SLE_UINT8, S, NO, 0, 0, MAX_CLIENTS, 0, STR_NULL, NULL),
SDTC_OMANY(network.server_lang, SLE_UINT8, S, NO, 0, 35, "ANY|ENGLISH|GERMAN|FRENCH|BRAZILIAN|BULGARIAN|CHINESE|CZECH|DANISH|DUTCH|ESPERANTO|FINNISH|HUNGARIAN|ICELANDIC|ITALIAN|JAPANESE|KOREAN|LITHUANIAN|NORWEGIAN|POLISH|PORTUGUESE|ROMANIAN|RUSSIAN|SLOVAK|SLOVENIAN|SPANISH|SWEDISH|TURKISH|UKRAINIAN|AFRIKAANS|CROATIAN|CATALAN|ESTONIAN|GALICIAN|GREEK|LATVIAN", STR_NULL, NULL),
SDTC_BOOL(network.reload_cfg, S, NO, false, STR_NULL, NULL),
SDTC_STR(network.last_host, SLE_STRB, S, 0, "0.0.0.0", STR_NULL, NULL),
SDTC_VAR(network.last_port, SLE_UINT16, S, 0, 0, 0, UINT16_MAX, 0, STR_NULL, NULL),
#endif /* ENABLE_NETWORK */
/*
* Since the network code (CmdChangeSetting and friends) use the index in this array to decide
* which setting the server is talking about all conditional compilation of this array must be at the
* end. This isn't really the best solution, the settings the server can tell the client about should
* either use a seperate array or some other form of identifier.
*/
#ifdef __APPLE__
/* We might need to emulate a right mouse button on mac */
SDTC_VAR(gui.right_mouse_btn_emulation, SLE_UINT8, S, MS, 0, 0, 2, 0, STR_CONFIG_SETTING_RIGHT_MOUSE_BTN_EMU, NULL),
#endif
SDT_END()
};
static const SettingDesc _currency_settings[] = {
SDT_VAR(CurrencySpec, rate, SLE_UINT16, S, 0, 1, 0, UINT16_MAX, 0, STR_NULL, NULL),
SDT_CHR(CurrencySpec, separator, S, 0, ".", STR_NULL, NULL),
SDT_VAR(CurrencySpec, to_euro, SLE_INT32, S, 0, 0, MIN_YEAR, MAX_YEAR, 0, STR_NULL, NULL),
SDT_STR(CurrencySpec, prefix, SLE_STRBQ, S, 0, NULL, STR_NULL, NULL),
SDT_STR(CurrencySpec, suffix, SLE_STRBQ, S, 0, " credits", STR_NULL, NULL),
SDT_END()
};
/* Undefine for the shortcut macros above */
#undef S
#undef C
#undef N
#undef D0
#undef NC
#undef MS
#undef NO
#undef CR
/**
* Prepare for reading and old diff_custom by zero-ing the memory.
*/
static void PrepareOldDiffCustom()
{
memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
}
/**
* Reading of the old diff_custom array and transforming it to the new format.
* @param savegame is it read from the config or savegame. In the latter case
* we are sure there is an array; in the former case we have
* to check that.
*/
static void HandleOldDiffCustom(bool savegame)
{
uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && CheckSavegameVersion(4)) ? 1 : 0);
if (!savegame) {
/* If we did read to old_diff_custom, then at least one value must be non 0. */
bool old_diff_custom_used = false;
for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
old_diff_custom_used = (_old_diff_custom[i] != 0);
}
if (!old_diff_custom_used) return;
}
for (uint i = 0; i < options_to_load; i++) {
const SettingDesc *sd = &_settings[i];
/* Skip deprecated options */
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
void *var = GetVariableAddress(savegame ? &_settings_game : &_settings_newgame, &sd->save);
Write_ValidateSetting(var, sd, (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]));
}
}
/** tries to convert newly introduced news settings based on old ones
* @param name pointer to the string defining name of the old news config
* @param value pointer to the string defining value of the old news config
* @returns true if conversion could have been made */
bool ConvertOldNewsSetting(const char *name, const char *value)
{
if (strcasecmp(name, "openclose") == 0) {
/* openclose has been split in "open" and "close".
* So the job is now to decrypt the value of the old news config
* and give it to the two newly introduced ones*/
NewsDisplay display = ND_OFF; // default
if (strcasecmp(value, "full") == 0) {
display = ND_FULL;
} else if (strcasecmp(value, "summarized") == 0) {
display = ND_SUMMARY;
}
/* tranfert of values */
_news_type_data[NT_INDUSTRY_OPEN].display = display;
_news_type_data[NT_INDUSTRY_CLOSE].display = display;
return true;
}
return false;
}
static void NewsDisplayLoadConfig(IniFile *ini, const char *grpname)
{
IniGroup *group = ini->GetGroup(grpname);
IniItem *item;
/* If no group exists, return */
if (group == NULL) return;
for (item = group->item; item != NULL; item = item->next) {
int news_item = -1;
for (int i = 0; i < NT_END; i++) {
if (strcasecmp(item->name, _news_type_data[i].name) == 0) {
news_item = i;
break;
}
}
/* the config been read is not within current aceptable config */
if (news_item == -1) {
/* if the conversion function cannot process it, advice by a debug warning*/
if (!ConvertOldNewsSetting(item->name, item->value)) {
DEBUG(misc, 0, "Invalid display option: %s", item->name);
}
/* in all cases, there is nothing left to do */
continue;
}
if (strcasecmp(item->value, "full") == 0) {
_news_type_data[news_item].display = ND_FULL;
} else if (strcasecmp(item->value, "off") == 0) {
_news_type_data[news_item].display = ND_OFF;
} else if (strcasecmp(item->value, "summarized") == 0) {
_news_type_data[news_item].display = ND_SUMMARY;
} else {
DEBUG(misc, 0, "Invalid display value: %s", item->value);
continue;
}
}
}
static void AILoadConfig(IniFile *ini, const char *grpname)
{
IniGroup *group = ini->GetGroup(grpname);
IniItem *item;
/* Clean any configured AI */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
AIConfig::GetConfig(c, true)->ChangeAI(NULL);
}
/* If no group exists, return */
if (group == NULL) return;
CompanyID c = COMPANY_FIRST;
for (item = group->item; c < MAX_COMPANIES && item != NULL; c++, item = item->next) {
AIConfig *config = AIConfig::GetConfig(c, true);
config->ChangeAI(item->name);
if (!config->HasAI()) {
if (strcmp(item->name, "none") != 0) {
DEBUG(ai, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item->name);
continue;
}
}
config->StringToSettings(item->value);
}
}
/* Load a GRF configuration from the given group name */
static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
{
IniGroup *group = ini->GetGroup(grpname);
IniItem *item;
GRFConfig *first = NULL;
GRFConfig **curr = &first;
if (group == NULL) return NULL;
for (item = group->item; item != NULL; item = item->next) {
GRFConfig *c = CallocT<GRFConfig>(1);
c->filename = strdup(item->name);
/* Parse parameters */
if (!StrEmpty(item->value)) {
c->num_params = parse_intlist(item->value, (int*)c->param, lengthof(c->param));
if (c->num_params == (byte)-1) {
ShowInfoF("ini: error in array '%s'", item->name);
c->num_params = 0;
}
}
/* Check if item is valid */
if (!FillGRFDetails(c, is_static)) {
const char *msg;
if (c->status == GCS_NOT_FOUND) {
msg = "not found";
} else if (HasBit(c->flags, GCF_UNSAFE)) {
msg = "unsafe for static use";
} else if (HasBit(c->flags, GCF_SYSTEM)) {
msg = "system NewGRF";
} else {
msg = "unknown";
}
ShowInfoF("ini: ignoring invalid NewGRF '%s': %s", item->name, msg);
ClearGRFConfig(&c);
continue;
}
/* Mark file as static to avoid saving in savegame. */
if (is_static) SetBit(c->flags, GCF_STATIC);
/* Add item to list */
*curr = c;
curr = &c->next;
}
return first;
}
static void NewsDisplaySaveConfig(IniFile *ini, const char *grpname)
{
IniGroup *group = ini->GetGroup(grpname);
for (int i = 0; i < NT_END; i++) {
const char *value;
int v = _news_type_data[i].display;
value = (v == ND_OFF ? "off" : (v == ND_SUMMARY ? "summarized" : "full"));
group->GetItem(_news_type_data[i].name, true)->SetValue(value);
}
}
static void AISaveConfig(IniFile *ini, const char *grpname)
{
IniGroup *group = ini->GetGroup(grpname);
if (group == NULL) return;
group->Clear();
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
AIConfig *config = AIConfig::GetConfig(c, true);
const char *name;
char value[1024];
config->SettingsToString(value, lengthof(value));
if (config->HasAI()) {
name = config->GetName();
} else {
name = "none";
}
IniItem *item = new IniItem(group, name, strlen(name));
item->SetValue(value);
}
}
/**
* Save the version of OpenTTD to the ini file.
* @param ini the ini to write to
*/
static void SaveVersionInConfig(IniFile *ini)
{
IniGroup *group = ini->GetGroup("version");
char version[9];
snprintf(version, lengthof(version), "%08X", _openttd_newgrf_version);
const char *versions[][2] = {
{ "version_string", _openttd_revision },
{ "version_number", version }
};
for (uint i = 0; i < lengthof(versions); i++) {
group->GetItem(versions[i][0], true)->SetValue(versions[i][1]);
}
}
/* Save a GRF configuration to the given group name */
static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
{
ini->RemoveGroup(grpname);
IniGroup *group = ini->GetGroup(grpname);
const GRFConfig *c;
for (c = list; c != NULL; c = c->next) {
char params[512];
GRFBuildParamList(params, c, lastof(params));
group->GetItem(c->filename, true)->SetValue(params);
}
}
/* Common handler for saving/loading variables to the configuration file */
static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list)
{
proc(ini, (const SettingDesc*)_misc_settings, "misc", NULL);
proc(ini, (const SettingDesc*)_music_settings, "music", &msf);
#if defined(WIN32) && !defined(DEDICATED)
proc(ini, (const SettingDesc*)_win32_settings, "win32", NULL);
#endif /* WIN32 */
proc(ini, _settings, "patches", &_settings_newgame);
proc(ini, _currency_settings,"currency", &_custom_currency);
#ifdef ENABLE_NETWORK
proc_list(ini, "servers", _network_host_list, lengthof(_network_host_list), NULL);
proc_list(ini, "bans", _network_ban_list, lengthof(_network_ban_list), NULL);
#endif /* ENABLE_NETWORK */
}
static IniFile *IniLoadConfig()
{
IniFile *ini = new IniFile(_list_group_names);
ini->LoadFromDisk(_config_file);
return ini;
}
/** Load the values from the configuration files */
void LoadFromConfig()
{
IniFile *ini = IniLoadConfig();
ResetCurrencies(false); // Initialize the array of curencies, without preserving the custom one
HandleSettingDescs(ini, ini_load_settings, ini_load_setting_list);
_grfconfig_newgame = GRFLoadConfig(ini, "newgrf", false);
_grfconfig_static = GRFLoadConfig(ini, "newgrf-static", true);
NewsDisplayLoadConfig(ini, "news_display");
AILoadConfig(ini, "ai_players");
PrepareOldDiffCustom();
ini_load_settings(ini, _gameopt_settings, "gameopt", &_settings_newgame);
HandleOldDiffCustom(false);
CheckDifficultyLevels();
delete ini;
}
/** Save the values to the configuration file */
void SaveToConfig()
{
IniFile *ini = IniLoadConfig();
/* Remove some obsolete groups. These have all been loaded into other groups. */
ini->RemoveGroup("patches");
ini->RemoveGroup("yapf");
ini->RemoveGroup("gameopt");
HandleSettingDescs(ini, ini_save_settings, ini_save_setting_list);
GRFSaveConfig(ini, "newgrf", _grfconfig_newgame);
GRFSaveConfig(ini, "newgrf-static", _grfconfig_static);
NewsDisplaySaveConfig(ini, "news_display");
AISaveConfig(ini, "ai_players");
SaveVersionInConfig(ini);
ini->SaveToDisk(_config_file);
delete ini;
}
void GetGRFPresetList(GRFPresetList *list)
{
list->Clear();
IniFile *ini = IniLoadConfig();
IniGroup *group;
for (group = ini->group; group != NULL; group = group->next) {
if (strncmp(group->name, "preset-", 7) == 0) {
*list->Append() = strdup(group->name + 7);
}
}
delete ini;
}
GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
{
char *section = (char*)alloca(strlen(config_name) + 8);
sprintf(section, "preset-%s", config_name);
IniFile *ini = IniLoadConfig();
GRFConfig *config = GRFLoadConfig(ini, section, false);
delete ini;
return config;
}
void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
{
char *section = (char*)alloca(strlen(config_name) + 8);
sprintf(section, "preset-%s", config_name);
IniFile *ini = IniLoadConfig();
GRFSaveConfig(ini, section, config);
ini->SaveToDisk(_config_file);
delete ini;
}
void DeleteGRFPresetFromConfig(const char *config_name)
{
char *section = (char*)alloca(strlen(config_name) + 8);
sprintf(section, "preset-%s", config_name);
IniFile *ini = IniLoadConfig();
ini->RemoveGroup(section);
ini->SaveToDisk(_config_file);
delete ini;
}
static const SettingDesc *GetSettingDescription(uint index)
{
if (index >= lengthof(_settings)) return NULL;
return &_settings[index];
}
/** Network-safe changing of settings (server-only).
* @param tile unused
* @param flags operation to perform
* @param p1 the index of the setting in the SettingDesc array which identifies it
* @param p2 the new value for the setting
* The new value is properly clamped to its minimum/maximum when setting
* @see _settings
*/
CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
const SettingDesc *sd = GetSettingDescription(p1);
if (sd == NULL) return CMD_ERROR;
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
if ((sd->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return CMD_ERROR;
if ((sd->desc.flags & SGF_NO_NETWORK) && _networking) return CMD_ERROR;
if ((sd->desc.flags & SGF_NEWGAME_ONLY) && _game_mode != GM_MENU) return CMD_ERROR;
if (flags & DC_EXEC) {
GameSettings *s = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;
void *var = GetVariableAddress(s, &sd->save);
int32 oldval = (int32)ReadValue(var, sd->save.conv);
int32 newval = (int32)p2;
Write_ValidateSetting(var, sd, newval);
newval = (int32)ReadValue(var, sd->save.conv);
if (oldval == newval) return CommandCost();
if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
WriteValue(var, sd->save.conv, (int64)oldval);
return CommandCost();
}
if (sd->desc.flags & SGF_NO_NETWORK) {
GamelogStartAction(GLAT_SETTING);
GamelogSetting(sd->desc.name, oldval, newval);
GamelogStopAction();
}
InvalidateWindow(WC_GAME_OPTIONS, 0);
}
return CommandCost();
}
/** Top function to save the new value of an element of the Settings struct
* @param index offset in the SettingDesc array of the Settings struct which
* identifies the setting member we want to change
* @param object pointer to a valid settings struct that has its settings change.
* This only affects setting-members that are not needed to be the same on all
* clients in a network game.
* @param value new value of the setting */
bool SetSettingValue(uint index, int32 value)
{
const SettingDesc *sd = &_settings[index];
/* If an item is company-based, we do not send it over the network
* (if any) to change. Also *hack*hack* we update the _newgame version
* of settings because changing a company-based setting in a game also
* changes its defaults. At least that is the convention we have chosen */
if (sd->save.conv & SLF_NETWORK_NO) {
void *var = GetVariableAddress((_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game, &sd->save);
Write_ValidateSetting(var, sd, value);
if (_game_mode != GM_MENU) {
void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
Write_ValidateSetting(var2, sd, value);
}
if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
InvalidateWindow(WC_GAME_OPTIONS, 0);
return true;
}
/* send non-company-based settings over the network */
if (!_networking || (_networking && _network_server)) {
return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
}
return false;
}
/**
* Set a setting value with a string.
* @param index the settings index.
* @param value the value to write
* @note CANNOT BE SAVED IN THE SAVEGAME.
*/
bool SetSettingValue(uint index, const char *value)
{
const SettingDesc *sd = &_settings[index];
assert(sd->save.conv & SLF_NETWORK_NO);
char *var = (char*)GetVariableAddress(NULL, &sd->save);
ttd_strlcpy(var, value, sd->save.length);
if (sd->desc.proc != NULL) sd->desc.proc(0);
return true;
}
/**
* Given a name of setting, return a setting description of it.
* @param name Name of the setting to return a setting description of
* @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
* @return Pointer to the setting description of setting \a name if it can be found,
* \c NULL indicates failure to obtain the description
*/
const SettingDesc *GetSettingFromName(const char *name, uint *i)
{
const SettingDesc *sd;
/* First check all full names */
for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
if (strcmp(sd->desc.name, name) == 0) return sd;
}
/* Then check the shortcut variant of the name. */
for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
const char *short_name = strchr(sd->desc.name, '.');
if (short_name != NULL) {
short_name++;
if (strcmp(short_name, name) == 0) return sd;
}
}
return NULL;
}
/* Those 2 functions need to be here, else we have to make some stuff non-static
* and besides, it is also better to keep stuff like this at the same place */
void IConsoleSetSetting(const char *name, const char *value)
{
uint index;
const SettingDesc *sd = GetSettingFromName(name, &index);
if (sd == NULL) {
IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
return;
}
bool success;
if (sd->desc.cmd == SDT_STRING) {
success = SetSettingValue(index, value);
} else {
uint32 val;
extern bool GetArgumentInteger(uint32 *value, const char *arg);
success = GetArgumentInteger(&val, value);
if (success) success = SetSettingValue(index, val);
}
if (!success) {
if (_network_server) {
IConsoleError("This command/variable is not available during network games.");
} else {
IConsoleError("This command/variable is only available to a network server.");
}
}
}
void IConsoleSetSetting(const char *name, int value)
{
uint index;
const SettingDesc *sd = GetSettingFromName(name, &index);
assert(sd != NULL);
SetSettingValue(index, value);
}
/**
* Output value of a specific setting to the console
* @param name Name of the setting to output its value
*/
void IConsoleGetSetting(const char *name)
{
char value[20];
uint index;
const SettingDesc *sd = GetSettingFromName(name, &index);
const void *ptr;
if (sd == NULL) {
IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
return;
}
ptr = GetVariableAddress((_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game, &sd->save);
if (sd->desc.cmd == SDT_STRING) {
IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (const char *)ptr);
} else {
if (sd->desc.cmd == SDT_BOOLX) {
snprintf(value, sizeof(value), (*(bool*)ptr == 1) ? "on" : "off");
} else {
snprintf(value, sizeof(value), "%d", (int32)ReadValue(ptr, sd->save.conv));
}
IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s' (min: %s%d, max: %d)",
name, value, (sd->desc.flags & SGF_0ISDISABLED) ? "(0) " : "", sd->desc.min, sd->desc.max);
}
}
/**
* List all settings and their value to the console
*
* @param prefilter If not \c NULL, only list settings with names that begin with \a prefilter prefix
*/
void IConsoleListSettings(const char *prefilter)
{
IConsolePrintF(CC_WARNING, "All settings with their current value:");
for (const SettingDesc *sd = _settings; sd->save.cmd != SL_END; sd++) {
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
if (prefilter != NULL) {
if (strncmp(sd->desc.name, prefilter, min(strlen(sd->desc.name), strlen(prefilter))) != 0) continue;
}
char value[80];
const void *ptr = GetVariableAddress((_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game, &sd->save);
if (sd->desc.cmd == SDT_BOOLX) {
snprintf(value, lengthof(value), (*(bool*)ptr == 1) ? "on" : "off");
} else if (sd->desc.cmd == SDT_STRING) {
snprintf(value, sizeof(value), "%s", (const char *)ptr);
} else {
snprintf(value, lengthof(value), "%d", (uint32)ReadValue(ptr, sd->save.conv));
}
IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
}
IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
}
/** Save and load handler for settings
* @param osd SettingDesc struct containing all information
* @param object can be either NULL in which case we load global variables or
* a pointer to a struct which is getting saved */
static void LoadSettings(const SettingDesc *osd, void *object)
{
for (; osd->save.cmd != SL_END; osd++) {
const SaveLoad *sld = &osd->save;
void *ptr = GetVariableAddress(object, sld);
if (!SlObjectMember(ptr, sld)) continue;
}
}
/** Loadhandler for a list of global variables
* @param sdg pointer for the global variable list SettingDescGlobVarList
* @note this is actually a stub for LoadSettings with the
* object pointer set to NULL */
static inline void LoadSettingsGlobList(const SettingDescGlobVarList *sdg)
{
LoadSettings((const SettingDesc*)sdg, NULL);
}
/** Save and load handler for settings
* @param sd SettingDesc struct containing all information
* @param object can be either NULL in which case we load global variables or
* a pointer to a struct which is getting saved */
static void SaveSettings(const SettingDesc *sd, void *object)
{
/* We need to write the CH_RIFF header, but unfortunately can't call
* SlCalcLength() because we have a different format. So do this manually */
const SettingDesc *i;
size_t length = 0;
for (i = sd; i->save.cmd != SL_END; i++) {
const void *ptr = GetVariableAddress(object, &i->save);
length += SlCalcObjMemberLength(ptr, &i->save);
}
SlSetLength(length);
for (i = sd; i->save.cmd != SL_END; i++) {
void *ptr = GetVariableAddress(object, &i->save);
SlObjectMember(ptr, &i->save);
}
}
/** Savehandler for a list of global variables
* @note this is actually a stub for SaveSettings with the
* object pointer set to NULL */
static inline void SaveSettingsGlobList(const SettingDescGlobVarList *sdg)
{
SaveSettings((const SettingDesc*)sdg, NULL);
}
static void Load_OPTS()
{
/* Copy over default setting since some might not get loaded in
* a networking environment. This ensures for example that the local
* autosave-frequency stays when joining a network-server */
PrepareOldDiffCustom();
LoadSettings(_gameopt_settings, &_settings_game);
HandleOldDiffCustom(true);
}
static void Load_PATS()
{
/* Copy over default setting since some might not get loaded in
* a networking environment. This ensures for example that the local
* signal_side stays when joining a network-server */
LoadSettings(_settings, &_settings_game);
}
static void Save_PATS()
{
SaveSettings(_settings, &_settings_game);
}
void CheckConfig()
{
/*
* Increase old default values for pf_maxdepth and pf_maxlength
* to support big networks.
*/
if (_settings_newgame.pf.opf.pf_maxdepth == 16 && _settings_newgame.pf.opf.pf_maxlength == 512) {
_settings_newgame.pf.opf.pf_maxdepth = 48;
_settings_newgame.pf.opf.pf_maxlength = 4096;
}
}
extern const ChunkHandler _setting_chunk_handlers[] = {
{ 'OPTS', NULL, Load_OPTS, CH_RIFF},
{ 'PATS', Save_PATS, Load_PATS, CH_RIFF | CH_LAST},
};
static bool IsSignedVarMemType(VarType vt)
{
switch (GetVarMemType(vt)) {
case SLE_VAR_I8:
case SLE_VAR_I16:
case SLE_VAR_I32:
case SLE_VAR_I64:
return true;
}
return false;
}
| 118,284
|
C++
|
.cpp
| 2,031
| 55.570162
| 395
| 0.617575
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,050
|
waypoint.cpp
|
EnergeticBark_OpenTTD-3DS/src/waypoint.cpp
|
/* $Id$ */
/** @file waypoint.cpp Handling of waypoints. */
#include "stdafx.h"
#include "strings_type.h"
#include "rail.h"
#include "station_base.h"
#include "town.h"
#include "waypoint.h"
#include "window_func.h"
#include "newgrf_station.h"
#include "oldpool_func.h"
#include "order_func.h"
DEFINE_OLD_POOL_GENERIC(Waypoint, Waypoint)
/**
* Update all signs
*/
void UpdateAllWaypointSigns()
{
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
UpdateWaypointSign(wp);
}
}
/**
* Daily loop for waypoints
*/
void WaypointsDailyLoop()
{
Waypoint *wp;
/* Check if we need to delete a waypoint */
FOR_ALL_WAYPOINTS(wp) {
if (wp->deleted != 0 && --wp->deleted == 0) delete wp;
}
}
/**
* This hacks together some dummy one-shot Station structure for a waypoint.
* @param tile on which to work
* @return pointer to a Station
*/
Station *ComposeWaypointStation(TileIndex tile)
{
Waypoint *wp = GetWaypointByTile(tile);
/* instead of 'static Station stat' use byte array to avoid Station's destructor call upon exit. As
* a side effect, the station is not constructed now. */
static byte stat_raw[sizeof(Station)];
static Station &stat = *(Station*)stat_raw;
stat.train_tile = stat.xy = wp->xy;
stat.town = GetTown(wp->town_index);
stat.build_date = wp->build_date;
return &stat;
}
/**
* Draw a waypoint
* @param x coordinate
* @param y coordinate
* @param stat_id station id
* @param railtype RailType to use for
*/
void DrawWaypointSprite(int x, int y, int stat_id, RailType railtype)
{
x += 33;
y += 17;
if (!DrawStationTile(x, y, railtype, AXIS_X, STAT_CLASS_WAYP, stat_id)) {
DrawDefaultWaypointSprite(x, y, railtype);
}
}
Waypoint::Waypoint(TileIndex tile)
{
this->xy = tile;
}
Waypoint::~Waypoint()
{
free(this->name);
if (CleaningPool()) return;
DeleteWindowById(WC_WAYPOINT_VIEW, this->index);
RemoveOrderFromAllVehicles(OT_GOTO_WAYPOINT, this->index);
RedrawWaypointSign(this);
this->xy = INVALID_TILE;
}
void InitializeWaypoints()
{
_Waypoint_pool.CleanPool();
_Waypoint_pool.AddBlockToPool();
}
| 2,055
|
C++
|
.cpp
| 84
| 22.642857
| 100
| 0.727971
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,051
|
cheat_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/cheat_gui.cpp
|
/* $Id$ */
/** @file cheat_gui.cpp GUI related to cheating. */
#include "stdafx.h"
#include "command_func.h"
#include "cheat_type.h"
#include "company_base.h"
#include "company_func.h"
#include "gfx_func.h"
#include "date_func.h"
#include "saveload/saveload.h"
#include "window_gui.h"
#include "newgrf.h"
#include "settings_type.h"
#include "strings_func.h"
#include "window_func.h"
#include "rail_gui.h"
#include "gui.h"
#include "company_gui.h"
#include "gamelog.h"
#include "table/strings.h"
#include "table/sprites.h"
/**
* The 'amount' to cheat with.
* This variable is semantically a constant value, but because the cheat
* code requires to be able to write to the variable it is not constified.
*/
static int32 _money_cheat_amount = 10000000;
static int32 ClickMoneyCheat(int32 p1, int32 p2)
{
DoCommandP(0, (uint32)(p2 * _money_cheat_amount), 0, CMD_MONEY_CHEAT);
return _money_cheat_amount;
}
/**
* @param p1 company to set to
* @param p2 is -1 or +1 (down/up)
*/
static int32 ClickChangeCompanyCheat(int32 p1, int32 p2)
{
while ((uint)p1 < GetCompanyPoolSize()) {
if (IsValidCompanyID((CompanyID)p1)) {
SetLocalCompany((CompanyID)p1);
return _local_company;
}
p1 += p2;
}
return _local_company;
}
/**
* @param p1 new value
* @param p2 unused
*/
static int32 ClickSetProdCheat(int32 p1, int32 p2)
{
InvalidateWindowClasses(WC_INDUSTRY_VIEW);
return p1;
}
/**
* @param p1 new climate
* @param p2 unused
*/
static int32 ClickChangeClimateCheat(int32 p1, int32 p2)
{
if (p1 == -1) p1 = 3;
if (p1 == 4) p1 = 0;
_settings_game.game_creation.landscape = p1;
GamelogStartAction(GLAT_CHEAT);
GamelogTestMode();
ReloadNewGRFData();
GamelogStopAction();
return _settings_game.game_creation.landscape;
}
extern void EnginesMonthlyLoop();
/**
* @param p1 unused
* @param p2 1 (increase) or -1 (decrease)
*/
static int32 ClickChangeDateCheat(int32 p1, int32 p2)
{
YearMonthDay ymd;
ConvertDateToYMD(_date, &ymd);
if ((ymd.year == MIN_YEAR && p2 == -1) || (ymd.year == MAX_YEAR && p2 == 1)) return _cur_year;
SetDate(ConvertYMDToDate(_cur_year + p2, ymd.month, ymd.day));
EnginesMonthlyLoop();
SetWindowDirty(FindWindowById(WC_STATUS_BAR, 0));
ResetSignalVariant();
return _cur_year;
}
typedef int32 CheckButtonClick(int32, int32);
struct CheatEntry {
VarType type; ///< type of selector
StringID str; ///< string with descriptive text
void *variable; ///< pointer to the variable
bool *been_used; ///< has this cheat been used before?
CheckButtonClick *proc;///< procedure
};
static const CheatEntry _cheats_ui[] = {
{SLE_INT32, STR_CHEAT_MONEY, &_money_cheat_amount, &_cheats.money.been_used, &ClickMoneyCheat },
{SLE_UINT8, STR_CHEAT_CHANGE_COMPANY, &_local_company, &_cheats.switch_company.been_used, &ClickChangeCompanyCheat },
{SLE_BOOL, STR_CHEAT_EXTRA_DYNAMITE, &_cheats.magic_bulldozer.value, &_cheats.magic_bulldozer.been_used, NULL },
{SLE_BOOL, STR_CHEAT_CROSSINGTUNNELS, &_cheats.crossing_tunnels.value, &_cheats.crossing_tunnels.been_used, NULL },
{SLE_BOOL, STR_CHEAT_BUILD_IN_PAUSE, &_cheats.build_in_pause.value, &_cheats.build_in_pause.been_used, NULL },
{SLE_BOOL, STR_CHEAT_NO_JETCRASH, &_cheats.no_jetcrash.value, &_cheats.no_jetcrash.been_used, NULL },
{SLE_BOOL, STR_CHEAT_SETUP_PROD, &_cheats.setup_prod.value, &_cheats.setup_prod.been_used, &ClickSetProdCheat },
{SLE_UINT8, STR_CHEAT_SWITCH_CLIMATE, &_settings_game.game_creation.landscape, &_cheats.switch_climate.been_used, &ClickChangeClimateCheat },
{SLE_INT32, STR_CHEAT_CHANGE_DATE, &_cur_year, &_cheats.change_date.been_used, &ClickChangeDateCheat },
};
static const Widget _cheat_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 399, 0, 13, STR_CHEATS, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 399, 14, 169, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 399, 14, 169, 0x0, STR_CHEATS_TIP},
{ WIDGETS_END},
};
struct CheatWindow : Window {
int clicked;
CheatWindow(const WindowDesc *desc) : Window(desc)
{
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
DrawStringMultiCenter(200, 25, STR_CHEATS_WARNING, width - 50);
for (int i = 0, x = 0, y = 45; i != lengthof(_cheats_ui); i++) {
const CheatEntry *ce = &_cheats_ui[i];
DrawSprite((*ce->been_used) ? SPR_BOX_CHECKED : SPR_BOX_EMPTY, PAL_NONE, x + 5, y + 2);
switch (ce->type) {
case SLE_BOOL: {
bool on = (*(bool*)ce->variable);
DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, on ? COLOUR_GREEN : COLOUR_RED, on ? FR_LOWERED : FR_NONE);
SetDParam(0, on ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF);
} break;
default: {
int32 val = (int32)ReadValue(ce->variable, ce->type);
char buf[512];
/* Draw [<][>] boxes for settings of an integer-type */
DrawArrowButtons(x + 20, y, COLOUR_YELLOW, clicked - (i * 2), true, true);
switch (ce->str) {
/* Display date for change date cheat */
case STR_CHEAT_CHANGE_DATE: SetDParam(0, _date); break;
/* Draw coloured flag for change company cheat */
case STR_CHEAT_CHANGE_COMPANY:
SetDParam(0, val + 1);
GetString(buf, STR_CHEAT_CHANGE_COMPANY, lastof(buf));
DrawCompanyIcon(_local_company, 60 + GetStringBoundingBox(buf).width, y + 2);
break;
/* Set correct string for switch climate cheat */
case STR_CHEAT_SWITCH_CLIMATE: val += STR_TEMPERATE_LANDSCAPE;
/* Fallthrough */
default: SetDParam(0, val);
}
} break;
}
DrawString(50, y + 1, ce->str, TC_FROMSTRING);
y += 12;
}
}
virtual void OnClick(Point pt, int widget)
{
uint btn = (pt.y - 46) / 12;
uint x = pt.x;
/* Not clicking a button? */
if (!IsInsideMM(x, 20, 40) || btn >= lengthof(_cheats_ui)) return;
const CheatEntry *ce = &_cheats_ui[btn];
int value = (int32)ReadValue(ce->variable, ce->type);
int oldvalue = value;
*ce->been_used = true;
switch (ce->type) {
case SLE_BOOL:
value ^= 1;
if (ce->proc != NULL) ce->proc(value, 0);
break;
default:
/* Take whatever the function returns */
value = ce->proc(value + ((x >= 30) ? 1 : -1), (x >= 30) ? 1 : -1);
/* The first cheat (money), doesn't return a different value. */
if (value != oldvalue || btn == 0) this->clicked = btn * 2 + 1 + ((x >= 30) ? 1 : 0);
break;
}
if (value != oldvalue) WriteValue(ce->variable, ce->type, (int64)value);
this->flags4 |= WF_TIMEOUT_BEGIN;
SetDirty();
}
virtual void OnTimeout()
{
this->clicked = 0;
this->SetDirty();
}
};
static const WindowDesc _cheats_desc(
240, 22, 400, 170, 400, 170,
WC_CHEATS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_cheat_widgets
);
void ShowCheatWindow()
{
DeleteWindowById(WC_CHEATS, 0);
new CheatWindow(&_cheats_desc);
}
| 7,372
|
C++
|
.cpp
| 200
| 34.025
| 145
| 0.645465
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,053
|
depot.cpp
|
EnergeticBark_OpenTTD-3DS/src/depot.cpp
|
/* $Id$ */
/** @file depot.cpp Handling of depots. */
#include "stdafx.h"
#include "depot_base.h"
#include "order_func.h"
#include "window_func.h"
#include "oldpool_func.h"
#include "core/bitmath_func.hpp"
#include "tile_map.h"
#include "water_map.h"
DEFINE_OLD_POOL_GENERIC(Depot, Depot)
/**
* Gets a depot from a tile
*
* @return Returns the depot if the tile had a depot, else it returns NULL
*/
Depot *GetDepotByTile(TileIndex tile)
{
/* A ship depot is multiple tiles. The north most tile is
* always the ->xy tile, so make sure we always look for
* the nothern tile and not the southern one. */
if (IsShipDepotTile(tile)) {
tile = min(tile, GetOtherShipDepotTile(tile));
}
Depot *depot;
FOR_ALL_DEPOTS(depot) {
if (depot->xy == tile) return depot;
}
return NULL;
}
/**
* Clean up a depot
*/
Depot::~Depot()
{
if (CleaningPool()) return;
/* Clear the depot from all order-lists */
RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, this->index);
/* Delete the depot-window */
DeleteWindowById(WC_VEHICLE_DEPOT, this->xy);
this->xy = INVALID_TILE;
}
void InitializeDepots()
{
_Depot_pool.CleanPool();
_Depot_pool.AddBlockToPool();
}
| 1,168
|
C++
|
.cpp
| 47
| 23
| 74
| 0.717117
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,055
|
town_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/town_gui.cpp
|
/* $Id$ */
/** @file town_gui.cpp GUI for towns. */
#include "stdafx.h"
#include "openttd.h"
#include "town.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "company_func.h"
#include "company_base.h"
#include "company_gui.h"
#include "network/network.h"
#include "variables.h"
#include "strings_func.h"
#include "sound_func.h"
#include "economy_func.h"
#include "tilehighlight_func.h"
#include "sortlist_type.h"
#include "road_cmd.h"
#include "landscape_type.h"
#include "landscape.h"
#include "cargotype.h"
#include "tile_map.h"
#include "table/sprites.h"
#include "table/strings.h"
typedef GUIList<const Town*> GUITownList;
static const Widget _town_authority_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // TWA_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 11, 316, 0, 13, STR_2022_LOCAL_AUTHORITY, STR_018C_WINDOW_TITLE_DRAG_THIS}, // TWA_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 316, 14, 105, 0x0, STR_NULL}, // TWA_RATING_INFO
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 304, 106, 157, 0x0, STR_2043_LIST_OF_THINGS_TO_DO_AT}, // TWA_COMMAND_LIST
{ WWT_SCROLLBAR, RESIZE_NONE, COLOUR_BROWN, 305, 316, 106, 157, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // TWA_SCROLLBAR
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 316, 158, 209, 0x0, STR_NULL}, // TWA_ACTION_INFO
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_BROWN, 0, 316, 210, 221, STR_2042_DO_IT, STR_2044_CARRY_OUT_THE_HIGHLIGHTED}, // TWA_EXECUTE
{ WIDGETS_END},
};
extern const byte _town_action_costs[8];
struct TownAuthorityWindow : Window {
private:
Town *town;
int sel_index;
enum TownAuthorityWidget {
TWA_CLOSEBOX = 0,
TWA_CAPTION,
TWA_RATING_INFO,
TWA_COMMAND_LIST,
TWA_SCROLLBAR,
TWA_ACTION_INFO,
TWA_EXECUTE,
};
/**
* Get the position of the Nth set bit.
*
* If there is no Nth bit set return -1
*
* @param bits The value to search in
* @param n The Nth set bit from which we want to know the position
* @return The position of the Nth set bit
*/
static int GetNthSetBit(uint32 bits, int n)
{
if (n >= 0) {
uint i;
FOR_EACH_SET_BIT(i, bits) {
n--;
if (n < 0) return i;
}
}
return -1;
}
public:
TownAuthorityWindow(const WindowDesc *desc, WindowNumber window_number) :
Window(desc, window_number), sel_index(-1)
{
this->town = GetTown(this->window_number);
this->vscroll.cap = 5;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
int numact;
uint buttons = GetMaskOfTownActions(&numact, _local_company, this->town);
SetVScrollCount(this, numact + 1);
if (this->sel_index != -1 && !HasBit(buttons, this->sel_index)) {
this->sel_index = -1;
}
this->SetWidgetDisabledState(6, this->sel_index == -1);
SetDParam(0, this->window_number);
this->DrawWidgets();
int y = this->widget[TWA_RATING_INFO].top + 1;
DrawString(2, y, STR_2023_TRANSPORT_COMPANY_RATINGS, TC_FROMSTRING);
y += 10;
/* Draw list of companies */
const Company *c;
FOR_ALL_COMPANIES(c) {
if ((HasBit(this->town->have_ratings, c->index) || this->town->exclusivity == c->index)) {
DrawCompanyIcon(c->index, 2, y);
SetDParam(0, c->index);
SetDParam(1, c->index);
int r = this->town->ratings[c->index];
StringID str;
(str = STR_3035_APPALLING, r <= RATING_APPALLING) || // Apalling
(str++, r <= RATING_VERYPOOR) || // Very Poor
(str++, r <= RATING_POOR) || // Poor
(str++, r <= RATING_MEDIOCRE) || // Mediocore
(str++, r <= RATING_GOOD) || // Good
(str++, r <= RATING_VERYGOOD) || // Very Good
(str++, r <= RATING_EXCELLENT) || // Excellent
(str++, true); // Outstanding
SetDParam(2, str);
if (this->town->exclusivity == c->index) { // red icon for company with exclusive rights
DrawSprite(SPR_BLOT, PALETTE_TO_RED, 18, y);
}
DrawString(28, y, STR_2024, TC_FROMSTRING);
y += 10;
}
}
if (y > this->widget[TWA_RATING_INFO].bottom) {
/* If the company list is too big to fit, mark ourself dirty and draw again. */
ResizeWindowForWidget(this, TWA_RATING_INFO, 0, y - this->widget[TWA_RATING_INFO].bottom);
this->SetDirty();
return;
}
y = this->widget[TWA_COMMAND_LIST].top + 1;
int pos = this->vscroll.pos;
if (--pos < 0) {
DrawString(2, y, STR_2045_ACTIONS_AVAILABLE, TC_FROMSTRING);
y += 10;
}
for (int i = 0; buttons; i++, buttons >>= 1) {
if (pos <= -5) break; ///< Draw only the 5 fitting lines
if ((buttons & 1) && --pos < 0) {
DrawString(3, y, STR_2046_SMALL_ADVERTISING_CAMPAIGN + i, TC_ORANGE);
y += 10;
}
}
if (this->sel_index != -1) {
SetDParam(1, (_price.build_industry >> 8) * _town_action_costs[this->sel_index]);
SetDParam(0, STR_2046_SMALL_ADVERTISING_CAMPAIGN + this->sel_index);
DrawStringMultiLine(2, this->widget[TWA_ACTION_INFO].top + 1, STR_204D_INITIATE_A_SMALL_LOCAL + this->sel_index, 313);
}
}
virtual void OnDoubleClick(Point pt, int widget) { HandleClick(pt, widget, true); }
virtual void OnClick(Point pt, int widget) { HandleClick(pt, widget, false); }
void HandleClick(Point pt, int widget, bool double_click)
{
switch (widget) {
case TWA_COMMAND_LIST: {
int y = (pt.y - this->widget[TWA_COMMAND_LIST].top - 1) / 10;
if (!IsInsideMM(y, 0, 5)) return;
y = GetNthSetBit(GetMaskOfTownActions(NULL, _local_company, this->town), y + this->vscroll.pos - 1);
if (y >= 0) {
this->sel_index = y;
this->SetDirty();
}
/* Fall through to clicking in case we are double-clicked */
if (!double_click || y < 0) break;
}
case TWA_EXECUTE:
DoCommandP(this->town->xy, this->window_number, this->sel_index, CMD_DO_TOWN_ACTION | CMD_MSG(STR_00B4_CAN_T_DO_THIS));
break;
}
}
virtual void OnHundredthTick()
{
this->SetDirty();
}
};
static const WindowDesc _town_authority_desc(
WDP_AUTO, WDP_AUTO, 317, 222, 317, 222,
WC_TOWN_AUTHORITY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_town_authority_widgets
);
static void ShowTownAuthorityWindow(uint town)
{
AllocateWindowDescFront<TownAuthorityWindow>(&_town_authority_desc, town);
}
struct TownViewWindow : Window {
private:
Town *town;
enum TownViewWidget {
TVW_CAPTION = 1,
TVW_STICKY,
TVW_VIEWPORTPANEL,
TVW_INFOPANEL = 5,
TVW_CENTERVIEW,
TVW_SHOWAUTORITY,
TVW_CHANGENAME,
TVW_EXPAND,
TVW_DELETE,
};
public:
enum {
TVW_HEIGHT_NORMAL = 150,
};
TownViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->town = GetTown(this->window_number);
bool ingame = _game_mode != GM_EDITOR;
this->flags4 |= WF_DISABLE_VP_SCROLL;
InitializeWindowViewport(this, 3, 17, 254, 86, this->town->xy, ZOOM_LVL_TOWN);
if (this->town->larger_town) this->widget[TVW_CAPTION].data = STR_CITY;
this->SetWidgetHiddenState(TVW_DELETE, ingame); // hide delete button on game mode
this->SetWidgetHiddenState(TVW_EXPAND, ingame); // hide expand button on game mode
this->SetWidgetHiddenState(TVW_SHOWAUTORITY, !ingame); // hide autority button on editor mode
if (ingame) {
/* resize caption bar */
this->widget[TVW_CAPTION].right = this->widget[TVW_STICKY].left -1;
/* move the rename from top on scenario to bottom in game */
this->widget[TVW_CHANGENAME].top = this->widget[TVW_EXPAND].top;
this->widget[TVW_CHANGENAME].bottom = this->widget[TVW_EXPAND].bottom;
this->widget[TVW_CHANGENAME].right = this->widget[TVW_STICKY].right;
}
this->ResizeWindowAsNeeded();
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
/* disable renaming town in network games if you are not the server */
this->SetWidgetDisabledState(TVW_CHANGENAME, _networking && !_network_server);
SetDParam(0, this->town->index);
this->DrawWidgets();
uint y = 107;
SetDParam(0, this->town->population);
SetDParam(1, this->town->num_houses);
DrawString(2, y, STR_2006_POPULATION, TC_FROMSTRING);
SetDParam(0, this->town->act_pass);
SetDParam(1, this->town->max_pass);
DrawString(2, y += 10, STR_200D_PASSENGERS_LAST_MONTH_MAX, TC_FROMSTRING);
SetDParam(0, this->town->act_mail);
SetDParam(1, this->town->max_mail);
DrawString(2, y += 10, STR_200E_MAIL_LAST_MONTH_MAX, TC_FROMSTRING);
uint cargo_needed_for_growth = 0;
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC:
if (TilePixelHeight(this->town->xy) >= LowestSnowLine()) cargo_needed_for_growth = 1;
break;
case LT_TROPIC:
if (GetTropicZone(this->town->xy) == TROPICZONE_DESERT) cargo_needed_for_growth = 2;
break;
default: break;
}
if (cargo_needed_for_growth > 0) {
DrawString(2, y += 10, STR_CARGO_FOR_TOWNGROWTH, TC_FROMSTRING);
CargoID first_food_cargo = CT_INVALID;
StringID food_name = STR_001E_FOOD;
CargoID first_water_cargo = CT_INVALID;
StringID water_name = STR_0021_WATER;
for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
const CargoSpec *cs = GetCargo(cid);
if (first_food_cargo == CT_INVALID && cs->town_effect == TE_FOOD) {
first_food_cargo = cid;
food_name = cs->name;
}
if (first_water_cargo == CT_INVALID && cs->town_effect == TE_WATER) {
first_water_cargo = cid;
water_name = cs->name;
}
}
if (first_food_cargo != CT_INVALID && this->town->act_food > 0) {
SetDParam(0, first_food_cargo);
SetDParam(1, this->town->act_food);
DrawString(2, y += 10, STR_CARGO_FOR_TOWNGROWTH_LAST_MONTH, TC_FROMSTRING);
} else {
SetDParam(0, food_name);
DrawString(2, y += 10, STR_CARGO_FOR_TOWNGROWTH_REQUIRED, TC_FROMSTRING);
}
if (cargo_needed_for_growth > 1) {
if (first_water_cargo != CT_INVALID && this->town->act_water > 0) {
SetDParam(0, first_water_cargo);
SetDParam(1, this->town->act_water);
DrawString(2, y += 10, STR_CARGO_FOR_TOWNGROWTH_LAST_MONTH, TC_FROMSTRING);
} else {
SetDParam(0, water_name);
DrawString(2, y += 10, STR_CARGO_FOR_TOWNGROWTH_REQUIRED, TC_FROMSTRING);
}
}
}
this->DrawViewport();
/* only show the town noise, if the noise option is activated. */
if (_settings_game.economy.station_noise_level) {
SetDParam(0, this->town->noise_reached);
SetDParam(1, this->town->MaxTownNoise());
DrawString(2, y += 10, STR_NOISE_IN_TOWN, TC_FROMSTRING);
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case TVW_CENTERVIEW: // scroll to location
if (_ctrl_pressed) {
ShowExtraViewPortWindow(this->town->xy);
} else {
ScrollMainWindowToTile(this->town->xy);
}
break;
case TVW_SHOWAUTORITY: // town authority
ShowTownAuthorityWindow(this->window_number);
break;
case TVW_CHANGENAME: // rename
SetDParam(0, this->window_number);
ShowQueryString(STR_TOWN, STR_2007_RENAME_TOWN, MAX_LENGTH_TOWN_NAME_BYTES, MAX_LENGTH_TOWN_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
break;
case TVW_EXPAND: // expand town - only available on Scenario editor
ExpandTown(this->town);
break;
case TVW_DELETE: // delete town - only available on Scenario editor
delete this->town;
break;
}
}
void ResizeWindowAsNeeded()
{
int aimed_height = TVW_HEIGHT_NORMAL;
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC:
if (TilePixelHeight(this->town->xy) >= LowestSnowLine()) aimed_height += 20;
break;
case LT_TROPIC:
if (GetTropicZone(this->town->xy) == TROPICZONE_DESERT) aimed_height += 30;
break;
default: break;
}
if (_settings_game.economy.station_noise_level) aimed_height += 10;
if (this->height != aimed_height) ResizeWindowForWidget(this, TVW_INFOPANEL, 0, aimed_height - this->height);
}
virtual void OnInvalidateData(int data = 0)
{
/* Called when setting station noise have changed, in order to resize the window */
this->SetDirty(); // refresh display for current size. This will allow to avoid glitches when downgrading
this->ResizeWindowAsNeeded();
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
DoCommandP(0, this->window_number, 0, CMD_RENAME_TOWN | CMD_MSG(STR_2008_CAN_T_RENAME_TOWN), NULL, str);
}
};
static const Widget _town_view_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 11, 172, 0, 13, STR_2005, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_BROWN, 248, 259, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 259, 14, 105, 0x0, STR_NULL},
{ WWT_INSET, RESIZE_NONE, COLOUR_BROWN, 2, 257, 16, 103, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 259, 106, 137, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_BROWN, 0, 85, 138, 149, STR_00E4_LOCATION, STR_200B_CENTER_THE_MAIN_VIEW_ON},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_BROWN, 86, 171, 138, 149, STR_2020_LOCAL_AUTHORITY, STR_2021_SHOW_INFORMATION_ON_LOCAL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_BROWN, 172, 247, 0, 13, STR_0130_RENAME, STR_200C_CHANGE_TOWN_NAME},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_BROWN, 86, 171, 138, 149, STR_023C_EXPAND, STR_023B_INCREASE_SIZE_OF_TOWN},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_BROWN, 172, 259, 138, 149, STR_0290_DELETE, STR_0291_DELETE_THIS_TOWN_COMPLETELY},
{ WIDGETS_END},
};
static const WindowDesc _town_view_desc(
WDP_AUTO, WDP_AUTO, 260, TownViewWindow::TVW_HEIGHT_NORMAL, 260, TownViewWindow::TVW_HEIGHT_NORMAL,
WC_TOWN_VIEW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
_town_view_widgets
);
void ShowTownViewWindow(TownID town)
{
AllocateWindowDescFront<TownViewWindow>(&_town_view_desc, town);
}
static const Widget _town_directory_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 11, 195, 0, 13, STR_2000_TOWNS, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_BROWN, 196, 207, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_BROWN, 0, 98, 14, 25, STR_SORT_BY_NAME, STR_SORT_ORDER_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_BROWN, 99, 195, 14, 25, STR_SORT_BY_POPULATION, STR_SORT_ORDER_TIP},
{ WWT_PANEL, RESIZE_BOTTOM, COLOUR_BROWN, 0, 195, 26, 189, 0x0, STR_200A_TOWN_NAMES_CLICK_ON_NAME},
{ WWT_SCROLLBAR, RESIZE_BOTTOM, COLOUR_BROWN, 196, 207, 14, 189, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_PANEL, RESIZE_TB, COLOUR_BROWN, 0, 195, 190, 201, 0x0, STR_NULL},
{ WWT_RESIZEBOX, RESIZE_TB, COLOUR_BROWN, 196, 207, 190, 201, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
struct TownDirectoryWindow : public Window {
private:
enum TownDirectoryWidget {
TDW_SORTNAME = 3,
TDW_SORTPOPULATION,
TDW_CENTERTOWN,
};
/* Runtime saved values */
static Listing last_sorting;
static const Town *last_town;
/* Constants for sorting towns */
static GUITownList::SortFunction * const sorter_funcs[];
GUITownList towns;
void BuildTownList()
{
if (!this->towns.NeedRebuild()) return;
this->towns.Clear();
const Town *t;
FOR_ALL_TOWNS(t) {
*this->towns.Append() = t;
}
this->towns.Compact();
this->towns.RebuildDone();
}
void SortTownList()
{
last_town = NULL;
this->towns.Sort();
}
/** Sort by town name */
static int CDECL TownNameSorter(const Town * const *a, const Town * const *b)
{
static char buf_cache[64];
const Town *ta = *a;
const Town *tb = *b;
char buf[64];
SetDParam(0, ta->index);
GetString(buf, STR_TOWN, lastof(buf));
/* If 'b' is the same town as in the last round, use the cached value
* We do this to speed stuff up ('b' is called with the same value a lot of
* times after eachother) */
if (tb != last_town) {
last_town = tb;
SetDParam(0, tb->index);
GetString(buf_cache, STR_TOWN, lastof(buf_cache));
}
return strcmp(buf, buf_cache);
}
/** Sort by population */
static int CDECL TownPopulationSorter(const Town * const *a, const Town * const *b)
{
return (*a)->population - (*b)->population;
}
public:
TownDirectoryWindow(const WindowDesc *desc) : Window(desc, 0)
{
this->vscroll.cap = 16;
this->resize.step_height = 10;
this->resize.height = this->height - 10 * 6; // minimum of 10 items in the list, each item 10 high
this->towns.SetListing(this->last_sorting);
this->towns.SetSortFuncs(this->sorter_funcs);
this->towns.ForceRebuild();
this->FindWindowPlacementAndResize(desc);
}
~TownDirectoryWindow()
{
this->last_sorting = this->towns.GetListing();
}
virtual void OnPaint()
{
this->BuildTownList();
this->SortTownList();
SetVScrollCount(this, this->towns.Length());
this->DrawWidgets();
this->DrawSortButtonState(this->towns.SortType() == 0 ? TDW_SORTNAME : TDW_SORTPOPULATION, this->towns.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
{
int n = 0;
uint16 i = this->vscroll.pos;
int y = 28;
while (i < this->towns.Length()) {
const Town *t = this->towns[i];
assert(t->xy != INVALID_TILE);
SetDParam(0, t->index);
SetDParam(1, t->population);
DrawString(2, y, STR_2057, TC_FROMSTRING);
y += 10;
i++;
if (++n == this->vscroll.cap) break; // max number of towns in 1 window
}
SetDParam(0, GetWorldPopulation());
DrawString(3, this->height - 12 + 2, STR_TOWN_POPULATION, TC_FROMSTRING);
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case TDW_SORTNAME: // Sort by Name ascending/descending
if (this->towns.SortType() == 0) {
this->towns.ToggleSortOrder();
} else {
this->towns.SetSortType(0);
}
this->SetDirty();
break;
case TDW_SORTPOPULATION: // Sort by Population ascending/descending
if (this->towns.SortType() == 1) {
this->towns.ToggleSortOrder();
} else {
this->towns.SetSortType(1);
}
this->SetDirty();
break;
case TDW_CENTERTOWN: { // Click on Town Matrix
uint16 id_v = (pt.y - 28) / 10;
if (id_v >= this->vscroll.cap) return; // click out of bounds
id_v += this->vscroll.pos;
if (id_v >= this->towns.Length()) return; // click out of town bounds
const Town *t = this->towns[id_v];
assert(t->xy != INVALID_TILE);
if (_ctrl_pressed) {
ShowExtraViewPortWindow(t->xy);
} else {
ScrollMainWindowToTile(t->xy);
}
break;
}
}
}
virtual void OnHundredthTick()
{
this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / 10;
}
virtual void OnInvalidateData(int data)
{
if (data == 0) {
this->towns.ForceRebuild();
} else {
this->towns.ForceResort();
}
}
};
Listing TownDirectoryWindow::last_sorting = {false, 0};
const Town *TownDirectoryWindow::last_town = NULL;
/* Available town directory sorting functions */
GUITownList::SortFunction * const TownDirectoryWindow::sorter_funcs[] = {
&TownNameSorter,
&TownPopulationSorter,
};
static const WindowDesc _town_directory_desc(
WDP_AUTO, WDP_AUTO, 208, 202, 208, 202,
WC_TOWN_DIRECTORY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_town_directory_widgets
);
void ShowTownDirectory()
{
if (BringWindowToFrontById(WC_TOWN_DIRECTORY, 0)) return;
new TownDirectoryWindow(&_town_directory_desc);
}
void CcBuildTown(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_1F_SPLAT, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
}
}
static const Widget _found_town_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 147, 0, 13, STR_0233_TOWN_GENERATION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 148, 159, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 159, 14, 161, 0x0, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 157, 16, 27, STR_0234_NEW_TOWN, STR_0235_CONSTRUCT_NEW_TOWN},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 157, 29, 40, STR_023D_RANDOM_TOWN, STR_023E_BUILD_TOWN_IN_RANDOM_LOCATION},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 157, 42, 53, STR_MANY_RANDOM_TOWNS, STR_RANDOM_TOWNS_TIP},
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 54, 67, STR_02A5_TOWN_SIZE, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 79, 68, 79, STR_02A1_SMALL, STR_02A4_SELECT_TOWN_SIZE},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 80, 157, 68, 79, STR_02A2_MEDIUM, STR_02A4_SELECT_TOWN_SIZE},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 79, 81, 92, STR_02A3_LARGE, STR_02A4_SELECT_TOWN_SIZE},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 80, 157, 81, 92, STR_SELECT_TOWN_SIZE_RANDOM, STR_02A4_SELECT_TOWN_SIZE},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 157, 96, 107, STR_FOUND_TOWN_CITY, STR_FOUND_TOWN_CITY_TOOLTIP},
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 108, 121, STR_TOWN_ROAD_LAYOUT, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 79, 122, 133, STR_SELECT_LAYOUT_ORIGINAL, STR_SELECT_TOWN_ROAD_LAYOUT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 80, 157, 122, 133, STR_SELECT_LAYOUT_BETTER_ROADS, STR_SELECT_TOWN_ROAD_LAYOUT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 79, 135, 146, STR_SELECT_LAYOUT_2X2_GRID, STR_SELECT_TOWN_ROAD_LAYOUT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 80, 157, 135, 146, STR_SELECT_LAYOUT_3X3_GRID, STR_SELECT_TOWN_ROAD_LAYOUT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 157, 148, 159, STR_SELECT_LAYOUT_RANDOM, STR_SELECT_TOWN_ROAD_LAYOUT},
{ WIDGETS_END},
};
struct FoundTownWindow : Window
{
private:
enum TownScenarioEditorWidget {
TSEW_NEWTOWN = 4,
TSEW_RANDOMTOWN,
TSEW_MANYRANDOMTOWNS,
TSEW_TOWNSIZE,
TSEW_SIZE_SMALL,
TSEW_SIZE_MEDIUM,
TSEW_SIZE_LARGE,
TSEW_SIZE_RANDOM,
TSEW_CITY,
TSEW_TOWNLAYOUT,
TSEW_LAYOUT_ORIGINAL,
TSEW_LAYOUT_BETTER,
TSEW_LAYOUT_GRID2,
TSEW_LAYOUT_GRID3,
TSEW_LAYOUT_RANDOM,
};
static TownSize town_size;
static bool city;
static TownLayout town_layout;
public:
FoundTownWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->FindWindowPlacementAndResize(desc);
town_layout = _settings_game.economy.town_layout;
city = false;
this->UpdateButtons();
}
void UpdateButtons()
{
for (int i = TSEW_SIZE_SMALL; i <= TSEW_SIZE_RANDOM; i++) {
this->SetWidgetLoweredState(i, i == TSEW_SIZE_SMALL + town_size);
}
this->SetWidgetLoweredState(TSEW_CITY, city);
for (int i = TSEW_LAYOUT_ORIGINAL; i <= TSEW_LAYOUT_RANDOM; i++) {
this->SetWidgetLoweredState(i, i == TSEW_LAYOUT_ORIGINAL + town_layout);
}
this->SetDirty();
}
virtual void OnPaint()
{
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case TSEW_NEWTOWN:
HandlePlacePushButton(this, TSEW_NEWTOWN, SPR_CURSOR_TOWN, VHM_RECT, PlaceProc_Town);
break;
case TSEW_RANDOMTOWN: {
this->HandleButtonClick(TSEW_RANDOMTOWN);
_generating_world = true;
UpdateNearestTownForRoadTiles(true);
const Town *t = CreateRandomTown(20, town_size, city, town_layout);
UpdateNearestTownForRoadTiles(false);
_generating_world = false;
if (t == NULL) {
ShowErrorMessage(STR_NO_SPACE_FOR_TOWN, STR_CANNOT_GENERATE_TOWN, 0, 0);
} else {
ScrollMainWindowToTile(t->xy);
}
} break;
case TSEW_MANYRANDOMTOWNS:
this->HandleButtonClick(TSEW_MANYRANDOMTOWNS);
_generating_world = true;
UpdateNearestTownForRoadTiles(true);
if (!GenerateTowns(town_layout)) {
ShowErrorMessage(STR_NO_SPACE_FOR_TOWN, STR_CANNOT_GENERATE_TOWN, 0, 0);
}
UpdateNearestTownForRoadTiles(false);
_generating_world = false;
break;
case TSEW_SIZE_SMALL: case TSEW_SIZE_MEDIUM: case TSEW_SIZE_LARGE: case TSEW_SIZE_RANDOM:
town_size = (TownSize)(widget - TSEW_SIZE_SMALL);
this->UpdateButtons();
break;
case TSEW_CITY:
city ^= true;
this->SetWidgetLoweredState(TSEW_CITY, city);
this->SetDirty();
break;
case TSEW_LAYOUT_ORIGINAL: case TSEW_LAYOUT_BETTER: case TSEW_LAYOUT_GRID2:
case TSEW_LAYOUT_GRID3: case TSEW_LAYOUT_RANDOM:
town_layout = (TownLayout)(widget - TSEW_LAYOUT_ORIGINAL);
this->UpdateButtons();
break;
}
}
virtual void OnTimeout()
{
this->RaiseWidget(TSEW_RANDOMTOWN);
this->RaiseWidget(TSEW_MANYRANDOMTOWNS);
this->SetDirty();
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_place_proc(tile);
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
this->UpdateButtons();
}
static void PlaceProc_Town(TileIndex tile)
{
uint32 townnameparts;
if (!GenerateTownName(&townnameparts)) {
ShowErrorMessage(STR_023A_TOO_MANY_TOWNS, STR_0236_CAN_T_BUILD_TOWN_HERE, 0, 0);
return;
}
DoCommandP(tile, town_size | city << 2 | town_layout << 3, townnameparts, CMD_BUILD_TOWN | CMD_MSG(STR_0236_CAN_T_BUILD_TOWN_HERE), CcBuildTown);
}
};
TownSize FoundTownWindow::town_size = TS_MEDIUM; // select medium-sized towns per default;
bool FoundTownWindow::city;
TownLayout FoundTownWindow::town_layout;
static const WindowDesc _found_town_desc(
WDP_AUTO, WDP_AUTO, 160, 162, 160, 162,
WC_FOUND_TOWN, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_found_town_widgets
);
void ShowBuildTownWindow()
{
if (_game_mode != GM_EDITOR && !IsValidCompanyID(_local_company)) return;
AllocateWindowDescFront<FoundTownWindow>(&_found_town_desc, 0);
}
| 27,279
|
C++
|
.cpp
| 700
| 35.777143
| 158
| 0.65505
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,057
|
dummy_land.cpp
|
EnergeticBark_OpenTTD-3DS/src/dummy_land.cpp
|
/* $Id$ */
/** @file dummy_land.cpp Handling of void (or dummy) tiles. */
#include "stdafx.h"
#include "tile_cmd.h"
#include "command_func.h"
#include "viewport_func.h"
#include "table/strings.h"
#include "table/sprites.h"
static void DrawTile_Dummy(TileInfo *ti)
{
DrawGroundSpriteAt(SPR_SHADOW_CELL, PAL_NONE, ti->x, ti->y, ti->z);
}
static uint GetSlopeZ_Dummy(TileIndex tile, uint x, uint y)
{
return 0;
}
static Foundation GetFoundation_Dummy(TileIndex tile, Slope tileh)
{
return FOUNDATION_NONE;
}
static CommandCost ClearTile_Dummy(TileIndex tile, DoCommandFlag flags)
{
return_cmd_error(STR_0001_OFF_EDGE_OF_MAP);
}
static void GetAcceptedCargo_Dummy(TileIndex tile, AcceptedCargo ac)
{
/* not used */
}
static void GetTileDesc_Dummy(TileIndex tile, TileDesc *td)
{
td->str = STR_EMPTY;
td->owner[0] = OWNER_NONE;
}
static void AnimateTile_Dummy(TileIndex tile)
{
/* not used */
}
static void TileLoop_Dummy(TileIndex tile)
{
/* not used */
}
static bool ClickTile_Dummy(TileIndex tile)
{
/* not used */
return false;
}
static void ChangeTileOwner_Dummy(TileIndex tile, Owner old_owner, Owner new_owner)
{
/* not used */
}
static TrackStatus GetTileTrackStatus_Dummy(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
{
return 0;
}
static CommandCost TerraformTile_Dummy(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
{
return_cmd_error(STR_0001_OFF_EDGE_OF_MAP);
}
extern const TileTypeProcs _tile_type_dummy_procs = {
DrawTile_Dummy, // draw_tile_proc
GetSlopeZ_Dummy, // get_slope_z_proc
ClearTile_Dummy, // clear_tile_proc
GetAcceptedCargo_Dummy, // get_accepted_cargo_proc
GetTileDesc_Dummy, // get_tile_desc_proc
GetTileTrackStatus_Dummy, // get_tile_track_status_proc
ClickTile_Dummy, // click_tile_proc
AnimateTile_Dummy, // animate_tile_proc
TileLoop_Dummy, // tile_loop_clear
ChangeTileOwner_Dummy, // change_tile_owner_clear
NULL, // get_produced_cargo_proc
NULL, // vehicle_enter_tile_proc
GetFoundation_Dummy, // get_foundation_proc
TerraformTile_Dummy, // terraform_tile_proc
};
| 2,203
|
C++
|
.cpp
| 74
| 28.148649
| 114
| 0.723828
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,059
|
group_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/group_gui.cpp
|
/* $Id$ */
/** @file group_gui.cpp GUI for the group window. */
#include "stdafx.h"
#include "openttd.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "vehicle_gui.h"
#include "vehicle_gui_base.h"
#include "vehicle_base.h"
#include "group.h"
#include "strings_func.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "autoreplace_gui.h"
#include "gfx_func.h"
#include "company_func.h"
#include "widgets/dropdown_type.h"
#include "widgets/dropdown_func.h"
#include "tilehighlight_func.h"
#include "table/strings.h"
#include "table/sprites.h"
typedef GUIList<const Group*> GUIGroupList;
enum GroupListWidgets {
GRP_WIDGET_CLOSEBOX = 0,
GRP_WIDGET_CAPTION,
GRP_WIDGET_STICKY,
GRP_WIDGET_SORT_BY_ORDER,
GRP_WIDGET_SORT_BY_DROPDOWN,
GRP_WIDGET_EMPTY_TOP_RIGHT,
GRP_WIDGET_LIST_VEHICLE,
GRP_WIDGET_LIST_VEHICLE_SCROLLBAR,
GRP_WIDGET_EMPTY2,
GRP_WIDGET_AVAILABLE_VEHICLES,
GRP_WIDGET_MANAGE_VEHICLES_DROPDOWN,
GRP_WIDGET_STOP_ALL,
GRP_WIDGET_START_ALL,
GRP_WIDGET_EMPTY_BOTTOM_RIGHT,
GRP_WIDGET_RESIZE,
GRP_WIDGET_EMPTY_TOP_LEFT,
GRP_WIDGET_ALL_VEHICLES,
GRP_WIDGET_DEFAULT_VEHICLES,
GRP_WIDGET_LIST_GROUP,
GRP_WIDGET_LIST_GROUP_SCROLLBAR,
GRP_WIDGET_CREATE_GROUP,
GRP_WIDGET_DELETE_GROUP,
GRP_WIDGET_RENAME_GROUP,
GRP_WIDGET_EMPTY1,
GRP_WIDGET_REPLACE_PROTECTION,
};
enum GroupActionListFunction {
GALF_REPLACE,
GALF_SERVICE,
GALF_DEPOT,
GALF_ADD_SHARED,
GALF_REMOVE_ALL,
};
/**
* Update/redraw the group action dropdown
* @param w the window the dropdown belongs to
* @param gid the currently selected group in the window
*/
static void ShowGroupActionDropdown(Window *w, GroupID gid)
{
DropDownList *list = new DropDownList();
list->push_back(new DropDownListStringItem(STR_REPLACE_VEHICLES, GALF_REPLACE, false));
list->push_back(new DropDownListStringItem(STR_SEND_FOR_SERVICING, GALF_SERVICE, false));
list->push_back(new DropDownListStringItem(STR_SEND_TRAIN_TO_DEPOT, GALF_DEPOT, false));
if (IsValidGroupID(gid)) {
list->push_back(new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, GALF_ADD_SHARED, false));
list->push_back(new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, GALF_REMOVE_ALL, false));
}
ShowDropDownList(w, list, 0, GRP_WIDGET_MANAGE_VEHICLES_DROPDOWN);
}
static const Widget _group_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // GRP_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 447, 0, 13, 0x0, STR_018C_WINDOW_TITLE_DRAG_THIS}, // GRP_WIDGET_CAPTION
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 448, 459, 0, 13, 0x0, STR_STICKY_BUTTON}, // GRP_WIDGET_STICKY
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 200, 280, 14, 25, STR_SORT_BY, STR_SORT_ORDER_TIP}, // GRP_WIDGET_SORT_BY_ORDER
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_GREY, 281, 447, 14, 25, 0x0, STR_SORT_CRITERIA_TIP}, // GRP_WIDGET_SORT_BY_DROPDOWN
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 448, 459, 14, 25, 0x0, STR_NULL}, // GRP_WIDGET_EMPTY_TOP_RIGHT
{ WWT_MATRIX, RESIZE_RB, COLOUR_GREY, 200, 447, 26, 181, 0x701, STR_NULL}, // GRP_WIDGET_LIST_VEHICLE
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 448, 459, 26, 181, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // GRP_WIDGET_LIST_VEHICLE_SCROLLBAR
{ WWT_PANEL, RESIZE_TB, COLOUR_GREY, 188, 199, 169, 193, 0x0, STR_NULL}, // GRP_WIDGET_EMPTY2
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 200, 305, 182, 193, 0x0, STR_AVAILABLE_ENGINES_TIP}, // GRP_WIDGET_AVAILABLE_VEHICLES
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 306, 423, 182, 193, STR_MANAGE_LIST, STR_MANAGE_LIST_TIP}, // GRP_WIDGET_MANAGE_VEHICLES_DROPDOWN
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 424, 435, 182, 193, SPR_FLAG_VEH_STOPPED, STR_MASS_STOP_LIST_TIP}, // GRP_WIDGET_STOP_ALL
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 436, 447, 182, 193, SPR_FLAG_VEH_RUNNING, STR_MASS_START_LIST_TIP}, // GRP_WIDGET_START_ALL
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 448, 447, 182, 193, 0x0, STR_NULL}, // GRP_WIDGET_EMPTY_BOTTOM_RIGHT
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 448, 459, 182, 193, 0x0, STR_RESIZE_BUTTON}, // GRP_WIDGET_RESIZE
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 199, 14, 25, 0x0, STR_NULL}, // GRP_WIDGET_EMPTY_TOP_LEFT
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 199, 26, 38, 0x0, STR_NULL}, // GRP_WIDGET_ALL_VEHICLES
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 199, 39, 51, 0x0, STR_NULL}, // GRP_WIDGET_DEFAULT_VEHICLES
{ WWT_MATRIX, RESIZE_BOTTOM, COLOUR_GREY, 0, 187, 52, 168, 0x701, STR_GROUPS_CLICK_ON_GROUP_FOR_TIP}, // GRP_WIDGET_LIST_GROUP
{ WWT_SCROLL2BAR, RESIZE_BOTTOM, COLOUR_GREY, 188, 199, 52, 168, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // GRP_WIDGET_LIST_GROUP_SCROLLBAR
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 0, 23, 169, 193, 0x0, STR_GROUP_CREATE_TIP}, // GRP_WIDGET_CREATE_GROUP
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 24, 47, 169, 193, 0x0, STR_GROUP_DELETE_TIP}, // GRP_WIDGET_DELETE_GROUP
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 48, 71, 169, 193, 0x0, STR_GROUP_RENAME_TIP}, // GRP_WIDGET_RENAME_GROUP
{ WWT_PANEL, RESIZE_TB, COLOUR_GREY, 72, 163, 169, 193, 0x0, STR_NULL}, // GRP_WIDGET_EMPTY1
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 164, 187, 169, 193, 0x0, STR_GROUP_REPLACE_PROTECTION_TIP}, // GRP_WIDGET_REPLACE_PROTECTION
{ WIDGETS_END},
};
class VehicleGroupWindow : public BaseVehicleListWindow {
private:
GroupID group_sel;
VehicleID vehicle_sel;
GUIGroupList groups;
/**
* (Re)Build the group list.
*
* @param owner The owner of the window
*/
void BuildGroupList(Owner owner)
{
if (!this->groups.NeedRebuild()) return;
this->groups.Clear();
const Group *g;
FOR_ALL_GROUPS(g) {
if (g->owner == owner && g->vehicle_type == this->vehicle_type) {
*this->groups.Append() = g;
}
}
this->groups.Compact();
this->groups.RebuildDone();
}
/** Sort the groups by their name */
static int CDECL GroupNameSorter(const Group * const *a, const Group * const *b)
{
static const Group *last_group[2] = { NULL, NULL };
static char last_name[2][64] = { "", "" };
if (*a != last_group[0]) {
last_group[0] = *a;
SetDParam(0, (*a)->index);
GetString(last_name[0], STR_GROUP_NAME, lastof(last_name[0]));
}
if (*b != last_group[1]) {
last_group[1] = *b;
SetDParam(0, (*b)->index);
GetString(last_name[1], STR_GROUP_NAME, lastof(last_name[1]));
}
int r = strcmp(last_name[0], last_name[1]); // sort by name
if (r == 0) return (*a)->index - (*b)->index;
return r;
}
public:
VehicleGroupWindow(const WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
{
const Owner owner = (Owner)GB(this->window_number, 0, 8);
this->vehicle_type = (VehicleType)GB(this->window_number, 11, 5);
this->owner = owner;
this->resize.step_width = 1;
switch (this->vehicle_type) {
default: NOT_REACHED();
case VEH_TRAIN:
case VEH_ROAD:
this->vscroll2.cap = 9;
this->vscroll.cap = 6;
this->resize.step_height = PLY_WND_PRC__SIZE_OF_ROW_SMALL;
break;
case VEH_SHIP:
case VEH_AIRCRAFT:
this->vscroll2.cap = 9;
this->vscroll.cap = 4;
this->resize.step_height = PLY_WND_PRC__SIZE_OF_ROW_BIG;
break;
}
this->widget[GRP_WIDGET_LIST_GROUP].data = (this->vscroll2.cap << 8) + 1;
this->widget[GRP_WIDGET_LIST_VEHICLE].data = (this->vscroll.cap << 8) + 1;
switch (this->vehicle_type) {
default: NOT_REACHED();
case VEH_TRAIN: this->sorting = &_sorting.train; break;
case VEH_ROAD: this->sorting = &_sorting.roadveh; break;
case VEH_SHIP: this->sorting = &_sorting.ship; break;
case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
}
this->vehicles.SetListing(*this->sorting);
this->vehicles.ForceRebuild();
this->vehicles.NeedResort();
this->groups.ForceRebuild();
this->groups.NeedResort();
this->group_sel = ALL_GROUP;
this->vehicle_sel = INVALID_VEHICLE;
switch (this->vehicle_type) {
case VEH_TRAIN:
this->widget[GRP_WIDGET_LIST_VEHICLE].tooltips = STR_883D_TRAINS_CLICK_ON_TRAIN_FOR;
this->widget[GRP_WIDGET_AVAILABLE_VEHICLES].data = STR_AVAILABLE_TRAINS;
this->widget[GRP_WIDGET_CREATE_GROUP].data = SPR_GROUP_CREATE_TRAIN;
this->widget[GRP_WIDGET_RENAME_GROUP].data = SPR_GROUP_RENAME_TRAIN;
this->widget[GRP_WIDGET_DELETE_GROUP].data = SPR_GROUP_DELETE_TRAIN;
break;
case VEH_ROAD:
this->widget[GRP_WIDGET_LIST_VEHICLE].tooltips = STR_901A_ROAD_VEHICLES_CLICK_ON;
this->widget[GRP_WIDGET_AVAILABLE_VEHICLES].data = STR_AVAILABLE_ROAD_VEHICLES;
this->widget[GRP_WIDGET_CREATE_GROUP].data = SPR_GROUP_CREATE_ROADVEH;
this->widget[GRP_WIDGET_RENAME_GROUP].data = SPR_GROUP_RENAME_ROADVEH;
this->widget[GRP_WIDGET_DELETE_GROUP].data = SPR_GROUP_DELETE_ROADVEH;
break;
case VEH_SHIP:
this->widget[GRP_WIDGET_LIST_VEHICLE].tooltips = STR_9823_SHIPS_CLICK_ON_SHIP_FOR;
this->widget[GRP_WIDGET_AVAILABLE_VEHICLES].data = STR_AVAILABLE_SHIPS;
this->widget[GRP_WIDGET_CREATE_GROUP].data = SPR_GROUP_CREATE_SHIP;
this->widget[GRP_WIDGET_RENAME_GROUP].data = SPR_GROUP_RENAME_SHIP;
this->widget[GRP_WIDGET_DELETE_GROUP].data = SPR_GROUP_DELETE_SHIP;
break;
case VEH_AIRCRAFT:
this->widget[GRP_WIDGET_LIST_VEHICLE].tooltips = STR_A01F_AIRCRAFT_CLICK_ON_AIRCRAFT;
this->widget[GRP_WIDGET_AVAILABLE_VEHICLES].data = STR_AVAILABLE_AIRCRAFT;
this->widget[GRP_WIDGET_CREATE_GROUP].data = SPR_GROUP_CREATE_AIRCRAFT;
this->widget[GRP_WIDGET_RENAME_GROUP].data = SPR_GROUP_RENAME_AIRCRAFT;
this->widget[GRP_WIDGET_DELETE_GROUP].data = SPR_GROUP_DELETE_AIRCRAFT;
break;
default: NOT_REACHED();
}
this->FindWindowPlacementAndResize(desc);
if (this->vehicle_type == VEH_TRAIN) ResizeWindow(this, 65, 0);
}
~VehicleGroupWindow()
{
*this->sorting = this->vehicles.GetListing();
}
virtual void OnInvalidateData(int data)
{
if (data == 0) {
this->vehicles.ForceRebuild();
this->groups.ForceRebuild();
} else {
this->vehicles.ForceResort();
this->groups.ForceResort();
}
if (!(IsAllGroupID(this->group_sel) || IsDefaultGroupID(this->group_sel) || IsValidGroupID(this->group_sel))) {
this->group_sel = ALL_GROUP;
HideDropDownMenu(this);
}
this->SetDirty();
}
virtual void OnPaint()
{
const Owner owner = (Owner)GB(this->window_number, 0, 8);
int x = this->widget[GRP_WIDGET_LIST_VEHICLE].left + 2;
int y1 = PLY_WND_PRC__OFFSET_TOP_WIDGET + 2;
int max;
int i;
/* If we select the all vehicles, this->list will contain all vehicles of the owner
* else this->list will contain all vehicles which belong to the selected group */
this->BuildVehicleList(owner, this->group_sel, IsAllGroupID(this->group_sel) ? VLW_STANDARD : VLW_GROUP_LIST);
this->SortVehicleList();
this->BuildGroupList(owner);
this->groups.Sort(&GroupNameSorter);
SetVScroll2Count(this, this->groups.Length());
SetVScrollCount(this, this->vehicles.Length());
/* The drop down menu is out, *but* it may not be used, retract it. */
if (this->vehicles.Length() == 0 && this->IsWidgetLowered(GRP_WIDGET_MANAGE_VEHICLES_DROPDOWN)) {
this->RaiseWidget(GRP_WIDGET_MANAGE_VEHICLES_DROPDOWN);
HideDropDownMenu(this);
}
/* Disable all lists management button when the list is empty */
this->SetWidgetsDisabledState(this->vehicles.Length() == 0 || _local_company != owner,
GRP_WIDGET_STOP_ALL,
GRP_WIDGET_START_ALL,
GRP_WIDGET_MANAGE_VEHICLES_DROPDOWN,
WIDGET_LIST_END);
/* Disable the group specific function when we select the default group or all vehicles */
this->SetWidgetsDisabledState(IsDefaultGroupID(this->group_sel) || IsAllGroupID(this->group_sel) || _local_company != owner,
GRP_WIDGET_DELETE_GROUP,
GRP_WIDGET_RENAME_GROUP,
GRP_WIDGET_REPLACE_PROTECTION,
WIDGET_LIST_END);
/* Disable remaining buttons for non-local companies
* Needed while changing _local_company, eg. by cheats
* All procedures (eg. move vehicle to another group)
* verify, whether you are the owner of the vehicle,
* so it doesn't have to be disabled
*/
this->SetWidgetsDisabledState(_local_company != owner,
GRP_WIDGET_CREATE_GROUP,
GRP_WIDGET_AVAILABLE_VEHICLES,
WIDGET_LIST_END);
/* If selected_group == DEFAULT_GROUP || ALL_GROUP, draw the standard caption
We list all vehicles or ungrouped vehicles */
if (IsDefaultGroupID(this->group_sel) || IsAllGroupID(this->group_sel)) {
SetDParam(0, owner);
SetDParam(1, this->vehicles.Length());
switch (this->vehicle_type) {
case VEH_TRAIN:
this->widget[GRP_WIDGET_CAPTION].data = STR_881B_TRAINS;
this->widget[GRP_WIDGET_REPLACE_PROTECTION].data = SPR_GROUP_REPLACE_OFF_TRAIN;
break;
case VEH_ROAD:
this->widget[GRP_WIDGET_CAPTION].data = STR_9001_ROAD_VEHICLES;
this->widget[GRP_WIDGET_REPLACE_PROTECTION].data = SPR_GROUP_REPLACE_OFF_ROADVEH;
break;
case VEH_SHIP:
this->widget[GRP_WIDGET_CAPTION].data = STR_9805_SHIPS;
this->widget[GRP_WIDGET_REPLACE_PROTECTION].data = SPR_GROUP_REPLACE_OFF_SHIP;
break;
case VEH_AIRCRAFT:
this->widget[GRP_WIDGET_CAPTION].data = STR_A009_AIRCRAFT;
this->widget[GRP_WIDGET_REPLACE_PROTECTION].data = SPR_GROUP_REPLACE_OFF_AIRCRAFT;
break;
default: NOT_REACHED();
}
} else {
const Group *g = GetGroup(this->group_sel);
SetDParam(0, g->index);
SetDParam(1, g->num_vehicle);
switch (this->vehicle_type) {
case VEH_TRAIN:
this->widget[GRP_WIDGET_CAPTION].data = STR_GROUP_TRAINS_CAPTION;
this->widget[GRP_WIDGET_REPLACE_PROTECTION].data = (g->replace_protection) ? SPR_GROUP_REPLACE_ON_TRAIN : SPR_GROUP_REPLACE_OFF_TRAIN;
break;
case VEH_ROAD:
this->widget[GRP_WIDGET_CAPTION].data = STR_GROUP_ROADVEH_CAPTION;
this->widget[GRP_WIDGET_REPLACE_PROTECTION].data = (g->replace_protection) ? SPR_GROUP_REPLACE_ON_ROADVEH : SPR_GROUP_REPLACE_OFF_ROADVEH;
break;
case VEH_SHIP:
this->widget[GRP_WIDGET_CAPTION].data = STR_GROUP_SHIPS_CAPTION;
this->widget[GRP_WIDGET_REPLACE_PROTECTION].data = (g->replace_protection) ? SPR_GROUP_REPLACE_ON_SHIP : SPR_GROUP_REPLACE_OFF_SHIP;
break;
case VEH_AIRCRAFT:
this->widget[GRP_WIDGET_CAPTION].data = STR_GROUP_AIRCRAFTS_CAPTION;
this->widget[GRP_WIDGET_REPLACE_PROTECTION].data = (g->replace_protection) ? SPR_GROUP_REPLACE_ON_AIRCRAFT : SPR_GROUP_REPLACE_OFF_AIRCRAFT;
break;
default: NOT_REACHED();
}
}
/* Set text of sort by dropdown */
this->widget[GRP_WIDGET_SORT_BY_DROPDOWN].data = this->vehicle_sorter_names[this->vehicles.SortType()];
this->DrawWidgets();
/* Draw Matrix Group
* The selected group is drawn in white */
StringID str_all_veh, str_no_group_veh;
switch (this->vehicle_type) {
case VEH_TRAIN:
str_all_veh = STR_GROUP_ALL_TRAINS;
str_no_group_veh = STR_GROUP_DEFAULT_TRAINS;
break;
case VEH_ROAD:
str_all_veh = STR_GROUP_ALL_ROADS;
str_no_group_veh = STR_GROUP_DEFAULT_ROADS;
break;
case VEH_SHIP:
str_all_veh = STR_GROUP_ALL_SHIPS;
str_no_group_veh = STR_GROUP_DEFAULT_SHIPS;
break;
case VEH_AIRCRAFT:
str_all_veh = STR_GROUP_ALL_AIRCRAFTS;
str_no_group_veh = STR_GROUP_DEFAULT_AIRCRAFTS;
break;
default: NOT_REACHED();
}
DrawString(10, y1, str_all_veh, IsAllGroupID(this->group_sel) ? TC_WHITE : TC_BLACK);
y1 += 13;
DrawString(10, y1, str_no_group_veh, IsDefaultGroupID(this->group_sel) ? TC_WHITE : TC_BLACK);
max = min(this->vscroll2.pos + this->vscroll2.cap, this->groups.Length());
for (i = this->vscroll2.pos ; i < max ; ++i) {
const Group *g = this->groups[i];
assert(g->owner == owner);
y1 += PLY_WND_PRC__SIZE_OF_ROW_TINY;
/* draw the selected group in white, else we draw it in black */
SetDParam(0, g->index);
DrawString(10, y1, STR_GROUP_NAME, (this->group_sel == g->index) ? TC_WHITE : TC_BLACK);
/* draw the number of vehicles of the group */
SetDParam(0, g->num_vehicle);
DrawStringRightAligned(187, y1 + 1, STR_GROUP_TINY_NUM, (this->group_sel == g->index) ? TC_WHITE : TC_BLACK);
}
this->DrawSortButtonState(GRP_WIDGET_SORT_BY_ORDER, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
this->DrawVehicleListItems(x, this->vehicle_sel);
}
virtual void OnClick(Point pt, int widget)
{
switch(widget) {
case GRP_WIDGET_SORT_BY_ORDER: // Flip sorting method ascending/descending
this->vehicles.ToggleSortOrder();
this->SetDirty();
break;
case GRP_WIDGET_SORT_BY_DROPDOWN: // Select sorting criteria dropdown menu
ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), GRP_WIDGET_SORT_BY_DROPDOWN, 0, (this->vehicle_type == VEH_TRAIN || this->vehicle_type == VEH_ROAD) ? 0 : (1 << 10));
return;
case GRP_WIDGET_ALL_VEHICLES: // All vehicles button
if (!IsAllGroupID(this->group_sel)) {
this->group_sel = ALL_GROUP;
this->vehicles.ForceRebuild();
this->SetDirty();
}
break;
case GRP_WIDGET_DEFAULT_VEHICLES: // Ungrouped vehicles button
if (!IsDefaultGroupID(this->group_sel)) {
this->group_sel = DEFAULT_GROUP;
this->vehicles.ForceRebuild();
this->SetDirty();
}
break;
case GRP_WIDGET_LIST_GROUP: { // Matrix Group
uint16 id_g = (pt.y - PLY_WND_PRC__OFFSET_TOP_WIDGET - 26) / PLY_WND_PRC__SIZE_OF_ROW_TINY;
if (id_g >= this->vscroll2.cap) return;
id_g += this->vscroll2.pos;
if (id_g >= this->groups.Length()) return;
this->group_sel = this->groups[id_g]->index;;
this->vehicles.ForceRebuild();
this->SetDirty();
break;
}
case GRP_WIDGET_LIST_VEHICLE: { // Matrix Vehicle
uint32 id_v = (pt.y - PLY_WND_PRC__OFFSET_TOP_WIDGET) / (int)this->resize.step_height;
const Vehicle *v;
if (id_v >= this->vscroll.cap) return; // click out of bounds
id_v += this->vscroll.pos;
if (id_v >= this->vehicles.Length()) return; // click out of list bound
v = this->vehicles[id_v];
this->vehicle_sel = v->index;
if (v->IsValid()) {
SetObjectToPlaceWnd(v->GetImage(DIR_W), GetVehiclePalette(v), VHM_DRAG, this);
_cursor.vehchain = true;
}
this->SetDirty();
break;
}
case GRP_WIDGET_CREATE_GROUP: // Create a new group
DoCommandP(0, this->vehicle_type, 0, CMD_CREATE_GROUP | CMD_MSG(STR_GROUP_CAN_T_CREATE));
break;
case GRP_WIDGET_DELETE_GROUP: { // Delete the selected group
GroupID group = this->group_sel;
this->group_sel = ALL_GROUP;
DoCommandP(0, group, 0, CMD_DELETE_GROUP | CMD_MSG(STR_GROUP_CAN_T_DELETE));
break;
}
case GRP_WIDGET_RENAME_GROUP: { // Rename the selected roup
assert(IsValidGroupID(this->group_sel));
const Group *g = GetGroup(this->group_sel);
SetDParam(0, g->index);
ShowQueryString(STR_GROUP_NAME, STR_GROUP_RENAME_CAPTION, MAX_LENGTH_GROUP_NAME_BYTES, MAX_LENGTH_GROUP_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
} break;
case GRP_WIDGET_AVAILABLE_VEHICLES:
ShowBuildVehicleWindow(INVALID_TILE, this->vehicle_type);
break;
case GRP_WIDGET_MANAGE_VEHICLES_DROPDOWN:
ShowGroupActionDropdown(this, this->group_sel);
break;
case GRP_WIDGET_START_ALL:
case GRP_WIDGET_STOP_ALL: { // Start/stop all vehicles of the list
DoCommandP(0, this->group_sel, ((IsAllGroupID(this->group_sel) ? VLW_STANDARD : VLW_GROUP_LIST) & VLW_MASK)
| (1 << 6)
| (widget == GRP_WIDGET_START_ALL ? (1 << 5) : 0)
| this->vehicle_type, CMD_MASS_START_STOP);
break;
}
case GRP_WIDGET_REPLACE_PROTECTION:
if (IsValidGroupID(this->group_sel)) {
const Group *g = GetGroup(this->group_sel);
DoCommandP(0, this->group_sel, !g->replace_protection, CMD_SET_GROUP_REPLACE_PROTECTION);
}
break;
}
}
virtual void OnDragDrop(Point pt, int widget)
{
switch (widget) {
case GRP_WIDGET_ALL_VEHICLES: // All vehicles
case GRP_WIDGET_DEFAULT_VEHICLES: // Ungrouped vehicles
DoCommandP(0, DEFAULT_GROUP, this->vehicle_sel, CMD_ADD_VEHICLE_GROUP | CMD_MSG(STR_GROUP_CAN_T_ADD_VEHICLE));
this->vehicle_sel = INVALID_VEHICLE;
this->SetDirty();
break;
case GRP_WIDGET_LIST_GROUP: { // Maxtrix group
uint16 id_g = (pt.y - PLY_WND_PRC__OFFSET_TOP_WIDGET - 26) / PLY_WND_PRC__SIZE_OF_ROW_TINY;
const VehicleID vindex = this->vehicle_sel;
this->vehicle_sel = INVALID_VEHICLE;
this->SetDirty();
if (id_g >= this->vscroll2.cap) return;
id_g += this->vscroll2.pos;
if (id_g >= this->groups.Length()) return;
DoCommandP(0, this->groups[id_g]->index, vindex, CMD_ADD_VEHICLE_GROUP | CMD_MSG(STR_GROUP_CAN_T_ADD_VEHICLE));
break;
}
case GRP_WIDGET_LIST_VEHICLE: { // Maxtrix vehicle
uint32 id_v = (pt.y - PLY_WND_PRC__OFFSET_TOP_WIDGET) / (int)this->resize.step_height;
const Vehicle *v;
const VehicleID vindex = this->vehicle_sel;
this->vehicle_sel = INVALID_VEHICLE;
this->SetDirty();
if (id_v >= this->vscroll.cap) return; // click out of bounds
id_v += this->vscroll.pos;
if (id_v >= this->vehicles.Length()) return; // click out of list bound
v = this->vehicles[id_v];
if (vindex == v->index) {
ShowVehicleViewWindow(v);
}
break;
}
}
_cursor.vehchain = false;
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
DoCommandP(0, this->group_sel, 0, CMD_RENAME_GROUP | CMD_MSG(STR_GROUP_CAN_T_RENAME), NULL, str);
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll2.cap += delta.y / PLY_WND_PRC__SIZE_OF_ROW_TINY;
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->widget[GRP_WIDGET_LIST_GROUP].data = (this->vscroll2.cap << 8) + 1;
this->widget[GRP_WIDGET_LIST_VEHICLE].data = (this->vscroll.cap << 8) + 1;
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case GRP_WIDGET_SORT_BY_DROPDOWN:
this->vehicles.SetSortType(index);
break;
case GRP_WIDGET_MANAGE_VEHICLES_DROPDOWN:
assert(this->vehicles.Length() != 0);
switch (index) {
case GALF_REPLACE: // Replace window
ShowReplaceGroupVehicleWindow(this->group_sel, this->vehicle_type);
break;
case GALF_SERVICE: // Send for servicing
DoCommandP(0, this->group_sel, ((IsAllGroupID(this->group_sel) ? VLW_STANDARD : VLW_GROUP_LIST) & VLW_MASK)
| DEPOT_MASS_SEND
| DEPOT_SERVICE, GetCmdSendToDepot(this->vehicle_type));
break;
case GALF_DEPOT: // Send to Depots
DoCommandP(0, this->group_sel, ((IsAllGroupID(this->group_sel) ? VLW_STANDARD : VLW_GROUP_LIST) & VLW_MASK)
| DEPOT_MASS_SEND, GetCmdSendToDepot(this->vehicle_type));
break;
case GALF_ADD_SHARED: // Add shared Vehicles
assert(IsValidGroupID(this->group_sel));
DoCommandP(0, this->group_sel, this->vehicle_type, CMD_ADD_SHARED_VEHICLE_GROUP | CMD_MSG(STR_GROUP_CAN_T_ADD_SHARED_VEHICLE));
break;
case GALF_REMOVE_ALL: // Remove all Vehicles from the selected group
assert(IsValidGroupID(this->group_sel));
DoCommandP(0, this->group_sel, this->vehicle_type, CMD_REMOVE_ALL_VEHICLES_GROUP | CMD_MSG(STR_GROUP_CAN_T_REMOVE_ALL_VEHICLES));
break;
default: NOT_REACHED();
}
break;
default: NOT_REACHED();
}
this->SetDirty();
}
virtual void OnTick()
{
if (_pause_game != 0) return;
if (this->groups.NeedResort() || this->vehicles.NeedResort()) {
this->SetDirty();
}
}
virtual void OnPlaceObjectAbort()
{
/* abort drag & drop */
this->vehicle_sel = INVALID_VEHICLE;
this->InvalidateWidget(GRP_WIDGET_LIST_VEHICLE);
}
/**
* Tests whether a given vehicle is selected in the window, and unselects it if necessary.
* Called when the vehicle is deleted.
* @param vehicle Vehicle that is going to be deleted
*/
void UnselectVehicle(VehicleID vehicle)
{
if (this->vehicle_sel == vehicle) ResetObjectToPlace();
}
};
static WindowDesc _group_desc(
WDP_AUTO, WDP_AUTO, 460, 194, 460, 246,
WC_INVALID, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_group_widgets
);
void ShowCompanyGroup(CompanyID company, VehicleType vehicle_type)
{
if (!IsValidCompanyID(company)) return;
_group_desc.cls = GetWindowClassForVehicleType(vehicle_type);
WindowNumber num = (vehicle_type << 11) | VLW_GROUP_LIST | company;
AllocateWindowDescFront<VehicleGroupWindow>(&_group_desc, num);
}
/**
* Removes the highlight of a vehicle in a group window
* @param *v Vehicle to remove all highlights from
*/
void DeleteGroupHighlightOfVehicle(const Vehicle *v)
{
VehicleGroupWindow *w;
/* If we haven't got any vehicles on the mouse pointer, we haven't got any highlighted in any group windows either
* If that is the case, we can skip looping though the windows and save time
*/
if (_special_mouse_mode != WSM_DRAGDROP) return;
VehicleType vehicle_type = v->type;
w = dynamic_cast<VehicleGroupWindow *>(FindWindowById(GetWindowClassForVehicleType(vehicle_type), (vehicle_type << 11) | VLW_GROUP_LIST | v->owner));
if (w != NULL) w->UnselectVehicle(v->index);
}
| 26,323
|
C++
|
.cpp
| 591
| 40.686971
| 200
| 0.669559
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,060
|
vehiclelist.cpp
|
EnergeticBark_OpenTTD-3DS/src/vehiclelist.cpp
|
/* $Id$ */
/** @file vehiclelist.cpp Lists of vehicles. */
#include "stdafx.h"
#include "vehicle_gui.h"
#include "train.h"
#include "vehiclelist.h"
/**
* Generate a list of vehicles inside a depot.
* @param type Type of vehicle
* @param tile The tile the depot is located on
* @param engines Pointer to list to add vehicles to
* @param wagons Pointer to list to add wagons to (can be NULL)
* @param individual_wagons If true add every wagon to #wagons which is not attached to an engine. If false only add the first wagon of every row.
*/
void BuildDepotVehicleList(VehicleType type, TileIndex tile, VehicleList *engines, VehicleList *wagons, bool individual_wagons)
{
engines->Clear();
if (wagons != NULL && wagons != engines) wagons->Clear();
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* General tests for all vehicle types */
if (v->type != type) continue;
if (v->tile != tile) continue;
switch (type) {
case VEH_TRAIN:
if (IsArticulatedPart(v) || IsRearDualheaded(v)) continue;
if (v->u.rail.track != TRACK_BIT_DEPOT) continue;
if (wagons != NULL && IsFreeWagon(v->First())) {
if (individual_wagons || IsFreeWagon(v)) *wagons->Append() = v;
continue;
}
break;
default:
if (!v->IsInDepot()) continue;
break;
}
if (!v->IsPrimaryVehicle()) continue;
*engines->Append() = v;
}
/* Ensure the lists are not wasting too much space. If the lists are fresh
* (i.e. built within a command) then this will actually do nothing. */
engines->Compact();
if (wagons != NULL && wagons != engines) wagons->Compact();
}
/**
* Generate a list of vehicles based on window type.
* @param list Pointer to list to add vehicles to
* @param type Type of vehicle
* @param owner Company to generate list for
* @param index This parameter has different meanings depending on window_type
* <ul>
* <li>VLW_STATION_LIST: index of station to generate a list for</li>
* <li>VLW_SHARED_ORDERS: index of order to generate a list for<li>
* <li>VLW_STANDARD: not used<li>
* <li>VLW_DEPOT_LIST: TileIndex of the depot/hangar to make the list for</li>
* <li>VLW_GROUP_LIST: index of group to generate a list for</li>
* <li>VLW_WAYPOINT_LIST: index of waypoint to generate a list for</li>
* </ul>
* @param window_type The type of window the list is for, using the VLW_ flags in vehicle_gui.h
*/
void GenerateVehicleSortList(VehicleList *list, VehicleType type, Owner owner, uint32 index, uint16 window_type)
{
list->Clear();
const Vehicle *v;
switch (window_type) {
case VLW_STATION_LIST:
FOR_ALL_VEHICLES(v) {
if (v->type == type && v->IsPrimaryVehicle()) {
const Order *order;
FOR_VEHICLE_ORDERS(v, order) {
if (order->IsType(OT_GOTO_STATION) && order->GetDestination() == index) {
*list->Append() = v;
break;
}
}
}
}
break;
case VLW_SHARED_ORDERS:
/* Add all vehicles from this vehicle's shared order list */
for (v = GetVehicle(index); v != NULL; v = v->NextShared()) {
*list->Append() = v;
}
break;
case VLW_STANDARD:
FOR_ALL_VEHICLES(v) {
if (v->type == type && v->owner == owner && v->IsPrimaryVehicle()) {
*list->Append() = v;
}
}
break;
case VLW_DEPOT_LIST:
FOR_ALL_VEHICLES(v) {
if (v->type == type && v->IsPrimaryVehicle()) {
const Order *order;
FOR_VEHICLE_ORDERS(v, order) {
if (order->IsType(OT_GOTO_DEPOT) && !(order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) && order->GetDestination() == index) {
*list->Append() = v;
break;
}
}
}
}
break;
case VLW_WAYPOINT_LIST:
FOR_ALL_VEHICLES(v) {
if (v->type == type && v->IsPrimaryVehicle()) {
const Order *order;
FOR_VEHICLE_ORDERS(v, order) {
if (order->IsType(OT_GOTO_WAYPOINT) && order->GetDestination() == index) {
*list->Append() = v;
break;
}
}
}
}
break;
case VLW_GROUP_LIST:
FOR_ALL_VEHICLES(v) {
if (v->type == type && v->IsPrimaryVehicle() &&
v->owner == owner && v->group_id == index) {
*list->Append() = v;
}
}
break;
default: NOT_REACHED(); break;
}
list->Compact();
}
| 4,245
|
C++
|
.cpp
| 129
| 29.031008
| 146
| 0.639717
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,062
|
genworld_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/genworld_gui.cpp
|
/* $Id$ */
/** @file genworld_gui.cpp GUI to configure and show progress during map generation. */
#include "stdafx.h"
#include "openttd.h"
#include "heightmap.h"
#include "gui.h"
#include "variables.h"
#include "settings_func.h"
#include "debug.h"
#include "genworld.h"
#include "network/network.h"
#include "newgrf_config.h"
#include "strings_func.h"
#include "window_func.h"
#include "date_func.h"
#include "sound_func.h"
#include "fios.h"
#include "string_func.h"
#include "gfx_func.h"
#include "settings_type.h"
#include "widgets/dropdown_type.h"
#include "widgets/dropdown_func.h"
#include "core/random_func.hpp"
#include "landscape_type.h"
#include "querystring_gui.h"
#include "town.h"
#include "table/strings.h"
#include "table/sprites.h"
/**
* In what 'mode' the GenerateLandscapeWindowProc is.
*/
enum glwp_modes {
GLWP_GENERATE,
GLWP_HEIGHTMAP,
GLWP_SCENARIO,
GLWP_END
};
extern void SwitchToMode(SwitchMode new_mode);
extern void MakeNewgameSettingsLive();
static inline void SetNewLandscapeType(byte landscape)
{
_settings_newgame.game_creation.landscape = landscape;
InvalidateWindowClasses(WC_SELECT_GAME);
InvalidateWindowClasses(WC_GENERATE_LANDSCAPE);
}
enum GenerateLandscapeWindowWidgets {
GLAND_TEMPERATE = 3,
GLAND_ARCTIC,
GLAND_TROPICAL,
GLAND_TOYLAND,
GLAND_MAPSIZE_X_TEXT,
GLAND_MAPSIZE_X_PULLDOWN,
GLAND_MAPSIZE_Y_TEXT,
GLAND_MAPSIZE_Y_PULLDOWN,
GLAND_TOWN_TEXT,
GLAND_TOWN_PULLDOWN,
GLAND_INDUSTRY_TEXT,
GLAND_INDUSTRY_PULLDOWN,
GLAND_RANDOM_TEXT,
GLAND_RANDOM_EDITBOX,
GLAND_RANDOM_BUTTON,
GLAND_GENERATE_BUTTON,
GLAND_START_DATE_TEXT1,
GLAND_START_DATE_DOWN,
GLAND_START_DATE_TEXT,
GLAND_START_DATE_UP,
GLAND_SNOW_LEVEL_TEXT1,
GLAND_SNOW_LEVEL_DOWN,
GLAND_SNOW_LEVEL_TEXT,
GLAND_SNOW_LEVEL_UP,
GLAND_TREE_TEXT,
GLAND_TREE_PULLDOWN,
GLAND_LANDSCAPE_TEXT,
GLAND_LANDSCAPE_PULLDOWN,
GLAND_HEIGHTMAP_ROTATION_TEXT = GLAND_LANDSCAPE_TEXT,
GLAND_HEIGHTMAP_ROTATION_PULLDOWN = GLAND_LANDSCAPE_PULLDOWN,
GLAND_TERRAIN_TEXT,
GLAND_TERRAIN_PULLDOWN,
GLAND_WATER_TEXT,
GLAND_WATER_PULLDOWN,
GLAND_SMOOTHNESS_TEXT,
GLAND_SMOOTHNESS_PULLDOWN,
GLAND_BORDER_TYPES,
GLAND_BORDERS_RANDOM,
GLAND_WATER_NW_TEXT,
GLAND_WATER_NE_TEXT,
GLAND_WATER_SE_TEXT,
GLAND_WATER_SW_TEXT,
GLAND_WATER_NW,
GLAND_WATER_NE,
GLAND_WATER_SE,
GLAND_WATER_SW,
};
#ifdef N3DS
static const Widget _generate_landscape_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 11, 319, 0, 13, STR_WORLD_GENERATION_CAPTION, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 319, 14, 313, 0x0, STR_NULL},
/* Landscape selection */
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 3, 79, 17, 71, SPR_SELECT_TEMPERATE, STR_030E_SELECT_TEMPERATE_LANDSCAPE}, // GLAND_TEMPERATE
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 82, 158, 17, 71, SPR_SELECT_SUB_ARCTIC, STR_030F_SELECT_SUB_ARCTIC_LANDSCAPE}, // GLAND_ARCTIC
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 161, 237, 17, 71, SPR_SELECT_SUB_TROPICAL, STR_0310_SELECT_SUB_TROPICAL_LANDSCAPE}, // GLAND_TROPICAL
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 240, 316, 17, 71, SPR_SELECT_TOYLAND, STR_0311_SELECT_TOYLAND_LANDSCAPE}, // GLAND_TOYLAND
/* Mapsize X */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 111, 74, 84, STR_MAPSIZE, STR_NULL}, // GLAND_MAPSIZE_X_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 102, 149, 73, 84, STR_NUM_1, STR_NULL}, // GLAND_MAPSIZE_X_PULLDOWN
/* Mapsize Y */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 156, 165, 74, 84, STR_BY, STR_NULL}, // GLAND_MAPSIZE_Y_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 168, 215, 73, 84, STR_NUM_2, STR_NULL}, // GLAND_MAPSIZE_Y_PULLDOWN
/* Number of towns */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 87, 97, STR_NUMBER_OF_TOWNS, STR_NULL}, // GLAND_TOWN_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 102, 165, 86, 97, 0x0, STR_NULL}, // GLAND_TOWN_PULLDOWN
/* Number of industries */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 100, 110, STR_NUMBER_OF_INDUSTRIES, STR_NULL}, // GLAND_INDUSTRY_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 102, 165, 99, 110, 0x0, STR_NULL}, // GLAND_INDUSTRY_PULLDOWN
/* Edit box for seed */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 113, 123, STR_RANDOM_SEED, STR_NULL}, // GLAND_RANDOM_TEXT
{ WWT_EDITBOX, RESIZE_NONE, COLOUR_WHITE, 102, 197, 112, 123, STR_RANDOM_SEED_OSKTITLE, STR_RANDOM_SEED_HELP}, // GLAND_RANDOM_EDITBOX
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 204, 316, 112, 123, STR_RANDOM, STR_RANDOM_HELP}, // GLAND_RANDOM_BUTTON
/* Generate button */
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREEN, 242, 316, 213, 236, STR_GENERATE, STR_NULL}, // GLAND_GENERATE_BUTTON
/* Start date */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 172, 202, 87, 97, STR_DATE, STR_NULL}, // GLAND_START_DATE_TEXT1
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 206, 217, 86, 97, SPR_ARROW_DOWN, STR_029E_MOVE_THE_STARTING_DATE}, // GLAND_START_DATE_DOWN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 218, 304, 86, 97, STR_GENERATE_DATE, STR_NULL}, // GLAND_START_DATE_TEXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 305, 316, 86, 97, SPR_ARROW_UP, STR_029F_MOVE_THE_STARTING_DATE}, // GLAND_START_DATE_UP
/* Snow line */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 172, 268, 100, 110, STR_SNOW_LINE_HEIGHT, STR_NULL}, // GLAND_SNOW_LEVEL_TEXT1
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 262, 273, 99, 110, SPR_ARROW_DOWN, STR_SNOW_LINE_DOWN}, // GLAND_SNOW_LEVEL_DOWN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 274, 304, 99, 110, STR_NUM_3, STR_NULL}, // GLAND_SNOW_LEVEL_TEXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 305, 316, 99, 110, SPR_ARROW_UP, STR_SNOW_LINE_UP}, // GLAND_SNOW_LEVEL_UP
/* Tree placer */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 139, 149, STR_TREE_PLACER, STR_NULL}, // GLAND_TREE_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 102, 221, 138, 149, 0x0, STR_NULL}, // GLAND_TREE_PULLDOWN
/* Landscape generator */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 126, 136, STR_LAND_GENERATOR, STR_NULL}, // GLAND_LANDSCAPE_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 102, 221, 125, 136, 0x0, STR_NULL}, // GLAND_LANDSCAPE_PULLDOWN
/* Terrain type */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 152, 162, STR_TERRAIN_TYPE, STR_NULL}, // GLAND_TERRAIN_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 102, 221, 151, 162, 0x0, STR_NULL}, // GLAND_TERRAIN_PULLDOWN
/* Water quantity */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 165, 175, STR_QUANTITY_OF_SEA_LAKES, STR_NULL}, // GLAND_WATER_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 102, 221, 164, 175, 0x0, STR_NULL}, // GLAND_WATER_PULLDOWN
/* Map smoothness */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 178, 188, STR_SMOOTHNESS, STR_NULL}, // GLAND_SMOOTHNESS_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 102, 221, 177, 188, 0x0, STR_NULL}, // GLAND_SMOOTHNESS_PULLDOWN
/* Water borders */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 110, 191, 201, STR_BORDER_TYPE, STR_NULL}, // GLAND_BORDER_TYPES
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 102, 221, 190, 201, STR_BORDER_RANDOMIZE, STR_NULL}, // GLAND_BORDERS_RANDOM
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 95, 208, 218, STR_NORTHWEST, STR_NULL}, // GLAND_WATER_NW_TEXT
/* Set northeast and southeast text off screen on the 3ds, there simply isn't enough room.
* Hopefully just northwest and southwest will give players a hint at what the buttons to the right do. */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 320, 320, 240, 240, STR_NORTHEAST, STR_NULL}, // GLAND_WATER_NE_TEXT
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 320, 320, 240, 240, STR_SOUTHEAST, STR_NULL}, // GLAND_WATER_SE_TEXT
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 3, 95, 220, 230, STR_SOUTHWEST, STR_NULL}, // GLAND_WATER_SW_TEXT
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 90, 162, 206, 217, 0x0, STR_NORTHWEST}, // GLAND_WATER_NW
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 163, 235, 206, 217, 0x0, STR_NORTHEAST}, // GLAND_WATER_NE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 163, 235, 218, 229, 0x0, STR_SOUTHEAST}, // GLAND_WATER_SE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 90, 162, 218, 229, 0x0, STR_SOUTHWEST}, // GLAND_WATER_SW
{ WIDGETS_END},
};
#else
static const Widget _generate_landscape_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 11, 337, 0, 13, STR_WORLD_GENERATION_CAPTION, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 337, 14, 313, 0x0, STR_NULL},
/* Landscape selection */
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 10, 86, 24, 78, SPR_SELECT_TEMPERATE, STR_030E_SELECT_TEMPERATE_LANDSCAPE}, // GLAND_TEMPERATE
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 90, 166, 24, 78, SPR_SELECT_SUB_ARCTIC, STR_030F_SELECT_SUB_ARCTIC_LANDSCAPE}, // GLAND_ARCTIC
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 170, 246, 24, 78, SPR_SELECT_SUB_TROPICAL, STR_0310_SELECT_SUB_TROPICAL_LANDSCAPE}, // GLAND_TROPICAL
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 250, 326, 24, 78, SPR_SELECT_TOYLAND, STR_0311_SELECT_TOYLAND_LANDSCAPE}, // GLAND_TOYLAND
/* Mapsize X */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 91, 101, STR_MAPSIZE, STR_NULL}, // GLAND_MAPSIZE_X_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 161, 90, 101, STR_NUM_1, STR_NULL}, // GLAND_MAPSIZE_X_PULLDOWN
/* Mapsize Y */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 168, 176, 91, 101, STR_BY, STR_NULL}, // GLAND_MAPSIZE_Y_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 180, 227, 90, 101, STR_NUM_2, STR_NULL}, // GLAND_MAPSIZE_Y_PULLDOWN
/* Number of towns */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 113, 123, STR_NUMBER_OF_TOWNS, STR_NULL}, // GLAND_TOWN_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 175, 112, 123, 0x0, STR_NULL}, // GLAND_TOWN_PULLDOWN
/* Number of industries */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 131, 141, STR_NUMBER_OF_INDUSTRIES, STR_NULL}, // GLAND_INDUSTRY_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 175, 130, 141, 0x0, STR_NULL}, // GLAND_INDUSTRY_PULLDOWN
/* Edit box for seed */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 153, 163, STR_RANDOM_SEED, STR_NULL}, // GLAND_RANDOM_TEXT
{ WWT_EDITBOX, RESIZE_NONE, COLOUR_WHITE, 114, 207, 152, 163, STR_RANDOM_SEED_OSKTITLE, STR_RANDOM_SEED_HELP}, // GLAND_RANDOM_EDITBOX
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 216, 326, 152, 163, STR_RANDOM, STR_RANDOM_HELP}, // GLAND_RANDOM_BUTTON
/* Generate button */
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREEN, 243, 326, 228, 257, STR_GENERATE, STR_NULL}, // GLAND_GENERATE_BUTTON
/* Start date */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 182, 212, 113, 123, STR_DATE, STR_NULL}, // GLAND_START_DATE_TEXT1
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 216, 227, 112, 123, SPR_ARROW_DOWN, STR_029E_MOVE_THE_STARTING_DATE}, // GLAND_START_DATE_DOWN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 228, 314, 112, 123, STR_GENERATE_DATE, STR_NULL}, // GLAND_START_DATE_TEXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 315, 326, 112, 123, SPR_ARROW_UP, STR_029F_MOVE_THE_STARTING_DATE}, // GLAND_START_DATE_UP
/* Snow line */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 182, 278, 131, 141, STR_SNOW_LINE_HEIGHT, STR_NULL}, // GLAND_SNOW_LEVEL_TEXT1
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 282, 293, 130, 141, SPR_ARROW_DOWN, STR_SNOW_LINE_DOWN}, // GLAND_SNOW_LEVEL_DOWN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 294, 314, 130, 141, STR_NUM_3, STR_NULL}, // GLAND_SNOW_LEVEL_TEXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 315, 326, 130, 141, SPR_ARROW_UP, STR_SNOW_LINE_UP}, // GLAND_SNOW_LEVEL_UP
/* Tree placer */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 193, 203, STR_TREE_PLACER, STR_NULL}, // GLAND_TREE_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 231, 192, 203, 0x0, STR_NULL}, // GLAND_TREE_PULLDOWN
/* Landscape generator */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 175, 185, STR_LAND_GENERATOR, STR_NULL}, // GLAND_LANDSCAPE_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 231, 174, 185, 0x0, STR_NULL}, // GLAND_LANDSCAPE_PULLDOWN
/* Terrain type */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 211, 221, STR_TERRAIN_TYPE, STR_NULL}, // GLAND_TERRAIN_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 231, 210, 221, 0x0, STR_NULL}, // GLAND_TERRAIN_PULLDOWN
/* Water quantity */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 229, 239, STR_QUANTITY_OF_SEA_LAKES, STR_NULL}, // GLAND_WATER_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 231, 228, 239, 0x0, STR_NULL}, // GLAND_WATER_PULLDOWN
/* Map smoothness */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 247, 257, STR_SMOOTHNESS, STR_NULL}, // GLAND_SMOOTHNESS_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 231, 246, 257, 0x0, STR_NULL}, // GLAND_SMOOTHNESS_PULLDOWN
/* Water borders */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 265, 275, STR_BORDER_TYPE, STR_NULL}, // GLAND_BORDER_TYPES
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 114, 231, 264, 275, STR_BORDER_RANDOMIZE, STR_NULL}, // GLAND_BORDERS_RANDOM
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 95, 282, 292, STR_NORTHWEST, STR_NULL}, // GLAND_WATER_NW_TEXT
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 250, 326, 282, 292, STR_NORTHEAST, STR_NULL}, // GLAND_WATER_NE_TEXT
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 250, 326, 294, 304, STR_SOUTHEAST, STR_NULL}, // GLAND_WATER_SE_TEXT
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 95, 294, 304, STR_SOUTHWEST, STR_NULL}, // GLAND_WATER_SW_TEXT
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 100, 172, 280, 291, 0x0, STR_NORTHWEST}, // GLAND_WATER_NW
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 173, 245, 280, 291, 0x0, STR_NORTHEAST}, // GLAND_WATER_NE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 173, 245, 292, 303, 0x0, STR_SOUTHEAST}, // GLAND_WATER_SE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 100, 172, 292, 303, 0x0, STR_SOUTHWEST}, // GLAND_WATER_SW
{ WIDGETS_END},
};
#endif /* N3DS */
static const Widget _heightmap_load_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 11, 337, 0, 13, STR_WORLD_GENERATION_CAPTION, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 337, 14, 235, 0x0, STR_NULL},
/* Landscape selection */
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 10, 86, 24, 78, SPR_SELECT_TEMPERATE, STR_030E_SELECT_TEMPERATE_LANDSCAPE}, // GLAND_TEMPERATE
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 90, 166, 24, 78, SPR_SELECT_SUB_ARCTIC, STR_030F_SELECT_SUB_ARCTIC_LANDSCAPE}, // GLAND_ARCTIC
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 170, 246, 24, 78, SPR_SELECT_SUB_TROPICAL, STR_0310_SELECT_SUB_TROPICAL_LANDSCAPE}, // GLAND_TROPICAL
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 250, 326, 24, 78, SPR_SELECT_TOYLAND, STR_0311_SELECT_TOYLAND_LANDSCAPE}, // GLAND_TOYLAND
/* Mapsize X */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 113, 123, STR_MAPSIZE, STR_NULL}, // GLAND_MAPSIZE_X_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 161, 112, 123, STR_NUM_1, STR_NULL}, // GLAND_MAPSIZE_X_PULLDOWN
/* Mapsize Y */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 168, 176, 113, 123, STR_BY, STR_NULL}, // GLAND_MAPSIZE_Y_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 180, 227, 112, 123, STR_NUM_2, STR_NULL}, // GLAND_MAPSIZE_Y_PULLDOWN
/* Number of towns */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 135, 145, STR_NUMBER_OF_TOWNS, STR_NULL}, // GLAND_TOWN_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 175, 134, 145, 0x0, STR_NULL}, // GLAND_TOWN_PULLDOWN
/* Number of industries */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 153, 163, STR_NUMBER_OF_INDUSTRIES, STR_NULL}, // GLAND_INDUSTRY_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 175, 152, 163, 0x0, STR_NULL}, // GLAND_INDUSTRY_PULLDOWN
/* Edit box for seed */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 175, 185, STR_RANDOM_SEED, STR_NULL}, // GLAND_RANDOM_TEXT
{ WWT_EDITBOX, RESIZE_NONE, COLOUR_WHITE, 114, 207, 174, 185, STR_RANDOM_SEED_OSKTITLE, STR_RANDOM_SEED_HELP}, // GLAND_RANDOM_EDITBOX
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 216, 326, 174, 185, STR_RANDOM, STR_RANDOM_HELP}, // GLAND_RANDOM_BUTTON
/* Generate button */
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREEN, 243, 326, 196, 225, STR_GENERATE, STR_NULL}, // GLAND_GENERATE_BUTTON
/* Starting date */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 182, 212, 135, 145, STR_DATE, STR_NULL}, // GLAND_START_DATE_TEXT1
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 216, 227, 134, 145, SPR_ARROW_DOWN, STR_029E_MOVE_THE_STARTING_DATE}, // GLAND_START_DATE_DOWN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 228, 314, 134, 145, STR_GENERATE_DATE, STR_NULL}, // GLAND_START_DATE_TEXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 315, 326, 134, 145, SPR_ARROW_UP, STR_029F_MOVE_THE_STARTING_DATE}, // GLAND_START_DATE_UP
/* Snow line */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 182, 278, 153, 163, STR_SNOW_LINE_HEIGHT, STR_NULL}, // GLAND_SNOW_LEVEL_TEXT1
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 282, 293, 152, 163, SPR_ARROW_DOWN, STR_SNOW_LINE_DOWN}, // GLAND_SNOW_LEVEL_DOWN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 294, 314, 152, 163, STR_NUM_3, STR_NULL}, // GLAND_SNOW_LEVEL_TEXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 315, 326, 152, 163, SPR_ARROW_UP, STR_SNOW_LINE_UP}, // GLAND_SNOW_LEVEL_UP
/* Tree placer */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 197, 207, STR_TREE_PLACER, STR_NULL}, // GLAND_TREE_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 231, 196, 207, STR_0225, STR_NULL}, // GLAND_TREE_PULLDOWN
/* Heightmap rotation */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 12, 110, 215, 225, STR_HEIGHTMAP_ROTATION, STR_NULL}, // GLAND_HEIGHTMAP_ROTATION_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 114, 231, 214, 225, STR_0225, STR_NULL}, // GLAND_HEIGHTMAP_ROTATION_PULLDOWN
{ WIDGETS_END},
};
void StartGeneratingLandscape(glwp_modes mode)
{
DeleteAllNonVitalWindows();
/* Copy all XXX_newgame to XXX when coming from outside the editor */
MakeNewgameSettingsLive();
ResetGRFConfig(true);
SndPlayFx(SND_15_BEEP);
switch (mode) {
case GLWP_GENERATE: _switch_mode = (_game_mode == GM_EDITOR) ? SM_GENRANDLAND : SM_NEWGAME; break;
case GLWP_HEIGHTMAP: _switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_HEIGHTMAP : SM_START_HEIGHTMAP; break;
case GLWP_SCENARIO: _switch_mode = SM_EDITOR; break;
default: NOT_REACHED();
}
}
static void LandscapeGenerationCallback(Window *w, bool confirmed)
{
if (confirmed) StartGeneratingLandscape((glwp_modes)w->window_number);
}
static DropDownList *BuildMapsizeDropDown()
{
DropDownList *list = new DropDownList();
for (uint i = 6; i <= 11; i++) {
DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_JUST_INT, i, false);
item->SetParam(0, 1 << i);
list->push_back(item);
}
return list;
}
static const StringID _elevations[] = {STR_682A_VERY_FLAT, STR_682B_FLAT, STR_682C_HILLY, STR_682D_MOUNTAINOUS, INVALID_STRING_ID};
static const StringID _sea_lakes[] = {STR_VERY_LOW, STR_6820_LOW, STR_6821_MEDIUM, STR_6822_HIGH, INVALID_STRING_ID};
static const StringID _smoothness[] = {STR_CONFIG_SETTING_ROUGHNESS_OF_TERRAIN_VERY_SMOOTH, STR_CONFIG_SETTING_ROUGHNESS_OF_TERRAIN_SMOOTH, STR_CONFIG_SETTING_ROUGHNESS_OF_TERRAIN_ROUGH, STR_CONFIG_SETTING_ROUGHNESS_OF_TERRAIN_VERY_ROUGH, INVALID_STRING_ID};
static const StringID _tree_placer[] = {STR_CONFIG_SETTING_TREE_PLACER_NONE, STR_CONFIG_SETTING_TREE_PLACER_ORIGINAL, STR_CONFIG_SETTING_TREE_PLACER_IMPROVED, INVALID_STRING_ID};
static const StringID _rotation[] = {STR_CONFIG_SETTING_HEIGHTMAP_ROTATION_COUNTER_CLOCKWISE, STR_CONFIG_SETTING_HEIGHTMAP_ROTATION_CLOCKWISE, INVALID_STRING_ID};
static const StringID _landscape[] = {STR_CONFIG_SETTING_LAND_GENERATOR_ORIGINAL, STR_CONFIG_SETTING_LAND_GENERATOR_TERRA_GENESIS, INVALID_STRING_ID};
static const StringID _num_towns[] = {STR_NUM_VERY_LOW, STR_6816_LOW, STR_6817_NORMAL, STR_6818_HIGH, STR_02BF_CUSTOM, INVALID_STRING_ID};
static const StringID _num_inds[] = {STR_NONE, STR_NUM_VERY_LOW, STR_6816_LOW, STR_6817_NORMAL, STR_6818_HIGH, INVALID_STRING_ID};
struct GenerateLandscapeWindow : public QueryStringBaseWindow {
uint widget_id;
uint x;
uint y;
char name[64];
glwp_modes mode;
GenerateLandscapeWindow(const WindowDesc *desc, WindowNumber number = 0) : QueryStringBaseWindow(11, desc, number)
{
this->LowerWidget(_settings_newgame.game_creation.landscape + GLAND_TEMPERATE);
/* snprintf() always outputs trailing '\0', so whole buffer can be used */
snprintf(this->edit_str_buf, this->edit_str_size, "%u", _settings_newgame.game_creation.generation_seed);
InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 120);
this->SetFocusedWidget(GLAND_RANDOM_EDITBOX);
this->caption = STR_NULL;
this->afilter = CS_NUMERAL;
this->mode = (glwp_modes)this->window_number;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
/* You can't select smoothness / non-water borders if not terragenesis */
if (mode == GLWP_GENERATE) {
this->SetWidgetDisabledState(GLAND_SMOOTHNESS_PULLDOWN, _settings_newgame.game_creation.land_generator == 0);
this->SetWidgetDisabledState(GLAND_BORDERS_RANDOM, _settings_newgame.game_creation.land_generator == 0 || !_settings_newgame.construction.freeform_edges);
this->SetWidgetsDisabledState(_settings_newgame.game_creation.land_generator == 0 || !_settings_newgame.construction.freeform_edges || _settings_newgame.game_creation.water_borders == BORDERS_RANDOM,
GLAND_WATER_NW, GLAND_WATER_NE, GLAND_WATER_SE, GLAND_WATER_SW, WIDGET_LIST_END);
this->SetWidgetLoweredState(GLAND_BORDERS_RANDOM, _settings_newgame.game_creation.water_borders == BORDERS_RANDOM);
this->SetWidgetLoweredState(GLAND_WATER_NW, HasBit(_settings_newgame.game_creation.water_borders, BORDER_NW));
this->SetWidgetLoweredState(GLAND_WATER_NE, HasBit(_settings_newgame.game_creation.water_borders, BORDER_NE));
this->SetWidgetLoweredState(GLAND_WATER_SE, HasBit(_settings_newgame.game_creation.water_borders, BORDER_SE));
this->SetWidgetLoweredState(GLAND_WATER_SW, HasBit(_settings_newgame.game_creation.water_borders, BORDER_SW));
}
/* Disable snowline if not hilly */
this->SetWidgetDisabledState(GLAND_SNOW_LEVEL_TEXT, _settings_newgame.game_creation.landscape != LT_ARCTIC);
/* Disable town, industry and trees in SE */
this->SetWidgetDisabledState(GLAND_TOWN_PULLDOWN, _game_mode == GM_EDITOR);
this->SetWidgetDisabledState(GLAND_INDUSTRY_PULLDOWN, _game_mode == GM_EDITOR);
this->SetWidgetDisabledState(GLAND_TREE_PULLDOWN, _game_mode == GM_EDITOR);
this->SetWidgetDisabledState(GLAND_START_DATE_DOWN, _settings_newgame.game_creation.starting_year <= MIN_YEAR);
this->SetWidgetDisabledState(GLAND_START_DATE_UP, _settings_newgame.game_creation.starting_year >= MAX_YEAR);
this->SetWidgetDisabledState(GLAND_SNOW_LEVEL_DOWN, _settings_newgame.game_creation.snow_line_height <= 2 || _settings_newgame.game_creation.landscape != LT_ARCTIC);
this->SetWidgetDisabledState(GLAND_SNOW_LEVEL_UP, _settings_newgame.game_creation.snow_line_height >= MAX_SNOWLINE_HEIGHT || _settings_newgame.game_creation.landscape != LT_ARCTIC);
this->SetWidgetLoweredState(GLAND_TEMPERATE, _settings_newgame.game_creation.landscape == LT_TEMPERATE);
this->SetWidgetLoweredState(GLAND_ARCTIC, _settings_newgame.game_creation.landscape == LT_ARCTIC);
this->SetWidgetLoweredState(GLAND_TROPICAL, _settings_newgame.game_creation.landscape == LT_TROPIC);
this->SetWidgetLoweredState(GLAND_TOYLAND, _settings_newgame.game_creation.landscape == LT_TOYLAND);
if (_game_mode == GM_EDITOR) {
this->widget[GLAND_TOWN_PULLDOWN].data = STR_6836_OFF;
this->widget[GLAND_INDUSTRY_PULLDOWN].data = STR_6836_OFF;
} else {
this->widget[GLAND_TOWN_PULLDOWN].data = _num_towns[_settings_newgame.difficulty.number_towns];
this->widget[GLAND_INDUSTRY_PULLDOWN].data = _num_inds[_settings_newgame.difficulty.number_industries];
}
if (mode == GLWP_GENERATE) {
this->widget[GLAND_LANDSCAPE_PULLDOWN].data = _landscape[_settings_newgame.game_creation.land_generator];
this->widget[GLAND_TREE_PULLDOWN].data = _tree_placer[_settings_newgame.game_creation.tree_placer];
this->widget[GLAND_TERRAIN_PULLDOWN].data = _elevations[_settings_newgame.difficulty.terrain_type];
this->widget[GLAND_WATER_PULLDOWN].data = _sea_lakes[_settings_newgame.difficulty.quantity_sea_lakes];
this->widget[GLAND_SMOOTHNESS_PULLDOWN].data = _smoothness[_settings_newgame.game_creation.tgen_smoothness];
this->widget[GLAND_BORDERS_RANDOM].data = (_settings_newgame.game_creation.water_borders == BORDERS_RANDOM) ? STR_BORDER_RANDOMIZE : STR_BORDER_MANUAL;
if (_settings_newgame.game_creation.water_borders == BORDERS_RANDOM) {
this->widget[GLAND_WATER_NE].data = STR_BORDER_RANDOM;
this->widget[GLAND_WATER_NW].data = STR_BORDER_RANDOM;
this->widget[GLAND_WATER_SE].data = STR_BORDER_RANDOM;
this->widget[GLAND_WATER_SW].data = STR_BORDER_RANDOM;
} else {
this->widget[GLAND_WATER_NE].data = HasBit(_settings_newgame.game_creation.water_borders,BORDER_NE) ? STR_BORDER_WATER : STR_BORDER_FREEFORM;
this->widget[GLAND_WATER_NW].data = HasBit(_settings_newgame.game_creation.water_borders,BORDER_NW) ? STR_BORDER_WATER : STR_BORDER_FREEFORM;
this->widget[GLAND_WATER_SE].data = HasBit(_settings_newgame.game_creation.water_borders,BORDER_SE) ? STR_BORDER_WATER : STR_BORDER_FREEFORM;
this->widget[GLAND_WATER_SW].data = HasBit(_settings_newgame.game_creation.water_borders,BORDER_SW) ? STR_BORDER_WATER : STR_BORDER_FREEFORM;
}
} else {
this->widget[GLAND_TREE_PULLDOWN].data = _tree_placer[_settings_newgame.game_creation.tree_placer];
this->widget[GLAND_HEIGHTMAP_ROTATION_PULLDOWN].data = _rotation[_settings_newgame.game_creation.heightmap_rotation];
}
/* Set parameters for widget text that requires them. */
SetDParam(0, ConvertYMDToDate(_settings_newgame.game_creation.starting_year, 0, 1)); // GLAND_START_DATE_TEXT
SetDParam(1, 1 << _settings_newgame.game_creation.map_x); // GLAND_MAPSIZE_X_PULLDOWN
SetDParam(2, 1 << _settings_newgame.game_creation.map_y); // GLAND_MAPSIZE_Y_PULLDOWN
SetDParam(3, _settings_newgame.game_creation.snow_line_height); // GLAND_SNOW_LEVEL_TEXT
this->DrawWidgets();
this->DrawEditBox(GLAND_RANDOM_EDITBOX);
if (mode != GLWP_GENERATE) {
char buffer[512];
if (_settings_newgame.game_creation.heightmap_rotation == HM_CLOCKWISE) {
SetDParam(0, this->y);
SetDParam(1, this->x);
} else {
SetDParam(0, this->x);
SetDParam(1, this->y);
}
GetString(buffer, STR_HEIGHTMAP_SIZE, lastof(buffer));
DrawStringRightAligned(326, 91, STR_HEIGHTMAP_SIZE, TC_BLACK);
DrawString( 12, 91, STR_HEIGHTMAP_NAME, TC_BLACK);
SetDParamStr(0, this->name);
DrawStringTruncated(114, 91, STR_JUST_RAW_STRING, TC_ORANGE, 326 - 114 - GetStringBoundingBox(buffer).width - 5);
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case 0: delete this; break;
case GLAND_TEMPERATE:
case GLAND_ARCTIC:
case GLAND_TROPICAL:
case GLAND_TOYLAND:
this->RaiseWidget(_settings_newgame.game_creation.landscape + GLAND_TEMPERATE);
SetNewLandscapeType(widget - GLAND_TEMPERATE);
break;
case GLAND_MAPSIZE_X_PULLDOWN: // Mapsize X
ShowDropDownList(this, BuildMapsizeDropDown(), _settings_newgame.game_creation.map_x, GLAND_MAPSIZE_X_PULLDOWN);
break;
case GLAND_MAPSIZE_Y_PULLDOWN: // Mapsize Y
ShowDropDownList(this, BuildMapsizeDropDown(), _settings_newgame.game_creation.map_y, GLAND_MAPSIZE_Y_PULLDOWN);
break;
case GLAND_TOWN_PULLDOWN: // Number of towns
ShowDropDownMenu(this, _num_towns, _settings_newgame.difficulty.number_towns, GLAND_TOWN_PULLDOWN, 0, 0);
break;
case GLAND_INDUSTRY_PULLDOWN: // Number of industries
ShowDropDownMenu(this, _num_inds, _settings_newgame.difficulty.number_industries, GLAND_INDUSTRY_PULLDOWN, 0, 0);
break;
case GLAND_RANDOM_BUTTON: // Random seed
_settings_newgame.game_creation.generation_seed = InteractiveRandom();
snprintf(this->edit_str_buf, this->edit_str_size, "%u", _settings_newgame.game_creation.generation_seed);
UpdateTextBufferSize(&this->text);
this->SetDirty();
break;
case GLAND_GENERATE_BUTTON: // Generate
MakeNewgameSettingsLive();
if (mode == GLWP_HEIGHTMAP &&
(this->x * 2 < (1U << _settings_newgame.game_creation.map_x) ||
this->x / 2 > (1U << _settings_newgame.game_creation.map_x) ||
this->y * 2 < (1U << _settings_newgame.game_creation.map_y) ||
this->y / 2 > (1U << _settings_newgame.game_creation.map_y))) {
ShowQuery(
STR_HEIGHTMAP_SCALE_WARNING_CAPTION,
STR_HEIGHTMAP_SCALE_WARNING_MESSAGE,
this,
LandscapeGenerationCallback);
} else {
StartGeneratingLandscape(mode);
}
break;
case GLAND_START_DATE_DOWN:
case GLAND_START_DATE_UP: // Year buttons
/* Don't allow too fast scrolling */
if ((this->flags4 & WF_TIMEOUT_MASK) <= WF_TIMEOUT_TRIGGER) {
this->HandleButtonClick(widget);
this->SetDirty();
_settings_newgame.game_creation.starting_year = Clamp(_settings_newgame.game_creation.starting_year + widget - GLAND_START_DATE_TEXT, MIN_YEAR, MAX_YEAR);
}
_left_button_clicked = false;
break;
case GLAND_START_DATE_TEXT: // Year text
this->widget_id = GLAND_START_DATE_TEXT;
SetDParam(0, _settings_newgame.game_creation.starting_year);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_START_DATE_QUERY_CAPT, 8, 100, this, CS_NUMERAL, QSF_NONE);
break;
case GLAND_SNOW_LEVEL_DOWN:
case GLAND_SNOW_LEVEL_UP: // Snow line buttons
/* Don't allow too fast scrolling */
if ((this->flags4 & WF_TIMEOUT_MASK) <= WF_TIMEOUT_TRIGGER) {
this->HandleButtonClick(widget);
this->SetDirty();
_settings_newgame.game_creation.snow_line_height = Clamp(_settings_newgame.game_creation.snow_line_height + widget - GLAND_SNOW_LEVEL_TEXT, 2, MAX_SNOWLINE_HEIGHT);
}
_left_button_clicked = false;
break;
case GLAND_SNOW_LEVEL_TEXT: // Snow line text
this->widget_id = GLAND_SNOW_LEVEL_TEXT;
SetDParam(0, _settings_newgame.game_creation.snow_line_height);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_SNOW_LINE_QUERY_CAPT, 3, 100, this, CS_NUMERAL, QSF_NONE);
break;
case GLAND_TREE_PULLDOWN: // Tree placer
ShowDropDownMenu(this, _tree_placer, _settings_newgame.game_creation.tree_placer, GLAND_TREE_PULLDOWN, 0, 0);
break;
case GLAND_LANDSCAPE_PULLDOWN: // Landscape generator OR Heightmap rotation
/* case GLAND_HEIGHTMAP_ROTATION_TEXT: case GLAND_HEIGHTMAP_ROTATION_PULLDOWN:*/
if (mode == GLWP_HEIGHTMAP) {
ShowDropDownMenu(this, _rotation, _settings_newgame.game_creation.heightmap_rotation, GLAND_HEIGHTMAP_ROTATION_PULLDOWN, 0, 0);
} else {
ShowDropDownMenu(this, _landscape, _settings_newgame.game_creation.land_generator, GLAND_LANDSCAPE_PULLDOWN, 0, 0);
}
break;
case GLAND_TERRAIN_PULLDOWN: // Terrain type
ShowDropDownMenu(this, _elevations, _settings_newgame.difficulty.terrain_type, GLAND_TERRAIN_PULLDOWN, 0, 0);
break;
case GLAND_WATER_PULLDOWN: // Water quantity
ShowDropDownMenu(this, _sea_lakes, _settings_newgame.difficulty.quantity_sea_lakes, GLAND_WATER_PULLDOWN, 0, 0);
break;
case GLAND_SMOOTHNESS_PULLDOWN: // Map smoothness
ShowDropDownMenu(this, _smoothness, _settings_newgame.game_creation.tgen_smoothness, GLAND_SMOOTHNESS_PULLDOWN, 0, 0);
break;
/* Freetype map borders */
case GLAND_WATER_NW:
_settings_newgame.game_creation.water_borders = ToggleBit(_settings_newgame.game_creation.water_borders, BORDER_NW);
break;
case GLAND_WATER_NE:
_settings_newgame.game_creation.water_borders = ToggleBit(_settings_newgame.game_creation.water_borders, BORDER_NE);
break;
case GLAND_WATER_SE:
_settings_newgame.game_creation.water_borders = ToggleBit(_settings_newgame.game_creation.water_borders, BORDER_SE);
break;
case GLAND_WATER_SW:
_settings_newgame.game_creation.water_borders = ToggleBit(_settings_newgame.game_creation.water_borders, BORDER_SW);
break;
case GLAND_BORDERS_RANDOM:
_settings_newgame.game_creation.water_borders = (_settings_newgame.game_creation.water_borders == BORDERS_RANDOM) ? 0 : BORDERS_RANDOM;
this->SetDirty();
break;
}
}
virtual void OnMouseLoop()
{
this->HandleEditBox(GLAND_RANDOM_EDITBOX);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
EventState state;
this->HandleEditBoxKey(GLAND_RANDOM_EDITBOX, key, keycode, state);
/* the seed is unsigned, therefore atoi cannot be used.
* As UINT32_MAX is a 'magic' value (use random seed) it
* should not be possible to be entered into the input
* field; the generate seed button can be used instead. */
_settings_newgame.game_creation.generation_seed = minu(strtoul(this->edit_str_buf, NULL, 10), UINT32_MAX - 1);
return state;
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case GLAND_MAPSIZE_X_PULLDOWN: _settings_newgame.game_creation.map_x = index; break;
case GLAND_MAPSIZE_Y_PULLDOWN: _settings_newgame.game_creation.map_y = index; break;
case GLAND_TREE_PULLDOWN: _settings_newgame.game_creation.tree_placer = index; break;
case GLAND_SMOOTHNESS_PULLDOWN: _settings_newgame.game_creation.tgen_smoothness = index; break;
case GLAND_TOWN_PULLDOWN:
if ((uint)index == CUSTOM_TOWN_NUMBER_DIFFICULTY) {
this->widget_id = widget;
SetDParam(0, _settings_newgame.game_creation.custom_town_number);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_NUMBER_OF_TOWNS, 5, 50, this, CS_NUMERAL, QSF_NONE);
};
IConsoleSetSetting("difficulty.number_towns", index);
break;
case GLAND_INDUSTRY_PULLDOWN:
IConsoleSetSetting("difficulty.number_industries", index);
break;
case GLAND_LANDSCAPE_PULLDOWN:
/* case GLAND_HEIGHTMAP_PULLDOWN: */
if (mode == GLWP_HEIGHTMAP) {
_settings_newgame.game_creation.heightmap_rotation = index;
} else {
_settings_newgame.game_creation.land_generator = index;
}
break;
case GLAND_TERRAIN_PULLDOWN: {
GameMode old_gm = _game_mode;
_game_mode = GM_MENU;
IConsoleSetSetting("difficulty.terrain_type", index);
_game_mode = old_gm;
break;
}
case GLAND_WATER_PULLDOWN: {
GameMode old_gm = _game_mode;
_game_mode = GM_MENU;
IConsoleSetSetting("difficulty.quantity_sea_lakes", index);
_game_mode = old_gm;
break;
}
}
this->SetDirty();
}
virtual void OnQueryTextFinished(char *str)
{
if (!StrEmpty(str)) {
int32 value = atoi(str);
switch (this->widget_id) {
case GLAND_START_DATE_TEXT:
this->InvalidateWidget(GLAND_START_DATE_TEXT);
_settings_newgame.game_creation.starting_year = Clamp(value, MIN_YEAR, MAX_YEAR);
break;
case GLAND_SNOW_LEVEL_TEXT:
this->InvalidateWidget(GLAND_SNOW_LEVEL_TEXT);
_settings_newgame.game_creation.snow_line_height = Clamp(value, 2, MAX_SNOWLINE_HEIGHT);
break;
case GLAND_TOWN_PULLDOWN:
_settings_newgame.game_creation.custom_town_number = Clamp(value, 1, CUSTOM_TOWN_MAX_NUMBER);
break;
}
this->SetDirty();
}
}
};
static const WindowDesc _generate_landscape_desc(
#ifdef N3DS
WDP_CENTER, WDP_CENTER, 320, 240, 320, 240,
#else
WDP_CENTER, WDP_CENTER, 338, 313, 338, 313,
#endif
WC_GENERATE_LANDSCAPE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_generate_landscape_widgets
);
static const WindowDesc _heightmap_load_desc(
WDP_CENTER, WDP_CENTER, 338, 236, 338, 236,
WC_GENERATE_LANDSCAPE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS,
_heightmap_load_widgets
);
static void _ShowGenerateLandscape(glwp_modes mode)
{
uint x = 0;
uint y = 0;
DeleteWindowByClass(WC_GENERATE_LANDSCAPE);
/* Always give a new seed if not editor */
if (_game_mode != GM_EDITOR) _settings_newgame.game_creation.generation_seed = InteractiveRandom();
if (mode == GLWP_HEIGHTMAP) {
/* If the function returns negative, it means there was a problem loading the heightmap */
if (!GetHeightmapDimensions(_file_to_saveload.name, &x, &y)) return;
}
GenerateLandscapeWindow *w = AllocateWindowDescFront<GenerateLandscapeWindow>((mode == GLWP_HEIGHTMAP) ? &_heightmap_load_desc : &_generate_landscape_desc, mode);
if (mode == GLWP_HEIGHTMAP) {
w->x = x;
w->y = y;
strecpy(w->name, _file_to_saveload.title, lastof(w->name));
}
InvalidateWindow(WC_GENERATE_LANDSCAPE, mode);
}
void ShowGenerateLandscape()
{
_ShowGenerateLandscape(GLWP_GENERATE);
}
void ShowHeightmapLoad()
{
_ShowGenerateLandscape(GLWP_HEIGHTMAP);
}
void StartScenarioEditor()
{
StartGeneratingLandscape(GLWP_SCENARIO);
}
void StartNewGameWithoutGUI(uint seed)
{
/* GenerateWorld takes care of the possible GENERATE_NEW_SEED value in 'seed' */
_settings_newgame.game_creation.generation_seed = seed;
StartGeneratingLandscape(GLWP_GENERATE);
}
enum CreateScenarioWindowWidgets {
CSCEN_TEMPERATE = 3,
CSCEN_ARCTIC,
CSCEN_TROPICAL,
CSCEN_TOYLAND,
CSCEN_EMPTY_WORLD,
CSCEN_RANDOM_WORLD,
CSCEN_MAPSIZE_X_TEXT,
CSCEN_MAPSIZE_X_PULLDOWN,
CSCEN_MAPSIZE_Y_TEXT,
CSCEN_MAPSIZE_Y_PULLDOWN,
CSCEN_START_DATE_LABEL,
CSCEN_START_DATE_DOWN,
CSCEN_START_DATE_TEXT,
CSCEN_START_DATE_UP,
CSCEN_FLAT_LAND_HEIGHT_LABEL,
CSCEN_FLAT_LAND_HEIGHT_DOWN,
CSCEN_FLAT_LAND_HEIGHT_TEXT,
CSCEN_FLAT_LAND_HEIGHT_UP
};
struct CreateScenarioWindow : public Window
{
uint widget_id;
CreateScenarioWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->LowerWidget(_settings_newgame.game_creation.landscape + CSCEN_TEMPERATE);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->SetWidgetDisabledState(CSCEN_START_DATE_DOWN, _settings_newgame.game_creation.starting_year <= MIN_YEAR);
this->SetWidgetDisabledState(CSCEN_START_DATE_UP, _settings_newgame.game_creation.starting_year >= MAX_YEAR);
this->SetWidgetDisabledState(CSCEN_FLAT_LAND_HEIGHT_DOWN, _settings_newgame.game_creation.se_flat_world_height <= 0);
this->SetWidgetDisabledState(CSCEN_FLAT_LAND_HEIGHT_UP, _settings_newgame.game_creation.se_flat_world_height >= MAX_TILE_HEIGHT);
this->SetWidgetLoweredState(CSCEN_TEMPERATE, _settings_newgame.game_creation.landscape == LT_TEMPERATE);
this->SetWidgetLoweredState(CSCEN_ARCTIC, _settings_newgame.game_creation.landscape == LT_ARCTIC);
this->SetWidgetLoweredState(CSCEN_TROPICAL, _settings_newgame.game_creation.landscape == LT_TROPIC);
this->SetWidgetLoweredState(CSCEN_TOYLAND, _settings_newgame.game_creation.landscape == LT_TOYLAND);
/* Set parameters for widget text that requires them */
SetDParam(0, ConvertYMDToDate(_settings_newgame.game_creation.starting_year, 0, 1)); // CSCEN_START_DATE_TEXT
SetDParam(1, 1 << _settings_newgame.game_creation.map_x); // CSCEN_MAPSIZE_X_PULLDOWN
SetDParam(2, 1 << _settings_newgame.game_creation.map_y); // CSCEN_MAPSIZE_Y_PULLDOWN
SetDParam(3, _settings_newgame.game_creation.se_flat_world_height); // CSCEN_FLAT_LAND_HEIGHT_TEXT
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case CSCEN_TEMPERATE:
case CSCEN_ARCTIC:
case CSCEN_TROPICAL:
case CSCEN_TOYLAND:
this->RaiseWidget(_settings_newgame.game_creation.landscape + CSCEN_TEMPERATE);
SetNewLandscapeType(widget - CSCEN_TEMPERATE);
break;
case CSCEN_MAPSIZE_X_PULLDOWN: // Mapsize X
ShowDropDownList(this, BuildMapsizeDropDown(), _settings_newgame.game_creation.map_x, CSCEN_MAPSIZE_X_PULLDOWN);
break;
case CSCEN_MAPSIZE_Y_PULLDOWN: // Mapsize Y
ShowDropDownList(this, BuildMapsizeDropDown(), _settings_newgame.game_creation.map_y, CSCEN_MAPSIZE_Y_PULLDOWN);
break;
case CSCEN_EMPTY_WORLD: // Empty world / flat world
StartGeneratingLandscape(GLWP_SCENARIO);
break;
case CSCEN_RANDOM_WORLD: // Generate
ShowGenerateLandscape();
break;
case CSCEN_START_DATE_DOWN:
case CSCEN_START_DATE_UP: // Year buttons
/* Don't allow too fast scrolling */
if ((this->flags4 & WF_TIMEOUT_MASK) <= WF_TIMEOUT_TRIGGER) {
this->HandleButtonClick(widget);
this->SetDirty();
_settings_newgame.game_creation.starting_year = Clamp(_settings_newgame.game_creation.starting_year + widget - CSCEN_START_DATE_TEXT, MIN_YEAR, MAX_YEAR);
}
_left_button_clicked = false;
break;
case CSCEN_START_DATE_TEXT: // Year text
this->widget_id = CSCEN_START_DATE_TEXT;
SetDParam(0, _settings_newgame.game_creation.starting_year);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_START_DATE_QUERY_CAPT, 8, 100, this, CS_NUMERAL, QSF_NONE);
break;
case CSCEN_FLAT_LAND_HEIGHT_DOWN:
case CSCEN_FLAT_LAND_HEIGHT_UP: // Height level buttons
/* Don't allow too fast scrolling */
if ((this->flags4 & WF_TIMEOUT_MASK) <= WF_TIMEOUT_TRIGGER) {
this->HandleButtonClick(widget);
this->SetDirty();
_settings_newgame.game_creation.se_flat_world_height = Clamp(_settings_newgame.game_creation.se_flat_world_height + widget - CSCEN_FLAT_LAND_HEIGHT_TEXT, 0, MAX_TILE_HEIGHT);
}
_left_button_clicked = false;
break;
case CSCEN_FLAT_LAND_HEIGHT_TEXT: // Height level text
this->widget_id = CSCEN_FLAT_LAND_HEIGHT_TEXT;
SetDParam(0, _settings_newgame.game_creation.se_flat_world_height);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_FLAT_WORLD_HEIGHT_QUERY_CAPT, 3, 100, this, CS_NUMERAL, QSF_NONE);
break;
}
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case CSCEN_MAPSIZE_X_PULLDOWN: _settings_newgame.game_creation.map_x = index; break;
case CSCEN_MAPSIZE_Y_PULLDOWN: _settings_newgame.game_creation.map_y = index; break;
}
this->SetDirty();
}
virtual void OnQueryTextFinished(char *str)
{
if (!StrEmpty(str)) {
int32 value = atoi(str);
switch (this->widget_id) {
case CSCEN_START_DATE_TEXT:
this->InvalidateWidget(CSCEN_START_DATE_TEXT);
_settings_newgame.game_creation.starting_year = Clamp(value, MIN_YEAR, MAX_YEAR);
break;
case CSCEN_FLAT_LAND_HEIGHT_TEXT:
this->InvalidateWidget(CSCEN_FLAT_LAND_HEIGHT_TEXT);
_settings_newgame.game_creation.se_flat_world_height = Clamp(value, 0, MAX_TILE_HEIGHT);
break;
}
this->SetDirty();
}
}
};
static const Widget _create_scenario_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 11, 337, 0, 13, STR_SE_CAPTION, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 337, 14, 169, 0x0, STR_NULL},
/* Landscape selection */
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 10, 86, 24, 78, SPR_SELECT_TEMPERATE, STR_030E_SELECT_TEMPERATE_LANDSCAPE}, // CSCEN_TEMPERATE
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 90, 166, 24, 78, SPR_SELECT_SUB_ARCTIC, STR_030F_SELECT_SUB_ARCTIC_LANDSCAPE}, // CSCEN_ARCTIC
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 170, 246, 24, 78, SPR_SELECT_SUB_TROPICAL, STR_0310_SELECT_SUB_TROPICAL_LANDSCAPE}, // CSCEN_TROPICAL
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 250, 326, 24, 78, SPR_SELECT_TOYLAND, STR_0311_SELECT_TOYLAND_LANDSCAPE}, // CSCEN_TOYLAND
/* Generation type */
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREEN, 12, 115, 95, 124, STR_SE_FLAT_WORLD, STR_SE_FLAT_WORLD_TIP}, // CSCEN_EMPTY_WORLD
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREEN, 12, 115, 131, 160, STR_SE_RANDOM_LAND, STR_022A_GENERATE_RANDOM_LAND}, // CSCEN_RANDOM_WORLD
/* Mapsize X */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 135, 212, 96, 106, STR_MAPSIZE, STR_NULL}, // CSCEN_MAPSIZE_X_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 216, 263, 95, 106, STR_NUM_1, STR_NULL}, // CSCEN_MAPSIZE_X_PULLDOWN
/* Mapsize Y */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 268, 276, 96, 106, STR_BY, STR_NULL}, // CSCEN_MAPSIZE_Y_TEXT
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_ORANGE, 279, 326, 95, 106, STR_NUM_2, STR_NULL}, // CSCEN_MAPSIZE_Y_PULLDOWN
/* Start date */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 135, 212, 114, 124, STR_DATE, STR_NULL}, // CSCEN_START_DATE_LABEL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 216, 227, 113, 124, SPR_ARROW_DOWN, STR_029E_MOVE_THE_STARTING_DATE}, // CSCEN_START_DATE_DOWN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 228, 314, 113, 124, STR_GENERATE_DATE, STR_NULL}, // CSCEN_START_DATE_TEXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 315, 326, 113, 124, SPR_ARROW_UP, STR_029F_MOVE_THE_STARTING_DATE}, // CSCEN_START_DATE_UP
/* Flat map height */
{ WWT_TEXT, RESIZE_NONE, COLOUR_ORANGE, 135, 278, 132, 142, STR_FLAT_WORLD_HEIGHT, STR_NULL}, // CSCEN_FLAT_LAND_HEIGHT_LABEL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 282, 293, 131, 142, SPR_ARROW_DOWN, STR_FLAT_WORLD_HEIGHT_DOWN}, // CSCEN_FLAT_LAND_HEIGHT_DOWN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_ORANGE, 294, 314, 131, 142, STR_NUM_3, STR_NULL}, // CSCEN_FLAT_LAND_HEIGHT_TEXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_ORANGE, 315, 326, 131, 142, SPR_ARROW_UP, STR_FLAT_WORLD_HEIGHT_UP}, // CSCEN_FLAT_LAND_HEIGHT_UP
{ WIDGETS_END},
};
static const WindowDesc _create_scenario_desc(
WDP_CENTER, WDP_CENTER, 338, 170, 338, 170,
WC_GENERATE_LANDSCAPE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS,
_create_scenario_widgets
);
void ShowCreateScenario()
{
DeleteWindowByClass(WC_GENERATE_LANDSCAPE);
new CreateScenarioWindow(&_create_scenario_desc, GLWP_SCENARIO);
}
static const Widget _generate_progress_widgets[] = {
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 0, 180, 0, 13, STR_GENERATION_WORLD, STR_018C_WINDOW_TITLE_DRAG_THIS}, // GPWW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 180, 14, 96, 0x0, STR_NULL}, // GPWW_BACKGROUND
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_WHITE, 20, 161, 74, 85, STR_GENERATION_ABORT, STR_NULL}, // GPWW_ABORT
{ WIDGETS_END},
};
static const WindowDesc _generate_progress_desc(
WDP_CENTER, WDP_CENTER, 181, 97, 181, 97,
WC_GENERATE_PROGRESS_WINDOW, WC_NONE,
WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_generate_progress_widgets
);
struct tp_info {
uint percent;
StringID cls;
uint current;
uint total;
int timer;
};
static tp_info _tp;
static void AbortGeneratingWorldCallback(Window *w, bool confirmed)
{
if (confirmed) {
AbortGeneratingWorld();
} else if (IsGeneratingWorld() && !IsGeneratingWorldAborted()) {
SetMouseCursor(SPR_CURSOR_ZZZ, PAL_NONE);
}
}
struct GenerateProgressWindow : public Window {
private:
enum GenerationProgressWindowWidgets {
GPWW_CAPTION,
GPWW_BACKGROUND,
GPWW_ABORT,
};
public:
GenerateProgressWindow() : Window(&_generate_progress_desc)
{
this->FindWindowPlacementAndResize(&_generate_progress_desc);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case GPWW_ABORT:
if (_cursor.sprite == SPR_CURSOR_ZZZ) SetMouseCursor(SPR_CURSOR_MOUSE, PAL_NONE);
ShowQuery(
STR_GENERATION_ABORT_CAPTION,
STR_GENERATION_ABORT_MESSAGE,
this,
AbortGeneratingWorldCallback
);
break;
}
}
virtual void OnPaint()
{
this->DrawWidgets();
/* Draw the % complete with a bar and a text */
DrawFrameRect(19, 20, (this->width - 18), 37, COLOUR_GREY, FR_BORDERONLY);
DrawFrameRect(20, 21, (int)((this->width - 40) * _tp.percent / 100) + 20, 36, COLOUR_MAUVE, FR_NONE);
SetDParam(0, _tp.percent);
DrawStringCentered(90, 25, STR_PROGRESS, TC_FROMSTRING);
/* Tell which class we are generating */
DrawStringCentered(90, 46, _tp.cls, TC_FROMSTRING);
/* And say where we are in that class */
SetDParam(0, _tp.current);
SetDParam(1, _tp.total);
DrawStringCentered(90, 58, STR_GENERATION_PROGRESS, TC_FROMSTRING);
this->SetDirty();
}
};
/**
* Initializes the progress counters to the starting point.
*/
void PrepareGenerateWorldProgress()
{
_tp.cls = STR_WORLD_GENERATION;
_tp.current = 0;
_tp.total = 0;
_tp.percent = 0;
_tp.timer = 0; // Forces to paint the progress window immediatelly
}
/**
* Show the window where a user can follow the process of the map generation.
*/
void ShowGenerateWorldProgress()
{
if (BringWindowToFrontById(WC_GENERATE_PROGRESS_WINDOW, 0)) return;
new GenerateProgressWindow();
}
static void _SetGeneratingWorldProgress(gwp_class cls, uint progress, uint total)
{
static const int percent_table[GWP_CLASS_COUNT + 1] = {0, 5, 15, 20, 40, 60, 65, 80, 85, 99, 100 };
static const StringID class_table[GWP_CLASS_COUNT] = {
STR_WORLD_GENERATION,
STR_022E_LANDSCAPE_GENERATION,
STR_CLEARING_TILES,
STR_022F_TOWN_GENERATION,
STR_0230_INDUSTRY_GENERATION,
STR_UNMOVABLE_GENERATION,
STR_TREE_GENERATION,
STR_SETTINGUP_GAME,
STR_PREPARING_TILELOOP,
STR_PREPARING_GAME
};
assert(cls < GWP_CLASS_COUNT);
/* Do not run this function if we aren't in a thread */
if (!IsGenerateWorldThreaded() && !_network_dedicated) return;
if (IsGeneratingWorldAborted()) HandleGeneratingWorldAbortion();
if (total == 0) {
assert(_tp.cls == class_table[cls]);
_tp.current += progress;
} else {
_tp.cls = class_table[cls];
_tp.current = progress;
_tp.total = total;
_tp.percent = percent_table[cls];
}
/* Don't update the screen too often. So update it once in every 200ms */
if (!_network_dedicated && _tp.timer != 0 && _realtime_tick - _tp.timer < 200) return;
/* Percentage is about the number of completed tasks, so 'current - 1' */
_tp.percent = percent_table[cls] + (percent_table[cls + 1] - percent_table[cls]) * (_tp.current == 0 ? 0 : _tp.current - 1) / _tp.total;
if (_network_dedicated) {
static uint last_percent = 0;
/* Never display 0% */
if (_tp.percent == 0) return;
/* Reset if percent is lower than the last recorded */
if (_tp.percent < last_percent) last_percent = 0;
/* Display every 5%, but 6% is also very valid.. just not smaller steps than 5% */
if (_tp.percent % 5 != 0 && _tp.percent <= last_percent + 5) return;
/* Never show steps smaller than 2%, even if it is a mod 5% */
if (_tp.percent <= last_percent + 2) return;
DEBUG(net, 1, "Map generation percentage complete: %d", _tp.percent);
last_percent = _tp.percent;
/* Don't continue as dedicated never has a thread running */
return;
}
InvalidateWindow(WC_GENERATE_PROGRESS_WINDOW, 0);
MarkWholeScreenDirty();
SetGeneratingWorldPaintStatus(true);
/* We wait here till the paint is done, so we don't read and write
* on the same tile at the same moment. Nasty hack, but that happens
* if you implement threading afterwards */
while (IsGeneratingWorldReadyForPaint()) { CSleep(10); }
_tp.timer = _realtime_tick;
}
/**
* Set the total of a stage of the world generation.
* @param cls the current class we are in.
* @param total Set the total expected items for this class.
*
* Warning: this function isn't clever. Don't go from class 4 to 3. Go upwards, always.
* Also, progress works if total is zero, total works if progress is zero.
*/
void SetGeneratingWorldProgress(gwp_class cls, uint total)
{
if (total == 0) return;
_SetGeneratingWorldProgress(cls, 0, total);
}
/**
* Increases the current stage of the world generation with one.
* @param cls the current class we are in.
*
* Warning: this function isn't clever. Don't go from class 4 to 3. Go upwards, always.
* Also, progress works if total is zero, total works if progress is zero.
*/
void IncreaseGeneratingWorldProgress(gwp_class cls)
{
/* In fact the param 'class' isn't needed.. but for some security reasons, we want it around */
_SetGeneratingWorldProgress(cls, 1, 0);
}
| 57,859
|
C++
|
.cpp
| 990
| 55.628283
| 259
| 0.649632
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,063
|
autoreplace_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/autoreplace_gui.cpp
|
/* $Id$ */
/** @file autoreplace_gui.cpp GUI for autoreplace handling. */
#include "stdafx.h"
#include "command_func.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "group.h"
#include "rail.h"
#include "strings_func.h"
#include "window_func.h"
#include "autoreplace_func.h"
#include "gfx_func.h"
#include "company_func.h"
#include "widgets/dropdown_type.h"
#include "engine_base.h"
#include "window_gui.h"
#include "engine_gui.h"
#include "table/strings.h"
void DrawEngineList(VehicleType type, int x, int r, int y, const GUIEngineList *eng_list, uint16 min, uint16 max, EngineID selected_id, int count_location, GroupID selected_group);
enum ReplaceVehicleWindowWidgets {
RVW_WIDGET_LEFT_MATRIX = 3,
RVW_WIDGET_LEFT_SCROLLBAR,
RVW_WIDGET_RIGHT_MATRIX,
RVW_WIDGET_RIGHT_SCROLLBAR,
RVW_WIDGET_LEFT_DETAILS,
RVW_WIDGET_RIGHT_DETAILS,
/* Button row */
RVW_WIDGET_START_REPLACE,
RVW_WIDGET_INFO_TAB,
RVW_WIDGET_STOP_REPLACE,
RVW_WIDGET_RESIZE,
/* Train only widgets */
RVW_WIDGET_TRAIN_ENGINEWAGON_TOGGLE,
RVW_WIDGET_TRAIN_FLUFF_LEFT,
RVW_WIDGET_TRAIN_RAILTYPE_DROPDOWN,
RVW_WIDGET_TRAIN_FLUFF_RIGHT,
RVW_WIDGET_TRAIN_WAGONREMOVE_TOGGLE,
};
static int CDECL EngineNumberSorter(const void *a, const void *b)
{
const EngineID va = *(const EngineID*)a;
const EngineID vb = *(const EngineID*)b;
int r = ListPositionOfEngine(va) - ListPositionOfEngine(vb);
return r;
}
/** Rebuild the left autoreplace list if an engine is removed or added
* @param e Engine to check if it is removed or added
* @param id_g The group the engine belongs to
* Note: this function only works if it is called either
* - when a new vehicle is build, but before it's counted in num_engines
* - when a vehicle is deleted and after it's substracted from num_engines
* - when not changing the count (used when changing replace orders)
*/
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
{
Company *c = GetCompany(_local_company);
uint num_engines = GetGroupNumEngines(_local_company, id_g, e);
if (num_engines == 0 || c->num_engines[e] == 0) {
/* We don't have any of this engine type.
* Either we just sold the last one, we build a new one or we stopped replacing it.
* In all cases, we need to update the left list */
InvalidateWindowData(WC_REPLACE_VEHICLE, GetEngine(e)->type, true);
}
}
/** When an engine is made buildable or is removed from being buildable, add/remove it from the build/autoreplace lists
* @param type The type of engine
*/
void AddRemoveEngineFromAutoreplaceAndBuildWindows(VehicleType type)
{
InvalidateWindowData(WC_REPLACE_VEHICLE, type, false); // Update the autoreplace window
InvalidateWindowClassesData(WC_BUILD_VEHICLE); // The build windows needs updating as well
}
/**
* Window for the autoreplacing of vehicles.
*/
class ReplaceVehicleWindow : public Window {
byte sel_index[2];
EngineID sel_engine[2];
uint16 count[2];
bool wagon_btnstate; ///< true means engine is selected
GUIEngineList list[2];
bool update_left;
bool update_right;
bool init_lists;
GroupID sel_group;
static RailType sel_railtype;
/** Figure out if an engine should be added to a list
* @param e The EngineID
* @param draw_left If true, then the left list is drawn (the engines specific to the railtype you selected)
* @param show_engines if truem then locomotives are drawn, else wagons (never both)
* @return true if the engine should be in the list (based on this check)
*/
bool GenerateReplaceRailList(EngineID e, bool draw_left, bool show_engines)
{
const RailVehicleInfo *rvi = RailVehInfo(e);
/* Ensure that the wagon/engine selection fits the engine. */
if ((rvi->railveh_type == RAILVEH_WAGON) == show_engines) return false;
if (draw_left && show_engines) {
/* Ensure that the railtype is specific to the selected one */
if (rvi->railtype != this->sel_railtype) return false;
}
return true;
}
/** Generate a list
* @param w Window, that contains the list
* @param draw_left true if generating the left list, otherwise false
*/
void GenerateReplaceVehList(Window *w, bool draw_left)
{
EngineID selected_engine = INVALID_ENGINE;
VehicleType type = (VehicleType)this->window_number;
byte i = draw_left ? 0 : 1;
GUIEngineList *list = &this->list[i];
list->Clear();
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, type) {
EngineID eid = e->index;
if (type == VEH_TRAIN && !GenerateReplaceRailList(eid, draw_left, this->wagon_btnstate)) continue; // special rules for trains
if (draw_left) {
const GroupID selected_group = this->sel_group;
const uint num_engines = GetGroupNumEngines(_local_company, selected_group, eid);
/* Skip drawing the engines we don't have any of and haven't set for replacement */
if (num_engines == 0 && EngineReplacementForCompany(GetCompany(_local_company), eid, selected_group) == INVALID_ENGINE) continue;
} else {
if (!CheckAutoreplaceValidity(this->sel_engine[0], eid, _local_company)) continue;
}
*list->Append() = eid;
if (eid == this->sel_engine[i]) selected_engine = eid; // The selected engine is still in the list
}
this->sel_engine[i] = selected_engine; // update which engine we selected (the same or none, if it's not in the list anymore)
EngList_Sort(list, &EngineNumberSorter);
}
/** Generate the lists */
void GenerateLists()
{
EngineID e = this->sel_engine[0];
if (this->update_left == true) {
/* We need to rebuild the left list */
GenerateReplaceVehList(this, true);
SetVScrollCount(this, this->list[0].Length());
if (this->init_lists && this->sel_engine[0] == INVALID_ENGINE && this->list[0].Length() != 0) {
this->sel_engine[0] = this->list[0][0];
}
}
if (this->update_right || e != this->sel_engine[0]) {
/* Either we got a request to rebuild the right list or the left list selected a different engine */
if (this->sel_engine[0] == INVALID_ENGINE) {
/* Always empty the right list when nothing is selected in the left list */
this->list[1].Clear();
this->sel_engine[1] = INVALID_ENGINE;
} else {
GenerateReplaceVehList(this, false);
SetVScroll2Count(this, this->list[1].Length());
if (this->init_lists && this->sel_engine[1] == INVALID_ENGINE && this->list[1].Length() != 0) {
this->sel_engine[1] = this->list[1][0];
}
}
}
/* Reset the flags about needed updates */
this->update_left = false;
this->update_right = false;
this->init_lists = false;
}
public:
ReplaceVehicleWindow(const WindowDesc *desc, VehicleType vehicletype, GroupID id_g) : Window(desc, vehicletype)
{
this->wagon_btnstate = true; // start with locomotives (all other vehicles will not read this bool)
this->update_left = true;
this->update_right = true;
this->init_lists = true;
this->sel_engine[0] = INVALID_ENGINE;
this->sel_engine[1] = INVALID_ENGINE;
this->resize.step_height = GetVehicleListHeight(vehicletype);
this->vscroll.cap = this->resize.step_height == 14 ? 8 : 4;
Widget *widget = this->widget;
widget[RVW_WIDGET_LEFT_MATRIX].data = widget[RVW_WIDGET_RIGHT_MATRIX].data = (this->vscroll.cap << 8) + 1;
if (vehicletype == VEH_TRAIN) {
this->wagon_btnstate = true;
/* The train window is bigger so we will move some of the widgets to fit the new size.
* We will start by moving the resize button to the lower right corner. */
widget[RVW_WIDGET_RESIZE].top = widget[RVW_WIDGET_TRAIN_ENGINEWAGON_TOGGLE].top;
widget[RVW_WIDGET_RESIZE].bottom = widget[RVW_WIDGET_TRAIN_ENGINEWAGON_TOGGLE].bottom;
widget[RVW_WIDGET_STOP_REPLACE].right = widget[RVW_WIDGET_RESIZE].right;
/* The detail panel is one line taller for trains so we will move some of the widgets one line (10 pixels) down. */
widget[RVW_WIDGET_LEFT_DETAILS].bottom += 10;
widget[RVW_WIDGET_RIGHT_DETAILS].bottom += 10;
for (int i = RVW_WIDGET_START_REPLACE; i < RVW_WIDGET_RESIZE; i++) {
widget[i].top += 10;
widget[i].bottom += 10;
}
} else {
/* Since it's not a train we will hide the train only widgets. */
this->SetWidgetsHiddenState(true,
RVW_WIDGET_TRAIN_ENGINEWAGON_TOGGLE,
RVW_WIDGET_TRAIN_FLUFF_LEFT,
RVW_WIDGET_TRAIN_RAILTYPE_DROPDOWN,
RVW_WIDGET_TRAIN_FLUFF_RIGHT,
RVW_WIDGET_TRAIN_WAGONREMOVE_TOGGLE,
WIDGET_LIST_END);
}
ResizeWindow(this, 0, this->resize.step_height * this->vscroll.cap);
/* Set the minimum window size to the current window size */
this->resize.width = this->width;
this->resize.height = this->height;
this->owner = _local_company;
this->sel_group = id_g;
this->vscroll2.cap = this->vscroll.cap; // these two are always the same
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
if (this->update_left || this->update_right) this->GenerateLists();
Company *c = GetCompany(_local_company);
EngineID selected_id[2];
const GroupID selected_group = this->sel_group;
selected_id[0] = this->sel_engine[0];
selected_id[1] = this->sel_engine[1];
/* Disable the "Start Replacing" button if:
* Either list is empty
* or The selected replacement engine has a replacement (to prevent loops)
* or The right list (new replacement) has the existing replacement vehicle selected */
this->SetWidgetDisabledState(RVW_WIDGET_START_REPLACE,
selected_id[0] == INVALID_ENGINE ||
selected_id[1] == INVALID_ENGINE ||
EngineReplacementForCompany(c, selected_id[1], selected_group) != INVALID_ENGINE ||
EngineReplacementForCompany(c, selected_id[0], selected_group) == selected_id[1]);
/* Disable the "Stop Replacing" button if:
* The left list (existing vehicle) is empty
* or The selected vehicle has no replacement set up */
this->SetWidgetDisabledState(RVW_WIDGET_STOP_REPLACE,
selected_id[0] == INVALID_ENGINE ||
!EngineHasReplacementForCompany(c, selected_id[0], selected_group));
/* now the actual drawing of the window itself takes place */
SetDParam(0, STR_019F_TRAIN + this->window_number);
if (this->window_number == VEH_TRAIN) {
/* set on/off for renew_keep_length */
SetDParam(1, c->renew_keep_length ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF);
/* set wagon/engine button */
SetDParam(2, this->wagon_btnstate ? STR_ENGINES : STR_WAGONS);
/* sets the colour of that art thing */
this->widget[RVW_WIDGET_TRAIN_FLUFF_LEFT].colour = _company_colours[_local_company];
this->widget[RVW_WIDGET_TRAIN_FLUFF_RIGHT].colour = _company_colours[_local_company];
}
if (this->window_number == VEH_TRAIN) {
/* Show the selected railtype in the pulldown menu */
const RailtypeInfo *rti = GetRailTypeInfo(sel_railtype);
this->widget[RVW_WIDGET_TRAIN_RAILTYPE_DROPDOWN].data = rti->strings.replace_text;
}
this->DrawWidgets();
/* sets up the string for the vehicle that is being replaced to */
if (selected_id[0] != INVALID_ENGINE) {
if (!EngineHasReplacementForCompany(c, selected_id[0], selected_group)) {
SetDParam(0, STR_NOT_REPLACING);
} else {
SetDParam(0, STR_ENGINE_NAME);
SetDParam(1, EngineReplacementForCompany(c, selected_id[0], selected_group));
}
} else {
SetDParam(0, STR_NOT_REPLACING_VEHICLE_SELECTED);
}
DrawStringTruncated(this->widget[RVW_WIDGET_INFO_TAB].left + 6, this->widget[RVW_WIDGET_INFO_TAB].top + 1, STR_02BD, TC_BLACK, this->GetWidgetWidth(RVW_WIDGET_INFO_TAB) - 12);
/* Draw the lists */
for (byte i = 0; i < 2; i++) {
uint widget = (i == 0) ? RVW_WIDGET_LEFT_MATRIX : RVW_WIDGET_RIGHT_MATRIX;
GUIEngineList *list = &this->list[i]; // which list to draw
EngineID start = i == 0 ? this->vscroll.pos : this->vscroll2.pos; // what is the offset for the start (scrolling)
EngineID end = min((i == 0 ? this->vscroll.cap : this->vscroll2.cap) + start, list->Length());
/* Do the actual drawing */
DrawEngineList((VehicleType)this->window_number, this->widget[widget].left + 2, this->widget[widget].right, this->widget[widget].top + 1, list, start, end, this->sel_engine[i], i == 0 ? this->widget[RVW_WIDGET_LEFT_MATRIX].right - 2 : 0, selected_group);
/* Also draw the details if an engine is selected */
if (this->sel_engine[i] != INVALID_ENGINE) {
const Widget *wi = &this->widget[i == 0 ? RVW_WIDGET_LEFT_DETAILS : RVW_WIDGET_RIGHT_DETAILS];
int text_end = DrawVehiclePurchaseInfo(wi->left + 2, wi->top + 1, wi->right - wi->left - 2, this->sel_engine[i]);
if (text_end > wi->bottom) {
this->SetDirty();
ResizeWindowForWidget(this, i == 0 ? RVW_WIDGET_LEFT_DETAILS : RVW_WIDGET_RIGHT_DETAILS, 0, text_end - wi->bottom);
this->SetDirty();
}
}
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case RVW_WIDGET_TRAIN_ENGINEWAGON_TOGGLE:
this->wagon_btnstate = !(this->wagon_btnstate);
this->update_left = true;
this->init_lists = true;
this->SetDirty();
break;
case RVW_WIDGET_TRAIN_RAILTYPE_DROPDOWN: { // Railtype selection dropdown menu
const Company *c = GetCompany(_local_company);
DropDownList *list = new DropDownList();
for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
const RailtypeInfo *rti = GetRailTypeInfo(rt);
/* Skip rail type if it has no label */
if (rti->label == 0) continue;
list->push_back(new DropDownListStringItem(rti->strings.replace_text, rt, !HasBit(c->avail_railtypes, rt)));
}
ShowDropDownList(this, list, sel_railtype, RVW_WIDGET_TRAIN_RAILTYPE_DROPDOWN);
break;
}
case RVW_WIDGET_TRAIN_WAGONREMOVE_TOGGLE: // toggle renew_keep_length
DoCommandP(0, 5, GetCompany(_local_company)->renew_keep_length ? 0 : 1, CMD_SET_AUTOREPLACE);
break;
case RVW_WIDGET_START_REPLACE: { // Start replacing
EngineID veh_from = this->sel_engine[0];
EngineID veh_to = this->sel_engine[1];
DoCommandP(0, 3 + (this->sel_group << 16) , veh_from + (veh_to << 16), CMD_SET_AUTOREPLACE);
this->SetDirty();
} break;
case RVW_WIDGET_STOP_REPLACE: { // Stop replacing
EngineID veh_from = this->sel_engine[0];
DoCommandP(0, 3 + (this->sel_group << 16), veh_from + (INVALID_ENGINE << 16), CMD_SET_AUTOREPLACE);
this->SetDirty();
} break;
case RVW_WIDGET_LEFT_MATRIX:
case RVW_WIDGET_RIGHT_MATRIX: {
uint i = (pt.y - 14) / this->resize.step_height;
uint16 click_scroll_pos = widget == RVW_WIDGET_LEFT_MATRIX ? this->vscroll.pos : this->vscroll2.pos;
uint16 click_scroll_cap = widget == RVW_WIDGET_LEFT_MATRIX ? this->vscroll.cap : this->vscroll2.cap;
byte click_side = widget == RVW_WIDGET_LEFT_MATRIX ? 0 : 1;
size_t engine_count = this->list[click_side].Length();
if (i < click_scroll_cap) {
i += click_scroll_pos;
EngineID e = engine_count > i ? this->list[click_side][i] : INVALID_ENGINE;
if (e == this->sel_engine[click_side]) break; // we clicked the one we already selected
this->sel_engine[click_side] = e;
if (click_side == 0) {
this->update_right = true;
this->init_lists = true;
}
this->SetDirty();
}
break;
}
}
}
virtual void OnDropdownSelect(int widget, int index)
{
RailType temp = (RailType)index;
if (temp == sel_railtype) return; // we didn't select a new one. No need to change anything
sel_railtype = temp;
/* Reset scrollbar positions */
this->vscroll.pos = 0;
this->vscroll2.pos = 0;
/* Rebuild the lists */
this->update_left = true;
this->update_right = true;
this->init_lists = true;
this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta) {
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->vscroll2.cap += delta.y / (int)this->resize.step_height;
Widget *widget = this->widget;
widget[RVW_WIDGET_LEFT_MATRIX].data = widget[RVW_WIDGET_RIGHT_MATRIX].data = (this->vscroll2.cap << 8) + 1;
if (delta.x != 0) {
/* We changed the width of the window so we have to resize the lists.
* Because ResizeButtons() makes each widget the same size it can't be used on the lists
* because then the lists would have the same size as the scrollbars.
* Instead we use it on the detail panels.
* Afterwards we use the new location of the detail panels (the middle of the window)
* to place the lists.
* This way the lists will have equal size while keeping the width of the scrollbars unchanged. */
ResizeButtons(this, RVW_WIDGET_LEFT_DETAILS, RVW_WIDGET_RIGHT_DETAILS);
widget[RVW_WIDGET_RIGHT_MATRIX].left = widget[RVW_WIDGET_RIGHT_DETAILS].left;
widget[RVW_WIDGET_LEFT_SCROLLBAR].right = widget[RVW_WIDGET_LEFT_DETAILS].right;
widget[RVW_WIDGET_LEFT_SCROLLBAR].left = widget[RVW_WIDGET_LEFT_SCROLLBAR].right - 11;
widget[RVW_WIDGET_LEFT_MATRIX].right = widget[RVW_WIDGET_LEFT_SCROLLBAR].left - 1;
}
}
virtual void OnInvalidateData(int data)
{
if (data != 0) {
this->update_left = true;
} else {
this->update_right = true;
}
}
};
static const Widget _replace_vehicle_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 443, 0, 13, STR_REPLACE_VEHICLES_WHITE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 444, 455, 0, 13, STR_NULL, STR_STICKY_BUTTON},
{ WWT_MATRIX, RESIZE_BOTTOM, COLOUR_GREY, 0, 215, 14, 13, 0x1, STR_REPLACE_HELP_LEFT_ARRAY},
{ WWT_SCROLLBAR, RESIZE_BOTTOM, COLOUR_GREY, 216, 227, 14, 13, STR_NULL, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_MATRIX, RESIZE_LRB, COLOUR_GREY, 228, 443, 14, 13, 0x1, STR_REPLACE_HELP_RIGHT_ARRAY},
{ WWT_SCROLL2BAR, RESIZE_LRB, COLOUR_GREY, 444, 455, 14, 13, STR_NULL, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_PANEL, RESIZE_TB, COLOUR_GREY, 0, 227, 14, 105, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 228, 455, 14, 105, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 138, 106, 117, STR_REPLACE_VEHICLES_START, STR_REPLACE_HELP_START_BUTTON},
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 139, 305, 106, 117, 0x0, STR_REPLACE_HELP_REPLACE_INFO_TAB},
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_GREY, 306, 443, 106, 117, STR_REPLACE_VEHICLES_STOP, STR_REPLACE_HELP_STOP_BUTTON},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 444, 455, 106, 117, STR_NULL, STR_RESIZE_BUTTON},
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 138, 128, 139, STR_REPLACE_ENGINE_WAGON_SELECT, STR_REPLACE_ENGINE_WAGON_SELECT_HELP},
{ WWT_PANEL, RESIZE_TB, COLOUR_GREY, 139, 153, 128, 139, 0x0, STR_NULL},
{ WWT_DROPDOWN, RESIZE_RTB, COLOUR_GREY, 154, 289, 128, 139, 0x0, STR_REPLACE_HELP_RAILTYPE},
{ WWT_PANEL, RESIZE_LRTB, COLOUR_GREY, 290, 305, 128, 139, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_GREY, 306, 443, 128, 139, STR_REPLACE_REMOVE_WAGON, STR_REPLACE_REMOVE_WAGON_HELP},
{ WIDGETS_END},
};
static const WindowDesc _replace_rail_vehicle_desc(
WDP_AUTO, WDP_AUTO, 456, 140, 456, 140,
WC_REPLACE_VEHICLE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE | WDF_CONSTRUCTION,
_replace_vehicle_widgets
);
static const WindowDesc _replace_vehicle_desc(
WDP_AUTO, WDP_AUTO, 456, 118, 456, 118,
WC_REPLACE_VEHICLE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE | WDF_CONSTRUCTION,
_replace_vehicle_widgets
);
RailType ReplaceVehicleWindow::sel_railtype = RAILTYPE_RAIL;
void ShowReplaceGroupVehicleWindow(GroupID id_g, VehicleType vehicletype)
{
DeleteWindowById(WC_REPLACE_VEHICLE, vehicletype);
new ReplaceVehicleWindow(vehicletype == VEH_TRAIN ? &_replace_rail_vehicle_desc : &_replace_vehicle_desc, vehicletype, id_g);
}
| 20,410
|
C++
|
.cpp
| 420
| 45.133333
| 257
| 0.680273
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,064
|
thread_morphos.cpp
|
EnergeticBark_OpenTTD-3DS/src/thread_morphos.cpp
|
/* $Id$ */
/** @file thread_morphos.cpp MorphOS implementation of Threads. */
#include "stdafx.h"
#include "thread.h"
#include "debug.h"
#include "core/alloc_func.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <exec/types.h>
#include <exec/rawfmt.h>
#include <dos/dostags.h>
#include <proto/dos.h>
#include <proto/exec.h>
/**
* avoid name clashes with MorphOS API functions
*/
#undef Exit
#undef Wait
/**
* NOTE: this code heavily depends on latest libnix updates. So make
* sure you link with new stuff which supports semaphore locking of
* the IO resources, else it will just go foobar.
*/
struct OTTDThreadStartupMessage {
struct Message msg; ///< standard exec.library message (MUST be the first thing in the message struct!)
OTTDThreadFunc func; ///< function the thread will execute
void *arg; ///< functions arguments for the thread function
};
/**
* Default OpenTTD STDIO/ERR debug output is not very useful for this, so we
* utilize serial/ramdebug instead.
*/
#ifndef NO_DEBUG_MESSAGES
void KPutStr(CONST_STRPTR format)
{
RawDoFmt(format, NULL, (void (*)())RAWFMTFUNC_SERIAL, NULL);
}
#else
#define KPutStr(x)
#endif
/**
* MorphOS version for ThreadObject.
*/
class ThreadObject_MorphOS : public ThreadObject {
private:
APTR m_thr; ///< System thread identifier.
struct MsgPort *m_replyport;
struct OTTDThreadStartupMessage m_msg;
bool self_destruct;
public:
/**
* Create a sub process and start it, calling proc(param).
*/
ThreadObject_MorphOS(OTTDThreadFunc proc, void *param, self_destruct) :
m_thr(0), self_destruct(self_destruct)
{
struct Task *parent;
KPutStr("[OpenTTD] Create thread...\n");
parent = FindTask(NULL);
/* Make sure main thread runs with sane priority */
SetTaskPri(parent, 0);
/* Things we'll pass down to the child by utilizing NP_StartupMsg */
m_msg.func = proc;
m_msg.arg = param;
m_replyport = CreateMsgPort();
if (m_replyport != NULL) {
struct Process *child;
m_msg.msg.mn_Node.ln_Type = NT_MESSAGE;
m_msg.msg.mn_ReplyPort = m_replyport;
m_msg.msg.mn_Length = sizeof(struct OTTDThreadStartupMessage);
child = CreateNewProcTags(
NP_CodeType, CODETYPE_PPC,
NP_Entry, ThreadObject_MorphOS::Proxy,
NP_StartupMsg, (IPTR)&m_msg,
NP_Priority, 5UL,
NP_Name, (IPTR)"OpenTTD Thread",
NP_PPCStackSize, 131072UL,
TAG_DONE);
m_thr = (APTR) child;
if (child != NULL) {
KPutStr("[OpenTTD] Child process launched.\n");
} else {
KPutStr("[OpenTTD] Couldn't create child process. (constructors never fail, yeah!)\n");
DeleteMsgPort(m_replyport);
}
}
}
/* virtual */ ~ThreadObject_MorphOS()
{
}
/* virtual */ bool Exit()
{
struct OTTDThreadStartupMessage *msg;
/* You can only exit yourself */
assert(IsCurrent());
KPutStr("[Child] Aborting...\n");
if (NewGetTaskAttrs(NULL, &msg, sizeof(struct OTTDThreadStartupMessage *), TASKINFOTYPE_STARTUPMSG, TAG_DONE) && msg != NULL) {
/* For now we terminate by throwing an error, gives much cleaner cleanup */
throw OTTDThreadExitSignal();
}
return true;
}
/* virtual */ void Join()
{
struct OTTDThreadStartupMessage *reply;
/* You cannot join yourself */
assert(!IsCurrent());
KPutStr("[OpenTTD] Join threads...\n");
KPutStr("[OpenTTD] Wait for child to quit...\n");
WaitPort(m_replyport);
GetMsg(m_replyport);
DeleteMsgPort(m_replyport);
m_thr = 0;
}
/* virtual */ bool IsCurrent()
{
return FindTask(NULL) == m_thr;
}
private:
/**
* On thread creation, this function is called, which calls the real startup
* function. This to get back into the correct instance again.
*/
static void Proxy(void)
{
struct Task *child = FindTask(NULL);
struct OTTDThreadStartupMessage *msg;
/* Make sure, we don't block the parent. */
SetTaskPri(child, -5);
KPutStr("[Child] Progressing...\n");
if (NewGetTaskAttrs(NULL, &msg, sizeof(struct OTTDThreadStartupMessage *), TASKINFOTYPE_STARTUPMSG, TAG_DONE) && msg != NULL) {
try {
msg->func(msg->arg);
} catch(OTTDThreadExitSignal e) {
KPutStr("[Child] Returned to main()\n");
} catch(...) {
NOT_REACHED();
}
}
/* Quit the child, exec.library will reply the startup msg internally. */
KPutStr("[Child] Done.\n");
if (self_destruct) delete this;
}
};
/* static */ bool ThreadObject::New(OTTDThreadFunc proc, void *param, ThreadObject **thread)
{
ThreadObject *to = new ThreadObject_MorphOS(proc, param, thread == NULL);
if (thread != NULL) *thread = to;
return true;
}
| 4,620
|
C++
|
.cpp
| 150
| 28.006667
| 129
| 0.694444
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,065
|
industry_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/industry_gui.cpp
|
/* $Id$ */
/** @file industry_gui.cpp GUIs related to industries. */
#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "industry.h"
#include "town.h"
#include "variables.h"
#include "cheat_type.h"
#include "newgrf.h"
#include "newgrf_industries.h"
#include "newgrf_text.h"
#include "strings_func.h"
#include "map_func.h"
#include "company_func.h"
#include "tilehighlight_func.h"
#include "string_func.h"
#include "sortlist_type.h"
#include "widgets/dropdown_func.h"
#include "company_base.h"
#include "table/strings.h"
#include "table/sprites.h"
bool _ignore_restrictions;
enum CargoSuffixType {
CST_FUND,
CST_VIEW,
CST_DIR,
};
/**
* Gets the string to display after the cargo name (using callback 37)
* @param cargo the cargo for which the suffix is requested
* - 00 - first accepted cargo type
* - 01 - second accepted cargo type
* - 02 - third accepted cargo type
* - 03 - first produced cargo type
* - 04 - second produced cargo type
* @param cst the cargo suffix type (for which window is it requested)
* @param ind the industry (NULL if in fund window)
* @param ind_type the industry type
* @param indspec the industry spec
* @return the string to display
*/
static StringID GetCargoSuffix(uint cargo, CargoSuffixType cst, Industry *ind, IndustryType ind_type, const IndustrySpec *indspec)
{
if (HasBit(indspec->callback_flags, CBM_IND_CARGO_SUFFIX)) {
uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, ind, ind_type, (cst != CST_FUND) ? ind->xy : INVALID_TILE);
if (GB(callback, 0, 8) != 0xFF) return GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback);
}
return STR_EMPTY;
}
/** Names of the widgets of the dynamic place industries gui */
enum DynamicPlaceIndustriesWidgets {
DPIW_CLOSEBOX = 0,
DPIW_CAPTION,
DPIW_MATRIX_WIDGET,
DPIW_SCROLLBAR,
DPIW_INFOPANEL,
DPIW_FUND_WIDGET,
DPIW_RESIZE_WIDGET,
};
/** Widget definition of the dynamic place industries gui */
static const Widget _build_industry_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // DPIW_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_DARK_GREEN, 11, 169, 0, 13, STR_0314_FUND_NEW_INDUSTRY, STR_018C_WINDOW_TITLE_DRAG_THIS}, // DPIW_CAPTION
{ WWT_MATRIX, RESIZE_RB, COLOUR_DARK_GREEN, 0, 157, 14, 118, 0x801, STR_INDUSTRY_SELECTION_HINT}, // DPIW_MATRIX_WIDGET
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_DARK_GREEN, 158, 169, 14, 118, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // DPIW_SCROLLBAR
{ WWT_PANEL, RESIZE_RTB, COLOUR_DARK_GREEN, 0, 169, 119, 199, 0x0, STR_NULL}, // DPIW_INFOPANEL
{ WWT_TEXTBTN, RESIZE_RTB, COLOUR_DARK_GREEN, 0, 157, 200, 211, STR_FUND_NEW_INDUSTRY, STR_NULL}, // DPIW_FUND_WIDGET
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_DARK_GREEN, 158, 169, 200, 211, 0x0, STR_RESIZE_BUTTON}, // DPIW_RESIZE_WIDGET
{ WIDGETS_END},
};
/** Window definition of the dynamic place industries gui */
static const WindowDesc _build_industry_desc(
WDP_AUTO, WDP_AUTO, 170, 212, 170, 212,
WC_BUILD_INDUSTRY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE | WDF_CONSTRUCTION,
_build_industry_widgets
);
class BuildIndustryWindow : public Window {
int selected_index; ///< index of the element in the matrix
IndustryType selected_type; ///< industry corresponding to the above index
uint16 callback_timer; ///< timer counter for callback eventual verification
bool timer_enabled; ///< timer can be used
uint16 count; ///< How many industries are loaded
IndustryType index[NUM_INDUSTRYTYPES + 1]; ///< Type of industry, in the order it was loaded
StringID text[NUM_INDUSTRYTYPES + 1]; ///< Text coming from CBM_IND_FUND_MORE_TEXT (if ever)
bool enabled[NUM_INDUSTRYTYPES + 1]; ///< availability state, coming from CBID_INDUSTRY_AVAILABLE (if ever)
void SetupArrays()
{
IndustryType ind;
const IndustrySpec *indsp;
this->count = 0;
for (uint i = 0; i < lengthof(this->index); i++) {
this->index[i] = INVALID_INDUSTRYTYPE;
this->text[i] = STR_NULL;
this->enabled[i] = false;
}
if (_game_mode == GM_EDITOR) { // give room for the Many Random "button"
this->index[this->count] = INVALID_INDUSTRYTYPE;
this->count++;
this->timer_enabled = false;
}
/* Fill the arrays with industries.
* The tests performed after the enabled allow to load the industries
* In the same way they are inserted by grf (if any)
*/
for (ind = 0; ind < NUM_INDUSTRYTYPES; ind++) {
indsp = GetIndustrySpec(ind);
if (indsp->enabled){
/* Rule is that editor mode loads all industries.
* In game mode, all non raw industries are loaded too
* and raw ones are loaded only when setting allows it */
if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
/* Unselect if the industry is no longer in the list */
if (this->selected_type == ind) this->selected_index = -1;
continue;
}
this->index[this->count] = ind;
this->enabled[this->count] = (_game_mode == GM_EDITOR) || CheckIfCallBackAllowsAvailability(ind, IACT_USERCREATION);
/* Keep the selection to the correct line */
if (this->selected_type == ind) this->selected_index = this->count;
this->count++;
}
}
/* first indutry type is selected if the current selection is invalid.
* I'll be damned if there are none available ;) */
if (this->selected_index == -1) {
this->selected_index = 0;
this->selected_type = this->index[0];
}
}
public:
BuildIndustryWindow() : Window(&_build_industry_desc)
{
/* Shorten the window to the equivalant of the additionnal purchase
* info coming from the callback. SO it will only be available to its full
* height when newindistries are loaded */
if (!_loaded_newgrf_features.has_newindustries) {
this->widget[DPIW_INFOPANEL].bottom -= 44;
this->widget[DPIW_FUND_WIDGET].bottom -= 44;
this->widget[DPIW_FUND_WIDGET].top -= 44;
this->widget[DPIW_RESIZE_WIDGET].bottom -= 44;
this->widget[DPIW_RESIZE_WIDGET].top -= 44;
this->resize.height = this->height -= 44;
}
this->timer_enabled = _loaded_newgrf_features.has_newindustries;
this->vscroll.cap = 8; // rows in grid, same in scroller
this->resize.step_height = 13;
this->selected_index = -1;
this->selected_type = INVALID_INDUSTRYTYPE;
/* Initialize arrays */
this->SetupArrays();
this->callback_timer = DAY_TICKS;
this->FindWindowPlacementAndResize(&_build_industry_desc);
}
virtual void OnPaint()
{
const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
int x_str = this->widget[DPIW_INFOPANEL].left + 3;
int y_str = this->widget[DPIW_INFOPANEL].top + 3;
const Widget *wi = &this->widget[DPIW_INFOPANEL];
int max_width = wi->right - wi->left - 4;
/* Raw industries might be prospected. Show this fact by changing the string
* In Editor, you just build, while ingame, or you fund or you prospect */
if (_game_mode == GM_EDITOR) {
/* We've chosen many random industries but no industries have been specified */
if (indsp == NULL) this->enabled[this->selected_index] = _settings_game.difficulty.number_industries != 0;
this->widget[DPIW_FUND_WIDGET].data = STR_BUILD_NEW_INDUSTRY;
} else {
this->widget[DPIW_FUND_WIDGET].data = (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_PROSPECT_NEW_INDUSTRY : STR_FUND_NEW_INDUSTRY;
}
this->SetWidgetDisabledState(DPIW_FUND_WIDGET, !this->enabled[this->selected_index]);
SetVScrollCount(this, this->count);
this->DrawWidgets();
/* and now with the matrix painting */
for (byte i = 0; i < this->vscroll.cap && ((i + this->vscroll.pos) < this->count); i++) {
int offset = i * 13;
int x = 3;
int y = 16;
bool selected = this->selected_index == i + this->vscroll.pos;
if (this->index[i + this->vscroll.pos] == INVALID_INDUSTRYTYPE) {
DrawStringTruncated(20, y + offset, STR_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE, max_width - 25);
continue;
}
const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll.pos]);
/* Draw the name of the industry in white is selected, otherwise, in orange */
DrawStringTruncated(20, y + offset, indsp->name, selected ? TC_WHITE : TC_ORANGE, max_width - 25);
GfxFillRect(x, y + 1 + offset, x + 10, y + 7 + offset, selected ? 15 : 0);
GfxFillRect(x + 1, y + 2 + offset, x + 9, y + 6 + offset, indsp->map_colour);
}
if (this->selected_type == INVALID_INDUSTRYTYPE) {
DrawStringMultiLine(x_str, y_str, STR_RANDOM_INDUSTRIES_TIP, max_width, wi->bottom - wi->top - 40);
return;
}
if (_game_mode != GM_EDITOR) {
SetDParam(0, indsp->GetConstructionCost());
DrawStringTruncated(x_str, y_str, STR_482F_COST, TC_FROMSTRING, max_width);
y_str += 11;
}
/* Draw the accepted cargos, if any. Otherwhise, will print "Nothing" */
StringID str = STR_4827_REQUIRES;
byte p = 0;
SetDParam(0, STR_00D0_NOTHING);
SetDParam(1, STR_EMPTY);
for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
if (indsp->accepts_cargo[j] == CT_INVALID) continue;
if (p > 0) str++;
SetDParam(p++, GetCargo(indsp->accepts_cargo[j])->name);
SetDParam(p++, GetCargoSuffix(j, CST_FUND, NULL, this->selected_type, indsp));
}
DrawStringTruncated(x_str, y_str, str, TC_FROMSTRING, max_width);
y_str += 11;
/* Draw the produced cargos, if any. Otherwhise, will print "Nothing" */
str = STR_4827_PRODUCES;
p = 0;
SetDParam(0, STR_00D0_NOTHING);
SetDParam(1, STR_EMPTY);
for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
if (indsp->produced_cargo[j] == CT_INVALID) continue;
if (p > 0) str++;
SetDParam(p++, GetCargo(indsp->produced_cargo[j])->name);
SetDParam(p++, GetCargoSuffix(j + 3, CST_FUND, NULL, this->selected_type, indsp));
}
DrawStringTruncated(x_str, y_str, str, TC_FROMSTRING, max_width);
y_str += 11;
/* Get the additional purchase info text, if it has not already been */
if (this->text[this->selected_index] == STR_NULL) { // Have i been called already?
if (HasBit(indsp->callback_flags, CBM_IND_FUND_MORE_TEXT)) { // No. Can it be called?
uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, NULL, this->selected_type, INVALID_TILE);
if (callback_res != CALLBACK_FAILED) { // Did it failed?
StringID newtxt = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res); // No. here's the new string
this->text[this->selected_index] = newtxt; // Store it for further usage
}
}
}
/* Draw the Additional purchase text, provided by newgrf callback, if any.
* Otherwhise, will print Nothing */
str = this->text[this->selected_index];
if (str != STR_NULL && str != STR_UNDEFINED) {
SetDParam(0, str);
DrawStringMultiLine(x_str, y_str, STR_JUST_STRING, max_width, wi->bottom - wi->top - 40);
}
}
virtual void OnDoubleClick(Point pt, int widget)
{
if (widget != DPIW_MATRIX_WIDGET) return;
this->OnClick(pt, DPIW_FUND_WIDGET);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case DPIW_MATRIX_WIDGET: {
const IndustrySpec *indsp;
int y = (pt.y - this->widget[DPIW_MATRIX_WIDGET].top) / 13 + this->vscroll.pos ;
if (y >= 0 && y < count) { // Is it within the boundaries of available data?
this->selected_index = y;
this->selected_type = this->index[y];
indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
this->SetDirty();
if ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
this->selected_type == INVALID_INDUSTRYTYPE) {
/* Reset the button state if going to prospecting or "build many industries" */
this->RaiseButtons();
ResetObjectToPlace();
}
}
} break;
case DPIW_FUND_WIDGET: {
if (this->selected_type == INVALID_INDUSTRYTYPE) {
this->HandleButtonClick(DPIW_FUND_WIDGET);
if (GetNumTowns() == 0) {
ShowErrorMessage(STR_0286_MUST_BUILD_TOWN_FIRST, STR_CAN_T_GENERATE_INDUSTRIES, 0, 0);
} else {
extern void GenerateIndustries();
_generating_world = true;
GenerateIndustries();
_generating_world = false;
}
} else if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_4830_CAN_T_CONSTRUCT_THIS_INDUSTRY));
this->HandleButtonClick(DPIW_FUND_WIDGET);
} else {
HandlePlacePushButton(this, DPIW_FUND_WIDGET, SPR_CURSOR_INDUSTRY, VHM_RECT, NULL);
}
} break;
}
}
virtual void OnResize(Point new_size, Point delta)
{
/* Adjust the number of items in the matrix depending of the rezise */
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->widget[DPIW_MATRIX_WIDGET].data = (this->vscroll.cap << 8) + 1;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
bool success = true;
/* We do not need to protect ourselves against "Random Many Industries" in this mode */
const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
uint32 seed = InteractiveRandom();
if (_game_mode == GM_EDITOR) {
/* Show error if no town exists at all */
if (GetNumTowns() == 0) {
SetDParam(0, indsp->name);
ShowErrorMessage(STR_0286_MUST_BUILD_TOWN_FIRST, STR_0285_CAN_T_BUILD_HERE, pt.x, pt.y);
return;
}
_current_company = OWNER_NONE;
_generating_world = true;
_ignore_restrictions = true;
success = DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 16) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_4830_CAN_T_CONSTRUCT_THIS_INDUSTRY));
if (!success) {
SetDParam(0, indsp->name);
ShowErrorMessage(_error_message, STR_0285_CAN_T_BUILD_HERE, pt.x, pt.y);
}
_ignore_restrictions = false;
_generating_world = false;
} else {
success = DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 16) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_4830_CAN_T_CONSTRUCT_THIS_INDUSTRY));
}
/* If an industry has been built, just reset the cursor and the system */
if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
}
virtual void OnTick()
{
if (_pause_game != 0) return;
if (!this->timer_enabled) return;
if (--this->callback_timer == 0) {
/* We have just passed another day.
* See if we need to update availability of currently selected industry */
this->callback_timer = DAY_TICKS; // restart counter
const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
if (indsp->enabled) {
bool call_back_result = CheckIfCallBackAllowsAvailability(this->selected_type, IACT_USERCREATION);
/* Only if result does match the previous state would it require a redraw. */
if (call_back_result != this->enabled[this->selected_index]) {
this->enabled[this->selected_index] = call_back_result;
this->SetDirty();
}
}
}
}
virtual void OnTimeout()
{
this->RaiseButtons();
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
}
virtual void OnInvalidateData(int data = 0)
{
this->SetupArrays();
this->SetDirty();
}
};
void ShowBuildIndustryWindow()
{
if (_game_mode != GM_EDITOR && !IsValidCompanyID(_local_company)) return;
if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
new BuildIndustryWindow();
}
static void UpdateIndustryProduction(Industry *i);
static inline bool IsProductionMinimum(const Industry *i, int pt)
{
return i->production_rate[pt] == 0;
}
static inline bool IsProductionMaximum(const Industry *i, int pt)
{
return i->production_rate[pt] >= 255;
}
static inline bool IsProductionAlterable(const Industry *i)
{
return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
(i->accepts_cargo[0] == CT_INVALID || i->accepts_cargo[0] == CT_VALUABLES));
}
/** Names of the widgets of the view industry gui */
enum IndustryViewWidgets {
IVW_CLOSEBOX = 0,
IVW_CAPTION,
IVW_STICKY,
IVW_BACKGROUND,
IVW_VIEWPORT,
IVW_INFO,
IVW_GOTO,
IVW_SPACER,
IVW_RESIZE,
};
class IndustryViewWindow : public Window
{
byte editbox_line; ///< The line clicked to open the edit box
byte clicked_line; ///< The line of the button that has been clicked
byte clicked_button; ///< The button that has been clicked (to raise)
byte production_offset_y; ///< The offset of the production texts/buttons
public:
IndustryViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->flags4 |= WF_DISABLE_VP_SCROLL;
this->editbox_line = 0;
this->clicked_line = 0;
this->clicked_button = 0;
InitializeWindowViewport(this, 3, 17, 254, 86, GetIndustry(window_number)->xy + TileDiffXY(1, 1), ZOOM_LVL_INDUSTRY);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
Industry *i = GetIndustry(this->window_number);
const IndustrySpec *ind = GetIndustrySpec(i->type);
int y = this->widget[IVW_INFO].top + 1;
bool first = true;
bool has_accept = false;
SetDParam(0, this->window_number);
this->DrawWidgets();
if (HasBit(ind->callback_flags, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_flags, CBM_IND_PRODUCTION_256_TICKS)) {
for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
if (i->accepts_cargo[j] == CT_INVALID) continue;
has_accept = true;
if (first) {
DrawStringTruncated(2, y, STR_INDUSTRY_WINDOW_WAITING_FOR_PROCESSING, TC_FROMSTRING, this->widget[IVW_INFO].right - 2);
y += 10;
first = false;
}
SetDParam(0, i->accepts_cargo[j]);
SetDParam(1, i->incoming_cargo_waiting[j]);
SetDParam(2, GetCargoSuffix(j, CST_VIEW, i, i->type, ind));
DrawStringTruncated(4, y, STR_INDUSTRY_WINDOW_WAITING_STOCKPILE_CARGO, TC_FROMSTRING, this->widget[IVW_INFO].right - 4);
y += 10;
}
} else {
StringID str = STR_4827_REQUIRES;
byte p = 0;
for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
if (i->accepts_cargo[j] == CT_INVALID) continue;
has_accept = true;
if (p > 0) str++;
SetDParam(p++, GetCargo(i->accepts_cargo[j])->name);
SetDParam(p++, GetCargoSuffix(j, CST_VIEW, i, i->type, ind));
}
if (has_accept) {
DrawStringTruncated(2, y, str, TC_FROMSTRING, this->widget[IVW_INFO].right - 2);
y += 10;
}
}
first = true;
for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
if (i->produced_cargo[j] == CT_INVALID) continue;
if (first) {
if (has_accept) y += 10;
DrawStringTruncated(2, y, STR_482A_PRODUCTION_LAST_MONTH, TC_FROMSTRING, this->widget[IVW_INFO].right - 2);
y += 10;
this->production_offset_y = y;
first = false;
}
SetDParam(0, i->produced_cargo[j]);
SetDParam(1, i->last_month_production[j]);
SetDParam(2, GetCargoSuffix(j + 3, CST_VIEW, i, i->type, ind));
SetDParam(3, i->last_month_pct_transported[j] * 100 >> 8);
uint x = 4 + (IsProductionAlterable(i) ? 30 : 0);
DrawStringTruncated(x, y, STR_482B_TRANSPORTED, TC_FROMSTRING, this->widget[IVW_INFO].right - x);
/* Let's put out those buttons.. */
if (IsProductionAlterable(i)) {
DrawArrowButtons(5, y, COLOUR_YELLOW, (this->clicked_line == j + 1) ? this->clicked_button : 0,
!IsProductionMinimum(i, j), !IsProductionMaximum(i, j));
}
y += 10;
}
/* Get the extra message for the GUI */
if (HasBit(ind->callback_flags, CBM_IND_WINDOW_MORE_TEXT)) {
uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->xy);
if (callback_res != CALLBACK_FAILED) {
StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
if (message != STR_NULL && message != STR_UNDEFINED) {
const Widget *wi = &this->widget[IVW_INFO];
y += 10;
PrepareTextRefStackUsage(6);
/* Use all the available space left from where we stand up to the end of the window */
y += DrawStringMultiLine(2, y, message, wi->right - wi->left - 4, -1);
StopTextRefStackUsage();
}
}
}
if (y > this->widget[IVW_INFO].bottom) {
this->SetDirty();
ResizeWindowForWidget(this, IVW_INFO, 0, y - this->widget[IVW_INFO].top);
this->SetDirty();
return;
}
this->DrawViewport();
}
virtual void OnClick(Point pt, int widget)
{
Industry *i;
switch (widget) {
case IVW_INFO: {
int line, x;
i = GetIndustry(this->window_number);
/* We should work if needed.. */
if (!IsProductionAlterable(i)) return;
x = pt.x;
line = (pt.y - this->production_offset_y) / 10;
if (pt.y >= this->production_offset_y && IsInsideMM(line, 0, 2) && i->produced_cargo[line] != CT_INVALID) {
if (IsInsideMM(x, 5, 25) ) {
/* Clicked buttons, decrease or increase production */
if (x < 15) {
if (IsProductionMinimum(i, line)) return;
i->production_rate[line] = max(i->production_rate[line] / 2, 0);
} else {
/* a zero production industry is unlikely to give anything but zero, so push it a little bit */
int new_prod = i->production_rate[line] == 0 ? 1 : i->production_rate[line] * 2;
if (IsProductionMaximum(i, line)) return;
i->production_rate[line] = minu(new_prod, 255);
}
UpdateIndustryProduction(i);
this->SetDirty();
this->flags4 |= WF_TIMEOUT_BEGIN;
this->clicked_line = line + 1;
this->clicked_button = (x < 15 ? 1 : 2);
} else if (IsInsideMM(x, 34, 160)) {
/* clicked the text */
this->editbox_line = line;
SetDParam(0, i->production_rate[line] * 8);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_CONFIG_GAME_PRODUCTION, 10, 100, this, CS_ALPHANUMERAL, QSF_NONE);
}
}
} break;
case IVW_GOTO:
i = GetIndustry(this->window_number);
if (_ctrl_pressed) {
ShowExtraViewPortWindow(i->xy + TileDiffXY(1, 1));
} else {
ScrollMainWindowToTile(i->xy + TileDiffXY(1, 1));
}
break;
}
}
virtual void OnTimeout()
{
this->clicked_line = 0;
this->clicked_button = 0;
this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta)
{
this->viewport->width += delta.x;
this->viewport->height += delta.y;
this->viewport->virtual_width += delta.x;
this->viewport->virtual_height += delta.y;
this->viewport->dest_scrollpos_x -= delta.x;
this->viewport->dest_scrollpos_y -= delta.y;
UpdateViewportPosition(this);
}
virtual void OnQueryTextFinished(char *str)
{
if (StrEmpty(str)) return;
Industry *i = GetIndustry(this->window_number);
int line = this->editbox_line;
i->production_rate[line] = ClampU(atoi(str), 0, 255);
UpdateIndustryProduction(i);
this->SetDirty();
}
};
static void UpdateIndustryProduction(Industry *i)
{
for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
if (i->produced_cargo[j] != CT_INVALID) {
i->last_month_production[j] = 8 * i->production_rate[j];
}
}
}
/** Widget definition of the view industy gui */
static const Widget _industry_view_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_CREAM, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // IVW_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_CREAM, 11, 247, 0, 13, STR_4801, STR_018C_WINDOW_TITLE_DRAG_THIS}, // IVW_CAPTION
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_CREAM, 248, 259, 0, 13, 0x0, STR_STICKY_BUTTON}, // IVW_STICKY
{ WWT_PANEL, RESIZE_RB, COLOUR_CREAM, 0, 259, 14, 105, 0x0, STR_NULL}, // IVW_BACKGROUND
{ WWT_INSET, RESIZE_RB, COLOUR_CREAM, 2, 257, 16, 103, 0x0, STR_NULL}, // IVW_VIEWPORT
{ WWT_PANEL, RESIZE_RTB, COLOUR_CREAM, 0, 259, 106, 107, 0x0, STR_NULL}, // IVW_INFO
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_CREAM, 0, 129, 108, 119, STR_00E4_LOCATION, STR_482C_CENTER_THE_MAIN_VIEW_ON}, // IVW_GOTO
{ WWT_PANEL, RESIZE_RTB, COLOUR_CREAM, 130, 247, 108, 119, 0x0, STR_NULL}, // IVW_SPACER
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_CREAM, 248, 259, 108, 119, 0x0, STR_RESIZE_BUTTON}, // IVW_RESIZE
{ WIDGETS_END},
};
/** Window definition of the view industy gui */
static const WindowDesc _industry_view_desc(
WDP_AUTO, WDP_AUTO, 260, 120, 260, 120,
WC_INDUSTRY_VIEW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_industry_view_widgets
);
void ShowIndustryViewWindow(int industry)
{
AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
}
/** Names of the widgets of the industry directory gui */
enum IndustryDirectoryWidgets {
IDW_CLOSEBOX = 0,
IDW_CAPTION,
IDW_STICKY,
IDW_DROPDOWN_ORDER,
IDW_DROPDOWN_CRITERIA,
IDW_SPACER,
IDW_INDUSTRY_LIST,
IDW_SCROLLBAR,
IDW_RESIZE,
};
/** Widget definition of the industy directory gui */
static const Widget _industry_directory_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // IDW_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_BROWN, 11, 415, 0, 13, STR_INDUSTRYDIR_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // IDW_CAPTION
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_BROWN, 416, 427, 0, 13, 0x0, STR_STICKY_BUTTON}, // IDW_STICKY
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_BROWN, 0, 80, 14, 25, STR_SORT_BY, STR_SORT_ORDER_TIP}, // IDW_DROPDOWN_ORDER
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_BROWN, 81, 243, 14, 25, 0x0, STR_SORT_CRITERIA_TIP}, // IDW_DROPDOWN_CRITERIA
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_BROWN, 244, 415, 14, 25, 0x0, STR_NULL}, // IDW_SPACER
{ WWT_PANEL, RESIZE_RB, COLOUR_BROWN, 0, 415, 26, 189, 0x0, STR_INDUSTRYDIR_LIST_CAPTION}, // IDW_INDUSRTY_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_BROWN, 416, 427, 14, 177, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // IDW_SCROLLBAR
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_BROWN, 416, 427, 178, 189, 0x0, STR_RESIZE_BUTTON}, // IDW_RESIZE
{ WIDGETS_END},
};
typedef GUIList<const Industry*> GUIIndustryList;
/**
* The list of industries.
*/
class IndustryDirectoryWindow : public Window {
protected:
/* Runtime saved values */
static Listing last_sorting;
static const Industry *last_industry;
/* Constants for sorting stations */
static const StringID sorter_names[];
static GUIIndustryList::SortFunction * const sorter_funcs[];
GUIIndustryList industries;
/** (Re)Build industries list */
void BuildIndustriesList()
{
if (!this->industries.NeedRebuild()) return;
this->industries.Clear();
DEBUG(misc, 3, "Building industry list");
const Industry *i;
FOR_ALL_INDUSTRIES(i) {
*this->industries.Append() = i;
}
this->industries.Compact();
this->industries.RebuildDone();
}
/**
* Returns percents of cargo transported if industry produces this cargo, else -1
*
* @param i industry to check
* @param id cargo slot
* @return percents of cargo transported, or -1 if industry doesn't use this cargo slot
*/
static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
{
assert(id < lengthof(i->produced_cargo));
if (i->produced_cargo[id] == CT_INVALID) return 101;
return i->last_month_pct_transported[id] * 100 >> 8;
}
/**
* Returns value representing industry's transported cargo
* percentage for industry sorting
*
* @param i industry to check
* @return value used for sorting
*/
static int GetCargoTransportedSortValue(const Industry *i)
{
int p1 = GetCargoTransportedPercentsIfValid(i, 0);
int p2 = GetCargoTransportedPercentsIfValid(i, 1);
if (p1 > p2) Swap(p1, p2); // lower value has higher priority
return (p1 << 8) + p2;
}
/** Sort industries by name */
static int CDECL IndustryNameSorter(const Industry * const *a, const Industry * const *b)
{
static char buf_cache[96];
static char buf[96];
SetDParam(0, (*a)->town->index);
GetString(buf, STR_TOWN, lastof(buf));
if (*b != last_industry) {
last_industry = *b;
SetDParam(0, (*b)->town->index);
GetString(buf_cache, STR_TOWN, lastof(buf_cache));
}
return strcmp(buf, buf_cache);
}
/** Sort industries by type and name */
static int CDECL IndustryTypeSorter(const Industry * const *a, const Industry * const *b)
{
int r = (*a)->type - (*b)->type;
return (r == 0) ? IndustryNameSorter(a, b) : r;
}
/** Sort industries by production and name */
static int CDECL IndustryProductionSorter(const Industry * const *a, const Industry * const *b)
{
int r = 0;
if ((*a)->produced_cargo[0] == CT_INVALID) {
if ((*b)->produced_cargo[0] != CT_INVALID) return -1;
} else {
if ((*b)->produced_cargo[0] == CT_INVALID) return 1;
r = ((*a)->last_month_production[0] + (*a)->last_month_production[1]) -
((*b)->last_month_production[0] + (*b)->last_month_production[1]);
}
return (r == 0) ? IndustryNameSorter(a, b) : r;
}
/** Sort industries by transported cargo and name */
static int CDECL IndustryTransportedCargoSorter(const Industry * const *a, const Industry * const *b)
{
int r = GetCargoTransportedSortValue(*a) - GetCargoTransportedSortValue(*b);
return (r == 0) ? IndustryNameSorter(a, b) : r;
}
/** Sort the industries list */
void SortIndustriesList()
{
if (!this->industries.Sort()) return;
/* Reset name sorter sort cache */
this->last_industry = NULL;
/* Set the modified widget dirty */
this->InvalidateWidget(IDW_INDUSTRY_LIST);
}
public:
IndustryDirectoryWindow(const WindowDesc *desc, WindowNumber number) : Window(desc, number)
{
this->vscroll.cap = 16;
this->resize.height = this->height - 6 * 10; // minimum 10 items
this->resize.step_height = 10;
this->FindWindowPlacementAndResize(desc);
this->industries.SetListing(this->last_sorting);
this->industries.SetSortFuncs(this->sorter_funcs);
this->industries.ForceRebuild();
this->industries.NeedResort();
this->SortIndustriesList();
this->widget[IDW_DROPDOWN_CRITERIA].data = this->sorter_names[this->industries.SortType()];
}
~IndustryDirectoryWindow()
{
this->last_sorting = this->industries.GetListing();
}
virtual void OnPaint()
{
BuildIndustriesList();
SortIndustriesList();
SetVScrollCount(this, this->industries.Length());
this->DrawWidgets();
this->DrawSortButtonState(IDW_DROPDOWN_ORDER, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
int max = min(this->vscroll.pos + this->vscroll.cap, this->industries.Length());
int y = 28; // start of the list-widget
for (int n = this->vscroll.pos; n < max; ++n) {
const Industry *i = this->industries[n];
const IndustrySpec *indsp = GetIndustrySpec(i->type);
byte p = 0;
/* Industry name */
SetDParam(p++, i->index);
/* Industry productions */
for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
if (i->produced_cargo[j] == CT_INVALID) continue;
SetDParam(p++, i->produced_cargo[j]);
SetDParam(p++, i->last_month_production[j]);
SetDParam(p++, GetCargoSuffix(j + 3, CST_DIR, (Industry*)i, i->type, indsp));
}
/* Transported productions */
for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
if (i->produced_cargo[j] == CT_INVALID) continue;
SetDParam(p++, i->last_month_pct_transported[j] * 100 >> 8);
}
/* Drawing the right string */
StringID str = STR_INDUSTRYDIR_ITEM_NOPROD;
if (p != 1) str = (p == 5) ? STR_INDUSTRYDIR_ITEM : STR_INDUSTRYDIR_ITEM_TWO;
DrawStringTruncated(4, y, str, TC_FROMSTRING, this->widget[IDW_INDUSTRY_LIST].right - 4);
y += 10;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case IDW_DROPDOWN_ORDER:
this->industries.ToggleSortOrder();
this->SetDirty();
break;
case IDW_DROPDOWN_CRITERIA:
ShowDropDownMenu(this, this->sorter_names, this->industries.SortType(), IDW_DROPDOWN_CRITERIA, 0, 0);
break;
case IDW_INDUSTRY_LIST: {
int y = (pt.y - 28) / 10;
uint16 p;
if (!IsInsideMM(y, 0, this->vscroll.cap)) return;
p = y + this->vscroll.pos;
if (p < this->industries.Length()) {
if (_ctrl_pressed) {
ShowExtraViewPortWindow(this->industries[p]->xy);
} else {
ScrollMainWindowToTile(this->industries[p]->xy);
}
}
} break;
}
}
virtual void OnDropdownSelect(int widget, int index)
{
if (this->industries.SortType() != index) {
this->industries.SetSortType(index);
this->widget[IDW_DROPDOWN_CRITERIA].data = this->sorter_names[this->industries.SortType()];
this->SetDirty();
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / 10;
}
virtual void OnInvalidateData(int data)
{
if (data == 0) {
this->industries.ForceRebuild();
} else {
this->industries.ForceResort();
}
this->InvalidateWidget(IDW_INDUSTRY_LIST);
}
};
Listing IndustryDirectoryWindow::last_sorting = {false, 0};
const Industry *IndustryDirectoryWindow::last_industry = NULL;
/* Availible station sorting functions */
GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
&IndustryNameSorter,
&IndustryTypeSorter,
&IndustryProductionSorter,
&IndustryTransportedCargoSorter
};
/* Names of the sorting functions */
const StringID IndustryDirectoryWindow::sorter_names[] = {
STR_SORT_BY_DROPDOWN_NAME,
STR_SORT_BY_TYPE,
STR_SORT_BY_PRODUCTION,
STR_SORT_BY_TRANSPORTED,
INVALID_STRING_ID
};
/** Window definition of the industy directory gui */
static const WindowDesc _industry_directory_desc(
WDP_AUTO, WDP_AUTO, 428, 190, 428, 190,
WC_INDUSTRY_DIRECTORY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_industry_directory_widgets
);
void ShowIndustryDirectory()
{
AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
}
| 35,249
|
C++
|
.cpp
| 851
| 38.128085
| 180
| 0.665849
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,066
|
aircraft_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/aircraft_cmd.cpp
|
/* $Id$ */
/** @file aircraft_cmd.cpp
* This file deals with aircraft and airport movements functionalities */
#include "stdafx.h"
#include "aircraft.h"
#include "debug.h"
#include "landscape.h"
#include "news_func.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "newgrf_sound.h"
#include "spritecache.h"
#include "strings_func.h"
#include "command_func.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "functions.h"
#include "variables.h"
#include "cheat_type.h"
#include "autoreplace_func.h"
#include "autoreplace_gui.h"
#include "gfx_func.h"
#include "ai/ai.hpp"
#include "company_func.h"
#include "effectvehicle_func.h"
#include "settings_type.h"
#include "table/strings.h"
#include "table/sprites.h"
void Aircraft::UpdateDeltaXY(Direction direction)
{
uint32 x;
#define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
switch (this->subtype) {
default: NOT_REACHED();
case AIR_AIRCRAFT:
case AIR_HELICOPTER:
switch (this->u.air.state) {
case ENDTAKEOFF:
case LANDING:
case HELILANDING:
case FLYING: x = MKIT(24, 24, -1, -1); break;
default: x = MKIT( 2, 2, -1, -1); break;
}
this->z_extent = 5;
break;
case AIR_SHADOW: this->z_extent = 1; x = MKIT(2, 2, 0, 0); break;
case AIR_ROTOR: this->z_extent = 1; x = MKIT(2, 2, -1, -1); break;
}
#undef MKIT
this->x_offs = GB(x, 0, 8);
this->y_offs = GB(x, 8, 8);
this->x_extent = GB(x, 16, 8);
this->y_extent = GB(x, 24, 8);
}
/** this maps the terminal to its corresponding state and block flag
* currently set for 10 terms, 4 helipads */
static const byte _airport_terminal_state[] = {2, 3, 4, 5, 6, 7, 19, 20, 0, 0, 8, 9, 21, 22};
static const byte _airport_terminal_flag[] = {0, 1, 2, 3, 4, 5, 22, 23, 0, 0, 6, 7, 24, 25};
static bool AirportMove(Vehicle *v, const AirportFTAClass *apc);
static bool AirportSetBlocks(Vehicle *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
static bool AirportHasBlock(Vehicle *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
static bool AirportFindFreeTerminal(Vehicle *v, const AirportFTAClass *apc);
static bool AirportFindFreeHelipad(Vehicle *v, const AirportFTAClass *apc);
static void CrashAirplane(Vehicle *v);
static const SpriteID _aircraft_sprite[] = {
0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
0x0EBD, 0x0EC5
};
/** Helicopter rotor animation states */
enum HelicopterRotorStates {
HRS_ROTOR_STOPPED,
HRS_ROTOR_MOVING_1,
HRS_ROTOR_MOVING_2,
HRS_ROTOR_MOVING_3,
};
/** Find the nearest hangar to v
* INVALID_STATION is returned, if the company does not have any suitable
* airports (like helipads only)
* @param v vehicle looking for a hangar
* @return the StationID if one is found, otherwise, INVALID_STATION
*/
static StationID FindNearestHangar(const Vehicle *v)
{
const Station *st;
uint best = 0;
StationID index = INVALID_STATION;
TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
FOR_ALL_STATIONS(st) {
if (st->owner != v->owner || !(st->facilities & FACIL_AIRPORT)) continue;
const AirportFTAClass *afc = st->Airport();
if (afc->nof_depots == 0 || (
/* don't crash the plane if we know it can't land at the airport */
afc->flags & AirportFTAClass::SHORT_STRIP &&
AircraftVehInfo(v->engine_type)->subtype & AIR_FAST &&
!_cheats.no_jetcrash.value
)) {
continue;
}
/* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
uint distance = DistanceSquare(vtile, st->airport_tile);
if (distance < best || index == INVALID_STATION) {
best = distance;
index = st->index;
}
}
return index;
}
#if 0
/** Check if given vehicle has a goto hangar in his orders
* @param v vehicle to inquiry
* @return true if vehicle v has an airport in the schedule, that has a hangar */
static bool HaveHangarInOrderList(Vehicle *v)
{
const Order *order;
FOR_VEHICLE_ORDERS(v, order) {
const Station *st = GetStation(order->station);
if (st->owner == v->owner && st->facilities & FACIL_AIRPORT) {
/* If an airport doesn't have a hangar, skip it */
if (st->Airport()->nof_depots != 0)
return true;
}
}
return false;
}
#endif
SpriteID Aircraft::GetImage(Direction direction) const
{
uint8 spritenum = this->spritenum;
if (is_custom_sprite(spritenum)) {
SpriteID sprite = GetCustomVehicleSprite(this, direction);
if (sprite != 0) return sprite;
spritenum = GetEngine(this->engine_type)->image_index;
}
return direction + _aircraft_sprite[spritenum];
}
SpriteID GetRotorImage(const Vehicle *v)
{
assert(v->subtype == AIR_HELICOPTER);
const Vehicle *w = v->Next()->Next();
if (is_custom_sprite(v->spritenum)) {
SpriteID sprite = GetCustomRotorSprite(v, false);
if (sprite != 0) return sprite;
}
/* Return standard rotor sprites if there are no custom sprites for this helicopter */
return SPR_ROTOR_STOPPED + w->u.air.state;
}
static SpriteID GetAircraftIcon(EngineID engine)
{
uint8 spritenum = AircraftVehInfo(engine)->image_index;
if (is_custom_sprite(spritenum)) {
SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W);
if (sprite != 0) return sprite;
spritenum = GetEngine(engine)->image_index;
}
return 6 + _aircraft_sprite[spritenum];
}
void DrawAircraftEngine(int x, int y, EngineID engine, SpriteID pal)
{
DrawSprite(GetAircraftIcon(engine), pal, x, y);
if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
SpriteID rotor_sprite = GetCustomRotorIcon(engine);
if (rotor_sprite == 0) rotor_sprite = SPR_ROTOR_STOPPED;
DrawSprite(rotor_sprite, PAL_NONE, x, y - 5);
}
}
/** Get the size of the sprite of an aircraft sprite heading west (used for lists)
* @param engine The engine to get the sprite from
* @param width The width of the sprite
* @param height The height of the sprite
*/
void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height)
{
const Sprite *spr = GetSprite(GetAircraftIcon(engine), ST_NORMAL);
width = spr->width;
height = spr->height;
}
/**
* Calculates cargo capacity based on an aircraft's passenger
* and mail capacities.
* @param cid Which cargo type to calculate a capacity for.
* @param avi Which engine to find a cargo capacity for.
* @return New cargo capacity value.
*/
uint16 AircraftDefaultCargoCapacity(CargoID cid, const AircraftVehicleInfo *avi)
{
assert(cid != CT_INVALID);
/* An aircraft can carry twice as much goods as normal cargo,
* and four times as many passengers. */
switch (cid) {
case CT_PASSENGERS:
return avi->passenger_capacity;
case CT_MAIL:
return avi->passenger_capacity + avi->mail_capacity;
case CT_GOODS:
return (avi->passenger_capacity + avi->mail_capacity) / 2;
default:
return (avi->passenger_capacity + avi->mail_capacity) / 4;
}
}
/** Build an aircraft.
* @param tile tile of depot where aircraft is built
* @param flags for command
* @param p1 aircraft type being built (engine)
* @param p2 unused
* return result of operation. Could be cost, error
*/
CommandCost CmdBuildAircraft(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsEngineBuildable(p1, VEH_AIRCRAFT, _current_company)) return_cmd_error(STR_AIRCRAFT_NOT_AVAILABLE);
const AircraftVehicleInfo *avi = AircraftVehInfo(p1);
const Engine *e = GetEngine(p1);
CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
/* Engines without valid cargo should not be available */
if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
/* to just query the cost, it is not neccessary to have a valid tile (automation/AI) */
if (flags & DC_QUERY_COST) return value;
if (!IsHangarTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
/* Prevent building aircraft types at places which can't handle them */
if (!CanVehicleUseStation(p1, GetStationByTile(tile))) return CMD_ERROR;
/* Allocate 2 or 3 vehicle structs, depending on type
* vl[0] = aircraft, vl[1] = shadow, [vl[2] = rotor] */
Vehicle *vl[3];
if (!Vehicle::AllocateList(vl, avi->subtype & AIR_CTOL ? 2 : 3)) {
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
}
UnitID unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_AIRCRAFT);
if (unit_num > _settings_game.vehicle.max_aircraft)
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
if (flags & DC_EXEC) {
Vehicle *v = vl[0]; // aircraft
Vehicle *u = vl[1]; // shadow
v = new (v) Aircraft();
u = new (u) Aircraft();
v->unitnumber = unit_num;
v->direction = DIR_SE;
v->owner = u->owner = _current_company;
v->tile = tile;
// u->tile = 0;
uint x = TileX(tile) * TILE_SIZE + 5;
uint y = TileY(tile) * TILE_SIZE + 3;
v->x_pos = u->x_pos = x;
v->y_pos = u->y_pos = y;
u->z_pos = GetSlopeZ(x, y);
v->z_pos = u->z_pos + 1;
v->running_ticks = 0;
// u->delta_x = u->delta_y = 0;
v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
u->vehstatus = VS_HIDDEN | VS_UNCLICKABLE | VS_SHADOW;
v->spritenum = avi->image_index;
// v->cargo_count = u->number_of_pieces = 0;
v->cargo_cap = avi->passenger_capacity;
u->cargo_cap = avi->mail_capacity;
v->cargo_type = e->GetDefaultCargoType();
u->cargo_type = CT_MAIL;
v->cargo_subtype = 0;
v->name = NULL;
// v->next_order_param = v->next_order = 0;
// v->load_unload_time_rem = 0;
// v->progress = 0;
v->last_station_visited = INVALID_STATION;
// v->destination_coords = 0;
v->max_speed = avi->max_speed;
v->acceleration = avi->acceleration;
v->engine_type = p1;
u->engine_type = p1;
v->subtype = (avi->subtype & AIR_CTOL ? AIR_AIRCRAFT : AIR_HELICOPTER);
v->UpdateDeltaXY(INVALID_DIR);
v->value = value.GetCost();
u->subtype = AIR_SHADOW;
u->UpdateDeltaXY(INVALID_DIR);
if (v->cargo_type != CT_PASSENGERS) {
uint16 callback = CALLBACK_FAILED;
if (HasBit(EngInfo(p1)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
}
if (callback == CALLBACK_FAILED) {
/* Callback failed, or not executed; use the default cargo capacity */
v->cargo_cap = AircraftDefaultCargoCapacity(v->cargo_type, avi);
} else {
v->cargo_cap = callback;
}
/* Set the 'second compartent' capacity to none */
u->cargo_cap = 0;
}
v->reliability = e->reliability;
v->reliability_spd_dec = e->reliability_spd_dec;
v->max_age = e->lifelength * DAYS_IN_LEAP_YEAR;
_new_vehicle_id = v->index;
/* When we click on hangar we know the tile it is on. By that we know
* its position in the array of depots the airport has.....we can search
* layout for #th position of depot. Since layout must start with a listing
* of all depots, it is simple */
for (uint i = 0;; i++) {
const Station *st = GetStationByTile(tile);
const AirportFTAClass *apc = st->Airport();
assert(i != apc->nof_depots);
if (st->airport_tile + ToTileIndexDiff(apc->airport_depots[i]) == tile) {
assert(apc->layout[i].heading == HANGAR);
v->u.air.pos = apc->layout[i].position;
break;
}
}
v->u.air.state = HANGAR;
v->u.air.previous_pos = v->u.air.pos;
v->u.air.targetairport = GetStationIndex(tile);
v->SetNext(u);
v->service_interval = _settings_game.vehicle.servint_aircraft;
v->date_of_last_service = _date;
v->build_year = u->build_year = _cur_year;
v->cur_image = u->cur_image = 0xEA0;
v->random_bits = VehicleRandomBits();
u->random_bits = VehicleRandomBits();
v->vehicle_flags = 0;
if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
UpdateAircraftCache(v);
VehicleMove(v, false);
VehicleMove(u, false);
/* Aircraft with 3 vehicles (chopper)? */
if (v->subtype == AIR_HELICOPTER) {
Vehicle *w = vl[2];
w = new (w) Aircraft();
w->engine_type = p1;
w->direction = DIR_N;
w->owner = _current_company;
w->x_pos = v->x_pos;
w->y_pos = v->y_pos;
w->z_pos = v->z_pos + 5;
w->vehstatus = VS_HIDDEN | VS_UNCLICKABLE;
w->spritenum = 0xFF;
w->subtype = AIR_ROTOR;
w->cur_image = SPR_ROTOR_STOPPED;
w->random_bits = VehicleRandomBits();
/* Use rotor's air.state to store the rotor animation frame */
w->u.air.state = HRS_ROTOR_STOPPED;
w->UpdateDeltaXY(INVALID_DIR);
u->SetNext(w);
VehicleMove(w, false);
}
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
InvalidateWindow(WC_COMPANY, v->owner);
if (IsLocalCompany())
InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Aircraft window
GetCompany(_current_company)->num_engines[p1]++;
}
return value;
}
/** Sell an aircraft.
* @param tile unused
* @param flags for command type
* @param p1 vehicle ID to be sold
* @param p2 unused
* @return result of operation. Error or sold value
*/
CommandCost CmdSellAircraft(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_AIRCRAFT || !CheckOwnership(v->owner)) return CMD_ERROR;
if (!v->IsStoppedInDepot()) return_cmd_error(STR_A01B_AIRCRAFT_MUST_BE_STOPPED);
if (HASBITS(v->vehstatus, VS_CRASHED)) return_cmd_error(STR_CAN_T_SELL_DESTROYED_VEHICLE);
CommandCost ret(EXPENSES_NEW_VEHICLES, -v->value);
if (flags & DC_EXEC) {
delete v;
}
return ret;
}
bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
{
const Station *st = GetTargetAirportIfValid(this);
/* If the station is not a valid airport or if it has no hangars */
if (st == NULL || st->Airport()->nof_depots == 0) {
/* the aircraft has to search for a hangar on its own */
StationID station = FindNearestHangar(this);
if (station == INVALID_STATION) return false;
st = GetStation(station);
}
if (location != NULL) *location = st->xy;
if (destination != NULL) *destination = st->index;
return true;
}
/** Send an aircraft to the hangar.
* @param tile unused
* @param flags for command type
* @param p1 vehicle ID to send to the hangar
* @param p2 various bitmasked elements
* - p2 bit 0-3 - DEPOT_ flags (see vehicle.h)
* - p2 bit 8-10 - VLW flag (for mass goto depot)
* @return o if everything went well
*/
CommandCost CmdSendAircraftToHangar(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (p2 & DEPOT_MASS_SEND) {
/* Mass goto depot requested */
if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
return SendAllVehiclesToDepot(VEH_AIRCRAFT, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
}
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_AIRCRAFT) return CMD_ERROR;
return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
}
/** Refits an aircraft to the specified cargo type.
* @param tile unused
* @param flags for command type
* @param p1 vehicle ID of the aircraft to refit
* @param p2 various bitstuffed elements
* - p2 = (bit 0-7) - the new cargo type to refit to
* - p2 = (bit 8-15) - the new cargo subtype to refit to
* - p2 = (bit 16) - refit only this vehicle (ignored)
* @return cost of refit or error
*/
CommandCost CmdRefitAircraft(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
byte new_subtype = GB(p2, 8, 8);
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_AIRCRAFT || !CheckOwnership(v->owner)) return CMD_ERROR;
if (!v->IsStoppedInDepot()) return_cmd_error(STR_A01B_AIRCRAFT_MUST_BE_STOPPED);
if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_CAN_T_REFIT_DESTROYED_VEHICLE);
/* Check cargo */
CargoID new_cid = GB(p2, 0, 8);
if (new_cid >= NUM_CARGO || !CanRefitTo(v->engine_type, new_cid)) return CMD_ERROR;
/* Check the refit capacity callback */
uint16 callback = CALLBACK_FAILED;
if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
/* Back up the existing cargo type */
CargoID temp_cid = v->cargo_type;
byte temp_subtype = v->cargo_subtype;
v->cargo_type = new_cid;
v->cargo_subtype = new_subtype;
callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
/* Restore the cargo type */
v->cargo_type = temp_cid;
v->cargo_subtype = temp_subtype;
}
const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
uint pass;
if (callback == CALLBACK_FAILED) {
/* If the callback failed, or wasn't executed, use the aircraft's
* default cargo capacity */
pass = AircraftDefaultCargoCapacity(new_cid, avi);
} else {
pass = callback;
}
_returned_refit_capacity = pass;
CommandCost cost;
if (new_cid != v->cargo_type) {
cost = GetRefitCost(v->engine_type);
}
if (flags & DC_EXEC) {
v->cargo_cap = pass;
Vehicle *u = v->Next();
uint mail = IsCargoInClass(new_cid, CC_PASSENGERS) ? avi->mail_capacity : 0;
u->cargo_cap = mail;
v->cargo.Truncate(v->cargo_type == new_cid ? pass : 0);
u->cargo.Truncate(v->cargo_type == new_cid ? mail : 0);
v->cargo_type = new_cid;
v->cargo_subtype = new_subtype;
v->colourmap = PAL_NONE; // invalidate vehicle colour map
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
}
return cost;
}
static void CheckIfAircraftNeedsService(Vehicle *v)
{
if (_settings_game.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
if (v->IsInDepot()) {
VehicleServiceInDepot(v);
return;
}
const Station *st = GetStation(v->current_order.GetDestination());
/* only goto depot if the target airport has terminals (eg. it is airport) */
if (st->IsValid() && st->airport_tile != INVALID_TILE && st->Airport()->terminals != NULL) {
// printf("targetairport = %d, st->index = %d\n", v->u.air.targetairport, st->index);
// v->u.air.targetairport = st->index;
v->current_order.MakeGoToDepot(st->index, ODTFB_SERVICE);
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
} else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
v->current_order.MakeDummy();
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
}
Money Aircraft::GetRunningCost() const
{
return GetVehicleProperty(this, 0x0E, AircraftVehInfo(this->engine_type)->running_cost) * _price.aircraft_running;
}
void Aircraft::OnNewDay()
{
if (!IsNormalAircraft(this)) return;
if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
CheckOrders(this);
CheckVehicleBreakdown(this);
AgeVehicle(this);
CheckIfAircraftNeedsService(this);
if (this->running_ticks == 0) return;
CommandCost cost(EXPENSES_AIRCRAFT_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
this->profit_this_year -= cost.GetCost();
this->running_ticks = 0;
SubtractMoneyFromCompanyFract(this->owner, cost);
InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
InvalidateWindowClasses(WC_AIRCRAFT_LIST);
}
static void AgeAircraftCargo(Vehicle *v)
{
if (_age_cargo_skip_counter != 0) return;
do {
v->cargo.AgeCargo();
v = v->Next();
} while (v != NULL);
}
static void HelicopterTickHandler(Vehicle *v)
{
Vehicle *u = v->Next()->Next();
if (u->vehstatus & VS_HIDDEN) return;
/* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
* loading/unloading at a terminal or stopped */
if (v->current_order.IsType(OT_LOADING) || (v->vehstatus & VS_STOPPED)) {
if (u->cur_speed != 0) {
u->cur_speed++;
if (u->cur_speed >= 0x80 && u->u.air.state == HRS_ROTOR_MOVING_3) {
u->cur_speed = 0;
}
}
} else {
if (u->cur_speed == 0)
u->cur_speed = 0x70;
if (u->cur_speed >= 0x50)
u->cur_speed--;
}
int tick = ++u->tick_counter;
int spd = u->cur_speed >> 4;
SpriteID img;
if (spd == 0) {
u->u.air.state = HRS_ROTOR_STOPPED;
img = GetRotorImage(v);
if (u->cur_image == img) return;
} else if (tick >= spd) {
u->tick_counter = 0;
u->u.air.state++;
if (u->u.air.state > HRS_ROTOR_MOVING_3) u->u.air.state = HRS_ROTOR_MOVING_1;
img = GetRotorImage(v);
} else {
return;
}
u->cur_image = img;
VehicleMove(u, true);
}
void SetAircraftPosition(Vehicle *v, int x, int y, int z)
{
v->x_pos = x;
v->y_pos = y;
v->z_pos = z;
v->cur_image = v->GetImage(v->direction);
if (v->subtype == AIR_HELICOPTER) v->Next()->Next()->cur_image = GetRotorImage(v);
VehicleMove(v, true);
Vehicle *u = v->Next();
int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
u->x_pos = x;
u->y_pos = y - ((v->z_pos-GetSlopeZ(safe_x, safe_y)) >> 3);;
safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
u->z_pos = GetSlopeZ(safe_x, safe_y);
u->cur_image = v->cur_image;
VehicleMove(u, true);
u = u->Next();
if (u != NULL) {
u->x_pos = x;
u->y_pos = y;
u->z_pos = z + 5;
VehicleMove(u, true);
}
}
/** Handle Aircraft specific tasks when a an Aircraft enters a hangar
* @param *v Vehicle that enters the hangar
*/
void HandleAircraftEnterHangar(Vehicle *v)
{
v->subspeed = 0;
v->progress = 0;
Vehicle *u = v->Next();
u->vehstatus |= VS_HIDDEN;
u = u->Next();
if (u != NULL) {
u->vehstatus |= VS_HIDDEN;
u->cur_speed = 0;
}
SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
}
static void PlayAircraftSound(const Vehicle *v)
{
if (!PlayVehicleSound(v, VSE_START)) {
SndPlayVehicleFx(AircraftVehInfo(v->engine_type)->sfx, v);
}
}
void UpdateAircraftCache(Vehicle *v)
{
uint max_speed = GetVehicleProperty(v, 0x0C, 0);
if (max_speed != 0) {
/* Convert from original units to (approx) km/h */
max_speed = (max_speed * 129) / 10;
v->u.air.cached_max_speed = max_speed;
} else {
v->u.air.cached_max_speed = 0xFFFF;
}
}
/**
* Special velocities for aircraft
*/
enum AircraftSpeedLimits {
SPEED_LIMIT_TAXI = 50, ///< Maximum speed of an aircraft while taxiing
SPEED_LIMIT_APPROACH = 230, ///< Maximum speed of an aircraft on finals
SPEED_LIMIT_BROKEN = 320, ///< Maximum speed of an aircraft that is broken
SPEED_LIMIT_HOLD = 425, ///< Maximum speed of an aircraft that flies the holding pattern
SPEED_LIMIT_NONE = 0xFFFF ///< No environmental speed limit. Speed limit is type dependent
};
/**
* Sets the new speed for an aircraft
* @param v The vehicle for which the speed should be obtained
* @param speed_limit The maximum speed the vehicle may have.
* @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
* @return The number of position updates needed within the tick
*/
static int UpdateAircraftSpeed(Vehicle *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
{
uint spd = v->acceleration * 16;
byte t;
/* Adjust speed limits by plane speed factor to prevent taxiing
* and take-off speeds being too low. */
speed_limit *= _settings_game.vehicle.plane_speed;
if (v->u.air.cached_max_speed < speed_limit) {
if (v->cur_speed < speed_limit) hard_limit = false;
speed_limit = v->u.air.cached_max_speed;
}
speed_limit = min(speed_limit, v->max_speed);
v->subspeed = (t=v->subspeed) + (byte)spd;
/* Aircraft's current speed is used twice so that very fast planes are
* forced to slow down rapidly in the short distance needed. The magic
* value 16384 was determined to give similar results to the old speed/48
* method at slower speeds. This also results in less reduction at slow
* speeds to that aircraft do not get to taxi speed straight after
* touchdown. */
if (!hard_limit && v->cur_speed > speed_limit) {
speed_limit = v->cur_speed - max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
}
spd = min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
/* adjust speed for broken vehicles */
if (v->vehstatus & VS_AIRCRAFT_BROKEN) spd = min(spd, SPEED_LIMIT_BROKEN);
/* updates statusbar only if speed have changed to save CPU time */
if (spd != v->cur_speed) {
v->cur_speed = spd;
if (_settings_client.gui.vehicle_speed)
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
/* Adjust distance moved by plane speed setting */
if (_settings_game.vehicle.plane_speed > 1) spd /= _settings_game.vehicle.plane_speed;
if (!(v->direction & 1)) spd = spd * 3 / 4;
spd += v->progress;
v->progress = (byte)spd;
return spd >> 8;
}
/**
* Gets the cruise altitude of an aircraft.
* The cruise altitude is determined by the velocity of the vehicle
* and the direction it is moving
* @param v The vehicle. Should be an aircraft
* @returns Altitude in pixel units
*/
byte GetAircraftFlyingAltitude(const Vehicle *v)
{
/* Make sure Aircraft fly no lower so that they don't conduct
* CFITs (controlled flight into terrain)
*/
byte base_altitude = 150;
/* Make sure eastbound and westbound planes do not "crash" into each
* other by providing them with vertical seperation
*/
switch (v->direction) {
case DIR_N:
case DIR_NE:
case DIR_E:
case DIR_SE:
base_altitude += 10;
break;
default: break;
}
/* Make faster planes fly higher so that they can overtake slower ones */
base_altitude += min(20 * (v->max_speed / 200), 90);
return base_altitude;
}
/**
* Find the entry point to an airport depending on direction which
* the airport is being approached from. Each airport can have up to
* four entry points for its approach system so that approaching
* aircraft do not fly through each other or are forced to do 180
* degree turns during the approach. The arrivals are grouped into
* four sectors dependent on the DiagDirection from which the airport
* is approached.
*
* @param v The vehicle that is approaching the airport
* @param apc The Airport Class being approached.
* @returns The index of the entry point
*/
static byte AircraftGetEntryPoint(const Vehicle *v, const AirportFTAClass *apc)
{
assert(v != NULL);
assert(apc != NULL);
/* In the case the station doesn't exit anymore, set target tile 0.
* It doesn't hurt much, aircraft will go to next order, nearest hangar
* or it will simply crash in next tick */
TileIndex tile = 0;
if (IsValidStationID(v->u.air.targetairport)) {
const Station *st = GetStation(v->u.air.targetairport);
/* Make sure we don't go to INVALID_TILE if the airport has been removed. */
tile = (st->airport_tile != INVALID_TILE) ? st->airport_tile : st->xy;
}
int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
DiagDirection dir;
if (abs(delta_y) < abs(delta_x)) {
/* We are northeast or southwest of the airport */
dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
} else {
/* We are northwest or southeast of the airport */
dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
}
return apc->entry_points[dir];
}
/**
* Controls the movement of an aircraft. This function actually moves the vehicle
* on the map and takes care of minor things like sound playback.
* @todo De-mystify the cur_speed values for helicopter rotors.
* @param v The vehicle that is moved. Must be the first vehicle of the chain
* @return Whether the position requested by the State Machine has been reached
*/
static bool AircraftController(Vehicle *v)
{
int count;
/* NULL if station is invalid */
const Station *st = IsValidStationID(v->u.air.targetairport) ? GetStation(v->u.air.targetairport) : NULL;
/* INVALID_TILE if there is no station */
TileIndex tile = INVALID_TILE;
if (st != NULL) {
tile = (st->airport_tile != INVALID_TILE) ? st->airport_tile : st->xy;
}
/* DUMMY if there is no station or no airport */
const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->Airport();
/* prevent going to INVALID_TILE if airport is deleted. */
if (st == NULL || st->airport_tile == INVALID_TILE) {
/* Jump into our "holding pattern" state machine if possible */
if (v->u.air.pos >= afc->nofelements) {
v->u.air.pos = v->u.air.previous_pos = AircraftGetEntryPoint(v, afc);
} else if (v->u.air.targetairport != v->current_order.GetDestination()) {
/* If not possible, just get out of here fast */
v->u.air.state = FLYING;
UpdateAircraftCache(v);
AircraftNextAirportPos_and_Order(v);
/* get aircraft back on running altitude */
SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlyingAltitude(v));
return false;
}
}
/* get airport moving data */
const AirportMovingData *amd = afc->MovingData(v->u.air.pos);
int x = TileX(tile) * TILE_SIZE;
int y = TileY(tile) * TILE_SIZE;
/* Helicopter raise */
if (amd->flag & AMED_HELI_RAISE) {
Vehicle *u = v->Next()->Next();
/* Make sure the rotors don't rotate too fast */
if (u->cur_speed > 32) {
v->cur_speed = 0;
if (--u->cur_speed == 32) SndPlayVehicleFx(SND_18_HELICOPTER, v);
} else {
u->cur_speed = 32;
count = UpdateAircraftSpeed(v);
if (count > 0) {
v->tile = 0;
/* Reached altitude? */
if (v->z_pos >= 184) {
v->cur_speed = 0;
return true;
}
SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, 184));
}
}
return false;
}
/* Helicopter landing. */
if (amd->flag & AMED_HELI_LOWER) {
if (st == NULL) {
/* FIXME - AircraftController -> if station no longer exists, do not land
* helicopter will circle until sign disappears, then go to next order
* what to do when it is the only order left, right now it just stays in 1 place */
v->u.air.state = FLYING;
UpdateAircraftCache(v);
AircraftNextAirportPos_and_Order(v);
return false;
}
/* Vehicle is now at the airport. */
v->tile = tile;
/* Find altitude of landing position. */
int z = GetSlopeZ(x, y) + 1 + afc->delta_z;
if (z == v->z_pos) {
Vehicle *u = v->Next()->Next();
/* Increase speed of rotors. When speed is 80, we've landed. */
if (u->cur_speed >= 80) return true;
u->cur_speed += 4;
} else {
count = UpdateAircraftSpeed(v);
if (count > 0) {
if (v->z_pos > z) {
SetAircraftPosition(v, v->x_pos, v->y_pos, max(v->z_pos - count, z));
} else {
SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z));
}
}
}
return false;
}
/* Get distance from destination pos to current pos. */
uint dist = abs(x + amd->x - v->x_pos) + abs(y + amd->y - v->y_pos);
/* Need exact position? */
if (!(amd->flag & AMED_EXACTPOS) && dist <= (amd->flag & AMED_SLOWTURN ? 8U : 4U)) return true;
/* At final pos? */
if (dist == 0) {
/* Change direction smoothly to final direction. */
DirDiff dirdiff = DirDifference(amd->direction, v->direction);
/* if distance is 0, and plane points in right direction, no point in calling
* UpdateAircraftSpeed(). So do it only afterwards */
if (dirdiff == DIRDIFF_SAME) {
v->cur_speed = 0;
return true;
}
if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
v->direction = ChangeDir(v->direction, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
v->cur_speed >>= 1;
SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
return false;
}
uint speed_limit = SPEED_LIMIT_TAXI;
bool hard_limit = true;
if (amd->flag & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
if (amd->flag & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
if (amd->flag & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
if (amd->flag & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
if (count == 0) return false;
if (v->load_unload_time_rem != 0) v->load_unload_time_rem--;
do {
GetNewVehiclePosResult gp;
if (dist < 4 || amd->flag & AMED_LAND) {
/* move vehicle one pixel towards target */
gp.x = (v->x_pos != (x + amd->x)) ?
v->x_pos + ((x + amd->x > v->x_pos) ? 1 : -1) :
v->x_pos;
gp.y = (v->y_pos != (y + amd->y)) ?
v->y_pos + ((y + amd->y > v->y_pos) ? 1 : -1) :
v->y_pos;
/* Oilrigs must keep v->tile as st->airport_tile, since the landing pad is in a non-airport tile */
gp.new_tile = (st->airport_type == AT_OILRIG) ? st->airport_tile : TileVirtXY(gp.x, gp.y);
} else {
/* Turn. Do it slowly if in the air. */
Direction newdir = GetDirectionTowards(v, x + amd->x, y + amd->y);
if (newdir != v->direction) {
v->direction = newdir;
if (amd->flag & AMED_SLOWTURN) {
if (v->load_unload_time_rem == 0) v->load_unload_time_rem = 8;
} else {
v->cur_speed >>= 1;
}
}
/* Move vehicle. */
gp = GetNewVehiclePos(v);
}
v->tile = gp.new_tile;
/* If vehicle is in the air, use tile coordinate 0. */
if (amd->flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
/* Adjust Z for land or takeoff? */
uint z = v->z_pos;
if (amd->flag & AMED_TAKEOFF) {
z = min(z + 2, GetAircraftFlyingAltitude(v));
}
if ((amd->flag & AMED_HOLD) && (z > 150)) z--;
if (amd->flag & AMED_LAND) {
if (st->airport_tile == INVALID_TILE) {
/* Airport has been removed, abort the landing procedure */
v->u.air.state = FLYING;
UpdateAircraftCache(v);
AircraftNextAirportPos_and_Order(v);
/* get aircraft back on running altitude */
SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlyingAltitude(v));
continue;
}
uint curz = GetSlopeZ(x, y) + 1;
if (curz > z) {
z++;
} else {
int t = max(1U, dist - 4);
z -= ((z - curz) + t - 1) / t;
if (z < curz) z = curz;
}
}
/* We've landed. Decrase speed when we're reaching end of runway. */
if (amd->flag & AMED_BRAKE) {
uint curz = GetSlopeZ(x, y) + 1;
if (z > curz) {
z--;
} else if (z < curz) {
z++;
}
}
SetAircraftPosition(v, gp.x, gp.y, z);
} while (--count != 0);
return false;
}
static void HandleCrashedAircraft(Vehicle *v)
{
v->u.air.crashed_counter += 3;
Station *st = GetTargetAirportIfValid(v);
/* make aircraft crash down to the ground */
if (v->u.air.crashed_counter < 500 && st == NULL && ((v->u.air.crashed_counter % 3) == 0) ) {
uint z = GetSlopeZ(v->x_pos, v->y_pos);
v->z_pos -= 1;
if (v->z_pos == z) {
v->u.air.crashed_counter = 500;
v->z_pos++;
}
}
if (v->u.air.crashed_counter < 650) {
uint32 r;
if (Chance16R(1,32,r)) {
static const DirDiff delta[] = {
DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
};
v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
r = Random();
CreateEffectVehicleRel(v,
GB(r, 0, 4) - 4,
GB(r, 4, 4) - 4,
GB(r, 8, 4),
EV_EXPLOSION_SMALL);
}
} else if (v->u.air.crashed_counter >= 10000) {
/* remove rubble of crashed airplane */
/* clear runway-in on all airports, set by crashing plane
* small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
* but they all share the same number */
if (st != NULL) {
CLRBITS(st->airport_flags, RUNWAY_IN_block);
CLRBITS(st->airport_flags, RUNWAY_IN_OUT_block); // commuter airport
CLRBITS(st->airport_flags, RUNWAY_IN2_block); // intercontinental
}
delete v;
}
}
static void HandleBrokenAircraft(Vehicle *v)
{
if (v->breakdown_ctr != 1) {
v->breakdown_ctr = 1;
v->vehstatus |= VS_AIRCRAFT_BROKEN;
if (v->breakdowns_since_last_service != 255)
v->breakdowns_since_last_service++;
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
}
}
static void HandleAircraftSmoke(Vehicle *v)
{
static const struct {
int8 x;
int8 y;
} smoke_pos[] = {
{ 5, 5 },
{ 6, 0 },
{ 5, -5 },
{ 0, -6 },
{ -5, -5 },
{ -6, 0 },
{ -5, 5 },
{ 0, 6 }
};
if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
if (v->cur_speed < 10) {
v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
v->breakdown_ctr = 0;
return;
}
if ((v->tick_counter & 0x1F) == 0) {
CreateEffectVehicleRel(v,
smoke_pos[v->direction].x,
smoke_pos[v->direction].y,
2,
EV_SMOKE
);
}
}
void HandleMissingAircraftOrders(Vehicle *v)
{
/*
* We do not have an order. This can be divided into two cases:
* 1) we are heading to an invalid station. In this case we must
* find another airport to go to. If there is nowhere to go,
* we will destroy the aircraft as it otherwise will enter
* the holding pattern for the first airport, which can cause
* the plane to go into an undefined state when building an
* airport with the same StationID.
* 2) we are (still) heading to a (still) valid airport, then we
* can continue going there. This can happen when you are
* changing the aircraft's orders while in-flight or in for
* example a depot. However, when we have a current order to
* go to a depot, we have to keep that order so the aircraft
* actually stops.
*/
const Station *st = GetTargetAirportIfValid(v);
if (st == NULL) {
CommandCost ret;
CompanyID old_company = _current_company;
_current_company = v->owner;
ret = DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_SEND_AIRCRAFT_TO_HANGAR);
_current_company = old_company;
if (CmdFailed(ret)) CrashAirplane(v);
} else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
v->current_order.Free();
}
}
TileIndex Aircraft::GetOrderStationLocation(StationID station)
{
/* Orders are changed in flight, ensure going to the right station. */
if (this->u.air.state == FLYING) {
AircraftNextAirportPos_and_Order(this);
}
/* Aircraft do not use dest-tile */
return 0;
}
void Aircraft::MarkDirty()
{
this->cur_image = this->GetImage(this->direction);
if (this->subtype == AIR_HELICOPTER) this->Next()->Next()->cur_image = GetRotorImage(this);
MarkSingleVehicleDirty(this);
}
static void CrashAirplane(Vehicle *v)
{
v->vehstatus |= VS_CRASHED;
v->u.air.crashed_counter = 0;
CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
uint amt = 2;
if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) amt += v->cargo.Count();
SetDParam(0, amt);
v->cargo.Truncate(0);
v->Next()->cargo.Truncate(0);
const Station *st = GetTargetAirportIfValid(v);
StringID newsitem;
AIEventVehicleCrashed::CrashReason crash_reason;
if (st == NULL) {
newsitem = STR_PLANE_CRASH_OUT_OF_FUEL;
crash_reason = AIEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT;
} else {
SetDParam(1, st->index);
newsitem = STR_A034_PLANE_CRASH_DIE_IN_FIREBALL;
crash_reason = AIEventVehicleCrashed::CRASH_PLANE_LANDING;
}
AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, crash_reason));
AddNewsItem(newsitem,
NS_ACCIDENT_VEHICLE,
v->index,
0);
SndPlayVehicleFx(SND_12_EXPLOSION, v);
}
static void MaybeCrashAirplane(Vehicle *v)
{
Station *st = GetStation(v->u.air.targetairport);
/* FIXME -- MaybeCrashAirplane -> increase crashing chances of very modern airplanes on smaller than AT_METROPOLITAN airports */
uint16 prob = 0x10000 / 1500;
if (st->Airport()->flags & AirportFTAClass::SHORT_STRIP &&
AircraftVehInfo(v->engine_type)->subtype & AIR_FAST &&
!_cheats.no_jetcrash.value) {
prob = 0x10000 / 20;
}
if (GB(Random(), 0, 16) > prob) return;
/* Crash the airplane. Remove all goods stored at the station. */
for (CargoID i = 0; i < NUM_CARGO; i++) {
st->goods[i].rating = 1;
st->goods[i].cargo.Truncate(0);
}
CrashAirplane(v);
}
/** we've landed and just arrived at a terminal */
static void AircraftEntersTerminal(Vehicle *v)
{
if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
Station *st = GetStation(v->u.air.targetairport);
v->last_station_visited = v->u.air.targetairport;
/* Check if station was ever visited before */
if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
st->had_vehicle_of_type |= HVOT_AIRCRAFT;
SetDParam(0, st->index);
/* show newsitem of celebrating citizens */
AddNewsItem(
STR_A033_CITIZENS_CELEBRATE_FIRST,
(v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
v->index,
st->index
);
AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
}
v->BeginLoading();
}
static void AircraftLandAirplane(Vehicle *v)
{
v->UpdateDeltaXY(INVALID_DIR);
if (!PlayVehicleSound(v, VSE_TOUCHDOWN)) {
SndPlayVehicleFx(SND_17_SKID_PLANE, v);
}
MaybeCrashAirplane(v);
}
/** set the right pos when heading to other airports after takeoff */
void AircraftNextAirportPos_and_Order(Vehicle *v)
{
if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
v->u.air.targetairport = v->current_order.GetDestination();
}
const Station *st = GetTargetAirportIfValid(v);
const AirportFTAClass *apc = st == NULL ? GetAirport(AT_DUMMY) : st->Airport();
v->u.air.pos = v->u.air.previous_pos = AircraftGetEntryPoint(v, apc);
}
void AircraftLeaveHangar(Vehicle *v)
{
v->cur_speed = 0;
v->subspeed = 0;
v->progress = 0;
v->direction = DIR_SE;
v->vehstatus &= ~VS_HIDDEN;
{
Vehicle *u = v->Next();
u->vehstatus &= ~VS_HIDDEN;
/* Rotor blades */
u = u->Next();
if (u != NULL) {
u->vehstatus &= ~VS_HIDDEN;
u->cur_speed = 80;
}
}
VehicleServiceInDepot(v);
SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClasses(WC_AIRCRAFT_LIST);
}
/** Checks if an aircraft should head towards a hangar because it needs replacement
* @param *v the vehicle to test
* @return true if the aircraft should head towards a hangar
*/
static inline bool CheckSendAircraftToHangarForReplacement(const Vehicle *v)
{
EngineID new_engine;
Company *c = GetCompany(v->owner);
if (VehicleHasDepotOrders(v)) return false; // The aircraft will end up in the hangar eventually on it's own
new_engine = EngineReplacementForCompany(c, v->engine_type, v->group_id);
if (new_engine == INVALID_ENGINE) {
/* There is no autoreplace assigned to this EngineID so we will set it to renew to the same type if needed */
new_engine = v->engine_type;
if (!v->NeedsAutorenewing(c)) {
/* No need to replace the aircraft */
return false;
}
}
if (!HasBit(GetEngine(new_engine)->company_avail, v->owner)) {
/* Engine is not buildable anymore */
return false;
}
if (c->money < (c->engine_renew_money + (2 * DoCommand(0, new_engine, 0, DC_QUERY_COST, CMD_BUILD_AIRCRAFT).GetCost()))) {
/* We lack enough money to request the replacement right away.
* We want 2*(the price of the new vehicle) and not looking at the value of the vehicle we are going to sell.
* The reason is that we don't want to send a whole lot of vehicles to the hangars when we only have enough money to replace a single one.
* Remember this happens in the background so the user can't stop this. */
return false;
}
/* We found no reason NOT to send the aircraft to a hangar so we will send it there at once */
return true;
}
////////////////////////////////////////////////////////////////////////////////
/////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
static void AircraftEventHandler_EnterTerminal(Vehicle *v, const AirportFTAClass *apc)
{
AircraftEntersTerminal(v);
v->u.air.state = apc->layout[v->u.air.pos].heading;
}
static void AircraftEventHandler_EnterHangar(Vehicle *v, const AirportFTAClass *apc)
{
VehicleEnterDepot(v);
v->u.air.state = apc->layout[v->u.air.pos].heading;
}
/** In an Airport Hangar */
static void AircraftEventHandler_InHangar(Vehicle *v, const AirportFTAClass *apc)
{
/* if we just arrived, execute EnterHangar first */
if (v->u.air.previous_pos != v->u.air.pos) {
AircraftEventHandler_EnterHangar(v, apc);
return;
}
/* if we were sent to the depot, stay there */
if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
v->current_order.Free();
return;
}
if (!v->current_order.IsType(OT_GOTO_STATION) &&
!v->current_order.IsType(OT_GOTO_DEPOT))
return;
/* if the block of the next position is busy, stay put */
if (AirportHasBlock(v, &apc->layout[v->u.air.pos], apc)) return;
/* We are already at the target airport, we need to find a terminal */
if (v->current_order.GetDestination() == v->u.air.targetairport) {
/* FindFreeTerminal:
* 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
if (v->subtype == AIR_HELICOPTER) {
if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
} else {
if (!AirportFindFreeTerminal(v, apc)) return; // airplane
}
} else { // Else prepare for launch.
/* airplane goto state takeoff, helicopter to helitakeoff */
v->u.air.state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
}
AircraftLeaveHangar(v);
AirportMove(v, apc);
}
/** At one of the Airport's Terminals */
static void AircraftEventHandler_AtTerminal(Vehicle *v, const AirportFTAClass *apc)
{
/* if we just arrived, execute EnterTerminal first */
if (v->u.air.previous_pos != v->u.air.pos) {
AircraftEventHandler_EnterTerminal(v, apc);
/* on an airport with helipads, a helicopter will always land there
* and get serviced at the same time - setting */
if (_settings_game.order.serviceathelipad) {
if (v->subtype == AIR_HELICOPTER && apc->helipads != NULL) {
/* an exerpt of ServiceAircraft, without the invisibility stuff */
v->date_of_last_service = _date;
v->breakdowns_since_last_service = 0;
v->reliability = GetEngine(v->engine_type)->reliability;
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
}
}
return;
}
if (!v->current_order.IsValid()) return;
/* if the block of the next position is busy, stay put */
if (AirportHasBlock(v, &apc->layout[v->u.air.pos], apc)) return;
/* airport-road is free. We either have to go to another airport, or to the hangar
* ---> start moving */
bool go_to_hangar = false;
switch (v->current_order.GetType()) {
case OT_GOTO_STATION: // ready to fly to another airport
break;
case OT_GOTO_DEPOT: // visit hangar for serivicing, sale, etc.
go_to_hangar = v->current_order.GetDestination() == v->u.air.targetairport;
break;
case OT_CONDITIONAL:
/* In case of a conditional order we just have to wait a tick
* longer, so the conditional order can actually be processed;
* we should not clear the order as that makes us go nowhere. */
return;
default: // orders have been deleted (no orders), goto depot and don't bother us
v->current_order.Free();
go_to_hangar = GetStation(v->u.air.targetairport)->Airport()->nof_depots != 0;
}
if (go_to_hangar) {
v->u.air.state = HANGAR;
} else {
/* airplane goto state takeoff, helicopter to helitakeoff */
v->u.air.state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
}
AirportMove(v, apc);
}
static void AircraftEventHandler_General(Vehicle *v, const AirportFTAClass *apc)
{
assert("OK, you shouldn't be here, check your Airport Scheme!" && 0);
}
static void AircraftEventHandler_TakeOff(Vehicle *v, const AirportFTAClass *apc)
{
PlayAircraftSound(v); // play takeoffsound for airplanes
v->u.air.state = STARTTAKEOFF;
}
static void AircraftEventHandler_StartTakeOff(Vehicle *v, const AirportFTAClass *apc)
{
v->u.air.state = ENDTAKEOFF;
v->UpdateDeltaXY(INVALID_DIR);
}
static void AircraftEventHandler_EndTakeOff(Vehicle *v, const AirportFTAClass *apc)
{
v->u.air.state = FLYING;
/* get the next position to go to, differs per airport */
AircraftNextAirportPos_and_Order(v);
}
static void AircraftEventHandler_HeliTakeOff(Vehicle *v, const AirportFTAClass *apc)
{
v->u.air.state = FLYING;
v->UpdateDeltaXY(INVALID_DIR);
/* get the next position to go to, differs per airport */
AircraftNextAirportPos_and_Order(v);
/* Send the helicopter to a hangar if needed for replacement */
if (CheckSendAircraftToHangarForReplacement(v)) {
_current_company = v->owner;
DoCommand(v->tile, v->index, DEPOT_SERVICE | DEPOT_LOCATE_HANGAR, DC_EXEC, CMD_SEND_AIRCRAFT_TO_HANGAR);
_current_company = OWNER_NONE;
}
}
static void AircraftEventHandler_Flying(Vehicle *v, const AirportFTAClass *apc)
{
Station *st = GetStation(v->u.air.targetairport);
/* runway busy or not allowed to use this airstation, circle */
if (apc->flags & (v->subtype == AIR_HELICOPTER ? AirportFTAClass::HELICOPTERS : AirportFTAClass::AIRPLANES) &&
st->airport_tile != INVALID_TILE &&
(st->owner == OWNER_NONE || st->owner == v->owner)) {
/* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
* if it is an airplane, look for LANDING, for helicopter HELILANDING
* it is possible to choose from multiple landing runways, so loop until a free one is found */
byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
const AirportFTA *current = apc->layout[v->u.air.pos].next;
while (current != NULL) {
if (current->heading == landingtype) {
/* save speed before, since if AirportHasBlock is false, it resets them to 0
* we don't want that for plane in air
* hack for speed thingie */
uint16 tcur_speed = v->cur_speed;
uint16 tsubspeed = v->subspeed;
if (!AirportHasBlock(v, current, apc)) {
v->u.air.state = landingtype; // LANDING / HELILANDING
/* it's a bit dirty, but I need to set position to next position, otherwise
* if there are multiple runways, plane won't know which one it took (because
* they all have heading LANDING). And also occupy that block! */
v->u.air.pos = current->next_position;
SETBITS(st->airport_flags, apc->layout[v->u.air.pos].block);
return;
}
v->cur_speed = tcur_speed;
v->subspeed = tsubspeed;
}
current = current->next;
}
}
v->u.air.state = FLYING;
v->u.air.pos = apc->layout[v->u.air.pos].next_position;
}
static void AircraftEventHandler_Landing(Vehicle *v, const AirportFTAClass *apc)
{
v->u.air.state = ENDLANDING;
AircraftLandAirplane(v); // maybe crash airplane
/* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
if (CheckSendAircraftToHangarForReplacement(v)) {
_current_company = v->owner;
DoCommand(v->tile, v->index, DEPOT_SERVICE, DC_EXEC, CMD_SEND_AIRCRAFT_TO_HANGAR);
_current_company = OWNER_NONE;
}
}
static void AircraftEventHandler_HeliLanding(Vehicle *v, const AirportFTAClass *apc)
{
v->u.air.state = HELIENDLANDING;
v->UpdateDeltaXY(INVALID_DIR);
}
static void AircraftEventHandler_EndLanding(Vehicle *v, const AirportFTAClass *apc)
{
/* next block busy, don't do a thing, just wait */
if (AirportHasBlock(v, &apc->layout[v->u.air.pos], apc)) return;
/* if going to terminal (OT_GOTO_STATION) choose one
* 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
* 2. not going for terminal (but depot, no order),
* --> get out of the way to the hangar. */
if (v->current_order.IsType(OT_GOTO_STATION)) {
if (AirportFindFreeTerminal(v, apc)) return;
}
v->u.air.state = HANGAR;
}
static void AircraftEventHandler_HeliEndLanding(Vehicle *v, const AirportFTAClass *apc)
{
/* next block busy, don't do a thing, just wait */
if (AirportHasBlock(v, &apc->layout[v->u.air.pos], apc)) return;
/* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
* 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
* 2. not going for terminal (but depot, no order),
* --> get out of the way to the hangar IF there are terminals on the airport.
* --> else TAKEOFF
* the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
* must go to a hangar. */
if (v->current_order.IsType(OT_GOTO_STATION)) {
if (AirportFindFreeHelipad(v, apc)) return;
}
v->u.air.state = (apc->nof_depots != 0) ? HANGAR : HELITAKEOFF;
}
typedef void AircraftStateHandler(Vehicle *v, const AirportFTAClass *apc);
static AircraftStateHandler * const _aircraft_state_handlers[] = {
AircraftEventHandler_General, // TO_ALL = 0
AircraftEventHandler_InHangar, // HANGAR = 1
AircraftEventHandler_AtTerminal, // TERM1 = 2
AircraftEventHandler_AtTerminal, // TERM2 = 3
AircraftEventHandler_AtTerminal, // TERM3 = 4
AircraftEventHandler_AtTerminal, // TERM4 = 5
AircraftEventHandler_AtTerminal, // TERM5 = 6
AircraftEventHandler_AtTerminal, // TERM6 = 7
AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
AircraftEventHandler_TakeOff, // TAKEOFF = 10
AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
AircraftEventHandler_Flying, // FLYING = 14
AircraftEventHandler_Landing, // LANDING = 15
AircraftEventHandler_EndLanding, // ENDLANDING = 16
AircraftEventHandler_HeliLanding, // HELILANDING = 17
AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
AircraftEventHandler_AtTerminal, // TERM7 = 19
AircraftEventHandler_AtTerminal, // TERM8 = 20
AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
AircraftEventHandler_AtTerminal, // HELIPAD4 = 22
};
static void AirportClearBlock(const Vehicle *v, const AirportFTAClass *apc)
{
/* we have left the previous block, and entered the new one. Free the previous block */
if (apc->layout[v->u.air.previous_pos].block != apc->layout[v->u.air.pos].block) {
Station *st = GetStation(v->u.air.targetairport);
CLRBITS(st->airport_flags, apc->layout[v->u.air.previous_pos].block);
}
}
static void AirportGoToNextPosition(Vehicle *v)
{
/* if aircraft is not in position, wait until it is */
if (!AircraftController(v)) return;
const AirportFTAClass *apc = GetStation(v->u.air.targetairport)->Airport();
AirportClearBlock(v, apc);
AirportMove(v, apc); // move aircraft to next position
}
/* gets pos from vehicle and next orders */
static bool AirportMove(Vehicle *v, const AirportFTAClass *apc)
{
/* error handling */
if (v->u.air.pos >= apc->nofelements) {
DEBUG(misc, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v->u.air.pos, apc->nofelements-1);
assert(v->u.air.pos < apc->nofelements);
}
const AirportFTA *current = &apc->layout[v->u.air.pos];
/* we have arrived in an important state (eg terminal, hangar, etc.) */
if (current->heading == v->u.air.state) {
byte prev_pos = v->u.air.pos; // location could be changed in state, so save it before-hand
byte prev_state = v->u.air.state;
_aircraft_state_handlers[v->u.air.state](v, apc);
if (v->u.air.state != FLYING) v->u.air.previous_pos = prev_pos;
if (v->u.air.state != prev_state || v->u.air.pos != prev_pos) UpdateAircraftCache(v);
return true;
}
v->u.air.previous_pos = v->u.air.pos; // save previous location
/* there is only one choice to move to */
if (current->next == NULL) {
if (AirportSetBlocks(v, current, apc)) {
v->u.air.pos = current->next_position;
UpdateAircraftCache(v);
} // move to next position
return false;
}
/* there are more choices to choose from, choose the one that
* matches our heading */
do {
if (v->u.air.state == current->heading || current->heading == TO_ALL) {
if (AirportSetBlocks(v, current, apc)) {
v->u.air.pos = current->next_position;
UpdateAircraftCache(v);
} // move to next position
return false;
}
current = current->next;
} while (current != NULL);
DEBUG(misc, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v->u.air.pos, v->u.air.state, v->index);
assert(0);
return false;
}
/* returns true if the road ahead is busy, eg. you must wait before proceeding */
static bool AirportHasBlock(Vehicle *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
{
const AirportFTA *reference = &apc->layout[v->u.air.pos];
const AirportFTA *next = &apc->layout[current_pos->next_position];
/* same block, then of course we can move */
if (apc->layout[current_pos->position].block != next->block) {
const Station *st = GetStation(v->u.air.targetairport);
uint64 airport_flags = next->block;
/* check additional possible extra blocks */
if (current_pos != reference && current_pos->block != NOTHING_block) {
airport_flags |= current_pos->block;
}
if (HASBITS(st->airport_flags, airport_flags)) {
v->cur_speed = 0;
v->subspeed = 0;
return true;
}
}
return false;
}
/**
* "reserve" a block for the plane
* @param v airplane that requires the operation
* @param current_pos of the vehicle in the list of blocks
* @param apc airport on which block is requsted to be set
* @returns true on success. Eg, next block was free and we have occupied it
*/
static bool AirportSetBlocks(Vehicle *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
{
const AirportFTA *next = &apc->layout[current_pos->next_position];
const AirportFTA *reference = &apc->layout[v->u.air.pos];
/* if the next position is in another block, check it and wait until it is free */
if ((apc->layout[current_pos->position].block & next->block) != next->block) {
uint64 airport_flags = next->block;
/* search for all all elements in the list with the same state, and blocks != N
* this means more blocks should be checked/set */
const AirportFTA *current = current_pos;
if (current == reference) current = current->next;
while (current != NULL) {
if (current->heading == current_pos->heading && current->block != 0) {
airport_flags |= current->block;
break;
}
current = current->next;
};
/* if the block to be checked is in the next position, then exclude that from
* checking, because it has been set by the airplane before */
if (current_pos->block == next->block) airport_flags ^= next->block;
Station *st = GetStation(v->u.air.targetairport);
if (HASBITS(st->airport_flags, airport_flags)) {
v->cur_speed = 0;
v->subspeed = 0;
return false;
}
if (next->block != NOTHING_block) {
SETBITS(st->airport_flags, airport_flags); // occupy next block
}
}
return true;
}
static bool FreeTerminal(Vehicle *v, byte i, byte last_terminal)
{
Station *st = GetStation(v->u.air.targetairport);
for (; i < last_terminal; i++) {
if (!HasBit(st->airport_flags, _airport_terminal_flag[i])) {
/* TERMINAL# HELIPAD# */
v->u.air.state = _airport_terminal_state[i]; // start moving to that terminal/helipad
SetBit(st->airport_flags, _airport_terminal_flag[i]); // occupy terminal/helipad
return true;
}
}
return false;
}
static uint GetNumTerminals(const AirportFTAClass *apc)
{
uint num = 0;
for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
return num;
}
static bool AirportFindFreeTerminal(Vehicle *v, const AirportFTAClass *apc)
{
/* example of more terminalgroups
* {0,HANGAR,NOTHING_block,1}, {0,255,TERM_GROUP1_block,0}, {0,255,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
* Heading 255 denotes a group. We see 2 groups here:
* 1. group 0 -- TERM_GROUP1_block (check block)
* 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
* First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
* looks at the corresponding terminals of that group. If no free ones are found, other
* possible groups are checked (in this case group 1, since that is after group 0). If that
* fails, then attempt fails and plane waits
*/
if (apc->terminals[0] > 1) {
const Station *st = GetStation(v->u.air.targetairport);
const AirportFTA *temp = apc->layout[v->u.air.pos].next;
while (temp != NULL) {
if (temp->heading == 255) {
if (!HASBITS(st->airport_flags, temp->block)) {
/* read which group do we want to go to?
* (the first free group) */
uint target_group = temp->next_position + 1;
/* at what terminal does the group start?
* that means, sum up all terminals of
* groups with lower number */
uint group_start = 0;
for (uint i = 1; i < target_group; i++) {
group_start += apc->terminals[i];
}
uint group_end = group_start + apc->terminals[target_group];
if (FreeTerminal(v, group_start, group_end)) return true;
}
} else {
/* once the heading isn't 255, we've exhausted the possible blocks.
* So we cannot move */
return false;
}
temp = temp->next;
}
}
/* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
return FreeTerminal(v, 0, GetNumTerminals(apc));
}
static uint GetNumHelipads(const AirportFTAClass *apc)
{
uint num = 0;
for (uint i = apc->helipads[0]; i > 0; i--) num += apc->helipads[i];
return num;
}
static bool AirportFindFreeHelipad(Vehicle *v, const AirportFTAClass *apc)
{
/* if an airport doesn't have helipads, use terminals */
if (apc->helipads == NULL) return AirportFindFreeTerminal(v, apc);
/* if there are more helicoptergroups, pick one, just as in AirportFindFreeTerminal() */
if (apc->helipads[0] > 1) {
const Station *st = GetStation(v->u.air.targetairport);
const AirportFTA *temp = apc->layout[v->u.air.pos].next;
while (temp != NULL) {
if (temp->heading == 255) {
if (!HASBITS(st->airport_flags, temp->block)) {
/* read which group do we want to go to?
* (the first free group) */
uint target_group = temp->next_position + 1;
/* at what terminal does the group start?
* that means, sum up all terminals of
* groups with lower number */
uint group_start = 0;
for (uint i = 1; i < target_group; i++) {
group_start += apc->helipads[i];
}
uint group_end = group_start + apc->helipads[target_group];
if (FreeTerminal(v, group_start, group_end)) return true;
}
} else {
/* once the heading isn't 255, we've exhausted the possible blocks.
* So we cannot move */
return false;
}
temp = temp->next;
}
} else {
/* only 1 helicoptergroup, check all helipads
* The blocks for helipads start after the last terminal (MAX_TERMINALS) */
return FreeTerminal(v, MAX_TERMINALS, GetNumHelipads(apc) + MAX_TERMINALS);
}
return false; // it shouldn't get here anytime, but just to be sure
}
static void AircraftEventHandler(Vehicle *v, int loop)
{
v->tick_counter++;
if (v->vehstatus & VS_CRASHED) {
HandleCrashedAircraft(v);
return;
}
if (v->vehstatus & VS_STOPPED) return;
/* aircraft is broken down? */
if (v->breakdown_ctr != 0) {
if (v->breakdown_ctr <= 2) {
HandleBrokenAircraft(v);
} else {
if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
}
}
HandleAircraftSmoke(v);
ProcessOrders(v);
v->HandleLoading(loop != 0);
if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return;
AirportGoToNextPosition(v);
}
void Aircraft::Tick()
{
if (!IsNormalAircraft(this)) return;
if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
AgeAircraftCargo(this);
this->current_order_time++;
for (uint i = 0; i != 2; i++) {
AircraftEventHandler(this, i);
if (this->type != VEH_AIRCRAFT) // In case it was deleted
break;
}
}
/** Returns aircraft's target station if v->u.air.target_airport
* is a valid station with airport.
* @param v vehicle to get target airport for
* @return pointer to target station, NULL if invalid
*/
Station *GetTargetAirportIfValid(const Vehicle *v)
{
assert(v->type == VEH_AIRCRAFT);
StationID sid = v->u.air.targetairport;
if (!IsValidStationID(sid)) return NULL;
Station *st = GetStation(sid);
return st->airport_tile == INVALID_TILE ? NULL : st;
}
/**
* Updates the status of the Aircraft heading or in the station
* @param st Station been updated
*/
void UpdateAirplanesOnNewStation(const Station *st)
{
/* only 1 station is updated per function call, so it is enough to get entry_point once */
const AirportFTAClass *ap = st->Airport();
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_AIRCRAFT && IsNormalAircraft(v)) {
if (v->u.air.targetairport == st->index) { // if heading to this airport
/* update position of airplane. If plane is not flying, landing, or taking off
* you cannot delete airport, so it doesn't matter */
if (v->u.air.state >= FLYING) { // circle around
v->u.air.pos = v->u.air.previous_pos = AircraftGetEntryPoint(v, ap);
v->u.air.state = FLYING;
UpdateAircraftCache(v);
/* landing plane needs to be reset to flying height (only if in pause mode upgrade,
* in normal mode, plane is reset in AircraftController. It doesn't hurt for FLYING */
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
/* set new position x,y,z */
SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlyingAltitude(v));
} else {
assert(v->u.air.state == ENDTAKEOFF || v->u.air.state == HELITAKEOFF);
byte takeofftype = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : ENDTAKEOFF;
/* search in airportdata for that heading
* easiest to do, since this doesn't happen a lot */
for (uint cnt = 0; cnt < ap->nofelements; cnt++) {
if (ap->layout[cnt].heading == takeofftype) {
v->u.air.pos = ap->layout[cnt].position;
UpdateAircraftCache(v);
break;
}
}
}
}
}
}
}
| 65,749
|
C++
|
.cpp
| 1,740
| 34.960345
| 140
| 0.687266
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,067
|
dock_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/dock_gui.cpp
|
/* $Id$ */
/** @file dock_gui.cpp GUI to create amazing water objects. */
#include "stdafx.h"
#include "openttd.h"
#include "tile_map.h"
#include "station_type.h"
#include "terraform_gui.h"
#include "window_gui.h"
#include "station_gui.h"
#include "command_func.h"
#include "water.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "company_func.h"
#include "slope_func.h"
#include "tilehighlight_func.h"
#include "company_base.h"
#include "settings_type.h"
#include "table/sprites.h"
#include "table/strings.h"
static void ShowBuildDockStationPicker(Window *parent);
static void ShowBuildDocksDepotPicker(Window *parent);
static Axis _ship_depot_direction;
void CcBuildDocks(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_02_SPLAT, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
}
}
void CcBuildCanal(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) SndPlayTileFx(SND_02_SPLAT, tile);
}
static void PlaceDocks_Dock(TileIndex tile)
{
uint32 p2 = INVALID_STATION << 16; // no station to join
/* tile is always the land tile, so need to evaluate _thd.pos */
CommandContainer cmdcont = { tile, _ctrl_pressed, p2, CMD_BUILD_DOCK | CMD_MSG(STR_9802_CAN_T_BUILD_DOCK_HERE), CcBuildDocks, "" };
ShowSelectStationIfNeeded(cmdcont, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE);
}
static void PlaceDocks_Depot(TileIndex tile)
{
DoCommandP(tile, _ship_depot_direction, 0, CMD_BUILD_SHIP_DEPOT | CMD_MSG(STR_3802_CAN_T_BUILD_SHIP_DEPOT), CcBuildDocks);
}
static void PlaceDocks_Buoy(TileIndex tile)
{
DoCommandP(tile, 0, 0, CMD_BUILD_BUOY | CMD_MSG(STR_9835_CAN_T_POSITION_BUOY_HERE), CcBuildDocks);
}
static void PlaceDocks_BuildCanal(TileIndex tile)
{
VpStartPlaceSizing(tile, (_game_mode == GM_EDITOR) ? VPM_X_AND_Y : VPM_X_OR_Y, DDSP_CREATE_WATER);
}
static void PlaceDocks_BuildLock(TileIndex tile)
{
DoCommandP(tile, 0, 0, CMD_BUILD_LOCK | CMD_MSG(STR_CANT_BUILD_LOCKS), CcBuildDocks);
}
static void PlaceDocks_BuildRiver(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_CREATE_RIVER);
}
static void PlaceDocks_Aqueduct(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_OR_Y, DDSP_BUILD_BRIDGE);
}
/** Enum referring to the widgets of the build dock toolbar */
enum DockToolbarWidgets {
DTW_BEGIN = 0, ///< Start of toolbar widgets
DTW_CLOSEBOX = DTW_BEGIN, ///< Close window button
DTW_CAPTION, ///< Window caption
DTW_STICKY, ///< Sticky window button
DTW_BUTTONS_BEGIN, ///< Begin of clickable buttons (except seperating panel)
DTW_CANAL = DTW_BUTTONS_BEGIN, ///< Build canal button
DTW_LOCK, ///< Build lock button
DTW_SEPERATOR, ///< Seperating panel between lock and demolish
DTW_DEMOLISH, ///< Demolish aka dynamite button
DTW_DEPOT, ///< Build depot button
DTW_STATION, ///< Build station button
DTW_BUOY, ///< Build buoy button
DTW_RIVER, ///< Build river button (in scenario editor)
DTW_BUILD_AQUEDUCT, ///< Build aqueduct button
DTW_END, ///< End of toolbar widgets
};
static void BuildDocksClick_Canal(Window *w)
{
HandlePlacePushButton(w, DTW_CANAL, SPR_CURSOR_CANAL, VHM_RECT, PlaceDocks_BuildCanal);
}
static void BuildDocksClick_Lock(Window *w)
{
HandlePlacePushButton(w, DTW_LOCK, SPR_CURSOR_LOCK, VHM_RECT, PlaceDocks_BuildLock);
}
static void BuildDocksClick_Demolish(Window *w)
{
HandlePlacePushButton(w, DTW_DEMOLISH, ANIMCURSOR_DEMOLISH, VHM_RECT, PlaceProc_DemolishArea);
}
static void BuildDocksClick_Depot(Window *w)
{
if (!CanBuildVehicleInfrastructure(VEH_SHIP)) return;
if (HandlePlacePushButton(w, DTW_DEPOT, SPR_CURSOR_SHIP_DEPOT, VHM_RECT, PlaceDocks_Depot)) ShowBuildDocksDepotPicker(w);
}
static void BuildDocksClick_Dock(Window *w)
{
if (!CanBuildVehicleInfrastructure(VEH_SHIP)) return;
if (HandlePlacePushButton(w, DTW_STATION, SPR_CURSOR_DOCK, VHM_SPECIAL, PlaceDocks_Dock)) ShowBuildDockStationPicker(w);
}
static void BuildDocksClick_Buoy(Window *w)
{
if (!CanBuildVehicleInfrastructure(VEH_SHIP)) return;
HandlePlacePushButton(w, DTW_BUOY, SPR_CURSOR_BOUY, VHM_RECT, PlaceDocks_Buoy);
}
static void BuildDocksClick_River(Window *w)
{
if (_game_mode != GM_EDITOR) return;
HandlePlacePushButton(w, DTW_RIVER, SPR_CURSOR_RIVER, VHM_RECT, PlaceDocks_BuildRiver);
}
static void BuildDocksClick_Aqueduct(Window *w)
{
HandlePlacePushButton(w, DTW_BUILD_AQUEDUCT, SPR_CURSOR_AQUEDUCT, VHM_RECT, PlaceDocks_Aqueduct);
}
typedef void OnButtonClick(Window *w);
static OnButtonClick * const _build_docks_button_proc[] = {
BuildDocksClick_Canal,
BuildDocksClick_Lock,
NULL,
BuildDocksClick_Demolish,
BuildDocksClick_Depot,
BuildDocksClick_Dock,
BuildDocksClick_Buoy,
BuildDocksClick_River,
BuildDocksClick_Aqueduct
};
struct BuildDocksToolbarWindow : Window {
BuildDocksToolbarWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->FindWindowPlacementAndResize(desc);
if (_settings_client.gui.link_terraform_toolbar) ShowTerraformToolbar(this);
}
~BuildDocksToolbarWindow()
{
if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false);
}
virtual void OnPaint()
{
this->SetWidgetsDisabledState(!CanBuildVehicleInfrastructure(VEH_SHIP), DTW_DEPOT, DTW_STATION, DTW_BUOY, WIDGET_LIST_END);
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
if (widget >= DTW_BUTTONS_BEGIN && widget != DTW_SEPERATOR) _build_docks_button_proc[widget - DTW_BUTTONS_BEGIN](this);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
switch (keycode) {
case '1': BuildDocksClick_Canal(this); break;
case '2': BuildDocksClick_Lock(this); break;
case '3': BuildDocksClick_Demolish(this); break;
case '4': BuildDocksClick_Depot(this); break;
case '5': BuildDocksClick_Dock(this); break;
case '6': BuildDocksClick_Buoy(this); break;
case '7': BuildDocksClick_River(this); break;
case 'B':
case '8': BuildDocksClick_Aqueduct(this); break;
default: return ES_NOT_HANDLED;
}
return ES_HANDLED;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_place_proc(tile);
}
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
{
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
{
if (pt.x != -1) {
switch (select_proc) {
case DDSP_BUILD_BRIDGE:
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
extern void CcBuildBridge(bool success, TileIndex tile, uint32 p1, uint32 p2);
DoCommandP(end_tile, start_tile, TRANSPORT_WATER << 15, CMD_BUILD_BRIDGE | CMD_MSG(STR_CAN_T_BUILD_AQUEDUCT_HERE), CcBuildBridge);
case DDSP_DEMOLISH_AREA:
GUIPlaceProcDragXY(select_proc, start_tile, end_tile);
break;
case DDSP_CREATE_WATER:
DoCommandP(end_tile, start_tile, (_game_mode == GM_EDITOR ? _ctrl_pressed : 0), CMD_BUILD_CANAL | CMD_MSG(STR_CANT_BUILD_CANALS), CcBuildCanal);
break;
case DDSP_CREATE_RIVER:
DoCommandP(end_tile, start_tile, 2, CMD_BUILD_CANAL | CMD_MSG(STR_CANT_PLACE_RIVERS), CcBuildCanal);
break;
default: break;
}
}
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
DeleteWindowById(WC_BUILD_STATION, 0);
DeleteWindowById(WC_BUILD_DEPOT, 0);
DeleteWindowById(WC_SELECT_STATION, 0);
DeleteWindowById(WC_BUILD_BRIDGE, 0);
}
virtual void OnPlacePresize(Point pt, TileIndex tile_from)
{
DiagDirection dir = GetInclinedSlopeDirection(GetTileSlope(tile_from, NULL));
TileIndex tile_to = (dir != INVALID_DIAGDIR ? TileAddByDiagDir(tile_from, ReverseDiagDir(dir)) : tile_from);
VpSetPresizeRange(tile_from, tile_to);
}
};
static const Widget _build_docks_toolb_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // DTW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 147, 0, 13, STR_9801_WATERWAYS_CONSTRUCTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // DTW_CAPTION
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 148, 159, 0, 13, 0x0, STR_STICKY_BUTTON}, // DTW_STICKY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 35, SPR_IMG_BUILD_CANAL, STR_BUILD_CANALS_TIP}, // DTW_CANAL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 35, SPR_IMG_BUILD_LOCK, STR_BUILD_LOCKS_TIP}, // DTW_LOCK
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 48, 14, 35, 0x0, STR_NULL}, // DTW_SEPERATOR
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 49, 70, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC}, // DTW_DEMOLISH
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 71, 92, 14, 35, SPR_IMG_SHIP_DEPOT, STR_981E_BUILD_SHIP_DEPOT_FOR_BUILDING}, // DTW_DEPOT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 93, 114, 14, 35, SPR_IMG_SHIP_DOCK, STR_981D_BUILD_SHIP_DOCK}, // DTW_STATION
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 115, 136, 14, 35, SPR_IMG_BOUY, STR_9834_POSITION_BUOY_WHICH_CAN}, // DTW_BUOY
{ WWT_EMPTY, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 0, 0, 0, 0x0, STR_NULL}, // DTW_RIVER
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 137, 159, 14, 35, SPR_IMG_AQUEDUCT, STR_BUILD_AQUEDUCT}, // DTW_BUILD_AQUEDUCT
{ WIDGETS_END},
};
static const WindowDesc _build_docks_toolbar_desc(
WDP_ALIGN_TBR, 22, 160, 36, 160, 36,
WC_BUILD_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_build_docks_toolb_widgets
);
void ShowBuildDocksToolbar()
{
if (!IsValidCompanyID(_local_company)) return;
DeleteWindowByClass(WC_BUILD_TOOLBAR);
AllocateWindowDescFront<BuildDocksToolbarWindow>(&_build_docks_toolbar_desc, TRANSPORT_WATER);
}
/* Widget definition for the build docks in scenario editor window */
static const Widget _build_docks_scen_toolb_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // DTW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 102, 0, 13, STR_9801_WATERWAYS_CONSTRUCTION_SE, STR_018C_WINDOW_TITLE_DRAG_THIS}, // DTW_CAPTION
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 103, 114, 0, 13, 0x0, STR_STICKY_BUTTON}, // DTW_STICKY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 35, SPR_IMG_BUILD_CANAL, STR_CREATE_LAKE}, // DTW_CANAL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 35, SPR_IMG_BUILD_LOCK, STR_BUILD_LOCKS_TIP}, // DTW_LOCK
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 48, 14, 35, 0x0, STR_NULL}, // DTW_SEPERATOR
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 49, 70, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC}, // DTW_DEMOLISH
{ WWT_EMPTY, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 0, 0, 0, 0x0, STR_NULL}, // DTW_DEPOT
{ WWT_EMPTY, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 0, 0, 0, 0x0, STR_NULL}, // DTW_STATION
{ WWT_EMPTY, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 0, 0, 0, 0x0, STR_NULL}, // DTW_BUOY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 71, 92, 14, 35, SPR_IMG_BUILD_RIVER, STR_CREATE_RIVER}, // DTW_RIVER
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 93, 114, 14, 35, SPR_IMG_AQUEDUCT, STR_BUILD_AQUEDUCT}, // DTW_BUILD_AQUEDUCT
{ WIDGETS_END},
};
/* Window definition for the build docks in scenario editor window */
static const WindowDesc _build_docks_scen_toolbar_desc(
WDP_AUTO, WDP_AUTO, 115, 36, 115, 36,
WC_SCEN_BUILD_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_build_docks_scen_toolb_widgets
);
void ShowBuildDocksScenToolbar()
{
AllocateWindowDescFront<BuildDocksToolbarWindow>(&_build_docks_scen_toolbar_desc, TRANSPORT_WATER);
}
struct BuildDocksStationWindow : public PickerWindowBase {
private:
enum BuildDockStationWidgets {
BDSW_CLOSE,
BDSW_CAPTION,
BDSW_BACKGROUND,
BDSW_LT_OFF,
BDSW_LT_ON,
BDSW_INFO,
};
public:
BuildDocksStationWindow(const WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->LowerWidget(_settings_client.gui.station_show_coverage + BDSW_LT_OFF);
this->FindWindowPlacementAndResize(desc);
}
virtual ~BuildDocksStationWindow()
{
DeleteWindowById(WC_SELECT_STATION, 0);
}
virtual void OnPaint()
{
int rad = (_settings_game.station.modified_catchment) ? CA_DOCK : CA_UNMODIFIED;
this->DrawWidgets();
if (_settings_client.gui.station_show_coverage) {
SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
} else {
SetTileSelectSize(1, 1);
}
int text_end = DrawStationCoverageAreaText(4, 50, SCT_ALL, rad, false);
text_end = DrawStationCoverageAreaText(4, text_end + 4, SCT_ALL, rad, true) + 4;
if (text_end != this->widget[BDSW_BACKGROUND].bottom) {
this->SetDirty();
ResizeWindowForWidget(this, 2, 0, text_end - this->widget[BDSW_BACKGROUND].bottom);
this->SetDirty();
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BDSW_LT_OFF:
case BDSW_LT_ON:
this->RaiseWidget(_settings_client.gui.station_show_coverage + BDSW_LT_OFF);
_settings_client.gui.station_show_coverage = (widget != BDSW_LT_OFF);
this->LowerWidget(_settings_client.gui.station_show_coverage + BDSW_LT_OFF);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
}
}
virtual void OnTick()
{
CheckRedrawStationCoverage(this);
}
};
static const Widget _build_dock_station_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BDSW_CLOSE
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 147, 0, 13, STR_3068_DOCK, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BDSW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 14, 74, 0x0, STR_NULL}, // BDSW_BACKGROUND
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 14, 73, 30, 40, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE}, // BDSW_LT_OFF
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 74, 133, 30, 40, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA}, // BDSW_LT_ON
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 17, 30, STR_3066_COVERAGE_AREA_HIGHLIGHT, STR_NULL}, // BDSW_INFO
{ WIDGETS_END},
};
static const WindowDesc _build_dock_station_desc(
WDP_AUTO, WDP_AUTO, 148, 75, 148, 75,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_build_dock_station_widgets
);
static void ShowBuildDockStationPicker(Window *parent)
{
new BuildDocksStationWindow(&_build_dock_station_desc, parent);
}
struct BuildDocksDepotWindow : public PickerWindowBase {
private:
enum BuildDockDepotWidgets {
BDDW_CLOSE,
BDDW_CAPTION,
BDDW_BACKGROUND,
BDDW_X,
BDDW_Y,
};
static void UpdateDocksDirection()
{
if (_ship_depot_direction != AXIS_X) {
SetTileSelectSize(1, 2);
} else {
SetTileSelectSize(2, 1);
}
}
public:
BuildDocksDepotWindow(const WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->LowerWidget(_ship_depot_direction + BDDW_X);
UpdateDocksDirection();
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
DrawShipDepotSprite(67, 35, 0);
DrawShipDepotSprite(35, 51, 1);
DrawShipDepotSprite(135, 35, 2);
DrawShipDepotSprite(167, 51, 3);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BDDW_X:
case BDDW_Y:
this->RaiseWidget(_ship_depot_direction + BDDW_X);
_ship_depot_direction = (widget == BDDW_X ? AXIS_X : AXIS_Y);
this->LowerWidget(_ship_depot_direction + BDDW_X);
SndPlayFx(SND_15_BEEP);
UpdateDocksDirection();
this->SetDirty();
break;
}
}
};
static const Widget _build_docks_depot_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BDDW_CLOSE
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 203, 0, 13, STR_3800_SHIP_DEPOT_ORIENTATION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BDDW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 203, 14, 85, 0x0, STR_NULL}, // BDDW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 3, 100, 17, 82, 0x0, STR_3803_SELECT_SHIP_DEPOT_ORIENTATION}, // BDDW_X
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 103, 200, 17, 82, 0x0, STR_3803_SELECT_SHIP_DEPOT_ORIENTATION}, // BDDW_Y
{ WIDGETS_END},
};
static const WindowDesc _build_docks_depot_desc(
WDP_AUTO, WDP_AUTO, 204, 86, 204, 86,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_build_docks_depot_widgets
);
static void ShowBuildDocksDepotPicker(Window *parent)
{
new BuildDocksDepotWindow(&_build_docks_depot_desc, parent);
}
void InitializeDockGui()
{
_ship_depot_direction = AXIS_X;
}
| 18,869
|
C++
|
.cpp
| 410
| 43.74878
| 176
| 0.656474
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,068
|
gfxinit.cpp
|
EnergeticBark_OpenTTD-3DS/src/gfxinit.cpp
|
/* $Id$ */
/** @file gfxinit.cpp Initializing of the (GRF) graphics. */
#include "stdafx.h"
#include "debug.h"
#include "spritecache.h"
#include "fileio_func.h"
#include "fios.h"
#include "newgrf.h"
#include "md5.h"
#include "fontcache.h"
#include "gfx_func.h"
#include "settings_type.h"
#include "string_func.h"
#include "ini_type.h"
#include "table/sprites.h"
#include "table/palette_convert.h"
/** The currently used palette */
PaletteType _use_palette = PAL_AUTODETECT;
/** Whether the given NewGRFs must get a palette remap or not. */
bool _palette_remap_grf[MAX_FILE_SLOTS];
/** Palette map to go from the !_use_palette to the _use_palette */
const byte *_palette_remap = NULL;
/** Palette map to go from the _use_palette to the !_use_palette */
const byte *_palette_reverse_remap = NULL;
char *_ini_graphics_set;
/** Structure holding filename and MD5 information about a single file */
struct MD5File {
const char *filename; ///< filename
uint8 hash[16]; ///< md5 sum of the file
const char *missing_warning; ///< warning when this file is missing
};
/** Types of graphics in the base graphics set */
enum GraphicsFileType {
GFT_BASE, ///< Base sprites for all climates
GFT_LOGOS, ///< Logos, landscape icons and original terrain generator sprites
GFT_ARCTIC, ///< Landscape replacement sprites for arctic
GFT_TROPICAL, ///< Landscape replacement sprites for tropical
GFT_TOYLAND, ///< Landscape replacement sprites for toyland
GFT_EXTRA, ///< Extra sprites that were not part of the original sprites
MAX_GFT ///< We are looking for this amount of GRFs
};
/** Information about a single graphics set. */
struct GraphicsSet {
const char *name; ///< The name of the graphics set
const char *description; ///< Description of the graphics set
uint32 shortname; ///< Four letter short variant of the name
uint32 version; ///< The version of this graphics set
PaletteType palette; ///< Palette of this graphics set
MD5File files[MAX_GFT]; ///< All GRF files part of this set
uint found_grfs; ///< Number of the GRFs that could be found
GraphicsSet *next; ///< The next graphics set in this list
/** Free everything we allocated */
~GraphicsSet()
{
free((void*)this->name);
free((void*)this->description);
for (uint i = 0; i < MAX_GFT; i++) {
free((void*)this->files[i].filename);
free((void*)this->files[i].missing_warning);
}
delete this->next;
}
};
/** All graphics sets currently available */
static GraphicsSet *_available_graphics_sets = NULL;
/** The one and only graphics set that is currently being used. */
static const GraphicsSet *_used_graphics_set = NULL;
#include "table/files.h"
#include "table/landscape_sprite.h"
static const SpriteID * const _landscape_spriteindexes[] = {
_landscape_spriteindexes_1,
_landscape_spriteindexes_2,
_landscape_spriteindexes_3,
};
static uint LoadGrfFile(const char *filename, uint load_index, int file_index)
{
uint load_index_org = load_index;
uint sprite_id = 0;
FioOpenFile(file_index, filename);
DEBUG(sprite, 2, "Reading grf-file '%s'", filename);
while (LoadNextSprite(load_index, file_index, sprite_id)) {
load_index++;
sprite_id++;
if (load_index >= MAX_SPRITES) {
usererror("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files.");
}
}
DEBUG(sprite, 2, "Currently %i sprites are loaded", load_index);
return load_index - load_index_org;
}
void LoadSpritesIndexed(int file_index, uint *sprite_id, const SpriteID *index_tbl)
{
uint start;
while ((start = *index_tbl++) != END) {
uint end = *index_tbl++;
do {
bool b = LoadNextSprite(start, file_index, *sprite_id);
assert(b);
(*sprite_id)++;
} while (++start <= end);
}
}
static void LoadGrfIndexed(const char *filename, const SpriteID *index_tbl, int file_index)
{
uint sprite_id = 0;
FioOpenFile(file_index, filename);
DEBUG(sprite, 2, "Reading indexed grf-file '%s'", filename);
LoadSpritesIndexed(file_index, &sprite_id, index_tbl);
}
/**
* Calculate and check the MD5 hash of the supplied filename.
* @param file filename and expected MD5 hash for the given filename.
* @return true if the checksum is correct.
*/
static bool FileMD5(const MD5File file)
{
size_t size;
FILE *f = FioFOpenFile(file.filename, "rb", DATA_DIR, &size);
if (f != NULL) {
Md5 checksum;
uint8 buffer[1024];
uint8 digest[16];
size_t len;
while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
size -= len;
checksum.Append(buffer, len);
}
FioFCloseFile(f);
checksum.Finish(digest);
return memcmp(file.hash, digest, sizeof(file.hash)) == 0;
} else { // file not found
return false;
}
}
/**
* Determine the graphics pack that has to be used.
* The one with the most correct files wins.
*/
static bool DetermineGraphicsPack()
{
if (_used_graphics_set != NULL) return true;
const GraphicsSet *best = _available_graphics_sets;
for (const GraphicsSet *c = _available_graphics_sets; c != NULL; c = c->next) {
if (best->found_grfs < c->found_grfs ||
(best->found_grfs == c->found_grfs && (
(best->shortname == c->shortname && best->version < c->version) ||
(best->palette != _use_palette && c->palette == _use_palette)))) {
best = c;
}
}
_used_graphics_set = best;
return _used_graphics_set != NULL;
}
extern void UpdateNewGRFConfigPalette();
/**
* Determine the palette that has to be used.
* - forced palette via command line -> leave it that way
* - otherwise -> palette based on the graphics pack
*/
static void DeterminePalette()
{
assert(_used_graphics_set != NULL);
if (_use_palette >= MAX_PAL) _use_palette = _used_graphics_set->palette;
switch (_use_palette) {
case PAL_DOS:
_palette_remap = _palmap_w2d;
_palette_reverse_remap = _palmap_d2w;
break;
case PAL_WINDOWS:
_palette_remap = _palmap_d2w;
_palette_reverse_remap = _palmap_w2d;
break;
default:
NOT_REACHED();
}
UpdateNewGRFConfigPalette();
}
/**
* Checks whether the MD5 checksums of the files are correct.
*
* @note Also checks sample.cat and other required non-NewGRF GRFs for corruption.
*/
void CheckExternalFiles()
{
DeterminePalette();
DEBUG(grf, 1, "Using the %s base graphics set with the %s palette", _used_graphics_set->name, _use_palette == PAL_DOS ? "DOS" : "Windows");
static const size_t ERROR_MESSAGE_LENGTH = 128;
char error_msg[ERROR_MESSAGE_LENGTH * (MAX_GFT + 1)];
error_msg[0] = '\0';
char *add_pos = error_msg;
const char *last = lastof(error_msg);
for (uint i = 0; i < lengthof(_used_graphics_set->files); i++) {
if (!FileMD5(_used_graphics_set->files[i])) {
add_pos += seprintf(add_pos, last, "Your '%s' file is corrupted or missing! %s\n", _used_graphics_set->files[i].filename, _used_graphics_set->files[i].missing_warning);
}
}
bool sound = false;
for (uint i = 0; !sound && i < lengthof(_sound_sets); i++) {
sound = FileMD5(_sound_sets[i]);
}
if (!sound) {
add_pos += seprintf(add_pos, last, "Your 'sample.cat' file is corrupted or missing! You can find 'sample.cat' on your Transport Tycoon Deluxe CD-ROM.\n");
}
if (add_pos != error_msg) ShowInfoF(error_msg);
}
static void LoadSpriteTables()
{
memset(_palette_remap_grf, 0, sizeof(_palette_remap_grf));
uint i = FIRST_GRF_SLOT;
_palette_remap_grf[i] = (_use_palette != _used_graphics_set->palette);
LoadGrfFile(_used_graphics_set->files[GFT_BASE].filename, 0, i++);
/*
* The second basic file always starts at the given location and does
* contain a different amount of sprites depending on the "type"; DOS
* has a few sprites less. However, we do not care about those missing
* sprites as they are not shown anyway (logos in intro game).
*/
_palette_remap_grf[i] = (_use_palette != _used_graphics_set->palette);
LoadGrfFile(_used_graphics_set->files[GFT_LOGOS].filename, 4793, i++);
/*
* Load additional sprites for climates other than temperate.
* This overwrites some of the temperate sprites, such as foundations
* and the ground sprites.
*/
if (_settings_game.game_creation.landscape != LT_TEMPERATE) {
_palette_remap_grf[i] = (_use_palette != _used_graphics_set->palette);
LoadGrfIndexed(
_used_graphics_set->files[GFT_ARCTIC + _settings_game.game_creation.landscape - 1].filename,
_landscape_spriteindexes[_settings_game.game_creation.landscape - 1],
i++
);
}
/* Initialize the unicode to sprite mapping table */
InitializeUnicodeGlyphMap();
/*
* Load the base NewGRF with OTTD required graphics as first NewGRF.
* However, we do not want it to show up in the list of used NewGRFs,
* so we have to manually add it, and then remove it later.
*/
GRFConfig *top = _grfconfig;
GRFConfig *master = CallocT<GRFConfig>(1);
master->filename = strdup(_used_graphics_set->files[GFT_EXTRA].filename);
FillGRFDetails(master, false);
master->windows_paletted = (_used_graphics_set->palette == PAL_WINDOWS);
ClrBit(master->flags, GCF_INIT_ONLY);
master->next = top;
_grfconfig = master;
LoadNewGRF(SPR_NEWGRFS_BASE, i);
/* Free and remove the top element. */
ClearGRFConfig(&master);
_grfconfig = top;
}
void GfxLoadSprites()
{
DEBUG(sprite, 2, "Loading sprite set %d", _settings_game.game_creation.landscape);
GfxInitSpriteMem();
LoadSpriteTables();
GfxInitPalettes();
}
/**
* Try to read a single piece of metadata and return false if it doesn't exist.
* @param name the name of the item to fetch.
*/
#define fetch_metadata(name) \
item = metadata->GetItem(name, false); \
if (item == NULL || strlen(item->value) == 0) { \
DEBUG(grf, 0, "Base graphics set detail loading: %s field missing", name); \
return false; \
}
/** Names corresponding to the GraphicsFileType */
static const char *_gft_names[MAX_GFT] = { "base", "logos", "arctic", "tropical", "toyland", "extra" };
/**
* Read the graphics set information from a loaded ini.
* @param graphics the graphics set to write to
* @param ini the ini to read from
* @param path the path to this ini file (for filenames)
* @return true if loading was successful.
*/
static bool FillGraphicsSetDetails(GraphicsSet *graphics, IniFile *ini, const char *path)
{
memset(graphics, 0, sizeof(*graphics));
IniGroup *metadata = ini->GetGroup("metadata");
IniItem *item;
fetch_metadata("name");
graphics->name = strdup(item->value);
fetch_metadata("description");
graphics->description = strdup(item->value);
fetch_metadata("shortname");
for (uint i = 0; item->value[i] != '\0' && i < 4; i++) {
graphics->shortname |= ((uint8)item->value[i]) << (i * 8);
}
fetch_metadata("version");
graphics->version = atoi(item->value);
fetch_metadata("palette");
graphics->palette = (*item->value == 'D' || *item->value == 'd') ? PAL_DOS : PAL_WINDOWS;
/* For each of the graphics file types we want to find the file, MD5 checksums and warning messages. */
IniGroup *files = ini->GetGroup("files");
IniGroup *md5s = ini->GetGroup("md5s");
IniGroup *origin = ini->GetGroup("origin");
for (uint i = 0; i < MAX_GFT; i++) {
MD5File *file = &graphics->files[i];
/* Find the filename first. */
item = files->GetItem(_gft_names[i], false);
if (item == NULL) {
DEBUG(grf, 0, "No graphics file for: %s", _gft_names[i]);
return false;
}
const char *filename = item->value;
file->filename = MallocT<char>(strlen(filename) + strlen(path) + 1);
sprintf((char*)file->filename, "%s%s", path, filename);
/* Then find the MD5 checksum */
item = md5s->GetItem(filename, false);
if (item == NULL) {
DEBUG(grf, 0, "No MD5 checksum specified for: %s", filename);
return false;
}
char *c = item->value;
for (uint i = 0; i < sizeof(file->hash) * 2; i++, c++) {
uint j;
if ('0' <= *c && *c <= '9') {
j = *c - '0';
} else if ('a' <= *c && *c <= 'f') {
j = *c - 'a' + 10;
} else if ('A' <= *c && *c <= 'F') {
j = *c - 'A' + 10;
} else {
DEBUG(grf, 0, "Malformed MD5 checksum specified for: %s", filename);
return false;
}
if (i % 2 == 0) {
file->hash[i / 2] = j << 4;
} else {
file->hash[i / 2] |= j;
}
}
/* Then find the warning message when the file's missing */
item = origin->GetItem(filename, false);
if (item == NULL) item = origin->GetItem("default", false);
if (item == NULL) {
DEBUG(grf, 1, "No origin warning message specified for: %s", filename);
file->missing_warning = strdup("");
} else {
file->missing_warning = strdup(item->value);
}
if (FileMD5(*file)) graphics->found_grfs++;
}
return true;
}
/** Helper for scanning for files with GRF as extension */
class OBGFileScanner : FileScanner {
public:
/* virtual */ bool AddFile(const char *filename, size_t basepath_length);
/** Do the scan for OBGs. */
static uint DoScan()
{
OBGFileScanner fs;
return fs.Scan(".obg", DATA_DIR);
}
};
/**
* Try to add a graphics set with the given filename.
* @param filename the full path to the file to read
* @param basepath_length amount of characters to chop of before to get a relative DATA_DIR filename
* @return true if the file is added.
*/
bool OBGFileScanner::AddFile(const char *filename, size_t basepath_length)
{
bool ret = false;
DEBUG(grf, 1, "Found %s as base graphics set", filename);
GraphicsSet *graphics = new GraphicsSet();;
IniFile *ini = new IniFile();
ini->LoadFromDisk(filename);
char *path = strdup(filename + basepath_length);
char *psep = strrchr(path, PATHSEPCHAR);
if (psep != NULL) {
psep[1] = '\0';
} else {
*path = '\0';
}
if (FillGraphicsSetDetails(graphics, ini, path)) {
bool duplicate = false;
for (const GraphicsSet *c = _available_graphics_sets; !duplicate && c != NULL; c = c->next) {
duplicate = (strcmp(c->name, graphics->name) == 0 || c->shortname == graphics->shortname) && c->version == graphics->version;
}
if (duplicate) {
delete graphics;
} else {
GraphicsSet **last = &_available_graphics_sets;
while (*last != NULL) last = &(*last)->next;
*last = graphics;
ret = true;
}
} else {
delete graphics;
}
free(path);
delete ini;
return ret;
}
/** Scan for all Grahpics sets */
void FindGraphicsSets()
{
DEBUG(grf, 1, "Scanning for Graphics sets");
OBGFileScanner::DoScan();
}
/**
* Set the graphics set to be used.
* @param name of the graphics set to use
* @return true if it could be loaded
*/
bool SetGraphicsSet(const char *name)
{
if (StrEmpty(name)) {
if (!DetermineGraphicsPack()) return false;
CheckExternalFiles();
return true;
}
for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) {
if (strcmp(name, g->name) == 0) {
_used_graphics_set = g;
CheckExternalFiles();
return true;
}
}
return false;
}
/**
* Returns a list with the graphics sets.
* @param p where to print to
* @param last the last character to print to
* @return the last printed character
*/
char *GetGraphicsSetsList(char *p, const char *last)
{
p += seprintf(p, last, "List of graphics sets:\n");
for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) {
if (g->found_grfs <= 1) continue;
p += seprintf(p, last, "%18s: %s", g->name, g->description);
int difference = MAX_GFT - g->found_grfs;
if (difference != 0) {
p += seprintf(p, last, " (missing %i file%s)\n", difference, difference == 1 ? "" : "s");
} else {
p += seprintf(p, last, "\n");
}
}
p += seprintf(p, last, "\n");
return p;
}
#if defined(ENABLE_NETWORK)
#include "network/network_content.h"
/**
* Check whether we have an graphics with the exact characteristics as ci.
* @param ci the characteristics to search on (shortname and md5sum)
* @param md5sum whether to check the MD5 checksum
* @return true iff we have an graphics set matching.
*/
bool HasGraphicsSet(const ContentInfo *ci, bool md5sum)
{
assert(ci->type == CONTENT_TYPE_BASE_GRAPHICS);
for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) {
if (g->found_grfs <= 1) continue;
if (g->shortname != ci->unique_id) continue;
if (!md5sum) return true;
byte md5[16];
memset(md5, 0, sizeof(md5));
for (uint i = 0; i < MAX_GFT; i++) {
for (uint j = 0; j < sizeof(md5); j++) {
md5[j] ^= g->files[i].hash[j];
}
}
if (memcmp(md5, ci->md5sum, sizeof(md5)) == 0) return true;
}
return false;
}
#endif /* ENABLE_NETWORK */
/**
* Count the number of available graphics sets.
*/
int GetNumGraphicsSets()
{
int n = 0;
for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) {
if (g != _used_graphics_set && g->found_grfs <= 1) continue;
n++;
}
return n;
}
/**
* Get the index of the currently active graphics set
*/
int GetIndexOfCurrentGraphicsSet()
{
int n = 0;
for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) {
if (g == _used_graphics_set) return n;
if (g->found_grfs <= 1) continue;
n++;
}
return -1;
}
/**
* Get the name of the graphics set at the specified index
*/
const char *GetGraphicsSetName(int index)
{
for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) {
if (g != _used_graphics_set && g->found_grfs <= 1) continue;
if (index == 0) return g->name;
index--;
}
error("GetGraphicsSetName: index %d out of range", index);
}
| 17,373
|
C++
|
.cpp
| 512
| 31.496094
| 171
| 0.679952
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,069
|
oldpool.cpp
|
EnergeticBark_OpenTTD-3DS/src/oldpool.cpp
|
/* $Id$ */
/** @file oldpool.cpp Implementation of the old pool. */
#include "stdafx.h"
#include "debug.h"
#include "oldpool.h"
#include "core/alloc_func.hpp"
/**
* Clean a pool in a safe way (does free all blocks)
*/
void OldMemoryPoolBase::CleanPool()
{
uint i;
DEBUG(misc, 4, "[Pool] (%s) cleaning pool..", this->name);
this->cleaning_pool = true;
/* Free all blocks */
for (i = 0; i < this->current_blocks; i++) {
if (this->clean_block_proc != NULL) {
this->clean_block_proc(i * (1 << this->block_size_bits), (i + 1) * (1 << this->block_size_bits) - 1);
}
free(this->blocks[i]);
}
this->cleaning_pool = false;
/* Free the block itself */
free(this->blocks);
/* Clear up some critical data */
this->total_items = 0;
this->current_blocks = 0;
this->blocks = NULL;
this->first_free_index = 0;
}
/**
* This function tries to increase the size of array by adding
* 1 block too it
*
* @return Returns false if the pool could not be increased
*/
bool OldMemoryPoolBase::AddBlockToPool()
{
/* Is the pool at his max? */
if (this->max_blocks == this->current_blocks) return false;
this->total_items = (this->current_blocks + 1) * (1 << this->block_size_bits);
DEBUG(misc, 4, "[Pool] (%s) increasing size of pool to %d items (%d bytes)", this->name, this->total_items, this->total_items * this->item_size);
/* Increase the poolsize */
this->blocks = ReallocT(this->blocks, this->current_blocks + 1);
/* Allocate memory to the new block item */
this->blocks[this->current_blocks] = CallocT<byte>(this->item_size * (1 << this->block_size_bits));
/* Call a custom function if defined (e.g. to fill indexes) */
if (this->new_block_proc != NULL) this->new_block_proc(this->current_blocks * (1 << this->block_size_bits));
/* We have a new block */
this->current_blocks++;
return true;
}
/**
* Adds blocks to the pool if needed (and possible) till index fits inside the pool
*
* @return Returns false if adding failed
*/
bool OldMemoryPoolBase::AddBlockIfNeeded(uint index)
{
while (index >= this->total_items) {
if (!this->AddBlockToPool()) return false;
}
return true;
}
| 2,130
|
C++
|
.cpp
| 64
| 31.203125
| 146
| 0.676916
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,070
|
newgrf_config.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_config.cpp
|
/* $Id$ */
/** @file newgrf_config.cpp Finding NewGRFs and configuring them. */
#include "stdafx.h"
#include "debug.h"
#include "md5.h"
#include "newgrf.h"
#include "string_func.h"
#include "gamelog.h"
#include "network/network_type.h"
#include "gfx_func.h"
#include "fileio_func.h"
#include "fios.h"
GRFConfig *_all_grfs;
GRFConfig *_grfconfig;
GRFConfig *_grfconfig_newgame;
GRFConfig *_grfconfig_static;
/**
* Update the palettes of the graphics from the config file.
* This is needed because the config file gets read and parsed
* before the palette is chosen (one can configure the base
* graphics set governing the palette in the config after all).
* As a result of this we update the settings from the config
* once we have determined the palette.
*/
void UpdateNewGRFConfigPalette()
{
for (GRFConfig *c = _grfconfig_newgame; c != NULL; c = c->next) c->windows_paletted = (_use_palette == PAL_WINDOWS);
for (GRFConfig *c = _grfconfig_static; c != NULL; c = c->next) c->windows_paletted = (_use_palette == PAL_WINDOWS);
}
/* Calculate the MD5 Sum for a GRF */
static bool CalcGRFMD5Sum(GRFConfig *config)
{
FILE *f;
Md5 checksum;
uint8 buffer[1024];
size_t len, size;
/* open the file */
f = FioFOpenFile(config->filename, "rb", DATA_DIR, &size);
if (f == NULL) return false;
/* calculate md5sum */
while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
size -= len;
checksum.Append(buffer, len);
}
checksum.Finish(config->md5sum);
FioFCloseFile(f);
return true;
}
/* Find the GRFID and calculate the md5sum */
bool FillGRFDetails(GRFConfig *config, bool is_static)
{
if (!FioCheckFileExists(config->filename)) {
config->status = GCS_NOT_FOUND;
return false;
}
/* Find and load the Action 8 information */
LoadNewGRFFile(config, CONFIG_SLOT, GLS_FILESCAN);
/* Skip if the grfid is 0 (not read) or 0xFFFFFFFF (ttdp system grf) */
if (config->grfid == 0 || config->grfid == 0xFFFFFFFF || config->IsOpenTTDBaseGRF()) return false;
if (is_static) {
/* Perform a 'safety scan' for static GRFs */
LoadNewGRFFile(config, 62, GLS_SAFETYSCAN);
/* GCF_UNSAFE is set if GLS_SAFETYSCAN finds unsafe actions */
if (HasBit(config->flags, GCF_UNSAFE)) return false;
}
config->windows_paletted = (_use_palette == PAL_WINDOWS);
return CalcGRFMD5Sum(config);
}
void ClearGRFConfig(GRFConfig **config)
{
/* GCF_COPY as in NOT strdupped/alloced the filename, name and info */
if (!HasBit((*config)->flags, GCF_COPY)) {
free((*config)->filename);
free((*config)->name);
free((*config)->info);
if ((*config)->error != NULL) {
free((*config)->error->custom_message);
free((*config)->error->data);
free((*config)->error);
}
}
free(*config);
*config = NULL;
}
/* Clear a GRF Config list */
void ClearGRFConfigList(GRFConfig **config)
{
GRFConfig *c, *next;
for (c = *config; c != NULL; c = next) {
next = c->next;
ClearGRFConfig(&c);
}
*config = NULL;
}
/** Copy a GRF Config list
* @param dst pointer to destination list
* @param src pointer to source list values
* @param init_only the copied GRF will be processed up to GLS_INIT
* @return pointer to the last value added to the destination list */
GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_only)
{
/* Clear destination as it will be overwritten */
ClearGRFConfigList(dst);
for (; src != NULL; src = src->next) {
GRFConfig *c = CallocT<GRFConfig>(1);
*c = *src;
if (src->filename != NULL) c->filename = strdup(src->filename);
if (src->name != NULL) c->name = strdup(src->name);
if (src->info != NULL) c->info = strdup(src->info);
if (src->error != NULL) {
c->error = CallocT<GRFError>(1);
memcpy(c->error, src->error, sizeof(GRFError));
if (src->error->data != NULL) c->error->data = strdup(src->error->data);
if (src->error->custom_message != NULL) c->error->custom_message = strdup(src->error->custom_message);
}
ClrBit(c->flags, GCF_INIT_ONLY);
if (init_only) SetBit(c->flags, GCF_INIT_ONLY);
*dst = c;
dst = &c->next;
}
return dst;
}
/**
* Removes duplicates from lists of GRFConfigs. These duplicates
* are introduced when the _grfconfig_static GRFs are appended
* to the _grfconfig on a newgame or savegame. As the parameters
* of the static GRFs could be different that the parameters of
* the ones used non-statically. This can result in desyncs in
* multiplayers, so the duplicate static GRFs have to be removed.
*
* This function _assumes_ that all static GRFs are placed after
* the non-static GRFs.
*
* @param list the list to remove the duplicates from
*/
static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
{
GRFConfig *prev;
GRFConfig *cur;
if (list == NULL) return;
for (prev = list, cur = list->next; cur != NULL; prev = cur, cur = cur->next) {
if (cur->grfid != list->grfid) continue;
prev->next = cur->next;
ClearGRFConfig(&cur);
cur = prev; // Just go back one so it continues as normal later on
}
RemoveDuplicatesFromGRFConfigList(list->next);
}
/**
* Appends the static GRFs to a list of GRFs
* @param dst the head of the list to add to
*/
void AppendStaticGRFConfigs(GRFConfig **dst)
{
GRFConfig **tail = dst;
while (*tail != NULL) tail = &(*tail)->next;
CopyGRFConfigList(tail, _grfconfig_static, false);
RemoveDuplicatesFromGRFConfigList(*dst);
}
/** Appends an element to a list of GRFs
* @param dst the head of the list to add to
* @param el the new tail to be */
void AppendToGRFConfigList(GRFConfig **dst, GRFConfig *el)
{
GRFConfig **tail = dst;
while (*tail != NULL) tail = &(*tail)->next;
*tail = el;
RemoveDuplicatesFromGRFConfigList(*dst);
}
/* Reset the current GRF Config to either blank or newgame settings */
void ResetGRFConfig(bool defaults)
{
CopyGRFConfigList(&_grfconfig, _grfconfig_newgame, !defaults);
AppendStaticGRFConfigs(&_grfconfig);
}
/** Check if all GRFs in the GRF config from a savegame can be loaded.
* @return will return any of the following 3 values:<br>
* <ul>
* <li> GLC_ALL_GOOD: No problems occured, all GRF files were found and loaded
* <li> GLC_COMPATIBLE: For one or more GRF's no exact match was found, but a
* compatible GRF with the same grfid was found and used instead
* <li> GLC_NOT_FOUND: For one or more GRF's no match was found at all
* </ul> */
GRFListCompatibility IsGoodGRFConfigList()
{
GRFListCompatibility res = GLC_ALL_GOOD;
for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
const GRFConfig *f = FindGRFConfig(c->grfid, c->md5sum);
if (f == NULL) {
char buf[256];
/* If we have not found the exactly matching GRF try to find one with the
* same grfid, as it most likely is compatible */
f = FindGRFConfig(c->grfid);
if (f != NULL) {
md5sumToString(buf, lastof(buf), c->md5sum);
DEBUG(grf, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c->grfid), c->filename, buf);
SetBit(c->flags, GCF_COMPATIBLE);
/* Non-found has precedence over compatibility load */
if (res != GLC_NOT_FOUND) res = GLC_COMPATIBLE;
GamelogGRFCompatible(f);
goto compatible_grf;
}
/* No compatible grf was found, mark it as disabled */
md5sumToString(buf, lastof(buf), c->md5sum);
DEBUG(grf, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c->grfid), c->filename, buf);
GamelogGRFRemove(c->grfid);
c->status = GCS_NOT_FOUND;
res = GLC_NOT_FOUND;
} else {
compatible_grf:
DEBUG(grf, 1, "Loading GRF %08X from %s", BSWAP32(f->grfid), f->filename);
/* The filename could be the filename as in the savegame. As we need
* to load the GRF here, we need the correct filename, so overwrite that
* in any case and set the name and info when it is not set already.
* When the GCF_COPY flag is set, it is certain that the filename is
* already a local one, so there is no need to replace it. */
if (!HasBit(c->flags, GCF_COPY)) {
free(c->filename);
c->filename = strdup(f->filename);
memcpy(c->md5sum, f->md5sum, sizeof(c->md5sum));
if (c->name == NULL && f->name != NULL) c->name = strdup(f->name);
if (c->info == NULL && f->info != NULL) c->info = strdup(f->info);
c->error = NULL;
}
}
}
return res;
}
/** Helper for scanning for files with GRF as extension */
class GRFFileScanner : FileScanner {
public:
/* virtual */ bool AddFile(const char *filename, size_t basepath_length);
/** Do the scan for GRFs. */
static uint DoScan()
{
GRFFileScanner fs;
return fs.Scan(".grf", DATA_DIR);
}
};
bool GRFFileScanner::AddFile(const char *filename, size_t basepath_length)
{
GRFConfig *c = CallocT<GRFConfig>(1);
c->filename = strdup(filename + basepath_length);
bool added = true;
if (FillGRFDetails(c, false)) {
if (_all_grfs == NULL) {
_all_grfs = c;
} else {
/* Insert file into list at a position determined by its
* name, so the list is sorted as we go along */
GRFConfig **pd, *d;
bool stop = false;
for (pd = &_all_grfs; (d = *pd) != NULL; pd = &d->next) {
if (c->grfid == d->grfid && memcmp(c->md5sum, d->md5sum, sizeof(c->md5sum)) == 0) added = false;
/* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
* before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
* just after the first with the same name. Avoids doubles in the list. */
if (strcasecmp(c->name, d->name) <= 0) {
stop = true;
} else if (stop) {
break;
}
}
if (added) {
c->next = d;
*pd = c;
}
}
} else {
added = false;
}
if (!added) {
/* File couldn't be opened, or is either not a NewGRF or is a
* 'system' NewGRF or it's already known, so forget about it. */
free(c->filename);
free(c->name);
free(c->info);
free(c);
}
return added;
}
/**
* Simple sorter for GRFS
* @param p1 the first GRFConfig *
* @param p2 the second GRFConfig *
* @return the same strcmp would return for the name of the NewGRF.
*/
static int CDECL GRFSorter(const void *p1, const void *p2)
{
const GRFConfig *c1 = *(const GRFConfig **)p1;
const GRFConfig *c2 = *(const GRFConfig **)p2;
return strcasecmp(c1->name != NULL ? c1->name : c1->filename,
c2->name != NULL ? c2->name : c2->filename);
}
/* Scan for all NewGRFs */
void ScanNewGRFFiles()
{
ClearGRFConfigList(&_all_grfs);
DEBUG(grf, 1, "Scanning for NewGRFs");
uint num = GRFFileScanner::DoScan();
DEBUG(grf, 1, "Scan complete, found %d files", num);
if (num == 0 || _all_grfs == NULL) return;
/* Sort the linked list using quicksort.
* For that we first have to make an array, the qsort and
* then remake the linked list. */
GRFConfig **to_sort = MallocT<GRFConfig*>(num);
uint i = 0;
for (GRFConfig *p = _all_grfs; p != NULL; p = p->next, i++) {
to_sort[i] = p;
}
/* Number of files is not necessarily right */
num = i;
qsort(to_sort, num, sizeof(GRFConfig*), GRFSorter);
for (i = 1; i < num; i++) {
to_sort[i - 1]->next = to_sort[i];
}
to_sort[num - 1]->next = NULL;
_all_grfs = to_sort[0];
free(to_sort);
}
/* Find a NewGRF in the scanned list, if md5sum is NULL, we don't care about it*/
const GRFConfig *FindGRFConfig(uint32 grfid, const uint8 *md5sum)
{
for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
if (c->grfid == grfid) {
if (md5sum == NULL) return c;
if (memcmp(md5sum, c->md5sum, sizeof(c->md5sum)) == 0) return c;
}
}
return NULL;
}
#ifdef ENABLE_NETWORK
/** Structure for UnknownGRFs; this is a lightweight variant of GRFConfig */
struct UnknownGRF : public GRFIdentifier {
UnknownGRF *next;
char name[NETWORK_GRF_NAME_LENGTH];
};
/**
* Finds the name of a NewGRF in the list of names for unknown GRFs. An
* unknown GRF is a GRF where the .grf is not found during scanning.
*
* The names are resolved via UDP calls to servers that should know the name,
* though the replies may not come. This leaves "<Unknown>" as name, though
* that shouldn't matter _very_ much as they need GRF crawler or so to look
* up the GRF anyway and that works better with the GRF ID.
*
* @param grfid the GRF ID part of the 'unique' GRF identifier
* @param md5sum the MD5 checksum part of the 'unique' GRF identifier
* @param create whether to create a new GRFConfig if the GRFConfig did not
* exist in the fake list of GRFConfigs.
* @return the GRFConfig with the given GRF ID and MD5 checksum or NULL when
* it does not exist and create is false. This value must NEVER be
* freed by the caller.
*/
char *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
{
UnknownGRF *grf;
static UnknownGRF *unknown_grfs = NULL;
for (grf = unknown_grfs; grf != NULL; grf = grf->next) {
if (grf->grfid == grfid) {
if (memcmp(md5sum, grf->md5sum, sizeof(grf->md5sum)) == 0) return grf->name;
}
}
if (!create) return NULL;
grf = CallocT<UnknownGRF>(1);
grf->grfid = grfid;
grf->next = unknown_grfs;
strecpy(grf->name, UNKNOWN_GRF_NAME_PLACEHOLDER, lastof(grf->name));
memcpy(grf->md5sum, md5sum, sizeof(grf->md5sum));
unknown_grfs = grf;
return grf->name;
}
#endif /* ENABLE_NETWORK */
/* Retrieve a NewGRF from the current config by its grfid */
GRFConfig *GetGRFConfig(uint32 grfid, uint32 mask)
{
GRFConfig *c;
for (c = _grfconfig; c != NULL; c = c->next) {
if ((c->grfid & mask) == (grfid & mask)) return c;
}
return NULL;
}
/* Build a space separated list of parameters, and terminate */
char *GRFBuildParamList(char *dst, const GRFConfig *c, const char *last)
{
uint i;
/* Return an empty string if there are no parameters */
if (c->num_params == 0) return strecpy(dst, "", last);
for (i = 0; i < c->num_params; i++) {
if (i > 0) dst = strecpy(dst, " ", last);
dst += seprintf(dst, last, "%d", c->param[i]);
}
return dst;
}
/** Base GRF ID for OpenTTD's base graphics GRFs. */
static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID = BSWAP32(0xFF4F5400);
/**
* Checks whether this GRF is a OpenTTD base graphic GRF.
* @return true if and only if it is a base GRF.
*/
bool GRFConfig::IsOpenTTDBaseGRF() const
{
return (this->grfid & 0x00FFFFFF) == OPENTTD_GRAPHICS_BASE_GRF_ID;
}
| 14,275
|
C++
|
.cpp
| 404
| 32.826733
| 121
| 0.686135
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,071
|
signal.cpp
|
EnergeticBark_OpenTTD-3DS/src/signal.cpp
|
/* $Id$ */
/** @file signal.cpp functions related to rail signals updating */
#include "stdafx.h"
#include "debug.h"
#include "station_map.h"
#include "tunnelbridge_map.h"
#include "vehicle_func.h"
#include "vehicle_base.h"
#include "functions.h"
/** these are the maximums used for updating signal blocks */
enum {
SIG_TBU_SIZE = 64, ///< number of signals entering to block
SIG_TBD_SIZE = 256, ///< number of intersections - open nodes in current block
SIG_GLOB_SIZE = 128, ///< number of open blocks (block can be opened more times until detected)
SIG_GLOB_UPDATE = 64, ///< how many items need to be in _globset to force update
};
/* need to typecast to compile with MorphOS */
assert_compile((int)SIG_GLOB_UPDATE <= (int)SIG_GLOB_SIZE);
/** incidating trackbits with given enterdir */
static const TrackBitsByte _enterdir_to_trackbits[DIAGDIR_END] = {
{TRACK_BIT_3WAY_NE},
{TRACK_BIT_3WAY_SE},
{TRACK_BIT_3WAY_SW},
{TRACK_BIT_3WAY_NW}
};
/** incidating trackdirbits with given enterdir */
static const TrackdirBitsShort _enterdir_to_trackdirbits[DIAGDIR_END] = {
{TRACKDIR_BIT_X_SW | TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_RIGHT_S},
{TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_LOWER_W | TRACKDIR_BIT_RIGHT_N},
{TRACKDIR_BIT_X_NE | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_LEFT_N},
{TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E | TRACKDIR_BIT_LEFT_S}
};
/**
* Set containing 'items' items of 'tile and Tdir'
* No tree structure is used because it would cause
* slowdowns in most usual cases
*/
template <typename Tdir, uint items>
struct SmallSet {
private:
uint n; // actual number of units
bool overflowed; // did we try to oveflow the set?
const char *name; // name, used for debugging purposes...
/** Element of set */
struct SSdata {
TileIndex tile;
Tdir dir;
} data[items];
public:
/** Constructor - just set default values and 'name' */
SmallSet(const char *name) : n(0), overflowed(false), name(name) { }
/** Reset variables to default values */
void Reset()
{
this->n = 0;
this->overflowed = false;
}
/**
* Returns value of 'oveflowed'
* @return did we try to overflow the set?
*/
bool Overflowed()
{
return this->overflowed;
}
/**
* Checks for empty set
* @return is the set empty?
*/
bool IsEmpty()
{
return this->n == 0;
}
/**
* Checks for full set
* @return is the set full?
*/
bool IsFull()
{
return this->n == lengthof(data);
}
/**
* Reads the number of items
* @return current number of items
*/
uint Items()
{
return this->n;
}
/**
* Tries to remove first instance of given tile and dir
* @param tile tile
* @param dir and dir to remove
* @return element was found and removed
*/
bool Remove(TileIndex tile, Tdir dir)
{
for (uint i = 0; i < this->n; i++) {
if (this->data[i].tile == tile && this->data[i].dir == dir) {
this->data[i] = this->data[--this->n];
return true;
}
}
return false;
}
/**
* Tries to find given tile and dir in the set
* @param tile tile
* @param dir and dir to find
* @return true iff the tile & dir elemnt was found
*/
bool IsIn(TileIndex tile, Tdir dir)
{
for (uint i = 0; i < this->n; i++) {
if (this->data[i].tile == tile && this->data[i].dir == dir) return true;
}
return false;
}
/**
* Adds tile & dir into the set, checks for full set
* Sets the 'overflowed' flag if the set was full
* @param tile tile
* @param dir and dir to add
* @return true iff the item could be added (set wasn't full)
*/
bool Add(TileIndex tile, Tdir dir)
{
if (this->IsFull()) {
overflowed = true;
DEBUG(misc, 0, "SignalSegment too complex. Set %s is full (maximum %d)", name, items);
return false; // set is full
}
this->data[this->n].tile = tile;
this->data[this->n].dir = dir;
this->n++;
return true;
}
/**
* Reads the last added element into the set
* @param tile pointer where tile is written to
* @param dir pointer where dir is written to
* @return false iff the set was empty
*/
bool Get(TileIndex *tile, Tdir *dir)
{
if (this->n == 0) return false;
this->n--;
*tile = this->data[this->n].tile;
*dir = this->data[this->n].dir;
return true;
}
};
static SmallSet<Trackdir, SIG_TBU_SIZE> _tbuset("_tbuset"); ///< set of signals that will be updated
static SmallSet<DiagDirection, SIG_TBD_SIZE> _tbdset("_tbdset"); ///< set of open nodes in current signal block
static SmallSet<DiagDirection, SIG_GLOB_SIZE> _globset("_globset"); ///< set of places to be updated in following runs
/** Check whether there is a train on rail, not in a depot */
static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
{
if (v->type != VEH_TRAIN || v->u.rail.track == TRACK_BIT_DEPOT) return NULL;
return v;
}
/**
* Perform some operations before adding data into Todo set
* The new and reverse direction is removed from _globset, because we are sure
* it doesn't need to be checked again
* Also, remove reverse direction from _tbdset
* This is the 'core' part so the graph seaching won't enter any tile twice
*
* @param t1 tile we are entering
* @param d1 direction (tile side) we are entering
* @param t2 tile we are leaving
* @param d2 direction (tile side) we are leaving
* @return false iff reverse direction was in Todo set
*/
static inline bool CheckAddToTodoSet(TileIndex t1, DiagDirection d1, TileIndex t2, DiagDirection d2)
{
_globset.Remove(t1, d1); // it can be in Global but not in Todo
_globset.Remove(t2, d2); // remove in all cases
assert(!_tbdset.IsIn(t1, d1)); // it really shouldn't be there already
if (_tbdset.Remove(t2, d2)) return false;
return true;
}
/**
* Perform some operations before adding data into Todo set
* The new and reverse direction is removed from Global set, because we are sure
* it doesn't need to be checked again
* Also, remove reverse direction from Todo set
* This is the 'core' part so the graph seaching won't enter any tile twice
*
* @param t1 tile we are entering
* @param d1 direction (tile side) we are entering
* @param t2 tile we are leaving
* @param d2 direction (tile side) we are leaving
* @return false iff the Todo buffer would be overrun
*/
static inline bool MaybeAddToTodoSet(TileIndex t1, DiagDirection d1, TileIndex t2, DiagDirection d2)
{
if (!CheckAddToTodoSet(t1, d1, t2, d2)) return true;
return _tbdset.Add(t1, d1);
}
/** Current signal block state flags */
enum SigFlags {
SF_NONE = 0,
SF_TRAIN = 1 << 0, ///< train found in segment
SF_EXIT = 1 << 1, ///< exitsignal found
SF_EXIT2 = 1 << 2, ///< two or more exits found
SF_GREEN = 1 << 3, ///< green exitsignal found
SF_GREEN2 = 1 << 4, ///< two or more green exits found
SF_FULL = 1 << 5, ///< some of buffers was full, do not continue
SF_PBS = 1 << 6, ///< pbs signal found
};
DECLARE_ENUM_AS_BIT_SET(SigFlags)
/**
* Search signal block
*
* @param owner owner whose signals we are updating
* @return SigFlags
*/
static SigFlags ExploreSegment(Owner owner)
{
SigFlags flags = SF_NONE;
TileIndex tile;
DiagDirection enterdir;
while (_tbdset.Get(&tile, &enterdir)) {
TileIndex oldtile = tile; // tile we are leaving
DiagDirection exitdir = enterdir == INVALID_DIAGDIR ? INVALID_DIAGDIR : ReverseDiagDir(enterdir); // expected new exit direction (for straight line)
switch (GetTileType(tile)) {
case MP_RAILWAY: {
if (GetTileOwner(tile) != owner) continue; // do not propagate signals on others' tiles (remove for tracksharing)
if (IsRailDepot(tile)) {
if (enterdir == INVALID_DIAGDIR) { // from 'inside' - train just entered or left the depot
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
exitdir = GetRailDepotDirection(tile);
tile += TileOffsByDiagDir(exitdir);
enterdir = ReverseDiagDir(exitdir);
break;
} else if (enterdir == GetRailDepotDirection(tile)) { // entered a depot
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
continue;
} else {
continue;
}
}
if (GetRailTileType(tile) == RAIL_TILE_WAYPOINT) {
if (GetWaypointAxis(tile) != DiagDirToAxis(enterdir)) continue;
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
tile += TileOffsByDiagDir(exitdir);
/* enterdir and exitdir stay the same */
break;
}
TrackBits tracks = GetTrackBits(tile); // trackbits of tile
TrackBits tracks_masked = (TrackBits)(tracks & _enterdir_to_trackbits[enterdir]); // only incidating trackbits
if (tracks == TRACK_BIT_HORZ || tracks == TRACK_BIT_VERT) { // there is exactly one incidating track, no need to check
tracks = tracks_masked;
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, &tracks, &EnsureNoTrainOnTrackProc)) flags |= SF_TRAIN;
} else {
if (tracks_masked == TRACK_BIT_NONE) continue; // no incidating track
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
}
if (HasSignals(tile)) { // there is exactly one track - not zero, because there is exit from this tile
Track track = TrackBitsToTrack(tracks_masked); // mask TRACK_BIT_X and Y too
if (HasSignalOnTrack(tile, track)) { // now check whole track, not trackdir
SignalType sig = GetSignalType(tile, track);
Trackdir trackdir = (Trackdir)FindFirstBit((tracks * 0x101) & _enterdir_to_trackdirbits[enterdir]);
Trackdir reversedir = ReverseTrackdir(trackdir);
/* add (tile, reversetrackdir) to 'to-be-updated' set when there is
* ANY conventional signal in REVERSE direction
* (if it is a presignal EXIT and it changes, it will be added to 'to-be-done' set later) */
if (HasSignalOnTrackdir(tile, reversedir)) {
if (IsPbsSignal(sig)) {
flags |= SF_PBS;
} else if (!_tbuset.Add(tile, reversedir)) {
return flags | SF_FULL;
}
}
if (HasSignalOnTrackdir(tile, trackdir) && !IsOnewaySignal(tile, track)) flags |= SF_PBS;
/* if it is a presignal EXIT in OUR direction and we haven't found 2 green exits yes, do special check */
if (!(flags & SF_GREEN2) && IsPresignalExit(tile, track) && HasSignalOnTrackdir(tile, trackdir)) { // found presignal exit
if (flags & SF_EXIT) flags |= SF_EXIT2; // found two (or more) exits
flags |= SF_EXIT; // found at least one exit - allow for compiler optimizations
if (GetSignalStateByTrackdir(tile, trackdir) == SIGNAL_STATE_GREEN) { // found green presignal exit
if (flags & SF_GREEN) flags |= SF_GREEN2;
flags |= SF_GREEN;
}
}
continue;
}
}
for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) { // test all possible exit directions
if (dir != enterdir && tracks & _enterdir_to_trackbits[dir]) { // any track incidating?
TileIndex newtile = tile + TileOffsByDiagDir(dir); // new tile to check
DiagDirection newdir = ReverseDiagDir(dir); // direction we are entering from
if (!MaybeAddToTodoSet(newtile, newdir, tile, dir)) return flags | SF_FULL;
}
}
continue; // continue the while() loop
}
case MP_STATION:
if (!IsRailwayStation(tile)) continue;
if (GetTileOwner(tile) != owner) continue;
if (DiagDirToAxis(enterdir) != GetRailStationAxis(tile)) continue; // different axis
if (IsStationTileBlocked(tile)) continue; // 'eye-candy' station tile
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
tile += TileOffsByDiagDir(exitdir);
break;
case MP_ROAD:
if (!IsLevelCrossing(tile)) continue;
if (GetTileOwner(tile) != owner) continue;
if (DiagDirToAxis(enterdir) == GetCrossingRoadAxis(tile)) continue; // different axis
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
tile += TileOffsByDiagDir(exitdir);
break;
case MP_TUNNELBRIDGE: {
if (GetTileOwner(tile) != owner) continue;
if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
DiagDirection dir = GetTunnelBridgeDirection(tile);
if (enterdir == INVALID_DIAGDIR) { // incoming from the wormhole
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
enterdir = dir;
exitdir = ReverseDiagDir(dir);
tile += TileOffsByDiagDir(exitdir); // just skip to next tile
} else { // NOT incoming from the wormhole!
if (ReverseDiagDir(enterdir) != dir) continue;
if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
tile = GetOtherTunnelBridgeEnd(tile); // just skip to exit tile
enterdir = INVALID_DIAGDIR;
exitdir = INVALID_DIAGDIR;
}
}
break;
default:
continue; // continue the while() loop
}
if (!MaybeAddToTodoSet(tile, enterdir, oldtile, exitdir)) return flags | SF_FULL;
}
return flags;
}
/**
* Update signals around segment in _tbuset
*
* @param flags info about segment
*/
static void UpdateSignalsAroundSegment(SigFlags flags)
{
TileIndex tile;
Trackdir trackdir;
while (_tbuset.Get(&tile, &trackdir)) {
assert(HasSignalOnTrackdir(tile, trackdir));
SignalType sig = GetSignalType(tile, TrackdirToTrack(trackdir));
SignalState newstate = SIGNAL_STATE_GREEN;
/* determine whether the new state is red */
if (flags & SF_TRAIN) {
/* train in the segment */
newstate = SIGNAL_STATE_RED;
} else {
/* is it a bidir combo? - then do not count its other signal direction as exit */
if (sig == SIGTYPE_COMBO && HasSignalOnTrackdir(tile, ReverseTrackdir(trackdir))) {
/* at least one more exit */
if (flags & SF_EXIT2 &&
/* no green exit */
(!(flags & SF_GREEN) ||
/* only one green exit, and it is this one - so all other exits are red */
(!(flags & SF_GREEN2) && GetSignalStateByTrackdir(tile, ReverseTrackdir(trackdir)) == SIGNAL_STATE_GREEN))) {
newstate = SIGNAL_STATE_RED;
}
} else { // entry, at least one exit, no green exit
if (IsPresignalEntry(tile, TrackdirToTrack(trackdir)) && flags & SF_EXIT && !(flags & SF_GREEN)) newstate = SIGNAL_STATE_RED;
}
}
/* only when the state changes */
if (newstate != GetSignalStateByTrackdir(tile, trackdir)) {
if (IsPresignalExit(tile, TrackdirToTrack(trackdir))) {
/* for pre-signal exits, add block to the global set */
DiagDirection exitdir = TrackdirToExitdir(ReverseTrackdir(trackdir));
_globset.Add(tile, exitdir); // do not check for full global set, first update all signals
}
SetSignalStateByTrackdir(tile, trackdir, newstate);
MarkTileDirtyByTile(tile);
}
}
}
/** Reset all sets after one set overflowed */
static inline void ResetSets()
{
_tbuset.Reset();
_tbdset.Reset();
_globset.Reset();
}
/**
* Updates blocks in _globset buffer
*
* @param owner company whose signals we are updating
* @return state of the first block from _globset
* @pre IsValidCompanyID(owner)
*/
static SigSegState UpdateSignalsInBuffer(Owner owner)
{
assert(IsValidCompanyID(owner));
bool first = true; // first block?
SigSegState state = SIGSEG_FREE; // value to return
TileIndex tile;
DiagDirection dir;
while (_globset.Get(&tile, &dir)) {
assert(_tbuset.IsEmpty());
assert(_tbdset.IsEmpty());
/* After updating signal, data stored are always MP_RAILWAY with signals.
* Other situations happen when data are from outside functions -
* modification of railbits (including both rail building and removal),
* train entering/leaving block, train leaving depot...
*/
switch (GetTileType(tile)) {
case MP_TUNNELBRIDGE:
/* 'optimization assert' - do not try to update signals when it is not needed */
assert(GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL);
assert(dir == INVALID_DIAGDIR || dir == ReverseDiagDir(GetTunnelBridgeDirection(tile)));
_tbdset.Add(tile, INVALID_DIAGDIR); // we can safely start from wormhole centre
_tbdset.Add(GetOtherTunnelBridgeEnd(tile), INVALID_DIAGDIR);
break;
case MP_RAILWAY:
if (IsRailDepot(tile)) {
/* 'optimization assert' do not try to update signals in other cases */
assert(dir == INVALID_DIAGDIR || dir == GetRailDepotDirection(tile));
_tbdset.Add(tile, INVALID_DIAGDIR); // start from depot inside
break;
}
/* FALLTHROUGH */
case MP_STATION:
case MP_ROAD:
if ((TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0)) & _enterdir_to_trackbits[dir]) != TRACK_BIT_NONE) {
/* only add to set when there is some 'interesting' track */
_tbdset.Add(tile, dir);
_tbdset.Add(tile + TileOffsByDiagDir(dir), ReverseDiagDir(dir));
break;
}
/* FALLTHROUGH */
default:
/* jump to next tile */
tile = tile + TileOffsByDiagDir(dir);
dir = ReverseDiagDir(dir);
if ((TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0)) & _enterdir_to_trackbits[dir]) != TRACK_BIT_NONE) {
_tbdset.Add(tile, dir);
break;
}
/* happens when removing a rail that wasn't connected at one or both sides */
continue; // continue the while() loop
}
assert(!_tbdset.Overflowed()); // it really shouldn't overflow by these one or two items
assert(!_tbdset.IsEmpty()); // it wouldn't hurt anyone, but shouldn't happen too
SigFlags flags = ExploreSegment(owner);
if (first) {
first = false;
/* SIGSEG_FREE is set by default */
if (flags & SF_PBS) {
state = SIGSEG_PBS;
} else if (flags & SF_TRAIN || (flags & SF_EXIT && !(flags & SF_GREEN)) || flags & SF_FULL) {
state = SIGSEG_FULL;
}
}
/* do not do anything when some buffer was full */
if (flags & SF_FULL) {
ResetSets(); // free all sets
break;
}
UpdateSignalsAroundSegment(flags);
}
return state;
}
static Owner _last_owner = INVALID_OWNER; ///< last owner whose track was put into _globset
/**
* Update signals in buffer
* Called from 'outside'
*/
void UpdateSignalsInBuffer()
{
if (!_globset.IsEmpty()) {
UpdateSignalsInBuffer(_last_owner);
_last_owner = INVALID_OWNER; // invalidate
}
}
/**
* Add track to signal update buffer
*
* @param tile tile where we start
* @param track track at which ends we will update signals
* @param owner owner whose signals we will update
*/
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
{
static const DiagDirection _search_dir_1[] = {
DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE
};
static const DiagDirection _search_dir_2[] = {
DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE
};
/* do not allow signal updates for two companies in one run */
assert(_globset.IsEmpty() || owner == _last_owner);
_last_owner = owner;
_globset.Add(tile, _search_dir_1[track]);
_globset.Add(tile, _search_dir_2[track]);
if (_globset.Items() >= SIG_GLOB_UPDATE) {
/* too many items, force update */
UpdateSignalsInBuffer(_last_owner);
_last_owner = INVALID_OWNER;
}
}
/**
* Add side of tile to signal update buffer
*
* @param tile tile where we start
* @param side side of tile
* @param owner owner whose signals we will update
*/
void AddSideToSignalBuffer(TileIndex tile, DiagDirection side, Owner owner)
{
/* do not allow signal updates for two companies in one run */
assert(_globset.IsEmpty() || owner == _last_owner);
_last_owner = owner;
_globset.Add(tile, side);
if (_globset.Items() >= SIG_GLOB_UPDATE) {
/* too many items, force update */
UpdateSignalsInBuffer(_last_owner);
_last_owner = INVALID_OWNER;
}
}
/**
* Update signals, starting at one side of a tile
* Will check tile next to this at opposite side too
*
* @see UpdateSignalsInBuffer()
* @param tile tile where we start
* @param side side of tile
* @param owner owner whose signals we will update
* @return the state of the signal segment
*/
SigSegState UpdateSignalsOnSegment(TileIndex tile, DiagDirection side, Owner owner)
{
assert(_globset.IsEmpty());
_globset.Add(tile, side);
return UpdateSignalsInBuffer(owner);
}
/**
* Update signals at segments that are at both ends of
* given (existent or non-existent) track
*
* @see UpdateSignalsInBuffer()
* @param tile tile where we start
* @param track track at which ends we will update signals
* @param owner owner whose signals we will update
*/
void SetSignalsOnBothDir(TileIndex tile, Track track, Owner owner)
{
assert(_globset.IsEmpty());
AddTrackToSignalBuffer(tile, track, owner);
UpdateSignalsInBuffer(owner);
}
| 20,608
|
C++
|
.cpp
| 555
| 33.756757
| 150
| 0.693037
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,072
|
rail_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/rail_cmd.cpp
|
/* $Id$ */
/** @file rail_cmd.cpp Handling of rail tiles. */
#include "stdafx.h"
#include "openttd.h"
#include "cmd_helper.h"
#include "landscape.h"
#include "town_map.h"
#include "viewport_func.h"
#include "command_func.h"
#include "engine_base.h"
#include "depot_base.h"
#include "waypoint.h"
#include "yapf/yapf.h"
#include "newgrf_engine.h"
#include "newgrf_station.h"
#include "newgrf_commons.h"
#include "train.h"
#include "variables.h"
#include "autoslope.h"
#include "water.h"
#include "tunnelbridge_map.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "tunnelbridge.h"
#include "station_map.h"
#include "functions.h"
#include "elrail_func.h"
#include "table/strings.h"
#include "table/railtypes.h"
#include "table/track_land.h"
RailtypeInfo _railtypes[RAILTYPE_END];
assert_compile(sizeof(_original_railtypes) <= sizeof(_railtypes));
/**
* Initialize rail type information.
*/
void ResetRailTypes()
{
memset(_railtypes, 0, sizeof(_railtypes));
memcpy(_railtypes, _original_railtypes, sizeof(_original_railtypes));
}
const byte _track_sloped_sprites[14] = {
14, 15, 22, 13,
0, 21, 17, 12,
23, 0, 18, 20,
19, 16
};
/* 4
* ---------
* |\ /|
* | \ 1/ |
* | \ / |
* | \ / |
* 16| \ |32
* | / \2 |
* | / \ |
* | / \ |
* |/ \|
* ---------
* 8
*/
/* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
* MAP3LO byte: abcd???? => Signal Exists?
* a and b are for diagonals, upper and left,
* one for each direction. (ie a == NE->SW, b ==
* SW->NE, or v.v., I don't know. b and c are
* similar for lower and right.
* MAP2 byte: ????abcd => Type of ground.
* MAP3LO byte: ????abcd => Type of rail.
* MAP5: 00abcdef => rail
* 01abcdef => rail w/ signals
* 10uuuuuu => unused
* 11uuuudd => rail depot
*/
Vehicle *EnsureNoTrainOnTrackProc(Vehicle *v, void *data)
{
TrackBits rail_bits = *(TrackBits *)data;
if (v->type != VEH_TRAIN) return NULL;
if ((v->u.rail.track != rail_bits) && !TracksOverlap(v->u.rail.track | rail_bits)) return NULL;
_error_message = VehicleInTheWayErrMsg(v);
return v;
}
/**
* Tests if a vehicle interacts with the specified track.
* All track bits interact except parallel TRACK_BIT_HORZ or TRACK_BIT_VERT.
*
* @param tile The tile.
* @param track The track.
*/
static bool EnsureNoTrainOnTrack(TileIndex tile, Track track)
{
TrackBits rail_bits = TrackToTrackBits(track);
return !HasVehicleOnPos(tile, &rail_bits, &EnsureNoTrainOnTrackProc);
}
static bool CheckTrackCombination(TileIndex tile, TrackBits to_build, uint flags)
{
TrackBits current; // The current track layout
TrackBits future; // The track layout we want to build
_error_message = STR_1001_IMPOSSIBLE_TRACK_COMBINATION;
if (!IsPlainRailTile(tile)) return false;
/* So, we have a tile with tracks on it (and possibly signals). Let's see
* what tracks first */
current = GetTrackBits(tile);
future = current | to_build;
/* Are we really building something new? */
if (current == future) {
/* Nothing new is being built */
_error_message = STR_1007_ALREADY_BUILT;
return false;
}
/* Let's see if we may build this */
if (flags & DC_NO_RAIL_OVERLAP || HasSignals(tile)) {
/* If we are not allowed to overlap (flag is on for ai companies or we have
* signals on the tile), check that */
return future == TRACK_BIT_HORZ || future == TRACK_BIT_VERT;
} else {
/* Normally, we may overlap and any combination is valid */
return true;
}
}
/** Valid TrackBits on a specific (non-steep)-slope without foundation */
static const TrackBits _valid_tracks_without_foundation[15] = {
TRACK_BIT_ALL,
TRACK_BIT_RIGHT,
TRACK_BIT_UPPER,
TRACK_BIT_X,
TRACK_BIT_LEFT,
TRACK_BIT_NONE,
TRACK_BIT_Y,
TRACK_BIT_LOWER,
TRACK_BIT_LOWER,
TRACK_BIT_Y,
TRACK_BIT_NONE,
TRACK_BIT_LEFT,
TRACK_BIT_X,
TRACK_BIT_UPPER,
TRACK_BIT_RIGHT,
};
/** Valid TrackBits on a specific (non-steep)-slope with leveled foundation */
static const TrackBits _valid_tracks_on_leveled_foundation[15] = {
TRACK_BIT_NONE,
TRACK_BIT_LEFT,
TRACK_BIT_LOWER,
TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
TRACK_BIT_RIGHT,
TRACK_BIT_ALL,
TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
TRACK_BIT_ALL,
TRACK_BIT_UPPER,
TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
TRACK_BIT_ALL,
TRACK_BIT_ALL,
TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
TRACK_BIT_ALL,
TRACK_BIT_ALL
};
/**
* Checks if a track combination is valid on a specific slope and returns the needed foundation.
*
* @param tileh Tile slope.
* @param bits Trackbits.
* @return Needed foundation or FOUNDATION_INVALID if track/slope combination is not allowed.
*/
Foundation GetRailFoundation(Slope tileh, TrackBits bits)
{
if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
if (IsSteepSlope(tileh)) {
/* Test for inclined foundations */
if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
/* Get higher track */
Corner highest_corner = GetHighestSlopeCorner(tileh);
TrackBits higher_track = CornerToTrackBits(highest_corner);
/* Only higher track? */
if (bits == higher_track) return HalftileFoundation(highest_corner);
/* Overlap with higher track? */
if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
/* either lower track or both higher and lower track */
return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
} else {
if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
Corner track_corner;
switch (bits) {
case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
case TRACK_BIT_HORZ:
if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
case TRACK_BIT_VERT:
if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
case TRACK_BIT_X:
if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_X;
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
case TRACK_BIT_Y:
if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_Y;
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
default:
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
}
/* Single diagonal track */
/* Track must be at least valid on leveled foundation */
if (!valid_on_leveled) return FOUNDATION_INVALID;
/* If slope has three raised corners, build leveled foundation */
if (IsSlopeWithThreeCornersRaised(tileh)) return FOUNDATION_LEVELED;
/* If neighboured corners of track_corner are lowered, build halftile foundation */
if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
/* else special anti-zig-zag foundation */
return SpecialRailFoundation(track_corner);
}
}
/**
* Tests if a track can be build on a tile.
*
* @param tileh Tile slope.
* @param rail_bits Tracks to build.
* @param existing Tracks already built.
* @param tile Tile (used for water test)
* @return Error message or cost for foundation building.
*/
static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
{
/* don't allow building on the lower side of a coast */
if (IsTileType(tile, MP_WATER) || (IsTileType(tile, MP_RAILWAY) && (GetRailGroundType(tile) == RAIL_GROUND_WATER))) {
if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return_cmd_error(STR_3807_CAN_T_BUILD_ON_WATER);
}
Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
/* check track/slope combination */
if ((f_new == FOUNDATION_INVALID) ||
((f_new != FOUNDATION_NONE) && (!_settings_game.construction.build_on_slopes))) {
return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
}
Foundation f_old = GetRailFoundation(tileh, existing);
return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price.terraform : (Money)0);
}
/* Validate functions for rail building */
static inline bool ValParamTrackOrientation(Track track) {return IsValidTrack(track);}
/** Build a single piece of rail
* @param tile tile to build on
* @param flags operation to perform
* @param p1 railtype of being built piece (normal, mono, maglev)
* @param p2 rail track to build
*/
CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Slope tileh;
RailType railtype = (RailType)p1;
Track track = (Track)p2;
TrackBits trackbit;
CommandCost cost(EXPENSES_CONSTRUCTION);
CommandCost ret;
if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
tileh = GetTileSlope(tile, NULL);
trackbit = TrackToTrackBits(track);
switch (GetTileType(tile)) {
case MP_RAILWAY:
if (!CheckTileOwnership(tile)) return CMD_ERROR;
if (!IsCompatibleRail(GetRailType(tile), railtype)) return_cmd_error(STR_1001_IMPOSSIBLE_TRACK_COMBINATION);
if (!CheckTrackCombination(tile, trackbit, flags) ||
!EnsureNoTrainOnTrack(tile, track)) {
return CMD_ERROR;
}
ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
if (CmdFailed(ret)) return ret;
cost.AddCost(ret);
/* If the rail types don't match, try to convert only if engines of
* the new rail type are not powered on the present rail type and engines of
* the present rail type are powered on the new rail type. */
if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
if (HasPowerOnRail(GetRailType(tile), railtype)) {
ret = DoCommand(tile, tile, railtype, flags, CMD_CONVERT_RAIL);
if (CmdFailed(ret)) return ret;
cost.AddCost(ret);
} else {
return CMD_ERROR;
}
}
if (flags & DC_EXEC) {
SetRailGroundType(tile, RAIL_GROUND_BARREN);
SetTrackBits(tile, GetTrackBits(tile) | trackbit);
}
break;
case MP_ROAD:
#define M(x) (1 << (x))
/* Level crossings may only be built on these slopes */
if (!HasBit(M(SLOPE_SEN) | M(SLOPE_ENW) | M(SLOPE_NWS) | M(SLOPE_NS) | M(SLOPE_WSE) | M(SLOPE_EW) | M(SLOPE_FLAT), tileh)) {
return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
}
#undef M
if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
if (IsNormalRoad(tile)) {
if (HasRoadWorks(tile)) return_cmd_error(STR_ROAD_WORKS_IN_PROGRESS);
if (GetDisallowedRoadDirections(tile) != DRD_NONE) return_cmd_error(STR_ERR_CROSSING_ON_ONEWAY_ROAD);
RoadTypes roadtypes = GetRoadTypes(tile);
RoadBits road = GetRoadBits(tile, ROADTYPE_ROAD);
RoadBits tram = GetRoadBits(tile, ROADTYPE_TRAM);
switch (roadtypes) {
default: break;
case ROADTYPES_TRAM:
/* Tram crossings must always have road. */
if (flags & DC_EXEC) SetRoadOwner(tile, ROADTYPE_ROAD, _current_company);
roadtypes |= ROADTYPES_ROAD;
break;
case ROADTYPES_ALL:
if (road != tram) return CMD_ERROR;
break;
}
road |= tram;
if ((track == TRACK_X && road == ROAD_Y) ||
(track == TRACK_Y && road == ROAD_X)) {
if (flags & DC_EXEC) {
MakeRoadCrossing(tile, GetRoadOwner(tile, ROADTYPE_ROAD), GetRoadOwner(tile, ROADTYPE_TRAM), _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtypes, GetTownIndex(tile));
UpdateLevelCrossing(tile, false);
}
break;
}
}
if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
return_cmd_error(STR_1007_ALREADY_BUILT);
}
/* FALLTHROUGH */
default:
/* Will there be flat water on the lower halftile? */
bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
if (CmdFailed(ret)) return ret;
cost.AddCost(ret);
ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return ret;
cost.AddCost(ret);
if (water_ground) {
cost.AddCost(-_price.clear_water);
cost.AddCost(_price.clear_roughland);
}
if (flags & DC_EXEC) {
MakeRailNormal(tile, _current_company, trackbit, railtype);
if (water_ground) SetRailGroundType(tile, RAIL_GROUND_WATER);
}
break;
}
if (flags & DC_EXEC) {
MarkTileDirtyByTile(tile);
AddTrackToSignalBuffer(tile, track, _current_company);
YapfNotifyTrackLayoutChange(tile, track);
}
return cost.AddCost(RailBuildCost(railtype));
}
/** Remove a single piece of track
* @param tile tile to remove track from
* @param flags operation to perform
* @param p1 unused
* @param p2 rail orientation
*/
CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Track track = (Track)p2;
TrackBits trackbit;
CommandCost cost(EXPENSES_CONSTRUCTION, _price.remove_rail );
bool crossing = false;
if (!ValParamTrackOrientation((Track)p2)) return CMD_ERROR;
trackbit = TrackToTrackBits(track);
/* Need to read tile owner now because it may change when the rail is removed
* Also, in case of floods, _current_company != owner
* There may be invalid tiletype even in exec run (when removing long track),
* so do not call GetTileOwner(tile) in any case here */
Owner owner = INVALID_OWNER;
Vehicle *v = NULL;
switch (GetTileType(tile)) {
case MP_ROAD: {
if (!IsLevelCrossing(tile) ||
GetCrossingRailBits(tile) != trackbit ||
(_current_company != OWNER_WATER && !CheckTileOwnership(tile)) ||
(!(flags & DC_BANKRUPT) && !EnsureNoVehicleOnGround(tile))) {
return CMD_ERROR;
}
if (flags & DC_EXEC) {
if (HasReservedTracks(tile, trackbit)) {
v = GetTrainForReservation(tile, track);
if (v != NULL) FreeTrainTrackReservation(v);
}
owner = GetTileOwner(tile);
MakeRoadNormal(tile, GetCrossingRoadBits(tile), GetRoadTypes(tile), GetTownIndex(tile), GetRoadOwner(tile, ROADTYPE_ROAD), GetRoadOwner(tile, ROADTYPE_TRAM));
}
break;
}
case MP_RAILWAY: {
TrackBits present;
if (!IsPlainRailTile(tile) ||
(_current_company != OWNER_WATER && !CheckTileOwnership(tile)) ||
!EnsureNoTrainOnTrack(tile, track)) {
return CMD_ERROR;
}
present = GetTrackBits(tile);
if ((present & trackbit) == 0) return CMD_ERROR;
if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
/* Charge extra to remove signals on the track, if they are there */
if (HasSignalOnTrack(tile, track))
cost.AddCost(DoCommand(tile, track, 0, flags, CMD_REMOVE_SIGNALS));
if (flags & DC_EXEC) {
if (HasReservedTracks(tile, trackbit)) {
v = GetTrainForReservation(tile, track);
if (v != NULL) FreeTrainTrackReservation(v);
}
owner = GetTileOwner(tile);
present ^= trackbit;
if (present == 0) {
Slope tileh = GetTileSlope(tile, NULL);
/* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
MakeShore(tile);
} else {
DoClearSquare(tile);
}
} else {
SetTrackBits(tile, present);
SetTrackReservation(tile, GetTrackReservation(tile) & present);
}
}
break;
}
default: return CMD_ERROR;
}
if (flags & DC_EXEC) {
/* if we got that far, 'owner' variable is set correctly */
assert(IsValidCompanyID(owner));
MarkTileDirtyByTile(tile);
if (crossing) {
/* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
* are removing one of these pieces, we'll need to update signals for
* both directions explicitly, as after the track is removed it won't
* 'connect' with the other piece. */
AddTrackToSignalBuffer(tile, TRACK_X, owner);
AddTrackToSignalBuffer(tile, TRACK_Y, owner);
YapfNotifyTrackLayoutChange(tile, TRACK_X);
YapfNotifyTrackLayoutChange(tile, TRACK_Y);
} else {
AddTrackToSignalBuffer(tile, track, owner);
YapfNotifyTrackLayoutChange(tile, track);
}
if (v != NULL) TryPathReserve(v, true);
}
return cost;
}
/**
* Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
* The function floods the lower halftile, if the tile has a halftile foundation.
*
* @param t The tile to flood.
* @return true if something was flooded.
*/
bool FloodHalftile(TileIndex t)
{
bool flooded = false;
if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
Slope tileh = GetTileSlope(t, NULL);
TrackBits rail_bits = GetTrackBits(t);
if (IsSlopeWithOneCornerRaised(tileh)) {
TrackBits lower_track = CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh)));
TrackBits to_remove = lower_track & rail_bits;
if (to_remove != 0) {
_current_company = OWNER_WATER;
if (CmdFailed(DoCommand(t, 0, FIND_FIRST_BIT(to_remove), DC_EXEC, CMD_REMOVE_SINGLE_RAIL))) return flooded; // not yet floodable
flooded = true;
rail_bits = rail_bits & ~to_remove;
if (rail_bits == 0) {
MakeShore(t);
MarkTileDirtyByTile(t);
return flooded;
}
}
if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
flooded = true;
SetRailGroundType(t, RAIL_GROUND_WATER);
MarkTileDirtyByTile(t);
}
} else {
/* Make shore on steep slopes and 'three-corners-raised'-slopes. */
if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
flooded = true;
SetRailGroundType(t, RAIL_GROUND_WATER);
MarkTileDirtyByTile(t);
}
}
}
return flooded;
}
static const TileIndexDiffC _trackdelta[] = {
{ -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
{ 0, 0 },
{ 0, 0 },
{ 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
{ 0, 0 },
{ 0, 0 }
};
static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
{
int x = TileX(start);
int y = TileY(start);
int ex = TileX(end);
int ey = TileY(end);
int dx, dy, trdx, trdy;
if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
/* calculate delta x,y from start to end tile */
dx = ex - x;
dy = ey - y;
/* calculate delta x,y for the first direction */
trdx = _trackdelta[*trackdir].x;
trdy = _trackdelta[*trackdir].y;
if (!IsDiagonalTrackdir(*trackdir)) {
trdx += _trackdelta[*trackdir ^ 1].x;
trdy += _trackdelta[*trackdir ^ 1].y;
}
/* validate the direction */
while (
(trdx <= 0 && dx > 0) ||
(trdx >= 0 && dx < 0) ||
(trdy <= 0 && dy > 0) ||
(trdy >= 0 && dy < 0)
) {
if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
SetBit(*trackdir, 3); // reverse the direction
trdx = -trdx;
trdy = -trdy;
} else { // other direction is invalid too, invalid drag
return CMD_ERROR;
}
}
/* (for diagonal tracks, this is already made sure of by above test), but:
* for non-diagonal tracks, check if the start and end tile are on 1 line */
if (!IsDiagonalTrackdir(*trackdir)) {
trdx = _trackdelta[*trackdir].x;
trdy = _trackdelta[*trackdir].y;
if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx))
return CMD_ERROR;
}
return CommandCost();
}
/** Build a stretch of railroad tracks.
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0-3) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
* - p2 = (bit 4-6) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 7) - 0 = build, 1 = remove tracks
*/
static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CommandCost ret, total_cost(EXPENSES_CONSTRUCTION);
Track track = (Track)GB(p2, 4, 3);
bool remove = HasBit(p2, 7);
RailType railtype = (RailType)GB(p2, 0, 4);
if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
if (p1 >= MapSize()) return CMD_ERROR;
TileIndex end_tile = p1;
Trackdir trackdir = TrackToTrackdir(track);
if (CmdFailed(ValidateAutoDrag(&trackdir, tile, end_tile))) return CMD_ERROR;
if (flags & DC_EXEC) SndPlayTileFx(SND_20_SPLAT_2, tile);
for (;;) {
ret = DoCommand(tile, railtype, TrackdirToTrack(trackdir), flags, remove ? CMD_REMOVE_SINGLE_RAIL : CMD_BUILD_SINGLE_RAIL);
if (CmdFailed(ret)) {
if (_error_message != STR_1007_ALREADY_BUILT && !remove) break;
_error_message = INVALID_STRING_ID;
} else {
total_cost.AddCost(ret);
}
if (tile == end_tile) break;
tile += ToTileIndexDiff(_trackdelta[trackdir]);
/* toggle railbit for the non-diagonal tracks */
if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
}
return (total_cost.GetCost() == 0) ? CommandCost(remove ? INVALID_STRING_ID : (_error_message == INVALID_STRING_ID ? STR_1007_ALREADY_BUILT : _error_message)) : total_cost;
}
/** Build rail on a stretch of track.
* Stub for the unified rail builder/remover
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0-3) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
* - p2 = (bit 4-6) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 7) - 0 = build, 1 = remove tracks
* @see CmdRailTrackHelper
*/
CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 7), text);
}
/** Build rail on a stretch of track.
* Stub for the unified rail builder/remover
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0-3) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
* - p2 = (bit 4-6) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 7) - 0 = build, 1 = remove tracks
* @see CmdRailTrackHelper
*/
CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 7), text);
}
/** Build a train depot
* @param tile position of the train depot
* @param flags operation to perform
* @param p1 rail type
* @param p2 bit 0..1 entrance direction (DiagDirection)
*
* @todo When checking for the tile slope,
* distingush between "Flat land required" and "land sloped in wrong direction"
*/
CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Slope tileh;
/* check railtype and valid direction for depot (0 through 3), 4 in total */
if (!ValParamRailtype((RailType)p1)) return CMD_ERROR;
tileh = GetTileSlope(tile, NULL);
DiagDirection dir = Extract<DiagDirection, 0>(p2);
/* Prohibit construction if
* The tile is non-flat AND
* 1) build-on-slopes is disabled
* 2) the tile is steep i.e. spans two height levels
* 3) the exit points in the wrong direction
*/
if (tileh != SLOPE_FLAT && (
!_settings_game.construction.build_on_slopes ||
IsSteepSlope(tileh) ||
!CanBuildDepotByTileh(dir, tileh)
)) {
return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
}
CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(cost)) return CMD_ERROR;
if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
if (!Depot::CanAllocateItem()) return CMD_ERROR;
if (flags & DC_EXEC) {
Depot *d = new Depot(tile);
MakeRailDepot(tile, _current_company, dir, (RailType)p1);
MarkTileDirtyByTile(tile);
d->town_index = ClosestTownFromTile(tile, UINT_MAX)->index;
AddSideToSignalBuffer(tile, INVALID_DIAGDIR, _current_company);
YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
}
return cost.AddCost(_price.build_train_depot);
}
/** Build signals, alternate between double/single, signal/semaphore,
* pre/exit/combo-signals, and what-else not. If the rail piece does not
* have any signals, bit 4 (cycle signal-type) is ignored
* @param tile tile where to build the signals
* @param flags operation to perform
* @param p1 various bitstuffed elements
* - p1 = (bit 0-2) - track-orientation, valid values: 0-5 (Track enum)
* - p1 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal or (for bit 7) toggle variant (CTRL-toggle)
* - p1 = (bit 4) - 0 = signals, 1 = semaphores
* - p1 = (bit 5-7) - type of the signal, for valid values see enum SignalType in rail_map.h
* - p1 = (bit 8) - convert the present signal type and variant
* - p1 = (bit 9-11)- start cycle from this signal type
* - p1 = (bit 12-14)-wrap around after this signal type
* - p1 = (bit 15-16)-cycle the signal direction this many times
* - p1 = (bit 17) - 1 = don't modify an existing signal but don't fail either, 0 = always set new signal type
* @param p2 used for CmdBuildManySignals() to copy direction of first signal
* TODO: p2 should be replaced by two bits for "along" and "against" the track.
*/
CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Track track = (Track)GB(p1, 0, 3);
bool ctrl_pressed = HasBit(p1, 3); // was the CTRL button pressed
SignalVariant sigvar = (ctrl_pressed ^ HasBit(p1, 4)) ? SIG_SEMAPHORE : SIG_ELECTRIC; // the signal variant of the new signal
SignalType sigtype = (SignalType)GB(p1, 5, 3); // the signal type of the new signal
bool convert_signal = HasBit(p1, 8); // convert button pressed
SignalType cycle_start = (SignalType)GB(p1, 9, 3);
SignalType cycle_stop = (SignalType)GB(p1, 12, 3);
CommandCost cost;
uint num_dir_cycle = GB(p1, 15, 2);
if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
if (!ValParamTrackOrientation(track) || !IsTileType(tile, MP_RAILWAY) || !EnsureNoTrainOnTrack(tile, track))
return CMD_ERROR;
/* Protect against invalid signal copying */
if (p2 != 0 && (p2 & SignalOnTrack(track)) == 0) return CMD_ERROR;
/* You can only build signals on plain rail tiles, and the selected track must exist */
if (!IsPlainRailTile(tile) || !HasTrack(tile, track)) return CMD_ERROR;
if (!CheckTileOwnership(tile)) return CMD_ERROR;
{
/* See if this is a valid track combination for signals, (ie, no overlap) */
TrackBits trackbits = GetTrackBits(tile);
if (KillFirstBit(trackbits) != TRACK_BIT_NONE && // More than one track present
trackbits != TRACK_BIT_HORZ &&
trackbits != TRACK_BIT_VERT) {
return_cmd_error(STR_1005_NO_SUITABLE_RAILROAD_TRACK);
}
}
/* In case we don't want to change an existing signal, return without error. */
if (HasBit(p1, 17) && HasSignalOnTrack(tile, track)) return CommandCost();
/* you can not convert a signal if no signal is on track */
if (convert_signal && !HasSignalOnTrack(tile, track)) return CMD_ERROR;
if (!HasSignalOnTrack(tile, track)) {
/* build new signals */
cost = CommandCost(EXPENSES_CONSTRUCTION, _price.build_signals);
} else {
if (p2 != 0 && sigvar != GetSignalVariant(tile, track)) {
/* convert signals <-> semaphores */
cost = CommandCost(EXPENSES_CONSTRUCTION, _price.build_signals + _price.remove_signals);
} else if (convert_signal) {
/* convert button pressed */
if (ctrl_pressed || GetSignalVariant(tile, track) != sigvar) {
/* convert electric <-> semaphore */
cost = CommandCost(EXPENSES_CONSTRUCTION, _price.build_signals + _price.remove_signals);
} else {
/* it is free to change signal type: normal-pre-exit-combo */
cost = CommandCost();
}
} else {
/* it is free to change orientation/pre-exit-combo signals */
cost = CommandCost();
}
}
if (flags & DC_EXEC) {
Vehicle *v = NULL;
/* The new/changed signal could block our path. As this can lead to
* stale reservations, we clear the path reservation here and try
* to redo it later on. */
if (HasReservedTracks(tile, TrackToTrackBits(track))) {
v = GetTrainForReservation(tile, track);
if (v != NULL) FreeTrainTrackReservation(v);
}
if (!HasSignals(tile)) {
/* there are no signals at all on this tile yet */
SetHasSignals(tile, true);
SetSignalStates(tile, 0xF); // all signals are on
SetPresentSignals(tile, 0); // no signals built by default
SetSignalType(tile, track, sigtype);
SetSignalVariant(tile, track, sigvar);
}
if (p2 == 0) {
if (!HasSignalOnTrack(tile, track)) {
/* build new signals */
SetPresentSignals(tile, GetPresentSignals(tile) | (IsPbsSignal(sigtype) ? KillFirstBit(SignalOnTrack(track)) : SignalOnTrack(track)));
SetSignalType(tile, track, sigtype);
SetSignalVariant(tile, track, sigvar);
while (num_dir_cycle-- > 0) CycleSignalSide(tile, track);
} else {
if (convert_signal) {
/* convert signal button pressed */
if (ctrl_pressed) {
/* toggle the pressent signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
SetSignalVariant(tile, track, (GetSignalVariant(tile, track) == SIG_ELECTRIC) ? SIG_SEMAPHORE : SIG_ELECTRIC);
/* Query current signal type so the check for PBS signals below works. */
sigtype = GetSignalType(tile, track);
} else {
/* convert the present signal to the chosen type and variant */
SetSignalType(tile, track, sigtype);
SetSignalVariant(tile, track, sigvar);
if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
}
}
} else if (ctrl_pressed) {
/* cycle between cycle_start and cycle_end */
sigtype = (SignalType)(GetSignalType(tile, track) + 1);
if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start;
SetSignalType(tile, track, sigtype);
if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
}
} else {
/* cycle the signal side: both -> left -> right -> both -> ... */
CycleSignalSide(tile, track);
/* Query current signal type so the check for PBS signals below works. */
sigtype = GetSignalType(tile, track);
}
}
} else {
/* If CmdBuildManySignals is called with copying signals, just copy the
* direction of the first signal given as parameter by CmdBuildManySignals */
SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | (p2 & SignalOnTrack(track)));
SetSignalVariant(tile, track, sigvar);
SetSignalType(tile, track, sigtype);
}
if (IsPbsSignal(sigtype)) {
/* PBS signals should show red unless they are on a reservation. */
uint mask = GetPresentSignals(tile) & SignalOnTrack(track);
SetSignalStates(tile, (GetSignalStates(tile) & ~mask) | ((HasBit(GetTrackReservation(tile), track) ? UINT_MAX : 0) & mask));
}
MarkTileDirtyByTile(tile);
AddTrackToSignalBuffer(tile, track, _current_company);
YapfNotifyTrackLayoutChange(tile, track);
if (v != NULL) TryPathReserve(v, true);
}
return cost;
}
static bool CheckSignalAutoFill(TileIndex &tile, Trackdir &trackdir, int &signal_ctr, bool remove)
{
tile = AddTileIndexDiffCWrap(tile, _trackdelta[trackdir]);
if (tile == INVALID_TILE) return false;
/* Check for track bits on the new tile */
TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits))) return false;
trackdirbits &= TrackdirReachesTrackdirs(trackdir);
/* No track bits, must stop */
if (trackdirbits == TRACKDIR_BIT_NONE) return false;
/* Get the first track dir */
trackdir = RemoveFirstTrackdir(&trackdirbits);
/* Any left? It's a junction so we stop */
if (trackdirbits != TRACKDIR_BIT_NONE) return false;
switch (GetTileType(tile)) {
case MP_RAILWAY:
if (IsRailDepot(tile)) return false;
if (!remove && HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) return false;
signal_ctr++;
if (IsDiagonalTrackdir(trackdir)) {
signal_ctr++;
/* Ensure signal_ctr even so X and Y pieces get signals */
ClrBit(signal_ctr, 0);
}
return true;
case MP_ROAD:
if (!IsLevelCrossing(tile)) return false;
signal_ctr += 2;
return true;
case MP_TUNNELBRIDGE: {
TileIndex orig_tile = tile; // backup old value
if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return false;
if (GetTunnelBridgeDirection(tile) != TrackdirToExitdir(trackdir)) return false;
/* Skip to end of tunnel or bridge
* note that tile is a parameter by reference, so it must be updated */
tile = GetOtherTunnelBridgeEnd(tile);
signal_ctr += (GetTunnelBridgeLength(orig_tile, tile) + 2) * 2;
return true;
}
default: return false;
}
}
/** Build many signals by dragging; AutoSignals
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
* - p2 = (bit 4) - 0 = signals, 1 = semaphores
* - p2 = (bit 5) - 0 = build, 1 = remove signals
* - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
* - p2 = (bit 7- 9) - default signal type
* - p2 = (bit 24-31) - user defined signals_density
*/
static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CommandCost ret, total_cost(EXPENSES_CONSTRUCTION);
int signal_ctr;
byte signals;
bool error = true;
TileIndex end_tile;
TileIndex start_tile = tile;
Track track = (Track)GB(p2, 0, 3);
bool mode = HasBit(p2, 3);
bool semaphores = HasBit(p2, 4);
bool remove = HasBit(p2, 5);
bool autofill = HasBit(p2, 6);
Trackdir trackdir = TrackToTrackdir(track);
byte signal_density = GB(p2, 24, 8);
if (p1 >= MapSize()) return CMD_ERROR;
end_tile = p1;
if (signal_density == 0 || signal_density > 20) return CMD_ERROR;
if (!IsTileType(tile, MP_RAILWAY)) return CMD_ERROR;
/* for vertical/horizontal tracks, double the given signals density
* since the original amount will be too dense (shorter tracks) */
signal_density *= 2;
if (CmdFailed(ValidateAutoDrag(&trackdir, tile, end_tile))) return CMD_ERROR;
track = TrackdirToTrack(trackdir); // trackdir might have changed, keep track in sync
Trackdir start_trackdir = trackdir;
/* Must start on a valid track to be able to avoid loops */
if (!HasTrack(tile, track)) return CMD_ERROR;
SignalType sigtype = (SignalType)GB(p2, 7, 3);
if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
/* copy the signal-style of the first rail-piece if existing */
if (HasSignalOnTrack(tile, track)) {
signals = GetPresentSignals(tile) & SignalOnTrack(track);
assert(signals != 0);
/* copy signal/semaphores style (independent of CTRL) */
semaphores = GetSignalVariant(tile, track) != SIG_ELECTRIC;
sigtype = GetSignalType(tile, track);
/* Don't but copy pre-signal type */
if (sigtype < SIGTYPE_PBS) sigtype = SIGTYPE_NORMAL;
} else { // no signals exist, drag a two-way signal stretch
signals = IsPbsSignal(sigtype) ? SignalAlongTrackdir(trackdir) : SignalOnTrack(track);
}
byte signal_dir = 0;
if (signals & SignalAlongTrackdir(trackdir)) SetBit(signal_dir, 0);
if (signals & SignalAgainstTrackdir(trackdir)) SetBit(signal_dir, 1);
/* signal_ctr - amount of tiles already processed
* signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
**********
* trackdir - trackdir to build with autorail
* semaphores - semaphores or signals
* signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
* and convert all others to semaphore/signal
* remove - 1 remove signals, 0 build signals */
signal_ctr = 0;
for (;;) {
/* only build/remove signals with the specified density */
if ((remove && autofill) || signal_ctr % signal_density == 0) {
uint32 p1 = GB(TrackdirToTrack(trackdir), 0, 3);
SB(p1, 3, 1, mode);
SB(p1, 4, 1, semaphores);
SB(p1, 5, 3, sigtype);
if (!remove && signal_ctr == 0) SetBit(p1, 17);
/* Pick the correct orientation for the track direction */
signals = 0;
if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(trackdir);
if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(trackdir);
ret = DoCommand(tile, p1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
/* Be user-friendly and try placing signals as much as possible */
if (CmdSucceeded(ret)) {
error = false;
total_cost.AddCost(ret);
}
}
if (autofill) {
if (!CheckSignalAutoFill(tile, trackdir, signal_ctr, remove)) break;
/* Prevent possible loops */
if (tile == start_tile && trackdir == start_trackdir) break;
} else {
if (tile == end_tile) break;
tile += ToTileIndexDiff(_trackdelta[trackdir]);
signal_ctr++;
/* toggle railbit for the non-diagonal tracks (|, -- tracks) */
if (IsDiagonalTrackdir(trackdir)) {
signal_ctr++;
} else {
ToggleBit(trackdir, 0);
}
}
}
return error ? CMD_ERROR : total_cost;
}
/** Build signals on a stretch of track.
* Stub for the unified signal builder/remover
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
* - p2 = (bit 4) - 0 = signals, 1 = semaphores
* - p2 = (bit 5) - 0 = build, 1 = remove signals
* - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
* - p2 = (bit 7- 9) - default signal type
* - p2 = (bit 24-31) - user defined signals_density
* @see CmdSignalTrackHelper
*/
CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
return CmdSignalTrackHelper(tile, flags, p1, p2,text);
}
/** Remove signals
* @param tile coordinates where signal is being deleted from
* @param flags operation to perform
* @param p1 various bitstuffed elements, only track information is used
* - (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
* - (bit 3) - override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
* - (bit 4) - 0 = signals, 1 = semaphores
* @param p2 unused
*/
CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Track track = (Track)GB(p1, 0, 3);
if (!ValParamTrackOrientation(track) ||
!IsTileType(tile, MP_RAILWAY) ||
!HasTrack(tile, track) ||
!EnsureNoTrainOnTrack(tile, track) ||
!HasSignalOnTrack(tile, track)) {
return CMD_ERROR;
}
/* Only water can remove signals from anyone */
if (_current_company != OWNER_WATER && !CheckTileOwnership(tile)) return CMD_ERROR;
/* Do it? */
if (flags & DC_EXEC) {
Vehicle *v = NULL;
if (HasReservedTracks(tile, TrackToTrackBits(track))) {
v = GetTrainForReservation(tile, track);
}
SetPresentSignals(tile, GetPresentSignals(tile) & ~SignalOnTrack(track));
/* removed last signal from tile? */
if (GetPresentSignals(tile) == 0) {
SetSignalStates(tile, 0);
SetHasSignals(tile, false);
SetSignalVariant(tile, INVALID_TRACK, SIG_ELECTRIC); // remove any possible semaphores
}
AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
YapfNotifyTrackLayoutChange(tile, track);
if (v != NULL) TryPathReserve(v, false);
MarkTileDirtyByTile(tile);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_signals);
}
/** Remove signals on a stretch of track.
* Stub for the unified signal builder/remover
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
* - p2 = (bit 4) - 0 = signals, 1 = semaphores
* - p2 = (bit 5) - 0 = build, 1 = remove signals
* - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
* - p2 = (bit 7- 9) - default signal type
* - p2 = (bit 24-31) - user defined signals_density
* @see CmdSignalTrackHelper
*/
CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit
}
/** Update power of train under which is the railtype being converted */
Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
{
/* Similiar checks as in TrainPowerChanged() */
if (v->type == VEH_TRAIN && !IsArticulatedPart(v)) {
const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
if (GetVehicleProperty(v, 0x0B, rvi->power) != 0) TrainPowerChanged(v->First());
}
return NULL;
}
/** Convert one rail type to the other. You can convert normal rail to
* monorail/maglev easily or vice-versa.
* @param tile end tile of rail conversion drag
* @param flags operation to perform
* @param p1 start tile of drag
* @param p2 new railtype to convert to
*/
CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CommandCost cost(EXPENSES_CONSTRUCTION);
RailType totype = (RailType)p2;
if (!ValParamRailtype(totype)) return CMD_ERROR;
if (p1 >= MapSize()) return CMD_ERROR;
uint ex = TileX(tile);
uint ey = TileY(tile);
uint sx = TileX(p1);
uint sy = TileY(p1);
/* make sure sx,sy are smaller than ex,ey */
if (ex < sx) Swap(ex, sx);
if (ey < sy) Swap(ey, sy);
_error_message = STR_1005_NO_SUITABLE_RAILROAD_TRACK; // by default, there is no track to convert
for (uint x = sx; x <= ex; ++x) {
for (uint y = sy; y <= ey; ++y) {
TileIndex tile = TileXY(x, y);
TileType tt = GetTileType(tile);
/* Check if there is any track on tile */
switch (tt) {
case MP_RAILWAY:
break;
case MP_STATION:
if (!IsRailwayStation(tile)) continue;
break;
case MP_ROAD:
if (!IsLevelCrossing(tile)) continue;
break;
case MP_TUNNELBRIDGE:
if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
break;
default: continue;
}
/* Original railtype we are converting from */
RailType type = GetRailType(tile);
/* Converting to the same type or converting 'hidden' elrail -> rail */
if (type == totype || (_settings_game.vehicle.disable_elrails && totype == RAILTYPE_RAIL && type == RAILTYPE_ELECTRIC)) continue;
/* Trying to convert other's rail */
if (!CheckTileOwnership(tile)) continue;
SmallVector<Vehicle*, 2> vehicles_affected;
/* Vehicle on the tile when not converting Rail <-> ElRail
* Tunnels and bridges have special check later */
if (tt != MP_TUNNELBRIDGE) {
if (!IsCompatibleRail(type, totype) && !EnsureNoVehicleOnGround(tile)) continue;
if (flags & DC_EXEC) { // we can safely convert, too
TrackBits reserved = GetReservedTrackbits(tile);
Track track;
while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
Vehicle *v = GetTrainForReservation(tile, track);
if (v != NULL && !HasPowerOnRail(v->u.rail.railtype, totype)) {
/* No power on new rail type, reroute. */
FreeTrainTrackReservation(v);
*vehicles_affected.Append() = v;
}
}
SetRailType(tile, totype);
MarkTileDirtyByTile(tile);
/* update power of train engines on this tile */
FindVehicleOnPos(tile, NULL, &UpdateTrainPowerProc);
}
}
switch (tt) {
case MP_RAILWAY:
switch (GetRailTileType(tile)) {
case RAIL_TILE_WAYPOINT:
if (flags & DC_EXEC) {
/* notify YAPF about the track layout change */
YapfNotifyTrackLayoutChange(tile, GetRailWaypointTrack(tile));
}
cost.AddCost(RailConvertCost(type, totype));
break;
case RAIL_TILE_DEPOT:
if (flags & DC_EXEC) {
/* notify YAPF about the track layout change */
YapfNotifyTrackLayoutChange(tile, GetRailDepotTrack(tile));
/* Update build vehicle window related to this depot */
InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
InvalidateWindowData(WC_BUILD_VEHICLE, tile);
}
cost.AddCost(RailConvertCost(type, totype));
break;
default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
if (flags & DC_EXEC) {
/* notify YAPF about the track layout change */
TrackBits tracks = GetTrackBits(tile);
while (tracks != TRACK_BIT_NONE) {
YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(&tracks));
}
}
cost.AddCost(RailConvertCost(type, totype) * CountBits(GetTrackBits(tile)));
break;
}
break;
case MP_TUNNELBRIDGE: {
TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
/* If both ends of tunnel/bridge are in the range, do not try to convert twice -
* it would cause assert because of different test and exec runs */
if (endtile < tile && TileX(endtile) >= sx && TileX(endtile) <= ex &&
TileY(endtile) >= sy && TileY(endtile) <= ey) continue;
/* When not coverting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
if (!IsCompatibleRail(GetRailType(tile), totype) &&
HasVehicleOnTunnelBridge(tile, endtile)) continue;
if (flags & DC_EXEC) {
Track track = DiagDirToDiagTrack(GetTunnelBridgeDirection(tile));
if (GetTunnelBridgeReservation(tile)) {
Vehicle *v = GetTrainForReservation(tile, track);
if (v != NULL && !HasPowerOnRail(v->u.rail.railtype, totype)) {
/* No power on new rail type, reroute. */
FreeTrainTrackReservation(v);
*vehicles_affected.Append() = v;
}
}
SetRailType(tile, totype);
SetRailType(endtile, totype);
FindVehicleOnPos(tile, NULL, &UpdateTrainPowerProc);
FindVehicleOnPos(endtile, NULL, &UpdateTrainPowerProc);
YapfNotifyTrackLayoutChange(tile, track);
YapfNotifyTrackLayoutChange(endtile, track);
MarkTileDirtyByTile(tile);
MarkTileDirtyByTile(endtile);
if (IsBridge(tile)) {
TileIndexDiff delta = TileOffsByDiagDir(GetTunnelBridgeDirection(tile));
TileIndex t = tile + delta;
for (; t != endtile; t += delta) MarkTileDirtyByTile(t); // TODO encapsulate this into a function
}
}
cost.AddCost((GetTunnelBridgeLength(tile, endtile) + 2) * RailConvertCost(type, totype));
} break;
default: // MP_STATION, MP_ROAD
if (flags & DC_EXEC) {
Track track = ((tt == MP_STATION) ? GetRailStationTrack(tile) : GetCrossingRailTrack(tile));
YapfNotifyTrackLayoutChange(tile, track);
}
cost.AddCost(RailConvertCost(type, totype));
break;
}
for (uint i = 0; i < vehicles_affected.Length(); ++i) {
TryPathReserve(vehicles_affected[i], true);
}
}
}
return (cost.GetCost() == 0) ? CMD_ERROR : cost;
}
static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
{
if (!CheckTileOwnership(tile) && _current_company != OWNER_WATER)
return CMD_ERROR;
if (!EnsureNoVehicleOnGround(tile))
return CMD_ERROR;
if (flags & DC_EXEC) {
/* read variables before the depot is removed */
DiagDirection dir = GetRailDepotDirection(tile);
Owner owner = GetTileOwner(tile);
Vehicle *v = NULL;
if (GetDepotWaypointReservation(tile)) {
v = GetTrainForReservation(tile, DiagDirToDiagTrack(dir));
if (v != NULL) FreeTrainTrackReservation(v);
}
DoClearSquare(tile);
delete GetDepotByTile(tile);
AddSideToSignalBuffer(tile, dir, owner);
YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
if (v != NULL) TryPathReserve(v, true);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_train_depot);
}
static CommandCost ClearTile_Track(TileIndex tile, DoCommandFlag flags)
{
CommandCost cost(EXPENSES_CONSTRUCTION);
CommandCost ret;
if (flags & DC_AUTO) {
if (!IsTileOwner(tile, _current_company))
return_cmd_error(STR_1024_AREA_IS_OWNED_BY_ANOTHER);
if (IsPlainRailTile(tile)) {
return_cmd_error(STR_1008_MUST_REMOVE_RAILROAD_TRACK);
} else {
return_cmd_error(STR_2004_BUILDING_MUST_BE_DEMOLISHED);
}
}
switch (GetRailTileType(tile)) {
case RAIL_TILE_SIGNALS:
case RAIL_TILE_NORMAL: {
Slope tileh = GetTileSlope(tile, NULL);
/* Is there flat water on the lower halftile, that gets cleared expensively? */
bool water_ground = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh));
TrackBits tracks = GetTrackBits(tile);
while (tracks != TRACK_BIT_NONE) {
Track track = RemoveFirstTrack(&tracks);
ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
if (CmdFailed(ret)) return CMD_ERROR;
cost.AddCost(ret);
}
/* when bankrupting, don't make water dirty, there could be a ship on lower halftile */
if (water_ground && !(flags & DC_BANKRUPT)) {
if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
/* The track was removed, and left a coast tile. Now also clear the water. */
if (flags & DC_EXEC) DoClearSquare(tile);
cost.AddCost(_price.clear_water);
}
return cost;
}
case RAIL_TILE_DEPOT:
return RemoveTrainDepot(tile, flags);
case RAIL_TILE_WAYPOINT:
return RemoveTrainWaypoint(tile, flags, false);
default:
return CMD_ERROR;
}
}
/**
* Get surface height in point (x,y)
* On tiles with halftile foundations move (x,y) to a safe point wrt. track
*/
static uint GetSaveSlopeZ(uint x, uint y, Track track)
{
switch (track) {
case TRACK_UPPER: x &= ~0xF; y &= ~0xF; break;
case TRACK_LOWER: x |= 0xF; y |= 0xF; break;
case TRACK_LEFT: x |= 0xF; y &= ~0xF; break;
case TRACK_RIGHT: x &= ~0xF; y |= 0xF; break;
default: break;
}
return GetSlopeZ(x, y);
}
static void DrawSingleSignal(TileIndex tile, Track track, byte condition, uint image, uint pos)
{
bool side = (_settings_game.vehicle.road_side != 0) && _settings_game.construction.signal_side;
static const Point SignalPositions[2][12] = {
{ // Signals on the left side
/* LEFT LEFT RIGHT RIGHT UPPER UPPER */
{ 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
/* LOWER LOWER X X Y Y */
{11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
}, { // Signals on the right side
/* LEFT LEFT RIGHT RIGHT UPPER UPPER */
{14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
/* LOWER LOWER X X Y Y */
{14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
}
};
uint x = TileX(tile) * TILE_SIZE + SignalPositions[side][pos].x;
uint y = TileY(tile) * TILE_SIZE + SignalPositions[side][pos].y;
SpriteID sprite;
SignalType type = GetSignalType(tile, track);
SignalVariant variant = GetSignalVariant(tile, track);
if (type == SIGTYPE_NORMAL && variant == SIG_ELECTRIC) {
/* Normal electric signals are picked from original sprites. */
sprite = SPR_ORIGINAL_SIGNALS_BASE + image + condition;
} else {
/* All other signals are picked from add on sprites. */
sprite = SPR_SIGNALS_BASE + (type - 1) * 16 + variant * 64 + image + condition + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
}
AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSaveSlopeZ(x, y, track));
}
static uint32 _drawtile_track_palette;
static void DrawTrackFence_NW(const TileInfo *ti, SpriteID base_image)
{
RailFenceOffset rfo = RFO_FLAT_X;
if (ti->tileh != SLOPE_FLAT) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW : RFO_SLOPE_NE;
AddSortableSpriteToDraw(base_image + rfo, _drawtile_track_palette,
ti->x, ti->y + 1, 16, 1, 4, ti->z);
}
static void DrawTrackFence_SE(const TileInfo *ti, SpriteID base_image)
{
RailFenceOffset rfo = RFO_FLAT_X;
if (ti->tileh != SLOPE_FLAT) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW : RFO_SLOPE_NE;
AddSortableSpriteToDraw(base_image + rfo, _drawtile_track_palette,
ti->x, ti->y + TILE_SIZE - 1, 16, 1, 4, ti->z);
}
static void DrawTrackFence_NW_SE(const TileInfo *ti, SpriteID base_image)
{
DrawTrackFence_NW(ti, base_image);
DrawTrackFence_SE(ti, base_image);
}
static void DrawTrackFence_NE(const TileInfo *ti, SpriteID base_image)
{
RailFenceOffset rfo = RFO_FLAT_Y;
if (ti->tileh != SLOPE_FLAT) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE : RFO_SLOPE_NW;
AddSortableSpriteToDraw(base_image + rfo, _drawtile_track_palette,
ti->x + 1, ti->y, 1, 16, 4, ti->z);
}
static void DrawTrackFence_SW(const TileInfo *ti, SpriteID base_image)
{
RailFenceOffset rfo = RFO_FLAT_Y;
if (ti->tileh != SLOPE_FLAT) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE : RFO_SLOPE_NW;
AddSortableSpriteToDraw(base_image + rfo, _drawtile_track_palette,
ti->x + TILE_SIZE - 1, ti->y, 1, 16, 4, ti->z);
}
static void DrawTrackFence_NE_SW(const TileInfo *ti, SpriteID base_image)
{
DrawTrackFence_NE(ti, base_image);
DrawTrackFence_SW(ti, base_image);
}
/**
* Draw fence at eastern side of track.
*/
static void DrawTrackFence_NS_1(const TileInfo *ti, SpriteID base_image)
{
uint z = ti->z + GetSlopeZInCorner(RemoveHalftileSlope(ti->tileh), CORNER_W);
AddSortableSpriteToDraw(base_image + RFO_FLAT_VERT, _drawtile_track_palette,
ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 4, z);
}
/**
* Draw fence at western side of track.
*/
static void DrawTrackFence_NS_2(const TileInfo *ti, SpriteID base_image)
{
uint z = ti->z + GetSlopeZInCorner(RemoveHalftileSlope(ti->tileh), CORNER_E);
AddSortableSpriteToDraw(base_image + RFO_FLAT_VERT, _drawtile_track_palette,
ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 4, z);
}
/**
* Draw fence at southern side of track.
*/
static void DrawTrackFence_WE_1(const TileInfo *ti, SpriteID base_image)
{
uint z = ti->z + GetSlopeZInCorner(RemoveHalftileSlope(ti->tileh), CORNER_N);
AddSortableSpriteToDraw(base_image + RFO_FLAT_HORZ, _drawtile_track_palette,
ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 4, z);
}
/**
* Draw fence at northern side of track.
*/
static void DrawTrackFence_WE_2(const TileInfo *ti, SpriteID base_image)
{
uint z = ti->z + GetSlopeZInCorner(RemoveHalftileSlope(ti->tileh), CORNER_S);
AddSortableSpriteToDraw(base_image + RFO_FLAT_HORZ, _drawtile_track_palette,
ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 4, z);
}
static void DrawTrackDetails(const TileInfo *ti)
{
/* Base sprite for track fences. */
SpriteID base_image = SPR_TRACK_FENCE_FLAT_X;
switch (GetRailGroundType(ti->tile)) {
case RAIL_GROUND_FENCE_NW: DrawTrackFence_NW(ti, base_image); break;
case RAIL_GROUND_FENCE_SE: DrawTrackFence_SE(ti, base_image); break;
case RAIL_GROUND_FENCE_SENW: DrawTrackFence_NW_SE(ti, base_image); break;
case RAIL_GROUND_FENCE_NE: DrawTrackFence_NE(ti, base_image); break;
case RAIL_GROUND_FENCE_SW: DrawTrackFence_SW(ti, base_image); break;
case RAIL_GROUND_FENCE_NESW: DrawTrackFence_NE_SW(ti, base_image); break;
case RAIL_GROUND_FENCE_VERT1: DrawTrackFence_NS_1(ti, base_image); break;
case RAIL_GROUND_FENCE_VERT2: DrawTrackFence_NS_2(ti, base_image); break;
case RAIL_GROUND_FENCE_HORIZ1: DrawTrackFence_WE_1(ti, base_image); break;
case RAIL_GROUND_FENCE_HORIZ2: DrawTrackFence_WE_2(ti, base_image); break;
case RAIL_GROUND_WATER: {
Corner track_corner;
if (IsHalftileSlope(ti->tileh)) {
/* Steep slope or one-corner-raised slope with halftile foundation */
track_corner = GetHalftileSlopeCorner(ti->tileh);
} else {
/* Three-corner-raised slope */
track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
}
switch (track_corner) {
case CORNER_W: DrawTrackFence_NS_1(ti, base_image); break;
case CORNER_S: DrawTrackFence_WE_2(ti, base_image); break;
case CORNER_E: DrawTrackFence_NS_2(ti, base_image); break;
case CORNER_N: DrawTrackFence_WE_1(ti, base_image); break;
default: NOT_REACHED();
}
break;
}
default: break;
}
}
/**
* Draw ground sprite and track bits
* @param ti TileInfo
* @param track TrackBits to draw
*/
static void DrawTrackBits(TileInfo *ti, TrackBits track)
{
/* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
static const int INF = 1000; // big number compared to tilesprite size
static const SubSprite _halftile_sub_sprite[4] = {
{ -INF , -INF , 32 - 33, INF }, // CORNER_W, clip 33 pixels from right
{ -INF , 0 + 7, INF , INF }, // CORNER_S, clip 7 pixels from top
{ -31 + 33, -INF , INF , INF }, // CORNER_E, clip 33 pixels from left
{ -INF , -INF , INF , 30 - 23 } // CORNER_N, clip 23 pixels from bottom
};
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
RailGroundType rgt = GetRailGroundType(ti->tile);
Foundation f = GetRailFoundation(ti->tileh, track);
Corner halftile_corner = CORNER_INVALID;
if (IsNonContinuousFoundation(f)) {
/* Save halftile corner */
halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
/* Draw lower part first */
track &= ~CornerToTrackBits(halftile_corner);
f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
}
DrawFoundation(ti, f);
/* DrawFoundation modifies ti */
SpriteID image;
SpriteID pal = PAL_NONE;
const SubSprite *sub = NULL;
bool junction = false;
/* Select the sprite to use. */
if (track == 0) {
/* Clear ground (only track on halftile foundation) */
if (rgt == RAIL_GROUND_WATER) {
if (IsSteepSlope(ti->tileh)) {
DrawShoreTile(ti->tileh);
image = 0;
} else {
image = SPR_FLAT_WATER_TILE;
}
} else {
switch (rgt) {
case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOWY_TILE; break;
default: image = SPR_FLAT_GRASS_TILE; break;
}
image += _tileh_to_sprite[ti->tileh];
}
} else {
if (ti->tileh != SLOPE_FLAT) {
/* track on non-flat ground */
image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
} else {
/* track on flat ground */
(image = rti->base_sprites.track_y, track == TRACK_BIT_Y) ||
(image++, track == TRACK_BIT_X) ||
(image++, track == TRACK_BIT_UPPER) ||
(image++, track == TRACK_BIT_LOWER) ||
(image++, track == TRACK_BIT_RIGHT) ||
(image++, track == TRACK_BIT_LEFT) ||
(image++, track == TRACK_BIT_CROSS) ||
(image = rti->base_sprites.track_ns, track == TRACK_BIT_HORZ) ||
(image++, track == TRACK_BIT_VERT) ||
(junction = true, false) ||
(image = rti->base_sprites.ground, (track & TRACK_BIT_3WAY_NE) == 0) ||
(image++, (track & TRACK_BIT_3WAY_SW) == 0) ||
(image++, (track & TRACK_BIT_3WAY_NW) == 0) ||
(image++, (track & TRACK_BIT_3WAY_SE) == 0) ||
(image++, true);
}
switch (rgt) {
case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
case RAIL_GROUND_ICE_DESERT: image += rti->snow_offset; break;
case RAIL_GROUND_WATER: {
/* three-corner-raised slope */
DrawShoreTile(ti->tileh);
Corner track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
sub = &(_halftile_sub_sprite[track_corner]);
break;
}
default: break;
}
}
if (image != 0) DrawGroundSprite(image, pal, sub);
/* Draw track pieces individually for junction tiles */
if (junction) {
if (track & TRACK_BIT_X) DrawGroundSprite(rti->base_sprites.single_y, PAL_NONE);
if (track & TRACK_BIT_Y) DrawGroundSprite(rti->base_sprites.single_x, PAL_NONE);
if (track & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PAL_NONE);
if (track & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PAL_NONE);
if (track & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PAL_NONE);
if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
}
/* PBS debugging, draw reserved tracks darker */
if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
TrackBits pbs = GetTrackReservation(ti->tile);
if (pbs & TRACK_BIT_X) {
if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
} else {
DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
}
}
if (pbs & TRACK_BIT_Y) {
if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
} else {
DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
}
}
if (pbs & TRACK_BIT_UPPER) AddSortableSpriteToDraw(rti->base_sprites.single_n, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + (ti->tileh & SLOPE_N ? 8 : 0));
if (pbs & TRACK_BIT_LOWER) AddSortableSpriteToDraw(rti->base_sprites.single_s, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + (ti->tileh & SLOPE_S ? 8 : 0));
if (pbs & TRACK_BIT_LEFT) AddSortableSpriteToDraw(rti->base_sprites.single_w, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + (ti->tileh & SLOPE_W ? 8 : 0));
if (pbs & TRACK_BIT_RIGHT) AddSortableSpriteToDraw(rti->base_sprites.single_e, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + (ti->tileh & SLOPE_E ? 8 : 0));
}
if (IsValidCorner(halftile_corner)) {
DrawFoundation(ti, HalftileFoundation(halftile_corner));
/* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
image = _track_sloped_sprites[fake_slope - 1] + rti->base_sprites.track_y;
pal = PAL_NONE;
switch (rgt) {
case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
case RAIL_GROUND_ICE_DESERT:
case RAIL_GROUND_HALF_SNOW: image += rti->snow_offset; break; // higher part has snow in this case too
default: break;
}
DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && IsSteepSlope(ti->tileh) && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
AddSortableSpriteToDraw(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 16);
}
}
}
/** Enums holding the offsets from base signal sprite,
* according to the side it is representing.
* The addtion of 2 per enum is necessary in order to "jump" over the
* green state sprite, all signal sprites being in pair,
* starting with the off-red state */
enum {
SIGNAL_TO_SOUTHWEST = 0,
SIGNAL_TO_NORTHEAST = 2,
SIGNAL_TO_SOUTHEAST = 4,
SIGNAL_TO_NORTHWEST = 6,
SIGNAL_TO_EAST = 8,
SIGNAL_TO_WEST = 10,
SIGNAL_TO_SOUTH = 12,
SIGNAL_TO_NORTH = 14,
};
static void DrawSignals(TileIndex tile, TrackBits rails)
{
#define MAYBE_DRAW_SIGNAL(x,y,z,t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, t, GetSingleSignalState(tile, x), y, z)
if (!(rails & TRACK_BIT_Y)) {
if (!(rails & TRACK_BIT_X)) {
if (rails & TRACK_BIT_LEFT) {
MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH, 0, TRACK_LEFT);
MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH, 1, TRACK_LEFT);
}
if (rails & TRACK_BIT_RIGHT) {
MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH, 2, TRACK_RIGHT);
MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH, 3, TRACK_RIGHT);
}
if (rails & TRACK_BIT_UPPER) {
MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST, 4, TRACK_UPPER);
MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST, 5, TRACK_UPPER);
}
if (rails & TRACK_BIT_LOWER) {
MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST, 6, TRACK_LOWER);
MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST, 7, TRACK_LOWER);
}
} else {
MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST, 8, TRACK_X);
MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST, 9, TRACK_X);
}
} else {
MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST, 10, TRACK_Y);
MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST, 11, TRACK_Y);
}
}
static void DrawTile_Track(TileInfo *ti)
{
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
SpriteID image;
_drawtile_track_palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
if (IsPlainRailTile(ti->tile)) {
TrackBits rails = GetTrackBits(ti->tile);
DrawTrackBits(ti, rails);
if (HasBit(_display_opt, DO_FULL_DETAIL)) DrawTrackDetails(ti);
if (HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
if (HasSignals(ti->tile)) DrawSignals(ti->tile, rails);
} else {
/* draw depot/waypoint */
const DrawTileSprites *dts;
const DrawTileSeqStruct *dtss;
uint32 relocation;
SpriteID pal = PAL_NONE;
if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
if (IsRailDepot(ti->tile)) {
if (IsInvisibilitySet(TO_BUILDINGS)) {
/* Draw rail instead of depot */
dts = &_depot_invisible_gfx_table[GetRailDepotDirection(ti->tile)];
} else {
dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
}
relocation = rti->total_offset;
image = dts->ground.sprite;
if (image != SPR_FLAT_GRASS_TILE) image += rti->total_offset;
/* adjust ground tile for desert
* don't adjust for snow, because snow in depots looks weird */
if (IsSnowRailGround(ti->tile) && _settings_game.game_creation.landscape == LT_TROPIC) {
if (image != SPR_FLAT_GRASS_TILE) {
image += rti->snow_offset; // tile with tracks
} else {
image = SPR_FLAT_SNOWY_TILE; // flat ground
}
}
} else {
/* look for customization */
byte stat_id = GetWaypointByTile(ti->tile)->stat_id;
const StationSpec *statspec = GetCustomStationSpec(STAT_CLASS_WAYP, stat_id);
if (statspec != NULL) {
/* emulate station tile - open with building */
const Station *st = ComposeWaypointStation(ti->tile);
uint gfx = 2;
if (HasBit(statspec->callbackmask, CBM_STATION_SPRITE_LAYOUT)) {
uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
if (callback != CALLBACK_FAILED) gfx = callback;
}
if (statspec->renderdata == NULL) {
dts = GetStationTileLayout(STATION_RAIL, gfx);
} else {
dts = &statspec->renderdata[(gfx < statspec->tiles ? gfx : 0) + GetWaypointAxis(ti->tile)];
}
if (dts != NULL && dts->seq != NULL) {
relocation = GetCustomStationRelocation(statspec, st, ti->tile);
image = dts->ground.sprite;
if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
image += rti->custom_ground_offset;
} else {
image += rti->total_offset;
}
pal = dts->ground.pal;
} else {
goto default_waypoint;
}
} else {
default_waypoint:
/* There is no custom layout, fall back to the default graphics */
dts = &_waypoint_gfx_table[GetWaypointAxis(ti->tile)];
relocation = 0;
image = dts->ground.sprite + rti->total_offset;
if (IsSnowRailGround(ti->tile)) image += rti->snow_offset;
}
}
DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, _drawtile_track_palette));
/* PBS debugging, draw reserved tracks darker */
if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && GetDepotWaypointReservation(ti->tile) &&
(!IsRailDepot(ti->tile) || GetRailDepotDirection(ti->tile) == DIAGDIR_SW || GetRailDepotDirection(ti->tile) == DIAGDIR_SE)) {
DrawGroundSprite(GetWaypointAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_y : rti->base_sprites.single_x, PALETTE_CRASH);
}
if (HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
foreach_draw_tile_seq(dtss, dts->seq) {
SpriteID image = dtss->image.sprite;
SpriteID pal = dtss->image.pal;
/* Stop drawing sprite sequence once we meet a sprite that doesn't have to be opaque */
if (IsInvisibilitySet(TO_BUILDINGS) && !HasBit(image, SPRITE_MODIFIER_OPAQUE)) return;
/* Unlike stations, our default waypoint has no variation for
* different railtype, so don't use the railtype offset if
* no relocation is set */
if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
image += rti->total_offset;
} else {
image += relocation;
}
pal = SpriteLayoutPaletteTransform(image, pal, _drawtile_track_palette);
if ((byte)dtss->delta_z != 0x80) {
AddSortableSpriteToDraw(
image, pal,
ti->x + dtss->delta_x, ti->y + dtss->delta_y,
dtss->size_x, dtss->size_y,
dtss->size_z, ti->z + dtss->delta_z,
!HasBit(image, SPRITE_MODIFIER_OPAQUE) && IsTransparencySet(TO_BUILDINGS)
);
} else {
/* For stations and original spritelayouts delta_x and delta_y are signed */
AddChildSpriteScreen(image, pal, dtss->delta_x, dtss->delta_y, !HasBit(image, SPRITE_MODIFIER_OPAQUE) && IsTransparencySet(TO_BUILDINGS));
}
}
}
DrawBridgeMiddle(ti);
}
static void DrawTileSequence(int x, int y, SpriteID ground, const DrawTileSeqStruct *dtss, uint32 offset)
{
SpriteID palette = COMPANY_SPRITE_COLOUR(_local_company);
DrawSprite(ground, PAL_NONE, x, y);
for (; dtss->image.sprite != 0; dtss++) {
Point pt = RemapCoords(dtss->delta_x, dtss->delta_y, dtss->delta_z);
SpriteID image = dtss->image.sprite + offset;
DrawSprite(image, HasBit(image, PALETTE_MODIFIER_COLOUR) ? palette : PAL_NONE, x + pt.x, y + pt.y);
}
}
void DrawTrainDepotSprite(int x, int y, int dir, RailType railtype)
{
const DrawTileSprites *dts = &_depot_gfx_table[dir];
SpriteID image = dts->ground.sprite;
uint32 offset = GetRailTypeInfo(railtype)->total_offset;
if (image != SPR_FLAT_GRASS_TILE) image += offset;
DrawTileSequence(x + 33, y + 17, image, dts->seq, offset);
}
void DrawDefaultWaypointSprite(int x, int y, RailType railtype)
{
uint32 offset = GetRailTypeInfo(railtype)->total_offset;
const DrawTileSprites *dts = &_waypoint_gfx_table[AXIS_X];
DrawTileSequence(x, y, dts->ground.sprite + offset, dts->seq, 0);
}
static uint GetSlopeZ_Track(TileIndex tile, uint x, uint y)
{
uint z;
Slope tileh = GetTileSlope(tile, &z);
if (tileh == SLOPE_FLAT) return z;
if (IsPlainRailTile(tile)) {
z += ApplyFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
} else {
return z + TILE_HEIGHT;
}
}
static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
{
return IsPlainRailTile(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
}
static void GetAcceptedCargo_Track(TileIndex tile, AcceptedCargo ac)
{
/* not used */
}
static void AnimateTile_Track(TileIndex tile)
{
/* not used */
}
static void TileLoop_Track(TileIndex tile)
{
RailGroundType old_ground = GetRailGroundType(tile);
RailGroundType new_ground;
if (old_ground == RAIL_GROUND_WATER) {
TileLoop_Water(tile);
return;
}
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC: {
uint z;
Slope slope = GetTileSlope(tile, &z);
bool half = false;
/* for non-flat track, use lower part of track
* in other cases, use the highest part with track */
if (IsPlainRailTile(tile)) {
TrackBits track = GetTrackBits(tile);
Foundation f = GetRailFoundation(slope, track);
switch (f) {
case FOUNDATION_NONE:
/* no foundation - is the track on the upper side of three corners raised tile? */
if (IsSlopeWithThreeCornersRaised(slope)) z += TILE_HEIGHT;
break;
case FOUNDATION_INCLINED_X:
case FOUNDATION_INCLINED_Y:
/* sloped track - is it on a steep slope? */
if (IsSteepSlope(slope)) z += TILE_HEIGHT;
break;
case FOUNDATION_STEEP_LOWER:
/* only lower part of steep slope */
z += TILE_HEIGHT;
break;
default:
/* if it is a steep slope, then there is a track on higher part */
if (IsSteepSlope(slope)) z += TILE_HEIGHT;
z += TILE_HEIGHT;
break;
}
half = IsInsideMM(f, FOUNDATION_STEEP_BOTH, FOUNDATION_HALFTILE_N + 1);
} else {
/* is the depot on a non-flat tile? */
if (slope != SLOPE_FLAT) z += TILE_HEIGHT;
}
/* 'z' is now the lowest part of the highest track bit -
* for sloped track, it is 'z' of lower part
* for two track bits, it is 'z' of higher track bit
* For non-continuous foundations (and STEEP_BOTH), 'half' is set */
if (z > GetSnowLine()) {
if (half && z - GetSnowLine() == TILE_HEIGHT) {
/* track on non-continuous foundation, lower part is not under snow */
new_ground = RAIL_GROUND_HALF_SNOW;
} else {
new_ground = RAIL_GROUND_ICE_DESERT;
}
goto set_ground;
}
break;
}
case LT_TROPIC:
if (GetTropicZone(tile) == TROPICZONE_DESERT) {
new_ground = RAIL_GROUND_ICE_DESERT;
goto set_ground;
}
break;
}
if (!IsPlainRailTile(tile)) return;
new_ground = RAIL_GROUND_GRASS;
if (old_ground != RAIL_GROUND_BARREN) { // wait until bottom is green
/* determine direction of fence */
TrackBits rail = GetTrackBits(tile);
switch (rail) {
case TRACK_BIT_UPPER: new_ground = RAIL_GROUND_FENCE_HORIZ1; break;
case TRACK_BIT_LOWER: new_ground = RAIL_GROUND_FENCE_HORIZ2; break;
case TRACK_BIT_LEFT: new_ground = RAIL_GROUND_FENCE_VERT1; break;
case TRACK_BIT_RIGHT: new_ground = RAIL_GROUND_FENCE_VERT2; break;
default: {
Owner owner = GetTileOwner(tile);
if (rail == (TRACK_BIT_LOWER | TRACK_BIT_RIGHT) || (
(rail & TRACK_BIT_3WAY_NW) == 0 &&
(rail & TRACK_BIT_X)
)) {
TileIndex n = tile + TileDiffXY(0, -1);
TrackBits nrail = GetTrackBits(n);
if (!IsTileType(n, MP_RAILWAY) ||
!IsTileOwner(n, owner) ||
nrail == TRACK_BIT_UPPER ||
nrail == TRACK_BIT_LEFT) {
new_ground = RAIL_GROUND_FENCE_NW;
}
}
if (rail == (TRACK_BIT_UPPER | TRACK_BIT_LEFT) || (
(rail & TRACK_BIT_3WAY_SE) == 0 &&
(rail & TRACK_BIT_X)
)) {
TileIndex n = tile + TileDiffXY(0, 1);
TrackBits nrail = GetTrackBits(n);
if (!IsTileType(n, MP_RAILWAY) ||
!IsTileOwner(n, owner) ||
nrail == TRACK_BIT_LOWER ||
nrail == TRACK_BIT_RIGHT) {
new_ground = (new_ground == RAIL_GROUND_FENCE_NW) ?
RAIL_GROUND_FENCE_SENW : RAIL_GROUND_FENCE_SE;
}
}
if (rail == (TRACK_BIT_LOWER | TRACK_BIT_LEFT) || (
(rail & TRACK_BIT_3WAY_NE) == 0 &&
(rail & TRACK_BIT_Y)
)) {
TileIndex n = tile + TileDiffXY(-1, 0);
TrackBits nrail = GetTrackBits(n);
if (!IsTileType(n, MP_RAILWAY) ||
!IsTileOwner(n, owner) ||
nrail == TRACK_BIT_UPPER ||
nrail == TRACK_BIT_RIGHT) {
new_ground = RAIL_GROUND_FENCE_NE;
}
}
if (rail == (TRACK_BIT_UPPER | TRACK_BIT_RIGHT) || (
(rail & TRACK_BIT_3WAY_SW) == 0 &&
(rail & TRACK_BIT_Y)
)) {
TileIndex n = tile + TileDiffXY(1, 0);
TrackBits nrail = GetTrackBits(n);
if (!IsTileType(n, MP_RAILWAY) ||
!IsTileOwner(n, owner) ||
nrail == TRACK_BIT_LOWER ||
nrail == TRACK_BIT_LEFT) {
new_ground = (new_ground == RAIL_GROUND_FENCE_NE) ?
RAIL_GROUND_FENCE_NESW : RAIL_GROUND_FENCE_SW;
}
}
break;
}
}
}
set_ground:
if (old_ground != new_ground) {
SetRailGroundType(tile, new_ground);
MarkTileDirtyByTile(tile);
}
}
static TrackStatus GetTileTrackStatus_Track(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
{
/* Case of half tile slope with water. */
if (mode == TRANSPORT_WATER && IsPlainRailTile(tile) && GetRailGroundType(tile) == RAIL_GROUND_WATER) {
TrackBits tb = GetTrackBits(tile);
switch (tb) {
default: NOT_REACHED();
case TRACK_BIT_UPPER: tb = TRACK_BIT_LOWER; break;
case TRACK_BIT_LOWER: tb = TRACK_BIT_UPPER; break;
case TRACK_BIT_LEFT: tb = TRACK_BIT_RIGHT; break;
case TRACK_BIT_RIGHT: tb = TRACK_BIT_LEFT; break;
}
return CombineTrackStatus(TrackBitsToTrackdirBits(tb), TRACKDIR_BIT_NONE);
}
if (mode != TRANSPORT_RAIL) return 0;
TrackBits trackbits = TRACK_BIT_NONE;
TrackdirBits red_signals = TRACKDIR_BIT_NONE;
switch (GetRailTileType(tile)) {
default: NOT_REACHED();
case RAIL_TILE_NORMAL:
trackbits = GetTrackBits(tile);
break;
case RAIL_TILE_SIGNALS: {
trackbits = GetTrackBits(tile);
byte a = GetPresentSignals(tile);
uint b = GetSignalStates(tile);
b &= a;
/* When signals are not present (in neither direction),
* we pretend them to be green. Otherwise, it depends on
* the signal type. For signals that are only active from
* one side, we set the missing signals explicitely to
* `green'. Otherwise, they implicitely become `red'. */
if (!IsOnewaySignal(tile, TRACK_UPPER) || (a & SignalOnTrack(TRACK_UPPER)) == 0) b |= ~a & SignalOnTrack(TRACK_UPPER);
if (!IsOnewaySignal(tile, TRACK_LOWER) || (a & SignalOnTrack(TRACK_LOWER)) == 0) b |= ~a & SignalOnTrack(TRACK_LOWER);
if ((b & 0x8) == 0) red_signals |= (TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E);
if ((b & 0x4) == 0) red_signals |= (TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_UPPER_W);
if ((b & 0x2) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_E);
if ((b & 0x1) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_W);
break;
}
case RAIL_TILE_DEPOT: {
DiagDirection dir = GetRailDepotDirection(tile);
if (side != INVALID_DIAGDIR && side != dir) break;
trackbits = DiagDirToDiagTrackBits(dir);
break;
}
case RAIL_TILE_WAYPOINT:
trackbits = GetRailWaypointBits(tile);
break;
}
return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), red_signals);
}
static bool ClickTile_Track(TileIndex tile)
{
switch (GetRailTileType(tile)) {
case RAIL_TILE_DEPOT: ShowDepotWindow(tile, VEH_TRAIN); return true;
case RAIL_TILE_WAYPOINT: ShowWaypointWindow(GetWaypointByTile(tile)); return true;
default: return false;
}
}
static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
{
td->owner[0] = GetTileOwner(tile);
switch (GetRailTileType(tile)) {
case RAIL_TILE_NORMAL:
td->str = STR_1021_RAILROAD_TRACK;
break;
case RAIL_TILE_SIGNALS: {
const StringID signal_type[6][6] = {
{
STR_RAILROAD_TRACK_WITH_NORMAL_SIGNALS,
STR_RAILROAD_TRACK_WITH_NORMAL_PRESIGNALS,
STR_RAILROAD_TRACK_WITH_NORMAL_EXITSIGNALS,
STR_RAILROAD_TRACK_WITH_NORMAL_COMBOSIGNALS,
STR_RAILROAD_TRACK_WITH_NORMAL_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_NORMAL_NOENTRYSIGNALS
},
{
STR_RAILROAD_TRACK_WITH_NORMAL_PRESIGNALS,
STR_RAILROAD_TRACK_WITH_PRESIGNALS,
STR_RAILROAD_TRACK_WITH_PRE_EXITSIGNALS,
STR_RAILROAD_TRACK_WITH_PRE_COMBOSIGNALS,
STR_RAILROAD_TRACK_WITH_PRE_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_PRE_NOENTRYSIGNALS
},
{
STR_RAILROAD_TRACK_WITH_NORMAL_EXITSIGNALS,
STR_RAILROAD_TRACK_WITH_PRE_EXITSIGNALS,
STR_RAILROAD_TRACK_WITH_EXITSIGNALS,
STR_RAILROAD_TRACK_WITH_EXIT_COMBOSIGNALS,
STR_RAILROAD_TRACK_WITH_EXIT_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_EXIT_NOENTRYSIGNALS
},
{
STR_RAILROAD_TRACK_WITH_NORMAL_COMBOSIGNALS,
STR_RAILROAD_TRACK_WITH_PRE_COMBOSIGNALS,
STR_RAILROAD_TRACK_WITH_EXIT_COMBOSIGNALS,
STR_RAILROAD_TRACK_WITH_COMBOSIGNALS,
STR_RAILROAD_TRACK_WITH_COMBO_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_COMBO_NOENTRYSIGNALS
},
{
STR_RAILROAD_TRACK_WITH_NORMAL_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_PRE_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_EXIT_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_COMBO_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_PBSSIGNALS,
STR_RAILROAD_TRACK_WITH_PBS_NOENTRYSIGNALS
},
{
STR_RAILROAD_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
STR_RAILROAD_TRACK_WITH_PRE_NOENTRYSIGNALS,
STR_RAILROAD_TRACK_WITH_EXIT_NOENTRYSIGNALS,
STR_RAILROAD_TRACK_WITH_COMBO_NOENTRYSIGNALS,
STR_RAILROAD_TRACK_WITH_PBS_NOENTRYSIGNALS,
STR_RAILROAD_TRACK_WITH_NOENTRYSIGNALS
}
};
SignalType primary_signal;
SignalType secondary_signal;
if (HasSignalOnTrack(tile, TRACK_UPPER)) {
primary_signal = GetSignalType(tile, TRACK_UPPER);
secondary_signal = HasSignalOnTrack(tile, TRACK_LOWER) ? GetSignalType(tile, TRACK_LOWER) : primary_signal;
} else {
secondary_signal = primary_signal = GetSignalType(tile, TRACK_LOWER);
}
td->str = signal_type[secondary_signal][primary_signal];
break;
}
case RAIL_TILE_DEPOT:
td->str = STR_1023_RAILROAD_TRAIN_DEPOT;
break;
case RAIL_TILE_WAYPOINT:
default:
td->str = STR_LANDINFO_WAYPOINT;
break;
}
}
static void ChangeTileOwner_Track(TileIndex tile, Owner old_owner, Owner new_owner)
{
if (!IsTileOwner(tile, old_owner)) return;
if (new_owner != INVALID_OWNER) {
SetTileOwner(tile, new_owner);
} else {
DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
}
}
static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
static const signed char _deltacoord_leaveoffset[8] = {
-1, 0, 1, 0, /* x */
0, 1, 0, -1 /* y */
};
/** Compute number of ticks when next wagon will leave a depot.
* Negative means next wagon should have left depot n ticks before.
* @param v vehicle outside (leaving) the depot
* @return number of ticks when the next wagon will leave
*/
int TicksToLeaveDepot(const Vehicle *v)
{
DiagDirection dir = GetRailDepotDirection(v->tile);
int length = v->u.rail.cached_veh_length;
switch (dir) {
case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1)));
case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1)));
case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1)));
default:
case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1)));
}
return 0; // make compilers happy
}
/** Tile callback routine when vehicle enters tile
* @see vehicle_enter_tile_proc */
static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *v, TileIndex tile, int x, int y)
{
byte fract_coord;
byte fract_coord_leave;
DiagDirection dir;
int length;
/* this routine applies only to trains in depot tiles */
if (v->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
/* depot direction */
dir = GetRailDepotDirection(tile);
/* calculate the point where the following wagon should be activated
* this depends on the length of the current vehicle */
length = v->u.rail.cached_veh_length;
fract_coord_leave =
((_fractcoords_enter[dir] & 0x0F) + // x
(length + 1) * _deltacoord_leaveoffset[dir]) +
(((_fractcoords_enter[dir] >> 4) + // y
((length + 1) * _deltacoord_leaveoffset[dir+4])) << 4);
fract_coord = (x & 0xF) + ((y & 0xF) << 4);
if (_fractcoords_behind[dir] == fract_coord) {
/* make sure a train is not entering the tile from behind */
return VETSB_CANNOT_ENTER;
} else if (_fractcoords_enter[dir] == fract_coord) {
if (DiagDirToDir(ReverseDiagDir(dir)) == v->direction) {
/* enter the depot */
v->u.rail.track = TRACK_BIT_DEPOT,
v->vehstatus |= VS_HIDDEN; // hide it
v->direction = ReverseDir(v->direction);
if (v->Next() == NULL) VehicleEnterDepot(v);
v->tile = tile;
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
return VETSB_ENTERED_WORMHOLE;
}
} else if (fract_coord_leave == fract_coord) {
if (DiagDirToDir(dir) == v->direction) {
/* leave the depot? */
if ((v = v->Next()) != NULL) {
v->vehstatus &= ~VS_HIDDEN;
v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
}
}
}
return VETSB_CONTINUE;
}
/**
* Tests if autoslope is allowed.
*
* @param tile The tile.
* @param flags Terraform command flags.
* @param z_old Old TileZ.
* @param tileh_old Old TileSlope.
* @param z_new New TileZ.
* @param tileh_new New TileSlope.
* @param rail_bits Trackbits.
*/
static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, uint z_old, Slope tileh_old, uint z_new, Slope tileh_new, TrackBits rail_bits)
{
if (!_settings_game.construction.build_on_slopes || !AutoslopeEnabled()) return CMD_ERROR;
/* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
if (CmdFailed(CheckRailSlope(tileh_new, rail_bits, TRACK_BIT_NONE, tile))) return CMD_ERROR;
/* Get the slopes on top of the foundations */
z_old += ApplyFoundationToSlope(GetRailFoundation(tileh_old, rail_bits), &tileh_old);
z_new += ApplyFoundationToSlope(GetRailFoundation(tileh_new, rail_bits), &tileh_new);
Corner track_corner;
switch (rail_bits) {
case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
/* Surface slope must not be changed */
default: return (((z_old != z_new) || (tileh_old != tileh_new)) ? CMD_ERROR : CommandCost(EXPENSES_CONSTRUCTION, _price.terraform));
}
/* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
z_old += GetSlopeZInCorner(RemoveHalftileSlope(tileh_old), track_corner);
z_new += GetSlopeZInCorner(RemoveHalftileSlope(tileh_new), track_corner);
if (z_old != z_new) return CMD_ERROR;
CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
/* Make the ground dirty, if surface slope has changed */
if (tileh_old != tileh_new) {
/* If there is flat water on the lower halftile add the cost for clearing it */
if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old)) cost.AddCost(_price.clear_water);
if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
}
return cost;
}
static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
{
uint z_old;
Slope tileh_old = GetTileSlope(tile, &z_old);
if (IsPlainRailTile(tile)) {
TrackBits rail_bits = GetTrackBits(tile);
/* Is there flat water on the lower halftile, that must be cleared expensively? */
bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
_error_message = STR_1008_MUST_REMOVE_RAILROAD_TRACK;
/* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
/* When there is only a single horizontal/vertical track, one corner can be terraformed. */
Corner allowed_corner;
switch (rail_bits) {
case TRACK_BIT_RIGHT: allowed_corner = CORNER_W; break;
case TRACK_BIT_UPPER: allowed_corner = CORNER_S; break;
case TRACK_BIT_LEFT: allowed_corner = CORNER_E; break;
case TRACK_BIT_LOWER: allowed_corner = CORNER_N; break;
default: return autoslope_result;
}
Foundation f_old = GetRailFoundation(tileh_old, rail_bits);
/* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result;
/* Everything is valid, which only changes allowed_corner */
for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) {
if (allowed_corner == corner) continue;
if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result;
}
/* Make the ground dirty */
if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
/* allow terraforming */
return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price.clear_water : (Money)0);
} else {
if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
switch (GetRailTileType(tile)) {
case RAIL_TILE_WAYPOINT: {
CommandCost cost = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, GetRailWaypointBits(tile));
if (!CmdFailed(cost)) return cost; // allow autoslope
break;
}
case RAIL_TILE_DEPOT:
if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
break;
default: NOT_REACHED();
}
}
}
return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
}
extern const TileTypeProcs _tile_type_rail_procs = {
DrawTile_Track, // draw_tile_proc
GetSlopeZ_Track, // get_slope_z_proc
ClearTile_Track, // clear_tile_proc
GetAcceptedCargo_Track, // get_accepted_cargo_proc
GetTileDesc_Track, // get_tile_desc_proc
GetTileTrackStatus_Track, // get_tile_track_status_proc
ClickTile_Track, // click_tile_proc
AnimateTile_Track, // animate_tile_proc
TileLoop_Track, // tile_loop_clear
ChangeTileOwner_Track, // change_tile_owner_clear
NULL, // get_produced_cargo_proc
VehicleEnter_Track, // vehicle_enter_tile_proc
GetFoundation_Track, // get_foundation_proc
TerraformTile_Track, // terraform_tile_proc
};
| 90,818
|
C++
|
.cpp
| 2,209
| 37.622001
| 196
| 0.689193
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,073
|
order_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/order_gui.cpp
|
/* $Id$ */
/** @file order_gui.cpp GUI related to orders. */
#include "stdafx.h"
#include "station_map.h"
#include "window_gui.h"
#include "command_func.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "depot_base.h"
#include "vehicle_base.h"
#include "vehicle_gui.h"
#include "timetable.h"
#include "cargotype.h"
#include "strings_func.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "company_func.h"
#include "newgrf_cargo.h"
#include "widgets/dropdown_func.h"
#include "textbuf_gui.h"
#include "string_func.h"
#include "tilehighlight_func.h"
#include "network/network.h"
#include "settings_type.h"
#include "table/sprites.h"
#include "table/strings.h"
enum OrderWindowWidgets {
ORDER_WIDGET_CLOSEBOX = 0,
ORDER_WIDGET_CAPTION,
ORDER_WIDGET_TIMETABLE_VIEW,
ORDER_WIDGET_STICKY,
ORDER_WIDGET_ORDER_LIST,
ORDER_WIDGET_SCROLLBAR,
ORDER_WIDGET_SKIP,
ORDER_WIDGET_DELETE,
ORDER_WIDGET_NON_STOP_DROPDOWN,
ORDER_WIDGET_NON_STOP,
ORDER_WIDGET_GOTO_DROPDOWN,
ORDER_WIDGET_GOTO,
ORDER_WIDGET_FULL_LOAD_DROPDOWN,
ORDER_WIDGET_FULL_LOAD,
ORDER_WIDGET_UNLOAD_DROPDOWN,
ORDER_WIDGET_UNLOAD,
ORDER_WIDGET_REFIT,
ORDER_WIDGET_SERVICE_DROPDOWN,
ORDER_WIDGET_SERVICE,
ORDER_WIDGET_COND_VARIABLE,
ORDER_WIDGET_COND_COMPARATOR,
ORDER_WIDGET_COND_VALUE,
ORDER_WIDGET_RESIZE_BAR,
ORDER_WIDGET_SHARED_ORDER_LIST,
ORDER_WIDGET_RESIZE,
};
/** Order load types that could be given to station orders. */
static const StringID _station_load_types[][5] = {
{
STR_EMPTY,
INVALID_STRING_ID,
STR_ORDER_FULL_LOAD,
STR_ORDER_FULL_LOAD_ANY,
STR_ORDER_NO_LOAD,
}, {
STR_ORDER_UNLOAD,
INVALID_STRING_ID,
STR_ORDER_UNLOAD_FULL_LOAD,
STR_ORDER_UNLOAD_FULL_LOAD_ANY,
STR_ORDER_UNLOAD_NO_LOAD,
}, {
STR_ORDER_TRANSFER,
INVALID_STRING_ID,
STR_ORDER_TRANSFER_FULL_LOAD,
STR_ORDER_TRANSFER_FULL_LOAD_ANY,
STR_ORDER_TRANSFER_NO_LOAD,
}, {
/* Unload and transfer do not work together. */
INVALID_STRING_ID,
INVALID_STRING_ID,
INVALID_STRING_ID,
INVALID_STRING_ID,
}, {
STR_ORDER_NO_UNLOAD,
INVALID_STRING_ID,
STR_ORDER_NO_UNLOAD_FULL_LOAD,
STR_ORDER_NO_UNLOAD_FULL_LOAD_ANY,
INVALID_STRING_ID,
}
};
static const StringID _order_non_stop_drowdown[] = {
STR_ORDER_GO_TO,
STR_ORDER_GO_NON_STOP_TO,
STR_ORDER_GO_VIA,
STR_ORDER_GO_NON_STOP_VIA,
INVALID_STRING_ID
};
static const StringID _order_full_load_drowdown[] = {
STR_ORDER_DROP_LOAD_IF_POSSIBLE,
STR_EMPTY,
STR_ORDER_DROP_FULL_LOAD_ALL,
STR_ORDER_DROP_FULL_LOAD_ANY,
STR_ORDER_DROP_NO_LOADING,
INVALID_STRING_ID
};
static const StringID _order_unload_drowdown[] = {
STR_ORDER_DROP_UNLOAD_IF_ACCEPTED,
STR_ORDER_DROP_UNLOAD,
STR_ORDER_DROP_TRANSFER,
STR_EMPTY,
STR_ORDER_DROP_NO_UNLOADING,
INVALID_STRING_ID
};
static const StringID _order_goto_dropdown[] = {
STR_ORDER_GO_TO,
STR_ORDER_GO_TO_NEAREST_DEPOT,
STR_ORDER_CONDITIONAL,
INVALID_STRING_ID
};
static const StringID _order_goto_dropdown_aircraft[] = {
STR_ORDER_GO_TO,
STR_ORDER_GO_TO_NEAREST_HANGAR,
STR_ORDER_CONDITIONAL,
INVALID_STRING_ID
};
static const StringID _order_conditional_variable[] = {
STR_ORDER_CONDITIONAL_LOAD_PERCENTAGE,
STR_ORDER_CONDITIONAL_RELIABILITY,
STR_ORDER_CONDITIONAL_MAX_SPEED,
STR_ORDER_CONDITIONAL_AGE,
STR_ORDER_CONDITIONAL_REQUIRES_SERVICE,
STR_ORDER_CONDITIONAL_UNCONDITIONALLY,
INVALID_STRING_ID,
};
static const StringID _order_conditional_condition[] = {
STR_ORDER_CONDITIONAL_COMPARATOR_EQUALS,
STR_ORDER_CONDITIONAL_COMPARATOR_NOT_EQUALS,
STR_ORDER_CONDITIONAL_COMPARATOR_LESS_THAN,
STR_ORDER_CONDITIONAL_COMPARATOR_LESS_EQUALS,
STR_ORDER_CONDITIONAL_COMPARATOR_MORE_THAN,
STR_ORDER_CONDITIONAL_COMPARATOR_MORE_EQUALS,
STR_ORDER_CONDITIONAL_COMPARATOR_IS_TRUE,
STR_ORDER_CONDITIONAL_COMPARATOR_IS_FALSE,
INVALID_STRING_ID,
};
extern uint ConvertSpeedToDisplaySpeed(uint speed);
extern uint ConvertDisplaySpeedToSpeed(uint speed);
static const StringID _order_depot_action_dropdown[] = {
STR_ORDER_DROP_GO_ALWAYS_DEPOT,
STR_ORDER_DROP_SERVICE_DEPOT,
STR_ORDER_DROP_HALT_DEPOT,
INVALID_STRING_ID
};
static int DepotActionStringIndex(const Order *order)
{
if (order->GetDepotActionType() & ODATFB_HALT) {
return DA_STOP;
} else if (order->GetDepotOrderType() & ODTFB_SERVICE) {
return DA_SERVICE;
} else {
return DA_ALWAYS_GO;
}
}
void DrawOrderString(const Vehicle *v, const Order *order, int order_index, int y, bool selected, bool timetable, int width)
{
StringID str = (v->cur_order_index == order_index) ? STR_8805 : STR_8804;
SetDParam(6, STR_EMPTY);
switch (order->GetType()) {
case OT_DUMMY:
SetDParam(1, STR_INVALID_ORDER);
SetDParam(2, order->GetDestination());
break;
case OT_GOTO_STATION: {
OrderLoadFlags load = order->GetLoadType();
OrderUnloadFlags unload = order->GetUnloadType();
SetDParam(1, STR_GO_TO_STATION);
SetDParam(2, STR_ORDER_GO_TO + ((v->type == VEH_TRAIN || v->type == VEH_ROAD) ? order->GetNonStopType() : 0));
SetDParam(3, order->GetDestination());
if (timetable) {
SetDParam(4, STR_EMPTY);
if (order->wait_time > 0) {
SetDParam(6, STR_TIMETABLE_STAY_FOR);
SetTimetableParams(7, 8, order->wait_time);
}
} else {
SetDParam(4, (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) ? STR_EMPTY : _station_load_types[unload][load]);
}
} break;
case OT_GOTO_DEPOT:
if (v->type == VEH_AIRCRAFT) {
if (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
SetDParam(1, STR_GO_TO_NEAREST_DEPOT);
SetDParam(3, STR_ORDER_NEAREST_HANGAR);
} else {
SetDParam(1, STR_GO_TO_HANGAR);
SetDParam(3, order->GetDestination());
}
SetDParam(4, STR_EMPTY);
} else {
if (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
SetDParam(1, STR_GO_TO_NEAREST_DEPOT);
SetDParam(3, STR_ORDER_NEAREST_DEPOT);
} else {
SetDParam(1, STR_GO_TO_DEPOT);
SetDParam(3, GetDepot(order->GetDestination())->town_index);
}
switch (v->type) {
case VEH_TRAIN: SetDParam(4, STR_ORDER_TRAIN_DEPOT); break;
case VEH_ROAD: SetDParam(4, STR_ORDER_ROAD_DEPOT); break;
case VEH_SHIP: SetDParam(4, STR_ORDER_SHIP_DEPOT); break;
default: NOT_REACHED();
}
}
if (order->GetDepotOrderType() & ODTFB_SERVICE) {
SetDParam(2, (order->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) ? STR_ORDER_SERVICE_NON_STOP_AT : STR_ORDER_SERVICE_AT);
} else {
SetDParam(2, (order->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) ? STR_ORDER_GO_NON_STOP_TO : STR_ORDER_GO_TO);
}
if (!timetable && (order->GetDepotActionType() & ODATFB_HALT)) {
SetDParam(6, STR_STOP_ORDER);
}
if (!timetable && order->IsRefit()) {
SetDParam(6, (order->GetDepotActionType() & ODATFB_HALT) ? STR_REFIT_STOP_ORDER : STR_REFIT_ORDER);
SetDParam(7, GetCargo(order->GetRefitCargo())->name);
}
break;
case OT_GOTO_WAYPOINT:
SetDParam(1, (order->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) ? STR_GO_NON_STOP_TO_WAYPOINT : STR_GO_TO_WAYPOINT);
SetDParam(2, order->GetDestination());
break;
case OT_CONDITIONAL:
SetDParam(2, order->GetConditionSkipToOrder() + 1);
if (order->GetConditionVariable() == OCV_UNCONDITIONALLY) {
SetDParam(1, STR_CONDITIONAL_UNCONDITIONAL);
} else {
OrderConditionComparator occ = order->GetConditionComparator();
SetDParam(1, (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) ? STR_CONDITIONAL_TRUE_FALSE : STR_CONDITIONAL_NUM);
SetDParam(3, STR_ORDER_CONDITIONAL_LOAD_PERCENTAGE + order->GetConditionVariable());
SetDParam(4, STR_ORDER_CONDITIONAL_COMPARATOR_EQUALS + occ);
uint value = order->GetConditionValue();
if (order->GetConditionVariable() == OCV_MAX_SPEED) value = ConvertSpeedToDisplaySpeed(value);
SetDParam(5, value);
}
if (timetable && order->wait_time > 0) {
SetDParam(6, STR_TIMETABLE_AND_TRAVEL_FOR);
SetTimetableParams(7, 8, order->wait_time);
} else {
SetDParam(6, STR_EMPTY);
}
break;
default: NOT_REACHED();
}
SetDParam(0, order_index + 1);
DrawStringTruncated(2, y, str, selected ? TC_WHITE : TC_BLACK, width);
}
static Order GetOrderCmdFromTile(const Vehicle *v, TileIndex tile)
{
Order order;
order.next = NULL;
order.index = 0;
/* check depot first */
if (_settings_game.order.gotodepot) {
switch (GetTileType(tile)) {
case MP_RAILWAY:
if (v->type == VEH_TRAIN && IsTileOwner(tile, _local_company)) {
if (IsRailDepot(tile)) {
order.MakeGoToDepot(GetDepotByTile(tile)->index, ODTFB_PART_OF_ORDERS);
if (_ctrl_pressed) order.SetDepotOrderType((OrderDepotTypeFlags)(order.GetDepotOrderType() ^ ODTFB_SERVICE));
if (_settings_client.gui.new_nonstop) order.SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
return order;
}
}
break;
case MP_ROAD:
if (IsRoadDepot(tile) && v->type == VEH_ROAD && IsTileOwner(tile, _local_company)) {
order.MakeGoToDepot(GetDepotByTile(tile)->index, ODTFB_PART_OF_ORDERS);
if (_ctrl_pressed) order.SetDepotOrderType((OrderDepotTypeFlags)(order.GetDepotOrderType() ^ ODTFB_SERVICE));
if (_settings_client.gui.new_nonstop) order.SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
return order;
}
break;
case MP_STATION:
if (v->type != VEH_AIRCRAFT) break;
if (IsHangar(tile) && IsTileOwner(tile, _local_company)) {
order.MakeGoToDepot(GetStationIndex(tile), ODTFB_PART_OF_ORDERS);
if (_ctrl_pressed) order.SetDepotOrderType((OrderDepotTypeFlags)(order.GetDepotOrderType() ^ ODTFB_SERVICE));
return order;
}
break;
case MP_WATER:
if (v->type != VEH_SHIP) break;
if (IsShipDepot(tile) && IsTileOwner(tile, _local_company)) {
TileIndex tile2 = GetOtherShipDepotTile(tile);
order.MakeGoToDepot(GetDepotByTile(tile < tile2 ? tile : tile2)->index, ODTFB_PART_OF_ORDERS);
if (_ctrl_pressed) order.SetDepotOrderType((OrderDepotTypeFlags)(order.GetDepotOrderType() ^ ODTFB_SERVICE));
return order;
}
default:
break;
}
}
/* check waypoint */
if (IsRailWaypointTile(tile) &&
v->type == VEH_TRAIN &&
IsTileOwner(tile, _local_company)) {
order.MakeGoToWaypoint(GetWaypointByTile(tile)->index);
if (_settings_client.gui.new_nonstop != _ctrl_pressed) order.SetNonStopType(ONSF_NO_STOP_AT_ANY_STATION);
return order;
}
if (IsTileType(tile, MP_STATION)) {
StationID st_index = GetStationIndex(tile);
const Station *st = GetStation(st_index);
if (st->owner == _local_company || st->owner == OWNER_NONE) {
byte facil;
(facil = FACIL_DOCK, v->type == VEH_SHIP) ||
(facil = FACIL_TRAIN, v->type == VEH_TRAIN) ||
(facil = FACIL_AIRPORT, v->type == VEH_AIRCRAFT) ||
(facil = FACIL_BUS_STOP, v->type == VEH_ROAD && IsCargoInClass(v->cargo_type, CC_PASSENGERS)) ||
(facil = FACIL_TRUCK_STOP, 1);
if (st->facilities & facil) {
order.MakeGoToStation(st_index);
if (_ctrl_pressed) order.SetLoadType(OLF_FULL_LOAD_ANY);
if (_settings_client.gui.new_nonstop && (v->type == VEH_TRAIN || v->type == VEH_ROAD)) order.SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
return order;
}
}
}
/* not found */
order.Free();
return order;
}
struct OrdersWindow : public Window {
private:
/** Under what reason are we using the PlaceObject functionality? */
enum OrderPlaceObjectState {
OPOS_GOTO,
OPOS_CONDITIONAL,
};
int selected_order;
OrderPlaceObjectState goto_type;
const Vehicle *vehicle;
/**
* Return the memorised selected order.
* @return the memorised order if it is a vaild one
* else return the number of orders
*/
int OrderGetSel()
{
int num = this->selected_order;
return (num >= 0 && num < vehicle->GetNumOrders()) ? num : vehicle->GetNumOrders();
}
/**
* Calculate the selected order.
* The calculation is based on the relative (to the window) y click position and
* the position of the scrollbar.
*
* @param y Y-value of the click relative to the window origin
* @param v current vehicle
* @return the new selected order if the order is valid else return that
* an invalid one has been selected.
*/
int GetOrderFromPt(int y)
{
/*
* Calculation description:
* 15 = 14 (w->widget[ORDER_WIDGET_ORDER_LIST].top) + 1 (frame-line)
* 10 = order text hight
*/
int sel = (y - this->widget[ORDER_WIDGET_ORDER_LIST].top - 1) / 10;
if ((uint)sel >= this->vscroll.cap) return INVALID_ORDER;
sel += this->vscroll.pos;
return (sel <= vehicle->GetNumOrders() && sel >= 0) ? sel : INVALID_ORDER;
}
bool HandleOrderVehClick(const Vehicle *u)
{
if (u->type != this->vehicle->type) return false;
if (!u->IsPrimaryVehicle()) {
u = u->First();
if (!u->IsPrimaryVehicle()) return false;
}
/* v is vehicle getting orders. Only copy/clone orders if vehicle doesn't have any orders yet
* obviously if you press CTRL on a non-empty orders vehicle you know what you are doing */
if (this->vehicle->GetNumOrders() != 0 && _ctrl_pressed == 0) return false;
if (DoCommandP(this->vehicle->tile, this->vehicle->index | (u->index << 16), _ctrl_pressed ? CO_SHARE : CO_COPY,
_ctrl_pressed ? CMD_CLONE_ORDER | CMD_MSG(STR_CANT_SHARE_ORDER_LIST) : CMD_CLONE_ORDER | CMD_MSG(STR_CANT_COPY_ORDER_LIST))) {
this->selected_order = -1;
ResetObjectToPlace();
}
return true;
}
/**
* Handle the click on the goto button.
*
* @param w current window
*/
static void OrderClick_Goto(OrdersWindow *w, int i)
{
w->InvalidateWidget(ORDER_WIDGET_GOTO);
w->ToggleWidgetLoweredState(ORDER_WIDGET_GOTO);
if (w->IsWidgetLowered(ORDER_WIDGET_GOTO)) {
_place_clicked_vehicle = NULL;
SetObjectToPlaceWnd(ANIMCURSOR_PICKSTATION, PAL_NONE, VHM_RECT, w);
w->goto_type = OPOS_GOTO;
} else {
ResetObjectToPlace();
}
}
/**
* Handle the click on the full load button.
*
* @param w current window
* @param load_type the way to load.
*/
static void OrderClick_FullLoad(OrdersWindow *w, int load_type)
{
VehicleOrderID sel_ord = w->OrderGetSel();
const Order *order = GetVehicleOrder(w->vehicle, sel_ord);
if (order == NULL || order->GetLoadType() == load_type) return;
if (load_type < 0) {
load_type = order->GetLoadType() == OLF_LOAD_IF_POSSIBLE ? OLF_FULL_LOAD_ANY : OLF_LOAD_IF_POSSIBLE;
}
DoCommandP(w->vehicle->tile, w->vehicle->index + (sel_ord << 16), MOF_LOAD | (load_type << 4), CMD_MODIFY_ORDER | CMD_MSG(STR_8835_CAN_T_MODIFY_THIS_ORDER));
}
/**
* Handle the click on the service.
*
* @param w current window
*/
static void OrderClick_Service(OrdersWindow *w, int i)
{
VehicleOrderID sel_ord = w->OrderGetSel();
if (i < 0) {
const Order *order = GetVehicleOrder(w->vehicle, sel_ord);
if (order == NULL) return;
i = (order->GetDepotOrderType() & ODTFB_SERVICE) ? DA_ALWAYS_GO : DA_SERVICE;
}
DoCommandP(w->vehicle->tile, w->vehicle->index + (sel_ord << 16), MOF_DEPOT_ACTION | (i << 4), CMD_MODIFY_ORDER | CMD_MSG(STR_8835_CAN_T_MODIFY_THIS_ORDER));
}
/**
* Handle the click on the service in nearest depot button.
*
* @param w current window
*/
static void OrderClick_NearestDepot(OrdersWindow *w, int i)
{
Order order;
order.next = NULL;
order.index = 0;
order.MakeGoToDepot(0, ODTFB_PART_OF_ORDERS);
order.SetDepotActionType(ODATFB_NEAREST_DEPOT);
DoCommandP(w->vehicle->tile, w->vehicle->index + (w->OrderGetSel() << 16), order.Pack(), CMD_INSERT_ORDER | CMD_MSG(STR_8833_CAN_T_INSERT_NEW_ORDER));
}
/**
* Handle the click on the conditional order button.
*
* @param w current window
*/
static void OrderClick_Conditional(OrdersWindow *w, int i)
{
w->InvalidateWidget(ORDER_WIDGET_GOTO);
w->LowerWidget(ORDER_WIDGET_GOTO);
SetObjectToPlaceWnd(ANIMCURSOR_PICKSTATION, PAL_NONE, VHM_RECT, w);
w->goto_type = OPOS_CONDITIONAL;
}
/**
* Handle the click on the unload button.
*
* @param w current window
*/
static void OrderClick_Unload(OrdersWindow *w, int unload_type)
{
VehicleOrderID sel_ord = w->OrderGetSel();
const Order *order = GetVehicleOrder(w->vehicle, sel_ord);
if (order == NULL || order->GetUnloadType() == unload_type) return;
if (unload_type < 0) {
unload_type = order->GetUnloadType() == OUF_UNLOAD_IF_POSSIBLE ? OUFB_UNLOAD : OUF_UNLOAD_IF_POSSIBLE;
}
DoCommandP(w->vehicle->tile, w->vehicle->index + (sel_ord << 16), MOF_UNLOAD | (unload_type << 4), CMD_MODIFY_ORDER | CMD_MSG(STR_8835_CAN_T_MODIFY_THIS_ORDER));
}
/**
* Handle the click on the nonstop button.
*
* @param w current window
* @param non_stop what non-stop type to use; -1 to use the 'next' one.
*/
static void OrderClick_Nonstop(OrdersWindow *w, int non_stop)
{
VehicleOrderID sel_ord = w->OrderGetSel();
const Order *order = GetVehicleOrder(w->vehicle, sel_ord);
if (order == NULL || order->GetNonStopType() == non_stop) return;
/* Keypress if negative, so 'toggle' to the next */
if (non_stop < 0) {
non_stop = order->GetNonStopType() ^ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS;
}
w->InvalidateWidget(ORDER_WIDGET_NON_STOP);
DoCommandP(w->vehicle->tile, w->vehicle->index + (sel_ord << 16), MOF_NON_STOP | non_stop << 4, CMD_MODIFY_ORDER | CMD_MSG(STR_8835_CAN_T_MODIFY_THIS_ORDER));
}
/**
* Handle the click on the skip button.
* If ctrl is pressed skip to selected order.
* Else skip to current order + 1
*
* @param w current window
*/
static void OrderClick_Skip(OrdersWindow *w, int i)
{
/* Don't skip when there's nothing to skip */
if (_ctrl_pressed && w->vehicle->cur_order_index == w->OrderGetSel()) return;
if (w->vehicle->GetNumOrders() <= 1) return;
DoCommandP(w->vehicle->tile, w->vehicle->index, _ctrl_pressed ? w->OrderGetSel() : ((w->vehicle->cur_order_index + 1) % w->vehicle->GetNumOrders()),
CMD_SKIP_TO_ORDER | CMD_MSG(_ctrl_pressed ? STR_CAN_T_SKIP_TO_ORDER : STR_CAN_T_SKIP_ORDER));
}
/**
* Handle the click on the delete button.
*
* @param w current window
*/
static void OrderClick_Delete(OrdersWindow *w, int i)
{
/* When networking, move one order lower */
int selected = w->selected_order + (int)_networking;
if (DoCommandP(w->vehicle->tile, w->vehicle->index, w->OrderGetSel(), CMD_DELETE_ORDER | CMD_MSG(STR_8834_CAN_T_DELETE_THIS_ORDER))) {
w->selected_order = selected >= w->vehicle->GetNumOrders() ? -1 : selected;
}
}
/**
* Handle the click on the refit button.
* If ctrl is pressed cancel refitting.
* Else show the refit window.
*
* @param w current window
*/
static void OrderClick_Refit(OrdersWindow *w, int i)
{
if (_ctrl_pressed) {
/* Cancel refitting */
DoCommandP(w->vehicle->tile, w->vehicle->index, (w->OrderGetSel() << 16) | (CT_NO_REFIT << 8) | CT_NO_REFIT, CMD_ORDER_REFIT);
} else {
ShowVehicleRefitWindow(w->vehicle, w->OrderGetSel(), w);
}
}
typedef void Handler(OrdersWindow*, int);
struct KeyToEvent {
uint16 keycode;
Handler *proc;
};
public:
OrdersWindow(const WindowDesc *desc, const Vehicle *v) : Window(desc, v->index)
{
this->owner = v->owner;
this->vscroll.cap = 6;
this->resize.step_height = 10;
this->selected_order = -1;
this->vehicle = v;
if (_settings_client.gui.quick_goto && v->owner == _local_company) {
/* If there are less than 2 station, make Go To active. */
int station_orders = 0;
const Order *order;
FOR_VEHICLE_ORDERS(v, order) {
if (order->IsType(OT_GOTO_STATION)) station_orders++;
}
if (station_orders < 2) OrderClick_Goto(this, 0);
}
if (_settings_game.order.timetabling) {
this->widget[ORDER_WIDGET_CAPTION].right -= 61;
} else {
this->HideWidget(ORDER_WIDGET_TIMETABLE_VIEW);
}
this->FindWindowPlacementAndResize(desc);
}
virtual void OnInvalidateData(int data)
{
switch (data) {
case 0:
/* Autoreplace replaced the vehicle */
this->vehicle = GetVehicle(this->window_number);
break;
case -1:
/* Removed / replaced all orders (after deleting / sharing) */
if (this->selected_order == -1) break;
this->DeleteChildWindows();
HideDropDownMenu(this);
this->selected_order = -1;
break;
default: {
/* Moving an order. If one of these is INVALID_VEH_ORDER_ID, then
* the order is being created / removed */
if (this->selected_order == -1) break;
VehicleOrderID from = GB(data, 0, 8);
VehicleOrderID to = GB(data, 8, 8);
if (from == to) break; // no need to change anything
if (from != this->selected_order) {
/* Moving from preceeding order? */
this->selected_order -= (int)(from <= this->selected_order);
/* Moving to preceeding order? */
this->selected_order += (int)(to <= this->selected_order);
break;
}
/* Now we are modifying the selected order */
if (to == INVALID_VEH_ORDER_ID) {
/* Deleting selected order */
this->DeleteChildWindows();
HideDropDownMenu(this);
this->selected_order = -1;
break;
}
/* Moving selected order */
this->selected_order = to;
} break;
}
}
virtual void OnPaint()
{
bool shared_orders = this->vehicle->IsOrderListShared();
SetVScrollCount(this, this->vehicle->GetNumOrders() + 1);
int sel = OrderGetSel();
const Order *order = GetVehicleOrder(this->vehicle, sel);
if (this->vehicle->owner == _local_company) {
/* Set the strings for the dropdown boxes. */
this->widget[ORDER_WIDGET_COND_VARIABLE].data = _order_conditional_variable[order == NULL ? 0 : order->GetConditionVariable()];
this->widget[ORDER_WIDGET_COND_COMPARATOR].data = _order_conditional_condition[order == NULL ? 0 : order->GetConditionComparator()];
/* skip */
this->SetWidgetDisabledState(ORDER_WIDGET_SKIP, this->vehicle->GetNumOrders() <= 1);
/* delete */
this->SetWidgetDisabledState(ORDER_WIDGET_DELETE,
(uint)this->vehicle->GetNumOrders() + ((shared_orders || this->vehicle->GetNumOrders() != 0) ? 1 : 0) <= (uint)this->selected_order);
/* non-stop only for trains */
this->SetWidgetDisabledState(ORDER_WIDGET_NON_STOP, (this->vehicle->type != VEH_TRAIN && this->vehicle->type != VEH_ROAD) || order == NULL);
this->SetWidgetDisabledState(ORDER_WIDGET_NON_STOP_DROPDOWN, this->IsWidgetDisabled(ORDER_WIDGET_NON_STOP));
this->SetWidgetDisabledState(ORDER_WIDGET_FULL_LOAD, order == NULL || (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) != 0); // full load
this->SetWidgetDisabledState(ORDER_WIDGET_FULL_LOAD_DROPDOWN, this->IsWidgetDisabled(ORDER_WIDGET_FULL_LOAD));
this->SetWidgetDisabledState(ORDER_WIDGET_UNLOAD, order == NULL || (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) != 0); // unload
this->SetWidgetDisabledState(ORDER_WIDGET_UNLOAD_DROPDOWN, this->IsWidgetDisabled(ORDER_WIDGET_UNLOAD));
/* Disable list of vehicles with the same shared orders if there is no list */
this->SetWidgetDisabledState(ORDER_WIDGET_SHARED_ORDER_LIST, !shared_orders);
this->SetWidgetDisabledState(ORDER_WIDGET_REFIT, order == NULL); // Refit
this->SetWidgetDisabledState(ORDER_WIDGET_SERVICE, order == NULL); // Service
this->SetWidgetDisabledState(ORDER_WIDGET_SERVICE_DROPDOWN, order == NULL); // Service
this->HideWidget(ORDER_WIDGET_REFIT); // Refit
this->HideWidget(ORDER_WIDGET_SERVICE); // Service
this->HideWidget(ORDER_WIDGET_SERVICE_DROPDOWN); // Service
this->HideWidget(ORDER_WIDGET_COND_VARIABLE);
this->HideWidget(ORDER_WIDGET_COND_COMPARATOR);
this->HideWidget(ORDER_WIDGET_COND_VALUE);
}
this->ShowWidget(ORDER_WIDGET_NON_STOP_DROPDOWN);
this->ShowWidget(ORDER_WIDGET_NON_STOP);
this->ShowWidget(ORDER_WIDGET_UNLOAD_DROPDOWN);
this->ShowWidget(ORDER_WIDGET_UNLOAD);
this->ShowWidget(ORDER_WIDGET_FULL_LOAD_DROPDOWN);
this->ShowWidget(ORDER_WIDGET_FULL_LOAD);
this->RaiseWidget(ORDER_WIDGET_NON_STOP);
this->RaiseWidget(ORDER_WIDGET_FULL_LOAD);
this->RaiseWidget(ORDER_WIDGET_UNLOAD);
this->RaiseWidget(ORDER_WIDGET_SERVICE);
if (order != NULL) {
this->SetWidgetLoweredState(ORDER_WIDGET_NON_STOP, order->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
switch (order->GetType()) {
case OT_GOTO_STATION:
if (!GetStation(order->GetDestination())->IsBuoy()) {
this->SetWidgetLoweredState(ORDER_WIDGET_FULL_LOAD, order->GetLoadType() == OLF_FULL_LOAD_ANY);
this->SetWidgetLoweredState(ORDER_WIDGET_UNLOAD, order->GetUnloadType() == OUFB_UNLOAD);
break;
}
/* Fall-through */
case OT_GOTO_WAYPOINT:
this->DisableWidget(ORDER_WIDGET_FULL_LOAD_DROPDOWN);
this->DisableWidget(ORDER_WIDGET_FULL_LOAD);
this->DisableWidget(ORDER_WIDGET_UNLOAD_DROPDOWN);
this->DisableWidget(ORDER_WIDGET_UNLOAD);
break;
case OT_GOTO_DEPOT:
/* Remove unload and replace it with refit */
this->HideWidget(ORDER_WIDGET_UNLOAD_DROPDOWN);
this->HideWidget(ORDER_WIDGET_UNLOAD);
this->HideWidget(ORDER_WIDGET_FULL_LOAD_DROPDOWN);
this->HideWidget(ORDER_WIDGET_FULL_LOAD);
this->ShowWidget(ORDER_WIDGET_REFIT);
this->ShowWidget(ORDER_WIDGET_SERVICE_DROPDOWN);
this->ShowWidget(ORDER_WIDGET_SERVICE);
this->SetWidgetLoweredState(ORDER_WIDGET_SERVICE, order->GetDepotOrderType() & ODTFB_SERVICE);
break;
case OT_CONDITIONAL: {
this->HideWidget(ORDER_WIDGET_NON_STOP_DROPDOWN);
this->HideWidget(ORDER_WIDGET_NON_STOP);
this->HideWidget(ORDER_WIDGET_UNLOAD);
this->HideWidget(ORDER_WIDGET_UNLOAD_DROPDOWN);
this->HideWidget(ORDER_WIDGET_FULL_LOAD);
this->HideWidget(ORDER_WIDGET_FULL_LOAD_DROPDOWN);
this->ShowWidget(ORDER_WIDGET_COND_VARIABLE);
this->ShowWidget(ORDER_WIDGET_COND_COMPARATOR);
this->ShowWidget(ORDER_WIDGET_COND_VALUE);
OrderConditionVariable ocv = order->GetConditionVariable();
this->SetWidgetDisabledState(ORDER_WIDGET_COND_COMPARATOR, ocv == OCV_UNCONDITIONALLY);
this->SetWidgetDisabledState(ORDER_WIDGET_COND_VALUE, ocv == OCV_REQUIRES_SERVICE || ocv == OCV_UNCONDITIONALLY);
uint value = order->GetConditionValue();
if (order->GetConditionVariable() == OCV_MAX_SPEED) value = ConvertSpeedToDisplaySpeed(value);
SetDParam(1, value);
} break;
default: // every other orders
this->DisableWidget(ORDER_WIDGET_NON_STOP_DROPDOWN);
this->DisableWidget(ORDER_WIDGET_NON_STOP);
this->DisableWidget(ORDER_WIDGET_FULL_LOAD_DROPDOWN);
this->DisableWidget(ORDER_WIDGET_FULL_LOAD);
this->DisableWidget(ORDER_WIDGET_UNLOAD_DROPDOWN);
this->DisableWidget(ORDER_WIDGET_UNLOAD);
}
}
SetDParam(0, this->vehicle->index);
this->DrawWidgets();
int y = 15;
int i = this->vscroll.pos;
order = GetVehicleOrder(this->vehicle, i);
StringID str;
while (order != NULL) {
/* Don't draw anything if it extends past the end of the window. */
if (i - this->vscroll.pos >= this->vscroll.cap) break;
DrawOrderString(this->vehicle, order, i, y, i == this->selected_order, false, this->widget[ORDER_WIDGET_ORDER_LIST].right - 4);
y += 10;
i++;
order = order->next;
}
if (i - this->vscroll.pos < this->vscroll.cap) {
str = shared_orders ? STR_END_OF_SHARED_ORDERS : STR_882A_END_OF_ORDERS;
DrawString(2, y, str, (i == this->selected_order) ? TC_WHITE : TC_BLACK);
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case ORDER_WIDGET_ORDER_LIST: {
ResetObjectToPlace();
int sel = this->GetOrderFromPt(pt.y);
if (_ctrl_pressed && sel < this->vehicle->GetNumOrders()) {
const Order *ord = GetVehicleOrder(this->vehicle, sel);
TileIndex xy = INVALID_TILE;
switch (ord->GetType()) {
case OT_GOTO_STATION: xy = GetStation(ord->GetDestination())->xy ; break;
case OT_GOTO_WAYPOINT: xy = GetWaypoint(ord->GetDestination())->xy; break;
case OT_GOTO_DEPOT:
if ((ord->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) break;
xy = (this->vehicle->type == VEH_AIRCRAFT) ? GetStation(ord->GetDestination())->xy : GetDepot(ord->GetDestination())->xy;
break;
default:
break;
}
if (xy != INVALID_TILE) ScrollMainWindowToTile(xy);
return;
}
/* This order won't be selected any more, close all child windows and dropdowns */
this->DeleteChildWindows();
HideDropDownMenu(this);
if (sel == INVALID_ORDER || sel == this->selected_order) {
/* Deselect clicked order */
this->selected_order = -1;
} else {
/* Select clicked order */
this->selected_order = sel;
if (this->vehicle->owner == _local_company) {
/* Activate drag and drop */
SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, VHM_DRAG, this);
}
}
this->SetDirty();
} break;
case ORDER_WIDGET_SKIP:
OrderClick_Skip(this, 0);
break;
case ORDER_WIDGET_DELETE:
OrderClick_Delete(this, 0);
break;
case ORDER_WIDGET_NON_STOP:
OrderClick_Nonstop(this, -1);
break;
case ORDER_WIDGET_NON_STOP_DROPDOWN: {
const Order *o = GetVehicleOrder(this->vehicle, this->OrderGetSel());
ShowDropDownMenu(this, _order_non_stop_drowdown, o->GetNonStopType(), ORDER_WIDGET_NON_STOP_DROPDOWN, 0, o->IsType(OT_GOTO_STATION) ? 0 : (o->IsType(OT_GOTO_WAYPOINT) ? 3 : 12));
} break;
case ORDER_WIDGET_GOTO:
OrderClick_Goto(this, 0);
break;
case ORDER_WIDGET_GOTO_DROPDOWN:
ShowDropDownMenu(this, this->vehicle->type == VEH_AIRCRAFT ? _order_goto_dropdown_aircraft : _order_goto_dropdown, 0, ORDER_WIDGET_GOTO_DROPDOWN, 0, 0);
break;
case ORDER_WIDGET_FULL_LOAD:
OrderClick_FullLoad(this, -1);
break;
case ORDER_WIDGET_FULL_LOAD_DROPDOWN:
ShowDropDownMenu(this, _order_full_load_drowdown, GetVehicleOrder(this->vehicle, this->OrderGetSel())->GetLoadType(), ORDER_WIDGET_FULL_LOAD_DROPDOWN, 0, 2);
break;
case ORDER_WIDGET_UNLOAD:
OrderClick_Unload(this, -1);
break;
case ORDER_WIDGET_UNLOAD_DROPDOWN:
ShowDropDownMenu(this, _order_unload_drowdown, GetVehicleOrder(this->vehicle, this->OrderGetSel())->GetUnloadType(), ORDER_WIDGET_UNLOAD_DROPDOWN, 0, 8);
break;
case ORDER_WIDGET_REFIT:
OrderClick_Refit(this, 0);
break;
case ORDER_WIDGET_SERVICE:
OrderClick_Service(this, -1);
break;
case ORDER_WIDGET_SERVICE_DROPDOWN:
ShowDropDownMenu(this, _order_depot_action_dropdown, DepotActionStringIndex(GetVehicleOrder(this->vehicle, this->OrderGetSel())), ORDER_WIDGET_SERVICE_DROPDOWN, 0, 0);
break;
case ORDER_WIDGET_TIMETABLE_VIEW:
ShowTimetableWindow(this->vehicle);
break;
case ORDER_WIDGET_COND_VARIABLE:
ShowDropDownMenu(this, _order_conditional_variable, GetVehicleOrder(this->vehicle, this->OrderGetSel())->GetConditionVariable(), ORDER_WIDGET_COND_VARIABLE, 0, 0);
break;
case ORDER_WIDGET_COND_COMPARATOR: {
const Order *o = GetVehicleOrder(this->vehicle, this->OrderGetSel());
ShowDropDownMenu(this, _order_conditional_condition, o->GetConditionComparator(), ORDER_WIDGET_COND_COMPARATOR, 0, (o->GetConditionVariable() == OCV_REQUIRES_SERVICE) ? 0x3F : 0xC0);
} break;
case ORDER_WIDGET_COND_VALUE: {
const Order *order = GetVehicleOrder(this->vehicle, this->OrderGetSel());
uint value = order->GetConditionValue();
if (order->GetConditionVariable() == OCV_MAX_SPEED) value = ConvertSpeedToDisplaySpeed(value);
SetDParam(0, value);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_ORDER_CONDITIONAL_VALUE_CAPT, 5, 100, this, CS_NUMERAL, QSF_NONE);
} break;
case ORDER_WIDGET_SHARED_ORDER_LIST:
ShowVehicleListWindow(this->vehicle);
break;
}
}
virtual void OnQueryTextFinished(char *str)
{
if (!StrEmpty(str)) {
VehicleOrderID sel = this->OrderGetSel();
uint value = atoi(str);
switch (GetVehicleOrder(this->vehicle, sel)->GetConditionVariable()) {
case OCV_MAX_SPEED:
value = ConvertDisplaySpeedToSpeed(value);
break;
case OCV_RELIABILITY:
case OCV_LOAD_PERCENTAGE:
value = Clamp(value, 0, 100);
default:
break;
}
DoCommandP(this->vehicle->tile, this->vehicle->index + (sel << 16), MOF_COND_VALUE | Clamp(value, 0, 2047) << 4, CMD_MODIFY_ORDER | CMD_MSG(STR_8835_CAN_T_MODIFY_THIS_ORDER));
}
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case ORDER_WIDGET_NON_STOP_DROPDOWN:
OrderClick_Nonstop(this, index);
break;
case ORDER_WIDGET_FULL_LOAD_DROPDOWN:
OrderClick_FullLoad(this, index);
break;
case ORDER_WIDGET_UNLOAD_DROPDOWN:
OrderClick_Unload(this, index);
break;
case ORDER_WIDGET_GOTO_DROPDOWN:
switch (index) {
case 0: OrderClick_Goto(this, 0); break;
case 1: OrderClick_NearestDepot(this, 0); break;
case 2: OrderClick_Conditional(this, 0); break;
default: NOT_REACHED();
}
break;
case ORDER_WIDGET_SERVICE_DROPDOWN:
OrderClick_Service(this, index);
break;
case ORDER_WIDGET_COND_VARIABLE:
DoCommandP(this->vehicle->tile, this->vehicle->index + (this->OrderGetSel() << 16), MOF_COND_VARIABLE | index << 4, CMD_MODIFY_ORDER | CMD_MSG(STR_8835_CAN_T_MODIFY_THIS_ORDER));
break;
case ORDER_WIDGET_COND_COMPARATOR:
DoCommandP(this->vehicle->tile, this->vehicle->index + (this->OrderGetSel() << 16), MOF_COND_COMPARATOR | index << 4, CMD_MODIFY_ORDER | CMD_MSG(STR_8835_CAN_T_MODIFY_THIS_ORDER));
break;
}
}
virtual void OnDragDrop(Point pt, int widget)
{
switch (widget) {
case ORDER_WIDGET_ORDER_LIST: {
int from_order = this->OrderGetSel();
int to_order = this->GetOrderFromPt(pt.y);
if (!(from_order == to_order || from_order == INVALID_ORDER || from_order > this->vehicle->GetNumOrders() || to_order == INVALID_ORDER || to_order > this->vehicle->GetNumOrders()) &&
DoCommandP(this->vehicle->tile, this->vehicle->index, from_order | (to_order << 16), CMD_MOVE_ORDER | CMD_MSG(STR_CAN_T_MOVE_THIS_ORDER))) {
this->selected_order = -1;
}
} break;
case ORDER_WIDGET_DELETE:
OrderClick_Delete(this, 0);
break;
}
ResetObjectToPlace();
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
static const KeyToEvent keytoevent[] = {
{'D', OrderClick_Skip},
{'F', OrderClick_Delete},
{'G', OrderClick_Goto},
{'H', OrderClick_Nonstop},
{'J', OrderClick_FullLoad},
{'K', OrderClick_Unload},
//('?', OrderClick_Service},
};
if (this->vehicle->owner != _local_company) return ES_NOT_HANDLED;
for (uint i = 0; i < lengthof(keytoevent); i++) {
if (keycode == keytoevent[i].keycode) {
keytoevent[i].proc(this, -1);
return ES_HANDLED;
}
}
return ES_NOT_HANDLED;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
if (this->goto_type == OPOS_GOTO) {
/* check if we're clicking on a vehicle first.. clone orders in that case. */
const Vehicle *v = CheckMouseOverVehicle();
if (v != NULL && this->HandleOrderVehClick(v)) return;
const Order cmd = GetOrderCmdFromTile(this->vehicle, tile);
if (!cmd.IsValid()) return;
if (DoCommandP(this->vehicle->tile, this->vehicle->index + (this->OrderGetSel() << 16), cmd.Pack(), CMD_INSERT_ORDER | CMD_MSG(STR_8833_CAN_T_INSERT_NEW_ORDER))) {
/* With quick goto the Go To button stays active */
if (!_settings_client.gui.quick_goto) ResetObjectToPlace();
}
}
}
virtual void OnPlaceObjectAbort()
{
if (this->goto_type == OPOS_CONDITIONAL) {
this->goto_type = OPOS_GOTO;
if (_cursor.pos.x >= (this->left + this->widget[ORDER_WIDGET_ORDER_LIST].left) &&
_cursor.pos.y >= (this->top + this->widget[ORDER_WIDGET_ORDER_LIST].top) &&
_cursor.pos.x <= (this->left + this->widget[ORDER_WIDGET_ORDER_LIST].right) &&
_cursor.pos.y <= (this->top + this->widget[ORDER_WIDGET_ORDER_LIST].bottom)) {
int order_id = this->GetOrderFromPt(_cursor.pos.y - this->top);
if (order_id != INVALID_ORDER) {
Order order;
order.next = NULL;
order.index = 0;
order.MakeConditional(order_id);
DoCommandP(this->vehicle->tile, this->vehicle->index + (this->OrderGetSel() << 16), order.Pack(), CMD_INSERT_ORDER | CMD_MSG(STR_8833_CAN_T_INSERT_NEW_ORDER));
}
}
}
this->RaiseWidget(ORDER_WIDGET_GOTO);
this->InvalidateWidget(ORDER_WIDGET_GOTO);
}
virtual void OnMouseLoop()
{
const Vehicle *v = _place_clicked_vehicle;
/*
* Check if we clicked on a vehicle
* and if the GOTO button of this window is pressed
* This is because of all open order windows WE_MOUSELOOP is called
* and if you have 3 windows open, and this check is not done
* the order is copied to the last open window instead of the
* one where GOTO is enabled
*/
if (v != NULL && this->IsWidgetLowered(ORDER_WIDGET_GOTO)) {
_place_clicked_vehicle = NULL;
this->HandleOrderVehClick(v);
}
}
virtual void OnResize(Point new_size, Point delta)
{
/* Update the scroll + matrix */
this->vscroll.cap = (this->widget[ORDER_WIDGET_ORDER_LIST].bottom - this->widget[ORDER_WIDGET_ORDER_LIST].top) / 10;
}
virtual void OnTimeout()
{
/* unclick all buttons except for the 'goto' button (ORDER_WIDGET_GOTO), which is 'persistent' */
for (uint i = 0; i < this->widget_count; i++) {
if (this->IsWidgetLowered(i) && i != ORDER_WIDGET_GOTO) {
this->RaiseWidget(i);
this->InvalidateWidget(i);
}
}
}
};
/**
* Widget definition for "your" train orders
*/
static const Widget _orders_train_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // ORDER_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 373, 0, 13, STR_8829_ORDERS, STR_018C_WINDOW_TITLE_DRAG_THIS}, // ORDER_WIDGET_CAPTION
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_GREY, 313, 373, 0, 13, STR_TIMETABLE_VIEW, STR_TIMETABLE_VIEW_TOOLTIP}, // ORDER_WIDGET_TIMETABLE_VIEW
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 374, 385, 0, 13, STR_NULL, STR_STICKY_BUTTON}, // ORDER_WIDGET_STICKY
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 373, 14, 75, 0x0, STR_8852_ORDERS_LIST_CLICK_ON_ORDER}, // ORDER_WIDGET_ORDER_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 374, 385, 14, 75, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // ORDER_WIDGET_SCROLLBAR
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 123, 88, 99, STR_8823_SKIP, STR_8853_SKIP_THE_CURRENT_ORDER}, // ORDER_WIDGET_SKIP
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 124, 247, 88, 99, STR_8824_DELETE, STR_8854_DELETE_THE_HIGHLIGHTED}, // ORDER_WIDGET_DELETE
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 0, 123, 76, 87, STR_NULL, STR_ORDER_TOOLTIP_NON_STOP}, // ORDER_WIDGET_NON_STOP_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 0, 111, 76, 87, STR_ORDER_NON_STOP, STR_ORDER_TOOLTIP_NON_STOP}, // ORDER_WIDGET_NON_STOP
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 248, 371, 88, 99, STR_EMPTY, STR_ORDER_GO_TO_DROPDOWN_TOOLTIP}, // ORDER_WIDGET_GOTO_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 248, 359, 88, 99, STR_8826_GO_TO, STR_8856_INSERT_A_NEW_ORDER_BEFORE}, // ORDER_WIDGET_GOTO
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 124, 247, 76, 87, STR_NULL, STR_ORDER_TOOLTIP_FULL_LOAD}, // ORDER_WIDGET_FULL_LOAD_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 124, 235, 76, 87, STR_ORDER_TOGGLE_FULL_LOAD, STR_ORDER_TOOLTIP_FULL_LOAD}, // ORDER_WIDGET_FULL_LOAD
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 248, 371, 76, 87, STR_NULL, STR_ORDER_TOOLTIP_UNLOAD}, // ORDER_WIDGET_UNLOAD_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 248, 359, 76, 87, STR_ORDER_TOGGLE_UNLOAD, STR_ORDER_TOOLTIP_UNLOAD}, // ORDER_WIDGET_UNLOAD
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 124, 247, 76, 87, STR_REFIT, STR_REFIT_TIP}, // ORDER_WIDGET_REFIT
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 248, 371, 76, 87, STR_NULL, STR_SERVICE_HINT}, // ORDER_WIDGET_SERVICE_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 248, 359, 76, 87, STR_SERVICE, STR_SERVICE_HINT}, // ORDER_WIDGET_SERVICE
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 0, 123, 76, 87, STR_NULL, STR_ORDER_CONDITIONAL_VARIABLE_TOOLTIP}, // ORDER_WIDGET_COND_VARIABLE
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 124, 247, 76, 87, STR_NULL, STR_ORDER_CONDITIONAL_COMPARATOR_TOOLTIP}, // ORDER_WIDGET_COND_COMPARATOR
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 248, 371, 76, 87, STR_CONDITIONAL_VALUE, STR_ORDER_CONDITIONAL_VALUE_TOOLTIP}, // ORDER_WIDGET_COND_VALUE
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 372, 373, 76, 99, 0x0, STR_NULL}, // ORDER_WIDGET_RESIZE_BAR
{ WWT_PUSHIMGBTN, RESIZE_LRTB, COLOUR_GREY, 372, 385, 76, 87, SPR_SHARED_ORDERS_ICON, STR_VEH_WITH_SHARED_ORDERS_LIST_TIP}, // ORDER_WIDGET_SHARED_ORDER_LIST
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 374, 385, 88, 99, 0x0, STR_RESIZE_BUTTON}, // ORDER_WIDGET_RESIZE
{ WIDGETS_END},
};
static const WindowDesc _orders_train_desc(
WDP_AUTO, WDP_AUTO, 386, 100, 386, 100,
WC_VEHICLE_ORDERS, WC_VEHICLE_VIEW,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_orders_train_widgets
);
/**
* Widget definition for "your" orders (!train)
*/
static const Widget _orders_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // ORDER_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 373, 0, 13, STR_8829_ORDERS, STR_018C_WINDOW_TITLE_DRAG_THIS}, // ORDER_WIDGET_CAPTION
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_GREY, 313, 373, 0, 13, STR_TIMETABLE_VIEW, STR_TIMETABLE_VIEW_TOOLTIP}, // ORDER_WIDGET_TIMETABLE_VIEW
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 374, 385, 0, 13, STR_NULL, STR_STICKY_BUTTON}, // ORDER_WIDGET_STICKY
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 373, 14, 75, 0x0, STR_8852_ORDERS_LIST_CLICK_ON_ORDER}, // ORDER_WIDGET_ORDER_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 374, 385, 14, 75, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // ORDER_WIDGET_SCROLLBAR
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 123, 88, 99, STR_8823_SKIP, STR_8853_SKIP_THE_CURRENT_ORDER}, // ORDER_WIDGET_SKIP
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 124, 247, 88, 99, STR_8824_DELETE, STR_8854_DELETE_THE_HIGHLIGHTED}, // ORDER_WIDGET_DELETE
{ WWT_EMPTY, RESIZE_TB, COLOUR_GREY, 0, 0, 76, 87, 0x0, 0x0}, // ORDER_WIDGET_NON_STOP_DROPDOWN
{ WWT_EMPTY, RESIZE_TB, COLOUR_GREY, 0, 0, 76, 87, 0x0, 0x0}, // ORDER_WIDGET_NON_STOP
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 248, 371, 88, 99, STR_EMPTY, STR_ORDER_GO_TO_DROPDOWN_TOOLTIP}, // ORDER_WIDGET_GOTO_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 248, 359, 88, 99, STR_8826_GO_TO, STR_8856_INSERT_A_NEW_ORDER_BEFORE}, // ORDER_WIDGET_GOTO
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 0, 185, 76, 87, STR_NULL, STR_ORDER_TOOLTIP_FULL_LOAD}, // ORDER_WIDGET_FULL_LOAD_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 0, 173, 76, 87, STR_ORDER_TOGGLE_FULL_LOAD, STR_ORDER_TOOLTIP_FULL_LOAD}, // ORDER_WIDGET_FULL_LOAD
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 186, 371, 76, 87, STR_NULL, STR_ORDER_TOOLTIP_UNLOAD}, // ORDER_WIDGET_UNLOAD_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 186, 359, 76, 87, STR_ORDER_TOGGLE_UNLOAD, STR_ORDER_TOOLTIP_UNLOAD}, // ORDER_WIDGET_UNLOAD
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 185, 76, 87, STR_REFIT, STR_REFIT_TIP}, // ORDER_WIDGET_REFIT
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 186, 371, 76, 87, STR_NULL, STR_SERVICE_HINT}, // ORDER_WIDGET_SERVICE_DROPDOWN
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_GREY, 186, 359, 76, 87, STR_SERVICE, STR_SERVICE_HINT}, // ORDER_WIDGET_SERVICE
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 0, 123, 76, 87, STR_NULL, STR_ORDER_CONDITIONAL_VARIABLE_TOOLTIP}, // ORDER_WIDGET_COND_VARIABLE
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 124, 247, 76, 87, STR_NULL, STR_ORDER_CONDITIONAL_COMPARATOR_TOOLTIP}, // ORDER_WIDGET_COND_COMPARATOR
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 248, 371, 76, 87, STR_CONDITIONAL_VALUE, STR_ORDER_CONDITIONAL_VALUE_TOOLTIP}, // ORDER_WIDGET_COND_VALUE
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 372, 373, 76, 99, 0x0, STR_NULL}, // ORDER_WIDGET_RESIZE_BAR
{ WWT_PUSHIMGBTN, RESIZE_LRTB, COLOUR_GREY, 372, 385, 76, 87, SPR_SHARED_ORDERS_ICON, STR_VEH_WITH_SHARED_ORDERS_LIST_TIP}, // ORDER_WIDGET_SHARED_ORDER_LIST
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 374, 385, 88, 99, 0x0, STR_RESIZE_BUTTON}, // ORDER_WIDGET_RESIZE
{ WIDGETS_END},
};
static const WindowDesc _orders_desc(
WDP_AUTO, WDP_AUTO, 386, 100, 386, 100,
WC_VEHICLE_ORDERS, WC_VEHICLE_VIEW,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_orders_widgets
);
/**
* Widget definition for competitor orders
*/
static const Widget _other_orders_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // ORDER_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 373, 0, 13, STR_8829_ORDERS, STR_018C_WINDOW_TITLE_DRAG_THIS}, // ORDER_WIDGET_CAPTION
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_GREY, 313, 373, 0, 13, STR_TIMETABLE_VIEW, STR_TIMETABLE_VIEW_TOOLTIP}, // ORDER_WIDGET_TIMETABLE_VIEW
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 374, 385, 0, 13, STR_NULL, STR_STICKY_BUTTON}, // ORDER_WIDGET_STICKY
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 373, 14, 75, 0x0, STR_8852_ORDERS_LIST_CLICK_ON_ORDER}, // ORDER_WIDGET_ORDER_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 374, 385, 14, 75, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // ORDER_WIDGET_SCROLLBAR
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_SKIP
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_DELETE
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_NON_STOP_DROPDOWN
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_NON_STOP
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_GOTO_DROPDOWN
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_GOTO
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_FULL_LOAD_DROPDOWN
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_FULL_LOAD
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_UNLOAD_DROPDOWN
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_UNLOAD
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_REFIT
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_SERVICE_DROPDOWN
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_SERVICE
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_COND_VARIABLE
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_COND_COMPARATOR
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_COND_VALUE
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 0, 373, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_RESIZE_BAR
{ WWT_EMPTY, RESIZE_TB, COLOUR_GREY, 0, 0, 76, 87, 0x0, STR_NULL}, // ORDER_WIDGET_SHARED_ORDER_LIST
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 374, 385, 76, 87, 0x0, STR_RESIZE_BUTTON}, // ORDER_WIDGET_RESIZE
{ WIDGETS_END},
};
static const WindowDesc _other_orders_desc(
WDP_AUTO, WDP_AUTO, 386, 88, 386, 88,
WC_VEHICLE_ORDERS, WC_VEHICLE_VIEW,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE | WDF_CONSTRUCTION,
_other_orders_widgets
);
void ShowOrdersWindow(const Vehicle *v)
{
DeleteWindowById(WC_VEHICLE_DETAILS, v->index, false);
DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
if (BringWindowToFrontById(WC_VEHICLE_ORDERS, v->index) != NULL) return;
if (v->owner != _local_company) {
new OrdersWindow(&_other_orders_desc, v);
} else {
new OrdersWindow((v->type == VEH_TRAIN || v->type == VEH_ROAD) ? &_orders_train_desc : &_orders_desc, v);
}
}
| 51,304
|
C++
|
.cpp
| 1,099
| 43.102821
| 186
| 0.652343
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,074
|
station_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/station_gui.cpp
|
/* $Id$ */
/** @file station_gui.cpp The GUI for stations. */
#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "company_func.h"
#include "command_func.h"
#include "vehicle_gui.h"
#include "cargotype.h"
#include "station_gui.h"
#include "strings_func.h"
#include "window_func.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "widgets/dropdown_func.h"
#include "newgrf_cargo.h"
#include "station_map.h"
#include "tilehighlight_func.h"
#include "core/smallmap_type.hpp"
#include "company_base.h"
#include "sortlist_type.h"
#include "settings_type.h"
#include "table/strings.h"
#include "table/sprites.h"
/**
* Draw small boxes of cargo amount and ratings data at the given
* coordinates. If amount exceeds 576 units, it is shown 'full', same
* goes for the rating: at above 90% orso (224) it is also 'full'
*
* @param x coordinate to draw the box at
* @param y coordinate to draw the box at
* @param type Cargo type
* @param amount Cargo amount
* @param rating ratings data for that particular cargo
*
* @note Each cargo-bar is 16 pixels wide and 6 pixels high
* @note Each rating 14 pixels wide and 1 pixel high and is 1 pixel below the cargo-bar
*/
static void StationsWndShowStationRating(int x, int y, CargoID type, uint amount, byte rating)
{
static const uint units_full = 576; ///< number of units to show station as 'full'
static const uint rating_full = 224; ///< rating needed so it is shown as 'full'
const CargoSpec *cs = GetCargo(type);
if (!cs->IsValid()) return;
int colour = cs->rating_colour;
uint w = (minu(amount, units_full) + 5) / 36;
/* Draw total cargo (limited) on station (fits into 16 pixels) */
if (w != 0) GfxFillRect(x, y, x + w - 1, y + 6, colour);
/* Draw a one pixel-wide bar of additional cargo meter, useful
* for stations with only a small amount (<=30) */
if (w == 0) {
uint rest = amount / 5;
if (rest != 0) {
w += x;
GfxFillRect(w, y + 6 - rest, w, y + 6, colour);
}
}
DrawString(x + 1, y, cs->abbrev, TC_BLACK);
/* Draw green/red ratings bar (fits into 14 pixels) */
y += 8;
GfxFillRect(x + 1, y, x + 14, y, 0xB8);
rating = minu(rating, rating_full) / 16;
if (rating != 0) GfxFillRect(x + 1, y, x + rating, y, 0xD0);
}
typedef GUIList<const Station*> GUIStationList;
/**
* The list of stations per company.
*/
class CompanyStationsWindow : public Window
{
/** Enum for CompanyStations, referring to _company_stations_widgets */
enum StationListWidgets {
SLW_CLOSEBOX = 0, ///< Close window button
SLW_CAPTION, ///< Window caption
SLW_STICKY, ///< Sticky button
SLW_LIST, ///< The main panel, list of stations
SLW_SCROLLBAR, ///< Scrollbar next to the main panel
SLW_RESIZE, ///< Resize button
SLW_TRAIN, ///< 'TRAIN' button - list only facilities where is a railroad station
SLW_TRUCK, ///< 'TRUCK' button - list only facilities where is a truck stop
SLW_BUS, ///< 'BUS' button - list only facilities where is a bus stop
SLW_AIRPLANE, ///< 'AIRPLANE' button - list only facilities where is an airport
SLW_SHIP, ///< 'SHIP' button - list only facilities where is a dock
SLW_FACILALL, ///< 'ALL' button - list all facilities
SLW_PAN_BETWEEN, ///< Small panel between list of types of ficilities and list of cargo types
SLW_NOCARGOWAITING, ///< 'NO' button - list stations where no cargo is waiting
SLW_CARGOALL, ///< 'ALL' button - list all stations
SLW_PAN_RIGHT, ///< Panel right of list of cargo types
SLW_SORTBY, ///< 'Sort by' button - reverse sort direction
SLW_SORTDROPBTN, ///< Dropdown button
SLW_PAN_SORT_RIGHT, ///< Panel right of sorting options
SLW_CARGOSTART, ///< Widget numbers used for list of cargo types (not present in _company_stations_widgets)
};
protected:
/* Runtime saved values */
static Listing last_sorting;
static byte facilities; // types of stations of interest
static bool include_empty; // whether we should include stations without waiting cargo
static const uint32 cargo_filter_max;
static uint32 cargo_filter; // bitmap of cargo types to include
static const Station *last_station;
/* Constants for sorting stations */
static const StringID sorter_names[];
static GUIStationList::SortFunction * const sorter_funcs[];
GUIStationList stations;
/**
* (Re)Build station list
*
* @param owner company whose stations are to be in list
*/
void BuildStationsList(const Owner owner)
{
if (!this->stations.NeedRebuild()) return;
DEBUG(misc, 3, "Building station list for company %d", owner);
this->stations.Clear();
const Station *st;
FOR_ALL_STATIONS(st) {
if (st->owner == owner || (st->owner == OWNER_NONE && !st->IsBuoy() && HasStationInUse(st->index, owner))) {
if (this->facilities & st->facilities) { // only stations with selected facilities
int num_waiting_cargo = 0;
for (CargoID j = 0; j < NUM_CARGO; j++) {
if (!st->goods[j].cargo.Empty()) {
num_waiting_cargo++; // count number of waiting cargo
if (HasBit(this->cargo_filter, j)) {
*this->stations.Append() = st;
break;
}
}
}
/* stations without waiting cargo */
if (num_waiting_cargo == 0 && this->include_empty) {
*this->stations.Append() = st;
}
}
}
}
this->stations.Compact();
this->stations.RebuildDone();
}
/** Sort stations by their name */
static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
{
static char buf_cache[64];
char buf[64];
SetDParam(0, (*a)->index);
GetString(buf, STR_STATION, lastof(buf));
if (*b != last_station) {
last_station = *b;
SetDParam(0, (*b)->index);
GetString(buf_cache, STR_STATION, lastof(buf_cache));
}
return strcmp(buf, buf_cache);
}
/** Sort stations by their type */
static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
{
return (*a)->facilities - (*b)->facilities;
}
/** Sort stations by their waiting cargo */
static int CDECL StationWaitingSorter(const Station * const *a, const Station * const *b)
{
Money diff = 0;
for (CargoID j = 0; j < NUM_CARGO; j++) {
if (!HasBit(cargo_filter, j)) continue;
if (!(*a)->goods[j].cargo.Empty()) diff += GetTransportedGoodsIncome((*a)->goods[j].cargo.Count(), 20, 50, j);
if (!(*b)->goods[j].cargo.Empty()) diff -= GetTransportedGoodsIncome((*b)->goods[j].cargo.Count(), 20, 50, j);
}
return ClampToI32(diff);
}
/** Sort stations by their rating */
static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
{
byte maxr1 = 0;
byte maxr2 = 0;
for (CargoID j = 0; j < NUM_CARGO; j++) {
if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) maxr1 = max(maxr1, (*a)->goods[j].rating);
if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) maxr2 = max(maxr2, (*b)->goods[j].rating);
}
return maxr1 - maxr2;
}
/** Sort the stations list */
void SortStationsList()
{
if (!this->stations.Sort()) return;
/* Reset name sorter sort cache */
this->last_station = NULL;
/* Set the modified widget dirty */
this->InvalidateWidget(SLW_LIST);
}
public:
CompanyStationsWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->owner = (Owner)this->window_number;
this->vscroll.cap = 12;
this->resize.step_height = 10;
this->resize.height = this->height - 10 * 7; // minimum if 5 in the list
/* Add cargo filter buttons */
uint num_active = 0;
for (CargoID c = 0; c < NUM_CARGO; c++) {
if (GetCargo(c)->IsValid()) num_active++;
}
this->widget_count += num_active;
this->widget = ReallocT(this->widget, this->widget_count + 1);
this->widget[this->widget_count].type = WWT_LAST;
uint i = 0;
for (CargoID c = 0; c < NUM_CARGO; c++) {
if (!GetCargo(c)->IsValid()) continue;
Widget *wi = &this->widget[SLW_CARGOSTART + i];
wi->type = WWT_PANEL;
wi->display_flags = RESIZE_NONE;
wi->colour = COLOUR_GREY;
wi->left = 89 + i * 14;
wi->right = wi->left + 13;
wi->top = 14;
wi->bottom = 24;
wi->data = 0;
wi->tooltips = STR_USE_CTRL_TO_SELECT_MORE;
if (HasBit(this->cargo_filter, c)) this->LowerWidget(SLW_CARGOSTART + i);
i++;
}
this->widget[SLW_NOCARGOWAITING].left += num_active * 14;
this->widget[SLW_NOCARGOWAITING].right += num_active * 14;
this->widget[SLW_CARGOALL].left += num_active * 14;
this->widget[SLW_CARGOALL].right += num_active * 14;
this->widget[SLW_PAN_RIGHT].left += num_active * 14;
if (num_active > 15) {
/* Resize and fix the minimum width, if necessary */
ResizeWindow(this, (num_active - 15) * 14, 0);
this->resize.width = this->width;
}
if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
for (uint i = 0; i < 5; i++) {
if (HasBit(this->facilities, i)) this->LowerWidget(i + SLW_TRAIN);
}
this->SetWidgetLoweredState(SLW_FACILALL, this->facilities == (FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK));
this->SetWidgetLoweredState(SLW_CARGOALL, this->cargo_filter == _cargo_mask && this->include_empty);
this->SetWidgetLoweredState(SLW_NOCARGOWAITING, this->include_empty);
this->stations.SetListing(this->last_sorting);
this->stations.SetSortFuncs(this->sorter_funcs);
this->stations.ForceRebuild();
this->stations.NeedResort();
this->SortStationsList();
this->widget[SLW_SORTDROPBTN].data = this->sorter_names[this->stations.SortType()];
this->FindWindowPlacementAndResize(desc);
}
~CompanyStationsWindow()
{
this->last_sorting = this->stations.GetListing();
}
virtual void OnPaint()
{
const Owner owner = (Owner)this->window_number;
this->BuildStationsList(owner);
this->SortStationsList();
SetVScrollCount(this, this->stations.Length());
/* draw widgets, with company's name in the caption */
SetDParam(0, owner);
SetDParam(1, this->vscroll.count);
this->DrawWidgets();
/* draw arrow pointing up/down for ascending/descending sorting */
this->DrawSortButtonState(SLW_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
int cg_ofst;
int x = 89;
int y = 14;
int xb = 2; ///< offset from left of widget
uint i = 0;
for (CargoID c = 0; c < NUM_CARGO; c++) {
const CargoSpec *cs = GetCargo(c);
if (!cs->IsValid()) continue;
cg_ofst = HasBit(this->cargo_filter, c) ? 2 : 1;
GfxFillRect(x + cg_ofst, y + cg_ofst, x + cg_ofst + 10 , y + cg_ofst + 7, cs->rating_colour);
DrawStringCentered(x + 6 + cg_ofst, y + cg_ofst, cs->abbrev, TC_BLACK);
x += 14;
i++;
}
x += 6;
cg_ofst = this->IsWidgetLowered(SLW_NOCARGOWAITING) ? 2 : 1;
DrawStringCentered(x + cg_ofst, y + cg_ofst, STR_ABBREV_NONE, TC_BLACK);
x += 14;
cg_ofst = this->IsWidgetLowered(SLW_CARGOALL) ? 2 : 1;
DrawStringCentered(x + cg_ofst, y + cg_ofst, STR_ABBREV_ALL, TC_BLACK);
cg_ofst = this->IsWidgetLowered(SLW_FACILALL) ? 2 : 1;
DrawString(71 + cg_ofst, y + cg_ofst, STR_ABBREV_ALL, TC_BLACK);
if (this->vscroll.count == 0) { // company has no stations
DrawString(xb, 40, STR_304A_NONE, TC_FROMSTRING);
return;
}
int max = min(this->vscroll.pos + this->vscroll.cap, this->stations.Length());
y = 40; // start of the list-widget
for (int i = this->vscroll.pos; i < max; ++i) { // do until max number of stations of owner
const Station *st = this->stations[i];
int x;
assert(st->xy != INVALID_TILE);
/* Do not do the complex check HasStationInUse here, it may be even false
* when the order had been removed and the station list hasn't been removed yet */
assert(st->owner == owner || (st->owner == OWNER_NONE && !st->IsBuoy()));
SetDParam(0, st->index);
SetDParam(1, st->facilities);
x = DrawString(xb, y, STR_3049_0, TC_FROMSTRING) + 5;
/* show cargo waiting and station ratings */
for (CargoID j = 0; j < NUM_CARGO; j++) {
if (!st->goods[j].cargo.Empty()) {
StationsWndShowStationRating(x, y, j, st->goods[j].cargo.Count(), st->goods[j].rating);
x += 20;
}
}
y += 10;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case SLW_LIST: {
uint32 id_v = (pt.y - 41) / 10;
if (id_v >= this->vscroll.cap) return; // click out of bounds
id_v += this->vscroll.pos;
if (id_v >= this->stations.Length()) return; // click out of list bound
const Station *st = this->stations[id_v];
/* do not check HasStationInUse - it is slow and may be invalid */
assert(st->owner == (Owner)this->window_number || (st->owner == OWNER_NONE && !st->IsBuoy()));
if (_ctrl_pressed) {
ShowExtraViewPortWindow(st->xy);
} else {
ScrollMainWindowToTile(st->xy);
}
break;
}
case SLW_TRAIN:
case SLW_TRUCK:
case SLW_BUS:
case SLW_AIRPLANE:
case SLW_SHIP:
if (_ctrl_pressed) {
ToggleBit(this->facilities, widget - SLW_TRAIN);
this->ToggleWidgetLoweredState(widget);
} else {
uint i;
FOR_EACH_SET_BIT(i, this->facilities) {
this->RaiseWidget(i + SLW_TRAIN);
}
SetBit(this->facilities, widget - SLW_TRAIN);
this->LowerWidget(widget);
}
this->SetWidgetLoweredState(SLW_FACILALL, this->facilities == (FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK));
this->stations.ForceRebuild();
this->SetDirty();
break;
case SLW_FACILALL:
for (uint i = 0; i < 5; i++) {
this->LowerWidget(i + SLW_TRAIN);
}
this->LowerWidget(SLW_FACILALL);
this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
this->stations.ForceRebuild();
this->SetDirty();
break;
case SLW_CARGOALL: {
uint i = 0;
for (CargoID c = 0; c < NUM_CARGO; c++) {
if (!GetCargo(c)->IsValid()) continue;
this->LowerWidget(i + SLW_CARGOSTART);
i++;
}
this->LowerWidget(SLW_NOCARGOWAITING);
this->LowerWidget(SLW_CARGOALL);
this->cargo_filter = _cargo_mask;
this->include_empty = true;
this->stations.ForceRebuild();
this->SetDirty();
break;
}
case SLW_SORTBY: // flip sorting method asc/desc
this->stations.ToggleSortOrder();
this->flags4 |= WF_TIMEOUT_BEGIN;
this->LowerWidget(SLW_SORTBY);
this->SetDirty();
break;
case SLW_SORTDROPBTN: // select sorting criteria dropdown menu
ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), SLW_SORTDROPBTN, 0, 0);
break;
case SLW_NOCARGOWAITING:
if (_ctrl_pressed) {
this->include_empty = !this->include_empty;
this->ToggleWidgetLoweredState(SLW_NOCARGOWAITING);
} else {
for (uint i = SLW_CARGOSTART; i < this->widget_count; i++) {
this->RaiseWidget(i);
}
this->cargo_filter = 0;
this->include_empty = true;
this->LowerWidget(SLW_NOCARGOWAITING);
}
this->SetWidgetLoweredState(SLW_CARGOALL, this->cargo_filter == _cargo_mask && this->include_empty);
this->stations.ForceRebuild();
this->SetDirty();
break;
default:
if (widget >= SLW_CARGOSTART) { // change cargo_filter
/* Determine the selected cargo type */
CargoID c;
int i = 0;
for (c = 0; c < NUM_CARGO; c++) {
if (!GetCargo(c)->IsValid()) continue;
if (widget - SLW_CARGOSTART == i) break;
i++;
}
if (_ctrl_pressed) {
ToggleBit(this->cargo_filter, c);
this->ToggleWidgetLoweredState(widget);
} else {
for (uint i = SLW_CARGOSTART; i < this->widget_count; i++) {
this->RaiseWidget(i);
}
this->RaiseWidget(SLW_NOCARGOWAITING);
this->cargo_filter = 0;
this->include_empty = false;
SetBit(this->cargo_filter, c);
this->LowerWidget(widget);
}
this->SetWidgetLoweredState(SLW_CARGOALL, this->cargo_filter == _cargo_mask && this->include_empty);
this->stations.ForceRebuild();
this->SetDirty();
}
break;
}
}
virtual void OnDropdownSelect(int widget, int index)
{
if (this->stations.SortType() != index) {
this->stations.SetSortType(index);
/* Display the current sort variant */
this->widget[SLW_SORTDROPBTN].data = this->sorter_names[this->stations.SortType()];
this->SetDirty();
}
}
virtual void OnTick()
{
if (_pause_game != 0) return;
if (this->stations.NeedResort()) {
DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
this->SetDirty();
}
}
virtual void OnTimeout()
{
this->RaiseWidget(SLW_SORTBY);
this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / 10;
}
virtual void OnInvalidateData(int data)
{
if (data == 0) {
this->stations.ForceRebuild();
} else {
this->stations.ForceResort();
}
}
};
Listing CompanyStationsWindow::last_sorting = {false, 0};
byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
bool CompanyStationsWindow::include_empty = true;
const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
const Station *CompanyStationsWindow::last_station = NULL;
/* Availible station sorting functions */
GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
&StationNameSorter,
&StationTypeSorter,
&StationWaitingSorter,
&StationRatingMaxSorter
};
/* Names of the sorting functions */
const StringID CompanyStationsWindow::sorter_names[] = {
STR_SORT_BY_DROPDOWN_NAME,
STR_SORT_BY_FACILITY,
STR_SORT_BY_WAITING,
STR_SORT_BY_RATING_MAX,
INVALID_STRING_ID
};
static const Widget _company_stations_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // SLW_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 345, 0, 13, STR_3048_STATIONS, STR_018C_WINDOW_TITLE_DRAG_THIS}, // SLW_CAPTION
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 346, 357, 0, 13, 0x0, STR_STICKY_BUTTON}, // SLW_STICKY
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 345, 37, 161, 0x0, STR_3057_STATION_NAMES_CLICK_ON}, // SLW_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 346, 357, 37, 149, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // SLW_SCROLLBAR
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 346, 357, 150, 161, 0x0, STR_RESIZE_BUTTON}, // SLW_RESIZE
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 13, 14, 24, STR_TRAIN, STR_USE_CTRL_TO_SELECT_MORE}, // SLW_TRAIN
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 14, 27, 14, 24, STR_LORRY, STR_USE_CTRL_TO_SELECT_MORE}, // SLW_TRUCK
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 28, 41, 14, 24, STR_BUS, STR_USE_CTRL_TO_SELECT_MORE}, // SLW_BUS
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 42, 55, 14, 24, STR_PLANE, STR_USE_CTRL_TO_SELECT_MORE}, // SLW_AIRPLANE
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 56, 69, 14, 24, STR_SHIP, STR_USE_CTRL_TO_SELECT_MORE}, // SLW_SHIP
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 70, 83, 14, 24, 0x0, STR_SELECT_ALL_FACILITIES}, // SLW_FACILALL
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 83, 88, 14, 24, 0x0, STR_NULL}, // SLW_PAN_BETWEEN
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 89, 102, 14, 24, 0x0, STR_NO_WAITING_CARGO}, // SLW_NOCARGOWAITING
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 103, 116, 14, 24, 0x0, STR_SELECT_ALL_TYPES}, // SLW_CARGOALL
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 117, 357, 14, 24, 0x0, STR_NULL}, // SLW_PAN_RIGHT
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 80, 25, 36, STR_SORT_BY, STR_SORT_ORDER_TIP}, // SLW_SORTBY
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_GREY, 81, 243, 25, 36, 0x0, STR_SORT_CRITERIA_TIP}, // SLW_SORTDROPBTN
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 244, 357, 25, 36, 0x0, STR_NULL}, // SLW_PAN_SORT_RIGHT
{ WIDGETS_END},
};
static const WindowDesc _company_stations_desc(
WDP_AUTO, WDP_AUTO, 358, 162, 358, 162,
WC_STATION_LIST, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_company_stations_widgets
);
/**
* Opens window with list of company's stations
*
* @param company whose stations' list show
*/
void ShowCompanyStations(CompanyID company)
{
if (!IsValidCompanyID(company)) return;
AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
}
static const Widget _station_view_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // SVW_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 236, 0, 13, STR_300A_0, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 237, 248, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 236, 14, 65, 0x0, STR_NULL}, // SVW_WAITING
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 237, 248, 14, 65, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 0, 248, 66, 97, 0x0, STR_NULL}, // SVW_ACCEPTLIST / SVW_RATINGLIST
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 59, 98, 109, STR_00E4_LOCATION, STR_3053_CENTER_MAIN_VIEW_ON_STATION}, // SVW_LOCATION
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 60, 120, 98, 109, STR_3032_RATINGS, STR_3054_SHOW_STATION_RATINGS}, // SVW_RATINGS / SVW_ACCEPTS
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_GREY, 121, 180, 98, 109, STR_0130_RENAME, STR_3055_CHANGE_NAME_OF_STATION}, // SVW_RENAME
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_GREY, 181, 194, 98, 109, STR_TRAIN, STR_SCHEDULED_TRAINS_TIP }, // SVW_TRAINS
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_GREY, 195, 208, 98, 109, STR_LORRY, STR_SCHEDULED_ROAD_VEHICLES_TIP }, // SVW_ROADVEHS
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_GREY, 209, 222, 98, 109, STR_PLANE, STR_SCHEDULED_AIRCRAFT_TIP }, // SVW_PLANES
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_GREY, 223, 236, 98, 109, STR_SHIP, STR_SCHEDULED_SHIPS_TIP }, // SVW_SHIPS
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 237, 248, 98, 109, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
SpriteID GetCargoSprite(CargoID i)
{
const CargoSpec *cs = GetCargo(i);
SpriteID sprite;
if (cs->sprite == 0xFFFF) {
/* A value of 0xFFFF indicates we should draw a custom icon */
sprite = GetCustomCargoSprite(cs);
} else {
sprite = cs->sprite;
}
if (sprite == 0) sprite = SPR_CARGO_GOODS;
return sprite;
}
/**
* Draws icons of waiting cargo in the StationView window
*
* @param i type of cargo
* @param waiting number of waiting units
* @param x x on-screen coordinate where to start with drawing icons
* @param y y coordinate
*/
static void DrawCargoIcons(CargoID i, uint waiting, int x, int y, uint width)
{
uint num = min((waiting + 5) / 10, width / 10); // maximum is width / 10 icons so it won't overflow
if (num == 0) return;
SpriteID sprite = GetCargoSprite(i);
do {
DrawSprite(sprite, PAL_NONE, x, y);
x += 10;
} while (--num);
}
struct CargoData {
CargoID cargo;
StationID source;
uint count;
CargoData(CargoID cargo, StationID source, uint count) :
cargo(cargo),
source(source),
count(count)
{ }
};
typedef std::list<CargoData> CargoDataList;
/**
* The StationView window
*/
struct StationViewWindow : public Window {
uint32 cargo; ///< Bitmask of cargo types to expand
uint16 cargo_rows[NUM_CARGO]; ///< Header row for each cargo type
StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
Owner owner = GetStation(window_number)->owner;
if (owner != OWNER_NONE) this->owner = owner;
this->vscroll.cap = 5;
this->resize.step_height = 10;
this->FindWindowPlacementAndResize(desc);
}
~StationViewWindow()
{
WindowNumber wno =
(this->window_number << 16) | VLW_STATION_LIST | GetStation(this->window_number)->owner;
DeleteWindowById(WC_TRAINS_LIST, wno | (VEH_TRAIN << 11), false);
DeleteWindowById(WC_ROADVEH_LIST, wno | (VEH_ROAD << 11), false);
DeleteWindowById(WC_SHIPS_LIST, wno | (VEH_SHIP << 11), false);
DeleteWindowById(WC_AIRCRAFT_LIST, wno | (VEH_AIRCRAFT << 11), false);
}
virtual void OnPaint()
{
StationID station_id = this->window_number;
const Station *st = GetStation(station_id);
CargoDataList cargolist;
uint32 transfers = 0;
/* count types of cargos waiting in station */
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (st->goods[i].cargo.Empty()) {
this->cargo_rows[i] = 0;
} else {
/* Add an entry for total amount of cargo of this type waiting. */
cargolist.push_back(CargoData(i, INVALID_STATION, st->goods[i].cargo.Count()));
/* Set the row for this cargo entry for the expand/hide button */
this->cargo_rows[i] = (uint16)cargolist.size();
/* Add an entry for each distinct cargo source. */
const CargoList::List *packets = st->goods[i].cargo.Packets();
for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
const CargoPacket *cp = *it;
if (cp->source != station_id) {
bool added = false;
/* Enable the expand/hide button for this cargo type */
SetBit(transfers, i);
/* Don't add cargo lines if not expanded */
if (!HasBit(this->cargo, i)) break;
/* Check if we already have this source in the list */
for (CargoDataList::iterator jt = cargolist.begin(); jt != cargolist.end(); jt++) {
CargoData *cd = &(*jt);
if (cd->cargo == i && cd->source == cp->source) {
cd->count += cp->count;
added = true;
break;
}
}
if (!added) cargolist.push_back(CargoData(i, cp->source, cp->count));
}
}
}
}
SetVScrollCount(this, (int)cargolist.size() + 1); // update scrollbar
/* disable some buttons */
this->SetWidgetDisabledState(SVW_RENAME, st->owner != _local_company);
this->SetWidgetDisabledState(SVW_TRAINS, !(st->facilities & FACIL_TRAIN));
this->SetWidgetDisabledState(SVW_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
this->SetWidgetDisabledState(SVW_PLANES, !(st->facilities & FACIL_AIRPORT));
this->SetWidgetDisabledState(SVW_SHIPS, !(st->facilities & FACIL_DOCK));
SetDParam(0, st->index);
SetDParam(1, st->facilities);
this->DrawWidgets();
int x = 2; ///< coordinates used for printing waiting/accepted/rating of cargo
int y = 15;
int pos = this->vscroll.pos; ///< = this->vscroll.pos
uint width = this->widget[SVW_WAITING].right - this->widget[SVW_WAITING].left - 4;
int maxrows = this->vscroll.cap;
StringID str;
if (--pos < 0) {
str = STR_00D0_NOTHING;
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (!st->goods[i].cargo.Empty()) str = STR_EMPTY;
}
SetDParam(0, str);
DrawString(x, y, STR_0008_WAITING, TC_FROMSTRING);
y += 10;
}
for (CargoDataList::const_iterator it = cargolist.begin(); it != cargolist.end() && pos > -maxrows; ++it) {
if (--pos < 0) {
const CargoData *cd = &(*it);
if (cd->source == INVALID_STATION) {
/* Heading */
DrawCargoIcons(cd->cargo, cd->count, x, y, width);
SetDParam(0, cd->cargo);
SetDParam(1, cd->count);
if (HasBit(transfers, cd->cargo)) {
/* This cargo has transfers waiting so show the expand or shrink 'button' */
const char *sym = HasBit(this->cargo, cd->cargo) ? "-" : "+";
DrawStringRightAligned(x + width - 8, y, STR_0009, TC_FROMSTRING);
DoDrawString(sym, x + width - 6, y, TC_YELLOW);
} else {
DrawStringRightAligned(x + width, y, STR_0009, TC_FROMSTRING);
}
} else {
SetDParam(0, cd->cargo);
SetDParam(1, cd->count);
SetDParam(2, cd->source);
DrawStringRightAlignedTruncated(x + width, y, STR_EN_ROUTE_FROM, TC_FROMSTRING, width);
}
y += 10;
}
}
if (this->widget[SVW_ACCEPTS].data == STR_3032_RATINGS) { // small window with list of accepted cargo
char string[512];
char *b = string;
bool first = true;
b = InlineString(b, STR_000C_ACCEPTS);
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (b >= lastof(string) - (1 + 2 * 4)) break; // ',' or ' ' and two calls to Utf8Encode()
if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) {
if (first) {
first = false;
} else {
/* Add a comma if this is not the first item */
*b++ = ',';
*b++ = ' ';
}
b = InlineString(b, GetCargo(i)->name);
}
}
/* If first is still true then no cargo is accepted */
if (first) b = InlineString(b, STR_00D0_NOTHING);
*b = '\0';
/* Make sure we detect any buffer overflow */
assert(b < endof(string));
SetDParamStr(0, string);
DrawStringMultiLine(2, this->widget[SVW_ACCEPTLIST].top + 1, STR_JUST_RAW_STRING, this->widget[SVW_ACCEPTLIST].right - this->widget[SVW_ACCEPTLIST].left);
} else { // extended window with list of cargo ratings
y = this->widget[SVW_RATINGLIST].top + 1;
DrawString(2, y, STR_3034_LOCAL_RATING_OF_TRANSPORT, TC_FROMSTRING);
y += 10;
for (CargoID i = 0; i < NUM_CARGO; i++) {
const CargoSpec *cs = GetCargo(i);
if (!cs->IsValid()) continue;
const GoodsEntry *ge = &st->goods[i];
if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) continue;
SetDParam(0, cs->name);
SetDParam(2, ge->rating * 101 >> 8);
SetDParam(1, STR_3035_APPALLING + (ge->rating >> 5));
DrawString(8, y, STR_303D, TC_FROMSTRING);
y += 10;
}
}
}
void HandleCargoWaitingClick(int row)
{
if (row == 0) return;
for (CargoID c = 0; c < NUM_CARGO; c++) {
if (this->cargo_rows[c] == row) {
ToggleBit(this->cargo, c);
this->InvalidateWidget(SVW_WAITING);
break;
}
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case SVW_WAITING:
this->HandleCargoWaitingClick((pt.y - this->widget[SVW_WAITING].top) / 10 + this->vscroll.pos);
break;
case SVW_LOCATION:
if (_ctrl_pressed) {
ShowExtraViewPortWindow(GetStation(this->window_number)->xy);
} else {
ScrollMainWindowToTile(GetStation(this->window_number)->xy);
}
break;
case SVW_RATINGS:
this->SetDirty();
if (this->widget[SVW_RATINGS].data == STR_3032_RATINGS) {
/* Switch to ratings view */
this->widget[SVW_RATINGS].data = STR_3033_ACCEPTS;
this->widget[SVW_RATINGS].tooltips = STR_3056_SHOW_LIST_OF_ACCEPTED_CARGO;
ResizeWindowForWidget(this, SVW_ACCEPTLIST, 0, 100);
} else {
/* Switch to accepts view */
this->widget[SVW_RATINGS].data = STR_3032_RATINGS;
this->widget[SVW_RATINGS].tooltips = STR_3054_SHOW_STATION_RATINGS;
ResizeWindowForWidget(this, SVW_ACCEPTLIST, 0, -100);
}
this->SetDirty();
break;
case SVW_RENAME:
SetDParam(0, this->window_number);
ShowQueryString(STR_STATION, STR_3030_RENAME_STATION_LOADING, MAX_LENGTH_STATION_NAME_BYTES, MAX_LENGTH_STATION_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
break;
case SVW_TRAINS: { // Show a list of scheduled trains to this station
const Station *st = GetStation(this->window_number);
ShowVehicleListWindow(st->owner, VEH_TRAIN, (StationID)this->window_number);
break;
}
case SVW_ROADVEHS: { // Show a list of scheduled road-vehicles to this station
const Station *st = GetStation(this->window_number);
ShowVehicleListWindow(st->owner, VEH_ROAD, (StationID)this->window_number);
break;
}
case SVW_PLANES: { // Show a list of scheduled aircraft to this station
const Station *st = GetStation(this->window_number);
/* Since oilrigs have no owners, show the scheduled aircraft of local company */
Owner owner = (st->owner == OWNER_NONE) ? _local_company : st->owner;
ShowVehicleListWindow(owner, VEH_AIRCRAFT, (StationID)this->window_number);
break;
}
case SVW_SHIPS: { // Show a list of scheduled ships to this station
const Station *st = GetStation(this->window_number);
/* Since oilrigs/bouys have no owners, show the scheduled ships of local company */
Owner owner = (st->owner == OWNER_NONE) ? _local_company : st->owner;
ShowVehicleListWindow(owner, VEH_SHIP, (StationID)this->window_number);
break;
}
}
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_3031_CAN_T_RENAME_STATION), NULL, str);
}
virtual void OnResize(Point new_size, Point delta)
{
if (delta.x != 0) ResizeButtons(this, SVW_LOCATION, SVW_RENAME);
this->vscroll.cap += delta.y / (int)this->resize.step_height;
}
};
static const WindowDesc _station_view_desc(
WDP_AUTO, WDP_AUTO, 249, 110, 249, 110,
WC_STATION_VIEW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_station_view_widgets
);
/**
* Opens StationViewWindow for given station
*
* @param station station which window should be opened
*/
void ShowStationViewWindow(StationID station)
{
AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
}
static SmallVector<StationID, 8> _stations_nearby_list;
static SmallMap<TileIndex, StationID, 8> _deleted_stations_nearby;
/** Context for FindStationsNearby */
struct FindNearbyStationContext {
TileIndex tile; ///< Base tile of station to be built
uint w; ///< Width of station to be built
uint h; ///< Height of station to be built
};
/**
* Add station on this tile to _stations_nearby_list if it's fully within the
* station spread.
* @param tile Tile just being checked
* @param user_data Pointer to FindNearbyStationContext context
*/
static bool AddNearbyStation(TileIndex tile, void *user_data)
{
FindNearbyStationContext *ctx = (FindNearbyStationContext *)user_data;
/* First check if there was a deleted station here */
SmallPair<TileIndex, StationID> *dst = _deleted_stations_nearby.Find(tile);
if (dst != _deleted_stations_nearby.End()) {
_stations_nearby_list.Include(dst->second);
return false;
}
/* Check if own station and if we stay within station spread */
if (!IsTileType(tile, MP_STATION)) return false;
StationID sid = GetStationIndex(tile);
Station *st = GetStation(sid);
if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST)) {
*_stations_nearby_list.Append() = sid;
}
return false; // We want to include *all* nearby stations
}
/**
* Circulate around the to-be-built station to find stations we could join.
* Make sure that only stations are returned where joining wouldn't exceed
* station spread and are our own station.
* @param tile Base tile of the to-be-built station
* @param w Width of the to-be-built station
* @param h Height of the to-be-built station
* @param distant_join Search for adjacent stations (false) or stations fully
* within station spread
**/
static const Station *FindStationsNearby(TileIndex tile, int w, int h, bool distant_join)
{
FindNearbyStationContext ctx;
ctx.tile = tile;
ctx.w = w;
ctx.h = h;
_stations_nearby_list.Clear();
_deleted_stations_nearby.Clear();
/* Check the inside, to return, if we sit on another station */
BEGIN_TILE_LOOP(t, w, h, tile)
if (t < MapSize() && IsTileType(t, MP_STATION)) return GetStationByTile(t);
END_TILE_LOOP(t, w, h, tile)
/* Look for deleted stations */
const Station *st;
FOR_ALL_STATIONS(st) {
if (st->facilities == 0 && st->owner == _local_company) {
/* Include only within station spread (yes, it is strictly less than) */
if (max(DistanceMax(tile, st->xy), DistanceMax(TILE_ADDXY(tile, w - 1, h - 1), st->xy)) < _settings_game.station.station_spread) {
_deleted_stations_nearby.Insert(st->xy, st->index);
/* Add the station when it's within where we're going to build */
if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
AddNearbyStation(st->xy, &ctx);
}
}
}
}
/* Only search tiles where we have a chance to stay within the station spread.
* The complete check needs to be done in the callback as we don't know the
* extent of the found station, yet. */
if (distant_join && min(w, h) >= _settings_game.station.station_spread) return NULL;
uint max_dist = distant_join ? _settings_game.station.station_spread - min(w, h) : 1;
tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
CircularTileSearch(&tile, max_dist, w, h, AddNearbyStation, &ctx);
return NULL;
}
enum JoinStationWidgets {
JSW_WIDGET_CLOSEBOX = 0,
JSW_WIDGET_CAPTION,
JSW_PANEL,
JSW_SCROLLBAR,
JSW_EMPTY,
JSW_RESIZEBOX,
};
static const Widget _select_station_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_DARK_GREEN, 11, 199, 0, 13, STR_SELECT_STATION_TO_JOIN, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_RB, COLOUR_DARK_GREEN, 0, 187, 14, 79, 0x0, STR_NULL},
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_DARK_GREEN, 188, 199, 14, 79, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_PANEL, RESIZE_RTB, COLOUR_DARK_GREEN, 0, 187, 80, 91, 0x0, STR_NULL},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_DARK_GREEN, 188, 199, 80, 91, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
struct SelectStationWindow : Window {
CommandContainer select_station_cmd; ///< Command to build new station
TileIndex tile; ///< Base tile of new station
int size_x; ///< Size in x direction of new station
int size_y; ///< Size in y direction of new station
SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, int w, int h) :
Window(desc, 0),
select_station_cmd(cmd),
tile(cmd.tile),
size_x(w),
size_y(h)
{
this->vscroll.cap = 6;
this->resize.step_height = 10;
FindStationsNearby(this->tile, this->size_x, this->size_y, true);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
SetVScrollCount(this, _stations_nearby_list.Length() + 1);
this->DrawWidgets();
uint y = 17;
if (this->vscroll.pos == 0) {
DrawStringTruncated(3, y, STR_CREATE_SPLITTED_STATION, TC_FROMSTRING, this->widget[JSW_PANEL].right - 5);
y += 10;
}
for (uint i = max<uint>(1, this->vscroll.pos); i <= _stations_nearby_list.Length(); ++i, y += 10) {
/* Don't draw anything if it extends past the end of the window. */
if (i - this->vscroll.pos >= this->vscroll.cap) break;
const Station *st = GetStation(_stations_nearby_list[i - 1]);
SetDParam(0, st->index);
SetDParam(1, st->facilities);
DrawStringTruncated(3, y, STR_3049_0, TC_FROMSTRING, this->widget[JSW_PANEL].right - 5);
}
}
virtual void OnClick(Point pt, int widget)
{
if (widget != JSW_PANEL) return;
uint32 st_index = (pt.y - 16) / 10 + this->vscroll.pos;
bool distant_join = (st_index > 0);
if (distant_join) st_index--;
if (distant_join && st_index >= _stations_nearby_list.Length()) return;
/* Insert station to be joined into stored command */
SB(this->select_station_cmd.p2, 16, 16,
(distant_join ? _stations_nearby_list[st_index] : INVALID_STATION));
/* Execute stored Command */
DoCommandP(&this->select_station_cmd);
/* Close Window; this might cause double frees! */
DeleteWindowById(WC_SELECT_STATION, 0);
}
virtual void OnTick()
{
if (_thd.dirty & 2) {
_thd.dirty &= ~2;
this->SetDirty();
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap = (this->widget[JSW_PANEL].bottom - this->widget[JSW_PANEL].top) / 10;
}
virtual void OnInvalidateData(int data)
{
FindStationsNearby(this->tile, this->size_x, this->size_y, true);
this->SetDirty();
}
};
static const WindowDesc _select_station_desc(
WDP_AUTO, WDP_AUTO, 200, 92, 200, 182,
WC_SELECT_STATION, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE | WDF_CONSTRUCTION,
_select_station_widgets
);
/**
* Check whether we need to show the station selection window.
* @param cmd Command to build the station.
* @param w Width of the to-be-built station
* @param h Height of the to-be-built station
* @return whether we need to show the station selection window.
*/
static bool StationJoinerNeeded(CommandContainer cmd, int w, int h)
{
/* Only show selection if distant join is enabled in the settings */
if (!_settings_game.station.distant_join_stations) return false;
/* If a window is already opened and we didn't ctrl-click,
* return true (i.e. just flash the old window) */
Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
if (selection_window != NULL) {
if (!_ctrl_pressed) return true;
/* Abort current distant-join and start new one */
delete selection_window;
UpdateTileSelection();
}
/* only show the popup, if we press ctrl */
if (!_ctrl_pressed) return false;
/* Now check if we could build there */
if (CmdFailed(DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))))) return false;
/* Test for adjacent station or station below selection.
* If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
* but join the other station immediatelly. */
const Station *st = FindStationsNearby(cmd.tile, w, h, false);
return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
}
/**
* Show the station selection window when needed. If not, build the station.
* @param cmd Command to build the station.
* @param w Width of the to-be-built station
* @param h Height of the to-be-built station
*/
void ShowSelectStationIfNeeded(CommandContainer cmd, int w, int h)
{
if (StationJoinerNeeded(cmd, w, h)) {
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
if (BringWindowToFrontById(WC_SELECT_STATION, 0)) return;
new SelectStationWindow(&_select_station_desc, cmd, w, h);
} else {
DoCommandP(&cmd);
}
}
| 43,368
|
C++
|
.cpp
| 1,046
| 38.056405
| 172
| 0.657159
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,075
|
aystar.cpp
|
EnergeticBark_OpenTTD-3DS/src/aystar.cpp
|
/* $Id$ */
/** @file aystar.cpp Implementation of A*. */
/*
* This file has the core function for AyStar
* AyStar is a fast pathfinding routine and is used for things like
* AI_pathfinding and Train_pathfinding.
* For more information about AyStar (A* Algorithm), you can look at
* http://en.wikipedia.org/wiki/A-star_search_algorithm
*/
/*
* Friendly reminder:
* Call (AyStar).free() when you are done with Aystar. It reserves a lot of memory
* And when not free'd, it can cause system-crashes.
* Also remember that when you stop an algorithm before it is finished, your
* should call clear() yourself!
*/
#include "stdafx.h"
#include "aystar.h"
#include "core/alloc_func.hpp"
int _aystar_stats_open_size;
int _aystar_stats_closed_size;
/* This looks in the Hash if a node exists in ClosedList
* If so, it returns the PathNode, else NULL */
static PathNode *AyStarMain_ClosedList_IsInList(AyStar *aystar, const AyStarNode *node)
{
return (PathNode*)Hash_Get(&aystar->ClosedListHash, node->tile, node->direction);
}
/* This adds a node to the ClosedList
* It makes a copy of the data */
static void AyStarMain_ClosedList_Add(AyStar *aystar, const PathNode *node)
{
/* Add a node to the ClosedList */
PathNode *new_node = MallocT<PathNode>(1);
*new_node = *node;
Hash_Set(&aystar->ClosedListHash, node->node.tile, node->node.direction, new_node);
}
/* Checks if a node is in the OpenList
* If so, it returns the OpenListNode, else NULL */
static OpenListNode *AyStarMain_OpenList_IsInList(AyStar *aystar, const AyStarNode *node)
{
return (OpenListNode*)Hash_Get(&aystar->OpenListHash, node->tile, node->direction);
}
/* Gets the best node from OpenList
* returns the best node, or NULL of none is found
* Also it deletes the node from the OpenList */
static OpenListNode *AyStarMain_OpenList_Pop(AyStar *aystar)
{
/* Return the item the Queue returns.. the best next OpenList item. */
OpenListNode *res = (OpenListNode*)aystar->OpenListQueue.pop(&aystar->OpenListQueue);
if (res != NULL) {
Hash_Delete(&aystar->OpenListHash, res->path.node.tile, res->path.node.direction);
}
return res;
}
/* Adds a node to the OpenList
* It makes a copy of node, and puts the pointer of parent in the struct */
static void AyStarMain_OpenList_Add(AyStar *aystar, PathNode *parent, const AyStarNode *node, int f, int g)
{
/* Add a new Node to the OpenList */
OpenListNode *new_node = MallocT<OpenListNode>(1);
new_node->g = g;
new_node->path.parent = parent;
new_node->path.node = *node;
Hash_Set(&aystar->OpenListHash, node->tile, node->direction, new_node);
/* Add it to the queue */
aystar->OpenListQueue.push(&aystar->OpenListQueue, new_node, f);
}
/*
* Checks one tile and calculate his f-value
* return values:
* AYSTAR_DONE : indicates we are done
*/
int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
{
int new_f, new_g, new_h;
PathNode *closedlist_parent;
OpenListNode *check;
/* Check the new node against the ClosedList */
if (AyStarMain_ClosedList_IsInList(aystar, current) != NULL) return AYSTAR_DONE;
/* Calculate the G-value for this node */
new_g = aystar->CalculateG(aystar, current, parent);
/* If the value was INVALID_NODE, we don't do anything with this node */
if (new_g == AYSTAR_INVALID_NODE) return AYSTAR_DONE;
/* There should not be given any other error-code.. */
assert(new_g >= 0);
/* Add the parent g-value to the new g-value */
new_g += parent->g;
if (aystar->max_path_cost != 0 && (uint)new_g > aystar->max_path_cost) return AYSTAR_DONE;
/* Calculate the h-value */
new_h = aystar->CalculateH(aystar, current, parent);
/* There should not be given any error-code.. */
assert(new_h >= 0);
/* The f-value if g + h */
new_f = new_g + new_h;
/* Get the pointer to the parent in the ClosedList (the currentone is to a copy of the one in the OpenList) */
closedlist_parent = AyStarMain_ClosedList_IsInList(aystar, &parent->path.node);
/* Check if this item is already in the OpenList */
check = AyStarMain_OpenList_IsInList(aystar, current);
if (check != NULL) {
uint i;
/* Yes, check if this g value is lower.. */
if (new_g > check->g) return AYSTAR_DONE;
aystar->OpenListQueue.del(&aystar->OpenListQueue, check, 0);
/* It is lower, so change it to this item */
check->g = new_g;
check->path.parent = closedlist_parent;
/* Copy user data, will probably have changed */
for (i = 0; i < lengthof(current->user_data); i++) {
check->path.node.user_data[i] = current->user_data[i];
}
/* Readd him in the OpenListQueue */
aystar->OpenListQueue.push(&aystar->OpenListQueue, check, new_f);
} else {
/* A new node, add him to the OpenList */
AyStarMain_OpenList_Add(aystar, closedlist_parent, current, new_f, new_g);
}
return AYSTAR_DONE;
}
/*
* This function is the core of AyStar. It handles one item and checks
* his neighbour items. If they are valid, they are added to be checked too.
* return values:
* AYSTAR_EMPTY_OPENLIST : indicates all items are tested, and no path
* has been found.
* AYSTAR_LIMIT_REACHED : Indicates that the max_nodes limit has been
* reached.
* AYSTAR_FOUND_END_NODE : indicates we found the end. Path_found now is true, and in path is the path found.
* AYSTAR_STILL_BUSY : indicates we have done this tile, did not found the path yet, and have items left to try.
*/
int AyStarMain_Loop(AyStar *aystar)
{
int i, r;
/* Get the best node from OpenList */
OpenListNode *current = AyStarMain_OpenList_Pop(aystar);
/* If empty, drop an error */
if (current == NULL) return AYSTAR_EMPTY_OPENLIST;
/* Check for end node and if found, return that code */
if (aystar->EndNodeCheck(aystar, current) == AYSTAR_FOUND_END_NODE) {
if (aystar->FoundEndNode != NULL)
aystar->FoundEndNode(aystar, current);
free(current);
return AYSTAR_FOUND_END_NODE;
}
/* Add the node to the ClosedList */
AyStarMain_ClosedList_Add(aystar, ¤t->path);
/* Load the neighbours */
aystar->GetNeighbours(aystar, current);
/* Go through all neighbours */
for (i = 0; i < aystar->num_neighbours; i++) {
/* Check and add them to the OpenList if needed */
r = aystar->checktile(aystar, &aystar->neighbours[i], current);
}
/* Free the node */
free(current);
if (aystar->max_search_nodes != 0 && Hash_Size(&aystar->ClosedListHash) >= aystar->max_search_nodes) {
/* We've expanded enough nodes */
return AYSTAR_LIMIT_REACHED;
} else {
/* Return that we are still busy */
return AYSTAR_STILL_BUSY;
}
}
/*
* This function frees the memory it allocated
*/
void AyStarMain_Free(AyStar *aystar)
{
aystar->OpenListQueue.free(&aystar->OpenListQueue, false);
/* 2nd argument above is false, below is true, to free the values only
* once */
delete_Hash(&aystar->OpenListHash, true);
delete_Hash(&aystar->ClosedListHash, true);
#ifdef AYSTAR_DEBUG
printf("[AyStar] Memory free'd\n");
#endif
}
/*
* This function make the memory go back to zero
* This function should be called when you are using the same instance again.
*/
void AyStarMain_Clear(AyStar *aystar)
{
/* Clean the Queue, but not the elements within. That will be done by
* the hash. */
aystar->OpenListQueue.clear(&aystar->OpenListQueue, false);
/* Clean the hashes */
clear_Hash(&aystar->OpenListHash, true);
clear_Hash(&aystar->ClosedListHash, true);
#ifdef AYSTAR_DEBUG
printf("[AyStar] Cleared AyStar\n");
#endif
}
/*
* This is the function you call to run AyStar.
* return values:
* AYSTAR_FOUND_END_NODE : indicates we found an end node.
* AYSTAR_NO_PATH : indicates that there was no path found.
* AYSTAR_STILL_BUSY : indicates we have done some checked, that we did not found the path yet, and that we still have items left to try.
* When the algorithm is done (when the return value is not AYSTAR_STILL_BUSY)
* aystar->clear() is called. Note that when you stop the algorithm halfway,
* you should still call clear() yourself!
*/
int AyStarMain_Main(AyStar *aystar) {
int r, i = 0;
/* Loop through the OpenList
* Quit if result is no AYSTAR_STILL_BUSY or is more than loops_per_tick */
while ((r = aystar->loop(aystar)) == AYSTAR_STILL_BUSY && (aystar->loops_per_tick == 0 || ++i < aystar->loops_per_tick)) { }
#ifdef AYSTAR_DEBUG
switch (r) {
case AYSTAR_FOUND_END_NODE: printf("[AyStar] Found path!\n"); break;
case AYSTAR_EMPTY_OPENLIST: printf("[AyStar] OpenList run dry, no path found\n"); break;
case AYSTAR_LIMIT_REACHED: printf("[AyStar] Exceeded search_nodes, no path found\n"); break;
default: break;
}
#endif
if (r != AYSTAR_STILL_BUSY) {
/* We're done, clean up */
_aystar_stats_open_size = aystar->OpenListHash.size;
_aystar_stats_closed_size = aystar->ClosedListHash.size;
aystar->clear(aystar);
}
switch (r) {
case AYSTAR_FOUND_END_NODE: return AYSTAR_FOUND_END_NODE;
case AYSTAR_EMPTY_OPENLIST:
case AYSTAR_LIMIT_REACHED: return AYSTAR_NO_PATH;
default: return AYSTAR_STILL_BUSY;
}
}
/*
* Adds a node from where to start an algorithm. Multiple nodes can be added
* if wanted. You should make sure that clear() is called before adding nodes
* if the AyStar has been used before (though the normal main loop calls
* clear() automatically when the algorithm finishes
* g is the cost for starting with this node.
*/
void AyStarMain_AddStartNode(AyStar *aystar, AyStarNode *start_node, uint g)
{
#ifdef AYSTAR_DEBUG
printf("[AyStar] Starting A* Algorithm from node (%d, %d, %d)\n",
TileX(start_node->tile), TileY(start_node->tile), start_node->direction);
#endif
AyStarMain_OpenList_Add(aystar, NULL, start_node, 0, g);
}
void init_AyStar(AyStar *aystar, Hash_HashProc hash, uint num_buckets)
{
/* Allocated the Hash for the OpenList and ClosedList */
init_Hash(&aystar->OpenListHash, hash, num_buckets);
init_Hash(&aystar->ClosedListHash, hash, num_buckets);
/* Set up our sorting queue
* BinaryHeap allocates a block of 1024 nodes
* When thatone gets full it reserves an otherone, till this number
* That is why it can stay this high */
init_BinaryHeap(&aystar->OpenListQueue, 102400);
aystar->addstart = AyStarMain_AddStartNode;
aystar->main = AyStarMain_Main;
aystar->loop = AyStarMain_Loop;
aystar->free = AyStarMain_Free;
aystar->clear = AyStarMain_Clear;
aystar->checktile = AyStarMain_CheckTile;
}
| 10,373
|
C++
|
.cpp
| 260
| 37.811538
| 139
| 0.721787
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,076
|
smallmap_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/smallmap_gui.cpp
|
/* $Id$ */
/** @file smallmap_gui.cpp GUI that shows a small map of the world with metadata like owner or height. */
#include "stdafx.h"
#include "clear_map.h"
#include "industry_map.h"
#include "station_map.h"
#include "landscape.h"
#include "window_gui.h"
#include "tree_map.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "town.h"
#include "blitter/factory.hpp"
#include "tunnelbridge_map.h"
#include "strings_func.h"
#include "zoom_func.h"
#include "core/endian_func.hpp"
#include "vehicle_base.h"
#include "sound_func.h"
#include "window_func.h"
#include "table/strings.h"
#include "table/sprites.h"
static const Widget _smallmap_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_BROWN, 11, 337, 0, 13, STR_00B0_MAP, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_BROWN, 338, 349, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_RB, COLOUR_BROWN, 0, 349, 14, 157, 0x0, STR_NULL},
{ WWT_INSET, RESIZE_RB, COLOUR_BROWN, 2, 347, 16, 155, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_RTB, COLOUR_BROWN, 0, 261, 158, 201, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_LRTB, COLOUR_BROWN, 262, 349, 158, 158, 0x0, STR_NULL},
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_BROWN, 284, 305, 158, 179, SPR_IMG_SHOW_COUNTOURS, STR_0191_SHOW_LAND_CONTOURS_ON_MAP},
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_BROWN, 306, 327, 158, 179, SPR_IMG_SHOW_VEHICLES, STR_0192_SHOW_VEHICLES_ON_MAP},
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_BROWN, 328, 349, 158, 179, SPR_IMG_INDUSTRY, STR_0193_SHOW_INDUSTRIES_ON_MAP},
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_BROWN, 284, 305, 180, 201, SPR_IMG_SHOW_ROUTES, STR_0194_SHOW_TRANSPORT_ROUTES_ON},
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_BROWN, 306, 327, 180, 201, SPR_IMG_PLANTTREES, STR_0195_SHOW_VEGETATION_ON_MAP},
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_BROWN, 328, 349, 180, 201, SPR_IMG_COMPANY_GENERAL, STR_0196_SHOW_LAND_OWNERS_ON_MAP},
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_BROWN, 262, 283, 158, 179, SPR_IMG_SMALLMAP, STR_SMALLMAP_CENTER},
{ WWT_IMGBTN, RESIZE_LRTB, COLOUR_BROWN, 262, 283, 180, 201, SPR_IMG_TOWN, STR_0197_TOGGLE_TOWN_NAMES_ON_OFF},
{ WWT_PANEL, RESIZE_RTB, COLOUR_BROWN, 0, 337, 202, 213, 0x0, STR_NULL},
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_BROWN, 0, 99, 202, 213, STR_MESSAGES_ENABLE_ALL, STR_NULL},
{ WWT_TEXTBTN, RESIZE_TB, COLOUR_BROWN, 100, 201, 202, 213, STR_MESSAGES_DISABLE_ALL, STR_NULL},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_BROWN, 338, 349, 202, 213, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
/* number of used industries */
static int _smallmap_industry_count;
/** Macro for ordinary entry of LegendAndColour */
#define MK(a, b) {a, b, INVALID_INDUSTRYTYPE, true, false, false}
/** Macro for end of list marker in arrays of LegendAndColour */
#define MKEND() {0, STR_NULL, INVALID_INDUSTRYTYPE, true, true, false}
/** Macro for break marker in arrays of LegendAndColour.
* It will have valid data, though */
#define MS(a, b) {a, b, INVALID_INDUSTRYTYPE, true, false, true}
/** Structure for holding relevant data for legends in small map */
struct LegendAndColour {
uint16 colour; ///< colour of the item on the map
StringID legend; ///< string corresponding to the coloured item
IndustryType type; ///< type of industry
bool show_on_map; ///< for filtering industries, if true is shown on map in colour
bool end; ///< this is the end of the list
bool col_break; ///< perform a break and go one collumn further
};
/** Legend text giving the colours to look for on the minimap */
static const LegendAndColour _legend_land_contours[] = {
MK(0x5A, STR_00F0_100M),
MK(0x5C, STR_00F1_200M),
MK(0x5E, STR_00F2_300M),
MK(0x1F, STR_00F3_400M),
MK(0x27, STR_00F4_500M),
MS(0xD7, STR_00EB_ROADS),
MK(0x0A, STR_00EC_RAILROADS),
MK(0x98, STR_00ED_STATIONS_AIRPORTS_DOCKS),
MK(0xB5, STR_00EE_BUILDINGS_INDUSTRIES),
MK(0x0F, STR_00EF_VEHICLES),
MKEND()
};
static const LegendAndColour _legend_vehicles[] = {
MK(0xB8, STR_00F5_TRAINS),
MK(0xBF, STR_00F6_ROAD_VEHICLES),
MK(0x98, STR_00F7_SHIPS),
MK(0x0F, STR_00F8_AIRCRAFT),
MS(0xD7, STR_00F9_TRANSPORT_ROUTES),
MK(0xB5, STR_00EE_BUILDINGS_INDUSTRIES),
MKEND()
};
static const LegendAndColour _legend_routes[] = {
MK(0xD7, STR_00EB_ROADS),
MK(0x0A, STR_00EC_RAILROADS),
MK(0xB5, STR_00EE_BUILDINGS_INDUSTRIES),
MS(0x56, STR_011B_RAILROAD_STATION),
MK(0xC2, STR_011C_TRUCK_LOADING_BAY),
MK(0xBF, STR_011D_BUS_STATION),
MK(0xB8, STR_011E_AIRPORT_HELIPORT),
MK(0x98, STR_011F_DOCK),
MKEND()
};
static const LegendAndColour _legend_vegetation[] = {
MK(0x52, STR_0120_ROUGH_LAND),
MK(0x54, STR_0121_GRASS_LAND),
MK(0x37, STR_0122_BARE_LAND),
MK(0x25, STR_0123_FIELDS),
MK(0x57, STR_0124_TREES),
MK(0xD0, STR_00FC_FOREST),
MS(0x0A, STR_0125_ROCKS),
MK(0xC2, STR_012A_DESERT),
MK(0x98, STR_012B_SNOW),
MK(0xD7, STR_00F9_TRANSPORT_ROUTES),
MK(0xB5, STR_00EE_BUILDINGS_INDUSTRIES),
MKEND()
};
static const LegendAndColour _legend_land_owners[] = {
MK(0xCA, STR_0126_WATER),
MK(0x54, STR_0127_NO_OWNER),
MK(0xB4, STR_0128_TOWNS),
MK(0x20, STR_0129_INDUSTRIES),
MKEND()
};
#undef MK
#undef MS
#undef MKEND
/** Allow room for all industries, plus a terminator entry
* This is required in order to have the indutry slots all filled up */
static LegendAndColour _legend_from_industries[NUM_INDUSTRYTYPES + 1];
/* For connecting industry type to position in industries list(small map legend) */
static uint _industry_to_list_pos[NUM_INDUSTRYTYPES];
/**
* Fills an array for the industries legends.
*/
void BuildIndustriesLegend()
{
const IndustrySpec *indsp;
uint j = 0;
/* Add each name */
for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
indsp = GetIndustrySpec(i);
if (indsp->enabled) {
_legend_from_industries[j].legend = indsp->name;
_legend_from_industries[j].colour = indsp->map_colour;
_legend_from_industries[j].type = i;
_legend_from_industries[j].show_on_map = true;
_legend_from_industries[j].col_break = false;
_legend_from_industries[j].end = false;
/* Store widget number for this industry type */
_industry_to_list_pos[i] = j;
j++;
}
}
/* Terminate the list */
_legend_from_industries[j].end = true;
/* Store number of enabled industries */
_smallmap_industry_count = j;
}
static const LegendAndColour * const _legend_table[] = {
_legend_land_contours,
_legend_vehicles,
_legend_from_industries,
_legend_routes,
_legend_vegetation,
_legend_land_owners,
};
#define MKCOLOUR(x) TO_LE32X(x)
/**
* Height encodings; MAX_TILE_HEIGHT + 1 levels, from 0 to MAX_TILE_HEIGHT
*/
static const uint32 _map_height_bits[] = {
MKCOLOUR(0x5A5A5A5A),
MKCOLOUR(0x5A5B5A5B),
MKCOLOUR(0x5B5B5B5B),
MKCOLOUR(0x5B5C5B5C),
MKCOLOUR(0x5C5C5C5C),
MKCOLOUR(0x5C5D5C5D),
MKCOLOUR(0x5D5D5D5D),
MKCOLOUR(0x5D5E5D5E),
MKCOLOUR(0x5E5E5E5E),
MKCOLOUR(0x5E5F5E5F),
MKCOLOUR(0x5F5F5F5F),
MKCOLOUR(0x5F1F5F1F),
MKCOLOUR(0x1F1F1F1F),
MKCOLOUR(0x1F271F27),
MKCOLOUR(0x27272727),
MKCOLOUR(0x27272727),
};
assert_compile(lengthof(_map_height_bits) == MAX_TILE_HEIGHT + 1);
struct AndOr {
uint32 mor;
uint32 mand;
};
static inline uint32 ApplyMask(uint32 colour, const AndOr *mask)
{
return (colour & mask->mand) | mask->mor;
}
static const AndOr _smallmap_contours_andor[] = {
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0x000A0A00), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00B5B500), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0x98989898), MKCOLOUR(0x00000000)},
{MKCOLOUR(0xCACACACA), MKCOLOUR(0x00000000)},
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0xB5B5B5B5), MKCOLOUR(0x00000000)},
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0x00B5B500), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x000A0A00), MKCOLOUR(0xFF0000FF)},
};
static const AndOr _smallmap_vehicles_andor[] = {
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00B5B500), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0xCACACACA), MKCOLOUR(0x00000000)},
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0xB5B5B5B5), MKCOLOUR(0x00000000)},
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0x00B5B500), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
};
static const AndOr _smallmap_vegetation_andor[] = {
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00B5B500), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00575700), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0xCACACACA), MKCOLOUR(0x00000000)},
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0xB5B5B5B5), MKCOLOUR(0x00000000)},
{MKCOLOUR(0x00000000), MKCOLOUR(0xFFFFFFFF)},
{MKCOLOUR(0x00B5B500), MKCOLOUR(0xFF0000FF)},
{MKCOLOUR(0x00D7D700), MKCOLOUR(0xFF0000FF)},
};
typedef uint32 GetSmallMapPixels(TileIndex tile); // typedef callthrough function
/**
* Draws one column of the small map in a certain mode onto the screen buffer. This
* function looks exactly the same for all types
*
* @param dst Pointer to a part of the screen buffer to write to.
* @param xc The X coordinate of the first tile in the column.
* @param yc The Y coordinate of the first tile in the column
* @param pitch Number of pixels to advance in the screen buffer each time a pixel is written.
* @param reps Number of lines to draw
* @param mask ?
* @param proc Pointer to the colour function
* @see GetSmallMapPixels(TileIndex)
*/
static void DrawSmallMapStuff(void *dst, uint xc, uint yc, int pitch, int reps, uint32 mask, GetSmallMapPixels *proc)
{
Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
void *dst_ptr_abs_end = blitter->MoveTo(_screen.dst_ptr, 0, _screen.height);
void *dst_ptr_end = blitter->MoveTo(dst_ptr_abs_end, -4, 0);
do {
/* check if the tile (xc,yc) is within the map range */
uint min_xy = _settings_game.construction.freeform_edges ? 1 : 0;
if (IsInsideMM(xc, min_xy, MapMaxX()) && IsInsideMM(yc, min_xy, MapMaxY())) {
/* check if the dst pointer points to a pixel inside the screen buffer */
if (dst < _screen.dst_ptr) continue;
if (dst >= dst_ptr_abs_end) continue;
uint32 val = proc(TileXY(xc, yc)) & mask;
uint8 *val8 = (uint8 *)&val;
if (dst <= dst_ptr_end) {
blitter->SetPixelIfEmpty(dst, 0, 0, val8[0]);
blitter->SetPixelIfEmpty(dst, 1, 0, val8[1]);
blitter->SetPixelIfEmpty(dst, 2, 0, val8[2]);
blitter->SetPixelIfEmpty(dst, 3, 0, val8[3]);
} else {
/* It happens that there are only 1, 2 or 3 pixels left to fill, so in that special case, write till the end of the video-buffer */
int i = 0;
do {
blitter->SetPixelIfEmpty(dst, 0, 0, val8[i]);
} while (i++, dst = blitter->MoveTo(dst, 1, 0), dst < dst_ptr_abs_end);
}
}
/* switch to next tile in the column */
} while (xc++, yc++, dst = blitter->MoveTo(dst, pitch, 0), --reps != 0);
}
static inline TileType GetEffectiveTileType(TileIndex tile)
{
TileType t = GetTileType(tile);
if (t == MP_TUNNELBRIDGE) {
TransportType tt = GetTunnelBridgeTransportType(tile);
switch (tt) {
case TRANSPORT_RAIL: t = MP_RAILWAY; break;
case TRANSPORT_ROAD: t = MP_ROAD; break;
default: t = MP_WATER; break;
}
}
return t;
}
/**
* Return the colour a tile would be displayed with in the small map in mode "Contour".
* @param tile The tile of which we would like to get the colour.
* @return The colour of tile in the small map in mode "Contour"
*/
static inline uint32 GetSmallMapContoursPixels(TileIndex tile)
{
TileType t = GetEffectiveTileType(tile);
return
ApplyMask(_map_height_bits[TileHeight(tile)], &_smallmap_contours_andor[t]);
}
/**
* Return the colour a tile would be displayed with in the small map in mode "Vehicles".
*
* @param tile The tile of which we would like to get the colour.
* @return The colour of tile in the small map in mode "Vehicles"
*/
static inline uint32 GetSmallMapVehiclesPixels(TileIndex tile)
{
TileType t = GetEffectiveTileType(tile);
return ApplyMask(MKCOLOUR(0x54545454), &_smallmap_vehicles_andor[t]);
}
/**
* Return the colour a tile would be displayed with in the small map in mode "Industries".
*
* @param tile The tile of which we would like to get the colour.
* @return The colour of tile in the small map in mode "Industries"
*/
static inline uint32 GetSmallMapIndustriesPixels(TileIndex tile)
{
TileType t = GetEffectiveTileType(tile);
if (t == MP_INDUSTRY) {
/* If industry is allowed to be seen, use its colour on the map */
if (_legend_from_industries[_industry_to_list_pos[GetIndustryByTile(tile)->type]].show_on_map) {
return GetIndustrySpec(GetIndustryByTile(tile)->type)->map_colour * 0x01010101;
} else {
/* otherwise, return the colour of the clear tiles, which will make it disappear */
return ApplyMask(MKCOLOUR(0x54545454), &_smallmap_vehicles_andor[MP_CLEAR]);
}
}
return ApplyMask(MKCOLOUR(0x54545454), &_smallmap_vehicles_andor[t]);
}
/**
* Return the colour a tile would be displayed with in the small map in mode "Routes".
*
* @param tile The tile of which we would like to get the colour.
* @return The colour of tile in the small map in mode "Routes"
*/
static inline uint32 GetSmallMapRoutesPixels(TileIndex tile)
{
TileType t = GetEffectiveTileType(tile);
uint32 bits;
if (t == MP_STATION) {
switch (GetStationType(tile)) {
case STATION_RAIL: bits = MKCOLOUR(0x56565656); break;
case STATION_AIRPORT: bits = MKCOLOUR(0xB8B8B8B8); break;
case STATION_TRUCK: bits = MKCOLOUR(0xC2C2C2C2); break;
case STATION_BUS: bits = MKCOLOUR(0xBFBFBFBF); break;
case STATION_DOCK: bits = MKCOLOUR(0x98989898); break;
default: bits = MKCOLOUR(0xFFFFFFFF); break;
}
} else {
/* ground colour */
bits = ApplyMask(MKCOLOUR(0x54545454), &_smallmap_contours_andor[t]);
}
return bits;
}
static const uint32 _vegetation_clear_bits[] = {
MKCOLOUR(0x54545454), ///< full grass
MKCOLOUR(0x52525252), ///< rough land
MKCOLOUR(0x0A0A0A0A), ///< rocks
MKCOLOUR(0x25252525), ///< fields
MKCOLOUR(0x98989898), ///< snow
MKCOLOUR(0xC2C2C2C2), ///< desert
MKCOLOUR(0x54545454), ///< unused
MKCOLOUR(0x54545454), ///< unused
};
static inline uint32 GetSmallMapVegetationPixels(TileIndex tile)
{
TileType t = GetEffectiveTileType(tile);
uint32 bits;
switch (t) {
case MP_CLEAR:
if (IsClearGround(tile, CLEAR_GRASS) && GetClearDensity(tile) < 3) {
bits = MKCOLOUR(0x37373737);
} else {
bits = _vegetation_clear_bits[GetClearGround(tile)];
}
break;
case MP_INDUSTRY:
bits = GetIndustrySpec(GetIndustryByTile(tile)->type)->check_proc == CHECK_FOREST ? MKCOLOUR(0xD0D0D0D0) : MKCOLOUR(0xB5B5B5B5);
break;
case MP_TREES:
if (GetTreeGround(tile) == TREE_GROUND_SNOW_DESERT) {
bits = (_settings_game.game_creation.landscape == LT_ARCTIC) ? MKCOLOUR(0x98575798) : MKCOLOUR(0xC25757C2);
} else {
bits = MKCOLOUR(0x54575754);
}
break;
default:
bits = ApplyMask(MKCOLOUR(0x54545454), &_smallmap_vehicles_andor[t]);
break;
}
return bits;
}
static uint32 _owner_colours[OWNER_END + 1];
/**
* Return the colour a tile would be displayed with in the small map in mode "Owner".
*
* @param tile The tile of which we would like to get the colour.
* @return The colour of tile in the small map in mode "Owner"
*/
static inline uint32 GetSmallMapOwnerPixels(TileIndex tile)
{
Owner o;
switch (GetTileType(tile)) {
case MP_INDUSTRY: o = OWNER_END; break;
case MP_HOUSE: o = OWNER_TOWN; break;
default: o = GetTileOwner(tile); break;
/* FIXME: For MP_ROAD there are multiple owners.
* GetTileOwner returns the rail owner (level crossing) resp. the owner of ROADTYPE_ROAD (normal road),
* even if there are no ROADTYPE_ROAD bits on the tile.
*/
}
return _owner_colours[o];
}
static const uint32 _smallmap_mask_left[3] = {
MKCOLOUR(0xFF000000),
MKCOLOUR(0xFFFF0000),
MKCOLOUR(0xFFFFFF00),
};
static const uint32 _smallmap_mask_right[] = {
MKCOLOUR(0x000000FF),
MKCOLOUR(0x0000FFFF),
MKCOLOUR(0x00FFFFFF),
};
/* each tile has 4 x pixels and 1 y pixel */
static GetSmallMapPixels *_smallmap_draw_procs[] = {
GetSmallMapContoursPixels,
GetSmallMapVehiclesPixels,
GetSmallMapIndustriesPixels,
GetSmallMapRoutesPixels,
GetSmallMapVegetationPixels,
GetSmallMapOwnerPixels,
};
static const byte _vehicle_type_colours[6] = {
184, 191, 152, 15, 215, 184
};
static void DrawVertMapIndicator(int x, int y, int x2, int y2)
{
GfxFillRect(x, y, x2, y + 3, 69);
GfxFillRect(x, y2 - 3, x2, y2, 69);
}
static void DrawHorizMapIndicator(int x, int y, int x2, int y2)
{
GfxFillRect(x, y, x + 3, y2, 69);
GfxFillRect(x2 - 3, y, x2, y2, 69);
}
enum SmallMapWindowWidgets {
SM_WIDGET_MAP_BORDER = 3,
SM_WIDGET_MAP,
SM_WIDGET_LEGEND,
SM_WIDGET_BUTTONSPANEL,
SM_WIDGET_CONTOUR,
SM_WIDGET_VEHICLES,
SM_WIDGET_INDUSTRIES,
SM_WIDGET_ROUTES,
SM_WIDGET_VEGETATION,
SM_WIDGET_OWNERS,
SM_WIDGET_CENTERMAP,
SM_WIDGET_TOGGLETOWNNAME,
SM_WIDGET_BOTTOMPANEL,
SM_WIDGET_ENABLEINDUSTRIES,
SM_WIDGET_DISABLEINDUSTRIES,
SM_WIDGET_RESIZEBOX,
};
class SmallMapWindow : public Window
{
enum SmallMapType {
SMT_CONTOUR,
SMT_VEHICLES,
SMT_INDUSTRY,
SMT_ROUTES,
SMT_VEGETATION,
SMT_OWNER,
};
static SmallMapType map_type;
static bool show_towns;
int32 scroll_x;
int32 scroll_y;
int32 subscroll;
uint8 refresh;
static const int COLUMN_WIDTH = 119;
static const int MIN_LEGEND_HEIGHT = 6 * 7;
public:
/**
* Draws the small map.
*
* Basically, the small map is draw column of pixels by column of pixels. The pixels
* are drawn directly into the screen buffer. The final map is drawn in multiple passes.
* The passes are:
* <ol><li>The colours of tiles in the different modes.</li>
* <li>Town names (optional)</li></ol>
*
* @param dpi pointer to pixel to write onto
* @param w pointer to Window struct
* @param type type of map requested (vegetation, owners, routes, etc)
* @param show_towns true if the town names should be displayed, false if not.
*/
void DrawSmallMap(DrawPixelInfo *dpi)
{
Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
DrawPixelInfo *old_dpi;
int dx, dy, x, y, x2, y2;
void *ptr;
int tile_x;
int tile_y;
ViewPort *vp;
old_dpi = _cur_dpi;
_cur_dpi = dpi;
/* clear it */
GfxFillRect(dpi->left, dpi->top, dpi->left + dpi->width - 1, dpi->top + dpi->height - 1, 0);
/* setup owner table */
if (this->map_type == SMT_OWNER) {
const Company *c;
/* fill with some special colours */
_owner_colours[OWNER_TOWN] = MKCOLOUR(0xB4B4B4B4);
_owner_colours[OWNER_NONE] = MKCOLOUR(0x54545454);
_owner_colours[OWNER_WATER] = MKCOLOUR(0xCACACACA);
_owner_colours[OWNER_END] = MKCOLOUR(0x20202020); // industry
/* now fill with the company colours */
FOR_ALL_COMPANIES(c) {
_owner_colours[c->index] =
_colour_gradient[c->colour][5] * 0x01010101;
}
}
tile_x = this->scroll_x / TILE_SIZE;
tile_y = this->scroll_y / TILE_SIZE;
dx = dpi->left + this->subscroll;
tile_x -= dx / 4;
tile_y += dx / 4;
dx &= 3;
dy = dpi->top;
tile_x += dy / 2;
tile_y += dy / 2;
if (dy & 1) {
tile_x++;
dx += 2;
if (dx > 3) {
dx -= 4;
tile_x--;
tile_y++;
}
}
ptr = blitter->MoveTo(dpi->dst_ptr, -dx - 4, 0);
x = - dx - 4;
y = 0;
for (;;) {
uint32 mask = 0xFFFFFFFF;
int reps;
int t;
/* distance from left edge */
if (x < 0) {
if (x < -3) goto skip_column;
/* mask to use at the left edge */
mask = _smallmap_mask_left[x + 3];
}
/* distance from right edge */
t = dpi->width - x;
if (t < 4) {
if (t <= 0) break; // exit loop
/* mask to use at the right edge */
mask &= _smallmap_mask_right[t - 1];
}
/* number of lines */
reps = (dpi->height - y + 1) / 2;
if (reps > 0) {
DrawSmallMapStuff(ptr, tile_x, tile_y, dpi->pitch * 2, reps, mask, _smallmap_draw_procs[this->map_type]);
}
skip_column:
if (y == 0) {
tile_y++;
y++;
ptr = blitter->MoveTo(ptr, 0, 1);
} else {
tile_x--;
y--;
ptr = blitter->MoveTo(ptr, 0, -1);
}
ptr = blitter->MoveTo(ptr, 2, 0);
x += 2;
}
/* draw vehicles? */
if (this->map_type == SMT_CONTOUR || this->map_type == SMT_VEHICLES) {
Vehicle *v;
bool skip;
byte colour;
FOR_ALL_VEHICLES(v) {
if (v->type != VEH_EFFECT &&
(v->vehstatus & (VS_HIDDEN | VS_UNCLICKABLE)) == 0) {
/* Remap into flat coordinates. */
Point pt = RemapCoords(
v->x_pos / TILE_SIZE - this->scroll_x / TILE_SIZE, // divide each one separately because (a-b)/c != a/c-b/c in integer world
v->y_pos / TILE_SIZE - this->scroll_y / TILE_SIZE, // dtto
0);
x = pt.x;
y = pt.y;
/* Check if y is out of bounds? */
y -= dpi->top;
if (!IsInsideMM(y, 0, dpi->height)) continue;
/* Default is to draw both pixels. */
skip = false;
/* Offset X coordinate */
x -= this->subscroll + 3 + dpi->left;
if (x < 0) {
/* if x+1 is 0, that means we're on the very left edge,
* and should thus only draw a single pixel */
if (++x != 0) continue;
skip = true;
} else if (x >= dpi->width - 1) {
/* Check if we're at the very right edge, and if so draw only a single pixel */
if (x != dpi->width - 1) continue;
skip = true;
}
/* Calculate pointer to pixel and the colour */
colour = (this->map_type == SMT_VEHICLES) ? _vehicle_type_colours[v->type] : 0xF;
/* And draw either one or two pixels depending on clipping */
blitter->SetPixel(dpi->dst_ptr, x, y, colour);
if (!skip) blitter->SetPixel(dpi->dst_ptr, x + 1, y, colour);
}
}
}
if (this->show_towns) {
const Town *t;
FOR_ALL_TOWNS(t) {
/* Remap the town coordinate */
Point pt = RemapCoords(
(int)(TileX(t->xy) * TILE_SIZE - this->scroll_x) / TILE_SIZE,
(int)(TileY(t->xy) * TILE_SIZE - this->scroll_y) / TILE_SIZE,
0);
x = pt.x - this->subscroll + 3 - (t->sign.width_2 >> 1);
y = pt.y;
/* Check if the town sign is within bounds */
if (x + t->sign.width_2 > dpi->left &&
x < dpi->left + dpi->width &&
y + 6 > dpi->top &&
y < dpi->top + dpi->height) {
/* And draw it. */
SetDParam(0, t->index);
DrawString(x, y, STR_2056, TC_WHITE);
}
}
}
/* Draw map indicators */
{
Point pt;
/* Find main viewport. */
vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
pt = RemapCoords(this->scroll_x, this->scroll_y, 0);
x = vp->virtual_left - pt.x;
y = vp->virtual_top - pt.y;
x2 = (x + vp->virtual_width) / TILE_SIZE;
y2 = (y + vp->virtual_height) / TILE_SIZE;
x /= TILE_SIZE;
y /= TILE_SIZE;
x -= this->subscroll;
x2 -= this->subscroll;
DrawVertMapIndicator(x, y, x, y2);
DrawVertMapIndicator(x2, y, x2, y2);
DrawHorizMapIndicator(x, y, x2, y);
DrawHorizMapIndicator(x, y2, x2, y2);
}
_cur_dpi = old_dpi;
}
void SmallMapCenterOnCurrentPos()
{
int x, y;
ViewPort *vp;
vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
x = ((vp->virtual_width - (this->widget[SM_WIDGET_MAP].right - this->widget[SM_WIDGET_MAP].left) * TILE_SIZE) / 2 + vp->virtual_left) / 4;
y = ((vp->virtual_height - (this->widget[SM_WIDGET_MAP].bottom - this->widget[SM_WIDGET_MAP].top ) * TILE_SIZE) / 2 + vp->virtual_top ) / 2 - TILE_SIZE * 2;
this->scroll_x = (y - x) & ~0xF;
this->scroll_y = (x + y) & ~0xF;
this->SetDirty();
}
void ResizeLegend()
{
Widget *legend = &this->widget[SM_WIDGET_LEGEND];
int rows = (legend->bottom - legend->top) - 1;
int columns = (legend->right - legend->left) / COLUMN_WIDTH;
int new_rows = (this->map_type == SMT_INDUSTRY) ? ((_smallmap_industry_count + columns - 1) / columns) * 6 : MIN_LEGEND_HEIGHT;
new_rows = max(new_rows, MIN_LEGEND_HEIGHT);
if (new_rows != rows) {
this->SetDirty();
/* The legend widget needs manual adjustment as by default
* it lays outside the filler widget's bounds. */
legend->top--;
/* Resize the filler widget, and move widgets below it. */
ResizeWindowForWidget(this, SM_WIDGET_BUTTONSPANEL, 0, new_rows - rows);
legend->top++;
/* Resize map border widget so the window stays the same size */
ResizeWindowForWidget(this, SM_WIDGET_MAP_BORDER, 0, rows - new_rows);
/* Manually adjust the map widget as it lies completely within
* the map border widget */
this->widget[SM_WIDGET_MAP].bottom += rows - new_rows;
this->SetDirty();
}
}
SmallMapWindow(const WindowDesc *desc, int window_number) : Window(desc, window_number)
{
this->LowerWidget(this->map_type + SM_WIDGET_CONTOUR);
this->SetWidgetLoweredState(SM_WIDGET_TOGGLETOWNNAME, this->show_towns);
this->SmallMapCenterOnCurrentPos();
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
DrawPixelInfo new_dpi;
/* Hide Enable all/Disable all buttons if is not industry type small map*/
this->SetWidgetHiddenState(SM_WIDGET_ENABLEINDUSTRIES, this->map_type != SMT_INDUSTRY);
this->SetWidgetHiddenState(SM_WIDGET_DISABLEINDUSTRIES, this->map_type != SMT_INDUSTRY);
/* draw the window */
SetDParam(0, STR_00E5_CONTOURS + this->map_type);
this->DrawWidgets();
const Widget *legend = &this->widget[SM_WIDGET_LEGEND];
int y_org = legend->top + 1;
int x = 4;
int y = y_org;
for (const LegendAndColour *tbl = _legend_table[this->map_type]; !tbl->end; ++tbl) {
if (tbl->col_break || y >= legend->bottom) {
/* Column break needed, continue at top, COLUMN_WIDTH pixels
* (one "row") to the right. */
x += COLUMN_WIDTH;
y = y_org;
}
if (this->map_type == SMT_INDUSTRY) {
/* Industry name must be formated, since it's not in tiny font in the specs.
* So, draw with a parameter and use the STR_SMALLMAP_INDUSTRY string, which is tiny font.*/
SetDParam(0, tbl->legend);
assert(tbl->type < NUM_INDUSTRYTYPES);
SetDParam(1, _industry_counts[tbl->type]);
if (!tbl->show_on_map) {
/* Simply draw the string, not the black border of the legend colour.
* This will enforce the idea of the disabled item */
DrawString(x + 11, y, STR_SMALLMAP_INDUSTRY, TC_GREY);
} else {
DrawString(x + 11, y, STR_SMALLMAP_INDUSTRY, TC_BLACK);
GfxFillRect(x, y + 1, x + 8, y + 5, 0); // outer border of the legend colour
}
} else {
/* Anything that is not an industry is using normal process */
GfxFillRect(x, y + 1, x + 8, y + 5, 0);
DrawString(x + 11, y, tbl->legend, TC_FROMSTRING);
}
GfxFillRect(x + 1, y + 2, x + 7, y + 4, tbl->colour); // legend colour
y += 6;
}
const Widget *wi = &this->widget[SM_WIDGET_MAP];
if (!FillDrawPixelInfo(&new_dpi, wi->left + 1, wi->top + 1, wi->right - wi->left - 1, wi->bottom - wi->top - 1)) return;
this->DrawSmallMap(&new_dpi);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case SM_WIDGET_MAP: { // Map window
/*
* XXX: scrolling with the left mouse button is done by subsequently
* clicking with the left mouse button; clicking once centers the
* large map at the selected point. So by unclicking the left mouse
* button here, it gets reclicked during the next inputloop, which
* would make it look like the mouse is being dragged, while it is
* actually being (virtually) clicked every inputloop.
*/
_left_button_clicked = false;
Point pt = RemapCoords(this->scroll_x, this->scroll_y, 0);
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
w->viewport->follow_vehicle = INVALID_VEHICLE;
w->viewport->dest_scrollpos_x = pt.x + ((_cursor.pos.x - this->left + 2) << 4) - (w->viewport->virtual_width >> 1);
w->viewport->dest_scrollpos_y = pt.y + ((_cursor.pos.y - this->top - 16) << 4) - (w->viewport->virtual_height >> 1);
this->SetDirty();
} break;
case SM_WIDGET_CONTOUR: // Show land contours
case SM_WIDGET_VEHICLES: // Show vehicles
case SM_WIDGET_INDUSTRIES: // Show industries
case SM_WIDGET_ROUTES: // Show transport routes
case SM_WIDGET_VEGETATION: // Show vegetation
case SM_WIDGET_OWNERS: // Show land owners
this->RaiseWidget(this->map_type + SM_WIDGET_CONTOUR);
this->map_type = (SmallMapType)(widget - SM_WIDGET_CONTOUR);
this->LowerWidget(this->map_type + SM_WIDGET_CONTOUR);
this->ResizeLegend();
this->SetDirty();
SndPlayFx(SND_15_BEEP);
break;
case SM_WIDGET_CENTERMAP: // Center the smallmap again
this->SmallMapCenterOnCurrentPos();
this->SetDirty();
SndPlayFx(SND_15_BEEP);
break;
case SM_WIDGET_TOGGLETOWNNAME: // Toggle town names
this->show_towns = !this->show_towns;
this->SetWidgetLoweredState(SM_WIDGET_TOGGLETOWNNAME, this->show_towns);
this->SetDirty();
SndPlayFx(SND_15_BEEP);
break;
case SM_WIDGET_LEGEND: // Legend
/* if industry type small map*/
if (this->map_type == SMT_INDUSTRY) {
/* if click on industries label, find right industry type and enable/disable it */
Widget *wi = &this->widget[SM_WIDGET_LEGEND]; // label panel
uint column = (pt.x - 4) / COLUMN_WIDTH;
uint line = (pt.y - wi->top - 2) / 6;
int rows_per_column = (wi->bottom - wi->top) / 6;
/* check if click is on industry label*/
int industry_pos = (column * rows_per_column) + line;
if (industry_pos < _smallmap_industry_count) {
_legend_from_industries[industry_pos].show_on_map = !_legend_from_industries[industry_pos].show_on_map;
}
/* Raise the two buttons "all", as we have done a specific choice */
this->RaiseWidget(SM_WIDGET_ENABLEINDUSTRIES);
this->RaiseWidget(SM_WIDGET_DISABLEINDUSTRIES);
this->SetDirty();
}
break;
case SM_WIDGET_ENABLEINDUSTRIES: // Enable all industries
for (int i = 0; i != _smallmap_industry_count; i++) {
_legend_from_industries[i].show_on_map = true;
}
/* toggle appeareance indicating the choice */
this->LowerWidget(SM_WIDGET_ENABLEINDUSTRIES);
this->RaiseWidget(SM_WIDGET_DISABLEINDUSTRIES);
this->SetDirty();
break;
case SM_WIDGET_DISABLEINDUSTRIES: // disable all industries
for (int i = 0; i != _smallmap_industry_count; i++) {
_legend_from_industries[i].show_on_map = false;
}
/* toggle appeareance indicating the choice */
this->RaiseWidget(SM_WIDGET_ENABLEINDUSTRIES);
this->LowerWidget(SM_WIDGET_DISABLEINDUSTRIES);
this->SetDirty();
break;
}
}
virtual void OnRightClick(Point pt, int widget)
{
if (widget == SM_WIDGET_MAP) {
if (_scrolling_viewport) return;
_scrolling_viewport = true;
_cursor.delta.x = 0;
_cursor.delta.y = 0;
}
}
virtual void OnTick()
{
/* update the window every now and then */
if ((++this->refresh & 0x1F) == 0) this->SetDirty();
}
virtual void OnScroll(Point delta)
{
_cursor.fix_at = true;
int x = this->scroll_x;
int y = this->scroll_y;
int sub = this->subscroll + delta.x;
x -= (sub >> 2) << 4;
y += (sub >> 2) << 4;
sub &= 3;
x += (delta.y >> 1) << 4;
y += (delta.y >> 1) << 4;
if (delta.y & 1) {
x += TILE_SIZE;
sub += 2;
if (sub > 3) {
sub -= 4;
x -= TILE_SIZE;
y += TILE_SIZE;
}
}
int hx = (this->widget[SM_WIDGET_MAP].right - this->widget[SM_WIDGET_MAP].left) / 2;
int hy = (this->widget[SM_WIDGET_MAP].bottom - this->widget[SM_WIDGET_MAP].top ) / 2;
int hvx = hx * -4 + hy * 8;
int hvy = hx * 4 + hy * 8;
if (x < -hvx) {
x = -hvx;
sub = 0;
}
if (x > (int)MapMaxX() * TILE_SIZE - hvx) {
x = MapMaxX() * TILE_SIZE - hvx;
sub = 0;
}
if (y < -hvy) {
y = -hvy;
sub = 0;
}
if (y > (int)MapMaxY() * TILE_SIZE - hvy) {
y = MapMaxY() * TILE_SIZE - hvy;
sub = 0;
}
this->scroll_x = x;
this->scroll_y = y;
this->subscroll = sub;
this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta)
{
if (delta.x != 0 && this->map_type == SMT_INDUSTRY) this->ResizeLegend();
}
};
SmallMapWindow::SmallMapType SmallMapWindow::map_type = SMT_CONTOUR;
bool SmallMapWindow::show_towns = true;
static const WindowDesc _smallmap_desc(
WDP_AUTO, WDP_AUTO, 350, 214, 446, 314,
WC_SMALLMAP, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_smallmap_widgets
);
void ShowSmallMap()
{
AllocateWindowDescFront<SmallMapWindow>(&_smallmap_desc, 0);
}
/* Extra ViewPort Window Stuff */
static const Widget _extra_view_port_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 287, 0, 13, STR_EXTRA_VIEW_PORT_TITLE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 288, 299, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 299, 14, 33, 0x0, STR_NULL},
{ WWT_INSET, RESIZE_RB, COLOUR_GREY, 2, 297, 16, 31, 0x0, STR_NULL},
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 0, 21, 34, 55, SPR_IMG_ZOOMIN, STR_017F_ZOOM_THE_VIEW_IN},
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 22, 43, 34, 55, SPR_IMG_ZOOMOUT, STR_0180_ZOOM_THE_VIEW_OUT},
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 44, 171, 34, 55, STR_EXTRA_VIEW_MOVE_MAIN_TO_VIEW, STR_EXTRA_VIEW_MOVE_MAIN_TO_VIEW_TT},
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 172, 298, 34, 55, STR_EXTRA_VIEW_MOVE_VIEW_TO_MAIN, STR_EXTRA_VIEW_MOVE_VIEW_TO_MAIN_TT},
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 299, 299, 34, 55, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 0, 287, 56, 67, 0x0, STR_NULL},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 288, 299, 56, 67, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
class ExtraViewportWindow : public Window
{
enum ExtraViewportWindowWidgets {
EVW_CLOSE,
EVW_CAPTION,
EVW_STICKY,
EVW_BACKGROUND,
EVW_VIEWPORT,
EVW_ZOOMIN,
EVW_ZOOMOUT,
EVW_MAIN_TO_VIEW,
EVW_VIEW_TO_MAIN,
EVW_SPACER1,
EVW_SPACER2,
EVW_RESIZE,
};
public:
ExtraViewportWindow(const WindowDesc *desc, int window_number, TileIndex tile) : Window(desc, window_number)
{
/* New viewport start at (zero,zero) */
InitializeWindowViewport(this, 3, 17, this->widget[EVW_VIEWPORT].right - this->widget[EVW_VIEWPORT].left - 1, this->widget[EVW_VIEWPORT].bottom - this->widget[EVW_VIEWPORT].top - 1, 0, ZOOM_LVL_VIEWPORT);
this->DisableWidget(EVW_ZOOMIN);
this->FindWindowPlacementAndResize(desc);
Point pt;
if (tile == INVALID_TILE) {
/* the main window with the main view */
const Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
/* center on same place as main window (zoom is maximum, no adjustment needed) */
pt.x = w->viewport->scrollpos_x + w->viewport->virtual_height / 2;
pt.y = w->viewport->scrollpos_y + w->viewport->virtual_height / 2;
} else {
pt = RemapCoords(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, TileHeight(tile));
}
this->viewport->scrollpos_x = pt.x - ((this->widget[EVW_VIEWPORT].right - this->widget[EVW_VIEWPORT].left) - 1) / 2;
this->viewport->scrollpos_y = pt.y - ((this->widget[EVW_VIEWPORT].bottom - this->widget[EVW_VIEWPORT].top) - 1) / 2;
this->viewport->dest_scrollpos_x = this->viewport->scrollpos_x;
this->viewport->dest_scrollpos_y = this->viewport->scrollpos_y;
}
virtual void OnPaint()
{
/* set the number in the title bar */
SetDParam(0, this->window_number + 1);
this->DrawWidgets();
this->DrawViewport();
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case EVW_ZOOMIN: DoZoomInOutWindow(ZOOM_IN, this); break;
case EVW_ZOOMOUT: DoZoomInOutWindow(ZOOM_OUT, this); break;
case EVW_MAIN_TO_VIEW: { // location button (move main view to same spot as this view) 'Paste Location'
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
int x = this->viewport->scrollpos_x; // Where is the main looking at
int y = this->viewport->scrollpos_y;
/* set this view to same location. Based on the center, adjusting for zoom */
w->viewport->dest_scrollpos_x = x - (w->viewport->virtual_width - this->viewport->virtual_width) / 2;
w->viewport->dest_scrollpos_y = y - (w->viewport->virtual_height - this->viewport->virtual_height) / 2;
w->viewport->follow_vehicle = INVALID_VEHICLE;
} break;
case EVW_VIEW_TO_MAIN: { // inverse location button (move this view to same spot as main view) 'Copy Location'
const Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
int x = w->viewport->scrollpos_x;
int y = w->viewport->scrollpos_y;
this->viewport->dest_scrollpos_x = x + (w->viewport->virtual_width - this->viewport->virtual_width) / 2;
this->viewport->dest_scrollpos_y = y + (w->viewport->virtual_height - this->viewport->virtual_height) / 2;
} break;
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->viewport->width += delta.x;
this->viewport->height += delta.y;
this->viewport->virtual_width += delta.x;
this->viewport->virtual_height += delta.y;
}
virtual void OnScroll(Point delta)
{
const ViewPort *vp = IsPtInWindowViewport(this, _cursor.pos.x, _cursor.pos.y);
if (vp == NULL) return;
this->viewport->scrollpos_x += ScaleByZoom(delta.x, vp->zoom);
this->viewport->scrollpos_y += ScaleByZoom(delta.y, vp->zoom);
this->viewport->dest_scrollpos_x = this->viewport->scrollpos_x;
this->viewport->dest_scrollpos_y = this->viewport->scrollpos_y;
}
virtual void OnMouseWheel(int wheel)
{
ZoomInOrOutToCursorWindow(wheel < 0, this);
}
virtual void OnInvalidateData(int data = 0)
{
/* Only handle zoom message if intended for us (msg ZOOM_IN/ZOOM_OUT) */
HandleZoomMessage(this, this->viewport, EVW_ZOOMIN, EVW_ZOOMOUT);
}
};
static const WindowDesc _extra_view_port_desc(
WDP_AUTO, WDP_AUTO, 300, 68, 300, 268,
WC_EXTRA_VIEW_PORT, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_extra_view_port_widgets
);
void ShowExtraViewPortWindow(TileIndex tile)
{
int i = 0;
/* find next free window number for extra viewport */
while (FindWindowById(WC_EXTRA_VIEW_PORT, i) != NULL) i++;
new ExtraViewportWindow(&_extra_view_port_desc, i, tile);
}
/**
* Scrolls the main window to given coordinates.
* @param x x coordinate
* @param y y coordinate
* @param z z coordinate; -1 to scroll to terrain height
* @param instant scroll instantly (meaningful only when smooth_scrolling is active)
* @return did the viewport position change?
*/
bool ScrollMainWindowTo(int x, int y, int z, bool instant)
{
bool res = ScrollWindowTo(x, y, z, FindWindowById(WC_MAIN_WINDOW, 0), instant);
/* If a user scrolls to a tile (via what way what so ever) and already is on
* that tile (e.g.: pressed twice), move the smallmap to that location,
* so you directly see where you are on the smallmap. */
if (res) return res;
SmallMapWindow *w = dynamic_cast<SmallMapWindow*>(FindWindowById(WC_SMALLMAP, 0));
if (w != NULL) w->SmallMapCenterOnCurrentPos();
return res;
}
| 40,301
|
C++
|
.cpp
| 1,052
| 35.21673
| 206
| 0.669909
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,077
|
station.cpp
|
EnergeticBark_OpenTTD-3DS/src/station.cpp
|
/* $Id$ */
/** @file station.cpp Implementation of the station base class. */
#include "stdafx.h"
#include "company_func.h"
#include "industry.h"
#include "newgrf_cargo.h"
#include "yapf/yapf.h"
#include "cargotype.h"
#include "roadveh.h"
#include "window_type.h"
#include "station_gui.h"
#include "zoom_func.h"
#include "functions.h"
#include "window_func.h"
#include "date_func.h"
#include "command_func.h"
#include "news_func.h"
#include "aircraft.h"
#include "vehicle_gui.h"
#include "settings_type.h"
#include "table/strings.h"
Station::Station(TileIndex tile)
{
DEBUG(station, cDebugCtorLevel, "I+%3d", index);
xy = tile;
airport_tile = dock_tile = train_tile = INVALID_TILE;
bus_stops = truck_stops = NULL;
had_vehicle_of_type = 0;
time_since_load = 255;
time_since_unload = 255;
delete_ctr = 0;
facilities = 0;
last_vehicle_type = VEH_INVALID;
indtype = IT_INVALID;
random_bits = 0; // Random() must be called when station is really built (DC_EXEC)
waiting_triggers = 0;
}
/**
* Clean up a station by clearing vehicle orders and invalidating windows.
* Aircraft-Hangar orders need special treatment here, as the hangars are
* actually part of a station (tiletype is STATION), but the order type
* is OT_GOTO_DEPOT.
*/
Station::~Station()
{
DEBUG(station, cDebugCtorLevel, "I-%3d", index);
free(this->name);
free(this->speclist);
if (CleaningPool()) return;
while (!loading_vehicles.empty()) {
loading_vehicles.front()->LeaveStation();
}
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_AIRCRAFT && IsNormalAircraft(v) && v->u.air.targetairport == this->index) {
v->u.air.targetairport = INVALID_STATION;
}
}
MarkDirty();
InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
DeleteWindowById(WC_STATION_VIEW, index);
WindowNumber wno = (index << 16) | VLW_STATION_LIST | this->owner;
DeleteWindowById(WC_TRAINS_LIST, wno | (VEH_TRAIN << 11));
DeleteWindowById(WC_ROADVEH_LIST, wno | (VEH_ROAD << 11));
DeleteWindowById(WC_SHIPS_LIST, wno | (VEH_SHIP << 11));
DeleteWindowById(WC_AIRCRAFT_LIST, wno | (VEH_AIRCRAFT << 11));
/* Now delete all orders that go to the station */
RemoveOrderFromAllVehicles(OT_GOTO_STATION, index);
/* Subsidies need removal as well */
DeleteSubsidyWithStation(index);
/* Remove all news items */
DeleteStationNews(this->index);
xy = INVALID_TILE;
InvalidateWindowData(WC_SELECT_STATION, 0, 0);
for (CargoID c = 0; c < NUM_CARGO; c++) {
goods[c].cargo.Truncate(0);
}
}
/**
* Get the primary road stop (the first road stop) that the given vehicle can load/unload.
* @param v the vehicle to get the first road stop for
* @return the first roadstop that this vehicle can load at
*/
RoadStop *Station::GetPrimaryRoadStop(const Vehicle *v) const
{
RoadStop *rs = this->GetPrimaryRoadStop(IsCargoInClass(v->cargo_type, CC_PASSENGERS) ? ROADSTOP_BUS : ROADSTOP_TRUCK);
for (; rs != NULL; rs = rs->next) {
/* The vehicle cannot go to this roadstop (different roadtype) */
if ((GetRoadTypes(rs->xy) & v->u.road.compatible_roadtypes) == ROADTYPES_NONE) continue;
/* The vehicle is articulated and can therefor not go the a standard road stop */
if (IsStandardRoadStopTile(rs->xy) && RoadVehHasArticPart(v)) continue;
/* The vehicle can actually go to this road stop. So, return it! */
break;
}
return rs;
}
/** Called when new facility is built on the station. If it is the first facility
* it initializes also 'xy' and 'random_bits' members */
void Station::AddFacility(byte new_facility_bit, TileIndex facil_xy)
{
if (facilities == 0) {
xy = facil_xy;
random_bits = Random();
}
facilities |= new_facility_bit;
owner = _current_company;
build_date = _date;
}
void Station::MarkDirty() const
{
if (sign.width_1 != 0) {
InvalidateWindowWidget(WC_STATION_VIEW, index, SVW_CAPTION);
/* We use ZOOM_LVL_MAX here, as every viewport can have an other zoom,
* and there is no way for us to know which is the biggest. So make the
* biggest area dirty, and we are safe for sure. */
MarkAllViewportsDirty(
sign.left - 6,
sign.top,
sign.left + ScaleByZoom(sign.width_1 + 12, ZOOM_LVL_MAX),
sign.top + ScaleByZoom(12, ZOOM_LVL_MAX));
}
}
void Station::MarkTilesDirty(bool cargo_change) const
{
TileIndex tile = train_tile;
int w, h;
if (tile == INVALID_TILE) return;
/* cargo_change is set if we're refreshing the tiles due to cargo moving
* around. */
if (cargo_change) {
/* Don't waste time updating if there are no custom station graphics
* that might change. Even if there are custom graphics, they might
* not change. Unfortunately we have no way of telling. */
if (this->num_specs == 0) return;
}
for (h = 0; h < trainst_h; h++) {
for (w = 0; w < trainst_w; w++) {
if (TileBelongsToRailStation(tile)) {
MarkTileDirtyByTile(tile);
}
tile += TileDiffXY(1, 0);
}
tile += TileDiffXY(-w, 1);
}
}
bool Station::TileBelongsToRailStation(TileIndex tile) const
{
return IsTileType(tile, MP_STATION) && GetStationIndex(tile) == index && IsRailwayStation(tile);
}
/** Obtain the length of a platform
* @pre tile must be a railway station tile
* @param tile A tile that contains the platform in question
* @return The length of the platform
*/
uint Station::GetPlatformLength(TileIndex tile) const
{
TileIndex t;
TileIndexDiff delta;
uint len = 0;
assert(TileBelongsToRailStation(tile));
delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
t = tile;
do {
t -= delta;
len++;
} while (IsCompatibleTrainStationTile(t, tile));
t = tile;
do {
t += delta;
len++;
} while (IsCompatibleTrainStationTile(t, tile));
return len - 1;
}
/** Determines the REMAINING length of a platform, starting at (and including)
* the given tile.
* @param tile the tile from which to start searching. Must be a railway station tile
* @param dir The direction in which to search.
* @return The platform length
*/
uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
{
TileIndex start_tile = tile;
uint length = 0;
assert(IsRailwayStationTile(tile));
assert(dir < DIAGDIR_END);
do {
length ++;
tile += TileOffsByDiagDir(dir);
} while (IsCompatibleTrainStationTile(tile, start_tile));
return length;
}
/** Determines whether a station is a buoy only.
* @todo Ditch this encoding of buoys
*/
bool Station::IsBuoy() const
{
return (had_vehicle_of_type & HVOT_BUOY) != 0;
}
/** Determines the catchment radius of the station
* @return The radius
*/
uint Station::GetCatchmentRadius() const
{
uint ret = CA_NONE;
if (_settings_game.station.modified_catchment) {
if (this->bus_stops != NULL) ret = max<uint>(ret, CA_BUS);
if (this->truck_stops != NULL) ret = max<uint>(ret, CA_TRUCK);
if (this->train_tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
if (this->dock_tile != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
if (this->airport_tile != INVALID_TILE) ret = max<uint>(ret, this->Airport()->catchment);
} else {
if (this->bus_stops != NULL || this->truck_stops != NULL || this->train_tile != INVALID_TILE || this->dock_tile != INVALID_TILE || this->airport_tile != INVALID_TILE) {
ret = CA_UNMODIFIED;
}
}
return ret;
}
/************************************************************************/
/* StationRect implementation */
/************************************************************************/
StationRect::StationRect()
{
MakeEmpty();
}
void StationRect::MakeEmpty()
{
left = top = right = bottom = 0;
}
/**
* Determines whether a given point (x, y) is within a certain distance of
* the station rectangle.
* @note x and y are in Tile coordinates
* @param x X coordinate
* @param y Y coordinate
* @param distance The maxmium distance a point may have (L1 norm)
* @return true if the point is within distance tiles of the station rectangle
*/
bool StationRect::PtInExtendedRect(int x, int y, int distance) const
{
return (left - distance <= x && x <= right + distance && top - distance <= y && y <= bottom + distance);
}
bool StationRect::IsEmpty() const
{
return (left == 0 || left > right || top > bottom);
}
bool StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
{
int x = TileX(tile);
int y = TileY(tile);
if (IsEmpty()) {
/* we are adding the first station tile */
if (mode != ADD_TEST) {
left = right = x;
top = bottom = y;
}
} else if (!PtInExtendedRect(x, y)) {
/* current rect is not empty and new point is outside this rect
* make new spread-out rectangle */
Rect new_rect = {min(x, left), min(y, top), max(x, right), max(y, bottom)};
/* check new rect dimensions against preset max */
int w = new_rect.right - new_rect.left + 1;
int h = new_rect.bottom - new_rect.top + 1;
if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
assert(mode != ADD_TRY);
_error_message = STR_306C_STATION_TOO_SPREAD_OUT;
return false;
}
/* spread-out ok, return true */
if (mode != ADD_TEST) {
/* we should update the station rect */
*this = new_rect;
}
} else {
; // new point is inside the rect, we don't need to do anything
}
return true;
}
bool StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
{
return (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) && // important when the old rect is completely inside the new rect, resp. the old one was empty
BeforeAddTile(tile, mode) && BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
}
/**
* Check whether station tiles of the given station id exist in the given rectangle
* @param st_id Station ID to look for in the rectangle
* @param left_a Minimal tile X edge of the rectangle
* @param top_a Minimal tile Y edge of the rectangle
* @param right_a Maximal tile X edge of the rectangle (inclusive)
* @param bottom_a Maximal tile Y edge of the rectangle (inclusive)
* @return \c true if a station tile with the given \a st_id exists in the rectangle, \c false otherwise
*/
/* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
{
TileIndex top_left = TileXY(left_a, top_a);
int width = right_a - left_a + 1;
int height = bottom_a - top_a + 1;
BEGIN_TILE_LOOP(tile, width, height, top_left)
if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
END_TILE_LOOP(tile, width, height, top_left);
return false;
}
bool StationRect::AfterRemoveTile(Station *st, TileIndex tile)
{
int x = TileX(tile);
int y = TileY(tile);
/* look if removed tile was on the bounding rect edge
* and try to reduce the rect by this edge
* do it until we have empty rect or nothing to do */
for (;;) {
/* check if removed tile is on rect edge */
bool left_edge = (x == left);
bool right_edge = (x == right);
bool top_edge = (y == top);
bool bottom_edge = (y == bottom);
/* can we reduce the rect in either direction? */
bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, top, x, bottom));
bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, left, y, right, y));
if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
if (reduce_x) {
/* reduce horizontally */
if (left_edge) {
/* move left edge right */
left = x = x + 1;
} else {
/* move right edge left */
right = x = x - 1;
}
}
if (reduce_y) {
/* reduce vertically */
if (top_edge) {
/* move top edge down */
top = y = y + 1;
} else {
/* move bottom edge up */
bottom = y = y - 1;
}
}
if (left > right || top > bottom) {
/* can't continue, if the remaining rectangle is empty */
MakeEmpty();
return true; // empty remaining rect
}
}
return false; // non-empty remaining rect
}
bool StationRect::AfterRemoveRect(Station *st, TileIndex tile, int w, int h)
{
assert(PtInExtendedRect(TileX(tile), TileY(tile)));
assert(PtInExtendedRect(TileX(tile) + w - 1, TileY(tile) + h - 1));
bool empty = AfterRemoveTile(st, tile);
if (w != 1 || h != 1) empty = empty || AfterRemoveTile(st, TILE_ADDXY(tile, w - 1, h - 1));
return empty;
}
StationRect& StationRect::operator = (Rect src)
{
left = src.left;
top = src.top;
right = src.right;
bottom = src.bottom;
return *this;
}
/************************************************************************/
/* RoadStop implementation */
/************************************************************************/
/** Initializes a RoadStop */
RoadStop::RoadStop(TileIndex tile) :
xy(tile),
status(3), // stop is free
num_vehicles(0),
next(NULL)
{
DEBUG(ms, cDebugCtorLevel, "I+ at %d[0x%x]", tile, tile);
}
/** De-Initializes a RoadStops. This includes clearing all slots that vehicles might
* have and unlinks it from the linked list of road stops at the given station
*/
RoadStop::~RoadStop()
{
if (CleaningPool()) return;
/* Clear the slot assignment of all vehicles heading for this road stop */
if (num_vehicles != 0) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_ROAD && v->u.road.slot == this) ClearSlot(v);
}
}
assert(num_vehicles == 0);
DEBUG(ms, cDebugCtorLevel , "I- at %d[0x%x]", xy, xy);
xy = INVALID_TILE;
}
/** Checks whether there is a free bay in this road stop */
bool RoadStop::HasFreeBay() const
{
return GB(status, 0, MAX_BAY_COUNT) != 0;
}
/** Checks whether the given bay is free in this road stop */
bool RoadStop::IsFreeBay(uint nr) const
{
assert(nr < MAX_BAY_COUNT);
return HasBit(status, nr);
}
/**
* Allocates a bay
* @return the allocated bay number
* @pre this->HasFreeBay()
*/
uint RoadStop::AllocateBay()
{
assert(HasFreeBay());
/* Find the first free bay. If the bit is set, the bay is free. */
uint bay_nr = 0;
while (!HasBit(status, bay_nr)) bay_nr++;
ClrBit(status, bay_nr);
return bay_nr;
}
/**
* Allocates a bay in a drive-through road stop
* @param nr the number of the bay to allocate
*/
void RoadStop::AllocateDriveThroughBay(uint nr)
{
assert(nr < MAX_BAY_COUNT);
ClrBit(status, nr);
}
/**
* Frees the given bay
* @param nr the number of the bay to free
*/
void RoadStop::FreeBay(uint nr)
{
assert(nr < MAX_BAY_COUNT);
SetBit(status, nr);
}
/** Checks whether the entrance of the road stop is occupied by a vehicle */
bool RoadStop::IsEntranceBusy() const
{
return HasBit(status, 7);
}
/** Makes an entrance occupied or free */
void RoadStop::SetEntranceBusy(bool busy)
{
SB(status, 7, 1, busy);
}
/**
* Get the next road stop accessible by this vehicle.
* @param v the vehicle to get the next road stop for.
* @return the next road stop accessible.
*/
RoadStop *RoadStop::GetNextRoadStop(const Vehicle *v) const
{
for (RoadStop *rs = this->next; rs != NULL; rs = rs->next) {
/* The vehicle cannot go to this roadstop (different roadtype) */
if ((GetRoadTypes(rs->xy) & v->u.road.compatible_roadtypes) == ROADTYPES_NONE) continue;
/* The vehicle is articulated and can therefor not go the a standard road stop */
if (IsStandardRoadStopTile(rs->xy) && RoadVehHasArticPart(v)) continue;
/* The vehicle can actually go to this road stop. So, return it! */
return rs;
}
return NULL;
}
| 15,414
|
C++
|
.cpp
| 461
| 31.175705
| 218
| 0.678528
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,078
|
queue.cpp
|
EnergeticBark_OpenTTD-3DS/src/queue.cpp
|
/* $Id$ */
/** @file queue.cpp Implementation of the Queue/Hash. */
#include "stdafx.h"
#include "queue.h"
#include "core/alloc_func.hpp"
/*
* Insertion Sorter
*/
static void InsSort_Clear(Queue *q, bool free_values)
{
InsSortNode *node = q->data.inssort.first;
InsSortNode *prev;
while (node != NULL) {
if (free_values) free(node->item);
prev = node;
node = node->next;
free(prev);
}
q->data.inssort.first = NULL;
}
static void InsSort_Free(Queue *q, bool free_values)
{
q->clear(q, free_values);
}
static bool InsSort_Push(Queue *q, void *item, int priority)
{
InsSortNode *newnode = MallocT<InsSortNode>(1);
newnode->item = item;
newnode->priority = priority;
if (q->data.inssort.first == NULL ||
q->data.inssort.first->priority >= priority) {
newnode->next = q->data.inssort.first;
q->data.inssort.first = newnode;
} else {
InsSortNode *node = q->data.inssort.first;
while (node != NULL) {
if (node->next == NULL || node->next->priority >= priority) {
newnode->next = node->next;
node->next = newnode;
break;
}
node = node->next;
}
}
return true;
}
static void *InsSort_Pop(Queue *q)
{
InsSortNode *node = q->data.inssort.first;
void *result;
if (node == NULL) return NULL;
result = node->item;
q->data.inssort.first = q->data.inssort.first->next;
assert(q->data.inssort.first == NULL || q->data.inssort.first->priority >= node->priority);
free(node);
return result;
}
static bool InsSort_Delete(Queue *q, void *item, int priority)
{
return false;
}
void init_InsSort(Queue *q)
{
q->push = InsSort_Push;
q->pop = InsSort_Pop;
q->del = InsSort_Delete;
q->clear = InsSort_Clear;
q->free = InsSort_Free;
q->data.inssort.first = NULL;
}
/*
* Binary Heap
* For information, see: http://www.policyalmanac.org/games/binaryHeaps.htm
*/
#define BINARY_HEAP_BLOCKSIZE (1 << BINARY_HEAP_BLOCKSIZE_BITS)
#define BINARY_HEAP_BLOCKSIZE_MASK (BINARY_HEAP_BLOCKSIZE - 1)
/* To make our life easy, we make the next define
* Because Binary Heaps works with array from 1 to n,
* and C with array from 0 to n-1, and we don't like typing
* q->data.binaryheap.elements[i - 1] every time, we use this define. */
#define BIN_HEAP_ARR(i) q->data.binaryheap.elements[((i) - 1) >> BINARY_HEAP_BLOCKSIZE_BITS][((i) - 1) & BINARY_HEAP_BLOCKSIZE_MASK]
static void BinaryHeap_Clear(Queue *q, bool free_values)
{
/* Free all items if needed and free all but the first blocks of memory */
uint i;
uint j;
for (i = 0; i < q->data.binaryheap.blocks; i++) {
if (q->data.binaryheap.elements[i] == NULL) {
/* No more allocated blocks */
break;
}
/* For every allocated block */
if (free_values) {
for (j = 0; j < (1 << BINARY_HEAP_BLOCKSIZE_BITS); j++) {
/* For every element in the block */
if ((q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS) == i &&
(q->data.binaryheap.size & BINARY_HEAP_BLOCKSIZE_MASK) == j) {
break; // We're past the last element
}
free(q->data.binaryheap.elements[i][j].item);
}
}
if (i != 0) {
/* Leave the first block of memory alone */
free(q->data.binaryheap.elements[i]);
q->data.binaryheap.elements[i] = NULL;
}
}
q->data.binaryheap.size = 0;
q->data.binaryheap.blocks = 1;
}
static void BinaryHeap_Free(Queue *q, bool free_values)
{
uint i;
q->clear(q, free_values);
for (i = 0; i < q->data.binaryheap.blocks; i++) {
if (q->data.binaryheap.elements[i] == NULL) break;
free(q->data.binaryheap.elements[i]);
}
free(q->data.binaryheap.elements);
}
static bool BinaryHeap_Push(Queue *q, void *item, int priority)
{
#ifdef QUEUE_DEBUG
printf("[BinaryHeap] Pushing an element. There are %d elements left\n", q->data.binaryheap.size);
#endif
if (q->data.binaryheap.size == q->data.binaryheap.max_size) return false;
assert(q->data.binaryheap.size < q->data.binaryheap.max_size);
if (q->data.binaryheap.elements[q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS] == NULL) {
/* The currently allocated blocks are full, allocate a new one */
assert((q->data.binaryheap.size & BINARY_HEAP_BLOCKSIZE_MASK) == 0);
q->data.binaryheap.elements[q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS] = MallocT<BinaryHeapNode>(BINARY_HEAP_BLOCKSIZE);
q->data.binaryheap.blocks++;
#ifdef QUEUE_DEBUG
printf("[BinaryHeap] Increasing size of elements to %d nodes\n", q->data.binaryheap.blocks * BINARY_HEAP_BLOCKSIZE);
#endif
}
/* Add the item at the end of the array */
BIN_HEAP_ARR(q->data.binaryheap.size + 1).priority = priority;
BIN_HEAP_ARR(q->data.binaryheap.size + 1).item = item;
q->data.binaryheap.size++;
/* Now we are going to check where it belongs. As long as the parent is
* bigger, we switch with the parent */
{
BinaryHeapNode temp;
int i;
int j;
i = q->data.binaryheap.size;
while (i > 1) {
/* Get the parent of this object (divide by 2) */
j = i / 2;
/* Is the parent bigger then the current, switch them */
if (BIN_HEAP_ARR(i).priority <= BIN_HEAP_ARR(j).priority) {
temp = BIN_HEAP_ARR(j);
BIN_HEAP_ARR(j) = BIN_HEAP_ARR(i);
BIN_HEAP_ARR(i) = temp;
i = j;
} else {
/* It is not, we're done! */
break;
}
}
}
return true;
}
static bool BinaryHeap_Delete(Queue *q, void *item, int priority)
{
uint i = 0;
#ifdef QUEUE_DEBUG
printf("[BinaryHeap] Deleting an element. There are %d elements left\n", q->data.binaryheap.size);
#endif
/* First, we try to find the item.. */
do {
if (BIN_HEAP_ARR(i + 1).item == item) break;
i++;
} while (i < q->data.binaryheap.size);
/* We did not find the item, so we return false */
if (i == q->data.binaryheap.size) return false;
/* Now we put the last item over the current item while decreasing the size of the elements */
q->data.binaryheap.size--;
BIN_HEAP_ARR(i + 1) = BIN_HEAP_ARR(q->data.binaryheap.size + 1);
/* Now the only thing we have to do, is resort it..
* On place i there is the item to be sorted.. let's start there */
{
uint j;
BinaryHeapNode temp;
/* Because of the fact that Binary Heap uses array from 1 to n, we need to
* increase i by 1
*/
i++;
for (;;) {
j = i;
/* Check if we have 2 childs */
if (2 * j + 1 <= q->data.binaryheap.size) {
/* Is this child smaller than the parent? */
if (BIN_HEAP_ARR(j).priority >= BIN_HEAP_ARR(2 * j).priority) i = 2 * j;
/* Yes, we _need_ to use i here, not j, because we want to have the smallest child
* This way we get that straight away! */
if (BIN_HEAP_ARR(i).priority >= BIN_HEAP_ARR(2 * j + 1).priority) i = 2 * j + 1;
/* Do we have one child? */
} else if (2 * j <= q->data.binaryheap.size) {
if (BIN_HEAP_ARR(j).priority >= BIN_HEAP_ARR(2 * j).priority) i = 2 * j;
}
/* One of our childs is smaller than we are, switch */
if (i != j) {
temp = BIN_HEAP_ARR(j);
BIN_HEAP_ARR(j) = BIN_HEAP_ARR(i);
BIN_HEAP_ARR(i) = temp;
} else {
/* None of our childs is smaller, so we stay here.. stop :) */
break;
}
}
}
return true;
}
static void *BinaryHeap_Pop(Queue *q)
{
void *result;
#ifdef QUEUE_DEBUG
printf("[BinaryHeap] Popping an element. There are %d elements left\n", q->data.binaryheap.size);
#endif
if (q->data.binaryheap.size == 0) return NULL;
/* The best item is always on top, so give that as result */
result = BIN_HEAP_ARR(1).item;
/* And now we should get rid of this item... */
BinaryHeap_Delete(q, BIN_HEAP_ARR(1).item, BIN_HEAP_ARR(1).priority);
return result;
}
void init_BinaryHeap(Queue *q, uint max_size)
{
assert(q != NULL);
q->push = BinaryHeap_Push;
q->pop = BinaryHeap_Pop;
q->del = BinaryHeap_Delete;
q->clear = BinaryHeap_Clear;
q->free = BinaryHeap_Free;
q->data.binaryheap.max_size = max_size;
q->data.binaryheap.size = 0;
/* We malloc memory in block of BINARY_HEAP_BLOCKSIZE
* It autosizes when it runs out of memory */
q->data.binaryheap.elements = CallocT<BinaryHeapNode*>((max_size - 1) / BINARY_HEAP_BLOCKSIZE + 1);
q->data.binaryheap.elements[0] = MallocT<BinaryHeapNode>(BINARY_HEAP_BLOCKSIZE);
q->data.binaryheap.blocks = 1;
#ifdef QUEUE_DEBUG
printf("[BinaryHeap] Initial size of elements is %d nodes\n", BINARY_HEAP_BLOCKSIZE);
#endif
}
/* Because we don't want anyone else to bother with our defines */
#undef BIN_HEAP_ARR
/*
* Hash
*/
void init_Hash(Hash *h, Hash_HashProc *hash, uint num_buckets)
{
/* Allocate space for the Hash, the buckets and the bucket flags */
uint i;
assert(h != NULL);
#ifdef HASH_DEBUG
debug("Allocated hash: %p", h);
#endif
h->hash = hash;
h->size = 0;
h->num_buckets = num_buckets;
h->buckets = (HashNode*)MallocT<byte>(num_buckets * (sizeof(*h->buckets) + sizeof(*h->buckets_in_use)));
#ifdef HASH_DEBUG
debug("Buckets = %p", h->buckets);
#endif
h->buckets_in_use = (bool*)(h->buckets + num_buckets);
for (i = 0; i < num_buckets; i++) h->buckets_in_use[i] = false;
}
void delete_Hash(Hash *h, bool free_values)
{
uint i;
/* Iterate all buckets */
for (i = 0; i < h->num_buckets; i++) {
if (h->buckets_in_use[i]) {
HashNode *node;
/* Free the first value */
if (free_values) free(h->buckets[i].value);
node = h->buckets[i].next;
while (node != NULL) {
HashNode *prev = node;
node = node->next;
/* Free the value */
if (free_values) free(prev->value);
/* Free the node */
free(prev);
}
}
}
free(h->buckets);
/* No need to free buckets_in_use, it is always allocated in one
* malloc with buckets */
#ifdef HASH_DEBUG
debug("Freeing Hash: %p", h);
#endif
}
#ifdef HASH_STATS
static void stat_Hash(const Hash *h)
{
uint used_buckets = 0;
uint max_collision = 0;
uint max_usage = 0;
uint usage[200];
uint i;
for (i = 0; i < lengthof(usage); i++) usage[i] = 0;
for (i = 0; i < h->num_buckets; i++) {
uint collision = 0;
if (h->buckets_in_use[i]) {
const HashNode *node;
used_buckets++;
for (node = &h->buckets[i]; node != NULL; node = node->next) collision++;
if (collision > max_collision) max_collision = collision;
}
if (collision >= lengthof(usage)) collision = lengthof(usage) - 1;
usage[collision]++;
if (collision > 0 && usage[collision] >= max_usage) {
max_usage = usage[collision];
}
}
printf(
"---\n"
"Hash size: %d\n"
"Nodes used: %d\n"
"Non empty buckets: %d\n"
"Max collision: %d\n",
h->num_buckets, h->size, used_buckets, max_collision
);
printf("{ ");
for (i = 0; i <= max_collision; i++) {
if (usage[i] > 0) {
printf("%d:%d ", i, usage[i]);
#if 0
if (i > 0) {
uint j;
for (j = 0; j < usage[i] * 160 / 800; j++) putchar('#');
}
printf("\n");
#endif
}
}
printf ("}\n");
}
#endif
void clear_Hash(Hash *h, bool free_values)
{
uint i;
#ifdef HASH_STATS
if (h->size > 2000) stat_Hash(h);
#endif
/* Iterate all buckets */
for (i = 0; i < h->num_buckets; i++) {
if (h->buckets_in_use[i]) {
HashNode *node;
h->buckets_in_use[i] = false;
/* Free the first value */
if (free_values) free(h->buckets[i].value);
node = h->buckets[i].next;
while (node != NULL) {
HashNode *prev = node;
node = node->next;
if (free_values) free(prev->value);
free(prev);
}
}
}
h->size = 0;
}
/** Finds the node that that saves this key pair. If it is not
* found, returns NULL. If it is found, *prev is set to the
* node before the one found, or if the node found was the first in the bucket
* to NULL. If it is not found, *prev is set to the last HashNode in the
* bucket, or NULL if it is empty. prev can also be NULL, in which case it is
* not used for output.
*/
static HashNode *Hash_FindNode(const Hash *h, uint key1, uint key2, HashNode** prev_out)
{
uint hash = h->hash(key1, key2);
HashNode *result = NULL;
#ifdef HASH_DEBUG
debug("Looking for %u, %u", key1, key2);
#endif
/* Check if the bucket is empty */
if (!h->buckets_in_use[hash]) {
if (prev_out != NULL) *prev_out = NULL;
result = NULL;
/* Check the first node specially */
} else if (h->buckets[hash].key1 == key1 && h->buckets[hash].key2 == key2) {
/* Save the value */
result = h->buckets + hash;
if (prev_out != NULL) *prev_out = NULL;
#ifdef HASH_DEBUG
debug("Found in first node: %p", result);
#endif
/* Check all other nodes */
} else {
HashNode *prev = h->buckets + hash;
HashNode *node;
for (node = prev->next; node != NULL; node = node->next) {
if (node->key1 == key1 && node->key2 == key2) {
/* Found it */
result = node;
#ifdef HASH_DEBUG
debug("Found in other node: %p", result);
#endif
break;
}
prev = node;
}
if (prev_out != NULL) *prev_out = prev;
}
#ifdef HASH_DEBUG
if (result == NULL) debug("Not found");
#endif
return result;
}
void *Hash_Delete(Hash *h, uint key1, uint key2)
{
void *result;
HashNode *prev; // Used as output var for below function call
HashNode *node = Hash_FindNode(h, key1, key2, &prev);
if (node == NULL) {
/* not found */
result = NULL;
} else if (prev == NULL) {
/* It is in the first node, we can't free that one, so we free
* the next one instead (if there is any)*/
/* Save the value */
result = node->value;
if (node->next != NULL) {
HashNode *next = node->next;
/* Copy the second to the first */
*node = *next;
/* Free the second */
#ifndef NOFREE
free(next);
#endif
} else {
/* This was the last in this bucket
* Mark it as empty */
uint hash = h->hash(key1, key2);
h->buckets_in_use[hash] = false;
}
} else {
/* It is in another node
* Save the value */
result = node->value;
/* Link previous and next nodes */
prev->next = node->next;
/* Free the node */
#ifndef NOFREE
free(node);
#endif
}
if (result != NULL) h->size--;
return result;
}
void *Hash_Set(Hash *h, uint key1, uint key2, void *value)
{
HashNode *prev;
HashNode *node = Hash_FindNode(h, key1, key2, &prev);
if (node != NULL) {
/* Found it */
void *result = node->value;
node->value = value;
return result;
}
/* It is not yet present, let's add it */
if (prev == NULL) {
/* The bucket is still empty */
uint hash = h->hash(key1, key2);
h->buckets_in_use[hash] = true;
node = h->buckets + hash;
} else {
/* Add it after prev */
node = MallocT<HashNode>(1);
prev->next = node;
}
node->next = NULL;
node->key1 = key1;
node->key2 = key2;
node->value = value;
h->size++;
return NULL;
}
void *Hash_Get(const Hash *h, uint key1, uint key2)
{
HashNode *node = Hash_FindNode(h, key1, key2, NULL);
#ifdef HASH_DEBUG
debug("Found node: %p", node);
#endif
return (node != NULL) ? node->value : NULL;
}
uint Hash_Size(const Hash *h)
{
return h->size;
}
| 14,589
|
C++
|
.cpp
| 498
| 26.662651
| 134
| 0.654968
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,080
|
engine_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/engine_gui.cpp
|
/* $Id$ */
/** @file engine_gui.cpp GUI to show engine related information. */
#include "stdafx.h"
#include "window_gui.h"
#include "gfx_func.h"
#include "engine_func.h"
#include "engine_base.h"
#include "command_func.h"
#include "news_type.h"
#include "newgrf_engine.h"
#include "strings_func.h"
#include "engine_gui.h"
#include "articulated_vehicles.h"
#include "rail.h"
#include "table/strings.h"
#include "table/sprites.h"
StringID GetEngineCategoryName(EngineID engine)
{
switch (GetEngine(engine)->type) {
default: NOT_REACHED();
case VEH_ROAD: return STR_8103_ROAD_VEHICLE;
case VEH_AIRCRAFT: return STR_8104_AIRCRAFT;
case VEH_SHIP: return STR_8105_SHIP;
case VEH_TRAIN:
return GetRailTypeInfo(RailVehInfo(engine)->railtype)->strings.new_loco;
}
}
static const Widget _engine_preview_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_LIGHT_BLUE, 11, 299, 0, 13, STR_8100_MESSAGE_FROM_VEHICLE_MANUFACTURE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 299, 14, 191, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 85, 144, 172, 183, STR_00C9_NO, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 155, 214, 172, 183, STR_00C8_YES, STR_NULL},
{ WIDGETS_END},
};
typedef void DrawEngineProc(int x, int y, EngineID engine, SpriteID pal);
typedef void DrawEngineInfoProc(EngineID, int x, int y, int maxw);
struct DrawEngineInfo {
DrawEngineProc *engine_proc;
DrawEngineInfoProc *info_proc;
};
static void DrawTrainEngineInfo(EngineID engine, int x, int y, int maxw);
static void DrawRoadVehEngineInfo(EngineID engine, int x, int y, int maxw);
static void DrawShipEngineInfo(EngineID engine, int x, int y, int maxw);
static void DrawAircraftEngineInfo(EngineID engine, int x, int y, int maxw);
static const DrawEngineInfo _draw_engine_list[4] = {
{ DrawTrainEngine, DrawTrainEngineInfo },
{ DrawRoadVehEngine, DrawRoadVehEngineInfo },
{ DrawShipEngine, DrawShipEngineInfo },
{ DrawAircraftEngine, DrawAircraftEngineInfo },
};
struct EnginePreviewWindow : Window {
EnginePreviewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
EngineID engine = this->window_number;
SetDParam(0, GetEngineCategoryName(engine));
DrawStringMultiCenter(150, 44, STR_8101_WE_HAVE_JUST_DESIGNED_A, 296);
SetDParam(0, engine);
DrawStringCentered(this->width >> 1, 80, STR_ENGINE_NAME, TC_BLACK);
const DrawEngineInfo *dei = &_draw_engine_list[GetEngine(engine)->type];
int width = this->width;
dei->engine_proc(width >> 1, 100, engine, 0);
dei->info_proc(engine, width >> 1, 130, width - 52);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case 4:
DoCommandP(0, this->window_number, 0, CMD_WANT_ENGINE_PREVIEW);
/* Fallthrough */
case 3:
delete this;
break;
}
}
};
static const WindowDesc _engine_preview_desc(
WDP_CENTER, WDP_CENTER, 300, 192, 300, 192,
WC_ENGINE_PREVIEW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_engine_preview_widgets
);
void ShowEnginePreviewWindow(EngineID engine)
{
AllocateWindowDescFront<EnginePreviewWindow>(&_engine_preview_desc, engine);
}
uint GetTotalCapacityOfArticulatedParts(EngineID engine, VehicleType type)
{
uint total = 0;
uint16 *cap = GetCapacityOfArticulatedParts(engine, type);
for (uint c = 0; c < NUM_CARGO; c++) {
total += cap[c];
}
return total;
}
static void DrawTrainEngineInfo(EngineID engine, int x, int y, int maxw)
{
const Engine *e = GetEngine(engine);
SetDParam(0, e->GetCost());
SetDParam(2, e->GetDisplayMaxSpeed());
SetDParam(3, e->GetPower());
SetDParam(1, e->GetDisplayWeight());
SetDParam(4, e->GetRunningCost());
uint capacity = GetTotalCapacityOfArticulatedParts(engine, VEH_TRAIN);
if (capacity != 0) {
SetDParam(5, e->GetDefaultCargoType());
SetDParam(6, capacity);
} else {
SetDParam(5, CT_INVALID);
}
DrawStringMultiCenter(x, y, STR_VEHICLE_INFO_COST_WEIGHT_SPEED_POWER, maxw);
}
static void DrawAircraftEngineInfo(EngineID engine, int x, int y, int maxw)
{
const Engine *e = GetEngine(engine);
CargoID cargo = e->GetDefaultCargoType();
if (cargo == CT_INVALID || cargo == CT_PASSENGERS) {
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
SetDParam(2, e->GetDisplayDefaultCapacity());
SetDParam(3, e->u.air.mail_capacity);
SetDParam(4, e->GetRunningCost());
DrawStringMultiCenter(x, y, STR_A02E_COST_MAX_SPEED_CAPACITY, maxw);
} else {
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
SetDParam(2, cargo);
SetDParam(3, e->GetDisplayDefaultCapacity());
SetDParam(4, e->GetRunningCost());
DrawStringMultiCenter(x, y, STR_982E_COST_MAX_SPEED_CAPACITY, maxw);
}
}
static void DrawRoadVehEngineInfo(EngineID engine, int x, int y, int maxw)
{
const Engine *e = GetEngine(engine);
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
SetDParam(2, e->GetRunningCost());
uint capacity = GetTotalCapacityOfArticulatedParts(engine, VEH_ROAD);
if (capacity != 0) {
SetDParam(3, e->GetDefaultCargoType());
SetDParam(4, capacity);
} else {
SetDParam(3, CT_INVALID);
}
DrawStringMultiCenter(x, y, STR_902A_COST_SPEED_RUNNING_COST, maxw);
}
static void DrawShipEngineInfo(EngineID engine, int x, int y, int maxw)
{
const Engine *e = GetEngine(engine);
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
SetDParam(2, e->GetDefaultCargoType());
SetDParam(3, e->GetDisplayDefaultCapacity());
SetDParam(4, e->GetRunningCost());
DrawStringMultiCenter(x, y, STR_982E_COST_MAX_SPEED_CAPACITY, maxw);
}
void DrawNewsNewVehicleAvail(Window *w, const NewsItem *ni)
{
EngineID engine = ni->data_a;
const DrawEngineInfo *dei = &_draw_engine_list[GetEngine(engine)->type];
SetDParam(0, GetEngineCategoryName(engine));
DrawStringMultiCenter(w->width >> 1, 20, STR_NEW_VEHICLE_NOW_AVAILABLE, w->width - 2);
GfxFillRect(25, 56, w->width - 25, w->height - 2, 10);
SetDParam(0, engine);
DrawStringMultiCenter(w->width >> 1, 57, STR_NEW_VEHICLE_TYPE, w->width - 2);
dei->engine_proc(w->width >> 1, 88, engine, 0);
GfxFillRect(25, 56, w->width - 56, 112, PALETTE_TO_STRUCT_GREY, FILLRECT_RECOLOUR);
dei->info_proc(engine, w->width >> 1, 129, w->width - 52);
}
/** Sort all items using qsort() and given 'CompareItems' function
* @param el list to be sorted
* @param compare function for evaluation of the quicksort
*/
void EngList_Sort(GUIEngineList *el, EngList_SortTypeFunction compare)
{
uint size = el->Length();
/* out-of-bounds access at the next line for size == 0 (even with operator[] at some systems)
* generally, do not sort if there are less than 2 items */
if (size < 2) return;
qsort(el->Begin(), size, sizeof(*el->Begin()), compare); // MorphOS doesn't know vector::at(int) ...
}
/** Sort selected range of items (on indices @ <begin, begin+num_items-1>)
* @param el list to be sorted
* @param compare function for evaluation of the quicksort
* @param begin start of sorting
* @param num_items count of items to be sorted
*/
void EngList_SortPartial(GUIEngineList *el, EngList_SortTypeFunction compare, uint begin, uint num_items)
{
if (num_items < 2) return;
assert(begin < el->Length());
assert(begin + num_items <= el->Length());
qsort(el->Get(begin), num_items, sizeof(*el->Begin()), compare);
}
| 7,802
|
C++
|
.cpp
| 200
| 36.86
| 152
| 0.713284
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,081
|
settings_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/settings_gui.cpp
|
/* $Id$ */
/** @file settings_gui.cpp GUI for settings. */
#include "stdafx.h"
#include "openttd.h"
#include "currency.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "engine_func.h"
#include "screenshot.h"
#include "network/network.h"
#include "town.h"
#include "variables.h"
#include "settings_internal.h"
#include "newgrf_townname.h"
#include "strings_func.h"
#include "window_func.h"
#include "string_func.h"
#include "gfx_func.h"
#include "waypoint.h"
#include "widgets/dropdown_type.h"
#include "widgets/dropdown_func.h"
#include "station_func.h"
#include "highscore.h"
#include "gfxinit.h"
#include <map>
#include "table/sprites.h"
#include "table/strings.h"
static const StringID _units_dropdown[] = {
STR_UNITS_IMPERIAL,
STR_UNITS_METRIC,
STR_UNITS_SI,
INVALID_STRING_ID
};
static const StringID _driveside_dropdown[] = {
STR_02E9_DRIVE_ON_LEFT,
STR_02EA_DRIVE_ON_RIGHT,
INVALID_STRING_ID
};
static const StringID _autosave_dropdown[] = {
STR_02F7_OFF,
STR_AUTOSAVE_1_MONTH,
STR_02F8_EVERY_3_MONTHS,
STR_02F9_EVERY_6_MONTHS,
STR_02FA_EVERY_12_MONTHS,
INVALID_STRING_ID,
};
static StringID *BuildDynamicDropdown(StringID base, int num)
{
static StringID buf[32 + 1];
StringID *p = buf;
while (--num >= 0) *p++ = base++;
*p = INVALID_STRING_ID;
return buf;
}
int _nb_orig_names = SPECSTR_TOWNNAME_LAST - SPECSTR_TOWNNAME_START + 1;
static StringID *_grf_names = NULL;
static int _nb_grf_names = 0;
void InitGRFTownGeneratorNames()
{
free(_grf_names);
_grf_names = GetGRFTownNameList();
_nb_grf_names = 0;
for (StringID *s = _grf_names; *s != INVALID_STRING_ID; s++) _nb_grf_names++;
}
static inline StringID TownName(int town_name)
{
if (town_name < _nb_orig_names) return STR_TOWNNAME_ORIGINAL_ENGLISH + town_name;
town_name -= _nb_orig_names;
if (town_name < _nb_grf_names) return _grf_names[town_name];
return STR_UNDEFINED;
}
static int GetCurRes()
{
int i;
for (i = 0; i != _num_resolutions; i++) {
if (_resolutions[i].width == _screen.width &&
_resolutions[i].height == _screen.height) {
break;
}
}
return i;
}
enum GameOptionsWidgets {
GAMEOPT_CURRENCY_BTN = 4,
GAMEOPT_DISTANCE_BTN = 6,
GAMEOPT_ROADSIDE_BTN = 8,
GAMEOPT_TOWNNAME_BTN = 10,
GAMEOPT_AUTOSAVE_BTN = 12,
GAMEOPT_LANG_BTN = 14,
GAMEOPT_RESOLUTION_BTN = 16,
GAMEOPT_FULLSCREEN,
GAMEOPT_SCREENSHOT_BTN = 19,
GAMEOPT_BASE_GRF_BTN = 21,
};
/**
* Update/redraw the townnames dropdown
* @param w the window the dropdown belongs to
* @param sel the currently selected townname generator
*/
static void ShowTownnameDropdown(Window *w, int sel)
{
typedef std::map<StringID, int, StringIDCompare> TownList;
TownList townnames;
/* Add and sort original townnames generators */
for (int i = 0; i < _nb_orig_names; i++) townnames[STR_TOWNNAME_ORIGINAL_ENGLISH + i] = i;
/* Add and sort newgrf townnames generators */
for (int i = 0; i < _nb_grf_names; i++) townnames[_grf_names[i]] = _nb_orig_names + i;
DropDownList *list = new DropDownList();
for (TownList::iterator it = townnames.begin(); it != townnames.end(); it++) {
list->push_back(new DropDownListStringItem((*it).first, (*it).second, !(_game_mode == GM_MENU || GetNumTowns() == 0 || (*it).second == sel)));
}
ShowDropDownList(w, list, sel, GAMEOPT_TOWNNAME_BTN);
}
static void ShowCustCurrency();
static void ShowGraphicsSetMenu(Window *w)
{
int n = GetNumGraphicsSets();
int current = GetIndexOfCurrentGraphicsSet();
DropDownList *list = new DropDownList();
for (int i = 0; i < n; i++) {
list->push_back(new DropDownListCharStringItem(GetGraphicsSetName(i), i, (_game_mode == GM_MENU) ? false : (current != i)));
}
ShowDropDownList(w, list, current, GAMEOPT_BASE_GRF_BTN);
}
struct GameOptionsWindow : Window {
GameSettings *opt;
bool reload;
GameOptionsWindow(const WindowDesc *desc) : Window(desc)
{
this->opt = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;
this->reload = false;
this->FindWindowPlacementAndResize(desc);
}
~GameOptionsWindow()
{
DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
if (this->reload) _switch_mode = SM_MENU;
}
virtual void OnPaint()
{
SetDParam(1, _currency_specs[this->opt->locale.currency].name);
SetDParam(2, STR_UNITS_IMPERIAL + this->opt->locale.units);
SetDParam(3, STR_02E9_DRIVE_ON_LEFT + this->opt->vehicle.road_side);
SetDParam(4, TownName(this->opt->game_creation.town_name));
SetDParam(5, _autosave_dropdown[_settings_client.gui.autosave]);
SetDParam(6, SPECSTR_LANGUAGE_START + _dynlang.curr);
int i = GetCurRes();
SetDParam(7, i == _num_resolutions ? STR_RES_OTHER : SPECSTR_RESOLUTION_START + i);
SetDParam(8, SPECSTR_SCREENSHOT_START + _cur_screenshot_format);
this->SetWidgetLoweredState(GAMEOPT_FULLSCREEN, _fullscreen);
SetDParamStr(9, GetGraphicsSetName(GetIndexOfCurrentGraphicsSet()));
this->DrawWidgets();
DrawString(20, 175, STR_OPTIONS_FULLSCREEN, TC_FROMSTRING); // fullscreen
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case GAMEOPT_CURRENCY_BTN: // Setup currencies dropdown
ShowDropDownMenu(this, BuildCurrencyDropdown(), this->opt->locale.currency, GAMEOPT_CURRENCY_BTN, _game_mode == GM_MENU ? 0 : ~GetMaskOfAllowedCurrencies(), 0);
break;
case GAMEOPT_DISTANCE_BTN: // Setup distance unit dropdown
ShowDropDownMenu(this, _units_dropdown, this->opt->locale.units, GAMEOPT_DISTANCE_BTN, 0, 0);
break;
case GAMEOPT_ROADSIDE_BTN: { // Setup road-side dropdown
int i = 0;
extern bool RoadVehiclesAreBuilt();
/* You can only change the drive side if you are in the menu or ingame with
* no vehicles present. In a networking game only the server can change it */
if ((_game_mode != GM_MENU && RoadVehiclesAreBuilt()) || (_networking && !_network_server)) {
i = (-1) ^ (1 << this->opt->vehicle.road_side); // disable the other value
}
ShowDropDownMenu(this, _driveside_dropdown, this->opt->vehicle.road_side, GAMEOPT_ROADSIDE_BTN, i, 0);
} break;
case GAMEOPT_TOWNNAME_BTN: // Setup townname dropdown
ShowTownnameDropdown(this, this->opt->game_creation.town_name);
break;
case GAMEOPT_AUTOSAVE_BTN: // Setup autosave dropdown
ShowDropDownMenu(this, _autosave_dropdown, _settings_client.gui.autosave, GAMEOPT_AUTOSAVE_BTN, 0, 0);
break;
case GAMEOPT_LANG_BTN: { // Setup interface language dropdown
typedef std::map<StringID, int, StringIDCompare> LangList;
/* Sort language names */
LangList langs;
for (int i = 0; i < _dynlang.num; i++) langs[SPECSTR_LANGUAGE_START + i] = i;
DropDownList *list = new DropDownList();
for (LangList::iterator it = langs.begin(); it != langs.end(); it++) {
list->push_back(new DropDownListStringItem((*it).first, (*it).second, false));
}
ShowDropDownList(this, list, _dynlang.curr, GAMEOPT_LANG_BTN);
} break;
case GAMEOPT_RESOLUTION_BTN: // Setup resolution dropdown
ShowDropDownMenu(this, BuildDynamicDropdown(SPECSTR_RESOLUTION_START, _num_resolutions), GetCurRes(), GAMEOPT_RESOLUTION_BTN, 0, 0);
break;
case GAMEOPT_FULLSCREEN: // Click fullscreen on/off
/* try to toggle full-screen on/off */
if (!ToggleFullScreen(!_fullscreen)) {
ShowErrorMessage(INVALID_STRING_ID, STR_FULLSCREEN_FAILED, 0, 0);
}
this->SetWidgetLoweredState(GAMEOPT_FULLSCREEN, _fullscreen);
this->SetDirty();
break;
case GAMEOPT_SCREENSHOT_BTN: // Setup screenshot format dropdown
ShowDropDownMenu(this, BuildDynamicDropdown(SPECSTR_SCREENSHOT_START, _num_screenshot_formats), _cur_screenshot_format, GAMEOPT_SCREENSHOT_BTN, 0, 0);
break;
case GAMEOPT_BASE_GRF_BTN:
ShowGraphicsSetMenu(this);
break;
}
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case GAMEOPT_CURRENCY_BTN: // Currency
if (index == CUSTOM_CURRENCY_ID) ShowCustCurrency();
this->opt->locale.currency = index;
MarkWholeScreenDirty();
break;
case GAMEOPT_DISTANCE_BTN: // Measuring units
this->opt->locale.units = index;
MarkWholeScreenDirty();
break;
case GAMEOPT_ROADSIDE_BTN: // Road side
if (this->opt->vehicle.road_side != index) { // only change if setting changed
uint i;
if (GetSettingFromName("vehicle.road_side", &i) == NULL) NOT_REACHED();
SetSettingValue(i, index);
MarkWholeScreenDirty();
}
break;
case GAMEOPT_TOWNNAME_BTN: // Town names
if (_game_mode == GM_MENU || GetNumTowns() == 0) {
this->opt->game_creation.town_name = index;
InvalidateWindow(WC_GAME_OPTIONS, 0);
}
break;
case GAMEOPT_AUTOSAVE_BTN: // Autosave options
_settings_client.gui.autosave = index;
this->SetDirty();
break;
case GAMEOPT_LANG_BTN: // Change interface language
ReadLanguagePack(index);
CheckForMissingGlyphsInLoadedLanguagePack();
UpdateAllStationVirtCoord();
UpdateAllWaypointSigns();
MarkWholeScreenDirty();
break;
case GAMEOPT_RESOLUTION_BTN: // Change resolution
if (index < _num_resolutions && ChangeResInGame(_resolutions[index].width, _resolutions[index].height)) {
this->SetDirty();
}
break;
case GAMEOPT_SCREENSHOT_BTN: // Change screenshot format
SetScreenshotFormat(index);
this->SetDirty();
break;
case GAMEOPT_BASE_GRF_BTN:
if (_game_mode == GM_MENU) {
const char *name = GetGraphicsSetName(index);
free(_ini_graphics_set);
_ini_graphics_set = strdup(name);
SetGraphicsSet(name);
this->reload = true;
}
break;
}
}
};
static const Widget _game_options_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 369, 0, 13, STR_00B1_GAME_OPTIONS, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 369, 14, 242, 0x0, STR_NULL},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 10, 179, 20, 55, STR_02E0_CURRENCY_UNITS, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 20, 169, 34, 45, STR_02E1, STR_02E2_CURRENCY_UNITS_SELECTION},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 190, 359, 20, 55, STR_MEASURING_UNITS, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 200, 349, 34, 45, STR_02E4, STR_MEASURING_UNITS_SELECTION},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 10, 179, 62, 97, STR_02E6_ROAD_VEHICLES, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 20, 169, 76, 87, STR_02E7, STR_02E8_SELECT_SIDE_OF_ROAD_FOR},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 190, 359, 62, 97, STR_02EB_TOWN_NAMES, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 200, 349, 76, 87, STR_02EC, STR_02ED_SELECT_STYLE_OF_TOWN_NAMES},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 10, 179, 104, 139, STR_02F4_AUTOSAVE, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 20, 169, 118, 129, STR_02F5, STR_02F6_SELECT_INTERVAL_BETWEEN},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 190, 359, 104, 139, STR_OPTIONS_LANG, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 200, 349, 118, 129, STR_OPTIONS_LANG_CBO, STR_OPTIONS_LANG_TIP},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 10, 179, 146, 190, STR_OPTIONS_RES, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 20, 169, 160, 171, STR_OPTIONS_RES_CBO, STR_OPTIONS_RES_TIP},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 149, 169, 176, 184, STR_EMPTY, STR_OPTIONS_FULLSCREEN_TIP},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 190, 359, 146, 190, STR_OPTIONS_SCREENSHOT_FORMAT, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 200, 349, 160, 171, STR_OPTIONS_SCREENSHOT_FORMAT_CBO, STR_OPTIONS_SCREENSHOT_FORMAT_TIP},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 10, 179, 197, 232, STR_OPTIONS_BASE_GRF, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_GREY, 20, 169, 211, 222, STR_OPTIONS_BASE_GRF_CBO, STR_OPTIONS_BASE_GRF_TIP},
{ WIDGETS_END},
};
static const WindowDesc _game_options_desc(
WDP_CENTER, WDP_CENTER, 370, 243, 370, 243,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_game_options_widgets
);
void ShowGameOptions()
{
DeleteWindowById(WC_GAME_OPTIONS, 0);
new GameOptionsWindow(&_game_options_desc);
}
extern void StartupEconomy();
/* Widget definition for the game difficulty settings window */
#if N3DS
static const Widget _game_difficulty_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_MAUVE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // GDW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_MAUVE, 11, 369, 0, 13, STR_6800_DIFFICULTY_LEVEL, STR_018C_WINDOW_TITLE_DRAG_THIS}, // GDW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_MAUVE, 0, 369, 14, 41, 0x0, STR_NULL}, // GDW_UPPER_BG
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 10, 96, 16, 27, STR_6801_EASY, STR_NULL}, // GDW_LVL_EASY
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 97, 183, 16, 27, STR_6802_MEDIUM, STR_NULL}, // GDW_LVL_MEDIUM
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 184, 270, 16, 27, STR_6803_HARD, STR_NULL}, // GDW_LVL_HARD
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 271, 357, 16, 27, STR_6804_CUSTOM, STR_NULL}, // GDW_LVL_CUSTOM
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREEN, 10, 357, 28, 39, STR_6838_SHOW_HI_SCORE_CHART, STR_NULL}, // GDW_HIGHSCORE
{ WWT_PANEL, RESIZE_NONE, COLOUR_MAUVE, 0, 369, 42, 223, 0x0, STR_NULL}, // GDW_SETTING_BG
{ WWT_PANEL, RESIZE_NONE, COLOUR_MAUVE, 0, 369, 224, 239, 0x0, STR_NULL}, // GDW_LOWER_BG
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 105, 185, 226, 237, STR_OPTIONS_SAVE_CHANGES, STR_NULL}, // GDW_ACCEPT
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 186, 266, 226, 237, STR_012E_CANCEL, STR_NULL}, // GDW_CANCEL
{ WIDGETS_END},
};
#else
static const Widget _game_difficulty_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_MAUVE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // GDW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_MAUVE, 11, 369, 0, 13, STR_6800_DIFFICULTY_LEVEL, STR_018C_WINDOW_TITLE_DRAG_THIS}, // GDW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_MAUVE, 0, 369, 14, 41, 0x0, STR_NULL}, // GDW_UPPER_BG
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 10, 96, 16, 27, STR_6801_EASY, STR_NULL}, // GDW_LVL_EASY
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 97, 183, 16, 27, STR_6802_MEDIUM, STR_NULL}, // GDW_LVL_MEDIUM
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 184, 270, 16, 27, STR_6803_HARD, STR_NULL}, // GDW_LVL_HARD
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 271, 357, 16, 27, STR_6804_CUSTOM, STR_NULL}, // GDW_LVL_CUSTOM
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREEN, 10, 357, 28, 39, STR_6838_SHOW_HI_SCORE_CHART, STR_NULL}, // GDW_HIGHSCORE
{ WWT_PANEL, RESIZE_NONE, COLOUR_MAUVE, 0, 369, 42, 262, 0x0, STR_NULL}, // GDW_SETTING_BG
{ WWT_PANEL, RESIZE_NONE, COLOUR_MAUVE, 0, 369, 263, 278, 0x0, STR_NULL}, // GDW_LOWER_BG
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 105, 185, 265, 276, STR_OPTIONS_SAVE_CHANGES, STR_NULL}, // GDW_ACCEPT
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 186, 266, 265, 276, STR_012E_CANCEL, STR_NULL}, // GDW_CANCEL
{ WIDGETS_END},
};
#endif
/* Window definition for the game difficulty settings window */
#ifdef N3DS
static const WindowDesc _game_difficulty_desc(
WDP_CENTER, WDP_CENTER, 370, 240, 370, 240,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_game_difficulty_widgets
);
#else
static const WindowDesc _game_difficulty_desc(
WDP_CENTER, WDP_CENTER, 370, 279, 370, 279,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_game_difficulty_widgets
);
#endif
void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
struct GameDifficultyWindow : public Window {
private:
static const uint GAME_DIFFICULTY_NUM = 18;
bool clicked_increase;
uint8 clicked_button;
uint8 timeout;
/* Temporary holding place of values in the difficulty window until 'Save' is clicked */
GameSettings opt_mod_temp;
enum {
GAMEDIFF_WND_TOP_OFFSET = 45,
GAMEDIFF_WND_ROWSIZE = 9,
NO_SETTINGS_BUTTON = 0xFF,
};
/* Names of the game difficulty settings window */
enum GameDifficultyWidgets {
GDW_CLOSEBOX = 0,
GDW_CAPTION,
GDW_UPPER_BG,
GDW_LVL_EASY,
GDW_LVL_MEDIUM,
GDW_LVL_HARD,
GDW_LVL_CUSTOM,
GDW_HIGHSCORE,
GDW_SETTING_BG,
GDW_LOWER_BG,
GDW_ACCEPT,
GDW_CANCEL,
};
public:
GameDifficultyWindow() : Window(&_game_difficulty_desc)
{
/* Copy current settings (ingame or in intro) to temporary holding place
* change that when setting stuff, copy back on clicking 'OK' */
this->opt_mod_temp = (_game_mode == GM_MENU) ? _settings_newgame : _settings_game;
this->clicked_increase = false;
this->clicked_button = NO_SETTINGS_BUTTON;
this->timeout = 0;
/* Hide the closebox to make sure that the user aborts or confirms his changes */
this->HideWidget(GDW_CLOSEBOX);
this->widget[GDW_CAPTION].left = 0;
/* Setup disabled buttons when creating window
* disable all other difficulty buttons during gameplay except for 'custom' */
this->SetWidgetsDisabledState(_game_mode == GM_NORMAL,
GDW_LVL_EASY,
GDW_LVL_MEDIUM,
GDW_LVL_HARD,
GDW_LVL_CUSTOM,
WIDGET_LIST_END);
this->SetWidgetDisabledState(GDW_HIGHSCORE, _game_mode == GM_EDITOR || _networking); // highscore chart in multiplayer
this->SetWidgetDisabledState(GDW_ACCEPT, _networking && !_network_server); // Save-button in multiplayer (and if client)
this->LowerWidget(GDW_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
this->FindWindowPlacementAndResize(&_game_difficulty_desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
uint i;
const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
int y = GAMEDIFF_WND_TOP_OFFSET;
StringID str = STR_6805_MAXIMUM_NO_COMPETITORS;
for (i = 0; i < GAME_DIFFICULTY_NUM; i++, sd++) {
const SettingDescBase *sdb = &sd->desc;
/* skip deprecated difficulty options */
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
int32 value = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
bool editable = (_game_mode == GM_MENU || (sdb->flags & SGF_NEWGAME_ONLY) == 0);
DrawArrowButtons(5, y, COLOUR_YELLOW,
(this->clicked_button == i) ? 1 + !!this->clicked_increase : 0,
editable && sdb->min != value,
editable && sdb->max != value);
value += sdb->str;
SetDParam(0, value);
DrawString(30, y, str, TC_FROMSTRING);
y += GAMEDIFF_WND_ROWSIZE + 2; // space items apart a bit
str++;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case GDW_SETTING_BG: { // Difficulty settings widget, decode click
/* Don't allow clients to make any changes */
if (_networking && !_network_server) return;
const int x = pt.x - 5;
if (!IsInsideMM(x, 0, 21)) return; // Button area
const int y = pt.y - GAMEDIFF_WND_TOP_OFFSET;
if (y < 0) return;
/* Get button from Y coord. */
uint8 btn = y / (GAMEDIFF_WND_ROWSIZE + 2);
if (btn >= 1) btn++; // Skip the deprecated option "competitor start time"
if (btn >= 8) btn++; // Skip the deprecated option "competitor intelligence"
if (btn >= GAME_DIFFICULTY_NUM || y % (GAMEDIFF_WND_ROWSIZE + 2) >= 9) return;
uint i;
const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i) + btn;
const SettingDescBase *sdb = &sd->desc;
/* Clicked disabled button? */
bool editable = (_game_mode == GM_MENU || (sdb->flags & SGF_NEWGAME_ONLY) == 0);
if (!editable) return;
this->timeout = 5;
int32 val = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
if (x >= 10) {
/* Increase button clicked */
val = min(val + sdb->interval, sdb->max);
this->clicked_increase = true;
} else {
/* Decrease button clicked */
val -= sdb->interval;
val = max(val, sdb->min);
this->clicked_increase = false;
}
this->clicked_button = btn;
/* save value in temporary variable */
WriteValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv, val);
this->RaiseWidget(GDW_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
SetDifficultyLevel(3, &this->opt_mod_temp.difficulty); // set difficulty level to custom
this->LowerWidget(GDW_LVL_CUSTOM);
this->SetDirty();
} break;
case GDW_LVL_EASY:
case GDW_LVL_MEDIUM:
case GDW_LVL_HARD:
case GDW_LVL_CUSTOM:
/* temporarily change difficulty level */
this->RaiseWidget(GDW_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
SetDifficultyLevel(widget - GDW_LVL_EASY, &this->opt_mod_temp.difficulty);
this->LowerWidget(GDW_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
this->SetDirty();
break;
case GDW_HIGHSCORE: // Highscore Table
ShowHighscoreTable(this->opt_mod_temp.difficulty.diff_level, -1);
break;
case GDW_ACCEPT: { // Save button - save changes
GameSettings *opt_ptr = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;
uint i;
const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
for (uint btn = 0; btn != GAME_DIFFICULTY_NUM; btn++, sd++) {
int32 new_val = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
int32 cur_val = (int32)ReadValue(GetVariableAddress(opt_ptr, &sd->save), sd->save.conv);
/* if setting has changed, change it */
if (new_val != cur_val) {
DoCommandP(0, i + btn, new_val, CMD_CHANGE_SETTING);
}
}
GetSettingFromName("difficulty.diff_level", &i);
DoCommandP(0, i, this->opt_mod_temp.difficulty.diff_level, CMD_CHANGE_SETTING);
delete this;
/* If we are in the editor, we should reload the economy.
* This way when you load a game, the max loan and interest rate
* are loaded correctly. */
if (_game_mode == GM_EDITOR) StartupEconomy();
break;
}
case GDW_CANCEL: // Cancel button - close window, abandon changes
delete this;
break;
}
}
virtual void OnTick()
{
if (this->timeout != 0) {
this->timeout--;
if (this->timeout == 0) this->clicked_button = NO_SETTINGS_BUTTON;
this->SetDirty();
}
}
};
void ShowGameDifficulty()
{
DeleteWindowById(WC_GAME_OPTIONS, 0);
new GameDifficultyWindow();
}
static const int SETTING_HEIGHT = 11; ///< Height of a single setting in the tree view in pixels
static const int LEVEL_WIDTH = 15; ///< Indenting width of a sub-page in pixels
/**
* Flags for #SettingEntry
* @note The #SEF_BUTTONS_MASK matches expectations of the formal parameter 'state' of #DrawArrowButtons
*/
enum SettingEntryFlags {
SEF_LEFT_DEPRESSED = 0x01, ///< Of a numeric setting entry, the left button is depressed
SEF_RIGHT_DEPRESSED = 0x02, ///< Of a numeric setting entry, the right button is depressed
SEF_BUTTONS_MASK = (SEF_LEFT_DEPRESSED | SEF_RIGHT_DEPRESSED), ///< Bit-mask for button flags
SEF_LAST_FIELD = 0x04, ///< This entry is the last one in a (sub-)page
/* Entry kind */
SEF_SETTING_KIND = 0x10, ///< Entry kind: Entry is a setting
SEF_SUBTREE_KIND = 0x20, ///< Entry kind: Entry is a sub-tree
SEF_KIND_MASK = (SEF_SETTING_KIND | SEF_SUBTREE_KIND), ///< Bit-mask for fetching entry kind
};
struct SettingsPage; // Forward declaration
/** Data fields for a sub-page (#SEF_SUBTREE_KIND kind)*/
struct SettingEntrySubtree {
SettingsPage *page; ///< Pointer to the sub-page
bool folded; ///< Sub-page is folded (not visible except for its title)
StringID title; ///< Title of the sub-page
};
/** Data fields for a single setting (#SEF_SETTING_KIND kind) */
struct SettingEntrySetting {
const char *name; ///< Name of the setting
const SettingDesc *setting; ///< Setting description of the setting
uint index; ///< Index of the setting in the settings table
};
/** Data structure describing a single setting in a tab */
struct SettingEntry {
byte flags; ///< Flags of the setting entry. @see SettingEntryFlags
byte level; ///< Nesting level of this setting entry
union {
SettingEntrySetting entry; ///< Data fields if entry is a setting
SettingEntrySubtree sub; ///< Data fields if entry is a sub-page
} d; ///< Data fields for each kind
SettingEntry(const char *nm);
SettingEntry(SettingsPage *sub, StringID title);
void Init(byte level, bool last_field);
void FoldAll();
void SetButtons(byte new_val);
uint Length() const;
SettingEntry *FindEntry(uint row, uint *cur_row);
uint Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row, uint parent_last);
private:
void DrawSetting(GameSettings *settings_ptr, const SettingDesc *sd, int x, int y, int max_x, int state);
};
/** Data structure describing one page of settings in the settings window. */
struct SettingsPage {
SettingEntry *entries; ///< Array of setting entries of the page.
byte num; ///< Number of entries on the page (statically filled).
void Init(byte level = 0);
void FoldAll();
uint Length() const;
SettingEntry *FindEntry(uint row, uint *cur_row) const;
uint Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row = 0, uint parent_last = 0) const;
};
/* == SettingEntry methods == */
/**
* Constructor for a single setting in the 'advanced settings' window
* @param nm Name of the setting in the setting table
*/
SettingEntry::SettingEntry(const char *nm)
{
this->flags = SEF_SETTING_KIND;
this->level = 0;
this->d.entry.name = nm;
this->d.entry.setting = NULL;
this->d.entry.index = 0;
}
/**
* Constructor for a sub-page in the 'advanced settings' window
* @param sub Sub-page
* @param title Title of the sub-page
*/
SettingEntry::SettingEntry(SettingsPage *sub, StringID title)
{
this->flags = SEF_SUBTREE_KIND;
this->level = 0;
this->d.sub.page = sub;
this->d.sub.folded = true;
this->d.sub.title = title;
}
/**
* Initialization of a setting entry
* @param level Page nesting level of this entry
* @param last_field Boolean indicating this entry is the last at the (sub-)page
*/
void SettingEntry::Init(byte level, bool last_field)
{
this->level = level;
if (last_field) this->flags |= SEF_LAST_FIELD;
switch (this->flags & SEF_KIND_MASK) {
case SEF_SETTING_KIND:
this->d.entry.setting = GetSettingFromName(this->d.entry.name, &this->d.entry.index);
assert(this->d.entry.setting != NULL);
break;
case SEF_SUBTREE_KIND:
this->d.sub.page->Init(level + 1);
break;
default: NOT_REACHED();
}
}
/** Recursively close all folds of sub-pages */
void SettingEntry::FoldAll()
{
switch(this->flags & SEF_KIND_MASK) {
case SEF_SETTING_KIND:
break;
case SEF_SUBTREE_KIND:
this->d.sub.folded = true;
this->d.sub.page->FoldAll();
break;
default: NOT_REACHED();
}
}
/**
* Set the button-depressed flags (#SEF_LEFT_DEPRESSED and #SEF_RIGHT_DEPRESSED) to a specified value
* @param new_val New value for the button flags
* @see SettingEntryFlags
*/
void SettingEntry::SetButtons(byte new_val)
{
assert((new_val & ~SEF_BUTTONS_MASK) == 0); // Should not touch any flags outside the buttons
this->flags = (this->flags & ~SEF_BUTTONS_MASK) | new_val;
}
/** Return numbers of rows needed to display the entry */
uint SettingEntry::Length() const
{
switch (this->flags & SEF_KIND_MASK) {
case SEF_SETTING_KIND:
return 1;
case SEF_SUBTREE_KIND:
if (this->d.sub.folded) return 1; // Only displaying the title
return 1 + this->d.sub.page->Length(); // 1 extra row for the title
default: NOT_REACHED();
}
}
/**
* Find setting entry at row \a row_num
* @param row_num Index of entry to return
* @param cur_row Current row number
* @return The requested setting entry or \c NULL if it not found
*/
SettingEntry *SettingEntry::FindEntry(uint row_num, uint *cur_row)
{
if (row_num == *cur_row) return this;
switch (this->flags & SEF_KIND_MASK) {
case SEF_SETTING_KIND:
(*cur_row)++;
break;
case SEF_SUBTREE_KIND:
(*cur_row)++; // add one for row containing the title
if (this->d.sub.folded) {
break;
}
/* sub-page is visible => search it too */
return this->d.sub.page->FindEntry(row_num, cur_row);
default: NOT_REACHED();
}
return NULL;
}
/**
* Draw a row in the settings panel.
*
* See SettingsPage::Draw() for an explanation about how drawing is performed.
*
* The \a parent_last parameter ensures that the vertical lines at the left are
* only drawn when another entry follows, that it prevents output like
* \verbatim
* |-- setting
* |-- (-) - Title
* | |-- setting
* | |-- setting
* \endverbatim
* The left-most vertical line is not wanted. It is prevented by setting the
* appropiate bit in the \a parent_last parameter.
*
* @param settings_ptr Pointer to current values of all settings
* @param base_x Left-most position in window/panel to start drawing \a first_row
* @param base_y Upper-most position in window/panel to start drawing \a first_row
* @param max_x The maximum x position to draw strings add.
* @param first_row First row number to draw
* @param max_row Row-number to stop drawing (the row-number of the row below the last row to draw)
* @param cur_row Current row number (internal variable)
* @param parent_last Last-field booleans of parent page level (page level \e i sets bit \e i to 1 if it is its last field)
* @return Row number of the next row to draw
*/
uint SettingEntry::Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row, uint parent_last)
{
if (cur_row >= max_row) return cur_row;
int x = base_x;
int y = base_y;
if (cur_row >= first_row) {
int colour = _colour_gradient[COLOUR_ORANGE][4];
y = base_y + (cur_row - first_row) * SETTING_HEIGHT; // Compute correct y start position
/* Draw vertical for parent nesting levels */
for (uint lvl = 0; lvl < this->level; lvl++) {
if (!HasBit(parent_last, lvl)) GfxDrawLine(x + 4, y, x + 4, y + SETTING_HEIGHT - 1, colour);
x += LEVEL_WIDTH;
}
/* draw own |- prefix */
int halfway_y = y + SETTING_HEIGHT / 2;
int bottom_y = (flags & SEF_LAST_FIELD) ? halfway_y : y + SETTING_HEIGHT - 1;
GfxDrawLine(x + 4, y, x + 4, bottom_y, colour);
/* Small horizontal line from the last vertical line */
GfxDrawLine(x + 4, halfway_y, x + LEVEL_WIDTH - 4, halfway_y, colour);
x += LEVEL_WIDTH;
}
switch(this->flags & SEF_KIND_MASK) {
case SEF_SETTING_KIND:
if (cur_row >= first_row) {
DrawSetting(settings_ptr, this->d.entry.setting, x, y, max_x, this->flags & SEF_BUTTONS_MASK);
}
cur_row++;
break;
case SEF_SUBTREE_KIND:
if (cur_row >= first_row) {
DrawSprite((this->d.sub.folded ? SPR_CIRCLE_FOLDED : SPR_CIRCLE_UNFOLDED), PAL_NONE, x, y);
DrawStringTruncated(x + 12, y, this->d.sub.title, TC_FROMSTRING, max_x - x - 12);
}
cur_row++;
if (!this->d.sub.folded) {
if (this->flags & SEF_LAST_FIELD) {
assert(this->level < sizeof(parent_last));
SetBit(parent_last, this->level); // Add own last-field state
}
cur_row = this->d.sub.page->Draw(settings_ptr, base_x, base_y, max_x, first_row, max_row, cur_row, parent_last);
}
break;
default: NOT_REACHED();
}
return cur_row;
}
/**
* Private function to draw setting value (button + text + current value)
* @param settings_ptr Pointer to current values of all settings
* @param sd Pointer to value description of setting to draw
* @param x Left-most position in window/panel to start drawing
* @param y Upper-most position in window/panel to start drawing
* @param max_x The maximum x position to draw strings add.
* @param state State of the left + right arrow buttons to draw for the setting
*/
void SettingEntry::DrawSetting(GameSettings *settings_ptr, const SettingDesc *sd, int x, int y, int max_x, int state)
{
const SettingDescBase *sdb = &sd->desc;
const void *var = GetVariableAddress(settings_ptr, &sd->save);
bool editable = true;
bool disabled = false;
/* We do not allow changes of some items when we are a client in a networkgame */
if (!(sd->save.conv & SLF_NETWORK_NO) && _networking && !_network_server) editable = false;
if ((sdb->flags & SGF_NETWORK_ONLY) && !_networking) editable = false;
if ((sdb->flags & SGF_NO_NETWORK) && _networking) editable = false;
if (sdb->cmd == SDT_BOOLX) {
static const Colours _bool_ctabs[2][2] = {{COLOUR_CREAM, COLOUR_RED}, {COLOUR_DARK_GREEN, COLOUR_GREEN}};
/* Draw checkbox for boolean-value either on/off */
bool on = (*(bool*)var);
DrawFrameRect(x, y, x + 19, y + 8, _bool_ctabs[!!on][!!editable], on ? FR_LOWERED : FR_NONE);
SetDParam(0, on ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF);
} else {
int32 value;
value = (int32)ReadValue(var, sd->save.conv);
/* Draw [<][>] boxes for settings of an integer-type */
DrawArrowButtons(x, y, COLOUR_YELLOW, state, editable && value != (sdb->flags & SGF_0ISDISABLED ? 0 : sdb->min), editable && value != sdb->max);
disabled = (value == 0) && (sdb->flags & SGF_0ISDISABLED);
if (disabled) {
SetDParam(0, STR_CONFIG_SETTING_DISABLED);
} else {
if (sdb->flags & SGF_CURRENCY) {
SetDParam(0, STR_CONFIG_SETTING_CURRENCY);
} else if (sdb->flags & SGF_MULTISTRING) {
SetDParam(0, sdb->str + value + 1);
} else {
SetDParam(0, (sdb->flags & SGF_NOCOMMA) ? STR_CONFIG_SETTING_INT32 : STR_7024);
}
SetDParam(1, value);
}
}
DrawStringTruncated(x + 25, y, (sdb->str) + disabled, TC_FROMSTRING, max_x - x - 25);
}
/* == SettingsPage methods == */
/**
* Initialization of an entire setting page
* @param level Nesting level of this page (internal variable, do not provide a value for it when calling)
*/
void SettingsPage::Init(byte level)
{
for (uint field = 0; field < this->num; field++) {
this->entries[field].Init(level, field + 1 == num);
}
}
/** Recursively close all folds of sub-pages */
void SettingsPage::FoldAll()
{
for (uint field = 0; field < this->num; field++) {
this->entries[field].FoldAll();
}
}
/** Return number of rows needed to display the whole page */
uint SettingsPage::Length() const
{
uint length = 0;
for (uint field = 0; field < this->num; field++) {
length += this->entries[field].Length();
}
return length;
}
/**
* Find the setting entry at row number \a row_num
* @param row_num Index of entry to return
* @param cur_row Variable used for keeping track of the current row number. Should point to memory initialized to \c 0 when first called.
* @return The requested setting entry or \c NULL if it does not exist
*/
SettingEntry *SettingsPage::FindEntry(uint row_num, uint *cur_row) const
{
SettingEntry *pe = NULL;
for (uint field = 0; field < this->num; field++) {
pe = this->entries[field].FindEntry(row_num, cur_row);
if (pe != NULL) {
break;
}
}
return pe;
}
/**
* Draw a selected part of the settings page.
*
* The scrollbar uses rows of the page, while the page data strucure is a tree of #SettingsPage and #SettingEntry objects.
* As a result, the drawing routing traverses the tree from top to bottom, counting rows in \a cur_row until it reaches \a first_row.
* Then it enables drawing rows while traversing until \a max_row is reached, at which point drawing is terminated.
*
* @param settings_ptr Pointer to current values of all settings
* @param base_x Left-most position in window/panel to start drawing of each setting row
* @param base_y Upper-most position in window/panel to start drawing of row number \a first_row
* @param max_x The maximum x position to draw strings add.
* @param first_row Number of first row to draw
* @param max_row Row-number to stop drawing (the row-number of the row below the last row to draw)
* @param cur_row Current row number (internal variable)
* @param parent_last Last-field booleans of parent page level (page level \e i sets bit \e i to 1 if it is its last field)
* @return Row number of the next row to draw
*/
uint SettingsPage::Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row, uint parent_last) const
{
if (cur_row >= max_row) return cur_row;
for (uint i = 0; i < this->num; i++) {
cur_row = this->entries[i].Draw(settings_ptr, base_x, base_y, max_x, first_row, max_row, cur_row, parent_last);
if (cur_row >= max_row) {
break;
}
}
return cur_row;
}
static SettingEntry _settings_ui_display[] = {
SettingEntry("gui.vehicle_speed"),
SettingEntry("gui.status_long_date"),
SettingEntry("gui.date_format_in_default_names"),
SettingEntry("gui.population_in_label"),
SettingEntry("gui.measure_tooltip"),
SettingEntry("gui.loading_indicators"),
SettingEntry("gui.liveries"),
SettingEntry("gui.show_track_reservation"),
SettingEntry("gui.expenses_layout"),
};
/** Display options sub-page */
static SettingsPage _settings_ui_display_page = {_settings_ui_display, lengthof(_settings_ui_display)};
static SettingEntry _settings_ui_interaction[] = {
SettingEntry("gui.window_snap_radius"),
SettingEntry("gui.window_soft_limit"),
SettingEntry("gui.link_terraform_toolbar"),
SettingEntry("gui.prefer_teamchat"),
SettingEntry("gui.autoscroll"),
SettingEntry("gui.reverse_scroll"),
SettingEntry("gui.smooth_scroll"),
SettingEntry("gui.left_mouse_btn_scrolling"),
/* While the horizontal scrollwheel scrolling is written as general code, only
* the cocoa (OSX) driver generates input for it.
* Since it's also able to completely disable the scrollwheel will we display it on all platforms anyway */
SettingEntry("gui.scrollwheel_scrolling"),
SettingEntry("gui.scrollwheel_multiplier"),
#ifdef __APPLE__
/* We might need to emulate a right mouse button on mac */
SettingEntry("gui.right_mouse_btn_emulation"),
#endif
};
/** Interaction sub-page */
static SettingsPage _settings_ui_interaction_page = {_settings_ui_interaction, lengthof(_settings_ui_interaction)};
static SettingEntry _settings_ui[] = {
SettingEntry(&_settings_ui_display_page, STR_CONFIG_SETTING_DISPLAY_OPTIONS),
SettingEntry(&_settings_ui_interaction_page, STR_CONFIG_SETTING_INTERACTION),
SettingEntry("gui.show_finances"),
SettingEntry("gui.errmsg_duration"),
SettingEntry("gui.toolbar_pos"),
SettingEntry("gui.pause_on_newgame"),
SettingEntry("gui.advanced_vehicle_list"),
SettingEntry("gui.timetable_in_ticks"),
SettingEntry("gui.quick_goto"),
SettingEntry("gui.default_rail_type"),
SettingEntry("gui.always_build_infrastructure"),
SettingEntry("gui.persistent_buildingtools"),
SettingEntry("gui.coloured_news_year"),
};
/** Interface subpage */
static SettingsPage _settings_ui_page = {_settings_ui, lengthof(_settings_ui)};
static SettingEntry _settings_construction_signals[] = {
SettingEntry("construction.signal_side"),
SettingEntry("gui.enable_signal_gui"),
SettingEntry("gui.drag_signals_density"),
SettingEntry("gui.semaphore_build_before"),
SettingEntry("gui.default_signal_type"),
SettingEntry("gui.cycle_signal_types"),
};
/** Signals subpage */
static SettingsPage _settings_construction_signals_page = {_settings_construction_signals, lengthof(_settings_construction_signals)};
static SettingEntry _settings_construction[] = {
SettingEntry(&_settings_construction_signals_page, STR_CONFIG_SETTING_CONSTRUCTION_SIGNALS),
SettingEntry("construction.build_on_slopes"),
SettingEntry("construction.autoslope"),
SettingEntry("construction.extra_dynamite"),
SettingEntry("construction.longbridges"),
SettingEntry("station.always_small_airport"),
SettingEntry("construction.freeform_edges"),
};
/** Construction sub-page */
static SettingsPage _settings_construction_page = {_settings_construction, lengthof(_settings_construction)};
static SettingEntry _settings_stations_cargo[] = {
SettingEntry("order.improved_load"),
SettingEntry("order.gradual_loading"),
SettingEntry("order.selectgoods"),
};
/** Cargo handling sub-page */
static SettingsPage _settings_stations_cargo_page = {_settings_stations_cargo, lengthof(_settings_stations_cargo)};
static SettingEntry _settings_stations[] = {
SettingEntry(&_settings_stations_cargo_page, STR_CONFIG_SETTING_STATIONS_CARGOHANDLING),
SettingEntry("station.join_stations"),
SettingEntry("station.nonuniform_stations"),
SettingEntry("station.adjacent_stations"),
SettingEntry("station.distant_join_stations"),
SettingEntry("station.station_spread"),
SettingEntry("economy.station_noise_level"),
SettingEntry("station.modified_catchment"),
SettingEntry("construction.road_stop_on_town_road"),
SettingEntry("construction.road_stop_on_competitor_road"),
};
/** Stations sub-page */
static SettingsPage _settings_stations_page = {_settings_stations, lengthof(_settings_stations)};
static SettingEntry _settings_economy_towns[] = {
SettingEntry("economy.bribe"),
SettingEntry("economy.exclusive_rights"),
SettingEntry("economy.town_layout"),
SettingEntry("economy.allow_town_roads"),
SettingEntry("economy.mod_road_rebuild"),
SettingEntry("economy.town_growth_rate"),
SettingEntry("economy.larger_towns"),
SettingEntry("economy.initial_city_size"),
};
/** Towns sub-page */
static SettingsPage _settings_economy_towns_page = {_settings_economy_towns, lengthof(_settings_economy_towns)};
static SettingEntry _settings_economy_industries[] = {
SettingEntry("construction.raw_industry_construction"),
SettingEntry("economy.multiple_industry_per_town"),
SettingEntry("economy.same_industry_close"),
SettingEntry("game_creation.oil_refinery_limit"),
};
/** Industries sub-page */
static SettingsPage _settings_economy_industries_page = {_settings_economy_industries, lengthof(_settings_economy_industries)};
static SettingEntry _settings_economy[] = {
SettingEntry(&_settings_economy_towns_page, STR_CONFIG_SETTING_ECONOMY_TOWNS),
SettingEntry(&_settings_economy_industries_page, STR_CONFIG_SETTING_ECONOMY_INDUSTRIES),
SettingEntry("economy.inflation"),
SettingEntry("economy.smooth_economy"),
};
/** Economy sub-page */
static SettingsPage _settings_economy_page = {_settings_economy, lengthof(_settings_economy)};
static SettingEntry _settings_ai_npc[] = {
SettingEntry("ai.ai_in_multiplayer"),
SettingEntry("ai.ai_disable_veh_train"),
SettingEntry("ai.ai_disable_veh_roadveh"),
SettingEntry("ai.ai_disable_veh_aircraft"),
SettingEntry("ai.ai_disable_veh_ship"),
SettingEntry("ai.ai_max_opcode_till_suspend"),
};
/** Computer players sub-page */
static SettingsPage _settings_ai_npc_page = {_settings_ai_npc, lengthof(_settings_ai_npc)};
static SettingEntry _settings_ai[] = {
SettingEntry(&_settings_ai_npc_page, STR_CONFIG_SETTING_AI_NPC),
SettingEntry("economy.give_money"),
SettingEntry("economy.allow_shares"),
};
/** AI sub-page */
static SettingsPage _settings_ai_page = {_settings_ai, lengthof(_settings_ai)};
static SettingEntry _settings_vehicles_routing[] = {
SettingEntry("pf.pathfinder_for_trains"),
SettingEntry("pf.forbid_90_deg"),
SettingEntry("pf.pathfinder_for_roadvehs"),
SettingEntry("pf.roadveh_queue"),
SettingEntry("pf.pathfinder_for_ships"),
};
/** Autorenew sub-page */
static SettingsPage _settings_vehicles_routing_page = {_settings_vehicles_routing, lengthof(_settings_vehicles_routing)};
static SettingEntry _settings_vehicles_autorenew[] = {
SettingEntry("gui.autorenew"),
SettingEntry("gui.autorenew_months"),
SettingEntry("gui.autorenew_money"),
};
/** Autorenew sub-page */
static SettingsPage _settings_vehicles_autorenew_page = {_settings_vehicles_autorenew, lengthof(_settings_vehicles_autorenew)};
static SettingEntry _settings_vehicles_servicing[] = {
SettingEntry("vehicle.servint_ispercent"),
SettingEntry("vehicle.servint_trains"),
SettingEntry("vehicle.servint_roadveh"),
SettingEntry("vehicle.servint_ships"),
SettingEntry("vehicle.servint_aircraft"),
SettingEntry("order.no_servicing_if_no_breakdowns"),
SettingEntry("order.serviceathelipad"),
};
/** Servicing sub-page */
static SettingsPage _settings_vehicles_servicing_page = {_settings_vehicles_servicing, lengthof(_settings_vehicles_servicing)};
static SettingEntry _settings_vehicles_trains[] = {
SettingEntry("vehicle.train_acceleration_model"),
SettingEntry("vehicle.mammoth_trains"),
SettingEntry("gui.lost_train_warn"),
SettingEntry("vehicle.wagon_speed_limits"),
SettingEntry("vehicle.disable_elrails"),
SettingEntry("vehicle.freight_trains"),
};
/** Trains sub-page */
static SettingsPage _settings_vehicles_trains_page = {_settings_vehicles_trains, lengthof(_settings_vehicles_trains)};
static SettingEntry _settings_vehicles[] = {
SettingEntry(&_settings_vehicles_routing_page, STR_CONFIG_SETTING_VEHICLES_ROUTING),
SettingEntry(&_settings_vehicles_autorenew_page, STR_CONFIG_SETTING_VEHICLES_AUTORENEW),
SettingEntry(&_settings_vehicles_servicing_page, STR_CONFIG_SETTING_VEHICLES_SERVICING),
SettingEntry(&_settings_vehicles_trains_page, STR_CONFIG_SETTING_VEHICLES_TRAINS),
SettingEntry("order.gotodepot"),
SettingEntry("gui.new_nonstop"),
SettingEntry("gui.order_review_system"),
SettingEntry("gui.vehicle_income_warn"),
SettingEntry("vehicle.never_expire_vehicles"),
SettingEntry("vehicle.max_trains"),
SettingEntry("vehicle.max_roadveh"),
SettingEntry("vehicle.max_aircraft"),
SettingEntry("vehicle.max_ships"),
SettingEntry("vehicle.plane_speed"),
SettingEntry("order.timetabling"),
SettingEntry("vehicle.dynamic_engines"),
};
/** Vehicles sub-page */
static SettingsPage _settings_vehicles_page = {_settings_vehicles, lengthof(_settings_vehicles)};
static SettingEntry _settings_main[] = {
SettingEntry(&_settings_ui_page, STR_CONFIG_SETTING_GUI),
SettingEntry(&_settings_construction_page, STR_CONFIG_SETTING_CONSTRUCTION),
SettingEntry(&_settings_vehicles_page, STR_CONFIG_SETTING_VEHICLES),
SettingEntry(&_settings_stations_page, STR_CONFIG_SETTING_STATIONS),
SettingEntry(&_settings_economy_page, STR_CONFIG_SETTING_ECONOMY),
SettingEntry(&_settings_ai_page, STR_CONFIG_SETTING_AI),
};
/** Main page, holding all advanced settings */
static SettingsPage _settings_main_page = {_settings_main, lengthof(_settings_main)};
/** Widget numbers of settings window */
enum GameSettingsWidgets {
SETTINGSEL_OPTIONSPANEL = 2, ///< Panel widget containing the option lists
SETTINGSEL_SCROLLBAR, ///< Scrollbar
SETTINGSEL_RESIZE, ///< Resize button
};
struct GameSettingsWindow : Window {
static const int SETTINGTREE_LEFT_OFFSET; ///< Position of left edge of setting values
static const int SETTINGTREE_TOP_OFFSET; ///< Position of top edge of setting values
static GameSettings *settings_ptr; ///< Pointer to the game settings being displayed and modified
SettingEntry *valuewindow_entry; ///< If non-NULL, pointer to setting for which a value-entering window has been opened
SettingEntry *clicked_entry; ///< If non-NULL, pointer to a clicked numeric setting (with a depressed left or right button)
GameSettingsWindow(const WindowDesc *desc) : Window(desc)
{
/* Check that the widget doesn't get moved without adapting the constant as well.
* - SETTINGTREE_LEFT_OFFSET should be 5 pixels to the right of the left edge of the panel
* - SETTINGTREE_TOP_OFFSET should be 5 pixels below the top edge of the panel
*/
assert(this->widget[SETTINGSEL_OPTIONSPANEL].left + 5 == SETTINGTREE_LEFT_OFFSET);
assert(this->widget[SETTINGSEL_OPTIONSPANEL].top + 5 == SETTINGTREE_TOP_OFFSET);
static bool first_time = true;
settings_ptr = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;
/* Build up the dynamic settings-array only once per OpenTTD session */
if (first_time) {
_settings_main_page.Init();
first_time = false;
} else {
_settings_main_page.FoldAll(); // Close all sub-pages
}
this->valuewindow_entry = NULL; // No setting entry for which a entry window is opened
this->clicked_entry = NULL; // No numeric setting buttons are depressed
this->vscroll.pos = 0;
this->vscroll.cap = (this->widget[SETTINGSEL_OPTIONSPANEL].bottom - this->widget[SETTINGSEL_OPTIONSPANEL].top - 8) / SETTING_HEIGHT;
SetVScrollCount(this, _settings_main_page.Length());
this->resize.step_height = SETTING_HEIGHT;
this->resize.height = this->height;
this->resize.step_width = 1;
this->resize.width = this->width;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
_settings_main_page.Draw(settings_ptr, SETTINGTREE_LEFT_OFFSET, SETTINGTREE_TOP_OFFSET,
this->width - 13, this->vscroll.pos, this->vscroll.pos + this->vscroll.cap);
}
virtual void OnClick(Point pt, int widget)
{
if (widget != SETTINGSEL_OPTIONSPANEL) return;
int y = pt.y - SETTINGTREE_TOP_OFFSET; // Shift y coordinate
if (y < 0) return; // Clicked above first entry
byte btn = this->vscroll.pos + y / SETTING_HEIGHT; // Compute which setting is selected
if (y % SETTING_HEIGHT > SETTING_HEIGHT - 2) return; // Clicked too low at the setting
uint cur_row = 0;
SettingEntry *pe = _settings_main_page.FindEntry(btn, &cur_row);
if (pe == NULL) return; // Clicked below the last setting of the page
int x = pt.x - SETTINGTREE_LEFT_OFFSET - (pe->level + 1) * LEVEL_WIDTH; // Shift x coordinate
if (x < 0) return; // Clicked left of the entry
if ((pe->flags & SEF_KIND_MASK) == SEF_SUBTREE_KIND) {
pe->d.sub.folded = !pe->d.sub.folded; // Flip 'folded'-ness of the sub-page
SetVScrollCount(this, _settings_main_page.Length());
this->SetDirty();
return;
}
assert((pe->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
const SettingDesc *sd = pe->d.entry.setting;
/* return if action is only active in network, or only settable by server */
if (!(sd->save.conv & SLF_NETWORK_NO) && _networking && !_network_server) return;
if ((sd->desc.flags & SGF_NETWORK_ONLY) && !_networking) return;
if ((sd->desc.flags & SGF_NO_NETWORK) && _networking) return;
void *var = GetVariableAddress(settings_ptr, &sd->save);
int32 value = (int32)ReadValue(var, sd->save.conv);
/* clicked on the icon on the left side. Either scroller or bool on/off */
if (x < 21) {
const SettingDescBase *sdb = &sd->desc;
int32 oldvalue = value;
switch (sdb->cmd) {
case SDT_BOOLX: value ^= 1; break;
case SDT_ONEOFMANY:
case SDT_NUMX: {
/* Add a dynamic step-size to the scroller. In a maximum of
* 50-steps you should be able to get from min to max,
* unless specified otherwise in the 'interval' variable
* of the current setting. */
uint32 step = (sdb->interval == 0) ? ((sdb->max - sdb->min) / 50) : sdb->interval;
if (step == 0) step = 1;
/* don't allow too fast scrolling */
if ((this->flags4 & WF_TIMEOUT_MASK) > WF_TIMEOUT_TRIGGER) {
_left_button_clicked = false;
return;
}
/* Increase or decrease the value and clamp it to extremes */
if (x >= 10) {
value += step;
if (value > sdb->max) value = sdb->max;
if (value < sdb->min) value = sdb->min; // skip between "disabled" and minimum
} else {
value -= step;
if (value < sdb->min) value = (sdb->flags & SGF_0ISDISABLED) ? 0 : sdb->min;
}
/* Set up scroller timeout for numeric values */
if (value != oldvalue && !(sd->desc.flags & SGF_MULTISTRING)) {
if (this->clicked_entry != NULL) { // Release previous buttons if any
this->clicked_entry->SetButtons(0);
}
this->clicked_entry = pe;
this->clicked_entry->SetButtons((x >= 10) ? SEF_RIGHT_DEPRESSED : SEF_LEFT_DEPRESSED);
this->flags4 |= WF_TIMEOUT_BEGIN;
_left_button_clicked = false;
}
} break;
default: NOT_REACHED();
}
if (value != oldvalue) {
SetSettingValue(pe->d.entry.index, value);
this->SetDirty();
}
} else {
/* only open editbox for types that its sensible for */
if (sd->desc.cmd != SDT_BOOLX && !(sd->desc.flags & SGF_MULTISTRING)) {
/* Show the correct currency-translated value */
if (sd->desc.flags & SGF_CURRENCY) value *= _currency->rate;
this->valuewindow_entry = pe;
SetDParam(0, value);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_CONFIG_SETTING_QUERY_CAPT, 10, 100, this, CS_NUMERAL, QSF_NONE);
}
}
}
virtual void OnTimeout()
{
if (this->clicked_entry != NULL) { // On timeout, release any depressed buttons
this->clicked_entry->SetButtons(0);
this->clicked_entry = NULL;
this->SetDirty();
}
}
virtual void OnQueryTextFinished(char *str)
{
if (!StrEmpty(str)) {
assert(this->valuewindow_entry != NULL);
assert((this->valuewindow_entry->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
const SettingDesc *sd = this->valuewindow_entry->d.entry.setting;
int32 value = atoi(str);
/* Save the correct currency-translated value */
if (sd->desc.flags & SGF_CURRENCY) value /= _currency->rate;
SetSettingValue(this->valuewindow_entry->d.entry.index, value);
this->SetDirty();
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / SETTING_HEIGHT;
SetVScrollCount(this, _settings_main_page.Length());
}
};
GameSettings *GameSettingsWindow::settings_ptr = NULL;
const int GameSettingsWindow::SETTINGTREE_LEFT_OFFSET = 5;
const int GameSettingsWindow::SETTINGTREE_TOP_OFFSET = 19;
#ifdef N3DS
static const Widget _settings_selection_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_MAUVE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_MAUVE, 11, 300, 0, 13, STR_CONFIG_SETTING_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_RB, COLOUR_MAUVE, 0, 288, 14, 187, 0x0, STR_NULL}, // SETTINGSEL_OPTIONSPANEL
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_MAUVE, 289, 300, 14, 175, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // SETTINGSEL_SCROLLBAR
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_MAUVE, 289, 300, 176, 187, 0x0, STR_RESIZE_BUTTON}, // SETTINGSEL_RESIZE
{ WIDGETS_END},
};
#else
static const Widget _settings_selection_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_MAUVE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_MAUVE, 11, 411, 0, 13, STR_CONFIG_SETTING_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_RB, COLOUR_MAUVE, 0, 399, 14, 187, 0x0, STR_NULL}, // SETTINGSEL_OPTIONSPANEL
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_MAUVE, 400, 411, 14, 175, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // SETTINGSEL_SCROLLBAR
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_MAUVE, 400, 411, 176, 187, 0x0, STR_RESIZE_BUTTON}, // SETTINGSEL_RESIZE
{ WIDGETS_END},
};
#endif
#ifdef N3DS
static const WindowDesc _settings_selection_desc(
WDP_CENTER, WDP_CENTER, 301, 188, 450, 397,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE,
_settings_selection_widgets
);
#else
static const WindowDesc _settings_selection_desc(
WDP_CENTER, WDP_CENTER, 412, 188, 450, 397,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE,
_settings_selection_widgets
);
#endif
void ShowGameSettings()
{
DeleteWindowById(WC_GAME_OPTIONS, 0);
new GameSettingsWindow(&_settings_selection_desc);
}
/**
* Draw [<][>] boxes.
* @param x the x position to draw
* @param y the y position to draw
* @param button_colour the colour of the button
* @param state 0 = none clicked, 1 = first clicked, 2 = second clicked
* @param clickable_left is the left button clickable?
* @param clickable_right is the right button clickable?
*/
void DrawArrowButtons(int x, int y, Colours button_colour, byte state, bool clickable_left, bool clickable_right)
{
int colour = _colour_gradient[button_colour][2];
DrawFrameRect(x, y + 1, x + 9, y + 9, button_colour, (state == 1) ? FR_LOWERED : FR_NONE);
DrawFrameRect(x + 10, y + 1, x + 19, y + 9, button_colour, (state == 2) ? FR_LOWERED : FR_NONE);
DrawStringCentered(x + 5, y + 1, STR_6819, TC_FROMSTRING); // [<]
DrawStringCentered(x + 15, y + 1, STR_681A, TC_FROMSTRING); // [>]
/* Grey out the buttons that aren't clickable */
if (!clickable_left) {
GfxFillRect(x + 1, y + 1, x + 1 + 8, y + 8, colour, FILLRECT_CHECKER);
}
if (!clickable_right) {
GfxFillRect(x + 11, y + 1, x + 11 + 8, y + 8, colour, FILLRECT_CHECKER);
}
}
/** These are not, strickly speaking, widget enums,
* since they have been changed as line coordinates.
* So, rather, they are more like order of appearance */
enum CustomCurrenciesWidgets {
CUSTCURR_EXCHANGERATE = 0,
CUSTCURR_SEPARATOR,
CUSTCURR_PREFIX,
CUSTCURR_SUFFIX,
CUSTCURR_TO_EURO,
};
struct CustomCurrencyWindow : Window {
char separator[2];
int click;
int query_widget;
CustomCurrencyWindow(const WindowDesc *desc) : Window(desc)
{
this->separator[0] = _custom_currency.separator;
this->separator[1] = '\0';
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
int x;
int y = 20;
this->DrawWidgets();
/* exchange rate */
DrawArrowButtons(10, y, COLOUR_YELLOW, GB(this->click, 0, 2), true, true);
SetDParam(0, 1);
SetDParam(1, 1);
DrawString(35, y + 1, STR_CURRENCY_EXCHANGE_RATE, TC_FROMSTRING);
y += 12;
/* separator */
DrawFrameRect(10, y + 1, 29, y + 9, COLOUR_DARK_BLUE, GB(this->click, 2, 2) ? FR_LOWERED : FR_NONE);
x = DrawString(35, y + 1, STR_CURRENCY_SEPARATOR, TC_FROMSTRING);
DoDrawString(this->separator, x + 4, y + 1, TC_ORANGE);
y += 12;
/* prefix */
DrawFrameRect(10, y + 1, 29, y + 9, COLOUR_DARK_BLUE, GB(this->click, 4, 2) ? FR_LOWERED : FR_NONE);
x = DrawString(35, y + 1, STR_CURRENCY_PREFIX, TC_FROMSTRING);
DoDrawString(_custom_currency.prefix, x + 4, y + 1, TC_ORANGE);
y += 12;
/* suffix */
DrawFrameRect(10, y + 1, 29, y + 9, COLOUR_DARK_BLUE, GB(this->click, 6, 2) ? FR_LOWERED : FR_NONE);
x = DrawString(35, y + 1, STR_CURRENCY_SUFFIX, TC_FROMSTRING);
DoDrawString(_custom_currency.suffix, x + 4, y + 1, TC_ORANGE);
y += 12;
/* switch to euro */
DrawArrowButtons(10, y, COLOUR_YELLOW, GB(this->click, 8, 2), true, true);
SetDParam(0, _custom_currency.to_euro);
DrawString(35, y + 1, (_custom_currency.to_euro != CF_NOEURO) ? STR_CURRENCY_SWITCH_TO_EURO : STR_CURRENCY_SWITCH_TO_EURO_NEVER, TC_FROMSTRING);
y += 12;
/* Preview */
y += 12;
SetDParam(0, 10000);
DrawString(35, y + 1, STR_CURRENCY_PREVIEW, TC_FROMSTRING);
}
virtual void OnClick(Point pt, int widget)
{
int line = (pt.y - 20) / 12;
int len = 0;
int x = pt.x;
StringID str = 0;
CharSetFilter afilter = CS_ALPHANUMERAL;
switch (line) {
case CUSTCURR_EXCHANGERATE:
if (IsInsideMM(x, 10, 30)) { // clicked buttons
if (x < 20) {
if (_custom_currency.rate > 1) _custom_currency.rate--;
this->click = 1 << (line * 2 + 0);
} else {
if (_custom_currency.rate < UINT16_MAX) _custom_currency.rate++;
this->click = 1 << (line * 2 + 1);
}
} else { // enter text
SetDParam(0, _custom_currency.rate);
str = STR_CONFIG_SETTING_INT32;
len = 5;
afilter = CS_NUMERAL;
}
break;
case CUSTCURR_SEPARATOR:
if (IsInsideMM(x, 10, 30)) { // clicked button
this->click = 1 << (line * 2 + 1);
}
SetDParamStr(0, this->separator);
str = STR_JUST_RAW_STRING;
len = 1;
break;
case CUSTCURR_PREFIX:
if (IsInsideMM(x, 10, 30)) { // clicked button
this->click = 1 << (line * 2 + 1);
}
SetDParamStr(0, _custom_currency.prefix);
str = STR_JUST_RAW_STRING;
len = 12;
break;
case CUSTCURR_SUFFIX:
if (IsInsideMM(x, 10, 30)) { // clicked button
this->click = 1 << (line * 2 + 1);
}
SetDParamStr(0, _custom_currency.suffix);
str = STR_JUST_RAW_STRING;
len = 12;
break;
case CUSTCURR_TO_EURO:
if (IsInsideMM(x, 10, 30)) { // clicked buttons
if (x < 20) {
_custom_currency.to_euro = (_custom_currency.to_euro <= 2000) ? CF_NOEURO : _custom_currency.to_euro - 1;
this->click = 1 << (line * 2 + 0);
} else {
_custom_currency.to_euro = Clamp(_custom_currency.to_euro + 1, 2000, MAX_YEAR);
this->click = 1 << (line * 2 + 1);
}
} else { // enter text
SetDParam(0, _custom_currency.to_euro);
str = STR_CONFIG_SETTING_INT32;
len = 7;
afilter = CS_NUMERAL;
}
break;
}
if (len != 0) {
this->query_widget = line;
ShowQueryString(str, STR_CURRENCY_CHANGE_PARAMETER, len + 1, 250, this, afilter, QSF_NONE);
}
this->flags4 |= WF_TIMEOUT_BEGIN;
this->SetDirty();
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
switch (this->query_widget) {
case CUSTCURR_EXCHANGERATE:
_custom_currency.rate = Clamp(atoi(str), 1, UINT16_MAX);
break;
case CUSTCURR_SEPARATOR: // Thousands seperator
_custom_currency.separator = StrEmpty(str) ? ' ' : str[0];
strecpy(this->separator, str, lastof(this->separator));
break;
case CUSTCURR_PREFIX:
strecpy(_custom_currency.prefix, str, lastof(_custom_currency.prefix));
break;
case CUSTCURR_SUFFIX:
strecpy(_custom_currency.suffix, str, lastof(_custom_currency.suffix));
break;
case CUSTCURR_TO_EURO: { // Year to switch to euro
int val = atoi(str);
_custom_currency.to_euro = (val < 2000 ? CF_NOEURO : min(val, MAX_YEAR));
break;
}
}
MarkWholeScreenDirty();
}
virtual void OnTimeout()
{
this->click = 0;
this->SetDirty();
}
};
static const Widget _cust_currency_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 229, 0, 13, STR_CURRENCY_WINDOW, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 229, 14, 119, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _cust_currency_desc(
WDP_CENTER, WDP_CENTER, 230, 120, 230, 120,
WC_CUSTOM_CURRENCY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_cust_currency_widgets
);
static void ShowCustCurrency()
{
DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
new CustomCurrencyWindow(&_cust_currency_desc);
}
| 64,480
|
C++
|
.cpp
| 1,483
| 40.598786
| 167
| 0.679558
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,082
|
npf.cpp
|
EnergeticBark_OpenTTD-3DS/src/npf.cpp
|
/* $Id$ */
/** @file npf.cpp Implementation of the NPF pathfinder. */
#include "stdafx.h"
#include "npf.h"
#include "debug.h"
#include "landscape.h"
#include "depot_base.h"
#include "depot_map.h"
#include "network/network.h"
#include "tunnelbridge_map.h"
#include "functions.h"
#include "vehicle_base.h"
#include "tunnelbridge.h"
#include "pbs.h"
#include "settings_type.h"
#include "pathfind.h"
static AyStar _npf_aystar;
/* The cost of each trackdir. A diagonal piece is the full NPF_TILE_LENGTH,
* the shorter piece is sqrt(2)/2*NPF_TILE_LENGTH =~ 0.7071
*/
#define NPF_STRAIGHT_LENGTH (uint)(NPF_TILE_LENGTH * STRAIGHT_TRACK_LENGTH)
static const uint _trackdir_length[TRACKDIR_END] = {
NPF_TILE_LENGTH, NPF_TILE_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH,
0, 0,
NPF_TILE_LENGTH, NPF_TILE_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH
};
/**
* Calculates the minimum distance traveled to get from t0 to t1 when only
* using tracks (ie, only making 45 degree turns). Returns the distance in the
* NPF scale, ie the number of full tiles multiplied by NPF_TILE_LENGTH to
* prevent rounding.
*/
static uint NPFDistanceTrack(TileIndex t0, TileIndex t1)
{
const uint dx = Delta(TileX(t0), TileX(t1));
const uint dy = Delta(TileY(t0), TileY(t1));
const uint straightTracks = 2 * min(dx, dy); // The number of straight (not full length) tracks
/* OPTIMISATION:
* Original: diagTracks = max(dx, dy) - min(dx,dy);
* Proof:
* (dx+dy) - straightTracks == (min + max) - straightTracks = min + max - 2 * min = max - min */
const uint diagTracks = dx + dy - straightTracks; // The number of diagonal (full tile length) tracks.
/* Don't factor out NPF_TILE_LENGTH below, this will round values and lose
* precision */
return diagTracks * NPF_TILE_LENGTH + straightTracks * NPF_TILE_LENGTH * STRAIGHT_TRACK_LENGTH;
}
#if 0
static uint NTPHash(uint key1, uint key2)
{
/* This function uses the old hash, which is fixed on 10 bits (1024 buckets) */
return PATHFIND_HASH_TILE(key1);
}
#endif
/**
* Calculates a hash value for use in the NPF.
* @param key1 The TileIndex of the tile to hash
* @param key2 The Trackdir of the track on the tile.
*
* @todo Think of a better hash.
*/
static uint NPFHash(uint key1, uint key2)
{
/* TODO: think of a better hash? */
uint part1 = TileX(key1) & NPF_HASH_HALFMASK;
uint part2 = TileY(key1) & NPF_HASH_HALFMASK;
assert(IsValidTrackdir((Trackdir)key2));
assert(IsValidTile(key1));
return ((part1 << NPF_HASH_HALFBITS | part2) + (NPF_HASH_SIZE * key2 / TRACKDIR_END)) % NPF_HASH_SIZE;
}
static int32 NPFCalcZero(AyStar *as, AyStarNode *current, OpenListNode *parent)
{
return 0;
}
/* Calcs the heuristic to the target station or tile. For train stations, it
* takes into account the direction of approach.
*/
static int32 NPFCalcStationOrTileHeuristic(AyStar *as, AyStarNode *current, OpenListNode *parent)
{
NPFFindStationOrTileData *fstd = (NPFFindStationOrTileData*)as->user_target;
NPFFoundTargetData *ftd = (NPFFoundTargetData*)as->user_path;
TileIndex from = current->tile;
TileIndex to = fstd->dest_coords;
uint dist;
/* for train-stations, we are going to aim for the closest station tile */
if (as->user_data[NPF_TYPE] == TRANSPORT_RAIL && fstd->station_index != INVALID_STATION)
to = CalcClosestStationTile(fstd->station_index, from);
if (as->user_data[NPF_TYPE] == TRANSPORT_ROAD) {
/* Since roads only have diagonal pieces, we use manhattan distance here */
dist = DistanceManhattan(from, to) * NPF_TILE_LENGTH;
} else {
/* Ships and trains can also go diagonal, so the minimum distance is shorter */
dist = NPFDistanceTrack(from, to);
}
DEBUG(npf, 4, "Calculating H for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), dist);
if (dist < ftd->best_bird_dist) {
ftd->best_bird_dist = dist;
ftd->best_trackdir = (Trackdir)current->user_data[NPF_TRACKDIR_CHOICE];
}
return dist;
}
/* Fills AyStarNode.user_data[NPF_TRACKDIRCHOICE] with the chosen direction to
* get here, either getting it from the current choice or from the parent's
* choice */
static void NPFFillTrackdirChoice(AyStarNode *current, OpenListNode *parent)
{
if (parent->path.parent == NULL) {
Trackdir trackdir = current->direction;
/* This is a first order decision, so we'd better save the
* direction we chose */
current->user_data[NPF_TRACKDIR_CHOICE] = trackdir;
DEBUG(npf, 6, "Saving trackdir: 0x%X", trackdir);
} else {
/* We've already made the decision, so just save our parent's decision */
current->user_data[NPF_TRACKDIR_CHOICE] = parent->path.node.user_data[NPF_TRACKDIR_CHOICE];
}
}
/* Will return the cost of the tunnel. If it is an entry, it will return the
* cost of that tile. If the tile is an exit, it will return the tunnel length
* including the exit tile. Requires that this is a Tunnel tile */
static uint NPFTunnelCost(AyStarNode *current)
{
DiagDirection exitdir = TrackdirToExitdir(current->direction);
TileIndex tile = current->tile;
if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(exitdir)) {
/* We just popped out if this tunnel, since were
* facing the tunnel exit */
return NPF_TILE_LENGTH * (GetTunnelBridgeLength(current->tile, GetOtherTunnelEnd(current->tile)) + 1);
/* @todo: Penalty for tunnels? */
} else {
/* We are entering the tunnel, the enter tile is just a
* straight track */
return NPF_TILE_LENGTH;
}
}
static inline uint NPFBridgeCost(AyStarNode *current)
{
return NPF_TILE_LENGTH * GetTunnelBridgeLength(current->tile, GetOtherBridgeEnd(current->tile));
}
static uint NPFSlopeCost(AyStarNode *current)
{
TileIndex next = current->tile + TileOffsByDiagDir(TrackdirToExitdir(current->direction));
/* Get center of tiles */
int x1 = TileX(current->tile) * TILE_SIZE + TILE_SIZE / 2;
int y1 = TileY(current->tile) * TILE_SIZE + TILE_SIZE / 2;
int x2 = TileX(next) * TILE_SIZE + TILE_SIZE / 2;
int y2 = TileY(next) * TILE_SIZE + TILE_SIZE / 2;
int dx4 = (x2 - x1) / 4;
int dy4 = (y2 - y1) / 4;
/* Get the height on both sides of the tile edge.
* Avoid testing the height on the tile-center. This will fail for halftile-foundations.
*/
int z1 = GetSlopeZ(x1 + dx4, y1 + dy4);
int z2 = GetSlopeZ(x2 - dx4, y2 - dy4);
if (z2 - z1 > 1) {
/* Slope up */
return _settings_game.pf.npf.npf_rail_slope_penalty;
}
return 0;
/* Should we give a bonus for slope down? Probably not, we
* could just substract that bonus from the penalty, because
* there is only one level of steepness... */
}
static uint NPFReservedTrackCost(AyStarNode *current)
{
TileIndex tile = current->tile;
TrackBits track = TrackToTrackBits(TrackdirToTrack(current->direction));
TrackBits res = GetReservedTrackbits(tile);
if (NPFGetFlag(current, NPF_FLAG_3RD_SIGNAL) || ((res & track) == TRACK_BIT_NONE && !TracksOverlap(res | track))) return 0;
if (IsTileType(tile, MP_TUNNELBRIDGE)) {
DiagDirection exitdir = TrackdirToExitdir(current->direction);
if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(exitdir)) {
return _settings_game.pf.npf.npf_rail_pbs_cross_penalty * (GetTunnelBridgeLength(tile, GetOtherTunnelBridgeEnd(tile)) + 1);
}
}
return _settings_game.pf.npf.npf_rail_pbs_cross_penalty;
}
/**
* Mark tiles by mowing the grass when npf debug level >= 1.
* Will not work for multiplayer games, since it can (will) cause desyncs.
*/
static void NPFMarkTile(TileIndex tile)
{
#ifndef NO_DEBUG_MESSAGES
if (_debug_npf_level < 1 || _networking) return;
switch (GetTileType(tile)) {
case MP_RAILWAY:
/* DEBUG: mark visited tiles by mowing the grass under them ;-) */
if (!IsRailDepot(tile)) {
SetRailGroundType(tile, RAIL_GROUND_BARREN);
MarkTileDirtyByTile(tile);
}
break;
case MP_ROAD:
if (!IsRoadDepot(tile)) {
SetRoadside(tile, ROADSIDE_BARREN);
MarkTileDirtyByTile(tile);
}
break;
default:
break;
}
#endif
}
static int32 NPFWaterPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
{
/* TileIndex tile = current->tile; */
int32 cost = 0;
Trackdir trackdir = current->direction;
cost = _trackdir_length[trackdir]; // Should be different for diagonal tracks
if (IsBuoyTile(current->tile) && IsDiagonalTrackdir(trackdir))
cost += _settings_game.pf.npf.npf_buoy_penalty; // A small penalty for going over buoys
if (current->direction != NextTrackdir((Trackdir)parent->path.node.direction))
cost += _settings_game.pf.npf.npf_water_curve_penalty;
/* @todo More penalties? */
return cost;
}
/* Determine the cost of this node, for road tracks */
static int32 NPFRoadPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
{
TileIndex tile = current->tile;
int32 cost = 0;
/* Determine base length */
switch (GetTileType(tile)) {
case MP_TUNNELBRIDGE:
cost = IsTunnel(tile) ? NPFTunnelCost(current) : NPFBridgeCost(current);
break;
case MP_ROAD:
cost = NPF_TILE_LENGTH;
/* Increase the cost for level crossings */
if (IsLevelCrossing(tile)) cost += _settings_game.pf.npf.npf_crossing_penalty;
break;
case MP_STATION:
cost = NPF_TILE_LENGTH;
/* Increase the cost for drive-through road stops */
if (IsDriveThroughStopTile(tile)) cost += _settings_game.pf.npf.npf_road_drive_through_penalty;
break;
default:
break;
}
/* Determine extra costs */
/* Check for slope */
cost += NPFSlopeCost(current);
/* Check for turns. Road vehicles only really drive diagonal, turns are
* represented by non-diagonal tracks */
if (!IsDiagonalTrackdir(current->direction))
cost += _settings_game.pf.npf.npf_road_curve_penalty;
NPFMarkTile(tile);
DEBUG(npf, 4, "Calculating G for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), cost);
return cost;
}
/* Determine the cost of this node, for railway tracks */
static int32 NPFRailPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
{
TileIndex tile = current->tile;
Trackdir trackdir = current->direction;
int32 cost = 0;
/* HACK: We create a OpenListNode manually, so we can call EndNodeCheck */
OpenListNode new_node;
/* Determine base length */
switch (GetTileType(tile)) {
case MP_TUNNELBRIDGE:
cost = IsTunnel(tile) ? NPFTunnelCost(current) : NPFBridgeCost(current);
break;
case MP_RAILWAY:
cost = _trackdir_length[trackdir]; // Should be different for diagonal tracks
break;
case MP_ROAD: // Railway crossing
cost = NPF_TILE_LENGTH;
break;
case MP_STATION:
/* We give a station tile a penalty. Logically we would only want to give
* station tiles that are not our destination this penalty. This would
* discourage trains to drive through busy stations. But, we can just
* give any station tile a penalty, because every possible route will get
* this penalty exactly once, on its end tile (if it's a station) and it
* will therefore not make a difference. */
cost = NPF_TILE_LENGTH + _settings_game.pf.npf.npf_rail_station_penalty;
break;
default:
break;
}
/* Determine extra costs */
/* Check for signals */
if (IsTileType(tile, MP_RAILWAY)) {
if (HasSignalOnTrackdir(tile, trackdir)) {
/* Ordinary track with signals */
if (GetSignalStateByTrackdir(tile, trackdir) == SIGNAL_STATE_RED) {
/* Signal facing us is red */
if (!NPFGetFlag(current, NPF_FLAG_SEEN_SIGNAL)) {
/* Penalize the first signal we
* encounter, if it is red */
/* Is this a presignal exit or combo? */
SignalType sigtype = GetSignalType(tile, TrackdirToTrack(trackdir));
if (!IsPbsSignal(sigtype)) {
if (sigtype == SIGTYPE_EXIT || sigtype == SIGTYPE_COMBO) {
/* Penalise exit and combo signals differently (heavier) */
cost += _settings_game.pf.npf.npf_rail_firstred_exit_penalty;
} else {
cost += _settings_game.pf.npf.npf_rail_firstred_penalty;
}
}
}
/* Record the state of this signal */
NPFSetFlag(current, NPF_FLAG_LAST_SIGNAL_RED, true);
} else {
/* Record the state of this signal */
NPFSetFlag(current, NPF_FLAG_LAST_SIGNAL_RED, false);
}
if (NPFGetFlag(current, NPF_FLAG_SEEN_SIGNAL)) {
if (NPFGetFlag(current, NPF_FLAG_2ND_SIGNAL)) {
NPFSetFlag(current, NPF_FLAG_3RD_SIGNAL, true);
} else {
NPFSetFlag(current, NPF_FLAG_2ND_SIGNAL, true);
}
} else {
NPFSetFlag(current, NPF_FLAG_SEEN_SIGNAL, true);
}
}
if (HasPbsSignalOnTrackdir(tile, ReverseTrackdir(trackdir)) && !NPFGetFlag(current, NPF_FLAG_3RD_SIGNAL)) {
cost += _settings_game.pf.npf.npf_rail_pbs_signal_back_penalty;
}
}
/* Penalise the tile if it is a target tile and the last signal was
* red */
/* HACK: We create a new_node here so we can call EndNodeCheck. Ugly as hell
* of course... */
new_node.path.node = *current;
if (as->EndNodeCheck(as, &new_node) == AYSTAR_FOUND_END_NODE && NPFGetFlag(current, NPF_FLAG_LAST_SIGNAL_RED))
cost += _settings_game.pf.npf.npf_rail_lastred_penalty;
/* Check for slope */
cost += NPFSlopeCost(current);
/* Check for turns */
if (current->direction != NextTrackdir((Trackdir)parent->path.node.direction))
cost += _settings_game.pf.npf.npf_rail_curve_penalty;
/* TODO, with realistic acceleration, also the amount of straight track between
* curves should be taken into account, as this affects the speed limit. */
/* Check for reverse in depot */
if (IsRailDepotTile(tile) && as->EndNodeCheck(as, &new_node) != AYSTAR_FOUND_END_NODE) {
/* Penalise any depot tile that is not the last tile in the path. This
* _should_ penalise every occurence of reversing in a depot (and only
* that) */
cost += _settings_game.pf.npf.npf_rail_depot_reverse_penalty;
}
/* Check for occupied track */
cost += NPFReservedTrackCost(current);
NPFMarkTile(tile);
DEBUG(npf, 4, "Calculating G for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), cost);
return cost;
}
/* Will find any depot */
static int32 NPFFindDepot(AyStar *as, OpenListNode *current)
{
/* It's not worth caching the result with NPF_FLAG_IS_TARGET here as below,
* since checking the cache not that much faster than the actual check */
return IsDepotTypeTile(current->path.node.tile, (TransportType)as->user_data[NPF_TYPE]) ?
AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
}
/** Find any safe and free tile. */
static int32 NPFFindSafeTile(AyStar *as, OpenListNode *current)
{
const Vehicle *v = ((NPFFindStationOrTileData*)as->user_target)->v;
return
IsSafeWaitingPosition(v, current->path.node.tile, current->path.node.direction, true, _settings_game.pf.forbid_90_deg) &&
IsWaitingPositionFree(v, current->path.node.tile, current->path.node.direction, _settings_game.pf.forbid_90_deg) ?
AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
}
/* Will find a station identified using the NPFFindStationOrTileData */
static int32 NPFFindStationOrTile(AyStar *as, OpenListNode *current)
{
NPFFindStationOrTileData *fstd = (NPFFindStationOrTileData*)as->user_target;
AyStarNode *node = ¤t->path.node;
TileIndex tile = node->tile;
/* If GetNeighbours said we could get here, we assume the station type
* is correct */
if (
(fstd->station_index == INVALID_STATION && tile == fstd->dest_coords) || // We've found the tile, or
(IsTileType(tile, MP_STATION) && GetStationIndex(tile) == fstd->station_index) // the station
) {
return AYSTAR_FOUND_END_NODE;
} else {
return AYSTAR_DONE;
}
}
/**
* Find the node containing the first signal on the path.
*
* If the first signal is on the very first two tiles of the path,
* the second signal is returnd. If no suitable signal is present, the
* last node of the path is returned.
*/
static const PathNode *FindSafePosition(PathNode *path, const Vehicle *v)
{
/* If there is no signal, reserve the whole path. */
PathNode *sig = path;
for(; path->parent != NULL; path = path->parent) {
if (IsSafeWaitingPosition(v, path->node.tile, path->node.direction, true, _settings_game.pf.forbid_90_deg)) {
sig = path;
}
}
return sig;
}
/**
* Lift the reservation of the tiles from @p start till @p end, excluding @p end itself.
*/
static void ClearPathReservation(const PathNode *start, const PathNode *end)
{
bool first_run = true;
for (; start != end; start = start->parent) {
if (IsRailwayStationTile(start->node.tile) && first_run) {
SetRailwayStationPlatformReservation(start->node.tile, TrackdirToExitdir(start->node.direction), false);
} else {
UnreserveRailTrack(start->node.tile, TrackdirToTrack(start->node.direction));
}
first_run = false;
}
}
/**
* To be called when @p current contains the (shortest route to) the target node.
* Will fill the contents of the NPFFoundTargetData using
* AyStarNode[NPF_TRACKDIR_CHOICE]. If requested, path reservation
* is done here.
*/
static void NPFSaveTargetData(AyStar *as, OpenListNode *current)
{
NPFFoundTargetData *ftd = (NPFFoundTargetData*)as->user_path;
ftd->best_trackdir = (Trackdir)current->path.node.user_data[NPF_TRACKDIR_CHOICE];
ftd->best_path_dist = current->g;
ftd->best_bird_dist = 0;
ftd->node = current->path.node;
ftd->res_okay = false;
if (as->user_target != NULL && ((NPFFindStationOrTileData*)as->user_target)->reserve_path && as->user_data[NPF_TYPE] == TRANSPORT_RAIL) {
/* Path reservation is requested. */
const Vehicle *v = ((NPFFindStationOrTileData*)as->user_target)->v;
const PathNode *target = FindSafePosition(¤t->path, v);
ftd->node = target->node;
/* If the target is a station skip to platform end. */
if (IsRailwayStationTile(target->node.tile)) {
DiagDirection dir = TrackdirToExitdir(target->node.direction);
uint len = GetStationByTile(target->node.tile)->GetPlatformLength(target->node.tile, dir);
TileIndex end_tile = TILE_ADD(target->node.tile, (len - 1) * TileOffsByDiagDir(dir));
/* Update only end tile, trackdir of a station stays the same. */
ftd->node.tile = end_tile;
if (!IsWaitingPositionFree(v, end_tile, target->node.direction, _settings_game.pf.forbid_90_deg)) return;
SetRailwayStationPlatformReservation(target->node.tile, dir, true);
SetRailwayStationReservation(target->node.tile, false);
} else {
if (!IsWaitingPositionFree(v, target->node.tile, target->node.direction, _settings_game.pf.forbid_90_deg)) return;
}
for (const PathNode *cur = target; cur->parent != NULL; cur = cur->parent) {
if (!TryReserveRailTrack(cur->node.tile, TrackdirToTrack(cur->node.direction))) {
/* Reservation failed, undo. */
ClearPathReservation(target, cur);
return;
}
}
ftd->res_okay = true;
}
}
/**
* Finds out if a given company's vehicles are allowed to enter a given tile.
* @param owner The owner of the vehicle.
* @param tile The tile that is about to be entered.
* @param enterdir The direction in which the vehicle wants to enter the tile.
* @return true if the vehicle can enter the tile.
* @todo This function should be used in other places than just NPF,
* maybe moved to another file too.
*/
static bool CanEnterTileOwnerCheck(Owner owner, TileIndex tile, DiagDirection enterdir)
{
if (IsTileType(tile, MP_RAILWAY) || // Rail tile (also rail depot)
IsRailwayStationTile(tile) || // Rail station tile
IsRoadDepotTile(tile) || // Road depot tile
IsStandardRoadStopTile(tile)) { // Road station tile (but not drive-through stops)
return IsTileOwner(tile, owner); // You need to own these tiles entirely to use them
}
switch (GetTileType(tile)) {
case MP_ROAD:
/* rail-road crossing : are we looking at the railway part? */
if (IsLevelCrossing(tile) &&
DiagDirToAxis(enterdir) != GetCrossingRoadAxis(tile)) {
return IsTileOwner(tile, owner); // Railway needs owner check, while the street is public
}
break;
case MP_TUNNELBRIDGE:
if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
return IsTileOwner(tile, owner);
}
break;
default:
break;
}
return true; // no need to check
}
/**
* Returns the direction the exit of the depot on the given tile is facing.
*/
static DiagDirection GetDepotDirection(TileIndex tile, TransportType type)
{
assert(IsDepotTypeTile(tile, type));
switch (type) {
case TRANSPORT_RAIL: return GetRailDepotDirection(tile);
case TRANSPORT_ROAD: return GetRoadDepotDirection(tile);
case TRANSPORT_WATER: return GetShipDepotDirection(tile);
default: return INVALID_DIAGDIR; // Not reached
}
}
/** Tests if a tile is a road tile with a single tramtrack (tram can reverse) */
static DiagDirection GetSingleTramBit(TileIndex tile)
{
if (IsNormalRoadTile(tile)) {
RoadBits rb = GetRoadBits(tile, ROADTYPE_TRAM);
switch (rb) {
case ROAD_NW: return DIAGDIR_NW;
case ROAD_SW: return DIAGDIR_SW;
case ROAD_SE: return DIAGDIR_SE;
case ROAD_NE: return DIAGDIR_NE;
default: break;
}
}
return INVALID_DIAGDIR;
}
/**
* Tests if a tile can be entered or left only from one side.
*
* Depots, non-drive-through roadstops, and tiles with single trambits are tested.
*
* @param tile The tile of interest.
* @param type The transporttype of the vehicle.
* @param subtype For TRANSPORT_ROAD the compatible RoadTypes of the vehicle.
* @return The single entry/exit-direction of the tile, or INVALID_DIAGDIR if there are more or less directions
*/
static DiagDirection GetTileSingleEntry(TileIndex tile, TransportType type, uint subtype)
{
if (type != TRANSPORT_WATER && IsDepotTypeTile(tile, type)) return GetDepotDirection(tile, type);
if (type == TRANSPORT_ROAD) {
if (IsStandardRoadStopTile(tile)) return GetRoadStopDir(tile);
if (HasBit(subtype, ROADTYPE_TRAM)) return GetSingleTramBit(tile);
}
return INVALID_DIAGDIR;
}
/**
* Tests if a vehicle must reverse on a tile.
*
* @param tile The tile of interest.
* @param dir The direction in which the vehicle drives on a tile.
* @param type The transporttype of the vehicle.
* @param subtype For TRANSPORT_ROAD the compatible RoadTypes of the vehicle.
* @return true iff the vehicle must reverse on the tile.
*/
static inline bool ForceReverse(TileIndex tile, DiagDirection dir, TransportType type, uint subtype)
{
DiagDirection single_entry = GetTileSingleEntry(tile, type, subtype);
return single_entry != INVALID_DIAGDIR && single_entry != dir;
}
/**
* Tests if a vehicle can enter a tile.
*
* @param tile The tile of interest.
* @param dir The direction in which the vehicle drives onto a tile.
* @param type The transporttype of the vehicle.
* @param subtype For TRANSPORT_ROAD the compatible RoadTypes of the vehicle.
* @param railtypes For TRANSPORT_RAIL the compatible RailTypes of the vehicle.
* @param owner The owner of the vehicle.
* @return true iff the vehicle can enter the tile.
*/
static bool CanEnterTile(TileIndex tile, DiagDirection dir, TransportType type, uint subtype, RailTypes railtypes, Owner owner)
{
/* Check tunnel entries and bridge ramps */
if (IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(tile) != dir) return false;
/* Test ownership */
if (!CanEnterTileOwnerCheck(owner, tile, dir)) return false;
/* check correct rail type (mono, maglev, etc) */
if (type == TRANSPORT_RAIL) {
RailType rail_type = GetTileRailType(tile);
if (!HasBit(railtypes, rail_type)) return false;
}
/* Depots, standard roadstops and single tram bits can only be entered from one direction */
DiagDirection single_entry = GetTileSingleEntry(tile, type, subtype);
if (single_entry != INVALID_DIAGDIR && single_entry != ReverseDiagDir(dir)) return false;
return true;
}
/**
* Returns the driveable Trackdirs on a tile.
*
* One-way-roads are taken into account. Signals are not tested.
*
* @param dst_tile The tile of interest.
* @param src_trackdir The direction the vehicle is currently moving.
* @param type The transporttype of the vehicle.
* @param subtype For TRANSPORT_ROAD the compatible RoadTypes of the vehicle.
* @return The Trackdirs the vehicle can continue moving on.
*/
static TrackdirBits GetDriveableTrackdirBits(TileIndex dst_tile, Trackdir src_trackdir, TransportType type, uint subtype)
{
TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(dst_tile, type, subtype));
if (trackdirbits == 0 && type == TRANSPORT_ROAD && HasBit(subtype, ROADTYPE_TRAM)) {
/* GetTileTrackStatus() returns 0 for single tram bits.
* As we cannot change it there (easily) without breaking something, change it here */
switch (GetSingleTramBit(dst_tile)) {
case DIAGDIR_NE:
case DIAGDIR_SW:
trackdirbits = TRACKDIR_BIT_X_NE | TRACKDIR_BIT_X_SW;
break;
case DIAGDIR_NW:
case DIAGDIR_SE:
trackdirbits = TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_Y_SE;
break;
default: break;
}
}
DEBUG(npf, 4, "Next node: (%d, %d) [%d], possible trackdirs: 0x%X", TileX(dst_tile), TileY(dst_tile), dst_tile, trackdirbits);
/* Select only trackdirs we can reach from our current trackdir */
trackdirbits &= TrackdirReachesTrackdirs(src_trackdir);
/* Filter out trackdirs that would make 90 deg turns for trains */
if (_settings_game.pf.forbid_90_deg && (type == TRANSPORT_RAIL || type == TRANSPORT_WATER)) trackdirbits &= ~TrackdirCrossesTrackdirs(src_trackdir);
DEBUG(npf, 6, "After filtering: (%d, %d), possible trackdirs: 0x%X", TileX(dst_tile), TileY(dst_tile), trackdirbits);
return trackdirbits;
}
/* Will just follow the results of GetTileTrackStatus concerning where we can
* go and where not. Uses AyStar.user_data[NPF_TYPE] as the transport type and
* an argument to GetTileTrackStatus. Will skip tunnels, meaning that the
* entry and exit are neighbours. Will fill
* AyStarNode.user_data[NPF_TRACKDIR_CHOICE] with an appropriate value, and
* copy AyStarNode.user_data[NPF_NODE_FLAGS] from the parent */
static void NPFFollowTrack(AyStar *aystar, OpenListNode *current)
{
/* We leave src_tile on track src_trackdir in direction src_exitdir */
Trackdir src_trackdir = current->path.node.direction;
TileIndex src_tile = current->path.node.tile;
DiagDirection src_exitdir = TrackdirToExitdir(src_trackdir);
/* Is src_tile valid, and can be used?
* When choosing track on a junction src_tile is the tile neighboured to the junction wrt. exitdir.
* But we must not check the validity of this move, as src_tile is totally unrelated to the move, if a roadvehicle reversed on a junction. */
bool ignore_src_tile = (current->path.parent == NULL && NPFGetFlag(¤t->path.node, NPF_FLAG_IGNORE_START_TILE));
/* Information about the vehicle: TransportType (road/rail/water) and SubType (compatible rail/road types) */
TransportType type = (TransportType)aystar->user_data[NPF_TYPE];
uint subtype = aystar->user_data[NPF_SUB_TYPE];
/* Initialize to 0, so we can jump out (return) somewhere an have no neighbours */
aystar->num_neighbours = 0;
DEBUG(npf, 4, "Expanding: (%d, %d, %d) [%d]", TileX(src_tile), TileY(src_tile), src_trackdir, src_tile);
/* We want to determine the tile we arrive, and which choices we have there */
TileIndex dst_tile;
TrackdirBits trackdirbits;
/* Find dest tile */
if (ignore_src_tile) {
/* Do not perform any checks that involve src_tile */
dst_tile = src_tile + TileOffsByDiagDir(src_exitdir);
trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
} else if (IsTileType(src_tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(src_tile) == src_exitdir) {
/* We drive through the wormhole and arrive on the other side */
dst_tile = GetOtherTunnelBridgeEnd(src_tile);
trackdirbits = TrackdirToTrackdirBits(src_trackdir);
} else if (ForceReverse(src_tile, src_exitdir, type, subtype)) {
/* We can only reverse on this tile */
dst_tile = src_tile;
src_trackdir = ReverseTrackdir(src_trackdir);
trackdirbits = TrackdirToTrackdirBits(src_trackdir);
} else {
/* We leave src_tile in src_exitdir and reach dst_tile */
dst_tile = AddTileIndexDiffCWrap(src_tile, TileIndexDiffCByDiagDir(src_exitdir));
if (dst_tile != INVALID_TILE && !CanEnterTile(dst_tile, src_exitdir, type, subtype, (RailTypes)aystar->user_data[NPF_RAILTYPES], (Owner)aystar->user_data[NPF_OWNER])) dst_tile = INVALID_TILE;
if (dst_tile == INVALID_TILE) {
/* We cannot enter the next tile. Road vehicles can reverse, others reach dead end */
if (type != TRANSPORT_ROAD || HasBit(subtype, ROADTYPE_TRAM)) return;
dst_tile = src_tile;
src_trackdir = ReverseTrackdir(src_trackdir);
}
trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
if (trackdirbits == 0) {
/* We cannot enter the next tile. Road vehicles can reverse, others reach dead end */
if (type != TRANSPORT_ROAD || HasBit(subtype, ROADTYPE_TRAM)) return;
dst_tile = src_tile;
src_trackdir = ReverseTrackdir(src_trackdir);
trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
}
}
if (NPFGetFlag(¤t->path.node, NPF_FLAG_IGNORE_RESERVED)) {
/* Mask out any reserved tracks. */
TrackBits reserved = GetReservedTrackbits(dst_tile);
trackdirbits &= ~TrackBitsToTrackdirBits(reserved);
uint bits = TrackdirBitsToTrackBits(trackdirbits);
int i;
FOR_EACH_SET_BIT(i, bits) {
if (TracksOverlap(reserved | TrackToTrackBits((Track)i))) trackdirbits &= ~TrackToTrackdirBits((Track)i);
}
}
/* Enumerate possible track */
uint i = 0;
while (trackdirbits != 0) {
Trackdir dst_trackdir = RemoveFirstTrackdir(&trackdirbits);
DEBUG(npf, 5, "Expanded into trackdir: %d, remaining trackdirs: 0x%X", dst_trackdir, trackdirbits);
/* Tile with signals? */
if (IsTileType(dst_tile, MP_RAILWAY) && GetRailTileType(dst_tile) == RAIL_TILE_SIGNALS) {
if (HasSignalOnTrackdir(dst_tile, ReverseTrackdir(dst_trackdir)) && !HasSignalOnTrackdir(dst_tile, dst_trackdir) && IsOnewaySignal(dst_tile, TrackdirToTrack(dst_trackdir)))
/* If there's a one-way signal not pointing towards us, stop going in this direction. */
break;
}
{
/* We've found ourselves a neighbour :-) */
AyStarNode *neighbour = &aystar->neighbours[i];
neighbour->tile = dst_tile;
neighbour->direction = dst_trackdir;
/* Save user data */
neighbour->user_data[NPF_NODE_FLAGS] = current->path.node.user_data[NPF_NODE_FLAGS];
NPFFillTrackdirChoice(neighbour, current);
}
i++;
}
aystar->num_neighbours = i;
}
/*
* Plan a route to the specified target (which is checked by target_proc),
* from start1 and if not NULL, from start2 as well. The type of transport we
* are checking is in type. reverse_penalty is applied to all routes that
* originate from the second start node.
* When we are looking for one specific target (optionally multiple tiles), we
* should use a good heuristic to perform aystar search. When we search for
* multiple targets that are spread around, we should perform a breadth first
* search by specifiying CalcZero as our heuristic.
*/
static NPFFoundTargetData NPFRouteInternal(AyStarNode *start1, bool ignore_start_tile1, AyStarNode *start2, bool ignore_start_tile2, NPFFindStationOrTileData *target, AyStar_EndNodeCheck target_proc, AyStar_CalculateH heuristic_proc, TransportType type, uint sub_type, Owner owner, RailTypes railtypes, uint reverse_penalty)
{
int r;
NPFFoundTargetData result;
/* Initialize procs */
_npf_aystar.CalculateH = heuristic_proc;
_npf_aystar.EndNodeCheck = target_proc;
_npf_aystar.FoundEndNode = NPFSaveTargetData;
_npf_aystar.GetNeighbours = NPFFollowTrack;
switch (type) {
default: NOT_REACHED();
case TRANSPORT_RAIL: _npf_aystar.CalculateG = NPFRailPathCost; break;
case TRANSPORT_ROAD: _npf_aystar.CalculateG = NPFRoadPathCost; break;
case TRANSPORT_WATER: _npf_aystar.CalculateG = NPFWaterPathCost; break;
}
/* Initialize Start Node(s) */
start1->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
start1->user_data[NPF_NODE_FLAGS] = 0;
NPFSetFlag(start1, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile1);
_npf_aystar.addstart(&_npf_aystar, start1, 0);
if (start2) {
start2->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
start2->user_data[NPF_NODE_FLAGS] = 0;
NPFSetFlag(start2, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile2);
NPFSetFlag(start2, NPF_FLAG_REVERSE, true);
_npf_aystar.addstart(&_npf_aystar, start2, reverse_penalty);
}
/* Initialize result */
result.best_bird_dist = UINT_MAX;
result.best_path_dist = UINT_MAX;
result.best_trackdir = INVALID_TRACKDIR;
result.node.tile = INVALID_TILE;
result.res_okay = false;
_npf_aystar.user_path = &result;
/* Initialize target */
_npf_aystar.user_target = target;
/* Initialize user_data */
_npf_aystar.user_data[NPF_TYPE] = type;
_npf_aystar.user_data[NPF_SUB_TYPE] = sub_type;
_npf_aystar.user_data[NPF_OWNER] = owner;
_npf_aystar.user_data[NPF_RAILTYPES] = railtypes;
/* GO! */
r = AyStarMain_Main(&_npf_aystar);
assert(r != AYSTAR_STILL_BUSY);
if (result.best_bird_dist != 0) {
if (target != NULL) {
DEBUG(npf, 1, "Could not find route to tile 0x%X from 0x%X.", target->dest_coords, start1->tile);
} else {
/* Assumption: target == NULL, so we are looking for a depot */
DEBUG(npf, 1, "Could not find route to a depot from tile 0x%X.", start1->tile);
}
}
return result;
}
NPFFoundTargetData NPFRouteToStationOrTileTwoWay(TileIndex tile1, Trackdir trackdir1, bool ignore_start_tile1, TileIndex tile2, Trackdir trackdir2, bool ignore_start_tile2, NPFFindStationOrTileData *target, TransportType type, uint sub_type, Owner owner, RailTypes railtypes)
{
AyStarNode start1;
AyStarNode start2;
start1.tile = tile1;
start2.tile = tile2;
/* We set this in case the target is also the start tile, we will just
* return a not found then */
start1.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
start1.direction = trackdir1;
start2.direction = trackdir2;
start2.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : NULL), ignore_start_tile2, target, NPFFindStationOrTile, NPFCalcStationOrTileHeuristic, type, sub_type, owner, railtypes, 0);
}
NPFFoundTargetData NPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, NPFFindStationOrTileData *target, TransportType type, uint sub_type, Owner owner, RailTypes railtypes)
{
return NPFRouteToStationOrTileTwoWay(tile, trackdir, ignore_start_tile, INVALID_TILE, INVALID_TRACKDIR, false, target, type, sub_type, owner, railtypes);
}
NPFFoundTargetData NPFRouteToDepotBreadthFirstTwoWay(TileIndex tile1, Trackdir trackdir1, bool ignore_start_tile1, TileIndex tile2, Trackdir trackdir2, bool ignore_start_tile2, TransportType type, uint sub_type, Owner owner, RailTypes railtypes, uint reverse_penalty)
{
AyStarNode start1;
AyStarNode start2;
start1.tile = tile1;
start2.tile = tile2;
/* We set this in case the target is also the start tile, we will just
* return a not found then */
start1.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
start1.direction = trackdir1;
start2.direction = trackdir2;
start2.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
/* perform a breadth first search. Target is NULL,
* since we are just looking for any depot...*/
return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : NULL), ignore_start_tile2, NULL, NPFFindDepot, NPFCalcZero, type, sub_type, owner, railtypes, reverse_penalty);
}
NPFFoundTargetData NPFRouteToDepotBreadthFirst(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, TransportType type, uint sub_type, Owner owner, RailTypes railtypes)
{
return NPFRouteToDepotBreadthFirstTwoWay(tile, trackdir, ignore_start_tile, INVALID_TILE, INVALID_TRACKDIR, false, type, sub_type, owner, railtypes, 0);
}
NPFFoundTargetData NPFRouteToDepotTrialError(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, TransportType type, uint sub_type, Owner owner, RailTypes railtypes)
{
/* Okay, what we're gonna do. First, we look at all depots, calculate
* the manhatten distance to get to each depot. We then sort them by
* distance. We start by trying to plan a route to the closest, then
* the next closest, etc. We stop when the best route we have found so
* far, is shorter than the manhattan distance. This will obviously
* always find the closest depot. It will probably be most efficient
* for ships, since the heuristic will not be to far off then. I hope.
*/
Queue depots;
int r;
NPFFoundTargetData best_result = {UINT_MAX, UINT_MAX, INVALID_TRACKDIR, {INVALID_TILE, INVALID_TRACKDIR, {0, 0}}, false};
NPFFoundTargetData result;
NPFFindStationOrTileData target;
AyStarNode start;
Depot *current;
Depot *depot;
init_InsSort(&depots);
/* Okay, let's find all depots that we can use first */
FOR_ALL_DEPOTS(depot) {
/* Check if this is really a valid depot, it is of the needed type and
* owner */
if (IsDepotTypeTile(depot->xy, type) && IsTileOwner(depot->xy, owner))
/* If so, let's add it to the queue, sorted by distance */
depots.push(&depots, depot, DistanceManhattan(tile, depot->xy));
}
/* Now, let's initialise the aystar */
/* Initialize procs */
_npf_aystar.CalculateH = NPFCalcStationOrTileHeuristic;
_npf_aystar.EndNodeCheck = NPFFindStationOrTile;
_npf_aystar.FoundEndNode = NPFSaveTargetData;
_npf_aystar.GetNeighbours = NPFFollowTrack;
switch (type) {
default: NOT_REACHED();
case TRANSPORT_RAIL: _npf_aystar.CalculateG = NPFRailPathCost; break;
case TRANSPORT_ROAD: _npf_aystar.CalculateG = NPFRoadPathCost; break;
case TRANSPORT_WATER: _npf_aystar.CalculateG = NPFWaterPathCost; break;
}
/* Initialize target */
target.station_index = INVALID_STATION; // We will initialize dest_coords inside the loop below
_npf_aystar.user_target = ⌖
/* Initialize user_data */
_npf_aystar.user_data[NPF_TYPE] = type;
_npf_aystar.user_data[NPF_SUB_TYPE] = sub_type;
_npf_aystar.user_data[NPF_OWNER] = owner;
/* Initialize Start Node */
start.tile = tile;
start.direction = trackdir; // We will initialize user_data inside the loop below
/* Initialize Result */
_npf_aystar.user_path = &result;
best_result.best_path_dist = UINT_MAX;
best_result.best_bird_dist = UINT_MAX;
/* Just iterate the depots in order of increasing distance */
while ((current = (Depot*)depots.pop(&depots))) {
/* Check to see if we already have a path shorter than this
* depot's manhattan distance. HACK: We call DistanceManhattan
* again, we should probably modify the queue to give us that
* value... */
if ( DistanceManhattan(tile, current->xy * NPF_TILE_LENGTH) > best_result.best_path_dist)
break;
/* Initialize Start Node
* We set this in case the target is also the start tile, we will just
* return a not found then */
start.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
start.user_data[NPF_NODE_FLAGS] = 0;
NPFSetFlag(&start, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile);
_npf_aystar.addstart(&_npf_aystar, &start, 0);
/* Initialize result */
result.best_bird_dist = UINT_MAX;
result.best_path_dist = UINT_MAX;
result.best_trackdir = INVALID_TRACKDIR;
/* Initialize target */
target.dest_coords = current->xy;
/* GO! */
r = AyStarMain_Main(&_npf_aystar);
assert(r != AYSTAR_STILL_BUSY);
/* This depot is closer */
if (result.best_path_dist < best_result.best_path_dist)
best_result = result;
}
if (result.best_bird_dist != 0) {
DEBUG(npf, 1, "Could not find route to any depot from tile 0x%X.", tile);
}
return best_result;
}
NPFFoundTargetData NPFRouteToSafeTile(const Vehicle *v, TileIndex tile, Trackdir trackdir, bool override_railtype)
{
assert(v->type == VEH_TRAIN);
NPFFindStationOrTileData fstd;
fstd.v = v;
fstd.reserve_path = true;
AyStarNode start1;
start1.tile = tile;
/* We set this in case the target is also the start tile, we will just
* return a not found then */
start1.user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
start1.direction = trackdir;
NPFSetFlag(&start1, NPF_FLAG_IGNORE_RESERVED, true);
RailTypes railtypes = v->u.rail.compatible_railtypes;
if (override_railtype) railtypes |= GetRailTypeInfo(v->u.rail.railtype)->compatible_railtypes;
/* perform a breadth first search. Target is NULL,
* since we are just looking for any safe tile...*/
return NPFRouteInternal(&start1, true, NULL, false, &fstd, NPFFindSafeTile, NPFCalcZero, TRANSPORT_RAIL, 0, v->owner, railtypes, 0);
}
void InitializeNPF()
{
static bool first_init = true;
if (first_init) {
first_init = false;
init_AyStar(&_npf_aystar, NPFHash, NPF_HASH_SIZE);
} else {
AyStarMain_Clear(&_npf_aystar);
}
_npf_aystar.loops_per_tick = 0;
_npf_aystar.max_path_cost = 0;
//_npf_aystar.max_search_nodes = 0;
/* We will limit the number of nodes for now, until we have a better
* solution to really fix performance */
_npf_aystar.max_search_nodes = _settings_game.pf.npf.npf_max_search_nodes;
}
void NPFFillWithOrderData(NPFFindStationOrTileData *fstd, Vehicle *v, bool reserve_path)
{
/* Ships don't really reach their stations, but the tile in front. So don't
* save the station id for ships. For roadvehs we don't store it either,
* because multistop depends on vehicles actually reaching the exact
* dest_tile, not just any stop of that station.
* So only for train orders to stations we fill fstd->station_index, for all
* others only dest_coords */
if (v->current_order.IsType(OT_GOTO_STATION) && v->type == VEH_TRAIN) {
fstd->station_index = v->current_order.GetDestination();
/* Let's take the closest tile of the station as our target for trains */
fstd->dest_coords = CalcClosestStationTile(fstd->station_index, v->tile);
} else {
fstd->dest_coords = v->dest_tile;
fstd->station_index = INVALID_STATION;
}
fstd->reserve_path = reserve_path;
fstd->v = v;
}
| 41,824
|
C++
|
.cpp
| 952
| 41.314076
| 324
| 0.736127
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,086
|
thread_os2.cpp
|
EnergeticBark_OpenTTD-3DS/src/thread_os2.cpp
|
/* $Id$ */
/** @file thread_os2.cpp OS/2 implementation of Threads. */
#include "stdafx.h"
#include "thread.h"
#define INCL_DOS
#include <os2.h>
#include <process.h>
/**
* OS/2 version for ThreadObject.
*/
class ThreadObject_OS2 : public ThreadObject {
private:
TID thread; ///< System thread identifier.
OTTDThreadFunc proc; ///< External thread procedure.
void *param; ///< Parameter for the external thread procedure.
bool self_destruct; ///< Free ourselves when done?
public:
/**
* Create a thread and start it, calling proc(param).
*/
ThreadObject_OS2(OTTDThreadFunc proc, void *param, bool self_destruct) :
thread(0),
proc(proc),
param(param),
self_destruct(self_destruct)
{
thread = _beginthread(stThreadProc, NULL, 32768, this);
}
/* virtual */ bool Exit()
{
_endthread();
return true;
}
/* virtual */ void Join()
{
DosWaitThread(&this->thread, DCWW_WAIT);
this->thread = 0;
}
private:
/**
* On thread creation, this function is called, which calls the real startup
* function. This to get back into the correct instance again.
*/
static void stThreadProc(void *thr)
{
((ThreadObject_OS2 *)thr)->ThreadProc();
}
/**
* A new thread is created, and this function is called. Call the custom
* function of the creator of the thread.
*/
void ThreadProc()
{
/* Call the proc of the creator to continue this thread */
try {
this->proc(this->param);
} catch (OTTDThreadExitSignal e) {
} catch (...) {
NOT_REACHED();
}
if (self_destruct) {
this->Exit();
delete this;
}
}
};
/* static */ bool ThreadObject::New(OTTDThreadFunc proc, void *param, ThreadObject **thread)
{
ThreadObject *to = new ThreadObject_OS2(proc, param, thread == NULL);
if (thread != NULL) *thread = to;
return true;
}
/**
* OS/2 version of ThreadMutex.
*/
class ThreadMutex_OS2 : public ThreadMutex {
private:
HMTX mutex;
public:
ThreadMutex_OS2()
{
DosCreateMutexSem(NULL, &mutex, 0, FALSE);
}
/* virtual */ ~ThreadMutex_OS2()
{
DosCloseMutexSem(mutex);
}
/* virtual */ void BeginCritical()
{
DosRequestMutexSem(mutex, (unsigned long) SEM_INDEFINITE_WAIT);
}
/* virtual */ void EndCritical()
{
DosReleaseMutexSem(mutex);
}
};
/* static */ ThreadMutex *ThreadMutex::New()
{
return new ThreadMutex_OS2();
}
| 2,324
|
C++
|
.cpp
| 100
| 20.95
| 92
| 0.69067
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,087
|
md5.cpp
|
EnergeticBark_OpenTTD-3DS/src/md5.cpp
|
/* $Id$ */
/** @file md5.cpp Creating MD5 checksums of files. */
/*
Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.c is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
2007-12-24 Changed to C++ and adapted to OpenTTD source
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
either statically or dynamically; added missing #include <string.h>
in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
unsigned in ANSI C, signed in traditional"; made test program
self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
#include "stdafx.h"
#include "core/bitmath_func.hpp"
#include "core/endian_func.hpp"
#include "md5.h"
#define T_MASK ((uint32)~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
static inline void Md5Set1(const uint32 *X, uint32 *a, const uint32 *b, const uint32 *c, const uint32 *d, const uint8 k, const uint8 s, const uint32 Ti)
{
uint32 t = (*b & *c) | (~*b & *d);
t += *a + X[k] + Ti;
*a = ROL(t, s) + *b;
}
static inline void Md5Set2(const uint32 *X, uint32 *a, const uint32 *b, const uint32 *c, const uint32 *d, const uint8 k, const uint8 s, const uint32 Ti)
{
uint32 t = (*b & *d) | (*c & ~*d);
t += *a + X[k] + Ti;
*a = ROL(t, s) + *b;
}
static inline void Md5Set3(const uint32 *X, uint32 *a, const uint32 *b, const uint32 *c, const uint32 *d, const uint8 k, const uint8 s, const uint32 Ti)
{
uint32 t = *b ^ *c ^ *d;
t += *a + X[k] + Ti;
*a = ROL(t, s) + *b;
}
static inline void Md5Set4(const uint32 *X, uint32 *a, const uint32 *b, const uint32 *c, const uint32 *d, const uint8 k, const uint8 s, const uint32 Ti)
{
uint32 t = *c ^ (*b | ~*d);
t += *a + X[k] + Ti;
*a = ROL(t, s) + *b;
}
Md5::Md5()
{
count[0] = 0;
count[1] = 0;
abcd[0] = 0x67452301;
abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
abcd[3] = 0x10325476;
}
void Md5::Process(const uint8 *data /*[64]*/)
{
uint32 a = this->abcd[0];
uint32 b = this->abcd[1];
uint32 c = this->abcd[2];
uint32 d = this->abcd[3];
uint32 X[16];
/* Convert the uint8 data to uint32 LE */
uint32 *px = (uint32 *)data;
for (uint i = 0; i < 16; i++) {
X[i] = TO_LE32(*px);
px++;
}
/* Round 1. */
Md5Set1(X, &a, &b, &c, &d, 0, 7, T1);
Md5Set1(X, &d, &a, &b, &c, 1, 12, T2);
Md5Set1(X, &c, &d, &a, &b, 2, 17, T3);
Md5Set1(X, &b, &c, &d, &a, 3, 22, T4);
Md5Set1(X, &a, &b, &c, &d, 4, 7, T5);
Md5Set1(X, &d, &a, &b, &c, 5, 12, T6);
Md5Set1(X, &c, &d, &a, &b, 6, 17, T7);
Md5Set1(X, &b, &c, &d, &a, 7, 22, T8);
Md5Set1(X, &a, &b, &c, &d, 8, 7, T9);
Md5Set1(X, &d, &a, &b, &c, 9, 12, T10);
Md5Set1(X, &c, &d, &a, &b, 10, 17, T11);
Md5Set1(X, &b, &c, &d, &a, 11, 22, T12);
Md5Set1(X, &a, &b, &c, &d, 12, 7, T13);
Md5Set1(X, &d, &a, &b, &c, 13, 12, T14);
Md5Set1(X, &c, &d, &a, &b, 14, 17, T15);
Md5Set1(X, &b, &c, &d, &a, 15, 22, T16);
/* Round 2. */
Md5Set2(X, &a, &b, &c, &d, 1, 5, T17);
Md5Set2(X, &d, &a, &b, &c, 6, 9, T18);
Md5Set2(X, &c, &d, &a, &b, 11, 14, T19);
Md5Set2(X, &b, &c, &d, &a, 0, 20, T20);
Md5Set2(X, &a, &b, &c, &d, 5, 5, T21);
Md5Set2(X, &d, &a, &b, &c, 10, 9, T22);
Md5Set2(X, &c, &d, &a, &b, 15, 14, T23);
Md5Set2(X, &b, &c, &d, &a, 4, 20, T24);
Md5Set2(X, &a, &b, &c, &d, 9, 5, T25);
Md5Set2(X, &d, &a, &b, &c, 14, 9, T26);
Md5Set2(X, &c, &d, &a, &b, 3, 14, T27);
Md5Set2(X, &b, &c, &d, &a, 8, 20, T28);
Md5Set2(X, &a, &b, &c, &d, 13, 5, T29);
Md5Set2(X, &d, &a, &b, &c, 2, 9, T30);
Md5Set2(X, &c, &d, &a, &b, 7, 14, T31);
Md5Set2(X, &b, &c, &d, &a, 12, 20, T32);
/* Round 3. */
Md5Set3(X, &a, &b, &c, &d, 5, 4, T33);
Md5Set3(X, &d, &a, &b, &c, 8, 11, T34);
Md5Set3(X, &c, &d, &a, &b, 11, 16, T35);
Md5Set3(X, &b, &c, &d, &a, 14, 23, T36);
Md5Set3(X, &a, &b, &c, &d, 1, 4, T37);
Md5Set3(X, &d, &a, &b, &c, 4, 11, T38);
Md5Set3(X, &c, &d, &a, &b, 7, 16, T39);
Md5Set3(X, &b, &c, &d, &a, 10, 23, T40);
Md5Set3(X, &a, &b, &c, &d, 13, 4, T41);
Md5Set3(X, &d, &a, &b, &c, 0, 11, T42);
Md5Set3(X, &c, &d, &a, &b, 3, 16, T43);
Md5Set3(X, &b, &c, &d, &a, 6, 23, T44);
Md5Set3(X, &a, &b, &c, &d, 9, 4, T45);
Md5Set3(X, &d, &a, &b, &c, 12, 11, T46);
Md5Set3(X, &c, &d, &a, &b, 15, 16, T47);
Md5Set3(X, &b, &c, &d, &a, 2, 23, T48);
/* Round 4. */
Md5Set4(X, &a, &b, &c, &d, 0, 6, T49);
Md5Set4(X, &d, &a, &b, &c, 7, 10, T50);
Md5Set4(X, &c, &d, &a, &b, 14, 15, T51);
Md5Set4(X, &b, &c, &d, &a, 5, 21, T52);
Md5Set4(X, &a, &b, &c, &d, 12, 6, T53);
Md5Set4(X, &d, &a, &b, &c, 3, 10, T54);
Md5Set4(X, &c, &d, &a, &b, 10, 15, T55);
Md5Set4(X, &b, &c, &d, &a, 1, 21, T56);
Md5Set4(X, &a, &b, &c, &d, 8, 6, T57);
Md5Set4(X, &d, &a, &b, &c, 15, 10, T58);
Md5Set4(X, &c, &d, &a, &b, 6, 15, T59);
Md5Set4(X, &b, &c, &d, &a, 13, 21, T60);
Md5Set4(X, &a, &b, &c, &d, 4, 6, T61);
Md5Set4(X, &d, &a, &b, &c, 11, 10, T62);
Md5Set4(X, &c, &d, &a, &b, 2, 15, T63);
Md5Set4(X, &b, &c, &d, &a, 9, 21, T64);
/* Then perform the following additions. (That is increment each
* of the four registers by the value it had before this block
* was started.) */
this->abcd[0] += a;
this->abcd[1] += b;
this->abcd[2] += c;
this->abcd[3] += d;
}
void Md5::Append(const void *data, const size_t nbytes)
{
const uint8 *p = (const uint8 *)data;
size_t left = nbytes;
const size_t offset = (this->count[0] >> 3) & 63;
const uint32 nbits = (uint32)(nbytes << 3);
if (nbytes <= 0) return;
/* Update the message length. */
this->count[1] += (uint32)(nbytes >> 29);
this->count[0] += nbits;
if (this->count[0] < nbits) this->count[1]++;
/* Process an initial partial block. */
if (offset) {
size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(this->buf + offset, p, copy);
if (offset + copy < 64) return;
p += copy;
left -= copy;
this->Process(this->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64) this->Process(p);
/* Process a final partial block. */
if (left) memcpy(this->buf, p, left);
}
void Md5::Finish(uint8 digest[16])
{
static const uint8 pad[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
uint8 data[8];
uint i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
data[i] = (uint8)(this->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
this->Append(pad, ((55 - (this->count[0] >> 3)) & 63) + 1);
/* Append the length. */
this->Append(data, 8);
for (i = 0; i < 16; ++i)
digest[i] = (uint8)(this->abcd[i >> 2] >> ((i & 3) << 3));
}
| 11,222
|
C++
|
.cpp
| 282
| 37.556738
| 152
| 0.612809
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,088
|
sdl.cpp
|
EnergeticBark_OpenTTD-3DS/src/sdl.cpp
|
/* $Id$ */
/** @file sdl.cpp Implementation of SDL support. */
#include "stdafx.h"
#ifdef WITH_SDL
#include "openttd.h"
#include "sdl.h"
#include <SDL.h>
#ifdef UNIX
#include <signal.h>
#ifdef __MORPHOS__
/* The system supplied definition of SIG_DFL is wrong on MorphOS */
#undef SIG_DFL
#define SIG_DFL (void (*)(int))0
#endif
#endif
static int _sdl_usage;
#ifdef DYNAMICALLY_LOADED_SDL
#include "win32.h"
#define M(x) x "\0"
static const char sdl_files[] =
M("sdl.dll")
M("SDL_Init")
M("SDL_InitSubSystem")
M("SDL_GetError")
M("SDL_QuitSubSystem")
M("SDL_UpdateRect")
M("SDL_UpdateRects")
M("SDL_SetColors")
M("SDL_WM_SetCaption")
M("SDL_ShowCursor")
M("SDL_FreeSurface")
M("SDL_PollEvent")
M("SDL_WarpMouse")
M("SDL_GetTicks")
M("SDL_OpenAudio")
M("SDL_PauseAudio")
M("SDL_CloseAudio")
M("SDL_LockSurface")
M("SDL_UnlockSurface")
M("SDL_GetModState")
M("SDL_Delay")
M("SDL_Quit")
M("SDL_SetVideoMode")
M("SDL_EnableKeyRepeat")
M("SDL_EnableUNICODE")
M("SDL_VideoDriverName")
M("SDL_ListModes")
M("SDL_GetKeyState")
M("SDL_LoadBMP_RW")
M("SDL_RWFromFile")
M("SDL_SetColorKey")
M("SDL_WM_SetIcon")
M("SDL_MapRGB")
M("")
;
#undef M
SDLProcs sdl_proc;
static const char *LoadSdlDLL()
{
if (sdl_proc.SDL_Init != NULL)
return NULL;
if (!LoadLibraryList((Function *)(void *)&sdl_proc, sdl_files))
return "Unable to load sdl.dll";
return NULL;
}
#endif /* DYNAMICALLY_LOADED_SDL */
#ifdef UNIX
static void SdlAbort(int sig)
{
/* Own hand-made parachute for the cases of failed assertions. */
SDL_CALL SDL_Quit();
switch (sig) {
case SIGSEGV:
case SIGFPE:
signal(sig, SIG_DFL);
raise(sig);
break;
default:
break;
}
}
#endif
const char *SdlOpen(uint32 x)
{
#ifdef DYNAMICALLY_LOADED_SDL
{
const char *s = LoadSdlDLL();
if (s != NULL) return s;
}
#endif
if (_sdl_usage++ == 0) {
if (SDL_CALL SDL_Init(x) == -1)
return SDL_CALL SDL_GetError();
} else if (x != 0) {
if (SDL_CALL SDL_InitSubSystem(x) == -1)
return SDL_CALL SDL_GetError();
}
#ifdef UNIX
signal(SIGABRT, SdlAbort);
signal(SIGSEGV, SdlAbort);
signal(SIGFPE, SdlAbort);
#endif
return NULL;
}
void SdlClose(uint32 x)
{
if (x != 0)
SDL_CALL SDL_QuitSubSystem(x);
if (--_sdl_usage == 0) {
SDL_CALL SDL_Quit();
#ifdef UNIX
signal(SIGABRT, SIG_DFL);
signal(SIGSEGV, SIG_DFL);
signal(SIGFPE, SIG_DFL);
#endif
}
}
#endif
| 2,396
|
C++
|
.cpp
| 118
| 18.211864
| 68
| 0.689135
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,089
|
intro_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/intro_gui.cpp
|
/* $Id$ */
/** @file intro_gui.cpp The main menu GUI. */
#include "stdafx.h"
#include "openttd.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "network/network.h"
#include "variables.h"
#include "genworld.h"
#include "network/network_gui.h"
#include "network/network_content.h"
#include "landscape_type.h"
#include "strings_func.h"
#include "window_func.h"
#include "fios.h"
#include "settings_type.h"
#include "functions.h"
#include "newgrf_config.h"
#include "ai/ai_gui.hpp"
#include "gfx_func.h"
#include "table/strings.h"
#include "table/sprites.h"
#ifdef N3DS
static const Widget _select_game_widgets[] = {
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 0, 319, 0, 13, STR_0307_OPENTTD, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 319, 14, 212, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 3, 160, 22, 33, STR_0140_NEW_GAME, STR_02FB_START_A_NEW_GAME},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 161, 316, 22, 33, STR_0141_LOAD_GAME, STR_02FC_LOAD_A_SAVED_GAME},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 3, 160, 40, 51, STR_029A_PLAY_SCENARIO, STR_0303_START_A_NEW_GAME_USING},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 161, 316, 40, 51, STR_PLAY_HEIGHTMAP, STR_PLAY_HEIGHTMAP_HINT},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 3, 160, 58, 69, STR_SCENARIO_EDITOR, STR_02FE_CREATE_A_CUSTOMIZED_GAME},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 161, 316, 58, 69, STR_MULTIPLAYER, STR_0300_SELECT_MULTIPLAYER_GAME},
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 3, 79, 77, 131, SPR_SELECT_TEMPERATE, STR_030E_SELECT_TEMPERATE_LANDSCAPE},
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 82, 158, 77, 131, SPR_SELECT_SUB_ARCTIC, STR_030F_SELECT_SUB_ARCTIC_LANDSCAPE},
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 161, 237, 77, 131, SPR_SELECT_SUB_TROPICAL, STR_0310_SELECT_SUB_TROPICAL_LANDSCAPE},
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 240, 316, 77, 131, SPR_SELECT_TOYLAND, STR_0311_SELECT_TOYLAND_LANDSCAPE},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 3, 160, 139, 150, STR_0148_GAME_OPTIONS, STR_0301_DISPLAY_GAME_OPTIONS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 161, 316, 139, 150, STR_01FE_DIFFICULTY, STR_0302_DISPLAY_DIFFICULTY_OPTIONS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 3, 160, 157, 168, STR_CONFIG_SETTING, STR_CONFIG_SETTING_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 161, 316, 157, 168, STR_NEWGRF_SETTINGS_BUTTON, STR_NEWGRF_SETTINGS_BUTTON_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 3, 160, 175, 186, STR_CONTENT_INTRO_BUTTON, STR_CONTENT_INTRO_BUTTON_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 161, 316, 175, 186, STR_AI_SETTINGS_BUTTON, STR_AI_SETTINGS_BUTTON_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 97, 224, 193, 204, STR_0304_QUIT, STR_0305_QUIT_OPENTTD},
{ WIDGETS_END},
};
#else
static const Widget _select_game_widgets[] = {
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 0, 335, 0, 13, STR_0307_OPENTTD, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 335, 14, 212, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 10, 167, 22, 33, STR_0140_NEW_GAME, STR_02FB_START_A_NEW_GAME},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 168, 325, 22, 33, STR_0141_LOAD_GAME, STR_02FC_LOAD_A_SAVED_GAME},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 10, 167, 40, 51, STR_029A_PLAY_SCENARIO, STR_0303_START_A_NEW_GAME_USING},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 168, 325, 40, 51, STR_PLAY_HEIGHTMAP, STR_PLAY_HEIGHTMAP_HINT},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 10, 167, 58, 69, STR_SCENARIO_EDITOR, STR_02FE_CREATE_A_CUSTOMIZED_GAME},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 168, 325, 58, 69, STR_MULTIPLAYER, STR_0300_SELECT_MULTIPLAYER_GAME},
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 10, 86, 77, 131, SPR_SELECT_TEMPERATE, STR_030E_SELECT_TEMPERATE_LANDSCAPE},
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 90, 166, 77, 131, SPR_SELECT_SUB_ARCTIC, STR_030F_SELECT_SUB_ARCTIC_LANDSCAPE},
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 170, 246, 77, 131, SPR_SELECT_SUB_TROPICAL, STR_0310_SELECT_SUB_TROPICAL_LANDSCAPE},
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_ORANGE, 250, 326, 77, 131, SPR_SELECT_TOYLAND, STR_0311_SELECT_TOYLAND_LANDSCAPE},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 10, 167, 139, 150, STR_0148_GAME_OPTIONS, STR_0301_DISPLAY_GAME_OPTIONS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 168, 325, 139, 150, STR_01FE_DIFFICULTY, STR_0302_DISPLAY_DIFFICULTY_OPTIONS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 10, 167, 157, 168, STR_CONFIG_SETTING, STR_CONFIG_SETTING_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 168, 325, 157, 168, STR_NEWGRF_SETTINGS_BUTTON, STR_NEWGRF_SETTINGS_BUTTON_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 10, 167, 175, 186, STR_CONTENT_INTRO_BUTTON, STR_CONTENT_INTRO_BUTTON_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 168, 325, 175, 186, STR_AI_SETTINGS_BUTTON, STR_AI_SETTINGS_BUTTON_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_ORANGE, 104, 231, 193, 204, STR_0304_QUIT, STR_0305_QUIT_OPENTTD},
{ WIDGETS_END},
};
#endif /* N3DS */
static inline void SetNewLandscapeType(byte landscape)
{
_settings_newgame.game_creation.landscape = landscape;
InvalidateWindowClasses(WC_SELECT_GAME);
}
struct SelectGameWindow : public Window {
private:
enum SelectGameIntroWidgets {
SGI_GENERATE_GAME = 2,
SGI_LOAD_GAME,
SGI_PLAY_SCENARIO,
SGI_PLAY_HEIGHTMAP,
SGI_EDIT_SCENARIO,
SGI_PLAY_NETWORK,
SGI_TEMPERATE_LANDSCAPE,
SGI_ARCTIC_LANDSCAPE,
SGI_TROPIC_LANDSCAPE,
SGI_TOYLAND_LANDSCAPE,
SGI_OPTIONS,
SGI_DIFFICULTIES,
SGI_SETTINGS_OPTIONS,
SGI_GRF_SETTINGS,
SGI_CONTENT_DOWNLOAD,
SGI_AI_SETTINGS,
SGI_EXIT,
};
public:
SelectGameWindow(const WindowDesc *desc) : Window(desc)
{
this->LowerWidget(_settings_newgame.game_creation.landscape + SGI_TEMPERATE_LANDSCAPE);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->SetWidgetLoweredState(SGI_TEMPERATE_LANDSCAPE, _settings_newgame.game_creation.landscape == LT_TEMPERATE);
this->SetWidgetLoweredState(SGI_ARCTIC_LANDSCAPE, _settings_newgame.game_creation.landscape == LT_ARCTIC);
this->SetWidgetLoweredState(SGI_TROPIC_LANDSCAPE, _settings_newgame.game_creation.landscape == LT_TROPIC);
this->SetWidgetLoweredState(SGI_TOYLAND_LANDSCAPE, _settings_newgame.game_creation.landscape == LT_TOYLAND);
SetDParam(0, STR_6801_EASY + _settings_newgame.difficulty.diff_level);
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
#ifdef ENABLE_NETWORK
/* Do not create a network server when you (just) have closed one of the game
* creation/load windows for the network server. */
if (IsInsideMM(widget, SGI_GENERATE_GAME, SGI_EDIT_SCENARIO + 1)) _is_network_server = false;
#endif /* ENABLE_NETWORK */
switch (widget) {
case SGI_GENERATE_GAME:
if (_ctrl_pressed) {
StartNewGameWithoutGUI(GENERATE_NEW_SEED);
} else {
ShowGenerateLandscape();
}
break;
case SGI_LOAD_GAME: ShowSaveLoadDialog(SLD_LOAD_GAME); break;
case SGI_PLAY_SCENARIO: ShowSaveLoadDialog(SLD_LOAD_SCENARIO); break;
case SGI_PLAY_HEIGHTMAP: ShowSaveLoadDialog(SLD_LOAD_HEIGHTMAP); break;
case SGI_EDIT_SCENARIO: StartScenarioEditor(); break;
case SGI_PLAY_NETWORK:
if (!_network_available) {
ShowErrorMessage(INVALID_STRING_ID, STR_NETWORK_ERR_NOTAVAILABLE, 0, 0);
} else {
ShowNetworkGameWindow();
}
break;
case SGI_TEMPERATE_LANDSCAPE: case SGI_ARCTIC_LANDSCAPE:
case SGI_TROPIC_LANDSCAPE: case SGI_TOYLAND_LANDSCAPE:
this->RaiseWidget(_settings_newgame.game_creation.landscape + SGI_TEMPERATE_LANDSCAPE);
SetNewLandscapeType(widget - SGI_TEMPERATE_LANDSCAPE);
break;
case SGI_OPTIONS: ShowGameOptions(); break;
case SGI_DIFFICULTIES: ShowGameDifficulty(); break;
case SGI_SETTINGS_OPTIONS:ShowGameSettings(); break;
case SGI_GRF_SETTINGS: ShowNewGRFSettings(true, true, false, &_grfconfig_newgame); break;
case SGI_CONTENT_DOWNLOAD:
if (!_network_available) {
ShowErrorMessage(INVALID_STRING_ID, STR_NETWORK_ERR_NOTAVAILABLE, 0, 0);
} else {
ShowNetworkContentListWindow();
}
break;
case SGI_AI_SETTINGS: ShowAIConfigWindow(); break;
case SGI_EXIT: HandleExitGameRequest(); break;
}
}
};
static const WindowDesc _select_game_desc(
WDP_CENTER, WDP_CENTER, 336, 213, 336, 213,
WC_SELECT_GAME, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_select_game_widgets
);
void ShowSelectGameWindow()
{
new SelectGameWindow(&_select_game_desc);
}
static void AskExitGameCallback(Window *w, bool confirmed)
{
if (confirmed) _exit_game = true;
}
void AskExitGame()
{
#if defined(_WIN32)
SetDParam(0, STR_OSNAME_WINDOWS);
#elif defined(__APPLE__)
SetDParam(0, STR_OSNAME_OSX);
#elif defined(__BEOS__)
SetDParam(0, STR_OSNAME_BEOS);
#elif defined(__MORPHOS__)
SetDParam(0, STR_OSNAME_MORPHOS);
#elif defined(__AMIGA__)
SetDParam(0, STR_OSNAME_AMIGAOS);
#elif defined(__OS2__)
SetDParam(0, STR_OSNAME_OS2);
#elif defined(SUNOS)
SetDParam(0, STR_OSNAME_SUNOS);
#elif defined(DOS)
SetDParam(0, STR_OSNAME_DOS);
#else
SetDParam(0, STR_OSNAME_UNIX);
#endif
ShowQuery(
STR_00C7_QUIT,
STR_00CA_ARE_YOU_SURE_YOU_WANT_TO,
NULL,
AskExitGameCallback
);
}
static void AskExitToGameMenuCallback(Window *w, bool confirmed)
{
if (confirmed) _switch_mode = SM_MENU;
}
void AskExitToGameMenu()
{
ShowQuery(
STR_0161_QUIT_GAME,
(_game_mode != GM_EDITOR) ? STR_ABANDON_GAME_QUERY : STR_QUIT_SCENARIO_QUERY,
NULL,
AskExitToGameMenuCallback
);
}
| 10,341
|
C++
|
.cpp
| 213
| 46.211268
| 142
| 0.689611
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,090
|
train_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/train_cmd.cpp
|
/* $Id$ */
/** @file train_cmd.cpp Handling of trains. */
#include "stdafx.h"
#include "gui.h"
#include "articulated_vehicles.h"
#include "command_func.h"
#include "npf.h"
#include "news_func.h"
#include "engine_func.h"
#include "engine_base.h"
#include "company_func.h"
#include "depot_base.h"
#include "vehicle_gui.h"
#include "train.h"
#include "newgrf_engine.h"
#include "newgrf_sound.h"
#include "newgrf_text.h"
#include "yapf/follow_track.hpp"
#include "group.h"
#include "table/sprites.h"
#include "strings_func.h"
#include "functions.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "variables.h"
#include "autoreplace_gui.h"
#include "gfx_func.h"
#include "ai/ai.hpp"
#include "newgrf_station.h"
#include "effectvehicle_func.h"
#include "gamelog.h"
#include "network/network.h"
#include "table/strings.h"
#include "table/train_cmd.h"
static Track ChooseTrainTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
static bool TrainCheckIfLineEnds(Vehicle *v);
static void TrainController(Vehicle *v, Vehicle *nomove);
static TileIndex TrainApproachingCrossingTile(const Vehicle *v);
static void CheckIfTrainNeedsService(Vehicle *v);
static void CheckNextTrainTile(Vehicle *v);
static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
/**
* Determine the side in which the train will leave the tile
*
* @param direction vehicle direction
* @param track vehicle track bits
* @return side of tile the train will leave
*/
static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
{
static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
DiagDirection diagdir = DirToDiagDir(direction);
/* Determine the diagonal direction in which we will exit this tile */
if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
}
return diagdir;
}
/** Return the cargo weight multiplier to use for a rail vehicle
* @param cargo Cargo type to get multiplier for
* @return Cargo weight multiplier
*/
byte FreightWagonMult(CargoID cargo)
{
if (!GetCargo(cargo)->is_freight) return 1;
return _settings_game.vehicle.freight_trains;
}
/**
* Recalculates the cached total power of a train. Should be called when the consist is changed
* @param v First vehicle of the consist.
*/
void TrainPowerChanged(Vehicle *v)
{
uint32 total_power = 0;
uint32 max_te = 0;
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
RailType railtype = GetRailType(u->tile);
/* Power is not added for articulated parts */
if (!IsArticulatedPart(u)) {
bool engine_has_power = HasPowerOnRail(u->u.rail.railtype, railtype);
const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
if (engine_has_power) {
uint16 power = GetVehicleProperty(u, 0x0B, rvi_u->power);
if (power != 0) {
/* Halve power for multiheaded parts */
if (IsMultiheaded(u)) power /= 2;
total_power += power;
/* Tractive effort in (tonnes * 1000 * 10 =) N */
max_te += (u->u.rail.cached_veh_weight * 10000 * GetVehicleProperty(u, 0x1F, rvi_u->tractive_effort)) / 256;
}
}
}
if (HasBit(u->u.rail.flags, VRF_POWEREDWAGON) && HasPowerOnRail(v->u.rail.railtype, railtype)) {
total_power += RailVehInfo(u->u.rail.first_engine)->pow_wag_power;
}
}
if (v->u.rail.cached_power != total_power || v->u.rail.cached_max_te != max_te) {
/* If it has no power (no catenary), stop the train */
if (total_power == 0) v->vehstatus |= VS_STOPPED;
v->u.rail.cached_power = total_power;
v->u.rail.cached_max_te = max_te;
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
}
/**
* Recalculates the cached weight of a train and its vehicles. Should be called each time the cargo on
* the consist changes.
* @param v First vehicle of the consist.
*/
static void TrainCargoChanged(Vehicle *v)
{
uint32 weight = 0;
for (Vehicle *u = v; u != NULL; u = u->Next()) {
uint32 vweight = GetCargo(u->cargo_type)->weight * u->cargo.Count() * FreightWagonMult(u->cargo_type) / 16;
/* Vehicle weight is not added for articulated parts. */
if (!IsArticulatedPart(u)) {
/* vehicle weight is the sum of the weight of the vehicle and the weight of its cargo */
vweight += GetVehicleProperty(u, 0x16, RailVehInfo(u->engine_type)->weight);
}
/* powered wagons have extra weight added */
if (HasBit(u->u.rail.flags, VRF_POWEREDWAGON)) {
vweight += RailVehInfo(u->u.rail.first_engine)->pow_wag_weight;
}
/* consist weight is the sum of the weight of all vehicles in the consist */
weight += vweight;
/* store vehicle weight in cache */
u->u.rail.cached_veh_weight = vweight;
}
/* store consist weight in cache */
v->u.rail.cached_weight = weight;
/* Now update train power (tractive effort is dependent on weight) */
TrainPowerChanged(v);
}
/** Logs a bug in GRF and shows a warning message if this
* is for the first time this happened.
* @param u first vehicle of chain
*/
static void RailVehicleLengthChanged(const Vehicle *u)
{
/* show a warning once for each engine in whole game and once for each GRF after each game load */
const Engine *engine = GetEngine(u->engine_type);
uint32 grfid = engine->grffile->grfid;
GRFConfig *grfconfig = GetGRFConfig(grfid);
if (GamelogGRFBugReverse(grfid, engine->internal_id) || !HasBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH)) {
ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, GBUG_VEH_LENGTH, true);
}
}
/** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
void CheckTrainsLengths()
{
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN && v->First() == v && !(v->vehstatus & VS_CRASHED)) {
for (const Vehicle *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
if (u->u.rail.track != TRACK_BIT_DEPOT) {
if ((w->u.rail.track != TRACK_BIT_DEPOT &&
max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->u.rail.cached_veh_length) ||
(w->u.rail.track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
SetDParam(0, v->index);
SetDParam(1, v->owner);
ShowErrorMessage(INVALID_STRING_ID, STR_BROKEN_VEHICLE_LENGTH, 0, 0);
if (!_networking) _pause_game = -1;
}
}
}
}
}
}
/**
* Recalculates the cached stuff of a train. Should be called each time a vehicle is added
* to/removed from the chain, and when the game is loaded.
* Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
* @param v First vehicle of the chain.
* @param same_length should length of vehicles stay the same?
*/
void TrainConsistChanged(Vehicle *v, bool same_length)
{
uint16 max_speed = UINT16_MAX;
assert(v->type == VEH_TRAIN);
assert(IsFrontEngine(v) || IsFreeWagon(v));
const RailVehicleInfo *rvi_v = RailVehInfo(v->engine_type);
EngineID first_engine = IsFrontEngine(v) ? v->engine_type : INVALID_ENGINE;
v->u.rail.cached_total_length = 0;
v->u.rail.compatible_railtypes = RAILTYPES_NONE;
bool train_can_tilt = true;
for (Vehicle *u = v; u != NULL; u = u->Next()) {
const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
/* Check the v->first cache. */
assert(u->First() == v);
/* update the 'first engine' */
u->u.rail.first_engine = v == u ? INVALID_ENGINE : first_engine;
u->u.rail.railtype = rvi_u->railtype;
if (IsTrainEngine(u)) first_engine = u->engine_type;
/* Set user defined data to its default value */
u->u.rail.user_def_data = rvi_u->user_def_data;
u->cache_valid = 0;
}
for (Vehicle *u = v; u != NULL; u = u->Next()) {
/* Update user defined data (must be done before other properties) */
u->u.rail.user_def_data = GetVehicleProperty(u, 0x25, u->u.rail.user_def_data);
u->cache_valid = 0;
}
for (Vehicle *u = v; u != NULL; u = u->Next()) {
const Engine *e_u = GetEngine(u->engine_type);
const RailVehicleInfo *rvi_u = &e_u->u.rail;
if (!HasBit(EngInfo(u->engine_type)->misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
/* Cache wagon override sprite group. NULL is returned if there is none */
u->u.rail.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->u.rail.first_engine);
/* Reset colour map */
u->colourmap = PAL_NONE;
if (rvi_u->visual_effect != 0) {
u->u.rail.cached_vis_effect = rvi_u->visual_effect;
} else {
if (IsTrainWagon(u) || IsArticulatedPart(u)) {
/* Wagons and articulated parts have no effect by default */
u->u.rail.cached_vis_effect = 0x40;
} else if (rvi_u->engclass == 0) {
/* Steam is offset by -4 units */
u->u.rail.cached_vis_effect = 4;
} else {
/* Diesel fumes and sparks come from the centre */
u->u.rail.cached_vis_effect = 8;
}
}
/* Check powered wagon / visual effect callback */
if (HasBit(EngInfo(u->engine_type)->callbackmask, CBM_TRAIN_WAGON_POWER)) {
uint16 callback = GetVehicleCallback(CBID_TRAIN_WAGON_POWER, 0, 0, u->engine_type, u);
if (callback != CALLBACK_FAILED) u->u.rail.cached_vis_effect = GB(callback, 0, 8);
}
if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
UsesWagonOverride(u) && !HasBit(u->u.rail.cached_vis_effect, 7)) {
/* wagon is powered */
SetBit(u->u.rail.flags, VRF_POWEREDWAGON); // cache 'powered' status
} else {
ClrBit(u->u.rail.flags, VRF_POWEREDWAGON);
}
if (!IsArticulatedPart(u)) {
/* Do not count powered wagons for the compatible railtypes, as wagons always
have railtype normal */
if (rvi_u->power > 0) {
v->u.rail.compatible_railtypes |= GetRailTypeInfo(u->u.rail.railtype)->powered_railtypes;
}
/* Some electric engines can be allowed to run on normal rail. It happens to all
* existing electric engines when elrails are disabled and then re-enabled */
if (HasBit(u->u.rail.flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
u->u.rail.railtype = RAILTYPE_RAIL;
u->u.rail.compatible_railtypes |= RAILTYPES_RAIL;
}
/* max speed is the minimum of the speed limits of all vehicles in the consist */
if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
uint16 speed = GetVehicleProperty(u, 0x09, rvi_u->max_speed);
if (speed != 0) max_speed = min(speed, max_speed);
}
}
if (e_u->CanCarryCargo() && u->cargo_type == e_u->GetDefaultCargoType() && u->cargo_subtype == 0) {
/* Set cargo capacity if we've not been refitted */
u->cargo_cap = GetVehicleProperty(u, 0x14, rvi_u->capacity);
}
/* check the vehicle length (callback) */
uint16 veh_len = CALLBACK_FAILED;
if (HasBit(EngInfo(u->engine_type)->callbackmask, CBM_VEHICLE_LENGTH)) {
veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
}
if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
veh_len = 8 - Clamp(veh_len, 0, u->Next() == NULL ? 7 : 5); // the clamp on vehicles not the last in chain is stricter, as too short wagons can break the 'follow next vehicle' code
/* verify length hasn't changed */
if (same_length && veh_len != u->u.rail.cached_veh_length) RailVehicleLengthChanged(u);
/* update vehicle length? */
if (!same_length) u->u.rail.cached_veh_length = veh_len;
v->u.rail.cached_total_length += u->u.rail.cached_veh_length;
u->cache_valid = 0;
}
/* store consist weight/max speed in cache */
v->u.rail.cached_max_speed = max_speed;
v->u.rail.cached_tilt = train_can_tilt;
/* recalculate cached weights and power too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) */
TrainCargoChanged(v);
if (IsFrontEngine(v)) {
UpdateTrainAcceleration(v);
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
}
}
enum AccelType {
AM_ACCEL,
AM_BRAKE
};
/** new acceleration*/
static int GetTrainAcceleration(Vehicle *v, bool mode)
{
static const int absolute_max_speed = UINT16_MAX;
int max_speed = absolute_max_speed;
int speed = v->cur_speed * 10 / 16; // km-ish/h -> mp/h
int curvecount[2] = {0, 0};
/* first find the curve speed limit */
int numcurve = 0;
int sum = 0;
int pos = 0;
int lastpos = -1;
for (const Vehicle *u = v; u->Next() != NULL; u = u->Next(), pos++) {
Direction this_dir = u->direction;
Direction next_dir = u->Next()->direction;
DirDiff dirdiff = DirDifference(this_dir, next_dir);
if (dirdiff == DIRDIFF_SAME) continue;
if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
if (lastpos != -1) {
numcurve++;
sum += pos - lastpos;
if (pos - lastpos == 1) {
max_speed = 88;
}
}
lastpos = pos;
}
/* if we have a 90 degree turn, fix the speed limit to 60 */
if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
max_speed = 61;
}
}
if ((curvecount[0] != 0 || curvecount[1] != 0) && max_speed > 88) {
int total = curvecount[0] + curvecount[1];
if (curvecount[0] == 1 && curvecount[1] == 1) {
max_speed = absolute_max_speed;
} else if (total > 1) {
if (numcurve > 0) sum /= numcurve;
max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
}
}
if (max_speed != absolute_max_speed) {
/* Apply the engine's rail type curve speed advantage, if it slowed by curves */
const RailtypeInfo *rti = GetRailTypeInfo(v->u.rail.railtype);
max_speed += (max_speed / 2) * rti->curve_speed;
if (v->u.rail.cached_tilt) {
/* Apply max_speed bonus of 20% for a tilting train */
max_speed += max_speed / 5;
}
}
if (IsTileType(v->tile, MP_STATION) && IsFrontEngine(v)) {
if (v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) {
int station_length = GetStationByTile(v->tile)->GetPlatformLength(v->tile, DirToDiagDir(v->direction));
int st_max_speed = 120;
int delta_v = v->cur_speed / (station_length + 1);
if (v->max_speed > (v->cur_speed - delta_v)) {
st_max_speed = v->cur_speed - (delta_v / 10);
}
st_max_speed = max(st_max_speed, 25 * station_length);
max_speed = min(max_speed, st_max_speed);
}
}
int mass = v->u.rail.cached_weight;
int power = v->u.rail.cached_power * 746;
max_speed = min(max_speed, v->u.rail.cached_max_speed);
int num = 0; // number of vehicles, change this into the number of axles later
int incl = 0;
int drag_coeff = 20; //[1e-4]
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
num++;
drag_coeff += 3;
if (u->u.rail.track == TRACK_BIT_DEPOT) max_speed = min(max_speed, 61);
if (HasBit(u->u.rail.flags, VRF_GOINGUP)) {
incl += u->u.rail.cached_veh_weight * 60; // 3% slope, quite a bit actually
} else if (HasBit(u->u.rail.flags, VRF_GOINGDOWN)) {
incl -= u->u.rail.cached_veh_weight * 60;
}
}
v->max_speed = max_speed;
const int area = 120;
const int friction = 35; //[1e-3]
int resistance;
if (v->u.rail.railtype != RAILTYPE_MAGLEV) {
resistance = 13 * mass / 10;
resistance += 60 * num;
resistance += friction * mass * speed / 1000;
resistance += (area * drag_coeff * speed * speed) / 10000;
} else {
resistance = (area * (drag_coeff / 2) * speed * speed) / 10000;
}
resistance += incl;
resistance *= 4; //[N]
const int max_te = v->u.rail.cached_max_te; // [N]
int force;
if (speed > 0) {
switch (v->u.rail.railtype) {
case RAILTYPE_RAIL:
case RAILTYPE_ELECTRIC:
case RAILTYPE_MONO:
force = power / speed; //[N]
force *= 22;
force /= 10;
if (mode == AM_ACCEL && force > max_te) force = max_te;
break;
default: NOT_REACHED();
case RAILTYPE_MAGLEV:
force = power / 25;
break;
}
} else {
/* "kickoff" acceleration */
force = (mode == AM_ACCEL && v->u.rail.railtype != RAILTYPE_MAGLEV) ? min(max_te, power) : power;
force = max(force, (mass * 8) + resistance);
}
if (mode == AM_ACCEL) {
return (force - resistance) / (mass * 2);
} else {
return min(-force - resistance, -10000) / mass;
}
}
void UpdateTrainAcceleration(Vehicle *v)
{
assert(IsFrontEngine(v));
v->max_speed = v->u.rail.cached_max_speed;
uint power = v->u.rail.cached_power;
uint weight = v->u.rail.cached_weight;
assert(weight != 0);
v->acceleration = Clamp(power / weight * 4, 1, 255);
}
SpriteID Train::GetImage(Direction direction) const
{
uint8 spritenum = this->spritenum;
SpriteID sprite;
if (HasBit(this->u.rail.flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
if (is_custom_sprite(spritenum)) {
sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)));
if (sprite != 0) return sprite;
spritenum = GetEngine(this->engine_type)->image_index;
}
sprite = _engine_sprite_base[spritenum] + ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]);
if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
return sprite;
}
static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y)
{
Direction dir = rear_head ? DIR_E : DIR_W;
uint8 spritenum = RailVehInfo(engine)->image_index;
if (is_custom_sprite(spritenum)) {
SpriteID sprite = GetCustomVehicleIcon(engine, dir);
if (sprite != 0) {
y += _traininfo_vehicle_pitch; // TODO Make this per-GRF
return sprite;
}
spritenum = GetEngine(engine)->image_index;
}
if (rear_head) spritenum++;
return ((6 + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
}
void DrawTrainEngine(int x, int y, EngineID engine, SpriteID pal)
{
if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
int yf = y;
int yr = y;
SpriteID spritef = GetRailIcon(engine, false, yf);
SpriteID spriter = GetRailIcon(engine, true, yr);
DrawSprite(spritef, pal, x - 14, yf);
DrawSprite(spriter, pal, x + 15, yr);
} else {
SpriteID sprite = GetRailIcon(engine, false, y);
DrawSprite(sprite, pal, x, y);
}
}
static CommandCost CmdBuildRailWagon(EngineID engine, TileIndex tile, DoCommandFlag flags)
{
const Engine *e = GetEngine(engine);
const RailVehicleInfo *rvi = &e->u.rail;
CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
/* Engines without valid cargo should not be available */
if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
if (flags & DC_QUERY_COST) return value;
/* Check that the wagon can drive on the track in question */
if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
uint num_vehicles = 1 + CountArticulatedParts(engine, false);
/* Allow for the wagon and the articulated parts, plus one to "terminate" the list. */
Vehicle **vl = AllocaM(Vehicle*, num_vehicles + 1);
memset(vl, 0, sizeof(*vl) * (num_vehicles + 1));
if (!Vehicle::AllocateList(vl, num_vehicles)) {
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
}
if (flags & DC_EXEC) {
Vehicle *v = vl[0];
v->spritenum = rvi->image_index;
Vehicle *u = NULL;
Vehicle *w;
FOR_ALL_VEHICLES(w) {
if (w->type == VEH_TRAIN && w->tile == tile &&
IsFreeWagon(w) && w->engine_type == engine &&
!HASBITS(w->vehstatus, VS_CRASHED)) { /// do not connect new wagon with crashed/flooded consists
u = GetLastVehicleInChain(w);
break;
}
}
v = new (v) Train();
v->engine_type = engine;
DiagDirection dir = GetRailDepotDirection(tile);
v->direction = DiagDirToDir(dir);
v->tile = tile;
int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
v->x_pos = x;
v->y_pos = y;
v->z_pos = GetSlopeZ(x, y);
v->owner = _current_company;
v->u.rail.track = TRACK_BIT_DEPOT;
v->vehstatus = VS_HIDDEN | VS_DEFPAL;
// v->subtype = 0;
SetTrainWagon(v);
if (u != NULL) {
u->SetNext(v);
} else {
SetFreeWagon(v);
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
}
v->cargo_type = e->GetDefaultCargoType();
// v->cargo_subtype = 0;
v->cargo_cap = rvi->capacity;
v->value = value.GetCost();
// v->day_counter = 0;
v->u.rail.railtype = rvi->railtype;
v->build_year = _cur_year;
v->cur_image = 0xAC2;
v->random_bits = VehicleRandomBits();
v->group_id = DEFAULT_GROUP;
AddArticulatedParts(vl, VEH_TRAIN);
_new_vehicle_id = v->index;
VehicleMove(v, false);
TrainConsistChanged(v->First(), false);
UpdateTrainGroupID(v->First());
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
if (IsLocalCompany()) {
InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
}
GetCompany(_current_company)->num_engines[engine]++;
CheckConsistencyOfArticulatedVehicle(v);
}
return value;
}
/** Move all free vehicles in the depot to the train */
static void NormalizeTrainVehInDepot(const Vehicle *u)
{
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN && IsFreeWagon(v) &&
v->tile == u->tile &&
v->u.rail.track == TRACK_BIT_DEPOT) {
if (CmdFailed(DoCommand(0, v->index | (u->index << 16), 1, DC_EXEC,
CMD_MOVE_RAIL_VEHICLE)))
break;
}
}
}
static void AddRearEngineToMultiheadedTrain(Vehicle *v, Vehicle *u, bool building)
{
u = new (u) Train();
u->direction = v->direction;
u->owner = v->owner;
u->tile = v->tile;
u->x_pos = v->x_pos;
u->y_pos = v->y_pos;
u->z_pos = v->z_pos;
u->u.rail.track = TRACK_BIT_DEPOT;
u->vehstatus = v->vehstatus & ~VS_STOPPED;
// u->subtype = 0;
SetMultiheaded(u);
u->spritenum = v->spritenum + 1;
u->cargo_type = v->cargo_type;
u->cargo_subtype = v->cargo_subtype;
u->cargo_cap = v->cargo_cap;
u->u.rail.railtype = v->u.rail.railtype;
if (building) v->SetNext(u);
u->engine_type = v->engine_type;
u->build_year = v->build_year;
if (building) v->value >>= 1;
u->value = v->value;
u->cur_image = 0xAC2;
u->random_bits = VehicleRandomBits();
VehicleMove(u, false);
}
/** Build a railroad vehicle.
* @param tile tile of the depot where rail-vehicle is built
* @param flags type of operation
* @param p1 engine type id
* @param p2 bit 1 prevents any free cars from being added to the train
*/
CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
/* Check if the engine-type is valid (for the company) */
if (!IsEngineBuildable(p1, VEH_TRAIN, _current_company)) return_cmd_error(STR_RAIL_VEHICLE_NOT_AVAILABLE);
const Engine *e = GetEngine(p1);
CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
/* Engines with CT_INVALID should not be available */
if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
if (flags & DC_QUERY_COST) return value;
/* Check if the train is actually being built in a depot belonging
* to the company. Doesn't matter if only the cost is queried */
if (!IsRailDepotTile(tile)) return CMD_ERROR;
if (!IsTileOwner(tile, _current_company)) return CMD_ERROR;
const RailVehicleInfo *rvi = RailVehInfo(p1);
if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(p1, tile, flags);
uint num_vehicles =
(rvi->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) +
CountArticulatedParts(p1, false);
/* Check if depot and new engine uses the same kind of tracks *
* We need to see if the engine got power on the tile to avoid eletric engines in non-electric depots */
if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
/* Allow for the dual-heads and the articulated parts, plus one to "terminate" the list. */
Vehicle **vl = AllocaM(Vehicle*, num_vehicles + 1);
memset(vl, 0, sizeof(*vl) * (num_vehicles + 1));
if (!Vehicle::AllocateList(vl, num_vehicles)) {
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
}
Vehicle *v = vl[0];
UnitID unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_TRAIN);
if (unit_num > _settings_game.vehicle.max_trains) {
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
}
if (flags & DC_EXEC) {
DiagDirection dir = GetRailDepotDirection(tile);
int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
v = new (v) Train();
v->unitnumber = unit_num;
v->direction = DiagDirToDir(dir);
v->tile = tile;
v->owner = _current_company;
v->x_pos = x;
v->y_pos = y;
v->z_pos = GetSlopeZ(x, y);
// v->running_ticks = 0;
v->u.rail.track = TRACK_BIT_DEPOT;
v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
v->spritenum = rvi->image_index;
v->cargo_type = e->GetDefaultCargoType();
// v->cargo_subtype = 0;
v->cargo_cap = rvi->capacity;
v->max_speed = rvi->max_speed;
v->value = value.GetCost();
v->last_station_visited = INVALID_STATION;
// v->dest_tile = 0;
v->engine_type = p1;
v->reliability = e->reliability;
v->reliability_spd_dec = e->reliability_spd_dec;
v->max_age = e->lifelength * DAYS_IN_LEAP_YEAR;
v->name = NULL;
v->u.rail.railtype = rvi->railtype;
_new_vehicle_id = v->index;
v->service_interval = _settings_game.vehicle.servint_trains;
v->date_of_last_service = _date;
v->build_year = _cur_year;
v->cur_image = 0xAC2;
v->random_bits = VehicleRandomBits();
// v->vehicle_flags = 0;
if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
v->group_id = DEFAULT_GROUP;
// v->subtype = 0;
SetFrontEngine(v);
SetTrainEngine(v);
VehicleMove(v, false);
if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
SetMultiheaded(v);
AddRearEngineToMultiheadedTrain(vl[0], vl[1], true);
/* Now we need to link the front and rear engines together
* other_multiheaded_part is the pointer that links to the other half of the engine
* vl[0] is the front and vl[1] is the rear
*/
vl[0]->u.rail.other_multiheaded_part = vl[1];
vl[1]->u.rail.other_multiheaded_part = vl[0];
} else {
AddArticulatedParts(vl, VEH_TRAIN);
}
TrainConsistChanged(v, false);
UpdateTrainGroupID(v);
if (!HasBit(p2, 1) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
NormalizeTrainVehInDepot(v);
}
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
InvalidateWindow(WC_COMPANY, v->owner);
if (IsLocalCompany()) {
InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
}
GetCompany(_current_company)->num_engines[p1]++;
CheckConsistencyOfArticulatedVehicle(v);
}
return value;
}
/* Check if all the wagons of the given train are in a depot, returns the
* number of cars (including loco) then. If not it returns -1 */
int CheckTrainInDepot(const Vehicle *v, bool needs_to_be_stopped)
{
TileIndex tile = v->tile;
/* check if stopped in a depot */
if (!IsRailDepotTile(tile) || v->cur_speed != 0) return -1;
int count = 0;
for (; v != NULL; v = v->Next()) {
/* This count is used by the depot code to determine the number of engines
* in the consist. Exclude articulated parts so that autoreplacing to
* engines with more articulated parts than before works correctly.
*
* Also skip counting rear ends of multiheaded engines */
if (!IsArticulatedPart(v) && !IsRearDualheaded(v)) count++;
if (v->u.rail.track != TRACK_BIT_DEPOT || v->tile != tile ||
(IsFrontEngine(v) && needs_to_be_stopped && !(v->vehstatus & VS_STOPPED))) {
return -1;
}
}
return count;
}
/* Used to check if the train is inside the depot and verifying that the VS_STOPPED flag is set */
int CheckTrainStoppedInDepot(const Vehicle *v)
{
return CheckTrainInDepot(v, true);
}
/* Used to check if the train is inside the depot, but not checking the VS_STOPPED flag */
inline bool CheckTrainIsInsideDepot(const Vehicle *v)
{
return CheckTrainInDepot(v, false) > 0;
}
/**
* Unlink a rail wagon from the consist.
* @param v Vehicle to remove.
* @param first The first vehicle of the consist.
* @return The first vehicle of the consist.
*/
static Vehicle *UnlinkWagon(Vehicle *v, Vehicle *first)
{
/* unlinking the first vehicle of the chain? */
if (v == first) {
v = GetNextVehicle(v);
if (v == NULL) return NULL;
if (IsTrainWagon(v)) SetFreeWagon(v);
/* First can be an articulated engine, meaning GetNextVehicle() isn't
* v->Next(). Thus set the next vehicle of the last articulated part
* and the last articulated part is just before the next vehicle (v). */
v->Previous()->SetNext(NULL);
return v;
}
Vehicle *u;
for (u = first; GetNextVehicle(u) != v; u = GetNextVehicle(u)) {}
GetLastEnginePart(u)->SetNext(GetNextVehicle(v));
return first;
}
static Vehicle *FindGoodVehiclePos(const Vehicle *src)
{
Vehicle *dst;
EngineID eng = src->engine_type;
TileIndex tile = src->tile;
FOR_ALL_VEHICLES(dst) {
if (dst->type == VEH_TRAIN && IsFreeWagon(dst) && dst->tile == tile && !HASBITS(dst->vehstatus, VS_CRASHED)) {
/* check so all vehicles in the line have the same engine. */
Vehicle *v = dst;
while (v->engine_type == eng) {
v = v->Next();
if (v == NULL) return dst;
}
}
}
return NULL;
}
/*
* add a vehicle v behind vehicle dest
* use this function since it sets flags as needed
*/
static void AddWagonToConsist(Vehicle *v, Vehicle *dest)
{
UnlinkWagon(v, v->First());
if (dest == NULL) return;
Vehicle *next = dest->Next();
v->SetNext(NULL);
dest->SetNext(v);
v->SetNext(next);
ClearFreeWagon(v);
ClearFrontEngine(v);
}
/*
* move around on the train so rear engines are placed correctly according to the other engines
* always call with the front engine
*/
static void NormaliseTrainConsist(Vehicle *v)
{
if (IsFreeWagon(v)) return;
assert(IsFrontEngine(v));
for (; v != NULL; v = GetNextVehicle(v)) {
if (!IsMultiheaded(v) || !IsTrainEngine(v)) continue;
/* make sure that there are no free cars before next engine */
Vehicle *u;
for (u = v; u->Next() != NULL && !IsTrainEngine(u->Next()); u = u->Next()) {}
if (u == v->u.rail.other_multiheaded_part) continue;
AddWagonToConsist(v->u.rail.other_multiheaded_part, u);
}
}
/** Move a rail vehicle around inside the depot.
* @param tile unused
* @param flags type of operation
* Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
* @param p1 various bitstuffed elements
* - p1 (bit 0 - 15) source vehicle index
* - p1 (bit 16 - 31) what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
* @param p2 (bit 0) move all vehicles following the source vehicle
*/
CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
VehicleID s = GB(p1, 0, 16);
VehicleID d = GB(p1, 16, 16);
if (!IsValidVehicleID(s)) return CMD_ERROR;
Vehicle *src = GetVehicle(s);
if (src->type != VEH_TRAIN || !CheckOwnership(src->owner)) return CMD_ERROR;
/* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
if (HASBITS(src->vehstatus, VS_CRASHED)) return CMD_ERROR;
/* if nothing is selected as destination, try and find a matching vehicle to drag to. */
Vehicle *dst;
if (d == INVALID_VEHICLE) {
dst = IsTrainEngine(src) ? NULL : FindGoodVehiclePos(src);
} else {
if (!IsValidVehicleID(d)) return CMD_ERROR;
dst = GetVehicle(d);
if (dst->type != VEH_TRAIN || !CheckOwnership(dst->owner)) return CMD_ERROR;
/* Do not allow appending to crashed vehicles, too */
if (HASBITS(dst->vehstatus, VS_CRASHED)) return CMD_ERROR;
}
/* if an articulated part is being handled, deal with its parent vehicle */
while (IsArticulatedPart(src)) src = src->Previous();
if (dst != NULL) {
while (IsArticulatedPart(dst)) dst = dst->Previous();
}
/* don't move the same vehicle.. */
if (src == dst) return CommandCost();
/* locate the head of the two chains */
Vehicle *src_head = src->First();
Vehicle *dst_head;
if (dst != NULL) {
dst_head = dst->First();
if (dst_head->tile != src_head->tile) return CMD_ERROR;
/* Now deal with articulated part of destination wagon */
dst = GetLastEnginePart(dst);
} else {
dst_head = NULL;
}
if (IsRearDualheaded(src)) return_cmd_error(STR_REAR_ENGINE_FOLLOW_FRONT_ERROR);
/* when moving all wagons, we can't have the same src_head and dst_head */
if (HasBit(p2, 0) && src_head == dst_head) return CommandCost();
/* check if all vehicles in the source train are stopped inside a depot. */
int src_len = CheckTrainStoppedInDepot(src_head);
if (src_len < 0) return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
if ((flags & DC_AUTOREPLACE) == 0) {
/* Check whether there are more than 'max_len' train units (articulated parts and rear heads do not count) in the new chain */
int max_len = _settings_game.vehicle.mammoth_trains ? 100 : 10;
/* check the destination row if the source and destination aren't the same. */
if (src_head != dst_head) {
int dst_len = 0;
if (dst_head != NULL) {
/* check if all vehicles in the dest train are stopped. */
dst_len = CheckTrainStoppedInDepot(dst_head);
if (dst_len < 0) return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
}
/* We are moving between rows, so only count the wagons from the source
* row that are being moved. */
if (HasBit(p2, 0)) {
const Vehicle *u;
for (u = src_head; u != src && u != NULL; u = GetNextVehicle(u))
src_len--;
} else {
/* If moving only one vehicle, just count that. */
src_len = 1;
}
if (src_len + dst_len > max_len) {
/* Abort if we're adding too many wagons to a train. */
if (dst_head != NULL && IsFrontEngine(dst_head)) return_cmd_error(STR_8819_TRAIN_TOO_LONG);
/* Abort if we're making a train on a new row. */
if (dst_head == NULL && IsTrainEngine(src)) return_cmd_error(STR_8819_TRAIN_TOO_LONG);
}
} else {
/* Abort if we're creating a new train on an existing row. */
if (src_len > max_len && src == src_head && IsTrainEngine(GetNextVehicle(src_head)))
return_cmd_error(STR_8819_TRAIN_TOO_LONG);
}
}
/* moving a loco to a new line?, then we need to assign a unitnumber. */
if (dst == NULL && !IsFrontEngine(src) && IsTrainEngine(src)) {
UnitID unit_num = ((flags & DC_AUTOREPLACE) != 0 ? 0 : GetFreeUnitNumber(VEH_TRAIN));
if (unit_num > _settings_game.vehicle.max_trains)
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
if (flags & DC_EXEC) src->unitnumber = unit_num;
}
/* When we move the front vehicle, the second vehicle might need a unitnumber */
if (!HasBit(p2, 0) && (IsFreeWagon(src) || (IsFrontEngine(src) && dst == NULL)) && (flags & DC_AUTOREPLACE) == 0) {
Vehicle *second = GetNextUnit(src);
if (second != NULL && IsTrainEngine(second) && GetFreeUnitNumber(VEH_TRAIN) > _settings_game.vehicle.max_trains) {
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
}
}
/*
* Check whether the vehicles in the source chain are in the destination
* chain. This can easily be done by checking whether the first vehicle
* of the source chain is in the destination chain as the Next/Previous
* pointers always make a doubly linked list of it where the assumption
* v->Next()->Previous() == v holds (assuming v->Next() != NULL).
*/
bool src_in_dst = false;
for (Vehicle *v = dst_head; !src_in_dst && v != NULL; v = v->Next()) src_in_dst = v == src;
/*
* If the source chain is in the destination chain then the user is
* only reordering the vehicles, thus not attaching a new vehicle.
* Therefor the 'allow wagon attach' callback does not need to be
* called. If it would be called strange things would happen because
* one 'attaches' an already 'attached' vehicle causing more trouble
* than it actually solves (infinite loops and such).
*/
if (dst_head != NULL && !src_in_dst && (flags & DC_AUTOREPLACE) == 0) {
/*
* When performing the 'allow wagon attach' callback, we have to check
* that for each and every wagon, not only the first one. This means
* that we have to test one wagon, attach it to the train and then test
* the next wagon till we have reached the end. We have to restore it
* to the state it was before we 'tried' attaching the train when the
* attaching fails or succeeds because we are not 'only' doing this
* in the DC_EXEC state.
*/
Vehicle *dst_tail = dst_head;
while (dst_tail->Next() != NULL) dst_tail = dst_tail->Next();
Vehicle *orig_tail = dst_tail;
Vehicle *next_to_attach = src;
Vehicle *src_previous = src->Previous();
while (next_to_attach != NULL) {
/* Don't check callback for articulated or rear dual headed parts */
if (!IsArticulatedPart(next_to_attach) && !IsRearDualheaded(next_to_attach)) {
/* Back up and clear the first_engine data to avoid using wagon override group */
EngineID first_engine = next_to_attach->u.rail.first_engine;
next_to_attach->u.rail.first_engine = INVALID_ENGINE;
uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, dst_head->engine_type, next_to_attach, dst_head);
/* Restore original first_engine data */
next_to_attach->u.rail.first_engine = first_engine;
if (callback != CALLBACK_FAILED) {
StringID error = STR_NULL;
if (callback == 0xFD) error = STR_INCOMPATIBLE_RAIL_TYPES;
if (callback < 0xFD) error = GetGRFStringID(GetEngineGRFID(dst_head->engine_type), 0xD000 + callback);
if (error != STR_NULL) {
/*
* The attaching is not allowed. In this case 'next_to_attach'
* can contain some vehicles of the 'source' and the destination
* train can have some too. We 'just' add the to-be added wagons
* to the chain and then split it where it was previously
* separated, i.e. the tail of the original destination train.
* Furthermore the 'previous' link of the original source vehicle needs
* to be restored, otherwise the train goes missing in the depot.
*/
dst_tail->SetNext(next_to_attach);
orig_tail->SetNext(NULL);
if (src_previous != NULL) src_previous->SetNext(src);
return_cmd_error(error);
}
}
}
/* Only check further wagons if told to move the chain */
if (!HasBit(p2, 0)) break;
/*
* Adding a next wagon to the chain so we can test the other wagons.
* First 'take' the first wagon from 'next_to_attach' and move it
* to the next wagon. Then add that to the tail of the destination
* train and update the tail with the new vehicle.
*/
Vehicle *to_add = next_to_attach;
next_to_attach = next_to_attach->Next();
to_add->SetNext(NULL);
dst_tail->SetNext(to_add);
dst_tail = dst_tail->Next();
}
/*
* When we reach this the attaching is allowed. It also means that the
* chain of vehicles to attach is empty, so we do not need to merge that.
* This means only the splitting needs to be done.
* Furthermore the 'previous' link of the original source vehicle needs
* to be restored, otherwise the train goes missing in the depot.
*/
orig_tail->SetNext(NULL);
if (src_previous != NULL) src_previous->SetNext(src);
}
/* do it? */
if (flags & DC_EXEC) {
/* If we move the front Engine and if the second vehicle is not an engine
add the whole vehicle to the DEFAULT_GROUP */
if (IsFrontEngine(src) && !IsDefaultGroupID(src->group_id)) {
Vehicle *v = GetNextVehicle(src);
if (v != NULL && IsTrainEngine(v)) {
v->group_id = src->group_id;
src->group_id = DEFAULT_GROUP;
}
}
if (HasBit(p2, 0)) {
/* unlink ALL wagons */
if (src != src_head) {
Vehicle *v = src_head;
while (GetNextVehicle(v) != src) v = GetNextVehicle(v);
GetLastEnginePart(v)->SetNext(NULL);
} else {
InvalidateWindowData(WC_VEHICLE_DEPOT, src_head->tile); // We removed a line
src_head = NULL;
}
} else {
/* if moving within the same chain, dont use dst_head as it may get invalidated */
if (src_head == dst_head) dst_head = NULL;
/* unlink single wagon from linked list */
src_head = UnlinkWagon(src, src_head);
GetLastEnginePart(src)->SetNext(NULL);
}
if (dst == NULL) {
/* We make a new line in the depot, so we know already that we invalidate the window data */
InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
/* move the train to an empty line. for locomotives, we set the type to TS_Front. for wagons, 4. */
if (IsTrainEngine(src)) {
if (!IsFrontEngine(src)) {
/* setting the type to 0 also involves setting up the orders field. */
SetFrontEngine(src);
assert(src->orders.list == NULL);
/* Decrease the engines number of the src engine_type */
if (!IsDefaultGroupID(src->group_id) && IsValidGroupID(src->group_id)) {
GetGroup(src->group_id)->num_engines[src->engine_type]--;
}
/* If we move an engine to a new line affect it to the DEFAULT_GROUP */
src->group_id = DEFAULT_GROUP;
}
} else {
SetFreeWagon(src);
}
dst_head = src;
} else {
if (IsFrontEngine(src)) {
/* the vehicle was previously a loco. need to free the order list and delete vehicle windows etc. */
DeleteWindowById(WC_VEHICLE_VIEW, src->index);
DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
DeleteWindowById(WC_VEHICLE_REFIT, src->index);
DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
DeleteVehicleOrders(src);
RemoveVehicleFromGroup(src);
}
if (IsFrontEngine(src) || IsFreeWagon(src)) {
InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
ClearFrontEngine(src);
ClearFreeWagon(src);
src->unitnumber = 0; // doesn't occupy a unitnumber anymore.
}
/* link in the wagon(s) in the chain. */
{
Vehicle *v;
for (v = src; GetNextVehicle(v) != NULL; v = GetNextVehicle(v)) {}
GetLastEnginePart(v)->SetNext(dst->Next());
}
dst->SetNext(src);
}
if (src->u.rail.other_multiheaded_part != NULL) {
if (src->u.rail.other_multiheaded_part == src_head) {
src_head = src_head->Next();
}
AddWagonToConsist(src->u.rail.other_multiheaded_part, src);
}
/* If there is an engine behind first_engine we moved away, it should become new first_engine
* To do this, CmdMoveRailVehicle must be called once more
* we can't loop forever here because next time we reach this line we will have a front engine */
if (src_head != NULL && !IsFrontEngine(src_head) && IsTrainEngine(src_head)) {
/* As in CmdMoveRailVehicle src_head->group_id will be equal to DEFAULT_GROUP
* we need to save the group and reaffect it to src_head */
const GroupID tmp_g = src_head->group_id;
CmdMoveRailVehicle(0, flags, src_head->index | (INVALID_VEHICLE << 16), 1, text);
SetTrainGroupID(src_head, tmp_g);
src_head = NULL; // don't do anything more to this train since the new call will do it
}
if (src_head != NULL) {
NormaliseTrainConsist(src_head);
TrainConsistChanged(src_head, false);
UpdateTrainGroupID(src_head);
if (IsFrontEngine(src_head)) {
/* Update the refit button and window */
InvalidateWindow(WC_VEHICLE_REFIT, src_head->index);
InvalidateWindowWidget(WC_VEHICLE_VIEW, src_head->index, VVW_WIDGET_REFIT_VEH);
}
/* Update the depot window */
InvalidateWindow(WC_VEHICLE_DEPOT, src_head->tile);
}
if (dst_head != NULL) {
NormaliseTrainConsist(dst_head);
TrainConsistChanged(dst_head, false);
UpdateTrainGroupID(dst_head);
if (IsFrontEngine(dst_head)) {
/* Update the refit button and window */
InvalidateWindowWidget(WC_VEHICLE_VIEW, dst_head->index, VVW_WIDGET_REFIT_VEH);
InvalidateWindow(WC_VEHICLE_REFIT, dst_head->index);
}
/* Update the depot window */
InvalidateWindow(WC_VEHICLE_DEPOT, dst_head->tile);
}
InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
}
return CommandCost();
}
/** Sell a (single) train wagon/engine.
* @param tile unused
* @param flags type of operation
* @param p1 the wagon/engine index
* @param p2 the selling mode
* - p2 = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
* - p2 = 1: sell the vehicle and all vehicles following it in the chain
* if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
*/
CommandCost CmdSellRailWagon(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
/* Check if we deleted a vehicle window */
Window *w = NULL;
if (!IsValidVehicleID(p1) || p2 > 1) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
if (HASBITS(v->vehstatus, VS_CRASHED)) return_cmd_error(STR_CAN_T_SELL_DESTROYED_VEHICLE);
while (IsArticulatedPart(v)) v = v->Previous();
Vehicle *first = v->First();
/* make sure the vehicle is stopped in the depot */
if (CheckTrainStoppedInDepot(first) < 0) {
return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
}
if (IsRearDualheaded(v)) return_cmd_error(STR_REAR_ENGINE_FOLLOW_FRONT_ERROR);
if (flags & DC_EXEC) {
if (v == first && IsFrontEngine(first)) {
DeleteWindowById(WC_VEHICLE_VIEW, first->index);
DeleteWindowById(WC_VEHICLE_ORDERS, first->index);
DeleteWindowById(WC_VEHICLE_REFIT, first->index);
DeleteWindowById(WC_VEHICLE_DETAILS, first->index);
DeleteWindowById(WC_VEHICLE_TIMETABLE, first->index);
}
InvalidateWindow(WC_VEHICLE_DEPOT, first->tile);
InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
}
CommandCost cost(EXPENSES_NEW_VEHICLES);
switch (p2) {
case 0: { // Delete given wagon
bool switch_engine = false; // update second wagon to engine?
/* 1. Delete the engine, if it is dualheaded also delete the matching
* rear engine of the loco (from the point of deletion onwards) */
Vehicle *rear = (IsMultiheaded(v) &&
IsTrainEngine(v)) ? v->u.rail.other_multiheaded_part : NULL;
if (rear != NULL) {
cost.AddCost(-rear->value);
if (flags & DC_EXEC) {
UnlinkWagon(rear, first);
delete rear;
}
}
/* 2. We are selling the front vehicle, some special action might be required
* here, so take attention */
if (v == first) {
Vehicle *new_f = GetNextVehicle(first);
/* 2.2 If there are wagons present after the deleted front engine, check
* if the second wagon (which will be first) is an engine. If it is one,
* promote it as a new train, retaining the unitnumber, orders */
if (new_f != NULL && IsTrainEngine(new_f)) {
if (IsTrainEngine(first)) {
/* Let the new front engine take over the setup of the old engine */
switch_engine = true;
if (flags & DC_EXEC) {
/* Make sure the group counts stay correct. */
new_f->group_id = first->group_id;
first->group_id = DEFAULT_GROUP;
/* Copy orders (by sharing) */
new_f->orders.list = first->orders.list;
new_f->AddToShared(first);
DeleteVehicleOrders(first);
/* Copy other important data from the front engine */
new_f->CopyVehicleConfigAndStatistics(first);
/* If we deleted a window then open a new one for the 'new' train */
if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_f);
}
} else {
/* We are selling a free wagon, and construct a new train at the same time.
* This needs lots of extra checks (e.g. train limit), which are done by first moving
* the remaining vehicles to a new row */
cost.AddCost(DoCommand(0, new_f->index | INVALID_VEHICLE << 16, 1, flags, CMD_MOVE_RAIL_VEHICLE));
if (cost.Failed()) return cost;
}
}
}
/* 3. Delete the requested wagon */
cost.AddCost(-v->value);
if (flags & DC_EXEC) {
first = UnlinkWagon(v, first);
delete v;
/* 4 If the second wagon was an engine, update it to front_engine
* which UnlinkWagon() has changed to TS_Free_Car */
if (switch_engine) SetFrontEngine(first);
/* 5. If the train still exists, update its acceleration, window, etc. */
if (first != NULL) {
NormaliseTrainConsist(first);
TrainConsistChanged(first, false);
UpdateTrainGroupID(first);
if (IsFrontEngine(first)) InvalidateWindow(WC_VEHICLE_REFIT, first->index);
}
}
} break;
case 1: { // Delete wagon and all wagons after it given certain criteria
/* Start deleting every vehicle after the selected one
* If we encounter a matching rear-engine to a front-engine
* earlier in the chain (before deletion), leave it alone */
for (Vehicle *tmp; v != NULL; v = tmp) {
tmp = GetNextVehicle(v);
if (IsMultiheaded(v)) {
if (IsTrainEngine(v)) {
/* We got a front engine of a multiheaded set. Now we will sell the rear end too */
Vehicle *rear = v->u.rail.other_multiheaded_part;
if (rear != NULL) {
cost.AddCost(-rear->value);
/* If this is a multiheaded vehicle with nothing
* between the parts, tmp will be pointing to the
* rear part, which is unlinked from the train and
* deleted here. However, because tmp has already
* been set it needs to be updated now so that the
* loop never sees the rear part. */
if (tmp == rear) tmp = GetNextVehicle(tmp);
if (flags & DC_EXEC) {
first = UnlinkWagon(rear, first);
delete rear;
}
}
} else if (v->u.rail.other_multiheaded_part != NULL) {
/* The front to this engine is earlier in this train. Do nothing */
continue;
}
}
cost.AddCost(-v->value);
if (flags & DC_EXEC) {
first = UnlinkWagon(v, first);
delete v;
}
}
/* 3. If it is still a valid train after selling, update its acceleration and cached values */
if (flags & DC_EXEC && first != NULL) {
NormaliseTrainConsist(first);
TrainConsistChanged(first, false);
UpdateTrainGroupID(first);
InvalidateWindow(WC_VEHICLE_REFIT, first->index);
}
} break;
}
return cost;
}
void Train::UpdateDeltaXY(Direction direction)
{
#define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
static const uint32 _delta_xy_table[8] = {
MKIT(3, 3, -1, -1),
MKIT(3, 7, -1, -3),
MKIT(3, 3, -1, -1),
MKIT(7, 3, -3, -1),
MKIT(3, 3, -1, -1),
MKIT(3, 7, -1, -3),
MKIT(3, 3, -1, -1),
MKIT(7, 3, -3, -1),
};
#undef MKIT
uint32 x = _delta_xy_table[direction];
this->x_offs = GB(x, 0, 8);
this->y_offs = GB(x, 8, 8);
this->x_extent = GB(x, 16, 8);
this->y_extent = GB(x, 24, 8);
this->z_extent = 6;
}
static void UpdateVarsAfterSwap(Vehicle *v)
{
v->UpdateDeltaXY(v->direction);
v->cur_image = v->GetImage(v->direction);
VehicleMove(v, true);
}
static inline void SetLastSpeed(Vehicle *v, int spd)
{
int old = v->u.rail.last_speed;
if (spd != old) {
v->u.rail.last_speed = spd;
if (_settings_client.gui.vehicle_speed || (old == 0) != (spd == 0)) {
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
}
}
/** Mark a train as stuck and stop it if it isn't stopped right now. */
static void MarkTrainAsStuck(Vehicle *v)
{
if (!HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
/* It is the first time the problem occured, set the "train stuck" flag. */
SetBit(v->u.rail.flags, VRF_TRAIN_STUCK);
v->load_unload_time_rem = 0;
/* Stop train */
v->cur_speed = 0;
v->subspeed = 0;
SetLastSpeed(v, 0);
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
}
static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
{
uint16 flag1 = *swap_flag1;
uint16 flag2 = *swap_flag2;
/* Clear the flags */
ClrBit(*swap_flag1, VRF_GOINGUP);
ClrBit(*swap_flag1, VRF_GOINGDOWN);
ClrBit(*swap_flag2, VRF_GOINGUP);
ClrBit(*swap_flag2, VRF_GOINGDOWN);
/* Reverse the rail-flags (if needed) */
if (HasBit(flag1, VRF_GOINGUP)) {
SetBit(*swap_flag2, VRF_GOINGDOWN);
} else if (HasBit(flag1, VRF_GOINGDOWN)) {
SetBit(*swap_flag2, VRF_GOINGUP);
}
if (HasBit(flag2, VRF_GOINGUP)) {
SetBit(*swap_flag1, VRF_GOINGDOWN);
} else if (HasBit(flag2, VRF_GOINGDOWN)) {
SetBit(*swap_flag1, VRF_GOINGUP);
}
}
static void ReverseTrainSwapVeh(Vehicle *v, int l, int r)
{
Vehicle *a, *b;
/* locate vehicles to swap */
for (a = v; l != 0; l--) a = a->Next();
for (b = v; r != 0; r--) b = b->Next();
if (a != b) {
/* swap the hidden bits */
{
uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus&VS_HIDDEN);
b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus&VS_HIDDEN);
a->vehstatus = tmp;
}
Swap(a->u.rail.track, b->u.rail.track);
Swap(a->direction, b->direction);
/* toggle direction */
if (a->u.rail.track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
if (b->u.rail.track != TRACK_BIT_DEPOT) b->direction = ReverseDir(b->direction);
Swap(a->x_pos, b->x_pos);
Swap(a->y_pos, b->y_pos);
Swap(a->tile, b->tile);
Swap(a->z_pos, b->z_pos);
SwapTrainFlags(&a->u.rail.flags, &b->u.rail.flags);
/* update other vars */
UpdateVarsAfterSwap(a);
UpdateVarsAfterSwap(b);
/* call the proper EnterTile function unless we are in a wormhole */
if (a->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
if (b->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(b, b->tile, b->x_pos, b->y_pos);
} else {
if (a->u.rail.track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
UpdateVarsAfterSwap(a);
if (a->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
}
/* Update train's power incase tiles were different rail type */
TrainPowerChanged(v);
}
/**
* Check if the vehicle is a train
* @param v vehicle on tile
* @return v if it is a train, NULL otherwise
*/
static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
{
return (v->type == VEH_TRAIN) ? v : NULL;
}
/**
* Checks if a train is approaching a rail-road crossing
* @param v vehicle on tile
* @param data tile with crossing we are testing
* @return v if it is approaching a crossing, NULL otherwise
*/
static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
{
/* not a train || not front engine || crashed */
if (v->type != VEH_TRAIN || !IsFrontEngine(v) || v->vehstatus & VS_CRASHED) return NULL;
TileIndex tile = *(TileIndex*)data;
if (TrainApproachingCrossingTile(v) != tile) return NULL;
return v;
}
/**
* Finds a vehicle approaching rail-road crossing
* @param tile tile to test
* @return true if a vehicle is approaching the crossing
* @pre tile is a rail-road crossing
*/
static bool TrainApproachingCrossing(TileIndex tile)
{
assert(IsLevelCrossingTile(tile));
DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
TileIndex tile_from = tile + TileOffsByDiagDir(dir);
if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
dir = ReverseDiagDir(dir);
tile_from = tile + TileOffsByDiagDir(dir);
return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
}
/**
* Sets correct crossing state
* @param tile tile to update
* @param sound should we play sound?
* @pre tile is a rail-road crossing
*/
void UpdateLevelCrossing(TileIndex tile, bool sound)
{
assert(IsLevelCrossingTile(tile));
/* train on crossing || train approaching crossing || reserved */
bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || GetCrossingReservation(tile);
if (new_state != IsCrossingBarred(tile)) {
if (new_state && sound) {
SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
}
SetCrossingBarred(tile, new_state);
MarkTileDirtyByTile(tile);
}
}
/**
* Bars crossing and plays ding-ding sound if not barred already
* @param tile tile with crossing
* @pre tile is a rail-road crossing
*/
static inline void MaybeBarCrossingWithSound(TileIndex tile)
{
if (!IsCrossingBarred(tile)) {
BarCrossing(tile);
SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
MarkTileDirtyByTile(tile);
}
}
/**
* Advances wagons for train reversing, needed for variable length wagons.
* This one is called before the train is reversed.
* @param v First vehicle in chain
*/
static void AdvanceWagonsBeforeSwap(Vehicle *v)
{
Vehicle *base = v;
Vehicle *first = base; // first vehicle to move
Vehicle *last = GetLastVehicleInChain(v); // last vehicle to move
uint length = CountVehiclesInChain(v);
while (length > 2) {
last = last->Previous();
first = first->Next();
int differential = base->u.rail.cached_veh_length - last->u.rail.cached_veh_length;
/* do not update images now
* negative differential will be handled in AdvanceWagonsAfterSwap() */
for (int i = 0; i < differential; i++) TrainController(first, last->Next());
base = first; // == base->Next()
length -= 2;
}
}
/**
* Advances wagons for train reversing, needed for variable length wagons.
* This one is called after the train is reversed.
* @param v First vehicle in chain
*/
static void AdvanceWagonsAfterSwap(Vehicle *v)
{
/* first of all, fix the situation when the train was entering a depot */
Vehicle *dep = v; // last vehicle in front of just left depot
while (dep->Next() != NULL && (dep->u.rail.track == TRACK_BIT_DEPOT || dep->Next()->u.rail.track != TRACK_BIT_DEPOT)) {
dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
}
Vehicle *leave = dep->Next(); // first vehicle in a depot we are leaving now
if (leave != NULL) {
/* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
int d = TicksToLeaveDepot(dep);
if (d <= 0) {
leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
leave->u.rail.track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
}
} else {
dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
}
Vehicle *base = v;
Vehicle *first = base; // first vehicle to move
Vehicle *last = GetLastVehicleInChain(v); // last vehicle to move
uint length = CountVehiclesInChain(v);
/* we have to make sure all wagons that leave a depot because of train reversing are moved coorectly
* they have already correct spacing, so we have to make sure they are moved how they should */
bool nomove = (dep == NULL); // if there is no vehicle leaving a depot, limit the number of wagons moved immediatelly
while (length > 2) {
/* we reached vehicle (originally) in front of a depot, stop now
* (we would move wagons that are alredy moved with new wagon length) */
if (base == dep) break;
/* the last wagon was that one leaving a depot, so do not move it anymore */
if (last == dep) nomove = true;
last = last->Previous();
first = first->Next();
int differential = last->u.rail.cached_veh_length - base->u.rail.cached_veh_length;
/* do not update images now */
for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
base = first; // == base->Next()
length -= 2;
}
}
static void ReverseTrainDirection(Vehicle *v)
{
if (IsRailDepotTile(v->tile)) {
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
}
/* Clear path reservation in front. */
FreeTrainTrackReservation(v);
/* Check if we were approaching a rail/road-crossing */
TileIndex crossing = TrainApproachingCrossingTile(v);
/* count number of vehicles */
int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
AdvanceWagonsBeforeSwap(v);
/* swap start<>end, start+1<>end-1, ... */
int l = 0;
do {
ReverseTrainSwapVeh(v, l++, r--);
} while (l <= r);
AdvanceWagonsAfterSwap(v);
if (IsRailDepotTile(v->tile)) {
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
}
ToggleBit(v->u.rail.flags, VRF_TOGGLE_REVERSE);
ClrBit(v->u.rail.flags, VRF_REVERSING);
/* recalculate cached data */
TrainConsistChanged(v, true);
/* update all images */
for (Vehicle *u = v; u != NULL; u = u->Next()) u->cur_image = u->GetImage(u->direction);
/* update crossing we were approaching */
if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
/* maybe we are approaching crossing now, after reversal */
crossing = TrainApproachingCrossingTile(v);
if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
/* If we are inside a depot after reversing, don't bother with path reserving. */
if (v->u.rail.track & TRACK_BIT_DEPOT) {
/* Can't be stuck here as inside a depot is always a safe tile. */
if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
return;
}
/* TrainExitDir does not always produce the desired dir for depots and
* tunnels/bridges that is needed for UpdateSignalsOnSegment. */
DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
/* If we are currently on a tile with conventional signals, we can't treat the
* current tile as a safe tile or we would enter a PBS block without a reservation. */
bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
HasSignalOnTrackdir(v->tile, GetVehicleTrackdir(v)) &&
!IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->u.rail.track))));
if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(GetVehicleTrackdir(v)), true);
if (TryPathReserve(v, false, first_tile_okay)) {
/* Do a look-ahead now in case our current tile was already a safe tile. */
CheckNextTrainTile(v);
} else if (v->current_order.GetType() != OT_LOADING) {
/* Do not wait for a way out when we're still loading */
MarkTrainAsStuck(v);
}
} else if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
/* A train not inside a PBS block can't be stuck. */
ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
v->load_unload_time_rem = 0;
}
}
/** Reverse train.
* @param tile unused
* @param flags type of operation
* @param p1 train to reverse
* @param p2 if true, reverse a unit in a train (needs to be in a depot)
*/
CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
if (p2 != 0) {
/* turn a single unit around */
if (IsMultiheaded(v) || HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) {
return_cmd_error(STR_ONLY_TURN_SINGLE_UNIT);
}
Vehicle *front = v->First();
/* make sure the vehicle is stopped in the depot */
if (CheckTrainStoppedInDepot(front) < 0) {
return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
}
if (flags & DC_EXEC) {
ToggleBit(v->u.rail.flags, VRF_REVERSE_DIRECTION);
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
}
} else {
/* turn the whole train around */
if (v->vehstatus & VS_CRASHED || v->breakdown_ctr != 0) return CMD_ERROR;
if (flags & DC_EXEC) {
/* Properly leave the station if we are loading and won't be loading anymore */
if (v->current_order.IsType(OT_LOADING)) {
const Vehicle *last = v;
while (last->Next() != NULL) last = last->Next();
/* not a station || different station --> leave the station */
if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
v->LeaveStation();
}
}
if (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && v->cur_speed != 0) {
ToggleBit(v->u.rail.flags, VRF_REVERSING);
} else {
v->cur_speed = 0;
SetLastSpeed(v, 0);
HideFillingPercent(&v->fill_percent_te_id);
ReverseTrainDirection(v);
}
}
}
return CommandCost();
}
/** Force a train through a red signal
* @param tile unused
* @param flags type of operation
* @param p1 train to ignore the red signal
* @param p2 unused
*/
CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
if (flags & DC_EXEC) v->u.rail.force_proceed = 0x50;
return CommandCost();
}
/** Refits a train to the specified cargo type.
* @param tile unused
* @param flags type of operation
* @param p1 vehicle ID of the train to refit
* param p2 various bitstuffed elements
* - p2 = (bit 0-7) - the new cargo type to refit to
* - p2 = (bit 8-15) - the new cargo subtype to refit to
* - p2 = (bit 16) - refit only this vehicle
* @return cost of refit or error
*/
CommandCost CmdRefitRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CargoID new_cid = GB(p2, 0, 8);
byte new_subtype = GB(p2, 8, 8);
bool only_this = HasBit(p2, 16);
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
if (CheckTrainStoppedInDepot(v) < 0) return_cmd_error(STR_TRAIN_MUST_BE_STOPPED);
if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_CAN_T_REFIT_DESTROYED_VEHICLE);
/* Check cargo */
if (new_cid >= NUM_CARGO) return CMD_ERROR;
CommandCost cost(EXPENSES_TRAIN_RUN);
uint num = 0;
do {
/* XXX: We also refit all the attached wagons en-masse if they
* can be refitted. This is how TTDPatch does it. TODO: Have
* some nice [Refit] button near each wagon. --pasky */
if (!CanRefitTo(v->engine_type, new_cid)) continue;
const Engine *e = GetEngine(v->engine_type);
if (e->CanCarryCargo()) {
uint16 amount = CALLBACK_FAILED;
if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
/* Back up the vehicle's cargo type */
CargoID temp_cid = v->cargo_type;
byte temp_subtype = v->cargo_subtype;
v->cargo_type = new_cid;
v->cargo_subtype = new_subtype;
/* Check the refit capacity callback */
amount = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
/* Restore the original cargo type */
v->cargo_type = temp_cid;
v->cargo_subtype = temp_subtype;
}
if (amount == CALLBACK_FAILED) { // callback failed or not used, use default
CargoID old_cid = e->GetDefaultCargoType();
/* normally, the capacity depends on the cargo type, a rail vehicle can
* carry twice as much mail/goods as normal cargo, and four times as
* many passengers
*/
amount = e->u.rail.capacity;
switch (old_cid) {
case CT_PASSENGERS: break;
case CT_MAIL:
case CT_GOODS: amount *= 2; break;
default: amount *= 4; break;
}
switch (new_cid) {
case CT_PASSENGERS: break;
case CT_MAIL:
case CT_GOODS: amount /= 2; break;
default: amount /= 4; break;
}
}
if (new_cid != v->cargo_type) {
cost.AddCost(GetRefitCost(v->engine_type));
}
num += amount;
if (flags & DC_EXEC) {
v->cargo.Truncate((v->cargo_type == new_cid) ? amount : 0);
v->cargo_type = new_cid;
v->cargo_cap = amount;
v->cargo_subtype = new_subtype;
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
}
}
} while ((v = v->Next()) != NULL && !only_this);
_returned_refit_capacity = num;
/* Update the train's cached variables */
if (flags & DC_EXEC) TrainConsistChanged(GetVehicle(p1)->First(), false);
return cost;
}
struct TrainFindDepotData {
uint best_length;
TileIndex tile;
Owner owner;
/**
* true if reversing is necessary for the train to get to this depot
* This value is unused when new depot finding and NPF are both disabled
*/
bool reverse;
};
static bool NtpCallbFindDepot(TileIndex tile, TrainFindDepotData *tfdd, int track, uint length)
{
if (IsTileType(tile, MP_RAILWAY) &&
IsTileOwner(tile, tfdd->owner) &&
IsRailDepot(tile)) {
/* approximate number of tiles by dividing by DIAG_FACTOR */
tfdd->best_length = length / DIAG_FACTOR;
tfdd->tile = tile;
return true;
}
return false;
}
/** returns the tile of a depot to goto to. The given vehicle must not be
* crashed! */
static TrainFindDepotData FindClosestTrainDepot(Vehicle *v, int max_distance)
{
assert(!(v->vehstatus & VS_CRASHED));
TrainFindDepotData tfdd;
tfdd.owner = v->owner;
tfdd.reverse = false;
if (IsRailDepotTile(v->tile)) {
tfdd.tile = v->tile;
tfdd.best_length = 0;
return tfdd;
}
PBSTileInfo origin = FollowTrainReservation(v);
if (IsRailDepotTile(origin.tile)) {
tfdd.tile = origin.tile;
tfdd.best_length = 0;
return tfdd;
}
tfdd.best_length = UINT_MAX;
uint8 pathfinder = _settings_game.pf.pathfinder_for_trains;
if ((_settings_game.pf.reserve_paths || HasReservedTracks(v->tile, v->u.rail.track)) && pathfinder == VPF_NTP) pathfinder = VPF_NPF;
switch (pathfinder) {
case VPF_YAPF: { // YAPF
bool found = YapfFindNearestRailDepotTwoWay(v, max_distance, NPF_INFINITE_PENALTY, &tfdd.tile, &tfdd.reverse);
tfdd.best_length = found ? max_distance / 2 : UINT_MAX; // some fake distance or NOT_FOUND
} break;
case VPF_NPF: { // NPF
const Vehicle *last = GetLastVehicleInChain(v);
Trackdir trackdir = GetVehicleTrackdir(v);
Trackdir trackdir_rev = ReverseTrackdir(GetVehicleTrackdir(last));
assert(trackdir != INVALID_TRACKDIR);
NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes, NPF_INFINITE_PENALTY);
if (ftd.best_bird_dist == 0) {
/* Found target */
tfdd.tile = ftd.node.tile;
/* Our caller expects a number of tiles, so we just approximate that
* number by this. It might not be completely what we want, but it will
* work for now :-) We can possibly change this when the old pathfinder
* is removed. */
tfdd.best_length = ftd.best_path_dist / NPF_TILE_LENGTH;
if (NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE)) tfdd.reverse = true;
}
} break;
default:
case VPF_NTP: { // NTP
/* search in the forward direction first. */
DiagDirection i = TrainExitDir(v->direction, v->u.rail.track);
NewTrainPathfind(v->tile, 0, v->u.rail.compatible_railtypes, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd);
if (tfdd.best_length == UINT_MAX){
tfdd.reverse = true;
/* search in backwards direction */
i = TrainExitDir(ReverseDir(v->direction), v->u.rail.track);
NewTrainPathfind(v->tile, 0, v->u.rail.compatible_railtypes, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd);
}
} break;
}
return tfdd;
}
bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
{
TrainFindDepotData tfdd = FindClosestTrainDepot(this, 0);
if (tfdd.best_length == UINT_MAX) return false;
if (location != NULL) *location = tfdd.tile;
if (destination != NULL) *destination = GetDepotByTile(tfdd.tile)->index;
if (reverse != NULL) *reverse = tfdd.reverse;
return true;
}
/** Send a train to a depot
* @param tile unused
* @param flags type of operation
* @param p1 train to send to the depot
* @param p2 various bitmasked elements
* - p2 bit 0-3 - DEPOT_ flags (see vehicle.h)
* - p2 bit 8-10 - VLW flag (for mass goto depot)
*/
CommandCost CmdSendTrainToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (p2 & DEPOT_MASS_SEND) {
/* Mass goto depot requested */
if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
return SendAllVehiclesToDepot(VEH_TRAIN, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
}
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_TRAIN) return CMD_ERROR;
return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
}
void OnTick_Train()
{
_age_cargo_skip_counter = (_age_cargo_skip_counter == 0) ? 184 : (_age_cargo_skip_counter - 1);
}
static const int8 _vehicle_smoke_pos[8] = {
1, 1, 1, 0, -1, -1, -1, 0
};
static void HandleLocomotiveSmokeCloud(const Vehicle *v)
{
bool sound = false;
if (v->vehstatus & VS_TRAIN_SLOWING || v->load_unload_time_rem != 0 || v->cur_speed < 2) {
return;
}
const Vehicle *u = v;
do {
const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
int effect_offset = GB(v->u.rail.cached_vis_effect, 0, 4) - 8;
byte effect_type = GB(v->u.rail.cached_vis_effect, 4, 2);
bool disable_effect = HasBit(v->u.rail.cached_vis_effect, 6);
/* no smoke? */
if ((rvi->railveh_type == RAILVEH_WAGON && effect_type == 0) ||
disable_effect ||
v->vehstatus & VS_HIDDEN) {
continue;
}
/* No smoke in depots or tunnels */
if (IsRailDepotTile(v->tile) || IsTunnelTile(v->tile)) continue;
/* No sparks for electric vehicles on nonelectrified tracks */
if (!HasPowerOnRail(v->u.rail.railtype, GetTileRailType(v->tile))) continue;
if (effect_type == 0) {
/* Use default effect type for engine class. */
effect_type = rvi->engclass;
} else {
effect_type--;
}
int x = _vehicle_smoke_pos[v->direction] * effect_offset;
int y = _vehicle_smoke_pos[(v->direction + 2) % 8] * effect_offset;
if (HasBit(v->u.rail.flags, VRF_REVERSE_DIRECTION)) {
x = -x;
y = -y;
}
switch (effect_type) {
case 0:
/* steam smoke. */
if (GB(v->tick_counter, 0, 4) == 0) {
CreateEffectVehicleRel(v, x, y, 10, EV_STEAM_SMOKE);
sound = true;
}
break;
case 1:
/* diesel smoke */
if (u->cur_speed <= 40 && Chance16(15, 128)) {
CreateEffectVehicleRel(v, 0, 0, 10, EV_DIESEL_SMOKE);
sound = true;
}
break;
case 2:
/* blue spark */
if (GB(v->tick_counter, 0, 2) == 0 && Chance16(1, 45)) {
CreateEffectVehicleRel(v, 0, 0, 10, EV_ELECTRIC_SPARK);
sound = true;
}
break;
default:
break;
}
} while ((v = v->Next()) != NULL);
if (sound) PlayVehicleSound(u, VSE_TRAIN_EFFECT);
}
void Train::PlayLeaveStationSound() const
{
static const SoundFx sfx[] = {
SND_04_TRAIN,
SND_0A_TRAIN_HORN,
SND_0A_TRAIN_HORN,
SND_47_MAGLEV_2,
SND_41_MAGLEV
};
if (PlayVehicleSound(this, VSE_START)) return;
EngineID engtype = this->engine_type;
SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
}
/** Check if the train is on the last reserved tile and try to extend the path then. */
static void CheckNextTrainTile(Vehicle *v)
{
/* Don't do any look-ahead if path_backoff_interval is 255. */
if (_settings_game.pf.path_backoff_interval == 255) return;
/* Exit if we reached our destination depot or are inside a depot. */
if ((v->tile == v->dest_tile && v->current_order.IsType(OT_GOTO_DEPOT)) || v->u.rail.track & TRACK_BIT_DEPOT) return;
/* Exit if we are on a station tile and are going to stop. */
if (IsRailwayStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
/* Exit if the current order doesn't have a destination, but the train has orders. */
if ((v->current_order.IsType(OT_NOTHING) || v->current_order.IsType(OT_LEAVESTATION) || v->current_order.IsType(OT_LOADING)) && v->GetNumOrders() > 0) return;
Trackdir td = GetVehicleTrackdir(v);
/* On a tile with a red non-pbs signal, don't look ahead. */
if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
!IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
CFollowTrackRail ft(v);
if (!ft.Follow(v->tile, td)) return;
if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
/* Next tile is not reserved. */
if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
/* If the next tile is a PBS signal, try to make a reservation. */
TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
}
ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
}
}
}
}
static bool CheckTrainStayInDepot(Vehicle *v)
{
/* bail out if not all wagons are in the same depot or not in a depot at all */
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
if (u->u.rail.track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
}
/* if the train got no power, then keep it in the depot */
if (v->u.rail.cached_power == 0) {
v->vehstatus |= VS_STOPPED;
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
return true;
}
SigSegState seg_state;
if (v->u.rail.force_proceed == 0) {
/* force proceed was not pressed */
if (++v->load_unload_time_rem < 37) {
InvalidateWindowClasses(WC_TRAINS_LIST);
return true;
}
v->load_unload_time_rem = 0;
seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
if (seg_state == SIGSEG_FULL || GetDepotWaypointReservation(v->tile)) {
/* Full and no PBS signal in block or depot reserved, can't exit. */
InvalidateWindowClasses(WC_TRAINS_LIST);
return true;
}
} else {
seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
}
/* Only leave when we can reserve a path to our destination. */
if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->u.rail.force_proceed == 0) {
/* No path and no force proceed. */
InvalidateWindowClasses(WC_TRAINS_LIST);
MarkTrainAsStuck(v);
return true;
}
SetDepotWaypointReservation(v->tile, true);
if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
VehicleServiceInDepot(v);
InvalidateWindowClasses(WC_TRAINS_LIST);
v->PlayLeaveStationSound();
v->u.rail.track = TRACK_BIT_X;
if (v->direction & 2) v->u.rail.track = TRACK_BIT_Y;
v->vehstatus &= ~VS_HIDDEN;
v->cur_speed = 0;
v->UpdateDeltaXY(v->direction);
v->cur_image = v->GetImage(v->direction);
VehicleMove(v, false);
UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
UpdateTrainAcceleration(v);
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
return false;
}
/** Clear the reservation of a tile that was just left by a wagon on track_dir. */
static void ClearPathReservation(const Vehicle *v, TileIndex tile, Trackdir track_dir)
{
DiagDirection dir = TrackdirToExitdir(track_dir);
if (IsTileType(tile, MP_TUNNELBRIDGE)) {
/* Are we just leaving a tunnel/bridge? */
if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
TileIndex end = GetOtherTunnelBridgeEnd(tile);
if (!HasVehicleOnTunnelBridge(tile, end, v)) {
/* Free the reservation only if no other train is on the tiles. */
SetTunnelBridgeReservation(tile, false);
SetTunnelBridgeReservation(end, false);
if (_settings_client.gui.show_track_reservation) {
MarkTileDirtyByTile(tile);
MarkTileDirtyByTile(end);
}
}
}
} else if (IsRailwayStationTile(tile)) {
TileIndex new_tile = TileAddByDiagDir(tile, dir);
/* If the new tile is not a further tile of the same station, we
* clear the reservation for the whole platform. */
if (!IsCompatibleTrainStationTile(new_tile, tile)) {
SetRailwayStationPlatformReservation(tile, ReverseDiagDir(dir), false);
}
} else {
/* Any other tile */
UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
}
}
/** Free the reserved path in front of a vehicle. */
void FreeTrainTrackReservation(const Vehicle *v, TileIndex origin, Trackdir orig_td)
{
assert(IsFrontEngine(v));
TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : GetVehicleTrackdir(v);
bool free_tile = tile != v->tile || !(IsRailwayStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
StationID station_id = IsRailwayStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
/* Don't free reservation if it's not ours. */
if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
CFollowTrackRail ft(v, GetRailTypeInfo(v->u.rail.railtype)->compatible_railtypes);
while (ft.Follow(tile, td)) {
tile = ft.m_new_tile;
TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
td = RemoveFirstTrackdir(&bits);
assert(bits == TRACKDIR_BIT_NONE);
if (!IsValidTrackdir(td)) break;
if (IsTileType(tile, MP_RAILWAY)) {
if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
/* Conventional signal along trackdir: remove reservation and stop. */
UnreserveRailTrack(tile, TrackdirToTrack(td));
break;
}
if (HasPbsSignalOnTrackdir(tile, td)) {
if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
/* Red PBS signal? Can't be our reservation, would be green then. */
break;
} else {
/* Turn the signal back to red. */
SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
MarkTileDirtyByTile(tile);
}
} else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
break;
}
}
/* Don't free first station/bridge/tunnel if we are on it. */
if (free_tile || (!(ft.m_is_station && GetStationIndex(ft.m_new_tile) == station_id) && !ft.m_is_tunnel && !ft.m_is_bridge)) ClearPathReservation(v, tile, td);
free_tile = true;
}
}
/** Check for station tiles */
struct TrainTrackFollowerData {
TileIndex dest_coords;
StationID station_index; ///< station index we're heading for
uint best_bird_dist;
uint best_track_dist;
TrackdirByte best_track;
};
static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, Trackdir track, uint length)
{
/* heading for nowhere? */
if (ttfd->dest_coords == 0) return false;
/* did we reach the final station? */
if ((ttfd->station_index == INVALID_STATION && tile == ttfd->dest_coords) || (
IsTileType(tile, MP_STATION) &&
IsRailwayStation(tile) &&
GetStationIndex(tile) == ttfd->station_index
)) {
/* We do not check for dest_coords if we have a station_index,
* because in that case the dest_coords are just an
* approximation of where the station is */
/* found station */
ttfd->best_track = track;
ttfd->best_bird_dist = 0;
return true;
} else {
/* didn't find station, keep track of the best path so far. */
uint dist = DistanceManhattan(tile, ttfd->dest_coords);
if (dist < ttfd->best_bird_dist) {
ttfd->best_bird_dist = dist;
ttfd->best_track = track;
}
return false;
}
}
static void FillWithStationData(TrainTrackFollowerData *fd, const Vehicle *v)
{
fd->dest_coords = v->dest_tile;
fd->station_index = v->current_order.IsType(OT_GOTO_STATION) ? v->current_order.GetDestination() : INVALID_STATION;
}
static const byte _initial_tile_subcoord[6][4][3] = {
{{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
{{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
{{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
{{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
{{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
{{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
};
static const byte _search_directions[6][4] = {
{ 0, 9, 2, 9 }, ///< track 1
{ 9, 1, 9, 3 }, ///< track 2
{ 9, 0, 3, 9 }, ///< track upper
{ 1, 9, 9, 2 }, ///< track lower
{ 3, 2, 9, 9 }, ///< track left
{ 9, 9, 1, 0 }, ///< track right
};
static const byte _pick_track_table[6] = {1, 3, 2, 2, 0, 0};
/**
* Perform pathfinding for a train.
*
* @param v The train
* @param tile The tile the train is about to enter
* @param enterdir Diagonal direction the train is coming from
* @param tracks Usable tracks on the new tile
* @param path_not_found [out] Set to false if the pathfinder couldn't find a way to the destination
* @param do_track_reservation Path reservation is requested
* @param dest [out] State and destination of the requested path
* @return The best track the train should follow
*/
static Track DoTrainPathfind(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool do_track_reservation, PBSTileInfo *dest)
{
Track best_track;
#ifdef PF_BENCHMARK
TIC()
#endif
if (path_not_found) *path_not_found = false;
uint8 pathfinder = _settings_game.pf.pathfinder_for_trains;
if (do_track_reservation && pathfinder == VPF_NTP) pathfinder = VPF_NPF;
switch (pathfinder) {
case VPF_YAPF: { // YAPF
Trackdir trackdir = YapfChooseRailTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
if (trackdir != INVALID_TRACKDIR) {
best_track = TrackdirToTrack(trackdir);
} else {
best_track = FindFirstTrack(tracks);
}
} break;
case VPF_NPF: { // NPF
void *perf = NpfBeginInterval();
NPFFindStationOrTileData fstd;
NPFFillWithOrderData(&fstd, v, do_track_reservation);
PBSTileInfo origin = FollowTrainReservation(v);
assert(IsValidTrackdir(origin.trackdir));
NPFFoundTargetData ftd = NPFRouteToStationOrTile(origin.tile, origin.trackdir, true, &fstd, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes);
if (dest != NULL) {
dest->tile = ftd.node.tile;
dest->trackdir = (Trackdir)ftd.node.direction;
dest->okay = ftd.res_okay;
}
if (ftd.best_trackdir == INVALID_TRACKDIR) {
/* We are already at our target. Just do something
* @todo maybe display error?
* @todo: go straight ahead if possible? */
best_track = FindFirstTrack(tracks);
} else {
/* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
* the direction we need to take to get there, if ftd.best_bird_dist is not 0,
* we did not find our target, but ftd.best_trackdir contains the direction leading
* to the tile closest to our target. */
if (ftd.best_bird_dist != 0 && path_not_found != NULL) *path_not_found = true;
/* Discard enterdir information, making it a normal track */
best_track = TrackdirToTrack(ftd.best_trackdir);
}
int time = NpfEndInterval(perf);
DEBUG(yapf, 4, "[NPFT] %d us - %d rounds - %d open - %d closed -- ", time, 0, _aystar_stats_open_size, _aystar_stats_closed_size);
} break;
default:
case VPF_NTP: { // NTP
void *perf = NpfBeginInterval();
TrainTrackFollowerData fd;
FillWithStationData(&fd, v);
/* New train pathfinding */
fd.best_bird_dist = UINT_MAX;
fd.best_track_dist = UINT_MAX;
fd.best_track = INVALID_TRACKDIR;
NewTrainPathfind(tile - TileOffsByDiagDir(enterdir), v->dest_tile,
v->u.rail.compatible_railtypes, enterdir, (NTPEnumProc*)NtpCallbFindStation, &fd);
/* check whether the path was found or only 'guessed' */
if (fd.best_bird_dist != 0 && path_not_found != NULL) *path_not_found = true;
if (fd.best_track == INVALID_TRACKDIR) {
/* blaha */
best_track = FindFirstTrack(tracks);
} else {
best_track = TrackdirToTrack(fd.best_track);
}
int time = NpfEndInterval(perf);
DEBUG(yapf, 4, "[NTPT] %d us - %d rounds - %d open - %d closed -- ", time, 0, 0, 0);
} break;
}
#ifdef PF_BENCHMARK
TOC("PF time = ", 1)
#endif
return best_track;
}
/**
* Extend a train path as far as possible. Stops on encountering a safe tile,
* another reservation or a track choice.
* @return INVALID_TILE indicates that the reservation failed.
*/
static PBSTileInfo ExtendTrainReservation(const Vehicle *v, TrackBits *new_tracks, DiagDirection *enterdir)
{
bool no_90deg_turns = _settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg;
PBSTileInfo origin = FollowTrainReservation(v);
CFollowTrackRail ft(v);
TileIndex tile = origin.tile;
Trackdir cur_td = origin.trackdir;
while (ft.Follow(tile, cur_td)) {
if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
/* Possible signal tile. */
if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
}
if (no_90deg_turns) {
ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
}
/* Station, depot or waypoint are a possible target. */
bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRailTile(ft.m_new_tile));
if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
/* Choice found or possible target encountered.
* On finding a possible target, we need to stop and let the pathfinder handle the
* remaining path. This is because we don't know if this target is in one of our
* orders, so we might cause pathfinding to fail later on if we find a choice.
* This failure would cause a bogous call to TryReserveSafePath which might reserve
* a wrong path not leading to our next destination. */
if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
/* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
* actually starts its search at the first unreserved tile. */
if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
/* Choice found, path valid but not okay. Save info about the choice tile as well. */
if (new_tracks) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
if (enterdir) *enterdir = ft.m_exitdir;
return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
}
tile = ft.m_new_tile;
cur_td = FindFirstTrackdir(ft.m_new_td_bits);
if (IsSafeWaitingPosition(v, tile, cur_td, true, no_90deg_turns)) {
bool wp_free = IsWaitingPositionFree(v, tile, cur_td, no_90deg_turns);
if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
/* Safe position is all good, path valid and okay. */
return PBSTileInfo(tile, cur_td, true);
}
if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
}
if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
/* End of line, path valid and okay. */
return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
}
/* Sorry, can't reserve path, back out. */
tile = origin.tile;
cur_td = origin.trackdir;
TileIndex stopped = ft.m_old_tile;
Trackdir stopped_td = ft.m_old_td;
while (tile != stopped || cur_td != stopped_td) {
if (!ft.Follow(tile, cur_td)) break;
if (no_90deg_turns) {
ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
}
assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
tile = ft.m_new_tile;
cur_td = FindFirstTrackdir(ft.m_new_td_bits);
UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
}
/* Path invalid. */
return PBSTileInfo();
}
/**
* Try to reserve any path to a safe tile, ignoring the vehicle's destination.
* Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
*
* @param v The vehicle.
* @param tile The tile the search should start from.
* @param td The trackdir the search should start from.
* @param override_tailtype Whether all physically compatible railtypes should be followed.
* @return True if a path to a safe stopping tile could be reserved.
*/
static bool TryReserveSafeTrack(const Vehicle *v, TileIndex tile, Trackdir td, bool override_tailtype)
{
if (_settings_game.pf.pathfinder_for_trains == VPF_YAPF) {
return YapfRailFindNearestSafeTile(v, tile, td, override_tailtype);
} else {
return NPFRouteToSafeTile(v, tile, td, override_tailtype).res_okay;
}
}
/** This class will save the current order of a vehicle and restore it on destruction. */
class VehicleOrderSaver
{
private:
Vehicle *v;
Order old_order;
TileIndex old_dest_tile;
StationID old_last_station_visited;
VehicleOrderID index;
public:
VehicleOrderSaver(Vehicle *_v) :
v(_v),
old_order(_v->current_order),
old_dest_tile(_v->dest_tile),
old_last_station_visited(_v->last_station_visited),
index(_v->cur_order_index)
{
}
~VehicleOrderSaver()
{
this->v->current_order = this->old_order;
this->v->dest_tile = this->old_dest_tile;
this->v->last_station_visited = this->old_last_station_visited;
}
/**
* Set the current vehicle order to the next order in the order list.
* @param skip_first Shall the first (i.e. active) order be skipped?
* @return True if a suitable next order could be found.
*/
bool SwitchToNextOrder(bool skip_first)
{
if (this->v->GetNumOrders() == 0) return false;
if (skip_first) ++this->index;
int conditional_depth = 0;
do {
/* Wrap around. */
if (this->index >= this->v->GetNumOrders()) this->index = 0;
Order *order = GetVehicleOrder(this->v, this->index);
assert(order != NULL);
switch (order->GetType()) {
case OT_GOTO_DEPOT:
/* Skip service in depot orders when the train doesn't need service. */
if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
case OT_GOTO_STATION:
case OT_GOTO_WAYPOINT:
this->v->current_order = *order;
UpdateOrderDest(this->v, order);
return true;
case OT_CONDITIONAL: {
if (conditional_depth > this->v->GetNumOrders()) return false;
VehicleOrderID next = ProcessConditionalOrder(order, this->v);
if (next != INVALID_VEH_ORDER_ID) {
conditional_depth++;
this->index = next;
/* Don't increment next, so no break here. */
continue;
}
break;
}
default:
break;
}
/* Don't increment inside the while because otherwise conditional
* orders can lead to an infinite loop. */
++this->index;
} while (this->index != this->v->cur_order_index);
return false;
}
};
/* choose a track */
static Track ChooseTrainTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
{
Track best_track = INVALID_TRACK;
bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
bool changed_signal = false;
assert((tracks & ~TRACK_BIT_MASK) == 0);
if (got_reservation != NULL) *got_reservation = false;
/* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
/* Do we have a suitable reserved track? */
if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
/* Quick return in case only one possible track is available */
if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
Track track = FindFirstTrack(tracks);
/* We need to check for signals only here, as a junction tile can't have signals. */
if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
do_track_reservation = true;
changed_signal = true;
SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
} else if (!do_track_reservation) {
return track;
}
best_track = track;
}
PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
DiagDirection dest_enterdir = enterdir;
if (do_track_reservation) {
/* Check if the train needs service here, so it has a chance to always find a depot.
* Also check if the current order is a service order so we don't reserve a path to
* the destination but instead to the next one if service isn't needed. */
CheckIfTrainNeedsService(v);
if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
if (res_dest.tile == INVALID_TILE) {
/* Reservation failed? */
if (mark_stuck) MarkTrainAsStuck(v);
if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
return FindFirstTrack(tracks);
}
}
/* Save the current train order. The destructor will restore the old order on function exit. */
VehicleOrderSaver orders(v);
/* If the current tile is the destination of the current order and
* a reservation was requested, advance to the next order.
* Don't advance on a depot order as depots are always safe end points
* for a path and no look-ahead is necessary. This also avoids a
* problem with depot orders not part of the order list when the
* order list itself is empty. */
if (v->current_order.IsType(OT_LEAVESTATION)) {
orders.SwitchToNextOrder(false);
} else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
v->current_order.IsType(OT_GOTO_STATION) ?
IsRailwayStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
v->tile == v->dest_tile))) {
orders.SwitchToNextOrder(true);
}
if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
/* Pathfinders are able to tell that route was only 'guessed'. */
bool path_not_found = false;
TileIndex new_tile = res_dest.tile;
Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, &path_not_found, do_track_reservation, &res_dest);
if (new_tile == tile) best_track = next_track;
/* handle "path not found" state */
if (path_not_found) {
/* PF didn't find the route */
if (!HasBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION)) {
/* it is first time the problem occurred, set the "path not found" flag */
SetBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION);
/* and notify user about the event */
AI::NewEvent(v->owner, new AIEventVehicleLost(v->index));
if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
SetDParam(0, v->index);
AddNewsItem(
STR_TRAIN_IS_LOST,
NS_ADVICE,
v->index,
0);
}
}
} else {
/* route found, is the train marked with "path not found" flag? */
if (HasBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION)) {
/* clear the flag as the PF's problem was solved */
ClrBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION);
/* can we also delete the "News" item somehow? */
}
}
}
/* No track reservation requested -> finished. */
if (!do_track_reservation) return best_track;
/* A path was found, but could not be reserved. */
if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
if (mark_stuck) MarkTrainAsStuck(v);
FreeTrainTrackReservation(v);
return best_track;
}
/* No possible reservation target found, we are probably lost. */
if (res_dest.tile == INVALID_TILE) {
/* Try to find any safe destination. */
PBSTileInfo origin = FollowTrainReservation(v);
if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
best_track = FindFirstTrack(res);
TryReserveRailTrack(v->tile, TrackdirToTrack(GetVehicleTrackdir(v)));
if (got_reservation != NULL) *got_reservation = true;
if (changed_signal) MarkTileDirtyByTile(tile);
} else {
FreeTrainTrackReservation(v);
if (mark_stuck) MarkTrainAsStuck(v);
}
return best_track;
}
if (got_reservation != NULL) *got_reservation = true;
/* Reservation target found and free, check if it is safe. */
while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
/* Extend reservation until we have found a safe position. */
DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
}
/* Get next order with destination. */
if (orders.SwitchToNextOrder(true)) {
PBSTileInfo cur_dest;
DoTrainPathfind(v, next_tile, exitdir, reachable, NULL, true, &cur_dest);
if (cur_dest.tile != INVALID_TILE) {
res_dest = cur_dest;
if (res_dest.okay) continue;
/* Path found, but could not be reserved. */
FreeTrainTrackReservation(v);
if (mark_stuck) MarkTrainAsStuck(v);
if (got_reservation != NULL) *got_reservation = false;
changed_signal = false;
break;
}
}
/* No order or no safe position found, try any position. */
if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
FreeTrainTrackReservation(v);
if (mark_stuck) MarkTrainAsStuck(v);
if (got_reservation != NULL) *got_reservation = false;
changed_signal = false;
}
break;
}
TryReserveRailTrack(v->tile, TrackdirToTrack(GetVehicleTrackdir(v)));
if (changed_signal) MarkTileDirtyByTile(tile);
return best_track;
}
/**
* Try to reserve a path to a safe position.
*
* @param v The vehicle
* @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
* @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
* @return True if a path could be reserved.
*/
bool TryPathReserve(Vehicle *v, bool mark_as_stuck, bool first_tile_okay)
{
assert(v->type == VEH_TRAIN && IsFrontEngine(v));
/* We have to handle depots specially as the track follower won't look
* at the depot tile itself but starts from the next tile. If we are still
* inside the depot, a depot reservation can never be ours. */
if (v->u.rail.track & TRACK_BIT_DEPOT) {
if (GetDepotWaypointReservation(v->tile)) {
if (mark_as_stuck) MarkTrainAsStuck(v);
return false;
} else {
/* Depot not reserved, but the next tile might be. */
TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
}
}
/* Special check if we are in front of a two-sided conventional signal. */
DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
TileIndex next_tile = TileAddByDiagDir(v->tile, dir);
if (IsTileType(next_tile, MP_RAILWAY) && HasReservedTracks(next_tile, DiagdirReachesTracks(dir))) {
/* Can have only one reserved trackdir. */
Trackdir td = FindFirstTrackdir(TrackBitsToTrackdirBits(GetReservedTrackbits(next_tile)) & DiagdirReachesTrackdirs(dir));
if (HasSignalOnTrackdir(next_tile, td) && HasSignalOnTrackdir(next_tile, ReverseTrackdir(td)) &&
!IsPbsSignal(GetSignalType(next_tile, TrackdirToTrack(td)))) {
/* Signal already reserved, is not ours. */
if (mark_as_stuck) MarkTrainAsStuck(v);
return false;
}
}
bool other_train = false;
PBSTileInfo origin = FollowTrainReservation(v, &other_train);
/* If we have a reserved path and the path ends at a safe tile, we are finished already. */
if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
/* Can't be stuck then. */
if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
return true;
}
/* The path we are driving on is alread blocked by some other train.
* This can only happen when tracks and signals are changed. A crash
* is probably imminent, don't do any further reservation because
* it might cause stale reservations. */
if (other_train && v->tile != origin.tile) {
if (mark_as_stuck) MarkTrainAsStuck(v);
return false;
}
/* If we are in a depot, tentativly reserve the depot. */
if (v->u.rail.track & TRACK_BIT_DEPOT) {
SetDepotWaypointReservation(v->tile, true);
if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
}
DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
bool res_made = false;
ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
if (!res_made) {
/* Free the depot reservation as well. */
if (v->u.rail.track & TRACK_BIT_DEPOT) SetDepotWaypointReservation(v->tile, false);
return false;
}
if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
v->load_unload_time_rem = 0;
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
return true;
}
static bool CheckReverseTrain(Vehicle *v)
{
if (_settings_game.difficulty.line_reverse_mode != 0 ||
v->u.rail.track == TRACK_BIT_DEPOT || v->u.rail.track == TRACK_BIT_WORMHOLE ||
!(v->direction & 1)) {
return false;
}
uint reverse_best = 0;
assert(v->u.rail.track);
switch (_settings_game.pf.pathfinder_for_trains) {
case VPF_YAPF: // YAPF
reverse_best = YapfCheckReverseTrain(v);
break;
case VPF_NPF: { // NPF
NPFFindStationOrTileData fstd;
NPFFoundTargetData ftd;
Vehicle *last = GetLastVehicleInChain(v);
NPFFillWithOrderData(&fstd, v);
Trackdir trackdir = GetVehicleTrackdir(v);
Trackdir trackdir_rev = ReverseTrackdir(GetVehicleTrackdir(last));
assert(trackdir != INVALID_TRACKDIR);
assert(trackdir_rev != INVALID_TRACKDIR);
ftd = NPFRouteToStationOrTileTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, &fstd, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes);
if (ftd.best_bird_dist != 0) {
/* We didn't find anything, just keep on going straight ahead */
reverse_best = false;
} else {
if (NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE)) {
reverse_best = true;
} else {
reverse_best = false;
}
}
} break;
default:
case VPF_NTP: { // NTP
TrainTrackFollowerData fd;
FillWithStationData(&fd, v);
int i = _search_directions[FindFirstTrack(v->u.rail.track)][DirToDiagDir(v->direction)];
int best_track = -1;
uint reverse = 0;
uint best_bird_dist = 0;
uint best_track_dist = 0;
for (;;) {
fd.best_bird_dist = UINT_MAX;
fd.best_track_dist = UINT_MAX;
NewTrainPathfind(v->tile, v->dest_tile, v->u.rail.compatible_railtypes, (DiagDirection)(reverse ^ i), (NTPEnumProc*)NtpCallbFindStation, &fd);
if (best_track != -1) {
if (best_bird_dist != 0) {
if (fd.best_bird_dist != 0) {
/* neither reached the destination, pick the one with the smallest bird dist */
if (fd.best_bird_dist > best_bird_dist) goto bad;
if (fd.best_bird_dist < best_bird_dist) goto good;
} else {
/* we found the destination for the first time */
goto good;
}
} else {
if (fd.best_bird_dist != 0) {
/* didn't find destination, but we've found the destination previously */
goto bad;
} else {
/* both old & new reached the destination, compare track length */
if (fd.best_track_dist > best_track_dist) goto bad;
if (fd.best_track_dist < best_track_dist) goto good;
}
}
/* if we reach this position, there's two paths of equal value so far.
* pick one randomly. */
int r = GB(Random(), 0, 8);
if (_pick_track_table[i] == (v->direction & 3)) r += 80;
if (_pick_track_table[best_track] == (v->direction & 3)) r -= 80;
if (r <= 127) goto bad;
}
good:;
best_track = i;
best_bird_dist = fd.best_bird_dist;
best_track_dist = fd.best_track_dist;
reverse_best = reverse;
bad:;
if (reverse != 0) break;
reverse = 2;
}
} break;
}
return reverse_best != 0;
}
TileIndex Train::GetOrderStationLocation(StationID station)
{
if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
const Station *st = GetStation(station);
if (!(st->facilities & FACIL_TRAIN)) {
/* The destination station has no trainstation tiles. */
this->cur_order_index++;
return 0;
}
return st->xy;
}
void Train::MarkDirty()
{
Vehicle *v = this;
do {
v->cur_image = v->GetImage(v->direction);
MarkSingleVehicleDirty(v);
} while ((v = v->Next()) != NULL);
/* need to update acceleration and cached values since the goods on the train changed. */
TrainCargoChanged(this);
UpdateTrainAcceleration(this);
}
/**
* This function looks at the vehicle and updates it's speed (cur_speed
* and subspeed) variables. Furthermore, it returns the distance that
* the train can drive this tick. This distance is expressed as 256 * n,
* where n is the number of straight (long) tracks the train can
* traverse. This means that moving along a straight track costs 256
* "speed" and a diagonal track costs 192 "speed".
* @param v The vehicle to update the speed of.
* @return distance to drive.
*/
static int UpdateTrainSpeed(Vehicle *v)
{
uint accel;
if (v->vehstatus & VS_STOPPED || HasBit(v->u.rail.flags, VRF_REVERSING) || HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
switch (_settings_game.vehicle.train_acceleration_model) {
default: NOT_REACHED();
case TAM_ORIGINAL: accel = v->acceleration * -4; break;
case TAM_REALISTIC: accel = GetTrainAcceleration(v, AM_BRAKE); break;
}
} else {
switch (_settings_game.vehicle.train_acceleration_model) {
default: NOT_REACHED();
case TAM_ORIGINAL: accel = v->acceleration * 2; break;
case TAM_REALISTIC: accel = GetTrainAcceleration(v, AM_ACCEL); break;
}
}
uint spd = v->subspeed + accel;
v->subspeed = (byte)spd;
{
int tempmax = v->max_speed;
if (v->cur_speed > v->max_speed)
tempmax = v->cur_speed - (v->cur_speed / 10) - 1;
v->cur_speed = spd = Clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax);
}
/* Scale speed by 3/4. Previously this was only done when the train was
* facing diagonally and would apply to however many moves the train made
* regardless the of direction actually moved in. Now it is always scaled,
* 256 spd is used to go straight and 192 is used to go diagonally
* (3/4 of 256). This results in the same effect, but without the error the
* previous method caused.
*
* The scaling is done in this direction and not by multiplying the amount
* to be subtracted by 4/3 so that the leftover speed can be saved in a
* byte in v->progress.
*/
int scaled_spd = spd * 3 >> 2;
scaled_spd += v->progress;
v->progress = 0; // set later in TrainLocoHandler or TrainController
return scaled_spd;
}
static void TrainEnterStation(Vehicle *v, StationID station)
{
v->last_station_visited = station;
/* check if a train ever visited this station before */
Station *st = GetStation(station);
if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
st->had_vehicle_of_type |= HVOT_TRAIN;
SetDParam(0, st->index);
AddNewsItem(
STR_8801_CITIZENS_CELEBRATE_FIRST,
v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
v->index,
st->index
);
AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
}
v->BeginLoading();
StationAnimationTrigger(st, v->tile, STAT_ANIM_TRAIN_ARRIVES);
}
static byte AfterSetTrainPos(Vehicle *v, bool new_tile)
{
byte old_z = v->z_pos;
v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
if (new_tile) {
ClrBit(v->u.rail.flags, VRF_GOINGUP);
ClrBit(v->u.rail.flags, VRF_GOINGDOWN);
if (v->u.rail.track == TRACK_BIT_X || v->u.rail.track == TRACK_BIT_Y) {
/* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped.
* To check whether the current tile is sloped, and in which
* direction it is sloped, we get the 'z' at the center of
* the tile (middle_z) and the edge of the tile (old_z),
* which we then can compare. */
static const int HALF_TILE_SIZE = TILE_SIZE / 2;
static const int INV_TILE_SIZE_MASK = ~(TILE_SIZE - 1);
byte middle_z = GetSlopeZ((v->x_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE, (v->y_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE);
/* For some reason tunnel tiles are always given as sloped :(
* But they are not sloped... */
if (middle_z != v->z_pos && !IsTunnelTile(TileVirtXY(v->x_pos, v->y_pos))) {
SetBit(v->u.rail.flags, (middle_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN);
}
}
}
VehicleMove(v, true);
return old_z;
}
static const Direction _new_vehicle_direction_table[11] = {
DIR_N , DIR_NW, DIR_W , INVALID_DIR,
DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
DIR_E , DIR_SE, DIR_S
};
static inline Direction GetNewVehicleDirectionByTile(TileIndex new_tile, TileIndex old_tile)
{
uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
TileX(new_tile) - TileX(old_tile) + 1;
assert(offs < 11);
return _new_vehicle_direction_table[offs];
}
static inline int GetDirectionToVehicle(const Vehicle *v, int x, int y)
{
byte offs;
x -= v->x_pos;
if (x >= 0) {
offs = (x > 2) ? 0 : 1;
} else {
offs = (x < -2) ? 2 : 1;
}
y -= v->y_pos;
if (y >= 0) {
offs += ((y > 2) ? 0 : 1) * 4;
} else {
offs += ((y < -2) ? 2 : 1) * 4;
}
assert(offs < 11);
return _new_vehicle_direction_table[offs];
}
/* Check if the vehicle is compatible with the specified tile */
static inline bool CheckCompatibleRail(const Vehicle *v, TileIndex tile)
{
return
IsTileOwner(tile, v->owner) && (
!IsFrontEngine(v) ||
HasBit(v->u.rail.compatible_railtypes, GetRailType(tile))
);
}
struct RailtypeSlowdownParams {
byte small_turn, large_turn;
byte z_up; // fraction to remove when moving up
byte z_down; // fraction to remove when moving down
};
static const RailtypeSlowdownParams _railtype_slowdown[] = {
/* normal accel */
{256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
{256 / 4, 256 / 2, 256 / 4, 2}, ///< electrified
{256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
{0, 256 / 2, 256 / 4, 2}, ///< maglev
};
/** Modify the speed of the vehicle due to a turn */
static inline void AffectSpeedByDirChange(Vehicle *v, Direction new_dir)
{
if (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL) return;
DirDiff diff = DirDifference(v->direction, new_dir);
if (diff == DIRDIFF_SAME) return;
const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->u.rail.railtype];
v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
}
/** Modify the speed of the vehicle due to a change in altitude */
static inline void AffectSpeedByZChange(Vehicle *v, byte old_z)
{
if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL) return;
const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->u.rail.railtype];
if (old_z < v->z_pos) {
v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
} else {
uint16 spd = v->cur_speed + rsp->z_down;
if (spd <= v->max_speed) v->cur_speed = spd;
}
}
static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
{
if (IsTileType(tile, MP_RAILWAY) &&
GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
Trackdir trackdir = FindFirstTrackdir(tracks);
if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
/* A PBS block with a non-PBS signal facing us? */
if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
}
}
return false;
}
static void SetVehicleCrashed(Vehicle *v)
{
if (v->u.rail.crash_anim_pos != 0) return;
/* Free a possible path reservation and try to mark all tiles occupied by the train reserved. */
if (IsFrontEngine(v)) {
/* Remove all reservations, also the ones currently under the train
* and any railway station paltform reservation. */
FreeTrainTrackReservation(v);
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
ClearPathReservation(u, u->tile, GetVehicleTrackdir(u));
if (IsTileType(u->tile, MP_TUNNELBRIDGE)) {
/* ClearPathReservation will not free the wormhole exit
* if the train has just entered the wormhole. */
SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(u->tile), false);
}
}
}
/* we may need to update crossing we were approaching */
TileIndex crossing = TrainApproachingCrossingTile(v);
v->u.rail.crash_anim_pos++;
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
if (v->u.rail.track == TRACK_BIT_DEPOT) {
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
}
InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
for (; v != NULL; v = v->Next()) {
v->vehstatus |= VS_CRASHED;
MarkSingleVehicleDirty(v);
}
/* must be updated after the train has been marked crashed */
if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
}
static uint CountPassengersInTrain(const Vehicle *v)
{
uint num = 0;
for (; v != NULL; v = v->Next()) {
if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) num += v->cargo.Count();
}
return num;
}
/**
* Marks train as crashed and creates an AI event.
* Doesn't do anything if the train is crashed already.
* @param v first vehicle of chain
* @return number of victims (including 2 drivers; zero if train was already crashed)
*/
static uint TrainCrashed(Vehicle *v)
{
/* do not crash train twice */
if (v->vehstatus & VS_CRASHED) return 0;
/* two drivers + passengers */
uint num = 2 + CountPassengersInTrain(v);
SetVehicleCrashed(v);
AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
return num;
}
struct TrainCollideChecker {
Vehicle *v; ///< vehicle we are testing for collision
uint num; ///< number of dead if train collided
};
static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
{
TrainCollideChecker *tcc = (TrainCollideChecker*)data;
if (v->type != VEH_TRAIN) return NULL;
/* get first vehicle now to make most usual checks faster */
Vehicle *coll = v->First();
/* can't collide with own wagons && can't crash in depot && the same height level */
if (coll != tcc->v && v->u.rail.track != TRACK_BIT_DEPOT && abs(v->z_pos - tcc->v->z_pos) < 6) {
int x_diff = v->x_pos - tcc->v->x_pos;
int y_diff = v->y_pos - tcc->v->y_pos;
/* needed to disable possible crash of competitor train in station by building diagonal track at its end */
if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
/* crash both trains */
tcc->num += TrainCrashed(tcc->v);
tcc->num += TrainCrashed(coll);
/* Try to reserve all tiles directly under the crashed trains.
* As there might be more than two trains involved, we have to do that for all vehicles */
const Vehicle *u;
FOR_ALL_VEHICLES(u) {
if (u->type == VEH_TRAIN && HASBITS(u->vehstatus, VS_CRASHED) && (u->u.rail.track & TRACK_BIT_DEPOT) == TRACK_BIT_NONE) {
TrackBits trackbits = u->u.rail.track;
if ((trackbits & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
/* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(u->tile));
}
TryReserveRailTrack(u->tile, TrackBitsToTrack(trackbits));
}
}
}
return NULL;
}
/**
* Checks whether the specified train has a collision with another vehicle. If
* so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
* Reports the incident in a flashy news item, modifies station ratings and
* plays a sound.
*/
static bool CheckTrainCollision(Vehicle *v)
{
/* can't collide in depot */
if (v->u.rail.track == TRACK_BIT_DEPOT) return false;
assert(v->u.rail.track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
TrainCollideChecker tcc;
tcc.v = v;
tcc.num = 0;
/* find colliding vehicles */
if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
} else {
FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
}
/* any dead -> no crash */
if (tcc.num == 0) return false;
SetDParam(0, tcc.num);
AddNewsItem(STR_8868_TRAIN_CRASH_DIE_IN_FIREBALL,
NS_ACCIDENT_VEHICLE,
v->index,
0
);
ModifyStationRatingAround(v->tile, v->owner, -160, 30);
SndPlayVehicleFx(SND_13_BIG_CRASH, v);
return true;
}
static Vehicle *CheckVehicleAtSignal(Vehicle *v, void *data)
{
DiagDirection exitdir = *(DiagDirection *)data;
/* front engine of a train, not inside wormhole or depot, not crashed */
if (v->type == VEH_TRAIN && IsFrontEngine(v) && (v->u.rail.track & TRACK_BIT_MASK) != 0 && !(v->vehstatus & VS_CRASHED)) {
if (v->cur_speed <= 5 && TrainExitDir(v->direction, v->u.rail.track) == exitdir) return v;
}
return NULL;
}
static void TrainController(Vehicle *v, Vehicle *nomove)
{
Vehicle *prev;
/* For every vehicle after and including the given vehicle */
for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
DiagDirection enterdir = DIAGDIR_BEGIN;
bool update_signals_crossing = false; // will we update signals or crossing state?
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
if (v->u.rail.track != TRACK_BIT_WORMHOLE) {
/* Not inside tunnel */
if (gp.old_tile == gp.new_tile) {
/* Staying in the old tile */
if (v->u.rail.track == TRACK_BIT_DEPOT) {
/* Inside depot */
gp.x = v->x_pos;
gp.y = v->y_pos;
} else {
/* Not inside depot */
/* Reverse when we are at the end of the track already, do not move to the new position */
if (IsFrontEngine(v) && !TrainCheckIfLineEnds(v)) return;
uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
if (HasBit(r, VETS_CANNOT_ENTER)) {
goto invalid_rail;
}
if (HasBit(r, VETS_ENTERED_STATION)) {
/* The new position is the end of the platform */
TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
}
}
} else {
/* A new tile is about to be entered. */
/* Determine what direction we're entering the new tile from */
Direction dir = GetNewVehicleDirectionByTile(gp.new_tile, gp.old_tile);
enterdir = DirToDiagDir(dir);
assert(IsValidDiagDirection(enterdir));
/* Get the status of the tracks in the new tile and mask
* away the bits that aren't reachable. */
TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg && prev == NULL) {
/* We allow wagons to make 90 deg turns, because forbid_90_deg
* can be switched on halfway a turn */
bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track));
}
if (bits == TRACK_BIT_NONE) goto invalid_rail;
/* Check if the new tile contrains tracks that are compatible
* with the current train, if not, bail out. */
if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
TrackBits chosen_track;
if (prev == NULL) {
/* Currently the locomotive is active. Determine which one of the
* available tracks to choose */
chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
/* Check if it's a red signal and that force proceed is not clicked. */
if (red_signals & chosen_track && v->u.rail.force_proceed == 0) {
/* In front of a red signal */
Trackdir i = FindFirstTrackdir(trackdirbits);
/* Don't handle stuck trains here. */
if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) return;
if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
v->cur_speed = 0;
v->subspeed = 0;
v->progress = 255 - 100;
if (_settings_game.pf.wait_oneway_signal == 255 || ++v->load_unload_time_rem < _settings_game.pf.wait_oneway_signal * 20) return;
} else if (HasSignalOnTrackdir(gp.new_tile, i)) {
v->cur_speed = 0;
v->subspeed = 0;
v->progress = 255 - 10;
if (_settings_game.pf.wait_twoway_signal == 255 || ++v->load_unload_time_rem < _settings_game.pf.wait_twoway_signal * 73) {
DiagDirection exitdir = TrackdirToExitdir(i);
TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
exitdir = ReverseDiagDir(exitdir);
/* check if a train is waiting on the other side */
if (!HasVehicleOnPos(o_tile, &exitdir, &CheckVehicleAtSignal)) return;
}
}
/* If we would reverse but are currently in a PBS block and
* reversing of stuck trains is disabled, don't reverse. */
if (_settings_game.pf.wait_for_pbs_path == 255 && UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
v->load_unload_time_rem = 0;
return;
}
goto reverse_train_direction;
} else {
TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
}
} else {
static const TrackBits _matching_tracks[8] = {
TRACK_BIT_LEFT | TRACK_BIT_RIGHT, TRACK_BIT_X,
TRACK_BIT_UPPER | TRACK_BIT_LOWER, TRACK_BIT_Y,
TRACK_BIT_LEFT | TRACK_BIT_RIGHT, TRACK_BIT_X,
TRACK_BIT_UPPER | TRACK_BIT_LOWER, TRACK_BIT_Y
};
/* The wagon is active, simply follow the prev vehicle. */
chosen_track = (TrackBits)(byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits);
}
/* Make sure chosen track is a valid track */
assert(
chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
/* Update XY to reflect the entrance to the new tile, and select the direction to use */
const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
gp.x = (gp.x & ~0xF) | b[0];
gp.y = (gp.y & ~0xF) | b[1];
Direction chosen_dir = (Direction)b[2];
/* Call the landscape function and tell it that the vehicle entered the tile */
uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
if (HasBit(r, VETS_CANNOT_ENTER)) {
goto invalid_rail;
}
if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
Track track = FindFirstTrack(chosen_track);
Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
if (IsFrontEngine(v) && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
MarkTileDirtyByTile(gp.new_tile);
}
/* Clear any track reservation when the last vehicle leaves the tile */
if (v->Next() == NULL) ClearPathReservation(v, v->tile, GetVehicleTrackdir(v));
v->tile = gp.new_tile;
if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
TrainPowerChanged(v->First());
}
v->u.rail.track = chosen_track;
assert(v->u.rail.track);
}
/* We need to update signal status, but after the vehicle position hash
* has been updated by AfterSetTrainPos() */
update_signals_crossing = true;
if (prev == NULL) AffectSpeedByDirChange(v, chosen_dir);
v->direction = chosen_dir;
if (IsFrontEngine(v)) {
v->load_unload_time_rem = 0;
/* If we are approching a crossing that is reserved, play the sound now. */
TileIndex crossing = TrainApproachingCrossingTile(v);
if (crossing != INVALID_TILE && GetCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
/* Always try to extend the reservation when entering a tile. */
CheckNextTrainTile(v);
}
}
} else {
/* In a tunnel or on a bridge
* - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
* - for bridges, only the middle part - without the bridge heads */
if (!(v->vehstatus & VS_HIDDEN)) {
v->cur_speed =
min(v->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
}
if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
/* Perform look-ahead on tunnel exit. */
if (IsFrontEngine(v)) {
TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
CheckNextTrainTile(v);
}
} else {
v->x_pos = gp.x;
v->y_pos = gp.y;
VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
continue;
}
}
/* update image of train, as well as delta XY */
v->UpdateDeltaXY(v->direction);
v->x_pos = gp.x;
v->y_pos = gp.y;
/* update the Z position of the vehicle */
byte old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile));
if (prev == NULL) {
/* This is the first vehicle in the train */
AffectSpeedByZChange(v, old_z);
}
if (update_signals_crossing) {
if (IsFrontEngine(v)) {
if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
/* We are entering a block with PBS signals right now, but
* not through a PBS signal. This means we don't have a
* reservation right now. As a conventional signal will only
* ever be green if no other train is in the block, getting
* a path should always be possible. If the player built
* such a strange network that it is not possible, the train
* will be marked as stuck and the player has to deal with
* the problem. */
if ((!HasReservedTracks(gp.new_tile, v->u.rail.track) &&
!TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->u.rail.track))) ||
!TryPathReserve(v)) {
MarkTrainAsStuck(v);
}
}
}
/* Signals can only change when the first
* (above) or the last vehicle moves. */
if (v->Next() == NULL) {
TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
}
}
/* Do not check on every tick to save some computing time. */
if (IsFrontEngine(v) && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
}
return;
invalid_rail:
/* We've reached end of line?? */
if (prev != NULL) error("Disconnecting train");
reverse_train_direction:
v->load_unload_time_rem = 0;
v->cur_speed = 0;
v->subspeed = 0;
ReverseTrainDirection(v);
}
/** Collect trackbits of all crashed train vehicles on a tile
* @param v Vehicle passed from Find/HasVehicleOnPos()
* @param data trackdirbits for the result
* @return NULL to iterate over all vehicles on the tile.
*/
static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
{
TrackBits *trackbits = (TrackBits *)data;
if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
if ((v->u.rail.track & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
/* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
*trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
} else {
*trackbits |= v->u.rail.track;
}
}
return NULL;
}
/**
* Deletes/Clears the last wagon of a crashed train. It takes the engine of the
* train, then goes to the last wagon and deletes that. Each call to this function
* will remove the last wagon of a crashed train. If this wagon was on a crossing,
* or inside a tunnel/bridge, recalculate the signals as they might need updating
* @param v the Vehicle of which last wagon is to be removed
*/
static void DeleteLastWagon(Vehicle *v)
{
Vehicle *first = v->First();
/* Go to the last wagon and delete the link pointing there
* *u is then the one-before-last wagon, and *v the last
* one which will physicially be removed */
Vehicle *u = v;
for (; v->Next() != NULL; v = v->Next()) u = v;
u->SetNext(NULL);
if (first != v) {
/* Recalculate cached train properties */
TrainConsistChanged(first, false);
/* Update the depot window if the first vehicle is in depot -
* if v == first, then it is updated in PreDestructor() */
if (first->u.rail.track == TRACK_BIT_DEPOT) {
InvalidateWindow(WC_VEHICLE_DEPOT, first->tile);
}
}
/* 'v' shouldn't be accessed after it has been deleted */
TrackBits trackbits = v->u.rail.track;
TileIndex tile = v->tile;
Owner owner = v->owner;
delete v;
v = NULL; // make sure nobody will try to read 'v' anymore
if ((trackbits & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
/* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
}
Track track = TrackBitsToTrack(trackbits);
if (HasReservedTracks(tile, trackbits)) {
UnreserveRailTrack(tile, track);
/* If there are still crashed vehicles on the tile, give the track reservation to them */
TrackBits remaining_trackbits = TRACK_BIT_NONE;
FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
/* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
for (Track t = TRACK_BEGIN; t < TRACK_END; t++) {
if (HasBit(remaining_trackbits, t)) {
TryReserveRailTrack(tile, t);
}
}
}
/* check if the wagon was on a road/rail-crossing */
if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
/* Update signals */
if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
} else {
SetSignalsOnBothDir(tile, track, owner);
}
}
static void ChangeTrainDirRandomly(Vehicle *v)
{
static const DirDiff delta[] = {
DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
};
do {
/* We don't need to twist around vehicles if they're not visible */
if (!(v->vehstatus & VS_HIDDEN)) {
v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
v->UpdateDeltaXY(v->direction);
v->cur_image = v->GetImage(v->direction);
/* Refrain from updating the z position of the vehicle when on
* a bridge, because AfterSetTrainPos will put the vehicle under
* the bridge in that case */
if (v->u.rail.track != TRACK_BIT_WORMHOLE) AfterSetTrainPos(v, false);
}
} while ((v = v->Next()) != NULL);
}
static void HandleCrashedTrain(Vehicle *v)
{
int state = ++v->u.rail.crash_anim_pos;
if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
}
uint32 r;
if (state <= 200 && Chance16R(1, 7, r)) {
int index = (r * 10 >> 16);
Vehicle *u = v;
do {
if (--index < 0) {
r = Random();
CreateEffectVehicleRel(u,
GB(r, 8, 3) + 2,
GB(r, 16, 3) + 2,
GB(r, 0, 3) + 5,
EV_EXPLOSION_SMALL);
break;
}
} while ((u = u->Next()) != NULL);
}
if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
if (state >= 4440 && !(v->tick_counter & 0x1F)) {
DeleteLastWagon(v);
InvalidateWindow(WC_REPLACE_VEHICLE, (v->group_id << 16) | VEH_TRAIN);
}
}
static void HandleBrokenTrain(Vehicle *v)
{
if (v->breakdown_ctr != 1) {
v->breakdown_ctr = 1;
v->cur_speed = 0;
if (v->breakdowns_since_last_service != 255)
v->breakdowns_since_last_service++;
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
}
if (!(v->vehstatus & VS_HIDDEN)) {
Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
if (u != NULL) u->u.effect.animation_state = v->breakdown_delay * 2;
}
}
if (!(v->tick_counter & 3)) {
if (!--v->breakdown_delay) {
v->breakdown_ctr = 0;
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
}
}
}
/** Maximum speeds for train that is broken down or approaching line end */
static const uint16 _breakdown_speeds[16] = {
225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
};
/**
* Train is approaching line end, slow down and possibly reverse
*
* @param v front train engine
* @param signal not line end, just a red signal
* @return true iff we did NOT have to reverse
*/
static bool TrainApproachingLineEnd(Vehicle *v, bool signal)
{
/* Calc position within the current tile */
uint x = v->x_pos & 0xF;
uint y = v->y_pos & 0xF;
/* for diagonal directions, 'x' will be 0..15 -
* for other directions, it will be 1, 3, 5, ..., 15 */
switch (v->direction) {
case DIR_N : x = ~x + ~y + 25; break;
case DIR_NW: x = y; // FALLTHROUGH
case DIR_NE: x = ~x + 16; break;
case DIR_E : x = ~x + y + 9; break;
case DIR_SE: x = y; break;
case DIR_S : x = x + y - 7; break;
case DIR_W : x = ~y + x + 9; break;
default: break;
}
/* do not reverse when approaching red signal */
if (!signal && x + (v->u.rail.cached_veh_length + 1) / 2 >= TILE_SIZE) {
/* we are too near the tile end, reverse now */
v->cur_speed = 0;
ReverseTrainDirection(v);
return false;
}
/* slow down */
v->vehstatus |= VS_TRAIN_SLOWING;
uint16 break_speed = _breakdown_speeds[x & 0xF];
if (break_speed < v->cur_speed) v->cur_speed = break_speed;
return true;
}
/**
* Determines whether train would like to leave the tile
* @param v train to test
* @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
*/
static bool TrainCanLeaveTile(const Vehicle *v)
{
/* Exit if inside a tunnel/bridge or a depot */
if (v->u.rail.track == TRACK_BIT_WORMHOLE || v->u.rail.track == TRACK_BIT_DEPOT) return false;
TileIndex tile = v->tile;
/* entering a tunnel/bridge? */
if (IsTileType(tile, MP_TUNNELBRIDGE)) {
DiagDirection dir = GetTunnelBridgeDirection(tile);
if (DiagDirToDir(dir) == v->direction) return false;
}
/* entering a depot? */
if (IsRailDepotTile(tile)) {
DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
if (DiagDirToDir(dir) == v->direction) return false;
}
return true;
}
/**
* Determines whether train is approaching a rail-road crossing
* (thus making it barred)
* @param v front engine of train
* @return TileIndex of crossing the train is approaching, else INVALID_TILE
* @pre v in non-crashed front engine
*/
static TileIndex TrainApproachingCrossingTile(const Vehicle *v)
{
assert(IsFrontEngine(v));
assert(!(v->vehstatus & VS_CRASHED));
if (!TrainCanLeaveTile(v)) return INVALID_TILE;
DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
TileIndex tile = v->tile + TileOffsByDiagDir(dir);
/* not a crossing || wrong axis || unusable rail (wrong type or owner) */
if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
!CheckCompatibleRail(v, tile)) {
return INVALID_TILE;
}
return tile;
}
/**
* Checks for line end. Also, bars crossing at next tile if needed
*
* @param v vehicle we are checking
* @return true iff we did NOT have to reverse
*/
static bool TrainCheckIfLineEnds(Vehicle *v)
{
/* First, handle broken down train */
int t = v->breakdown_ctr;
if (t > 1) {
v->vehstatus |= VS_TRAIN_SLOWING;
uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
if (break_speed < v->cur_speed) v->cur_speed = break_speed;
} else {
v->vehstatus &= ~VS_TRAIN_SLOWING;
}
if (!TrainCanLeaveTile(v)) return true;
/* Determine the non-diagonal direction in which we will exit this tile */
DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
/* Calculate next tile */
TileIndex tile = v->tile + TileOffsByDiagDir(dir);
/* Determine the track status on the next tile */
TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
/* We are sure the train is not entering a depot, it is detected above */
/* mask unreachable track bits if we are forbidden to do 90deg turns */
TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track));
}
/* no suitable trackbits at all || unusable rail (wrong type or owner) */
if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
return TrainApproachingLineEnd(v, false);
}
/* approaching red signal */
if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true);
/* approaching a rail/road crossing? then make it red */
if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
return true;
}
static void TrainLocoHandler(Vehicle *v, bool mode)
{
/* train has crashed? */
if (v->vehstatus & VS_CRASHED) {
if (!mode) HandleCrashedTrain(v);
return;
}
if (v->u.rail.force_proceed != 0) {
v->u.rail.force_proceed--;
ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
/* train is broken down? */
if (v->breakdown_ctr != 0) {
if (v->breakdown_ctr <= 2) {
HandleBrokenTrain(v);
return;
}
if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
}
if (HasBit(v->u.rail.flags, VRF_REVERSING) && v->cur_speed == 0) {
ReverseTrainDirection(v);
}
/* exit if train is stopped */
if (v->vehstatus & VS_STOPPED && v->cur_speed == 0) return;
bool valid_order = v->current_order.IsValid() && v->current_order.GetType() != OT_CONDITIONAL;
if (ProcessOrders(v) && CheckReverseTrain(v)) {
v->load_unload_time_rem = 0;
v->cur_speed = 0;
v->subspeed = 0;
ReverseTrainDirection(v);
return;
}
v->HandleLoading(mode);
if (v->current_order.IsType(OT_LOADING)) return;
if (CheckTrainStayInDepot(v)) return;
if (!mode) HandleLocomotiveSmokeCloud(v);
/* We had no order but have an order now, do look ahead. */
if (!valid_order && v->current_order.IsValid()) {
CheckNextTrainTile(v);
}
/* Handle stuck trains. */
if (!mode && HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
++v->load_unload_time_rem;
/* Should we try reversing this tick if still stuck? */
bool turn_around = v->load_unload_time_rem % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.wait_for_pbs_path < 255;
if (!turn_around && v->load_unload_time_rem % _settings_game.pf.path_backoff_interval != 0 && v->u.rail.force_proceed == 0) return;
if (!TryPathReserve(v)) {
/* Still stuck. */
if (turn_around) ReverseTrainDirection(v);
if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK) && v->load_unload_time_rem > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
/* Show message to player. */
if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
SetDParam(0, v->index);
AddNewsItem(
STR_TRAIN_IS_STUCK,
NS_ADVICE,
v->index,
0);
}
v->load_unload_time_rem = 0;
}
/* Exit if force proceed not pressed, else reset stuck flag anyway. */
if (v->u.rail.force_proceed == 0) return;
ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
v->load_unload_time_rem = 0;
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
}
if (v->current_order.IsType(OT_LEAVESTATION)) {
v->current_order.Free();
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
return;
}
int j = UpdateTrainSpeed(v);
/* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
if (v->cur_speed == 0 && v->u.rail.last_speed == 0 && v->vehstatus & VS_STOPPED) {
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
int adv_spd = (v->direction & 1) ? 192 : 256;
if (j < adv_spd) {
/* if the vehicle has speed 0, update the last_speed field. */
if (v->cur_speed == 0) SetLastSpeed(v, v->cur_speed);
} else {
TrainCheckIfLineEnds(v);
/* Loop until the train has finished moving. */
do {
j -= adv_spd;
TrainController(v, NULL);
/* Don't continue to move if the train crashed. */
if (CheckTrainCollision(v)) break;
/* 192 spd used for going straight, 256 for going diagonally. */
adv_spd = (v->direction & 1) ? 192 : 256;
} while (j >= adv_spd);
SetLastSpeed(v, v->cur_speed);
}
for (Vehicle *u = v; u != NULL; u = u->Next()) {
if ((u->vehstatus & VS_HIDDEN) != 0) continue;
uint16 old_image = u->cur_image;
u->cur_image = u->GetImage(u->direction);
if (old_image != u->cur_image) VehicleMove(u, true);
}
if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
}
Money Train::GetRunningCost() const
{
Money cost = 0;
const Vehicle *v = this;
do {
const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
byte cost_factor = GetVehicleProperty(v, 0x0D, rvi->running_cost);
if (cost_factor == 0) continue;
/* Halve running cost for multiheaded parts */
if (IsMultiheaded(v)) cost_factor /= 2;
cost += cost_factor * GetPriceByIndex(rvi->running_cost_class);
} while ((v = GetNextVehicle(v)) != NULL);
return cost;
}
void Train::Tick()
{
if (_age_cargo_skip_counter == 0) this->cargo.AgeCargo();
this->tick_counter++;
if (IsFrontEngine(this)) {
if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
this->current_order_time++;
TrainLocoHandler(this, false);
/* make sure vehicle wasn't deleted. */
if (this->type == VEH_TRAIN && IsFrontEngine(this))
TrainLocoHandler(this, true);
} else if (IsFreeWagon(this) && HASBITS(this->vehstatus, VS_CRASHED)) {
/* Delete flooded standalone wagon chain */
if (++this->u.rail.crash_anim_pos >= 4400) delete this;
}
}
static void CheckIfTrainNeedsService(Vehicle *v)
{
static const uint MAX_ACCEPTABLE_DEPOT_DIST = 16;
if (_settings_game.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
if (v->IsInDepot()) {
VehicleServiceInDepot(v);
return;
}
TrainFindDepotData tfdd = FindClosestTrainDepot(v, MAX_ACCEPTABLE_DEPOT_DIST);
/* Only go to the depot if it is not too far out of our way. */
if (tfdd.best_length == UINT_MAX || tfdd.best_length > MAX_ACCEPTABLE_DEPOT_DIST) {
if (v->current_order.IsType(OT_GOTO_DEPOT)) {
/* If we were already heading for a depot but it has
* suddenly moved farther away, we continue our normal
* schedule? */
v->current_order.MakeDummy();
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
return;
}
const Depot *depot = GetDepotByTile(tfdd.tile);
if (v->current_order.IsType(OT_GOTO_DEPOT) &&
v->current_order.GetDestination() != depot->index &&
!Chance16(3, 16)) {
return;
}
v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
v->dest_tile = tfdd.tile;
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
void Train::OnNewDay()
{
if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
if (IsFrontEngine(this)) {
CheckVehicleBreakdown(this);
AgeVehicle(this);
CheckIfTrainNeedsService(this);
CheckOrders(this);
/* update destination */
if (this->current_order.IsType(OT_GOTO_STATION)) {
TileIndex tile = GetStation(this->current_order.GetDestination())->train_tile;
if (tile != INVALID_TILE) this->dest_tile = tile;
}
if (this->running_ticks != 0) {
/* running costs */
CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
this->profit_this_year -= cost.GetCost();
this->running_ticks = 0;
SubtractMoneyFromCompanyFract(this->owner, cost);
InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
InvalidateWindowClasses(WC_TRAINS_LIST);
}
} else if (IsTrainEngine(this)) {
/* Also age engines that aren't front engines */
AgeVehicle(this);
}
}
void InitializeTrains()
{
_age_cargo_skip_counter = 1;
}
| 148,809
|
C++
|
.cpp
| 3,687
| 37.070789
| 204
| 0.689649
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,092
|
misc_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/misc_gui.cpp
|
/* $Id$ */
/** @file misc_gui.cpp GUIs for a number of misc windows. */
#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "landscape.h"
#include "newgrf_text.h"
#include "saveload/saveload.h"
#include "tile_map.h"
#include "gui.h"
#include "station_gui.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "station_func.h"
#include "command_func.h"
#include "company_func.h"
#include "town.h"
#include "network/network.h"
#include "network/network_content.h"
#include "variables.h"
#include "company_base.h"
#include "texteff.hpp"
#include "cargotype.h"
#include "company_manager_face.h"
#include "strings_func.h"
#include "fileio_func.h"
#include "fios.h"
#include "zoom_func.h"
#include "window_func.h"
#include "string_func.h"
#include "newgrf_cargo.h"
#include "tilehighlight_func.h"
#include "querystring_gui.h"
#include "table/strings.h"
/* Variables to display file lists */
SaveLoadDialogMode _saveload_mode;
static bool _fios_path_changed;
static bool _savegame_sort_dirty;
int _caret_timer;
static const Widget _land_info_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 299, 0, 13, STR_01A3_LAND_AREA_INFORMATION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_BOTTOM, COLOUR_GREY, 0, 299, 14, 99, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _land_info_desc(
WDP_AUTO, WDP_AUTO, 300, 100, 300, 100,
WC_LAND_INFO, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_land_info_widgets
);
class LandInfoWindow : public Window {
enum {
LAND_INFO_CENTERED_LINES = 12, ///< Up to 12 centered lines
LAND_INFO_MULTICENTER_LINE = LAND_INFO_CENTERED_LINES, ///< One multicenter line
LAND_INFO_LINE_END,
LAND_INFO_LINE_BUFF_SIZE = 512,
};
public:
char landinfo_data[LAND_INFO_LINE_END][LAND_INFO_LINE_BUFF_SIZE];
virtual void OnPaint()
{
this->DrawWidgets();
uint y = 21;
for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
if (StrEmpty(this->landinfo_data[i])) break;
DoDrawStringCentered(150, y, this->landinfo_data[i], i == 0 ? TC_LIGHT_BLUE : TC_FROMSTRING);
y += i == 0 ? 16 : 12;
}
y += 6;
if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
DrawStringMultiCenter(150, y, STR_JUST_RAW_STRING, this->width - 4);
}
}
LandInfoWindow(TileIndex tile) : Window(&_land_info_desc) {
Company *c = GetCompany(IsValidCompanyID(_local_company) ? _local_company : COMPANY_FIRST);
Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
Money old_money = c->money;
c->money = INT64_MAX;
CommandCost costclear = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
c->money = old_money;
/* Because build_date is not set yet in every TileDesc, we make sure it is empty */
TileDesc td;
AcceptedCargo ac;
td.build_date = INVALID_DATE;
/* Most tiles have only one owner, but
* - drivethrough roadstops can be build on town owned roads (up to 2 owners) and
* - roads can have up to four owners (railroad, road, tram, 3rd-roadtype "highway").
*/
td.owner_type[0] = STR_01A7_OWNER; // At least one owner is displayed, though it might be "N/A".
td.owner_type[1] = STR_NULL; // STR_NULL results in skipping the owner
td.owner_type[2] = STR_NULL;
td.owner_type[3] = STR_NULL;
td.owner[0] = OWNER_NONE;
td.owner[1] = OWNER_NONE;
td.owner[2] = OWNER_NONE;
td.owner[3] = OWNER_NONE;
td.station_class = STR_NULL;
td.station_name = STR_NULL;
td.grf = NULL;
GetAcceptedCargo(tile, ac);
GetTileDesc(tile, &td);
uint line_nr = 0;
/* Tiletype */
SetDParam(0, td.dparam[0]);
GetString(this->landinfo_data[line_nr], td.str, lastof(this->landinfo_data[line_nr]));
line_nr++;
/* Up to four owners */
for (uint i = 0; i < 4; i++) {
if (td.owner_type[i] == STR_NULL) continue;
SetDParam(0, STR_01A6_N_A);
if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) GetNameOfOwner(td.owner[i], tile);
GetString(this->landinfo_data[line_nr], td.owner_type[i], lastof(this->landinfo_data[line_nr]));
line_nr++;
}
/* Cost to clear/revenue when cleared */
StringID str = STR_01A4_COST_TO_CLEAR_N_A;
if (CmdSucceeded(costclear)) {
Money cost = costclear.GetCost();
if (cost < 0) {
cost = -cost; // Negate negative cost to a positive revenue
str = STR_REVENUE_WHEN_CLEARED;
} else {
str = STR_01A5_COST_TO_CLEAR;
}
SetDParam(0, cost);
}
GetString(this->landinfo_data[line_nr], str, lastof(this->landinfo_data[line_nr]));
line_nr++;
/* Location */
char tmp[16];
snprintf(tmp, lengthof(tmp), "0x%.4X", tile);
SetDParam(0, TileX(tile));
SetDParam(1, TileY(tile));
SetDParam(2, TileHeight(tile));
SetDParamStr(3, tmp);
GetString(this->landinfo_data[line_nr], STR_LANDINFO_COORDS, lastof(this->landinfo_data[line_nr]));
line_nr++;
/* Local authority */
SetDParam(0, STR_01A9_NONE);
if (t != NULL && t->IsValid()) {
SetDParam(0, STR_TOWN);
SetDParam(1, t->index);
}
GetString(this->landinfo_data[line_nr], STR_01A8_LOCAL_AUTHORITY, lastof(this->landinfo_data[line_nr]));
line_nr++;
/* Build date */
if (td.build_date != INVALID_DATE) {
SetDParam(0, td.build_date);
GetString(this->landinfo_data[line_nr], STR_BUILD_DATE, lastof(this->landinfo_data[line_nr]));
line_nr++;
}
/* Station class */
if (td.station_class != STR_NULL) {
SetDParam(0, td.station_class);
GetString(this->landinfo_data[line_nr], STR_TILEDESC_STATION_CLASS, lastof(this->landinfo_data[line_nr]));
line_nr++;
}
/* Station type name */
if (td.station_name != STR_NULL) {
SetDParam(0, td.station_name);
GetString(this->landinfo_data[line_nr], STR_TILEDESC_STATION_TYPE, lastof(this->landinfo_data[line_nr]));
line_nr++;
}
/* NewGRF name */
if (td.grf != NULL) {
SetDParamStr(0, td.grf);
GetString(this->landinfo_data[line_nr], STR_TILEDESC_NEWGRF_NAME, lastof(this->landinfo_data[line_nr]));
line_nr++;
}
assert(line_nr < LAND_INFO_CENTERED_LINES);
/* Mark last line empty */
this->landinfo_data[line_nr][0] = '\0';
/* Cargo acceptance is displayed in a extra multiline */
char *strp = GetString(this->landinfo_data[LAND_INFO_MULTICENTER_LINE], STR_01CE_CARGO_ACCEPTED, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
bool found = false;
for (CargoID i = 0; i < NUM_CARGO; ++i) {
if (ac[i] > 0) {
/* Add a comma between each item. */
if (found) {
*strp++ = ',';
*strp++ = ' ';
}
found = true;
/* If the accepted value is less than 8, show it in 1/8:ths */
if (ac[i] < 8) {
SetDParam(0, ac[i]);
SetDParam(1, GetCargo(i)->name);
strp = GetString(strp, STR_01D1_8, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
} else {
strp = GetString(strp, GetCargo(i)->name, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
}
}
}
if (!found) this->landinfo_data[LAND_INFO_MULTICENTER_LINE][0] = '\0';
if (found) line_nr += 2;
if (line_nr > 6) ResizeWindow(this, 0, 12 * (line_nr - 6));
this->FindWindowPlacementAndResize(&_land_info_desc);
#if defined(_DEBUG)
# define LANDINFOD_LEVEL 0
#else
# define LANDINFOD_LEVEL 1
#endif
DEBUG(misc, LANDINFOD_LEVEL, "TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
DEBUG(misc, LANDINFOD_LEVEL, "type_height = %#x", _m[tile].type_height);
DEBUG(misc, LANDINFOD_LEVEL, "m1 = %#x", _m[tile].m1);
DEBUG(misc, LANDINFOD_LEVEL, "m2 = %#x", _m[tile].m2);
DEBUG(misc, LANDINFOD_LEVEL, "m3 = %#x", _m[tile].m3);
DEBUG(misc, LANDINFOD_LEVEL, "m4 = %#x", _m[tile].m4);
DEBUG(misc, LANDINFOD_LEVEL, "m5 = %#x", _m[tile].m5);
DEBUG(misc, LANDINFOD_LEVEL, "m6 = %#x", _m[tile].m6);
DEBUG(misc, LANDINFOD_LEVEL, "m7 = %#x", _me[tile].m7);
#undef LANDINFOD_LEVEL
}
};
static void Place_LandInfo(TileIndex tile)
{
DeleteWindowById(WC_LAND_INFO, 0);
new LandInfoWindow(tile);
}
void PlaceLandBlockInfo()
{
if (_cursor.sprite == SPR_CURSOR_QUERY) {
ResetObjectToPlace();
} else {
_place_proc = Place_LandInfo;
SetObjectToPlace(SPR_CURSOR_QUERY, PAL_NONE, VHM_RECT, WC_MAIN_TOOLBAR, 0);
}
}
static const Widget _about_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 419, 0, 13, STR_015B_OPENTTD, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 419, 14, 271, 0x0, STR_NULL},
{ WWT_FRAME, RESIZE_NONE, COLOUR_GREY, 5, 414, 40, 245, STR_NULL, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _about_desc(
WDP_CENTER, WDP_CENTER, 420, 272, 420, 272,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_about_widgets
);
struct AboutWindow : public Window {
int scroll_height;
uint16 counter;
AboutWindow() : Window(&_about_desc)
{
this->counter = 5;
this->scroll_height = this->height - 40;
this->FindWindowPlacementAndResize(&_about_desc);
}
virtual void OnPaint()
{
static const char *credits[] = {
/*************************************************************************
* maximum length of string which fits in window -^*/
"Original design by Chris Sawyer",
"Original graphics by Simon Foster",
"",
"The OpenTTD team (in alphabetical order):",
" Jean-Francois Claeys (Belugas) - GUI, newindustries and more",
" Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles",
" Matthijs Kooijman (blathijs) - Pathfinder-guru, pool rework",
" Victor Fischer (Celestar) - Programming everywhere you need him to",
" Christoph Elsenhans (frosch) - General coding",
" Lo\xC3\xAF""c Guilloux (glx) - Windows Expert",
" Michael Lutz (michi_cc) - Path based signals",
" Owen Rudge (orudge) - Forum host, OS/2 port",
" Peter Nelson (peter1138) - Spiritual descendant from newGRF gods",
" Remko Bijker (Rubidium) - Lead coder and way more",
" Zdenek Sojka (SmatZ) - Bug finder and fixer",
" Thijs Marinussen (Yexo) - AI Framework",
"",
"Inactive Developers:",
" Tam\xC3\xA1s Farag\xC3\xB3 (Darkvater) - Ex-Lead coder",
" Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;)",
" Jonathan Coome (Maedhros) - High priest of the NewGRF Temple",
" Attila B\xC3\xA1n (MiHaMiX) - WebTranslator, Nightlies, Wiki and bugtracker host",
" Christoph Mallon (Tron) - Programmer, code correctness police",
"",
"Retired Developers:",
" Ludvig Strigeus (ludde) - OpenTTD author, main coder (0.1 - 0.3.3)",
" Serge Paquet (vurlix) - Assistant project manager, coder (0.1 - 0.3.3)",
" Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3.0 - 0.3.6)",
" Benedikt Brüggemeier (skidd13) - Bug fixer and code reworker",
" Patric Stout (TrueLight) - Programmer, webhoster (0.3 - pre0.7)",
"",
"Special thanks go out to:",
" Josef Drexler - For his great work on TTDPatch",
" Marcin Grzegorczyk - For his documentation of TTD internals",
" Petr Baudis (pasky) - Many patches, newGRF support",
" Stefan Meißner (sign_de) - For his work on the console",
" Simon Sasburg (HackyKid) - Many bugfixes he has blessed us with",
" Cian Duffy (MYOB) - BeOS port / manual writing",
" Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
" Richard Kempton (richK) - additional airports, initial TGP implementation",
"",
" Alberto Demichelis - Squirrel scripting language © 2003-2008",
" Michael Blunck - Pre-Signals and Semaphores © 2003",
" George - Canal/Lock graphics © 2003-2004",
" David Dallaston - Tram tracks",
" Marcin Grzegorczyk - Foundations for Tracks on Slopes",
" All Translators - Who made OpenTTD a truly international game",
" Bug Reporters - Without whom OpenTTD would still be full of bugs!",
"",
"",
"And last but not least:",
" Chris Sawyer - For an amazing game!"
};
this->DrawWidgets();
/* Show original copyright and revision version */
DrawStringCentered(210, 17, STR_00B6_ORIGINAL_COPYRIGHT, TC_FROMSTRING);
DrawStringCentered(210, 17 + 10, STR_00B7_VERSION, TC_FROMSTRING);
int y = this->scroll_height;
/* Show all scrolling credits */
for (uint i = 0; i < lengthof(credits); i++) {
if (y >= 50 && y < (this->height - 40)) {
DoDrawString(credits[i], 10, y, TC_BLACK);
}
y += 10;
}
/* If the last text has scrolled start a new from the start */
if (y < 50) this->scroll_height = this->height - 40;
DoDrawStringCentered(210, this->height - 25, "Website: http://www.openttd.org", TC_BLACK);
DrawStringCentered(210, this->height - 15, STR_00BA_COPYRIGHT_OPENTTD, TC_FROMSTRING);
}
virtual void OnTick()
{
if (--this->counter == 0) {
this->counter = 5;
this->scroll_height--;
this->SetDirty();
}
}
};
void ShowAboutWindow()
{
DeleteWindowById(WC_GAME_OPTIONS, 0);
new AboutWindow();
}
static const Widget _errmsg_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_RED, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_RED, 11, 239, 0, 13, STR_00B2_MESSAGE, STR_NULL},
{ WWT_PANEL, RESIZE_BOTTOM, COLOUR_RED, 0, 239, 14, 45, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const Widget _errmsg_face_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_RED, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_RED, 11, 333, 0, 13, STR_00B3_MESSAGE_FROM, STR_NULL},
{ WWT_PANEL, RESIZE_BOTTOM, COLOUR_RED, 0, 333, 14, 136, 0x0, STR_NULL},
{ WIDGETS_END},
};
struct ErrmsgWindow : public Window {
private:
uint duration;
uint64 decode_params[20];
StringID message_1;
StringID message_2;
bool show_company_manager_face;
int y[2];
public:
ErrmsgWindow(Point pt, int width, int height, StringID msg1, StringID msg2, const Widget *widget, bool show_company_manager_face) :
Window(pt.x, pt.y, width, height, WC_ERRMSG, widget),
show_company_manager_face(show_company_manager_face)
{
this->duration = _settings_client.gui.errmsg_duration;
CopyOutDParam(this->decode_params, 0, lengthof(this->decode_params));
this->message_1 = msg1;
this->message_2 = msg2;
this->desc_flags = WDF_STD_BTN | WDF_DEF_WIDGET;
SwitchToErrorRefStack();
RewindTextRefStack();
assert(msg2 != INVALID_STRING_ID);
int h2 = 3 + GetStringHeight(msg2, width - 2); // msg2 is printed first
int h1 = (msg1 == INVALID_STRING_ID) ? 0 : 3 + GetStringHeight(msg1, width - 2);
SwitchToNormalRefStack();
int h = 15 + h1 + h2;
height = max<int>(height, h);
if (msg1 == INVALID_STRING_ID) {
/* only 1 line will be printed */
y[1] = (height - 15) / 2 + 15 - 5;
} else {
int over = (height - h) / 4;
y[1] = 15 + h2 / 2 + 1 - 5 + over;
y[0] = height - 3 - h1 / 2 - 5 - over;
}
this->FindWindowPlacementAndResize(width, height);
}
virtual void OnPaint()
{
CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
this->DrawWidgets();
CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
/* If the error message comes from a NewGRF, we must use the text ref. stack reserved for error messages.
* If the message doesn't come from a NewGRF, it won't use the TTDP-style text ref. stack, so we won't hurt anything
*/
SwitchToErrorRefStack();
RewindTextRefStack();
if (this->show_company_manager_face) {
const Company *c = GetCompany((CompanyID)GetDParamX(this->decode_params, 2));
DrawCompanyManagerFace(c->face, c->colour, 2, 16);
}
DrawStringMultiCenter(this->width - 120, y[1], this->message_2, this->width - 2);
if (this->message_1 != INVALID_STRING_ID) DrawStringMultiCenter(this->width - 120, y[0], this->message_1, this->width - 2);
/* Switch back to the normal text ref. stack for NewGRF texts */
SwitchToNormalRefStack();
}
virtual void OnMouseLoop()
{
if (_right_button_down) delete this;
}
virtual void OnHundredthTick()
{
if (--this->duration == 0) delete this;
}
~ErrmsgWindow()
{
SetRedErrorSquare(INVALID_TILE);
extern StringID _switch_mode_errorstr;
_switch_mode_errorstr = INVALID_STRING_ID;
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
if (keycode != WKC_SPACE) return ES_NOT_HANDLED;
delete this;
return ES_HANDLED;
}
};
void ShowErrorMessage(StringID msg_1, StringID msg_2, int x, int y)
{
DeleteWindowById(WC_ERRMSG, 0);
if (!_settings_client.gui.errmsg_duration) return;
if (msg_2 == STR_NULL) msg_2 = STR_EMPTY;
Point pt;
const ViewPort *vp;
if (msg_1 != STR_013B_OWNED_BY || GetDParam(2) >= 8) {
if ((x | y) != 0) {
pt = RemapCoords2(x, y);
vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
/* move x pos to opposite corner */
pt.x = UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left;
pt.x = (pt.x < (_screen.width >> 1)) ? _screen.width - 260 : 20;
/* move y pos to opposite corner */
pt.y = UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top;
pt.y = (pt.y < (_screen.height >> 1)) ? _screen.height - 80 : 100;
} else {
pt.x = (_screen.width - 240) >> 1;
pt.y = (_screen.height - 46) >> 1;
}
new ErrmsgWindow(pt, 240, 46, msg_1, msg_2, _errmsg_widgets, false);
} else {
if ((x | y) != 0) {
pt = RemapCoords2(x, y);
vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
pt.x = Clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (334 / 2), 0, _screen.width - 334);
pt.y = Clamp(UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top - (137 / 2), 22, _screen.height - 137);
} else {
pt.x = (_screen.width - 334) >> 1;
pt.y = (_screen.height - 137) >> 1;
}
new ErrmsgWindow(pt, 334, 137, msg_1, msg_2, _errmsg_face_widgets, true);
}
}
void ShowEstimatedCostOrIncome(Money cost, int x, int y)
{
StringID msg = STR_0805_ESTIMATED_COST;
if (cost < 0) {
cost = -cost;
msg = STR_0807_ESTIMATED_INCOME;
}
SetDParam(0, cost);
ShowErrorMessage(INVALID_STRING_ID, msg, x, y);
}
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
{
Point pt = RemapCoords(x, y, z);
StringID msg = STR_0801_COST;
if (cost < 0) {
cost = -cost;
msg = STR_0803_INCOME;
}
SetDParam(0, cost);
AddTextEffect(msg, pt.x, pt.y, 0x250, TE_RISING);
}
void ShowFeederIncomeAnimation(int x, int y, int z, Money cost)
{
Point pt = RemapCoords(x, y, z);
SetDParam(0, cost);
AddTextEffect(STR_FEEDER, pt.x, pt.y, 0x250, TE_RISING);
}
TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
{
Point pt = RemapCoords(x, y, z);
assert(string != STR_NULL);
SetDParam(0, percent);
return AddTextEffect(string, pt.x, pt.y, 0xFFFF, TE_STATIC);
}
void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
{
assert(string != STR_NULL);
SetDParam(0, percent);
UpdateTextEffect(te_id, string);
}
void HideFillingPercent(TextEffectID *te_id)
{
if (*te_id == INVALID_TE_ID) return;
RemoveTextEffect(*te_id);
*te_id = INVALID_TE_ID;
}
static const Widget _tooltips_widgets[] = {
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 199, 0, 31, 0x0, STR_NULL},
{ WIDGETS_END},
};
struct TooltipsWindow : public Window
{
StringID string_id;
byte paramcount;
uint64 params[5];
bool use_left_mouse_button;
TooltipsWindow(int x, int y, int width, int height, const Widget *widget,
StringID str, uint paramcount, const uint64 params[], bool use_left_mouse_button) :
Window(x, y, width, height, WC_TOOLTIPS, widget)
{
this->string_id = str;
assert(sizeof(this->params[0]) == sizeof(params[0]));
assert(paramcount <= lengthof(this->params));
memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
this->paramcount = paramcount;
this->use_left_mouse_button = use_left_mouse_button;
this->flags4 &= ~WF_WHITE_BORDER_MASK; // remove white-border from tooltip
this->widget[0].right = width;
this->widget[0].bottom = height;
FindWindowPlacementAndResize(width, height);
}
virtual void OnPaint()
{
GfxFillRect(0, 0, this->width - 1, this->height - 1, 0);
GfxFillRect(1, 1, this->width - 2, this->height - 2, 0x44);
for (uint arg = 0; arg < this->paramcount; arg++) {
SetDParam(arg, this->params[arg]);
}
DrawStringMultiCenter((this->width >> 1), (this->height >> 1) - 5, this->string_id, this->width - 2);
}
virtual void OnMouseLoop()
{
/* We can show tooltips while dragging tools. These are shown as long as
* we are dragging the tool. Normal tooltips work with rmb */
if (this->use_left_mouse_button ? !_left_button_down : !_right_button_down) delete this;
}
};
/** Shows a tooltip
* @param str String to be displayed
* @param paramcount number of params to deal with
* @param params (optional) up to 5 pieces of additional information that may be added to a tooltip
* @param use_left_mouse_button close the tooltip when the left (true) or right (false) mousebutton is released
*/
void GuiShowTooltips(StringID str, uint paramcount, const uint64 params[], bool use_left_mouse_button)
{
DeleteWindowById(WC_TOOLTIPS, 0);
if (str == STR_NULL) return;
for (uint i = 0; i != paramcount; i++) SetDParam(i, params[i]);
char buffer[512];
GetString(buffer, str, lastof(buffer));
Dimension br = GetStringBoundingBox(buffer);
br.width += 6; br.height += 4; // increase slightly to have some space around the box
/* Cut tooltip length to 200 pixels max, wrap to new line if longer */
if (br.width > 200) {
br.height += ((br.width - 4) / 176) * 10;
br.width = 200;
}
/* Correctly position the tooltip position, watch out for window and cursor size
* Clamp value to below main toolbar and above statusbar. If tooltip would
* go below window, flip it so it is shown above the cursor */
int y = Clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, 22, _screen.height - 12);
if (y + br.height > _screen.height - 12) y = _cursor.pos.y + _cursor.offs.y - br.height - 5;
int x = Clamp(_cursor.pos.x - (br.width >> 1), 0, _screen.width - br.width);
new TooltipsWindow(x, y, br.width, br.height, _tooltips_widgets, str, paramcount, params, use_left_mouse_button);
}
static int DrawStationCoverageText(const AcceptedCargo cargo,
int str_x, int str_y, StationCoverageType sct, bool supplies)
{
bool first = true;
char string[512];
char *b = InlineString(string, supplies ? STR_SUPPLIES : STR_000D_ACCEPTS);
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (b >= lastof(string) - (1 + 2 * 4)) break; // ',' or ' ' and two calls to Utf8Encode()
switch (sct) {
case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
case SCT_ALL: break;
default: NOT_REACHED();
}
if (cargo[i] >= (supplies ? 1U : 8U)) {
if (first) {
first = false;
} else {
/* Add a comma if this is not the first item */
*b++ = ',';
*b++ = ' ';
}
b = InlineString(b, GetCargo(i)->name);
}
}
/* If first is still true then no cargo is accepted */
if (first) b = InlineString(b, STR_00D0_NOTHING);
*b = '\0';
/* Make sure we detect any buffer overflow */
assert(b < endof(string));
SetDParamStr(0, string);
return DrawStringMultiLine(str_x, str_y, STR_JUST_RAW_STRING, 144);
}
/**
* Calculates and draws the accepted or supplied cargo around the selected tile(s)
* @param sx x position where the string is to be drawn
* @param sy y position where the string is to be drawn
* @param sct which type of cargo is to be displayed (passengers/non-passengers)
* @param rad radius around selected tile(s) to be searched
* @param supplies if supplied cargos should be drawn, else accepted cargos
* @return Returns the y value below the string that was drawn
*/
int DrawStationCoverageAreaText(int sx, int sy, StationCoverageType sct, int rad, bool supplies)
{
TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
AcceptedCargo cargo;
if (tile < MapSize()) {
if (supplies) {
GetProductionAroundTiles(cargo, tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE , rad);
} else {
GetAcceptanceAroundTiles(cargo, tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE , rad);
}
return sy + DrawStationCoverageText(cargo, sx, sy, sct, supplies);
}
return sy;
}
void CheckRedrawStationCoverage(const Window *w)
{
if (_thd.dirty & 1) {
_thd.dirty &= ~1;
SetWindowDirty(w);
}
}
/* Delete a character at the caret position in a text buf.
* If backspace is set, delete the character before the caret,
* else delete the character after it. */
static void DelChar(Textbuf *tb, bool backspace)
{
WChar c;
char *s = tb->buf + tb->caretpos;
if (backspace) s = Utf8PrevChar(s);
uint16 len = (uint16)Utf8Decode(&c, s);
uint width = GetCharacterWidth(FS_NORMAL, c);
tb->width -= width;
if (backspace) {
tb->caretpos -= len;
tb->caretxoffs -= width;
}
/* Move the remaining characters over the marker */
memmove(s, s + len, tb->size - (s - tb->buf) - len);
tb->size -= len;
}
/**
* Delete a character from a textbuffer, either with 'Delete' or 'Backspace'
* The character is delete from the position the caret is at
* @param tb Textbuf type to be changed
* @param delmode Type of deletion, either WKC_BACKSPACE or WKC_DELETE
* @return Return true on successful change of Textbuf, or false otherwise
*/
bool DeleteTextBufferChar(Textbuf *tb, int delmode)
{
if (delmode == WKC_BACKSPACE && tb->caretpos != 0) {
DelChar(tb, true);
return true;
} else if (delmode == WKC_DELETE && tb->caretpos < tb->size - 1) {
DelChar(tb, false);
return true;
}
return false;
}
/**
* Delete every character in the textbuffer
* @param tb Textbuf buffer to be emptied
*/
void DeleteTextBufferAll(Textbuf *tb)
{
memset(tb->buf, 0, tb->maxsize);
tb->size = 1;
tb->width = tb->caretpos = tb->caretxoffs = 0;
}
/**
* Insert a character to a textbuffer. If maxwidth of the Textbuf is zero,
* we don't care about the visual-length but only about the physical
* length of the string
* @param tb Textbuf type to be changed
* @param key Character to be inserted
* @return Return true on successful change of Textbuf, or false otherwise
*/
bool InsertTextBufferChar(Textbuf *tb, WChar key)
{
const byte charwidth = GetCharacterWidth(FS_NORMAL, key);
uint16 len = (uint16)Utf8CharLen(key);
if (tb->size + len <= tb->maxsize && (tb->maxwidth == 0 || tb->width + charwidth <= tb->maxwidth)) {
memmove(tb->buf + tb->caretpos + len, tb->buf + tb->caretpos, tb->size - tb->caretpos);
Utf8Encode(tb->buf + tb->caretpos, key);
tb->size += len;
tb->width += charwidth;
tb->caretpos += len;
tb->caretxoffs += charwidth;
return true;
}
return false;
}
/**
* Handle text navigation with arrow keys left/right.
* This defines where the caret will blink and the next characer interaction will occur
* @param tb Textbuf type where navigation occurs
* @param navmode Direction in which navigation occurs WKC_LEFT, WKC_RIGHT, WKC_END, WKC_HOME
* @return Return true on successful change of Textbuf, or false otherwise
*/
bool MoveTextBufferPos(Textbuf *tb, int navmode)
{
switch (navmode) {
case WKC_LEFT:
if (tb->caretpos != 0) {
WChar c;
const char *s = Utf8PrevChar(tb->buf + tb->caretpos);
Utf8Decode(&c, s);
tb->caretpos = s - tb->buf; // -= (tb->buf + tb->caretpos - s)
tb->caretxoffs -= GetCharacterWidth(FS_NORMAL, c);
return true;
}
break;
case WKC_RIGHT:
if (tb->caretpos < tb->size - 1) {
WChar c;
tb->caretpos += (uint16)Utf8Decode(&c, tb->buf + tb->caretpos);
tb->caretxoffs += GetCharacterWidth(FS_NORMAL, c);
return true;
}
break;
case WKC_HOME:
tb->caretpos = 0;
tb->caretxoffs = 0;
return true;
case WKC_END:
tb->caretpos = tb->size - 1;
tb->caretxoffs = tb->width;
return true;
default:
break;
}
return false;
}
/**
* Initialize the textbuffer by supplying it the buffer to write into
* and the maximum length of this buffer
* @param tb Textbuf type which is getting initialized
* @param buf the buffer that will be holding the data for input
* @param maxsize maximum size in bytes, including terminating '\0'
* @param maxwidth maximum length in pixels of this buffer. If reached, buffer
* cannot grow, even if maxsize would allow because there is space. Width
* of zero '0' means the buffer is only restricted by maxsize */
void InitializeTextBuffer(Textbuf *tb, char *buf, uint16 maxsize, uint16 maxwidth)
{
assert(maxsize != 0);
tb->buf = buf;
tb->maxsize = maxsize;
tb->maxwidth = maxwidth;
tb->caret = true;
UpdateTextBufferSize(tb);
}
/**
* Update Textbuf type with its actual physical character and screenlength
* Get the count of characters in the string as well as the width in pixels.
* Useful when copying in a larger amount of text at once
* @param tb Textbuf type which length is calculated
*/
void UpdateTextBufferSize(Textbuf *tb)
{
const char *buf = tb->buf;
tb->width = 0;
tb->size = 1; // terminating zero
WChar c;
while ((c = Utf8Consume(&buf)) != '\0') {
tb->width += GetCharacterWidth(FS_NORMAL, c);
tb->size += Utf8CharLen(c);
}
assert(tb->size <= tb->maxsize);
tb->caretpos = tb->size - 1;
tb->caretxoffs = tb->width;
}
bool HandleCaret(Textbuf *tb)
{
/* caret changed? */
bool b = !!(_caret_timer & 0x20);
if (b != tb->caret) {
tb->caret = b;
return true;
}
return false;
}
bool QueryString::HasEditBoxFocus(const Window *w, int wid) const
{
return ((w->window_class == WC_OSK &&
_focused_window == w->parent &&
w->parent->focused_widget &&
w->parent->focused_widget->type == WWT_EDITBOX) ||
w->IsWidgetGloballyFocused(wid));
}
HandleEditBoxResult QueryString::HandleEditBoxKey(Window *w, int wid, uint16 key, uint16 keycode, Window::EventState &state)
{
if (!QueryString::HasEditBoxFocus(w, wid)) return HEBR_NOT_FOCUSED;
state = Window::ES_HANDLED;
switch (keycode) {
case WKC_ESC: return HEBR_CANCEL;
case WKC_RETURN: case WKC_NUM_ENTER: return HEBR_CONFIRM;
case (WKC_CTRL | 'V'):
if (InsertTextBufferClipboard(&this->text)) w->InvalidateWidget(wid);
break;
case (WKC_CTRL | 'U'):
DeleteTextBufferAll(&this->text);
w->InvalidateWidget(wid);
break;
case WKC_BACKSPACE: case WKC_DELETE:
if (DeleteTextBufferChar(&this->text, keycode)) w->InvalidateWidget(wid);
break;
case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
if (MoveTextBufferPos(&this->text, keycode)) w->InvalidateWidget(wid);
break;
default:
if (IsValidChar(key, this->afilter)) {
if (InsertTextBufferChar(&this->text, key)) w->InvalidateWidget(wid);
} else {
state = Window::ES_NOT_HANDLED;
}
}
return HEBR_EDITING;
}
void QueryString::HandleEditBox(Window *w, int wid)
{
if (HasEditBoxFocus(w, wid) && HandleCaret(&this->text)) {
w->InvalidateWidget(wid);
/* When we're not the OSK, notify 'our' OSK to redraw the widget,
* so the caret changes appropriately. */
if (w->window_class != WC_OSK) {
Window *w_osk = FindWindowById(WC_OSK, 0);
if (w_osk != NULL && w_osk->parent == w) w_osk->OnInvalidateData();
}
}
}
void QueryString::DrawEditBox(Window *w, int wid)
{
const Widget *wi = &w->widget[wid];
assert((wi->type & WWT_MASK) == WWT_EDITBOX);
GfxFillRect(wi->left + 1, wi->top + 1, wi->right - 1, wi->bottom - 1, 215);
DrawPixelInfo dpi;
int delta;
/* Limit the drawing of the string inside the widget boundaries */
if (!FillDrawPixelInfo(&dpi,
wi->left + 4,
wi->top + 1,
wi->right - wi->left - 4,
wi->bottom - wi->top - 1)) {
return;
}
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &dpi;
/* We will take the current widget length as maximum width, with a small
* space reserved at the end for the caret to show */
const Textbuf *tb = &this->text;
delta = (wi->right - wi->left) - tb->width - 10;
if (delta > 0) delta = 0;
if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
DoDrawString(tb->buf, delta, 0, TC_YELLOW);
if (HasEditBoxFocus(w, wid) && tb->caret) DoDrawString("_", tb->caretxoffs + delta, 0, TC_WHITE);
_cur_dpi = old_dpi;
}
HandleEditBoxResult QueryStringBaseWindow::HandleEditBoxKey(int wid, uint16 key, uint16 keycode, EventState &state)
{
return this->QueryString::HandleEditBoxKey(this, wid, key, keycode, state);
}
void QueryStringBaseWindow::HandleEditBox(int wid)
{
this->QueryString::HandleEditBox(this, wid);
}
void QueryStringBaseWindow::DrawEditBox(int wid)
{
this->QueryString::DrawEditBox(this, wid);
}
void QueryStringBaseWindow::OnOpenOSKWindow(int wid)
{
ShowOnScreenKeyboard(this, wid, 0, 0);
}
enum QueryStringWidgets {
QUERY_STR_WIDGET_TEXT = 3,
QUERY_STR_WIDGET_DEFAULT,
QUERY_STR_WIDGET_CANCEL,
QUERY_STR_WIDGET_OK
};
struct QueryStringWindow : public QueryStringBaseWindow
{
QueryStringWindow(uint16 size, const WindowDesc *desc, Window *parent) : QueryStringBaseWindow(size, desc)
{
this->parent = parent;
this->SetFocusedWidget(QUERY_STR_WIDGET_TEXT);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
SetDParam(0, this->caption);
this->DrawWidgets();
this->DrawEditBox(QUERY_STR_WIDGET_TEXT);
}
void OnOk()
{
if (this->orig == NULL || strcmp(this->text.buf, this->orig) != 0) {
/* If the parent is NULL, the editbox is handled by general function
* HandleOnEditText */
if (this->parent != NULL) {
this->parent->OnQueryTextFinished(this->text.buf);
} else {
HandleOnEditText(this->text.buf);
}
this->handled = true;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case QUERY_STR_WIDGET_DEFAULT:
this->text.buf[0] = '\0';
/* Fallthrough */
case QUERY_STR_WIDGET_OK:
this->OnOk();
/* Fallthrough */
case QUERY_STR_WIDGET_CANCEL:
delete this;
break;
}
}
virtual void OnMouseLoop()
{
this->HandleEditBox(QUERY_STR_WIDGET_TEXT);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
EventState state = ES_NOT_HANDLED;
switch (this->HandleEditBoxKey(QUERY_STR_WIDGET_TEXT, key, keycode, state)) {
default: NOT_REACHED();
case HEBR_EDITING: {
Window *osk = FindWindowById(WC_OSK, 0);
if (osk != NULL && osk->parent == this) osk->OnInvalidateData();
} break;
case HEBR_CONFIRM: this->OnOk();
/* FALL THROUGH */
case HEBR_CANCEL: delete this; break; // close window, abandon changes
case HEBR_NOT_FOCUSED: break;
}
return state;
}
virtual void OnOpenOSKWindow(int wid)
{
ShowOnScreenKeyboard(this, wid, QUERY_STR_WIDGET_CANCEL, QUERY_STR_WIDGET_OK);
}
~QueryStringWindow()
{
if (!this->handled && this->parent != NULL) {
Window *parent = this->parent;
this->parent = NULL; // so parent doesn't try to delete us again
parent->OnQueryTextFinished(NULL);
}
}
};
static const Widget _query_string_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 259, 0, 13, STR_012D, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 259, 14, 29, 0x0, STR_NULL},
{ WWT_EDITBOX, RESIZE_NONE, COLOUR_GREY, 2, 257, 16, 27, 0x0, STR_NULL}, // QUERY_STR_WIDGET_TEXT
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 86, 30, 41, STR_DEFAULT, STR_NULL}, // QUERY_STR_WIDGET_DEFAULT
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 87, 172, 30, 41, STR_012E_CANCEL, STR_NULL}, // QUERY_STR_WIDGET_CANCEL
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 173, 259, 30, 41, STR_012F_OK, STR_NULL}, // QUERY_STR_WIDGET_OK
{ WIDGETS_END},
};
static const WindowDesc _query_string_desc(
190, 219, 260, 42, 260, 42,
WC_QUERY_STRING, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_query_string_widgets
);
/** Show a query popup window with a textbox in it.
* @param str StringID for the text shown in the textbox
* @param caption StringID of text shown in caption of querywindow
* @param maxsize maximum size in bytes (including terminating '\0')
* @param maxwidth maximum width in pixels allowed
* @param parent pointer to a Window that will handle the events (ok/cancel) of this
* window. If NULL, results are handled by global function HandleOnEditText
* @param afilter filters out unwanted character input
* @param flags various flags, @see QueryStringFlags
*/
void ShowQueryString(StringID str, StringID caption, uint maxsize, uint maxwidth, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
{
DeleteWindowById(WC_QUERY_STRING, 0);
QueryStringWindow *w = new QueryStringWindow(maxsize, &_query_string_desc, parent);
GetString(w->edit_str_buf, str, &w->edit_str_buf[maxsize - 1]);
w->edit_str_buf[maxsize - 1] = '\0';
if ((flags & QSF_ACCEPT_UNCHANGED) == 0) w->orig = strdup(w->edit_str_buf);
if ((flags & QSF_ENABLE_DEFAULT) == 0) {
/* without the "Default" button, make "Cancel" and "OK" buttons wider */
w->SetWidgetHiddenState(QUERY_STR_WIDGET_DEFAULT, true);
w->widget[QUERY_STR_WIDGET_CANCEL].left = 0;
w->widget[QUERY_STR_WIDGET_CANCEL].right = w->width / 2 - 1;
w->widget[QUERY_STR_WIDGET_OK].left = w->width / 2;
w->widget[QUERY_STR_WIDGET_OK].right = w->width - 1;
}
w->LowerWidget(QUERY_STR_WIDGET_TEXT);
w->caption = caption;
w->afilter = afilter;
InitializeTextBuffer(&w->text, w->edit_str_buf, maxsize, maxwidth);
}
enum QueryWidgets {
QUERY_WIDGET_CAPTION = 1,
QUERY_WIDGET_NO = 3,
QUERY_WIDGET_YES
};
/**
* Window used for asking the user a YES/NO question.
*/
struct QueryWindow : public Window {
QueryCallbackProc *proc; ///< callback function executed on closing of popup. Window* points to parent, bool is true if 'yes' clicked, false otherwise
uint64 params[10]; ///< local copy of _decode_parameters
StringID message; ///< message shown for query window
QueryWindow(const WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window(desc)
{
if (parent == NULL) parent = FindWindowById(WC_MAIN_WINDOW, 0);
this->parent = parent;
this->left = parent->left + (parent->width / 2) - (this->width / 2);
this->top = parent->top + (parent->height / 2) - (this->height / 2);
/* Create a backup of the variadic arguments to strings because it will be
* overridden pretty often. We will copy these back for drawing */
CopyOutDParam(this->params, 0, lengthof(this->params));
this->widget[QUERY_WIDGET_CAPTION].data = caption;
this->message = message;
this->proc = callback;
this->FindWindowPlacementAndResize(desc);
}
~QueryWindow()
{
if (this->proc != NULL) this->proc(this->parent, false);
}
virtual void OnPaint()
{
CopyInDParam(0, this->params, lengthof(this->params));
this->DrawWidgets();
CopyInDParam(0, this->params, lengthof(this->params));
DrawStringMultiCenter(this->width / 2, (this->height / 2) - 10, this->message, this->width - 2);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case QUERY_WIDGET_YES: {
/* in the Generate New World window, clicking 'Yes' causes
* DeleteNonVitalWindows() to be called - we shouldn't be in a window then */
QueryCallbackProc *proc = this->proc;
Window *parent = this->parent;
/* Prevent the destructor calling the callback function */
this->proc = NULL;
delete this;
if (proc != NULL) {
proc(parent, true);
proc = NULL;
}
} break;
case QUERY_WIDGET_NO:
delete this;
break;
}
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
/* ESC closes the window, Enter confirms the action */
switch (keycode) {
case WKC_RETURN:
case WKC_NUM_ENTER:
if (this->proc != NULL) {
this->proc(this->parent, true);
this->proc = NULL;
}
/* Fallthrough */
case WKC_ESC:
delete this;
return ES_HANDLED;
}
return ES_NOT_HANDLED;
}
};
static const Widget _query_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_RED, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_RED, 11, 209, 0, 13, STR_NULL, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_RED, 0, 209, 14, 81, 0x0, /*OVERRIDE*/STR_NULL},
{WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 20, 90, 62, 73, STR_00C9_NO, STR_NULL},
{WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 120, 190, 62, 73, STR_00C8_YES, STR_NULL},
{ WIDGETS_END },
};
static const WindowDesc _query_desc(
WDP_CENTER, WDP_CENTER, 210, 82, 210, 82,
WC_CONFIRM_POPUP_QUERY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_DEF_WIDGET | WDF_MODAL,
_query_widgets
);
/** Show a modal confirmation window with standard 'yes' and 'no' buttons
* The window is aligned to the centre of its parent.
* NOTE: You cannot use BindCString as parameter for this window!
* @param caption string shown as window caption
* @param message string that will be shown for the window
* @param parent pointer to parent window, if this pointer is NULL the parent becomes
* the main window WC_MAIN_WINDOW
* @param callback callback function pointer to set in the window descriptor
*/
void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
{
new QueryWindow(&_query_desc, caption, message, parent, callback);
}
static const Widget _load_dialog_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 256, 0, 13, STR_NULL, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 127, 14, 25, STR_SORT_BY_NAME, STR_SORT_ORDER_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 128, 256, 14, 25, STR_SORT_BY_DATE, STR_SORT_ORDER_TIP},
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 0, 256, 26, 47, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 256, 48, 153, 0x0, STR_NULL},
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 245, 256, 48, 59, SPR_HOUSE_ICON, STR_SAVELOAD_HOME_BUTTON},
{ WWT_INSET, RESIZE_RB, COLOUR_GREY, 2, 243, 50, 139, 0x0, STR_400A_LIST_OF_DRIVES_DIRECTORIES},
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 245, 256, 60, 141, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_GREY, 0, 243, 142, 153, STR_CONTENT_INTRO_BUTTON, STR_CONTENT_INTRO_BUTTON_TIP},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 245, 256, 142, 153, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
static const Widget _save_dialog_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 256, 0, 13, STR_NULL, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 127, 14, 25, STR_SORT_BY_NAME, STR_SORT_ORDER_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 128, 256, 14, 25, STR_SORT_BY_DATE, STR_SORT_ORDER_TIP},
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 0, 256, 26, 47, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 256, 48, 167, 0x0, STR_NULL},
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 245, 256, 48, 59, SPR_HOUSE_ICON, STR_SAVELOAD_HOME_BUTTON},
{ WWT_INSET, RESIZE_RB, COLOUR_GREY, 2, 243, 50, 150, 0x0, STR_400A_LIST_OF_DRIVES_DIRECTORIES},
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 245, 256, 60, 151, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 0, 256, 152, 0, 0x0, STR_NULL},
{ WWT_EDITBOX, RESIZE_RTB, COLOUR_GREY, 2, 254, 154, 165, STR_SAVE_OSKTITLE, STR_400B_CURRENTLY_SELECTED_NAME},
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 127, 168, 179, STR_4003_DELETE, STR_400C_DELETE_THE_CURRENTLY_SELECTED},
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 128, 244, 168, 179, STR_4002_SAVE, STR_400D_SAVE_THE_CURRENT_GAME_USING},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 245, 256, 168, 179, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
/* Colours for fios types */
const TextColour _fios_colours[] = {
TC_LIGHT_BLUE, TC_DARK_GREEN, TC_DARK_GREEN, TC_ORANGE, TC_LIGHT_BROWN,
TC_ORANGE, TC_LIGHT_BROWN, TC_ORANGE, TC_ORANGE, TC_YELLOW
};
void BuildFileList()
{
_fios_path_changed = true;
FiosFreeSavegameList();
switch (_saveload_mode) {
case SLD_NEW_GAME:
case SLD_LOAD_SCENARIO:
case SLD_SAVE_SCENARIO:
FiosGetScenarioList(_saveload_mode); break;
case SLD_LOAD_HEIGHTMAP:
FiosGetHeightmapList(_saveload_mode); break;
default: FiosGetSavegameList(_saveload_mode); break;
}
}
static void DrawFiosTexts(uint maxw)
{
static const char *path = NULL;
static StringID str = STR_4006_UNABLE_TO_READ_DRIVE;
static uint64 tot = 0;
if (_fios_path_changed) {
str = FiosGetDescText(&path, &tot);
_fios_path_changed = false;
}
if (str != STR_4006_UNABLE_TO_READ_DRIVE) SetDParam(0, tot);
DrawString(2, 37, str, TC_FROMSTRING);
DoDrawStringTruncated(path, 2, 27, TC_BLACK, maxw);
}
static void MakeSortedSaveGameList()
{
uint sort_start = 0;
uint sort_end = 0;
/* Directories are always above the files (FIOS_TYPE_DIR)
* Drives (A:\ (windows only) are always under the files (FIOS_TYPE_DRIVE)
* Only sort savegames/scenarios, not directories
*/
for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) {
switch (item->type) {
case FIOS_TYPE_DIR: sort_start++; break;
case FIOS_TYPE_PARENT: sort_start++; break;
case FIOS_TYPE_DRIVE: sort_end++; break;
default: break;
}
}
uint s_amount = _fios_items.Length() - sort_start - sort_end;
if (s_amount > 0) {
qsort(_fios_items.Get(sort_start), s_amount, sizeof(FiosItem), compare_FiosItems);
}
}
extern void StartupEngines();
struct SaveLoadWindow : public QueryStringBaseWindow {
private:
enum SaveLoadWindowWidgets {
SLWW_CLOSE = 0,
SLWW_WINDOWTITLE,
SLWW_SORT_BYNAME,
SLWW_SORT_BYDATE,
SLWW_HOME_BUTTON = 6,
SLWW_DRIVES_DIRECTORIES_LIST,
SLWW_CONTENT_DOWNLOAD = 9, ///< only available for play scenario/heightmap (content download)
SLWW_SAVE_OSK_TITLE, ///< only available for save operations
SLWW_DELETE_SELECTION, ///< same in here
SLWW_SAVE_GAME, ///< not to mention in here too
};
FiosItem o_dir;
public:
void GenerateFileName()
{
GenerateDefaultSaveName(this->edit_str_buf, &this->edit_str_buf[this->edit_str_size - 1]);
}
SaveLoadWindow(const WindowDesc *desc, SaveLoadDialogMode mode) : QueryStringBaseWindow(64, desc)
{
static const StringID saveload_captions[] = {
STR_4001_LOAD_GAME,
STR_0298_LOAD_SCENARIO,
STR_4000_SAVE_GAME,
STR_0299_SAVE_SCENARIO,
STR_LOAD_HEIGHTMAP,
};
this->vscroll.cap = 10;
this->resize.step_width = 2;
this->resize.step_height = 10;
SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, VHM_NONE, WC_MAIN_WINDOW, 0);
/* Use an array to define what will be the current file type being handled
* by current file mode */
switch (mode) {
case SLD_LOAD_GAME:
this->HideWidget(SLWW_CONTENT_DOWNLOAD);
this->widget[SLWW_DRIVES_DIRECTORIES_LIST].bottom += this->widget[SLWW_CONTENT_DOWNLOAD].bottom - this->widget[SLWW_CONTENT_DOWNLOAD].top;
break;
case SLD_LOAD_SCENARIO:
case SLD_LOAD_HEIGHTMAP:
this->vscroll.cap--;
case SLD_SAVE_GAME: this->GenerateFileName(); break;
case SLD_SAVE_SCENARIO: strcpy(this->edit_str_buf, "UNNAMED"); break;
default: break;
}
assert((uint)mode < lengthof(saveload_captions));
this->widget[SLWW_WINDOWTITLE].data = saveload_captions[mode];
this->LowerWidget(SLWW_DRIVES_DIRECTORIES_LIST);
this->afilter = CS_ALPHANUMERAL;
InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 240);
/* pause is only used in single-player, non-editor mode, non-menu mode. It
* will be unpaused in the WE_DESTROY event handler. */
if (_game_mode != GM_MENU && !_networking && _game_mode != GM_EDITOR) {
if (_pause_game >= 0) DoCommandP(0, 1, 0, CMD_PAUSE);
}
BuildFileList();
ResetObjectToPlace();
o_dir.type = FIOS_TYPE_DIRECT;
switch (_saveload_mode) {
case SLD_SAVE_GAME:
case SLD_LOAD_GAME:
FioGetDirectory(o_dir.name, lengthof(o_dir.name), SAVE_DIR);
break;
case SLD_SAVE_SCENARIO:
case SLD_LOAD_SCENARIO:
FioGetDirectory(o_dir.name, lengthof(o_dir.name), SCENARIO_DIR);
break;
case SLD_LOAD_HEIGHTMAP:
FioGetDirectory(o_dir.name, lengthof(o_dir.name), HEIGHTMAP_DIR);
break;
default:
strecpy(o_dir.name, _personal_dir, lastof(o_dir.name));
}
/* Focus the edit box by default in the save windows */
if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
this->SetFocusedWidget(SLWW_SAVE_OSK_TITLE);
}
this->FindWindowPlacementAndResize(desc);
}
virtual ~SaveLoadWindow()
{
/* pause is only used in single-player, non-editor mode, non menu mode */
if (!_networking && _game_mode != GM_EDITOR && _game_mode != GM_MENU) {
if (_pause_game >= 0) DoCommandP(0, 0, 0, CMD_PAUSE);
}
FiosFreeSavegameList();
}
virtual void OnPaint()
{
int y;
SetVScrollCount(this, _fios_items.Length());
this->DrawWidgets();
DrawFiosTexts(this->width);
if (_savegame_sort_dirty) {
_savegame_sort_dirty = false;
MakeSortedSaveGameList();
}
const Widget *widg = &this->widget[SLWW_DRIVES_DIRECTORIES_LIST];
GfxFillRect(widg->left + 1, widg->top + 1, widg->right, widg->bottom, 0xD7);
this->DrawSortButtonState(_savegame_sort_order & SORT_BY_NAME ? SLWW_SORT_BYNAME : SLWW_SORT_BYDATE, _savegame_sort_order & SORT_DESCENDING ? SBS_DOWN : SBS_UP);
y = widg->top + 1;
for (uint pos = this->vscroll.pos; pos < _fios_items.Length(); pos++) {
const FiosItem *item = _fios_items.Get(pos);
DoDrawStringTruncated(item->title, 4, y, _fios_colours[item->type], this->width - 18);
y += 10;
if (y >= this->vscroll.cap * 10 + widg->top + 1) break;
}
if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
this->DrawEditBox(SLWW_SAVE_OSK_TITLE);
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case SLWW_SORT_BYNAME: // Sort save names by name
_savegame_sort_order = (_savegame_sort_order == SORT_BY_NAME) ?
SORT_BY_NAME | SORT_DESCENDING : SORT_BY_NAME;
_savegame_sort_dirty = true;
this->SetDirty();
break;
case SLWW_SORT_BYDATE: // Sort save names by date
_savegame_sort_order = (_savegame_sort_order == SORT_BY_DATE) ?
SORT_BY_DATE | SORT_DESCENDING : SORT_BY_DATE;
_savegame_sort_dirty = true;
this->SetDirty();
break;
case SLWW_HOME_BUTTON: // OpenTTD 'button', jumps to OpenTTD directory
FiosBrowseTo(&o_dir);
this->SetDirty();
BuildFileList();
break;
case SLWW_DRIVES_DIRECTORIES_LIST: { // Click the listbox
int y = (pt.y - this->widget[widget].top - 1) / 10;
if (y < 0 || (y += this->vscroll.pos) >= this->vscroll.count) return;
const FiosItem *file = _fios_items.Get(y);
const char *name = FiosBrowseTo(file);
if (name != NULL) {
if (_saveload_mode == SLD_LOAD_GAME || _saveload_mode == SLD_LOAD_SCENARIO) {
_switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD;
SetFiosType(file->type);
strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
strecpy(_file_to_saveload.title, file->title, lastof(_file_to_saveload.title));
delete this;
} else if (_saveload_mode == SLD_LOAD_HEIGHTMAP) {
SetFiosType(file->type);
strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
strecpy(_file_to_saveload.title, file->title, lastof(_file_to_saveload.title));
delete this;
ShowHeightmapLoad();
} else {
/* SLD_SAVE_GAME, SLD_SAVE_SCENARIO copy clicked name to editbox */
ttd_strlcpy(this->text.buf, file->title, this->text.maxsize);
UpdateTextBufferSize(&this->text);
this->InvalidateWidget(SLWW_SAVE_OSK_TITLE);
}
} else {
/* Changed directory, need repaint. */
this->SetDirty();
BuildFileList();
}
break;
}
case SLWW_CONTENT_DOWNLOAD:
if (!_network_available) {
ShowErrorMessage(INVALID_STRING_ID, STR_NETWORK_ERR_NOTAVAILABLE, 0, 0);
} else {
#if defined(ENABLE_NETWORK)
switch (_saveload_mode) {
default: NOT_REACHED();
case SLD_LOAD_SCENARIO: ShowNetworkContentListWindow(NULL, CONTENT_TYPE_SCENARIO); break;
case SLD_LOAD_HEIGHTMAP: ShowNetworkContentListWindow(NULL, CONTENT_TYPE_HEIGHTMAP); break;
}
#endif
}
break;
case SLWW_DELETE_SELECTION: case SLWW_SAVE_GAME: // Delete, Save game
break;
}
}
virtual void OnMouseLoop()
{
if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
this->HandleEditBox(SLWW_SAVE_OSK_TITLE);
}
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
if (keycode == WKC_ESC) {
delete this;
return ES_HANDLED;
}
EventState state = ES_NOT_HANDLED;
if ((_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) &&
this->HandleEditBoxKey(SLWW_SAVE_OSK_TITLE, key, keycode, state) == HEBR_CONFIRM) {
this->HandleButtonClick(SLWW_SAVE_GAME);
}
return state;
}
virtual void OnTimeout()
{
/* This test protects against using widgets 11 and 12 which are only available
* in those two saveload mode */
if (!(_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO)) return;
if (this->IsWidgetLowered(SLWW_DELETE_SELECTION)) { // Delete button clicked
if (!FiosDelete(this->text.buf)) {
ShowErrorMessage(INVALID_STRING_ID, STR_4008_UNABLE_TO_DELETE_FILE, 0, 0);
} else {
BuildFileList();
/* Reset file name to current date on successful delete */
if (_saveload_mode == SLD_SAVE_GAME) GenerateFileName();
}
UpdateTextBufferSize(&this->text);
this->SetDirty();
} else if (this->IsWidgetLowered(SLWW_SAVE_GAME)) { // Save button clicked
_switch_mode = SM_SAVE;
FiosMakeSavegameName(_file_to_saveload.name, this->text.buf, sizeof(_file_to_saveload.name));
/* In the editor set up the vehicle engines correctly (date might have changed) */
if (_game_mode == GM_EDITOR) StartupEngines();
}
}
virtual void OnResize(Point new_size, Point delta)
{
/* Widget 2 and 3 have to go with halve speed, make it so obiwan */
uint diff = delta.x / 2;
this->widget[SLWW_SORT_BYNAME].right += diff;
this->widget[SLWW_SORT_BYDATE].left += diff;
this->widget[SLWW_SORT_BYDATE].right += delta.x;
/* Same for widget 11 and 12 in save-dialog */
if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
this->widget[SLWW_DELETE_SELECTION].right += diff;
this->widget[SLWW_SAVE_GAME].left += diff;
this->widget[SLWW_SAVE_GAME].right += delta.x;
}
this->vscroll.cap += delta.y / 10;
}
virtual void OnInvalidateData(int data)
{
BuildFileList();
}
};
static const WindowDesc _load_dialog_desc(
WDP_CENTER, WDP_CENTER, 257, 154, 257, 294,
WC_SAVELOAD, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_load_dialog_widgets
);
static const WindowDesc _save_dialog_desc(
WDP_CENTER, WDP_CENTER, 257, 180, 257, 320,
WC_SAVELOAD, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_save_dialog_widgets
);
/** These values are used to convert the file/operations mode into a corresponding file type.
* So each entry, as expressed by the related comment, is based on the enum */
static const FileType _file_modetotype[] = {
FT_SAVEGAME, ///< used for SLD_LOAD_GAME
FT_SCENARIO, ///< used for SLD_LOAD_SCENARIO
FT_SAVEGAME, ///< used for SLD_SAVE_GAME
FT_SCENARIO, ///< used for SLD_SAVE_SCENARIO
FT_HEIGHTMAP, ///< used for SLD_LOAD_HEIGHTMAP
FT_SAVEGAME, ///< SLD_NEW_GAME
};
void ShowSaveLoadDialog(SaveLoadDialogMode mode)
{
DeleteWindowById(WC_SAVELOAD, 0);
const WindowDesc *sld;
switch (mode) {
case SLD_SAVE_GAME:
case SLD_SAVE_SCENARIO:
sld = &_save_dialog_desc; break;
default:
sld = &_load_dialog_desc; break;
}
_saveload_mode = mode;
_file_to_saveload.filetype = _file_modetotype[mode];
new SaveLoadWindow(sld, mode);
}
void RedrawAutosave()
{
SetWindowDirty(FindWindowById(WC_STATUS_BAR, 0));
}
void SetFiosType(const byte fiostype)
{
switch (fiostype) {
case FIOS_TYPE_FILE:
case FIOS_TYPE_SCENARIO:
_file_to_saveload.mode = SL_LOAD;
break;
case FIOS_TYPE_OLDFILE:
case FIOS_TYPE_OLD_SCENARIO:
_file_to_saveload.mode = SL_OLD_LOAD;
break;
#ifdef WITH_PNG
case FIOS_TYPE_PNG:
_file_to_saveload.mode = SL_PNG;
break;
#endif /* WITH_PNG */
case FIOS_TYPE_BMP:
_file_to_saveload.mode = SL_BMP;
break;
default:
_file_to_saveload.mode = SL_INVALID;
break;
}
}
| 58,030
|
C++
|
.cpp
| 1,514
| 35.409511
| 163
| 0.673865
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,093
|
os2.cpp
|
EnergeticBark_OpenTTD-3DS/src/os2.cpp
|
/* $Id$ */
/** @file os2.cpp OS2 related OS support. */
#include "stdafx.h"
#include "openttd.h"
#include "variables.h"
#include "gui.h"
#include "fileio_func.h"
#include "fios.h"
#include "functions.h"
#include "core/random_func.hpp"
#include "string_func.h"
#include "textbuf_gui.h"
#include "table/strings.h"
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <time.h>
#ifndef __INNOTEK_LIBC__
#include <dos.h>
#endif
#define INCL_WIN
#define INCL_WINCLIPBOARD
#include <os2.h>
#ifndef __INNOTEK_LIBC__
#include <i86.h>
#endif
bool FiosIsRoot(const char *file)
{
return file[3] == '\0';
}
void FiosGetDrives()
{
uint disk, disk2, save, total;
#ifndef __INNOTEK_LIBC__
_dos_getdrive(&save); // save original drive
#else
save = _getdrive(); // save original drive
char wd[MAX_PATH];
getcwd(wd, MAX_PATH);
total = 'z';
#endif
/* get an available drive letter */
#ifndef __INNOTEK_LIBC__
for (disk = 1;; disk++) {
_dos_setdrive(disk, &total);
#else
for (disk = 'A';; disk++) {
_chdrive(disk);
#endif
if (disk >= total) break;
#ifndef __INNOTEK_LIBC__
_dos_getdrive(&disk2);
#else
disk2 = _getdrive();
#endif
if (disk == disk2) {
FiosItem *fios = _fios_items.Append();
fios->type = FIOS_TYPE_DRIVE;
fios->mtime = 0;
#ifndef __INNOTEK_LIBC__
snprintf(fios->name, lengthof(fios->name), "%c:", 'A' + disk - 1);
#else
snprintf(fios->name, lengthof(fios->name), "%c:", disk);
#endif
strecpy(fios->title, fios->name, lastof(fios->title));
}
}
/* Restore the original drive */
#ifndef __INNOTEK_LIBC__
_dos_setdrive(save, &total);
#else
chdir(wd);
#endif
}
bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
{
#ifndef __INNOTEK_LIBC__
struct diskfree_t free;
char drive = path[0] - 'A' + 1;
if (tot != NULL && _getdiskfree(drive, &free) == 0) {
*tot = free.avail_clusters * free.sectors_per_cluster * free.bytes_per_sector;
return true;
}
return false;
#else
uint64 free = 0;
#ifdef HAS_STATVFS
{
struct statvfs s;
if (statvfs(path, &s) != 0) return false;
free = (uint64)s.f_frsize * s.f_bavail;
}
#endif
if (tot != NULL) *tot = free;
return true;
#endif
}
bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb)
{
char filename[MAX_PATH];
snprintf(filename, lengthof(filename), "%s" PATHSEP "%s", path, ent->d_name);
return stat(filename, sb) == 0;
}
bool FiosIsHiddenFile(const struct dirent *ent)
{
return ent->d_name[0] == '.';
}
void ShowInfo(const char *str)
{
HAB hab;
HMQ hmq;
ULONG rc;
/* init PM env. */
hmq = WinCreateMsgQueue((hab = WinInitialize(0)), 0);
/* display the box */
rc = WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, (const unsigned char *)str, (const unsigned char *)"OpenTTD", 0, MB_OK | MB_MOVEABLE | MB_INFORMATION);
/* terminate PM env. */
WinDestroyMsgQueue(hmq);
WinTerminate(hab);
}
void ShowOSErrorBox(const char *buf, bool system)
{
HAB hab;
HMQ hmq;
ULONG rc;
/* init PM env. */
hmq = WinCreateMsgQueue((hab = WinInitialize(0)), 0);
/* display the box */
rc = WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, (const unsigned char *)buf, (const unsigned char *)"OpenTTD", 0, MB_OK | MB_MOVEABLE | MB_ERROR);
/* terminate PM env. */
WinDestroyMsgQueue(hmq);
WinTerminate(hab);
}
int CDECL main(int argc, char *argv[])
{
SetRandomSeed(time(NULL));
return ttd_main(argc, argv);
}
/**
* Insert a chunk of text from the clipboard onto the textbuffer. Get TEXT clipboard
* and append this up to the maximum length (either absolute or screenlength). If maxlength
* is zero, we don't care about the screenlength but only about the physical length of the string
* @param tb Textbuf type to be changed
* @return Return true on successful change of Textbuf, or false otherwise
*/
bool InsertTextBufferClipboard(Textbuf *tb)
{
/* XXX -- Currently no clipboard support implemented with GCC */
#ifndef __INNOTEK_LIBC__
HAB hab = 0;
if (WinOpenClipbrd(hab))
{
const char *text = (const char*)WinQueryClipbrdData(hab, CF_TEXT);
if (text != NULL)
{
uint length = 0;
uint width = 0;
const char *i;
for (i = text; IsValidAsciiChar(*i); i++)
{
uint w;
if (tb->size + length + 1 > tb->maxsize) break;
w = GetCharacterWidth(FS_NORMAL, (byte)*i);
if (tb->maxwidth != 0 && width + tb->width + w > tb->maxwidth) break;
width += w;
length++;
}
memmove(tb->buf + tb->caretpos + length, tb->buf + tb->caretpos, tb->size - tb->caretpos);
memcpy(tb->buf + tb->caretpos, text, length);
tb->width += width;
tb->caretxoffs += width;
tb->size += length;
tb->caretpos += length;
WinCloseClipbrd(hab);
return true;
}
WinCloseClipbrd(hab);
}
#endif
return false;
}
void CSleep(int milliseconds)
{
#ifndef __INNOTEK_LIBC__
delay(milliseconds);
#else
usleep(milliseconds * 1000);
#endif
}
const char *FS2OTTD(const char *name) {return name;}
const char *OTTD2FS(const char *name) {return name;}
| 4,973
|
C++
|
.cpp
| 192
| 23.71875
| 151
| 0.687566
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,095
|
thread_none.cpp
|
EnergeticBark_OpenTTD-3DS/src/thread_none.cpp
|
/* $Id$ */
/** @file thread_none.cpp No-Threads-Available implementation of Threads */
#include "stdafx.h"
#include "thread.h"
/* static */ bool ThreadObject::New(OTTDThreadFunc proc, void *param, ThreadObject **thread)
{
if (thread != NULL) *thread = NULL;
return false;
}
/** Mutex that doesn't do locking because it ain't needed when there're no threads */
class ThreadMutex_None : public ThreadMutex {
public:
virtual void BeginCritical() {}
virtual void EndCritical() {}
};
/* static */ ThreadMutex *ThreadMutex::New()
{
return new ThreadMutex_None();
}
| 569
|
C++
|
.cpp
| 19
| 28.421053
| 92
| 0.730275
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,096
|
landscape.cpp
|
EnergeticBark_OpenTTD-3DS/src/landscape.cpp
|
/* $Id$ */
/** @file landscape.cpp Functions related to the landscape (slopes etc.). */
/** @defgroup SnowLineGroup Snowline functions and data structures */
#include "stdafx.h"
#include "heightmap.h"
#include "clear_map.h"
#include "spritecache.h"
#include "viewport_func.h"
#include "command_func.h"
#include "landscape.h"
#include "variables.h"
#include "void_map.h"
#include "tgp.h"
#include "genworld.h"
#include "fios.h"
#include "functions.h"
#include "date_func.h"
#include "water.h"
#include "effectvehicle_func.h"
#include "landscape_type.h"
#include "settings_type.h"
#include "table/sprites.h"
extern const TileTypeProcs
_tile_type_clear_procs,
_tile_type_rail_procs,
_tile_type_road_procs,
_tile_type_town_procs,
_tile_type_trees_procs,
_tile_type_station_procs,
_tile_type_water_procs,
_tile_type_dummy_procs,
_tile_type_industry_procs,
_tile_type_tunnelbridge_procs,
_tile_type_unmovable_procs;
/** Tile callback functions for each type of tile.
* @ingroup TileCallbackGroup
* @see TileType */
const TileTypeProcs * const _tile_type_procs[16] = {
&_tile_type_clear_procs, ///< Callback functions for MP_CLEAR tiles
&_tile_type_rail_procs, ///< Callback functions for MP_RAILWAY tiles
&_tile_type_road_procs, ///< Callback functions for MP_ROAD tiles
&_tile_type_town_procs, ///< Callback functions for MP_HOUSE tiles
&_tile_type_trees_procs, ///< Callback functions for MP_TREES tiles
&_tile_type_station_procs, ///< Callback functions for MP_STATION tiles
&_tile_type_water_procs, ///< Callback functions for MP_WATER tiles
&_tile_type_dummy_procs, ///< Callback functions for MP_VOID tiles
&_tile_type_industry_procs, ///< Callback functions for MP_INDUSTRY tiles
&_tile_type_tunnelbridge_procs, ///< Callback functions for MP_TUNNELBRIDGE tiles
&_tile_type_unmovable_procs, ///< Callback functions for MP_UNMOVABLE tiles
};
/* landscape slope => sprite */
const byte _tileh_to_sprite[32] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0,
0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 17, 0, 15, 18, 0,
};
/**
* Description of the snow line throughout the year.
*
* If it is \c NULL, a static snowline height is used, as set by \c _settings_game.game_creation.snow_line.
* Otherwise it points to a table loaded from a newGRF file, that describes the variable snowline
* @ingroup SnowLineGroup
* @see GetSnowLine() GameCreationSettings */
SnowLine *_snow_line = NULL;
/**
* Applies a foundation to a slope.
*
* @pre Foundation and slope must be valid combined.
* @param f The #Foundation.
* @param s The #Slope to modify.
* @return Increment to the tile Z coordinate.
*/
uint ApplyFoundationToSlope(Foundation f, Slope *s)
{
if (!IsFoundation(f)) return 0;
if (IsLeveledFoundation(f)) {
uint dz = TILE_HEIGHT + (IsSteepSlope(*s) ? TILE_HEIGHT : 0);
*s = SLOPE_FLAT;
return dz;
}
if (f != FOUNDATION_STEEP_BOTH && IsNonContinuousFoundation(f)) {
*s = HalftileSlope(*s, GetHalftileFoundationCorner(f));
return 0;
}
if (IsSpecialRailFoundation(f)) {
*s = SlopeWithThreeCornersRaised(OppositeCorner(GetRailFoundationCorner(f)));
return 0;
}
uint dz = IsSteepSlope(*s) ? TILE_HEIGHT : 0;
Corner highest_corner = GetHighestSlopeCorner(*s);
switch (f) {
case FOUNDATION_INCLINED_X:
*s = (((highest_corner == CORNER_W) || (highest_corner == CORNER_S)) ? SLOPE_SW : SLOPE_NE);
break;
case FOUNDATION_INCLINED_Y:
*s = (((highest_corner == CORNER_S) || (highest_corner == CORNER_E)) ? SLOPE_SE : SLOPE_NW);
break;
case FOUNDATION_STEEP_LOWER:
*s = SlopeWithOneCornerRaised(highest_corner);
break;
case FOUNDATION_STEEP_BOTH:
*s = HalftileSlope(SlopeWithOneCornerRaised(highest_corner), highest_corner);
break;
default: NOT_REACHED();
}
return dz;
}
/**
* Determines height at given coordinate of a slope
* @param x x coordinate
* @param y y coordinate
* @param corners slope to examine
* @return height of given point of given slope
*/
uint GetPartialZ(int x, int y, Slope corners)
{
if (IsHalftileSlope(corners)) {
switch (GetHalftileSlopeCorner(corners)) {
case CORNER_W:
if (x - y >= 0) return GetSlopeMaxZ(corners);
break;
case CORNER_S:
if (x - (y ^ 0xF) >= 0) return GetSlopeMaxZ(corners);
break;
case CORNER_E:
if (y - x >= 0) return GetSlopeMaxZ(corners);
break;
case CORNER_N:
if ((y ^ 0xF) - x >= 0) return GetSlopeMaxZ(corners);
break;
default: NOT_REACHED();
}
}
int z = 0;
switch (RemoveHalftileSlope(corners)) {
case SLOPE_W:
if (x - y >= 0) {
z = (x - y) >> 1;
}
break;
case SLOPE_S:
y ^= 0xF;
if ((x - y) >= 0) {
z = (x - y) >> 1;
}
break;
case SLOPE_SW:
z = (x >> 1) + 1;
break;
case SLOPE_E:
if (y - x >= 0) {
z = (y - x) >> 1;
}
break;
case SLOPE_EW:
case SLOPE_NS:
case SLOPE_ELEVATED:
z = 4;
break;
case SLOPE_SE:
z = (y >> 1) + 1;
break;
case SLOPE_WSE:
z = 8;
y ^= 0xF;
if (x - y < 0) {
z += (x - y) >> 1;
}
break;
case SLOPE_N:
y ^= 0xF;
if (y - x >= 0) {
z = (y - x) >> 1;
}
break;
case SLOPE_NW:
z = (y ^ 0xF) >> 1;
break;
case SLOPE_NWS:
z = 8;
if (x - y < 0) {
z += (x - y) >> 1;
}
break;
case SLOPE_NE:
z = (x ^ 0xF) >> 1;
break;
case SLOPE_ENW:
z = 8;
y ^= 0xF;
if (y - x < 0) {
z += (y - x) >> 1;
}
break;
case SLOPE_SEN:
z = 8;
if (y - x < 0) {
z += (y - x) >> 1;
}
break;
case SLOPE_STEEP_S:
z = 1 + ((x + y) >> 1);
break;
case SLOPE_STEEP_W:
z = 1 + ((x + (y ^ 0xF)) >> 1);
break;
case SLOPE_STEEP_N:
z = 1 + (((x ^ 0xF) + (y ^ 0xF)) >> 1);
break;
case SLOPE_STEEP_E:
z = 1 + (((x ^ 0xF) + y) >> 1);
break;
default: break;
}
return z;
}
uint GetSlopeZ(int x, int y)
{
TileIndex tile = TileVirtXY(x, y);
return _tile_type_procs[GetTileType(tile)]->get_slope_z_proc(tile, x, y);
}
/**
* Determine the Z height of a corner relative to TileZ.
*
* @pre The slope must not be a halftile slope.
*
* @param tileh The slope.
* @param corner The corner.
* @return Z position of corner relative to TileZ.
*/
int GetSlopeZInCorner(Slope tileh, Corner corner)
{
assert(!IsHalftileSlope(tileh));
return ((tileh & SlopeWithOneCornerRaised(corner)) != 0 ? TILE_HEIGHT : 0) + (tileh == SteepSlope(corner) ? TILE_HEIGHT : 0);
}
/**
* Determine the Z height of the corners of a specific tile edge
*
* @note If a tile has a non-continuous halftile foundation, a corner can have different heights wrt. it's edges.
*
* @pre z1 and z2 must be initialized (typ. with TileZ). The corner heights just get added.
*
* @param tileh The slope of the tile.
* @param edge The edge of interest.
* @param z1 Gets incremented by the height of the first corner of the edge. (near corner wrt. the camera)
* @param z2 Gets incremented by the height of the second corner of the edge. (far corner wrt. the camera)
*/
void GetSlopeZOnEdge(Slope tileh, DiagDirection edge, int *z1, int *z2)
{
static const Slope corners[4][4] = {
/* corner | steep slope
* z1 z2 | z1 z2 */
{SLOPE_E, SLOPE_N, SLOPE_STEEP_E, SLOPE_STEEP_N}, // DIAGDIR_NE, z1 = E, z2 = N
{SLOPE_S, SLOPE_E, SLOPE_STEEP_S, SLOPE_STEEP_E}, // DIAGDIR_SE, z1 = S, z2 = E
{SLOPE_S, SLOPE_W, SLOPE_STEEP_S, SLOPE_STEEP_W}, // DIAGDIR_SW, z1 = S, z2 = W
{SLOPE_W, SLOPE_N, SLOPE_STEEP_W, SLOPE_STEEP_N}, // DIAGDIR_NW, z1 = W, z2 = N
};
int halftile_test = (IsHalftileSlope(tileh) ? SlopeWithOneCornerRaised(GetHalftileSlopeCorner(tileh)) : 0);
if (halftile_test == corners[edge][0]) *z2 += TILE_HEIGHT; // The slope is non-continuous in z2. z2 is on the upper side.
if (halftile_test == corners[edge][1]) *z1 += TILE_HEIGHT; // The slope is non-continuous in z1. z1 is on the upper side.
if ((tileh & corners[edge][0]) != 0) *z1 += TILE_HEIGHT; // z1 is raised
if ((tileh & corners[edge][1]) != 0) *z2 += TILE_HEIGHT; // z2 is raised
if (RemoveHalftileSlope(tileh) == corners[edge][2]) *z1 += TILE_HEIGHT; // z1 is highest corner of a steep slope
if (RemoveHalftileSlope(tileh) == corners[edge][3]) *z2 += TILE_HEIGHT; // z2 is highest corner of a steep slope
}
/**
* Get slope of a tile on top of a (possible) foundation
* If a tile does not have a foundation, the function returns the same as GetTileSlope.
*
* @param tile The tile of interest.
* @param z returns the z of the foundation slope. (Can be NULL, if not needed)
* @return The slope on top of the foundation.
*/
Slope GetFoundationSlope(TileIndex tile, uint *z)
{
Slope tileh = GetTileSlope(tile, z);
Foundation f = _tile_type_procs[GetTileType(tile)]->get_foundation_proc(tile, tileh);
uint z_inc = ApplyFoundationToSlope(f, &tileh);
if (z != NULL) *z += z_inc;
return tileh;
}
static bool HasFoundationNW(TileIndex tile, Slope slope_here, uint z_here)
{
uint z;
int z_W_here = z_here;
int z_N_here = z_here;
GetSlopeZOnEdge(slope_here, DIAGDIR_NW, &z_W_here, &z_N_here);
Slope slope = GetFoundationSlope(TILE_ADDXY(tile, 0, -1), &z);
int z_W = z;
int z_N = z;
GetSlopeZOnEdge(slope, DIAGDIR_SE, &z_W, &z_N);
return (z_N_here > z_N) || (z_W_here > z_W);
}
static bool HasFoundationNE(TileIndex tile, Slope slope_here, uint z_here)
{
uint z;
int z_E_here = z_here;
int z_N_here = z_here;
GetSlopeZOnEdge(slope_here, DIAGDIR_NE, &z_E_here, &z_N_here);
Slope slope = GetFoundationSlope(TILE_ADDXY(tile, -1, 0), &z);
int z_E = z;
int z_N = z;
GetSlopeZOnEdge(slope, DIAGDIR_SW, &z_E, &z_N);
return (z_N_here > z_N) || (z_E_here > z_E);
}
/**
* Draw foundation \a f at tile \a ti. Updates \a ti.
* @param ti Tile to draw foundation on
* @param f Foundation to draw
*/
void DrawFoundation(TileInfo *ti, Foundation f)
{
if (!IsFoundation(f)) return;
/* Two part foundations must be drawn separately */
assert(f != FOUNDATION_STEEP_BOTH);
uint sprite_block = 0;
uint z;
Slope slope = GetFoundationSlope(ti->tile, &z);
/* Select the needed block of foundations sprites
* Block 0: Walls at NW and NE edge
* Block 1: Wall at NE edge
* Block 2: Wall at NW edge
* Block 3: No walls at NW or NE edge
*/
if (!HasFoundationNW(ti->tile, slope, z)) sprite_block += 1;
if (!HasFoundationNE(ti->tile, slope, z)) sprite_block += 2;
/* Use the original slope sprites if NW and NE borders should be visible */
SpriteID leveled_base = (sprite_block == 0 ? (int)SPR_FOUNDATION_BASE : (SPR_SLOPES_VIRTUAL_BASE + sprite_block * SPR_TRKFOUND_BLOCK_SIZE));
SpriteID inclined_base = SPR_SLOPES_VIRTUAL_BASE + SPR_SLOPES_INCLINED_OFFSET + sprite_block * SPR_TRKFOUND_BLOCK_SIZE;
SpriteID halftile_base = SPR_HALFTILE_FOUNDATION_BASE + sprite_block * SPR_HALFTILE_BLOCK_SIZE;
if (IsSteepSlope(ti->tileh)) {
if (!IsNonContinuousFoundation(f)) {
/* Lower part of foundation */
AddSortableSpriteToDraw(
leveled_base + (ti->tileh & ~SLOPE_STEEP), PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z
);
}
Corner highest_corner = GetHighestSlopeCorner(ti->tileh);
ti->z += ApplyFoundationToSlope(f, &ti->tileh);
if (IsInclinedFoundation(f)) {
/* inclined foundation */
byte inclined = highest_corner * 2 + (f == FOUNDATION_INCLINED_Y ? 1 : 0);
AddSortableSpriteToDraw(inclined_base + inclined, PAL_NONE, ti->x, ti->y,
f == FOUNDATION_INCLINED_X ? 16 : 1,
f == FOUNDATION_INCLINED_Y ? 16 : 1,
TILE_HEIGHT, ti->z
);
OffsetGroundSprite(31, 9);
} else if (IsLeveledFoundation(f)) {
AddSortableSpriteToDraw(leveled_base + SlopeWithOneCornerRaised(highest_corner), PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z - TILE_HEIGHT);
OffsetGroundSprite(31, 1);
} else if (f == FOUNDATION_STEEP_LOWER) {
/* one corner raised */
OffsetGroundSprite(31, 1);
} else {
/* halftile foundation */
int x_bb = (((highest_corner == CORNER_W) || (highest_corner == CORNER_S)) ? 8 : 0);
int y_bb = (((highest_corner == CORNER_S) || (highest_corner == CORNER_E)) ? 8 : 0);
AddSortableSpriteToDraw(halftile_base + highest_corner, PAL_NONE, ti->x + x_bb, ti->y + y_bb, 8, 8, 7, ti->z + TILE_HEIGHT);
OffsetGroundSprite(31, 9);
}
} else {
if (IsLeveledFoundation(f)) {
/* leveled foundation */
AddSortableSpriteToDraw(leveled_base + ti->tileh, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
OffsetGroundSprite(31, 1);
} else if (IsNonContinuousFoundation(f)) {
/* halftile foundation */
Corner halftile_corner = GetHalftileFoundationCorner(f);
int x_bb = (((halftile_corner == CORNER_W) || (halftile_corner == CORNER_S)) ? 8 : 0);
int y_bb = (((halftile_corner == CORNER_S) || (halftile_corner == CORNER_E)) ? 8 : 0);
AddSortableSpriteToDraw(halftile_base + halftile_corner, PAL_NONE, ti->x + x_bb, ti->y + y_bb, 8, 8, 7, ti->z);
OffsetGroundSprite(31, 9);
} else if (IsSpecialRailFoundation(f)) {
/* anti-zig-zag foundation */
SpriteID spr;
if (ti->tileh == SLOPE_NS || ti->tileh == SLOPE_EW) {
/* half of leveled foundation under track corner */
spr = leveled_base + SlopeWithThreeCornersRaised(GetRailFoundationCorner(f));
} else {
/* tile-slope = sloped along X/Y, foundation-slope = three corners raised */
spr = inclined_base + 2 * GetRailFoundationCorner(f) + ((ti->tileh == SLOPE_SW || ti->tileh == SLOPE_NE) ? 1 : 0);
}
AddSortableSpriteToDraw(spr, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
OffsetGroundSprite(31, 9);
} else {
/* inclined foundation */
byte inclined = GetHighestSlopeCorner(ti->tileh) * 2 + (f == FOUNDATION_INCLINED_Y ? 1 : 0);
AddSortableSpriteToDraw(inclined_base + inclined, PAL_NONE, ti->x, ti->y,
f == FOUNDATION_INCLINED_X ? 16 : 1,
f == FOUNDATION_INCLINED_Y ? 16 : 1,
TILE_HEIGHT, ti->z
);
OffsetGroundSprite(31, 9);
}
ti->z += ApplyFoundationToSlope(f, &ti->tileh);
}
}
void DoClearSquare(TileIndex tile)
{
MakeClear(tile, CLEAR_GRASS, _generating_world ? 3 : 0);
MarkTileDirtyByTile(tile);
}
/** Returns information about trackdirs and signal states.
* If there is any trackbit at 'side', return all trackdirbits.
* For TRANSPORT_ROAD, return no trackbits if there is no roadbit (of given subtype) at given side.
* @param tile tile to get info about
* @param mode transport type
* @param sub_mode for TRANSPORT_ROAD, roadtypes to check
* @param side side we are entering from, INVALID_DIAGDIR to return all trackbits
* @return trackdirbits and other info depending on 'mode'
*/
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
{
return _tile_type_procs[GetTileType(tile)]->get_tile_track_status_proc(tile, mode, sub_mode, side);
}
/**
* Change the owner of a tile
* @param tile Tile to change
* @param old_owner Current owner of the tile
* @param new_owner New owner of the tile
*/
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
{
_tile_type_procs[GetTileType(tile)]->change_tile_owner_proc(tile, old_owner, new_owner);
}
void GetAcceptedCargo(TileIndex tile, AcceptedCargo ac)
{
memset(ac, 0, sizeof(AcceptedCargo));
_tile_type_procs[GetTileType(tile)]->get_accepted_cargo_proc(tile, ac);
}
void AnimateTile(TileIndex tile)
{
_tile_type_procs[GetTileType(tile)]->animate_tile_proc(tile);
}
bool ClickTile(TileIndex tile)
{
return _tile_type_procs[GetTileType(tile)]->click_tile_proc(tile);
}
void GetTileDesc(TileIndex tile, TileDesc *td)
{
_tile_type_procs[GetTileType(tile)]->get_tile_desc_proc(tile, td);
}
/**
* Has a snow line table already been loaded.
* @return true if the table has been loaded already.
* @ingroup SnowLineGroup
*/
bool IsSnowLineSet(void)
{
return _snow_line != NULL;
}
/**
* Set a variable snow line, as loaded from a newgrf file.
* @param table the 12 * 32 byte table containing the snowline for each day
* @ingroup SnowLineGroup
*/
void SetSnowLine(byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS])
{
_snow_line = CallocT<SnowLine>(1);
_snow_line->lowest_value = 0xFF;
memcpy(_snow_line->table, table, sizeof(_snow_line->table));
for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
_snow_line->highest_value = max(_snow_line->highest_value, table[i][j]);
_snow_line->lowest_value = min(_snow_line->lowest_value, table[i][j]);
}
}
}
/**
* Get the current snow line, either variable or static.
* @return the snow line height.
* @ingroup SnowLineGroup
*/
byte GetSnowLine(void)
{
if (_snow_line == NULL) return _settings_game.game_creation.snow_line;
YearMonthDay ymd;
ConvertDateToYMD(_date, &ymd);
return _snow_line->table[ymd.month][ymd.day];
}
/**
* Get the highest possible snow line height, either variable or static.
* @return the highest snow line height.
* @ingroup SnowLineGroup
*/
byte HighestSnowLine(void)
{
return _snow_line == NULL ? _settings_game.game_creation.snow_line : _snow_line->highest_value;
}
/**
* Get the lowest possible snow line height, either variable or static.
* @return the lowest snow line height.
* @ingroup SnowLineGroup
*/
byte LowestSnowLine(void)
{
return _snow_line == NULL ? _settings_game.game_creation.snow_line : _snow_line->lowest_value;
}
/**
* Clear the variable snow line table and free the memory.
* @ingroup SnowLineGroup
*/
void ClearSnowLine(void)
{
free(_snow_line);
_snow_line = NULL;
}
/** Clear a piece of landscape
* @param tile tile to clear
* @param flags of operation to conduct
* @param p1 unused
* @param p2 unused
*/
CommandCost CmdLandscapeClear(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
return _tile_type_procs[GetTileType(tile)]->clear_tile_proc(tile, flags);
}
/** Clear a big piece of landscape
* @param tile end tile of area dragging
* @param p1 start tile of area dragging
* @param flags of operation to conduct
* @param p2 unused
*/
CommandCost CmdClearArea(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (p1 >= MapSize()) return CMD_ERROR;
/* make sure sx,sy are smaller than ex,ey */
int ex = TileX(tile);
int ey = TileY(tile);
int sx = TileX(p1);
int sy = TileY(p1);
if (ex < sx) Swap(ex, sx);
if (ey < sy) Swap(ey, sy);
Money money = GetAvailableMoneyForCommand();
CommandCost cost(EXPENSES_CONSTRUCTION);
bool success = false;
for (int x = sx; x <= ex; ++x) {
for (int y = sy; y <= ey; ++y) {
CommandCost ret = DoCommand(TileXY(x, y), 0, 0, flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) continue;
success = true;
if (flags & DC_EXEC) {
money -= ret.GetCost();
if (ret.GetCost() > 0 && money < 0) {
_additional_cash_required = ret.GetCost();
return cost;
}
DoCommand(TileXY(x, y), 0, 0, flags, CMD_LANDSCAPE_CLEAR);
/* draw explosion animation... */
if ((x == sx || x == ex) && (y == sy || y == ey)) {
/* big explosion in each corner, or small explosion for single tiles */
CreateEffectVehicleAbove(x * TILE_SIZE + TILE_SIZE / 2, y * TILE_SIZE + TILE_SIZE / 2, 2,
sy == ey && sx == ex ? EV_EXPLOSION_SMALL : EV_EXPLOSION_LARGE
);
}
}
cost.AddCost(ret);
}
}
return (success) ? cost : CMD_ERROR;
}
TileIndex _cur_tileloop_tile;
#define TILELOOP_BITS 4
#define TILELOOP_SIZE (1 << TILELOOP_BITS)
#define TILELOOP_ASSERTMASK ((TILELOOP_SIZE - 1) + ((TILELOOP_SIZE - 1) << MapLogX()))
#define TILELOOP_CHKMASK (((1 << (MapLogX() - TILELOOP_BITS))-1) << TILELOOP_BITS)
void RunTileLoop()
{
TileIndex tile = _cur_tileloop_tile;
assert((tile & ~TILELOOP_ASSERTMASK) == 0);
uint count = (MapSizeX() / TILELOOP_SIZE) * (MapSizeY() / TILELOOP_SIZE);
do {
_tile_type_procs[GetTileType(tile)]->tile_loop_proc(tile);
if (TileX(tile) < MapSizeX() - TILELOOP_SIZE) {
tile += TILELOOP_SIZE; // no overflow
} else {
tile = TILE_MASK(tile - TILELOOP_SIZE * (MapSizeX() / TILELOOP_SIZE - 1) + TileDiffXY(0, TILELOOP_SIZE)); // x would overflow, also increase y
}
} while (--count != 0);
assert((tile & ~TILELOOP_ASSERTMASK) == 0);
tile += 9;
if (tile & TILELOOP_CHKMASK) {
tile = (tile + MapSizeX()) & TILELOOP_ASSERTMASK;
}
_cur_tileloop_tile = tile;
}
void InitializeLandscape()
{
uint maxx = MapMaxX();
uint maxy = MapMaxY();
uint sizex = MapSizeX();
uint y;
for (y = _settings_game.construction.freeform_edges ? 1 : 0; y < maxy; y++) {
uint x;
for (x = _settings_game.construction.freeform_edges ? 1 : 0; x < maxx; x++) {
MakeClear(sizex * y + x, CLEAR_GRASS, 3);
SetTileHeight(sizex * y + x, 0);
SetTropicZone(sizex * y + x, TROPICZONE_NORMAL);
ClearBridgeMiddle(sizex * y + x);
}
MakeVoid(sizex * y + x);
}
for (uint x = 0; x < sizex; x++) MakeVoid(sizex * y + x);
}
static const byte _genterrain_tbl_1[5] = { 10, 22, 33, 37, 4 };
static const byte _genterrain_tbl_2[5] = { 0, 0, 0, 0, 33 };
static void GenerateTerrain(int type, uint flag)
{
uint32 r = Random();
const Sprite *templ = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + 4845, ST_MAPGEN);
uint x = r & MapMaxX();
uint y = (r >> MapLogX()) & MapMaxY();
if (x < 2 || y < 2) return;
DiagDirection direction = (DiagDirection)GB(r, 22, 2);
uint w = templ->width;
uint h = templ->height;
if (DiagDirToAxis(direction) == AXIS_Y) Swap(w, h);
const byte *p = templ->data;
if ((flag & 4) != 0) {
uint xw = x * MapSizeY();
uint yw = y * MapSizeX();
uint bias = (MapSizeX() + MapSizeY()) * 16;
switch (flag & 3) {
default: NOT_REACHED();
case 0:
if (xw + yw > MapSize() - bias) return;
break;
case 1:
if (yw < xw + bias) return;
break;
case 2:
if (xw + yw < MapSize() + bias) return;
break;
case 3:
if (xw < yw + bias) return;
break;
}
}
if (x + w >= MapMaxX() - 1) return;
if (y + h >= MapMaxY() - 1) return;
Tile *tile = &_m[TileXY(x, y)];
switch (direction) {
default: NOT_REACHED();
case DIAGDIR_NE:
do {
Tile *tile_cur = tile;
for (uint w_cur = w; w_cur != 0; --w_cur) {
if (GB(*p, 0, 4) >= tile_cur->type_height) tile_cur->type_height = GB(*p, 0, 4);
p++;
tile_cur++;
}
tile += TileDiffXY(0, 1);
} while (--h != 0);
break;
case DIAGDIR_SE:
do {
Tile *tile_cur = tile;
for (uint h_cur = h; h_cur != 0; --h_cur) {
if (GB(*p, 0, 4) >= tile_cur->type_height) tile_cur->type_height = GB(*p, 0, 4);
p++;
tile_cur += TileDiffXY(0, 1);
}
tile += TileDiffXY(1, 0);
} while (--w != 0);
break;
case DIAGDIR_SW:
tile += TileDiffXY(w - 1, 0);
do {
Tile *tile_cur = tile;
for (uint w_cur = w; w_cur != 0; --w_cur) {
if (GB(*p, 0, 4) >= tile_cur->type_height) tile_cur->type_height = GB(*p, 0, 4);
p++;
tile_cur--;
}
tile += TileDiffXY(0, 1);
} while (--h != 0);
break;
case DIAGDIR_NW:
tile += TileDiffXY(0, h - 1);
do {
Tile *tile_cur = tile;
for (uint h_cur = h; h_cur != 0; --h_cur) {
if (GB(*p, 0, 4) >= tile_cur->type_height) tile_cur->type_height = GB(*p, 0, 4);
p++;
tile_cur -= TileDiffXY(0, 1);
}
tile += TileDiffXY(1, 0);
} while (--w != 0);
break;
}
}
#include "table/genland.h"
static void CreateDesertOrRainForest()
{
TileIndex update_freq = MapSize() / 4;
const TileIndexDiffC *data;
for (TileIndex tile = 0; tile != MapSize(); ++tile) {
if ((tile % update_freq) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
for (data = _make_desert_or_rainforest_data;
data != endof(_make_desert_or_rainforest_data); ++data) {
TileIndex t = AddTileIndexDiffCWrap(tile, *data);
if (t != INVALID_TILE && (TileHeight(t) >= 4 || IsTileType(t, MP_WATER))) break;
}
if (data == endof(_make_desert_or_rainforest_data))
SetTropicZone(tile, TROPICZONE_DESERT);
}
for (uint i = 0; i != 256; i++) {
if ((i % 64) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
RunTileLoop();
}
for (TileIndex tile = 0; tile != MapSize(); ++tile) {
if ((tile % update_freq) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
for (data = _make_desert_or_rainforest_data;
data != endof(_make_desert_or_rainforest_data); ++data) {
TileIndex t = AddTileIndexDiffCWrap(tile, *data);
if (t != INVALID_TILE && IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_DESERT)) break;
}
if (data == endof(_make_desert_or_rainforest_data))
SetTropicZone(tile, TROPICZONE_RAINFOREST);
}
}
void GenerateLandscape(byte mode)
{
static const int gwp_desert_amount = 4 + 8;
if (mode == GW_HEIGHTMAP) {
SetGeneratingWorldProgress(GWP_LANDSCAPE, (_settings_game.game_creation.landscape == LT_TROPIC) ? 1 + gwp_desert_amount : 1);
LoadHeightmap(_file_to_saveload.name);
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
} else if (_settings_game.game_creation.land_generator == LG_TERRAGENESIS) {
SetGeneratingWorldProgress(GWP_LANDSCAPE, (_settings_game.game_creation.landscape == LT_TROPIC) ? 3 + gwp_desert_amount : 3);
GenerateTerrainPerlin();
} else {
if (_settings_game.construction.freeform_edges) {
for (uint x = 0; x < MapSizeX(); x++) MakeVoid(TileXY(x, 0));
for (uint y = 0; y < MapSizeY(); y++) MakeVoid(TileXY(0, y));
}
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC: {
SetGeneratingWorldProgress(GWP_LANDSCAPE, 2);
uint32 r = Random();
for (uint i = ScaleByMapSize(GB(r, 0, 7) + 950); i != 0; --i) {
GenerateTerrain(2, 0);
}
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
uint flag = GB(r, 7, 2) | 4;
for (uint i = ScaleByMapSize(GB(r, 9, 7) + 450); i != 0; --i) {
GenerateTerrain(4, flag);
}
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
} break;
case LT_TROPIC: {
SetGeneratingWorldProgress(GWP_LANDSCAPE, 3 + gwp_desert_amount);
uint32 r = Random();
for (uint i = ScaleByMapSize(GB(r, 0, 7) + 170); i != 0; --i) {
GenerateTerrain(0, 0);
}
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
uint flag = GB(r, 7, 2) | 4;
for (uint i = ScaleByMapSize(GB(r, 9, 8) + 1700); i != 0; --i) {
GenerateTerrain(0, flag);
}
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
flag ^= 2;
for (uint i = ScaleByMapSize(GB(r, 17, 7) + 410); i != 0; --i) {
GenerateTerrain(3, flag);
}
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
} break;
default: {
SetGeneratingWorldProgress(GWP_LANDSCAPE, 1);
uint32 r = Random();
uint i = ScaleByMapSize(GB(r, 0, 7) + (3 - _settings_game.difficulty.quantity_sea_lakes) * 256 + 100);
for (; i != 0; --i) {
GenerateTerrain(_settings_game.difficulty.terrain_type, 0);
}
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
} break;
}
}
FixSlopes();
ConvertGroundTilesIntoWaterTiles();
if (_settings_game.game_creation.landscape == LT_TROPIC) CreateDesertOrRainForest();
}
void OnTick_Town();
void OnTick_Trees();
void OnTick_Station();
void OnTick_Industry();
void OnTick_Companies();
void OnTick_Train();
void CallLandscapeTick()
{
OnTick_Town();
OnTick_Trees();
OnTick_Station();
OnTick_Industry();
OnTick_Companies();
OnTick_Train();
}
| 27,189
|
C++
|
.cpp
| 798
| 31.112782
| 145
| 0.661826
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,097
|
animated_tile.cpp
|
EnergeticBark_OpenTTD-3DS/src/animated_tile.cpp
|
/* $Id$ */
/** @file animated_tile.cpp Everything related to animated tiles. */
#include "stdafx.h"
#include "core/alloc_func.hpp"
#include "functions.h"
/** The table/list with animated tiles. */
TileIndex *_animated_tile_list = NULL;
/** The number of animated tiles in the current state. */
uint _animated_tile_count = 0;
/** The number of slots for animated tiles allocated currently. */
uint _animated_tile_allocated = 0;
/**
* Removes the given tile from the animated tile table.
* @param tile the tile to remove
*/
void DeleteAnimatedTile(TileIndex tile)
{
for (TileIndex *ti = _animated_tile_list; ti < _animated_tile_list + _animated_tile_count; ti++) {
if (tile == *ti) {
/* Remove the hole
* The order of the remaining elements must stay the same, otherwise the animation loop
* may miss a tile; that's why we must use memmove instead of just moving the last element.
*/
memmove(ti, ti + 1, (_animated_tile_list + _animated_tile_count - (ti + 1)) * sizeof(*ti));
_animated_tile_count--;
MarkTileDirtyByTile(tile);
return;
}
}
}
/**
* Add the given tile to the animated tile table (if it does not exist
* on that table yet). Also increases the size of the table if necessary.
* @param tile the tile to make animated
*/
void AddAnimatedTile(TileIndex tile)
{
MarkTileDirtyByTile(tile);
for (const TileIndex *ti = _animated_tile_list; ti < _animated_tile_list + _animated_tile_count; ti++) {
if (tile == *ti) return;
}
/* Table not large enough, so make it larger */
if (_animated_tile_count == _animated_tile_allocated) {
_animated_tile_allocated *= 2;
_animated_tile_list = ReallocT<TileIndex>(_animated_tile_list, _animated_tile_allocated);
}
_animated_tile_list[_animated_tile_count] = tile;
_animated_tile_count++;
}
/**
* Animate all tiles in the animated tile list, i.e.\ call AnimateTile on them.
*/
void AnimateAnimatedTiles()
{
const TileIndex *ti = _animated_tile_list;
while (ti < _animated_tile_list + _animated_tile_count) {
const TileIndex curr = *ti;
AnimateTile(curr);
/* During the AnimateTile call, DeleteAnimatedTile could have been called,
* deleting an element we've already processed and pushing the rest one
* slot to the left. We can detect this by checking whether the index
* in the current slot has changed - if it has, an element has been deleted,
* and we should process the current slot again instead of going forward.
* NOTE: this will still break if more than one animated tile is being
* deleted during the same AnimateTile call, but no code seems to
* be doing this anyway.
*/
if (*ti == curr) ++ti;
}
}
/**
* Initialize all animated tile variables to some known begin point
*/
void InitializeAnimatedTiles()
{
_animated_tile_list = ReallocT<TileIndex>(_animated_tile_list, 256);
_animated_tile_count = 0;
_animated_tile_allocated = 256;
}
| 2,901
|
C++
|
.cpp
| 79
| 34.379747
| 105
| 0.716927
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
1,539,099
|
music_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/music_gui.cpp
|
/* $Id$ */
/** @file music_gui.cpp GUI for the music playback. */
#include "stdafx.h"
#include "openttd.h"
#include "fileio_func.h"
#include "music.h"
#include "music/music_driver.hpp"
#include "window_gui.h"
#include "strings_func.h"
#include "window_func.h"
#include "sound_func.h"
#include "gfx_func.h"
#include "core/math_func.hpp"
#include "core/random_func.hpp"
#include "table/strings.h"
#include "table/sprites.h"
static byte _music_wnd_cursong;
static bool _song_is_active;
static byte _cur_playlist[NUM_SONGS_PLAYLIST];
static byte _playlist_all[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 0
};
static byte _playlist_old_style[] = {
1, 8, 2, 9, 14, 15, 19, 13, 0
};
static byte _playlist_new_style[] = {
6, 11, 10, 17, 21, 18, 5, 0
};
static byte _playlist_ezy_street[] = {
12, 7, 16, 3, 20, 4, 0
};
static byte * const _playlists[] = {
_playlist_all,
_playlist_old_style,
_playlist_new_style,
_playlist_ezy_street,
msf.custom_1,
msf.custom_2,
};
static void SkipToPrevSong()
{
byte *b = _cur_playlist;
byte *p = b;
byte t;
if (b[0] == 0) return; // empty playlist
do p++; while (p[0] != 0); // find the end
t = *--p; // and copy the bytes
while (p != b) {
p--;
p[1] = p[0];
}
*b = t;
_song_is_active = false;
}
static void SkipToNextSong()
{
byte *b = _cur_playlist;
byte t;
t = b[0];
if (t != 0) {
while (b[1] != 0) {
b[0] = b[1];
b++;
}
b[0] = t;
}
_song_is_active = false;
}
static void MusicVolumeChanged(byte new_vol)
{
_music_driver->SetVolume(new_vol);
}
static void DoPlaySong()
{
char filename[MAX_PATH];
FioFindFullPath(filename, lengthof(filename), GM_DIR,
_origin_songs_specs[_music_wnd_cursong - 1].filename);
_music_driver->PlaySong(filename);
}
static void DoStopMusic()
{
_music_driver->StopSong();
}
static void SelectSongToPlay()
{
uint i = 0;
uint j = 0;
memset(_cur_playlist, 0, sizeof(_cur_playlist));
do {
/* We are now checking for the existence of that file prior
* to add it to the list of available songs */
if (FioCheckFileExists(_origin_songs_specs[_playlists[msf.playlist][i] - 1].filename, GM_DIR)) {
_cur_playlist[j] = _playlists[msf.playlist][i];
j++;
}
} while (_playlists[msf.playlist][++i] != 0 && j < lengthof(_cur_playlist) - 1);
/* Do not shuffle when on the intro-start window, as the song to play has to be the original TTD Theme*/
if (msf.shuffle && _game_mode != GM_MENU) {
i = 500;
do {
uint32 r = InteractiveRandom();
byte *a = &_cur_playlist[GB(r, 0, 5)];
byte *b = &_cur_playlist[GB(r, 8, 5)];
if (*a != 0 && *b != 0) {
byte t = *a;
*a = *b;
*b = t;
}
} while (--i);
}
}
static void StopMusic()
{
_music_wnd_cursong = 0;
DoStopMusic();
_song_is_active = false;
InvalidateWindowWidget(WC_MUSIC_WINDOW, 0, 9);
}
static void PlayPlaylistSong()
{
if (_cur_playlist[0] == 0) {
SelectSongToPlay();
/* if there is not songs in the playlist, it may indicate
* no file on the gm folder, or even no gm folder.
* Stop the playback, then */
if (_cur_playlist[0] == 0) {
_song_is_active = false;
_music_wnd_cursong = 0;
msf.playing = false;
return;
}
}
_music_wnd_cursong = _cur_playlist[0];
DoPlaySong();
_song_is_active = true;
InvalidateWindowWidget(WC_MUSIC_WINDOW, 0, 9);
}
void ResetMusic()
{
_music_wnd_cursong = 1;
DoPlaySong();
}
void MusicLoop()
{
if (!msf.playing && _song_is_active) {
StopMusic();
} else if (msf.playing && !_song_is_active) {
PlayPlaylistSong();
}
if (!_song_is_active) return;
if (!_music_driver->IsSongPlaying()) {
if (_game_mode != GM_MENU) {
StopMusic();
SkipToNextSong();
PlayPlaylistSong();
} else {
ResetMusic();
}
}
}
struct MusicTrackSelectionWindow : public Window {
private:
enum MusicTrackSelectionWidgets {
MTSW_CLOSE,
MTSW_CAPTION,
MTSW_BACKGROUND,
MTSW_LIST_LEFT,
MTSW_LIST_RIGHT,
MTSW_ALL,
MTSW_OLD,
MTSW_NEW,
MTSW_EZY,
MTSW_CUSTOM1,
MTSW_CUSTOM2,
MTSW_CLEAR,
MTSW_SAVE,
};
public:
MusicTrackSelectionWindow(const WindowDesc *desc, WindowNumber number) : Window(desc, number)
{
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
const byte *p;
uint i;
int y;
this->SetWidgetDisabledState(MTSW_CLEAR, msf.playlist <= 3);
this->LowerWidget(MTSW_LIST_LEFT);
this->LowerWidget(MTSW_LIST_RIGHT);
this->DrawWidgets();
GfxFillRect( 3, 23, 3 + 177, 23 + 191, 0);
GfxFillRect(251, 23, 251 + 177, 23 + 191, 0);
DrawStringCentered(92, 15, STR_01EE_TRACK_INDEX, TC_FROMSTRING);
SetDParam(0, STR_01D5_ALL + msf.playlist);
DrawStringCentered(340, 15, STR_01EF_PROGRAM, TC_FROMSTRING);
for (i = 1; i <= NUM_SONGS_AVAILABLE; i++) {
SetDParam(0, i);
SetDParam(2, i);
SetDParam(1, SPECSTR_SONGNAME);
DrawString(4, 23 + (i - 1) * 6, (i < 10) ? STR_01EC_0 : STR_01ED, TC_FROMSTRING);
}
for (i = 0; i != 6; i++) {
DrawStringCentered(216, 45 + i * 8, STR_01D5_ALL + i, (i == msf.playlist) ? TC_WHITE : TC_BLACK);
}
DrawStringCentered(216, 45 + 8 * 6 + 16, STR_01F0_CLEAR, TC_FROMSTRING);
#if 0
DrawStringCentered(216, 45 + 8 * 6 + 16 * 2, STR_01F1_SAVE, TC_FROMSTRING);
#endif
y = 23;
for (p = _playlists[msf.playlist], i = 0; (i = *p) != 0; p++) {
SetDParam(0, i);
SetDParam(1, SPECSTR_SONGNAME);
SetDParam(2, i);
DrawString(252, y, (i < 10) ? STR_01EC_0 : STR_01ED, TC_FROMSTRING);
y += 6;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case MTSW_LIST_LEFT: { // add to playlist
int y = (pt.y - 23) / 6;
uint i;
byte *p;
if (msf.playlist < 4) return;
if (!IsInsideMM(y, 0, NUM_SONGS_AVAILABLE)) return;
p = _playlists[msf.playlist];
for (i = 0; i != NUM_SONGS_PLAYLIST - 1; i++) {
if (p[i] == 0) {
p[i] = y + 1;
p[i + 1] = 0;
this->SetDirty();
SelectSongToPlay();
break;
}
}
} break;
case MTSW_LIST_RIGHT: { // remove from playlist
int y = (pt.y - 23) / 6;
uint i;
byte *p;
if (msf.playlist < 4) return;
if (!IsInsideMM(y, 0, NUM_SONGS_AVAILABLE)) return;
p = _playlists[msf.playlist];
for (i = y; i != NUM_SONGS_PLAYLIST - 1; i++) {
p[i] = p[i + 1];
}
this->SetDirty();
SelectSongToPlay();
} break;
case MTSW_CLEAR: // clear
_playlists[msf.playlist][0] = 0;
this->SetDirty();
StopMusic();
SelectSongToPlay();
break;
#if 0
case MTSW_SAVE: // save
ShowInfo("MusicTrackSelectionWndProc:save not implemented");
break;
#endif
case MTSW_ALL: case MTSW_OLD: case MTSW_NEW:
case MTSW_EZY: case MTSW_CUSTOM1: case MTSW_CUSTOM2: // set playlist
msf.playlist = widget - MTSW_ALL;
this->SetDirty();
InvalidateWindow(WC_MUSIC_WINDOW, 0);
StopMusic();
SelectSongToPlay();
break;
}
}
};
static const Widget _music_track_selection_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // MTSW_CLOSE
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 431, 0, 13, STR_01EB_MUSIC_PROGRAM_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // MTSW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 431, 14, 217, 0x0, STR_NULL}, // MTSW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 181, 22, 215, 0x0, STR_01FA_CLICK_ON_MUSIC_TRACK_TO}, // MTSW_LIST_LEFT
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 250, 429, 22, 215, 0x0, STR_CLICK_ON_TRACK_TO_REMOVE}, // MTSW_LIST_RIGHT
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 186, 245, 44, 51, 0x0, STR_01F3_SELECT_ALL_TRACKS_PROGRAM}, // MTSW_ALL
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 186, 245, 52, 59, 0x0, STR_01F4_SELECT_OLD_STYLE_MUSIC}, // MTSW_OLD
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 186, 245, 60, 67, 0x0, STR_01F5_SELECT_NEW_STYLE_MUSIC}, // MTSW_NEW
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 186, 245, 68, 75, 0x0, STR_0330_SELECT_EZY_STREET_STYLE}, // MTSW_EZY
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 186, 245, 76, 83, 0x0, STR_01F6_SELECT_CUSTOM_1_USER_DEFINED}, // MTSW_CUSTOM1
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 186, 245, 84, 91, 0x0, STR_01F7_SELECT_CUSTOM_2_USER_DEFINED}, // MTSW_CUSTOM2
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 186, 245, 108, 115, 0x0, STR_01F8_CLEAR_CURRENT_PROGRAM_CUSTOM1}, // MTSW_CLEAR
#if 0
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 186, 245, 124, 131, 0x0, STR_01F9_SAVE_MUSIC_SETTINGS}, // MTSW_SAVE
#endif
{ WIDGETS_END},
};
static const WindowDesc _music_track_selection_desc(
104, 131, 432, 218, 432, 218,
WC_MUSIC_TRACK_SELECTION, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_music_track_selection_widgets
);
static void ShowMusicTrackSelection()
{
AllocateWindowDescFront<MusicTrackSelectionWindow>(&_music_track_selection_desc, 0);
}
struct MusicWindow : public Window {
private:
enum MusicWidgets {
MW_CLOSE,
MW_CAPTION,
MW_PREV,
MW_NEXT,
MW_STOP,
MW_PLAY,
MW_SLIDERS,
MW_GAUGE,
MW_BACKGROUND,
MW_INFO,
MW_SHUFFLE,
MW_PROGRAMME,
MW_ALL,
MW_OLD,
MW_NEW,
MW_EZY,
MW_CUSTOM1,
MW_CUSTOM2,
};
public:
MusicWindow(const WindowDesc *desc, WindowNumber number) : Window(desc, number)
{
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
uint i;
StringID str;
this->RaiseWidget(MW_GAUGE);
this->RaiseWidget(MW_INFO);
this->DrawWidgets();
GfxFillRect(187, 16, 200, 33, 0);
for (i = 0; i != 8; i++) {
int colour = 0xD0;
if (i > 4) {
colour = 0xBF;
if (i > 6) {
colour = 0xB8;
}
}
GfxFillRect(187, NUM_SONGS_PLAYLIST - i * 2, 200, NUM_SONGS_PLAYLIST - i * 2, colour);
}
GfxFillRect(60, 46, 239, 52, 0);
if (_song_is_active == 0 || _music_wnd_cursong == 0) {
str = STR_01E3;
} else {
SetDParam(0, _music_wnd_cursong);
str = (_music_wnd_cursong < 10) ? STR_01E4_0 : STR_01E5;
}
DrawString(62, 46, str, TC_FROMSTRING);
str = STR_01E6;
if (_song_is_active != 0 && _music_wnd_cursong != 0) {
str = STR_01E7;
SetDParam(0, SPECSTR_SONGNAME);
SetDParam(1, _music_wnd_cursong);
}
DrawStringCentered(155, 46, str, TC_FROMSTRING);
DrawString(60, 38, STR_01E8_TRACK_XTITLE, TC_FROMSTRING);
for (i = 0; i != 6; i++) {
DrawStringCentered(25 + i * 50, 59, STR_01D5_ALL + i, msf.playlist == i ? TC_WHITE : TC_BLACK);
}
DrawStringCentered( 31, 43, STR_01E9_SHUFFLE, (msf.shuffle ? TC_WHITE : TC_BLACK));
DrawStringCentered(269, 43, STR_01EA_PROGRAM, TC_FROMSTRING);
DrawStringCentered(141, 15, STR_01DB_MUSIC_VOLUME, TC_FROMSTRING);
DrawStringCentered(141, 29, STR_01DD_MIN_MAX, TC_FROMSTRING);
DrawStringCentered(247, 15, STR_01DC_EFFECTS_VOLUME, TC_FROMSTRING);
DrawStringCentered(247, 29, STR_01DD_MIN_MAX, TC_FROMSTRING);
DrawFrameRect(108, 23, 174, 26, COLOUR_GREY, FR_LOWERED);
DrawFrameRect(214, 23, 280, 26, COLOUR_GREY, FR_LOWERED);
DrawFrameRect(
108 + msf.music_vol / 2, 22, 111 + msf.music_vol / 2, 28, COLOUR_GREY, FR_NONE
);
DrawFrameRect(
214 + msf.effect_vol / 2, 22, 217 + msf.effect_vol / 2, 28, COLOUR_GREY, FR_NONE
);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case MW_PREV: // skip to prev
if (!_song_is_active) return;
SkipToPrevSong();
break;
case MW_NEXT: // skip to next
if (!_song_is_active) return;
SkipToNextSong();
break;
case MW_STOP: // stop playing
msf.playing = false;
break;
case MW_PLAY: // start playing
msf.playing = true;
break;
case MW_SLIDERS: { // volume sliders
byte *vol, new_vol;
int x = pt.x - 88;
if (x < 0) return;
vol = &msf.music_vol;
if (x >= 106) {
vol = &msf.effect_vol;
x -= 106;
}
new_vol = min(max(x - 21, 0) * 2, 127);
if (new_vol != *vol) {
*vol = new_vol;
if (vol == &msf.music_vol) MusicVolumeChanged(new_vol);
this->SetDirty();
}
_left_button_clicked = false;
} break;
case MW_SHUFFLE: // toggle shuffle
msf.shuffle ^= 1;
StopMusic();
SelectSongToPlay();
break;
case MW_PROGRAMME: // show track selection
ShowMusicTrackSelection();
break;
case MW_ALL: case MW_OLD: case MW_NEW:
case MW_EZY: case MW_CUSTOM1: case MW_CUSTOM2: // playlist
msf.playlist = widget - MW_ALL;
this->SetDirty();
InvalidateWindow(WC_MUSIC_TRACK_SELECTION, 0);
StopMusic();
SelectSongToPlay();
break;
}
}
#if 0
virtual void OnTick()
{
this->InvalidateWidget(MW_GAUGE);
}
#endif
};
static const Widget _music_window_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // MW_CLOSE
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 299, 0, 13, STR_01D2_JAZZ_JUKEBOX, STR_018C_WINDOW_TITLE_DRAG_THIS}, // MW_CAPTION
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 21, 14, 35, SPR_IMG_SKIP_TO_PREV, STR_01DE_SKIP_TO_PREVIOUS_TRACK}, // MW_PREV
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 22, 43, 14, 35, SPR_IMG_SKIP_TO_NEXT, STR_01DF_SKIP_TO_NEXT_TRACK_IN_SELECTION}, // MW_NEXT
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 44, 65, 14, 35, SPR_IMG_STOP_MUSIC, STR_01E0_STOP_PLAYING_MUSIC}, // MW_STOP
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 66, 87, 14, 35, SPR_IMG_PLAY_MUSIC, STR_01E1_START_PLAYING_MUSIC}, // MW_PLAY
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 88, 299, 14, 35, 0x0, STR_01E2_DRAG_SLIDERS_TO_SET_MUSIC}, // MW_SLIDERS
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 186, 201, 15, 34, 0x0, STR_NULL}, // MW_GAUGE
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 299, 36, 57, 0x0, STR_NULL}, // MW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 59, 240, 45, 53, 0x0, STR_NULL}, // MW_INFO
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 6, 55, 42, 49, 0x0, STR_01FB_TOGGLE_PROGRAM_SHUFFLE}, // MW_SHUFFLE
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 244, 293, 42, 49, 0x0, STR_01FC_SHOW_MUSIC_TRACK_SELECTION}, // MW_PROGRAMME
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 0, 49, 58, 65, 0x0, STR_01F3_SELECT_ALL_TRACKS_PROGRAM}, // MW_ALL
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 50, 99, 58, 65, 0x0, STR_01F4_SELECT_OLD_STYLE_MUSIC}, // MW_OLD
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 100, 149, 58, 65, 0x0, STR_01F5_SELECT_NEW_STYLE_MUSIC}, // MW_NEW
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 150, 199, 58, 65, 0x0, STR_0330_SELECT_EZY_STREET_STYLE}, // MW_EZY
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 200, 249, 58, 65, 0x0, STR_01F6_SELECT_CUSTOM_1_USER_DEFINED}, // MW_CUSTOM1
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 250, 299, 58, 65, 0x0, STR_01F7_SELECT_CUSTOM_2_USER_DEFINED}, // MW_CUSTOM2
{ WIDGETS_END},
};
static const WindowDesc _music_window_desc(
0, 22, 300, 66, 300, 66,
WC_MUSIC_WINDOW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_music_window_widgets
);
void ShowMusicWindow()
{
AllocateWindowDescFront<MusicWindow>(&_music_window_desc, 0);
}
| 16,250
|
C++
|
.cpp
| 470
| 31.574468
| 168
| 0.601045
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,100
|
newgrf_station.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_station.cpp
|
/* $Id$ */
/** @file newgrf_station.cpp Functions for dealing with station classes and custom stations. */
#include "stdafx.h"
#include "variables.h"
#include "landscape.h"
#include "debug.h"
#include "station_map.h"
#include "newgrf_commons.h"
#include "newgrf_station.h"
#include "newgrf_spritegroup.h"
#include "newgrf_sound.h"
#include "town.h"
#include "newgrf_town.h"
#include "gfx_func.h"
#include "date_func.h"
#include "company_func.h"
#include "animated_tile_func.h"
#include "functions.h"
#include "tunnelbridge_map.h"
#include "spritecache.h"
#include "table/strings.h"
static StationClass _station_classes[STAT_CLASS_MAX];
enum {
MAX_SPECLIST = 255,
};
/**
* 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()
{
for (StationClassID i = STAT_CLASS_BEGIN; 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 = MallocT<StationSpec*>(1);
_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 = MallocT<StationSpec*>(1);
_station_classes[1].spec[0] = NULL;
}
/**
* Allocate a station class for the given class id.
* @param cls A 32 bit value identifying the class.
* @return Index into _station_classes of allocated class.
*/
StationClassID AllocateStationClass(uint32 cls)
{
for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
if (_station_classes[i].id == cls) {
/* 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 = cls;
return i;
}
}
grfmsg(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;
}
/**
* Get the number of station classes in use.
* @return Number of station classes.
*/
uint GetNumStationClasses()
{
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 statspec The station spec.
*/
void SetCustomStationSpec(StationSpec *statspec)
{
StationClass *station_class;
int i;
/* If the station has already been allocated, don't reallocate it. */
if (statspec->allocated) return;
assert(statspec->sclass < STAT_CLASS_MAX);
station_class = &_station_classes[statspec->sclass];
i = station_class->stations++;
station_class->spec = ReallocT(station_class->spec, station_class->stations);
station_class->spec[i] = statspec;
statspec->allocated = true;
}
/**
* 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;
}
/**
* Retrieve a station spec by GRF location.
* @param grfid GRF ID of station spec.
* @param localidx Index within GRF file of station spec.
* @param index Pointer to return the index of the station spec in its station class. If NULL then not used.
* @return The station spec.
*/
const StationSpec *GetCustomStationSpecByGrf(uint32 grfid, byte localidx, int *index)
{
uint j;
for (StationClassID i = STAT_CLASS_BEGIN; 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->grffile->grfid == grfid && statspec->localidx == localidx) {
if (index != NULL) *index = j;
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) {
Swap(platforms, length);
Swap(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, y & 0xF);
SB(retval, 4, 4, x & 0xF);
} 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 (!IsRailWaypointTile(new_tile)) 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);
}
static uint32 GetRailContinuationInfo(TileIndex tile)
{
/* Tile offsets and exit dirs for X axis */
static const Direction x_dir[8] = { DIR_SW, DIR_NE, DIR_SE, DIR_NW, DIR_S, DIR_E, DIR_W, DIR_N };
static const DiagDirection x_exits[8] = { DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SW, DIAGDIR_NE };
/* Tile offsets and exit dirs for Y axis */
static const Direction y_dir[8] = { DIR_SE, DIR_NW, DIR_SW, DIR_NE, DIR_S, DIR_W, DIR_E, DIR_N };
static const DiagDirection y_exits[8] = { DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SE, DIAGDIR_NW };
Axis axis = IsTileType(tile, MP_RAILWAY) ? GetWaypointAxis(tile) : GetRailStationAxis(tile);
/* Choose appropriate lookup table to use */
const Direction *dir = axis == AXIS_X ? x_dir : y_dir;
const DiagDirection *diagdir = axis == AXIS_X ? x_exits : y_exits;
uint32 res = 0;
uint i;
for (i = 0; i < lengthof(x_dir); i++, dir++, diagdir++) {
TileIndex neighbour_tile = tile + TileOffsByDir(*dir);
TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(neighbour_tile, TRANSPORT_RAIL, 0));
if (trackbits != TRACK_BIT_NONE) {
/* If there is any track on the tile, set the bit in the second byte */
SetBit(res, i + 8);
/* With tunnels and bridges the tile has tracks, but they are not necessarily connected
* with the next tile because the ramp is not going in the right direction. */
if (IsTileType(neighbour_tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(neighbour_tile) != *diagdir) {
continue;
}
/* If any track reaches our exit direction, set the bit in the lower byte */
if (trackbits & DiagdirReachesTracks(*diagdir)) SetBit(res, i);
}
}
return res;
}
/* 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;
}
/**
* Station variable cache
* This caches 'expensive' station variable lookups which iterate over
* several tiles that may be called multiple times per Resolve().
*/
static struct {
uint32 v40;
uint32 v41;
uint32 v45;
uint32 v46;
uint32 v47;
uint32 v49;
uint8 valid;
} _svc;
static uint32 StationGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
{
const Station *st = object->u.station.st;
TileIndex tile = object->u.station.tile;
if (object->scope == VSG_SCOPE_PARENT) {
/* Pass the request on to the town of the station */
const Town *t;
if (st != NULL) {
t = st->town;
} else if (tile != INVALID_TILE) {
t = ClosestTownFromTile(tile, UINT_MAX);
} else {
*available = false;
return UINT_MAX;
}
return TownGetVariable(variable, parameter, available, t);
}
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_company; // Station owner
case 0x44: return 2; // PBS status
case 0xFA: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value
}
*available = false;
return UINT_MAX;
}
switch (variable) {
/* Calculated station variables */
case 0x40:
if (!HasBit(_svc.valid, 0)) { _svc.v40 = GetPlatformInfoHelper(tile, false, false, false); SetBit(_svc.valid, 0); }
return _svc.v40;
case 0x41:
if (!HasBit(_svc.valid, 1)) { _svc.v41 = GetPlatformInfoHelper(tile, true, false, false); SetBit(_svc.valid, 1); }
return _svc.v41;
case 0x42: return GetTerrainType(tile) | (GetRailType(tile) << 8);
case 0x43: return st->owner; // Station owner
case 0x44:
if (IsRailWaypointTile(tile)) {
return GetDepotWaypointReservation(tile) ? 7 : 4;
} else {
return GetRailwayStationReservation(tile) ? 7 : 4; // PBS status
}
case 0x45:
if (!HasBit(_svc.valid, 2)) { _svc.v45 = GetRailContinuationInfo(tile); SetBit(_svc.valid, 2); }
return _svc.v45;
case 0x46:
if (!HasBit(_svc.valid, 3)) { _svc.v46 = GetPlatformInfoHelper(tile, false, false, true); SetBit(_svc.valid, 3); }
return _svc.v46;
case 0x47:
if (!HasBit(_svc.valid, 4)) { _svc.v47 = GetPlatformInfoHelper(tile, true, false, true); SetBit(_svc.valid, 4); }
return _svc.v47;
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].acceptance_pickup, GoodsEntry::PICKUP)) SetBit(value, cargo_type);
}
return value;
}
case 0x49:
if (!HasBit(_svc.valid, 5)) { _svc.v49 = GetPlatformInfoHelper(tile, false, true, false); SetBit(_svc.valid, 5); }
return _svc.v49;
case 0x4A: // Animation frame of tile
return GetStationAnimationFrame(tile);
/* Variables which use the parameter */
/* Variables 0x60 to 0x65 are handled separately below */
case 0x66: // Animation frame of nearby tile
if (parameter != 0) tile = GetNearbyTile(parameter, tile);
return st->TileBelongsToRailStation(tile) ? GetStationAnimationFrame(tile) : UINT_MAX;
case 0x67: { // Land info of nearby tile
Axis axis = GetRailStationAxis(tile);
if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
Slope tileh = GetTileSlope(tile, NULL);
bool swap = (axis == AXIS_Y && HasBit(tileh, SLOPE_W) != HasBit(tileh, SLOPE_E));
return GetNearbyTileInformation(tile) ^ (swap ? SLOPE_EW : 0);
}
case 0x68: { // Station info of nearby tiles
TileIndex nearby_tile = GetNearbyTile(parameter, tile);
if (!IsRailwayStationTile(nearby_tile)) return 0xFFFFFFFF;
uint32 grfid = st->speclist[GetCustomStationSpecIndex(tile)].grfid;
bool perpendicular = GetRailStationAxis(tile) != GetRailStationAxis(nearby_tile);
bool same_station = st->TileBelongsToRailStation(nearby_tile);
uint32 res = GB(GetStationGfx(nearby_tile), 1, 2) << 12 | !!perpendicular << 11 | !!same_station << 10;
if (IsCustomStationSpecIndex(nearby_tile)) {
const StationSpecList ssl = GetStationByTile(nearby_tile)->speclist[GetCustomStationSpecIndex(nearby_tile)];
res |= 1 << (ssl.grfid != grfid ? 9 : 8) | ssl.localidx;
}
return res;
}
/* 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 GB(st->airport_flags, 8, 8);
case 0xFA: return Clamp(st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
}
/* Handle cargo variables with parameter, 0x60 to 0x65 */
if (variable >= 0x60 && variable <= 0x65) {
CargoID c = GetCargoTranslation(parameter, object->u.station.statspec->grffile);
if (c == CT_INVALID) return 0;
const GoodsEntry *ge = &st->goods[c];
switch (variable) {
case 0x60: return min(ge->cargo.Count(), 4095);
case 0x61: return ge->days_since_pickup;
case 0x62: return ge->rating;
case 0x63: return ge->cargo.DaysInTransit();
case 0x64: return ge->last_speed | (ge->last_age << 8);
case 0x65: return GB(ge->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1) << 3;
}
}
/* 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->cargo.Count();
case 1: return GB(min(g->cargo.Count(), 4095), 0, 4) | (GB(g->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1) << 7);
case 2: return g->days_since_pickup;
case 3: return g->rating;
case 4: return g->cargo.Source();
case 5: return g->cargo.DaysInTransit();
case 6: return g->last_speed;
case 7: return g->last_age;
}
}
DEBUG(grf, 1, "Unhandled station property 0x%X", variable);
*available = false;
return UINT_MAX;
}
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 = object->u.station.cargo_type;
if (st == NULL || statspec->sclass == STAT_CLASS_WAYP) {
return group->g.real.loading[0];
}
switch (cargo_type) {
case CT_INVALID:
case CT_DEFAULT_NA:
case CT_PURCHASE:
cargo = 0;
break;
case CT_DEFAULT:
for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
cargo += st->goods[cargo_type].cargo.Count();
}
break;
default:
cargo = st->goods[cargo_type].cargo.Count();
break;
}
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) / (4096 - 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 = CBID_NO_CALLBACK;
res->callback_param1 = 0;
res->callback_param2 = 0;
res->last_value = 0;
res->trigger = 0;
res->reseed = 0;
res->count = 0;
res->grffile = (statspec != NULL ? statspec->grffile : NULL);
}
static const SpriteGroup *ResolveStation(ResolverObject *object)
{
const SpriteGroup *group;
CargoID ctype = CT_DEFAULT_NA;
if (object->u.station.st == NULL) {
/* No station, so we are in a purchase list */
ctype = CT_PURCHASE;
} else {
/* Pick the first cargo that we have waiting */
for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
const CargoSpec *cs = GetCargo(cargo);
if (cs->IsValid() && object->u.station.statspec->spritegroup[cargo] != NULL &&
!object->u.station.st->goods[cargo].cargo.Empty()) {
ctype = cargo;
break;
}
}
}
group = object->u.station.statspec->spritegroup[ctype];
if (group == NULL) {
ctype = CT_DEFAULT;
group = object->u.station.statspec->spritegroup[ctype];
}
if (group == NULL) return NULL;
/* Remember the cargo type we've picked */
object->u.station.cargo_type = ctype;
/* Invalidate all cached vars */
_svc.valid = 0;
return Resolve(group, object);
}
SpriteID GetCustomStationRelocation(const StationSpec *statspec, const Station *st, TileIndex tile)
{
const SpriteGroup *group;
ResolverObject object;
NewStationResolver(&object, statspec, st, tile);
group = ResolveStation(&object);
if (group == NULL || group->type != SGT_RESULT) return 0;
return group->g.result.sprite - 0x42D;
}
SpriteID GetCustomStationGroundRelocation(const StationSpec *statspec, const Station *st, TileIndex tile)
{
const SpriteGroup *group;
ResolverObject object;
NewStationResolver(&object, statspec, st, tile);
object.callback_param1 = 1; // Indicate we are resolving the ground sprite
group = ResolveStation(&object);
if (group == NULL || group->type != SGT_RESULT) return 0;
return group->g.result.sprite - 0x42D;
}
uint16 GetStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, const Station *st, TileIndex tile)
{
const SpriteGroup *group;
ResolverObject object;
NewStationResolver(&object, statspec, st, tile);
object.callback = callback;
object.callback_param1 = param1;
object.callback_param2 = param2;
group = ResolveStation(&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 statspec 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 || st == NULL) return 0;
for (i = 1; i < st->num_specs && i < MAX_SPECLIST; i++) {
if (st->speclist[i].spec == NULL && st->speclist[i].grfid == 0) break;
}
if (i == MAX_SPECLIST) {
/* As final effort when the spec list is already full...
* try to find the same spec and return that one. This might
* result in slighty "wrong" (as per specs) looking stations,
* but it's fairly unlikely that one reaches the limit anyways.
*/
for (i = 1; i < st->num_specs && i < MAX_SPECLIST; i++) {
if (st->speclist[i].spec == statspec) return i;
}
return -1;
}
if (exec) {
if (i >= st->num_specs) {
st->num_specs = i + 1;
st->speclist = ReallocT(st->speclist, st->num_specs);
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->grffile->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.
*/
void DeallocateSpecFromStation(Station *st, byte specindex)
{
/* specindex of 0 (default) is never freeable */
if (specindex == 0) return;
/* 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) {
return;
}
} END_TILE_LOOP(tile, st->trainst_w, st->trainst_h, st->train_tile)
/* This specindex is no longer in use, so deallocate it */
st->speclist[specindex].spec = NULL;
st->speclist[specindex].grfid = 0;
st->speclist[specindex].localidx = 0;
/* If this was the highest spec index, reallocate */
if (specindex == st->num_specs - 1) {
for (; st->speclist[st->num_specs - 1].grfid == 0 && st->num_specs > 1; st->num_specs--) {}
if (st->num_specs > 1) {
st->speclist = ReallocT(st->speclist, st->num_specs);
} else {
free(st->speclist);
st->num_specs = 0;
st->speclist = NULL;
st->cached_anim_triggers = 0;
return;
}
}
StationUpdateAnimTriggers(st);
}
/** Draw representation of a station tile for GUI purposes.
* @param x Position x of image.
* @param y Position y of image.
* @param axis Axis.
* @param railtype Rail type.
* @param sclass, station Type of station.
* @param station station ID
* @return True if the tile was drawn (allows for fallback to default graphic)
*/
bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID sclass, uint station)
{
const StationSpec *statspec;
const DrawTileSprites *sprites;
const DrawTileSeqStruct *seq;
const RailtypeInfo *rti = GetRailTypeInfo(railtype);
SpriteID relocation;
SpriteID image;
SpriteID palette = COMPANY_SPRITE_COLOUR(_local_company);
uint tile = 2;
statspec = GetCustomStationSpec(sclass, station);
if (statspec == NULL) return false;
relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE);
if (HasBit(statspec->callbackmask, CBM_STATION_SPRITE_LAYOUT)) {
uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0x2110000, 0, statspec, NULL, INVALID_TILE);
if (callback != CALLBACK_FAILED) tile = callback;
}
if (statspec->renderdata == NULL) {
sprites = GetStationTileLayout(STATION_RAIL, tile + axis);
} else {
sprites = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : (uint)axis];
}
image = sprites->ground.sprite;
SpriteID pal = sprites->ground.pal;
if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
image += GetCustomStationGroundRelocation(statspec, NULL, INVALID_TILE);
image += rti->custom_ground_offset;
} else {
image += rti->total_offset;
}
DrawSprite(image, GroundSpritePaletteTransform(image, pal, palette), x, y);
Point child_offset = {0, 0};
foreach_draw_tile_seq(seq, sprites->seq) {
image = seq->image.sprite;
if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
image += rti->total_offset;
} else {
image += relocation;
}
pal = SpriteLayoutPaletteTransform(image, seq->image.pal, palette);
if ((byte)seq->delta_z != 0x80) {
Point pt = RemapCoords(seq->delta_x, seq->delta_y, seq->delta_z);
DrawSprite(image, pal, x + pt.x, y + pt.y);
const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
child_offset.x = pt.x + spr->x_offs;
child_offset.y = pt.y + spr->y_offs;
} else {
/* For stations and original spritelayouts delta_x and delta_y are signed */
DrawSprite(image, pal, x + child_offset.x + seq->delta_x, y + child_offset.y + seq->delta_y);
}
}
return true;
}
const StationSpec *GetStationSpec(TileIndex t)
{
const Station *st;
uint specindex;
if (!IsCustomStationSpecIndex(t)) return NULL;
st = GetStationByTile(t);
specindex = GetCustomStationSpecIndex(t);
return specindex < st->num_specs ? st->speclist[specindex].spec : NULL;
}
/* Check if a rail station tile is traversable.
* XXX This could be cached (during build) in the map array to save on all the dereferencing */
bool IsStationTileBlocked(TileIndex tile)
{
const StationSpec *statspec = GetStationSpec(tile);
return statspec != NULL && HasBit(statspec->blocked, GetStationGfx(tile));
}
/* Check if a rail station tile is electrifiable.
* XXX This could be cached (during build) in the map array to save on all the dereferencing */
bool IsStationTileElectrifiable(TileIndex tile)
{
const StationSpec *statspec = GetStationSpec(tile);
return
statspec == NULL ||
HasBit(statspec->pylons, GetStationGfx(tile)) ||
!HasBit(statspec->wires, GetStationGfx(tile));
}
void AnimateStationTile(TileIndex tile)
{
const StationSpec *ss = GetStationSpec(tile);
if (ss == NULL) return;
const Station *st = GetStationByTile(tile);
uint8 animation_speed = ss->anim_speed;
if (HasBit(ss->callbackmask, CBM_STATION_ANIMATION_SPEED)) {
uint16 callback = GetStationCallback(CBID_STATION_ANIMATION_SPEED, 0, 0, ss, st, tile);
if (callback != CALLBACK_FAILED) animation_speed = Clamp(callback & 0xFF, 0, 16);
}
if (_tick_counter % (1 << animation_speed) != 0) return;
uint8 frame = GetStationAnimationFrame(tile);
uint8 num_frames = ss->anim_frames;
bool frame_set_by_callback = false;
if (HasBit(ss->callbackmask, CBM_STATION_ANIMATION_NEXT_FRAME)) {
uint32 param = HasBit(ss->flags, 2) ? Random() : 0;
uint16 callback = GetStationCallback(CBID_STATION_ANIM_NEXT_FRAME, param, 0, ss, st, tile);
if (callback != CALLBACK_FAILED) {
frame_set_by_callback = true;
switch (callback & 0xFF) {
case 0xFF:
DeleteAnimatedTile(tile);
break;
case 0xFE:
frame_set_by_callback = false;
break;
default:
frame = callback & 0xFF;
break;
}
/* If the lower 7 bits of the upper byte of the callback
* result are not empty, it is a sound effect. */
if (GB(callback, 8, 7) != 0) PlayTileSound(ss->grffile, GB(callback, 8, 7), tile);
}
}
if (!frame_set_by_callback) {
if (frame < num_frames) {
frame++;
} else if (frame == num_frames && HasBit(ss->anim_status, 0)) {
/* This animation loops, so start again from the beginning */
frame = 0;
} else {
/* This animation doesn't loop, so stay here */
DeleteAnimatedTile(tile);
}
}
SetStationAnimationFrame(tile, frame);
MarkTileDirtyByTile(tile);
}
static void ChangeStationAnimationFrame(const StationSpec *ss, const Station *st, TileIndex tile, uint16 random_bits, StatAnimTrigger trigger, CargoID cargo_type)
{
uint16 callback = GetStationCallback(CBID_STATION_ANIM_START_STOP, (random_bits << 16) | Random(), (uint8)trigger | (cargo_type << 8), ss, st, tile);
if (callback == CALLBACK_FAILED) return;
switch (callback & 0xFF) {
case 0xFD: /* Do nothing. */ break;
case 0xFE: AddAnimatedTile(tile); break;
case 0xFF: DeleteAnimatedTile(tile); break;
default:
SetStationAnimationFrame(tile, callback);
AddAnimatedTile(tile);
break;
}
/* If the lower 7 bits of the upper byte of the callback
* result are not empty, it is a sound effect. */
if (GB(callback, 8, 7) != 0) PlayTileSound(ss->grffile, GB(callback, 8, 7), tile);
}
enum TriggerArea {
TA_TILE,
TA_PLATFORM,
TA_WHOLE,
};
struct TileArea {
TileIndex tile;
uint8 w;
uint8 h;
TileArea(const Station *st, TileIndex tile, TriggerArea ta)
{
switch (ta) {
default: NOT_REACHED();
case TA_TILE:
this->tile = tile;
this->w = 1;
this->h = 1;
break;
case TA_PLATFORM: {
TileIndex start, end;
Axis axis = GetRailStationAxis(tile);
TileIndexDiff delta = TileOffsByDiagDir(AxisToDiagDir(axis));
for (end = tile; IsRailwayStationTile(end + delta) && IsCompatibleTrainStationTile(tile, end + delta); end += delta) { /* Nothing */ }
for (start = tile; IsRailwayStationTile(start - delta) && IsCompatibleTrainStationTile(tile, start - delta); start -= delta) { /* Nothing */ }
this->tile = start;
this->w = TileX(end) - TileX(start) + 1;
this->h = TileY(end) - TileY(start) + 1;
break;
}
case TA_WHOLE:
this->tile = st->train_tile;
this->w = st->trainst_w + 1;
this->h = st->trainst_h + 1;
break;
}
}
};
void StationAnimationTrigger(const Station *st, TileIndex tile, StatAnimTrigger trigger, CargoID cargo_type)
{
/* List of coverage areas for each animation trigger */
static const TriggerArea tas[] = {
TA_TILE, TA_WHOLE, TA_WHOLE, TA_PLATFORM, TA_PLATFORM, TA_PLATFORM, TA_WHOLE
};
/* Get Station if it wasn't supplied */
if (st == NULL) st = GetStationByTile(tile);
/* Check the cached animation trigger bitmask to see if we need
* to bother with any further processing. */
if (!HasBit(st->cached_anim_triggers, trigger)) return;
uint16 random_bits = Random();
TileArea area = TileArea(st, tile, tas[trigger]);
for (uint y = 0; y < area.h; y++) {
for (uint x = 0; x < area.w; x++) {
if (st->TileBelongsToRailStation(area.tile)) {
const StationSpec *ss = GetStationSpec(area.tile);
if (ss != NULL && HasBit(ss->anim_triggers, trigger)) {
CargoID cargo;
if (cargo_type == CT_INVALID) {
cargo = CT_INVALID;
} else {
cargo = GetReverseCargoTranslation(cargo_type, ss->grffile);
}
ChangeStationAnimationFrame(ss, st, area.tile, random_bits, trigger, cargo);
}
}
area.tile += TileDiffXY(1, 0);
}
area.tile += TileDiffXY(-area.w, 1);
}
}
/**
* Update the cached animation trigger bitmask for a station.
* @param st Station to update.
*/
void StationUpdateAnimTriggers(Station *st)
{
st->cached_anim_triggers = 0;
/* Combine animation trigger bitmask for all station specs
* of this station. */
for (uint i = 0; i < st->num_specs; i++) {
const StationSpec *ss = st->speclist[i].spec;
if (ss != NULL) st->cached_anim_triggers |= ss->anim_triggers;
}
}
| 32,318
|
C++
|
.cpp
| 872
| 34.286697
| 162
| 0.700851
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,102
|
window.cpp
|
EnergeticBark_OpenTTD-3DS/src/window.cpp
|
/* $Id$ */
/** @file window.cpp Windowing system, widgets and events */
#include "stdafx.h"
#include <stdarg.h>
#include "openttd.h"
#include "company_func.h"
#include "gfx_func.h"
#include "console_func.h"
#include "console_gui.h"
#include "viewport_func.h"
#include "variables.h"
#include "genworld.h"
#include "blitter/factory.hpp"
#include "zoom_func.h"
#include "map_func.h"
#include "vehicle_base.h"
#include "settings_type.h"
#include "cheat_type.h"
#include "window_func.h"
#include "tilehighlight_func.h"
#include "network/network.h"
#include "querystring_gui.h"
#include "widgets/dropdown_func.h"
#include "table/sprites.h"
static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
static Window *_mouseover_last_w = NULL; ///< Window of the last MOUSEOVER event
/** List of windows opened at the screen sorted from the front. */
Window *_z_front_window = NULL;
/** List of windows opened at the screen sorted from the back. */
Window *_z_back_window = NULL;
/*
* Window that currently have focus. - The main purpose is to generate
* FocusLost events, not to give next window in z-order focus when a
* window is closed.
*/
Window *_focused_window;
Point _cursorpos_drag_start;
int _scrollbar_start_pos;
int _scrollbar_size;
byte _scroller_click_timeout;
bool _scrolling_scrollbar;
bool _scrolling_viewport;
byte _special_mouse_mode;
/** Window description constructor. */
WindowDesc::WindowDesc(int16 left, int16 top, int16 min_width, int16 min_height, int16 def_width, int16 def_height,
WindowClass window_class, WindowClass parent_class, uint32 flags, const Widget *widgets)
{
this->left = left;
this->top = top;
this->minimum_width = min_width;
this->minimum_height = min_height;
this->default_width = def_width;
this->default_height = def_height;
this->cls = window_class;
this->parent_cls = parent_class;
this->flags = flags;
this->widgets = widgets;
}
/**
* Set the window that has the focus
* @param w The window to set the focus on
*/
void SetFocusedWindow(Window *w)
{
if (_focused_window == w) return;
/* Invalidate focused widget */
if (_focused_window != NULL && _focused_window->focused_widget != NULL) {
uint focused_widget_id = _focused_window->focused_widget - _focused_window->widget;
_focused_window->InvalidateWidget(focused_widget_id);
}
/* Remember which window was previously focused */
Window *old_focused = _focused_window;
_focused_window = w;
/* So we can inform it that it lost focus */
if (old_focused != NULL) old_focused->OnFocusLost();
if (_focused_window != NULL) _focused_window->OnFocus();
}
/**
* Gets the globally focused widget. Which is the focused widget of the focused window.
* @return A pointer to the globally focused Widget, or NULL if there is no globally focused widget.
*/
const Widget *GetGloballyFocusedWidget()
{
return _focused_window != NULL ? _focused_window->focused_widget : NULL;
}
/**
* Check if an edit box is in global focus. That is if focused window
* has a edit box as focused widget, or if a console is focused.
* @return returns true if an edit box is in global focus or if the focused window is a console, else false
*/
bool EditBoxInGlobalFocus()
{
const Widget *wi = GetGloballyFocusedWidget();
/* The console does not have an edit box so a special case is needed. */
return (wi != NULL && wi->type == WWT_EDITBOX) ||
(_focused_window != NULL && _focused_window->window_class == WC_CONSOLE);
}
/**
* Sets the enabled/disabled status of a list of widgets.
* By default, widgets are enabled.
* On certain conditions, they have to be disabled.
* @param disab_stat status to use ie: disabled = true, enabled = false
* @param widgets list of widgets ended by WIDGET_LIST_END
*/
void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
{
va_list wdg_list;
va_start(wdg_list, widgets);
while (widgets != WIDGET_LIST_END) {
SetWidgetDisabledState(widgets, disab_stat);
widgets = va_arg(wdg_list, int);
}
va_end(wdg_list);
}
/**
* Sets the hidden/shown status of a list of widgets.
* By default, widgets are visible.
* On certain conditions, they have to be hidden.
* @param hidden_stat status to use ie. hidden = true, visible = false
* @param widgets list of widgets ended by WIDGET_LIST_END
*/
void CDECL Window::SetWidgetsHiddenState(bool hidden_stat, int widgets, ...)
{
va_list wdg_list;
va_start(wdg_list, widgets);
while (widgets != WIDGET_LIST_END) {
SetWidgetHiddenState(widgets, hidden_stat);
widgets = va_arg(wdg_list, int);
}
va_end(wdg_list);
}
/**
* Sets the lowered/raised status of a list of widgets.
* @param lowered_stat status to use ie: lowered = true, raised = false
* @param widgets list of widgets ended by WIDGET_LIST_END
*/
void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
{
va_list wdg_list;
va_start(wdg_list, widgets);
while (widgets != WIDGET_LIST_END) {
SetWidgetLoweredState(widgets, lowered_stat);
widgets = va_arg(wdg_list, int);
}
va_end(wdg_list);
}
/**
* Raise all buttons of the window
*/
void Window::RaiseButtons()
{
for (uint i = 0; i < this->widget_count; i++) {
if (this->IsWidgetLowered(i)) {
this->RaiseWidget(i);
this->InvalidateWidget(i);
}
}
}
/**
* Invalidate a widget, i.e. mark it as being changed and in need of redraw.
* @param widget_index the widget to redraw.
*/
void Window::InvalidateWidget(byte widget_index) const
{
const Widget *wi = &this->widget[widget_index];
/* Don't redraw the window if the widget is invisible or of no-type */
if (wi->type == WWT_EMPTY || IsWidgetHidden(widget_index)) return;
SetDirtyBlocks(this->left + wi->left, this->top + wi->top, this->left + wi->right + 1, this->top + wi->bottom + 1);
}
/**
* Do all things to make a button look clicked and mark it to be
* unclicked in a few ticks.
* @param widget the widget to "click"
*/
void Window::HandleButtonClick(byte widget)
{
this->LowerWidget(widget);
this->flags4 |= WF_TIMEOUT_BEGIN;
this->InvalidateWidget(widget);
}
/**
* Checks if the window has at least one widget of given type
* @param widget_type the widget type to look for
*/
bool Window::HasWidgetOfType(WidgetType widget_type) const
{
for (uint i = 0; i < this->widget_count; i++) {
if (this->widget[i].type == widget_type) return true;
}
return false;
}
static void StartWindowDrag(Window *w);
static void StartWindowSizing(Window *w);
/**
* Dispatch left mouse-button (possibly double) click in window.
* @param w Window to dispatch event in
* @param x X coordinate of the click
* @param y Y coordinate of the click
* @param double_click Was it a double click?
*/
static void DispatchLeftClickEvent(Window *w, int x, int y, bool double_click)
{
bool focused_widget_changed = false;
int widget = 0;
if (w->desc_flags & WDF_DEF_WIDGET) {
widget = GetWidgetFromPos(w, x, y);
/* If clicked on a window that previously did dot have focus */
if (_focused_window != w &&
(w->desc_flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
!(w->desc_flags & WDF_STD_BTN && widget == 0)) { // Don't change focused window if 'X' (close button) was clicked
focused_widget_changed = true;
if (_focused_window != NULL) {
_focused_window->OnFocusLost();
/* The window that lost focus may have had opened a OSK, window so close it, unless the user has clicked on the OSK window. */
if (w->window_class != WC_OSK) DeleteWindowById(WC_OSK, 0);
}
SetFocusedWindow(w);
w->OnFocus();
}
if (widget < 0) return; // exit if clicked outside of widgets
/* don't allow any interaction if the button has been disabled */
if (w->IsWidgetDisabled(widget)) return;
const Widget *wi = &w->widget[widget];
/* Clicked on a widget that is not disabled.
* So unless the clicked widget is the caption bar, change focus to this widget */
if (wi->type != WWT_CAPTION) {
/* Close the OSK window if a edit box loses focus */
if (w->focused_widget && w->focused_widget->type == WWT_EDITBOX && // An edit box was previously selected
w->focused_widget != wi && // and focus is going to change
w->window_class != WC_OSK) { // and it is not the OSK window
DeleteWindowById(WC_OSK, 0);
}
if (w->focused_widget != wi) {
/* Repaint the widget that loss focus. A focused edit box may else leave the caret left on the screen */
if (w->focused_widget) w->InvalidateWidget(w->focused_widget - w->widget);
focused_widget_changed = true;
w->focused_widget = wi;
}
}
if (wi->type & WWB_MASK) {
/* special widget handling for buttons*/
switch (wi->type) {
default: NOT_REACHED();
case WWT_PANEL | WWB_PUSHBUTTON: // WWT_PUSHBTN
case WWT_IMGBTN | WWB_PUSHBUTTON: // WWT_PUSHIMGBTN
case WWT_TEXTBTN | WWB_PUSHBUTTON: // WWT_PUSHTXTBTN
w->HandleButtonClick(widget);
break;
}
} else if (wi->type == WWT_SCROLLBAR || wi->type == WWT_SCROLL2BAR || wi->type == WWT_HSCROLLBAR) {
ScrollbarClickHandler(w, wi, x, y);
} else if (wi->type == WWT_EDITBOX && !focused_widget_changed) { // Only open the OSK window if clicking on an already focused edit box
/* Open the OSK window if clicked on an edit box */
QueryStringBaseWindow *qs = dynamic_cast<QueryStringBaseWindow*>(w);
if (qs != NULL) {
const int widget_index = wi - w->widget;
qs->OnOpenOSKWindow(widget_index);
}
}
/* Close any child drop down menus. If the button pressed was the drop down
* list's own button, then we should not process the click any further. */
if (HideDropDownMenu(w) == widget) return;
if (w->desc_flags & WDF_STD_BTN) {
if (widget == 0) { // 'X'
delete w;
return;
}
if (widget == 1) { // 'Title bar'
StartWindowDrag(w);
return;
}
}
if (w->desc_flags & WDF_RESIZABLE && wi->type == WWT_RESIZEBOX) {
StartWindowSizing(w);
w->InvalidateWidget(widget);
return;
}
if (w->desc_flags & WDF_STICKY_BUTTON && wi->type == WWT_STICKYBOX) {
w->flags4 ^= WF_STICKY;
w->InvalidateWidget(widget);
return;
}
}
Point pt = { x, y };
if (double_click) {
w->OnDoubleClick(pt, widget);
} else {
w->OnClick(pt, widget);
}
}
/**
* Dispatch right mouse-button click in window.
* @param w Window to dispatch event in
* @param x X coordinate of the click
* @param y Y coordinate of the click
*/
static void DispatchRightClickEvent(Window *w, int x, int y)
{
int widget = 0;
/* default tooltips handler? */
if (w->desc_flags & WDF_STD_TOOLTIPS) {
widget = GetWidgetFromPos(w, x, y);
if (widget < 0) return; // exit if clicked outside of widgets
if (w->widget[widget].tooltips != 0) {
GuiShowTooltips(w->widget[widget].tooltips);
return;
}
}
Point pt = { x, y };
w->OnRightClick(pt, widget);
}
/**
* Dispatch the mousewheel-action to the window.
* The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
* @param w Window
* @param widget the widget where the scrollwheel was used
* @param wheel scroll up or down
*/
static void DispatchMouseWheelEvent(Window *w, int widget, int wheel)
{
if (widget < 0) return;
const Widget *wi1 = &w->widget[widget];
const Widget *wi2 = &w->widget[widget + 1];
/* The listbox can only scroll if scrolling was done on the scrollbar itself,
* or on the listbox (and the next item is (must be) the scrollbar)
* XXX - should be rewritten as a widget-dependent scroller but that's
* not happening until someone rewrites the whole widget-code */
Scrollbar *sb;
if ((sb = &w->vscroll, wi1->type == WWT_SCROLLBAR) || (sb = &w->vscroll2, wi1->type == WWT_SCROLL2BAR) ||
(sb = &w->vscroll2, wi2->type == WWT_SCROLL2BAR) || (sb = &w->vscroll, wi2->type == WWT_SCROLLBAR) ) {
if (sb->count > sb->cap) {
int pos = Clamp(sb->pos + wheel, 0, sb->count - sb->cap);
if (pos != sb->pos) {
sb->pos = pos;
w->SetDirty();
}
}
}
}
/**
* Generate repaint events for the visible part of window w within the rectangle.
*
* The function goes recursively upwards in the window stack, and splits the rectangle
* into multiple pieces at the window edges, so obscured parts are not redrawn.
*
* @param w Window that needs to be repainted
* @param left Left edge of the rectangle that should be repainted
* @param top Top edge of the rectangle that should be repainted
* @param right Right edge of the rectangle that should be repainted
* @param bottom Bottom edge of the rectangle that should be repainted
*/
static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
{
const Window *v;
FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
if (right > v->left &&
bottom > v->top &&
left < v->left + v->width &&
top < v->top + v->height) {
/* v and rectangle intersect with eeach other */
int x;
if (left < (x = v->left)) {
DrawOverlappedWindow(w, left, top, x, bottom);
DrawOverlappedWindow(w, x, top, right, bottom);
return;
}
if (right > (x = v->left + v->width)) {
DrawOverlappedWindow(w, left, top, x, bottom);
DrawOverlappedWindow(w, x, top, right, bottom);
return;
}
if (top < (x = v->top)) {
DrawOverlappedWindow(w, left, top, right, x);
DrawOverlappedWindow(w, left, x, right, bottom);
return;
}
if (bottom > (x = v->top + v->height)) {
DrawOverlappedWindow(w, left, top, right, x);
DrawOverlappedWindow(w, left, x, right, bottom);
return;
}
return;
}
}
/* Setup blitter, and dispatch a repaint event to window *wz */
DrawPixelInfo *dp = _cur_dpi;
dp->width = right - left;
dp->height = bottom - top;
dp->left = left - w->left;
dp->top = top - w->top;
dp->pitch = _screen.pitch;
dp->dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
dp->zoom = ZOOM_LVL_NORMAL;
w->OnPaint();
}
/**
* From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
* These windows should be re-painted.
* @param left Left edge of the rectangle that should be repainted
* @param top Top edge of the rectangle that should be repainted
* @param right Right edge of the rectangle that should be repainted
* @param bottom Bottom edge of the rectangle that should be repainted
*/
void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
{
Window *w;
DrawPixelInfo bk;
_cur_dpi = &bk;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (right > w->left &&
bottom > w->top &&
left < w->left + w->width &&
top < w->top + w->height) {
/* Window w intersects with the rectangle => needs repaint */
DrawOverlappedWindow(w, left, top, right, bottom);
}
}
}
/**
* Mark entire window as dirty (in need of re-paint)
* @ingroup dirty
*/
void Window::SetDirty() const
{
SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
}
/**
* Mark entire window as dirty (in need of re-paint)
* @param w Window to redraw
* @ingroup dirty
*/
void SetWindowDirty(const Window *w)
{
if (w != NULL) w->SetDirty();
}
/** Find the Window whose parent pointer points to this window
* @param w parent Window to find child of
* @return a Window pointer that is the child of w, or NULL otherwise */
static Window *FindChildWindow(const Window *w)
{
Window *v;
FOR_ALL_WINDOWS_FROM_BACK(v) {
if (v->parent == w) return v;
}
return NULL;
}
/**
* Delete all children a window might have in a head-recursive manner
*/
void Window::DeleteChildWindows() const
{
Window *child = FindChildWindow(this);
while (child != NULL) {
delete child;
child = FindChildWindow(this);
}
}
/**
* Remove window and all its child windows from the window stack.
*/
Window::~Window()
{
if (_thd.place_mode != VHM_NONE &&
_thd.window_class == this->window_class &&
_thd.window_number == this->window_number) {
ResetObjectToPlace();
}
/* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
if (_mouseover_last_w == this) _mouseover_last_w = NULL;
/* Make sure we don't try to access this window as the focused window when it don't exist anymore. */
if (_focused_window == this) _focused_window = NULL;
this->DeleteChildWindows();
if (this->viewport != NULL) DeleteWindowViewport(this);
this->SetDirty();
free(this->widget);
/* N3DS.
* Backported this line from a later version of OpenTTD so optimizations will no longer break on new versions of GCC */
const_cast<volatile WindowClass &>(this->window_class) = WC_INVALID;
}
/**
* Find a window by its class and window number
* @param cls Window class
* @param number Number of the window within the window class
* @return Pointer to the found window, or \c NULL if not available
*/
Window *FindWindowById(WindowClass cls, WindowNumber number)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == cls && w->window_number == number) return w;
}
return NULL;
}
/**
* Delete a window by its class and window number (if it is open).
* @param cls Window class
* @param number Number of the window within the window class
* @param force force deletion; if false don't delete when stickied
*/
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
{
Window *w = FindWindowById(cls, number);
if (force || w == NULL ||
(w->desc_flags & WDF_STICKY_BUTTON) == 0 ||
(w->flags4 & WF_STICKY) == 0) {
delete w;
}
}
/**
* Delete all windows of a given class
* @param cls Window class of windows to delete
*/
void DeleteWindowByClass(WindowClass cls)
{
Window *w;
restart_search:
/* When we find the window to delete, we need to restart the search
* as deleting this window could cascade in deleting (many) others
* anywhere in the z-array */
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == cls) {
delete w;
goto restart_search;
}
}
}
/** Delete all windows of a company. We identify windows of a company
* by looking at the caption colour. If it is equal to the company ID
* then we say the window belongs to the company and should be deleted
* @param id company identifier */
void DeleteCompanyWindows(CompanyID id)
{
Window *w;
restart_search:
/* When we find the window to delete, we need to restart the search
* as deleting this window could cascade in deleting (many) others
* anywhere in the z-array */
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->owner == id) {
delete w;
goto restart_search;
}
}
/* Also delete the company specific windows, that don't have a company-colour */
DeleteWindowById(WC_BUY_COMPANY, id);
}
/** Change the owner of all the windows one company can take over from another
* company in the case of a company merger. Do not change ownership of windows
* that need to be deleted once takeover is complete
* @param old_owner original owner of the window
* @param new_owner the new owner of the window */
void ChangeWindowOwner(Owner old_owner, Owner new_owner)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->owner != old_owner) continue;
switch (w->window_class) {
case WC_COMPANY_COLOUR:
case WC_FINANCES:
case WC_STATION_LIST:
case WC_TRAINS_LIST:
case WC_ROADVEH_LIST:
case WC_SHIPS_LIST:
case WC_AIRCRAFT_LIST:
case WC_BUY_COMPANY:
case WC_COMPANY:
continue;
default:
w->owner = new_owner;
break;
}
}
}
static void BringWindowToFront(Window *w);
/** Find a window and make it the top-window on the screen. The window
* gets a white border for a brief period of time to visualize its "activation"
* @param cls WindowClass of the window to activate
* @param number WindowNumber of the window to activate
* @return a pointer to the window thus activated */
Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
{
Window *w = FindWindowById(cls, number);
if (w != NULL) {
w->flags4 |= WF_WHITE_BORDER_MASK;
BringWindowToFront(w);
w->SetDirty();
}
return w;
}
static inline bool IsVitalWindow(const Window *w)
{
switch (w->window_class) {
case WC_MAIN_TOOLBAR:
case WC_STATUS_BAR:
case WC_NEWS_WINDOW:
case WC_SEND_NETWORK_MSG:
return true;
default:
return false;
}
}
/** On clicking on a window, make it the frontmost window of all. However
* there are certain windows that always need to be on-top; these include
* - Toolbar, Statusbar (always on)
* - New window, Chatbar (only if open)
* The window is marked dirty for a repaint if the window is actually moved
* @param w window that is put into the foreground
* @return pointer to the window, the same as the input pointer
*/
static void BringWindowToFront(Window *w)
{
Window *v = _z_front_window;
/* Bring the window just below the vital windows */
for (; v != NULL && v != w && IsVitalWindow(v); v = v->z_back) { }
if (v == NULL || w == v) return; // window is already in the right position
/* w cannot be at the top already! */
assert(w != _z_front_window);
if (w->z_back == NULL) {
_z_back_window = w->z_front;
} else {
w->z_back->z_front = w->z_front;
}
w->z_front->z_back = w->z_back;
w->z_front = v->z_front;
w->z_back = v;
if (v->z_front == NULL) {
_z_front_window = w;
} else {
v->z_front->z_back = w;
}
v->z_front = w;
w->SetDirty();
}
/**
* Assign widgets to a new window by initialising its widget pointers, and by
* copying the widget array \a widget to \c w->widget to allow for resizable
* windows.
* @param w Window on which to attach the widget array
* @param widget pointer of widget array to fill the window with
*
* @post \c w->widget points to allocated memory and contains the copied widget array except for the terminating widget,
* \c w->widget_count contains number of widgets in the allocated memory.
*/
static void AssignWidgetToWindow(Window *w, const Widget *widget)
{
if (widget != NULL) {
uint index = 1;
for (const Widget *wi = widget; wi->type != WWT_LAST; wi++) index++;
w->widget = MallocT<Widget>(index);
memcpy(w->widget, widget, sizeof(*w->widget) * index);
w->widget_count = index - 1;
} else {
w->widget = NULL;
w->widget_count = 0;
}
}
/**
* Initializes a new Window.
* This function is called the constructors.
* See descriptions for those functions for usage
* Only addition here is window_number, which is the window_number being assigned to the new window
* @param x offset in pixels from the left of the screen
* @param y offset in pixels from the top of the screen
* @param min_width minimum width in pixels of the window
* @param min_height minimum height in pixels of the window
* @param cls see WindowClass class of the window, used for identification and grouping
* @param *widget see Widget pointer to the window layout and various elements
* @param window_number number being assigned to the new window
* @return Window pointer of the newly created window
*/
void Window::Initialize(int x, int y, int min_width, int min_height,
WindowClass cls, const Widget *widget, int window_number)
{
/* Set up window properties */
this->window_class = cls;
this->flags4 = WF_WHITE_BORDER_MASK; // just opened windows have a white border
this->owner = INVALID_OWNER;
this->left = x;
this->top = y;
this->width = min_width;
this->height = min_height;
AssignWidgetToWindow(this, widget);
this->focused_widget = 0;
this->resize.width = min_width;
this->resize.height = min_height;
this->resize.step_width = 1;
this->resize.step_height = 1;
this->window_number = window_number;
/* Give focus to the opened window unless it is the OSK window or a text box
* of focused window has focus (so we don't interrupt typing). But if the new
* window has a text box, then take focus anyway. */
if (this->window_class != WC_OSK && (!EditBoxInGlobalFocus() || this->HasWidgetOfType(WWT_EDITBOX))) SetFocusedWindow(this);
/* Hacky way of specifying always-on-top windows. These windows are
* always above other windows because they are moved below them.
* status-bar is above news-window because it has been created earlier.
* Also, as the chat-window is excluded from this, it will always be
* the last window, thus always on top.
* XXX - Yes, ugly, probably needs something like w->always_on_top flag
* to implement correctly, but even then you need some kind of distinction
* between on-top of chat/news and status windows, because these conflict */
Window *w = _z_front_window;
if (w != NULL && this->window_class != WC_SEND_NETWORK_MSG && this->window_class != WC_HIGHSCORE && this->window_class != WC_ENDSCREEN) {
if (FindWindowById(WC_MAIN_TOOLBAR, 0) != NULL) w = w->z_back;
if (FindWindowById(WC_STATUS_BAR, 0) != NULL) w = w->z_back;
if (FindWindowById(WC_NEWS_WINDOW, 0) != NULL) w = w->z_back;
if (FindWindowById(WC_SEND_NETWORK_MSG, 0) != NULL) w = w->z_back;
if (w == NULL) {
_z_back_window->z_front = this;
this->z_back = _z_back_window;
_z_back_window = this;
} else {
if (w->z_front == NULL) {
_z_front_window = this;
} else {
this->z_front = w->z_front;
w->z_front->z_back = this;
}
this->z_back = w;
w->z_front = this;
}
} else {
this->z_back = _z_front_window;
if (_z_front_window != NULL) {
_z_front_window->z_front = this;
} else {
_z_back_window = this;
}
_z_front_window = this;
}
}
/**
* Resize window towards the default size.
* Prior to construction, a position for the new window (for its default size)
* has been found with LocalGetWindowPlacement(). Initially, the window is
* constructed with minimal size. Resizing the window to its default size is
* done here.
* @param def_width default width in pixels of the window
* @param def_height default height in pixels of the window
* @see Window::Window(), Window::Initialize()
*/
void Window::FindWindowPlacementAndResize(int def_width, int def_height)
{
/* Try to make windows smaller when our window is too small.
* w->(width|height) is normally the same as min_(width|height),
* but this way the GUIs can be made a little more dynamic;
* one can use the same spec for multiple windows and those
* can then determine the real minimum size of the window. */
if (this->width != def_width || this->height != def_height) {
/* Think about the overlapping toolbars when determining the minimum window size */
int free_height = _screen.height;
const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
if (wt != NULL) free_height -= wt->height;
wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
if (wt != NULL) free_height -= wt->height;
int enlarge_x = max(min(def_width - this->width, _screen.width - this->width), 0);
int enlarge_y = max(min(def_height - this->height, free_height - this->height), 0);
/* X and Y has to go by step.. calculate it.
* The cast to int is necessary else x/y are implicitly casted to
* unsigned int, which won't work. */
if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
ResizeWindow(this, enlarge_x, enlarge_y);
Point size;
Point diff;
size.x = this->width;
size.y = this->height;
diff.x = enlarge_x;
diff.y = enlarge_y;
this->OnResize(size, diff);
}
int nx = this->left;
int ny = this->top;
if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
nx = max(nx, 0);
if (this->viewport != NULL) {
this->viewport->left += nx - this->left;
this->viewport->top += ny - this->top;
}
this->left = nx;
this->top = ny;
this->SetDirty();
}
/**
* Resize window towards the default size given in the window description.
* @param desc the description to get the default size from.
*/
void Window::FindWindowPlacementAndResize(const WindowDesc *desc)
{
this->FindWindowPlacementAndResize(desc->default_width, desc->default_height);
}
/**
* Open a new window. If there is no space for a new window, close an open
* window. Try to avoid stickied windows, but if there is no else, close one of
* those as well. Then make sure all created windows are below some always-on-top
* ones. Finally set all variables and call the WE_CREATE event
* @param x offset in pixels from the left of the screen
* @param y offset in pixels from the top of the screen
* @param width width in pixels of the window
* @param height height in pixels of the window
* @param cls see WindowClass class of the window, used for identification and grouping
* @param *widget see Widget pointer to the window layout and various elements
* @return Window pointer of the newly created window
*/
Window::Window(int x, int y, int width, int height, WindowClass cls, const Widget *widget)
{
this->Initialize(x, y, width, height, cls, widget, 0);
}
/**
* Decide whether a given rectangle is a good place to open a completely visible new window.
* The new window should be within screen borders, and not overlap with another already
* existing window (except for the main window in the background).
* @param left Left edge of the rectangle
* @param top Top edge of the rectangle
* @param width Width of the rectangle
* @param height Height of the rectangle
* @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
* @return Boolean indication that the rectangle is a good place for the new window
*/
static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
{
int right = width + left;
int bottom = height + top;
if (left < 0 || top < 22 || right > _screen.width || bottom > _screen.height) return false;
/* Make sure it is not obscured by any window. */
const Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == WC_MAIN_WINDOW) continue;
if (right > w->left &&
w->left + w->width > left &&
bottom > w->top &&
w->top + w->height > top) {
return false;
}
}
pos.x = left;
pos.y = top;
return true;
}
/**
* Decide whether a given rectangle is a good place to open a mostly visible new window.
* The new window should be mostly within screen borders, and not overlap with another already
* existing window (except for the main window in the background).
* @param left Left edge of the rectangle
* @param top Top edge of the rectangle
* @param width Width of the rectangle
* @param height Height of the rectangle
* @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
* @return Boolean indication that the rectangle is a good place for the new window
*/
static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
{
/* Left part of the rectangle may be at most 1/4 off-screen,
* right part of the rectangle may be at most 1/2 off-screen
*/
if (left < -(width>>2) || left > _screen.width - (width>>1)) return false;
/* Bottom part of the rectangle may be at most 1/4 off-screen */
if (top < 22 || top > _screen.height - (height>>2)) return false;
/* Make sure it is not obscured by any window. */
const Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == WC_MAIN_WINDOW) continue;
if (left + width > w->left &&
w->left + w->width > left &&
top + height > w->top &&
w->top + w->height > top) {
return false;
}
}
pos.x = left;
pos.y = top;
return true;
}
/**
* Find a good place for opening a new window of a given width and height.
* @param width Width of the new window
* @param height Height of the new window
* @return Top-left coordinate of the new window
*/
static Point GetAutoPlacePosition(int width, int height)
{
Point pt;
/* First attempt, try top-left of the screen */
if (IsGoodAutoPlace1(0, 24, width, height, pt)) return pt;
/* Second attempt, try around all existing windows with a distance of 2 pixels.
* The new window must be entirely on-screen, and not overlap with an existing window.
* Eight starting points are tried, two at each corner.
*/
const Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == WC_MAIN_WINDOW) continue;
if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
if (IsGoodAutoPlace1(w->left - width - 2, w->top, width, height, pt)) return pt;
if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
if (IsGoodAutoPlace1(w->left, w->top - height - 2, width, height, pt)) return pt;
if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
if (IsGoodAutoPlace1(w->left - width - 2, w->top + w->height - height, width, height, pt)) return pt;
if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2, width, height, pt)) return pt;
}
/* Third attempt, try around all existing windows with a distance of 2 pixels.
* The new window may be partly off-screen, and must not overlap with an existing window.
* Only four starting points are tried.
*/
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == WC_MAIN_WINDOW) continue;
if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
if (IsGoodAutoPlace2(w->left - width - 2, w->top, width, height, pt)) return pt;
if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
if (IsGoodAutoPlace2(w->left, w->top - height - 2, width, height, pt)) return pt;
}
/* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
* of (+5, +5)
*/
int left = 0, top = 24;
restart:
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->left == left && w->top == top) {
left += 5;
top += 5;
goto restart;
}
}
pt.x = left;
pt.y = top;
return pt;
}
/**
* Compute the position of the top-left corner of a new window that is opened.
*
* By default position a child window at an offset of 10/10 of its parent.
* With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
* and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/36 of
* its parent. So it's exactly under the parent toolbar and no buttons will be covered.
* However if it falls too extremely outside window positions, reposition
* it to an automatic place.
*
* @param *desc The pointer to the WindowDesc to be created
* @param window_number the window number of the new window
*
* @return Coordinate of the top-left corner of the new window
*/
static Point LocalGetWindowPlacement(const WindowDesc *desc, int window_number)
{
Point pt;
Window *w;
if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
(w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {
pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
if (pt.x > _screen.width + 10 - desc->default_width) {
pt.x = (_screen.width + 10 - desc->default_width) - 20;
}
pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 36 : 10);
} else {
switch (desc->left) {
case WDP_ALIGN_TBR: // Align the right side with the top toolbar
w = FindWindowById(WC_MAIN_TOOLBAR, 0);
pt.x = (w->left + w->width) - desc->default_width;
break;
case WDP_ALIGN_TBL: // Align the left side with the top toolbar
pt.x = FindWindowById(WC_MAIN_TOOLBAR, 0)->left;
break;
case WDP_AUTO: // Find a good automatic position for the window
return GetAutoPlacePosition(desc->default_width, desc->default_height);
case WDP_CENTER: // Centre the window horizontally
pt.x = (_screen.width - desc->default_width) / 2;
break;
default:
pt.x = desc->left;
if (pt.x < 0) pt.x += _screen.width; // negative is from right of the screen
}
switch (desc->top) {
case WDP_CENTER: // Centre the window vertically
pt.y = (_screen.height - desc->default_height) / 2;
break;
/* WDP_AUTO sets the position at once and is controlled by desc->left.
* Both left and top must be set to WDP_AUTO */
case WDP_AUTO:
NOT_REACHED();
assert(desc->left == WDP_AUTO && desc->top != WDP_AUTO);
/* fallthrough */
default:
pt.y = desc->top;
if (pt.y < 0) pt.y += _screen.height; // negative is from bottom of the screen
break;
}
}
return pt;
}
/**
* Set the positions of a new window from a WindowDesc and open it.
*
* @param *desc The pointer to the WindowDesc to be created
* @param window_number the window number of the new window
*
* @return Window pointer of the newly created window
*/
Window::Window(const WindowDesc *desc, WindowNumber window_number)
{
Point pt = LocalGetWindowPlacement(desc, window_number);
this->Initialize(pt.x, pt.y, desc->minimum_width, desc->minimum_height, desc->cls, desc->widgets, window_number);
this->desc_flags = desc->flags;
}
/** Do a search for a window at specific coordinates. For this we start
* at the topmost window, obviously and work our way down to the bottom
* @param x position x to query
* @param y position y to query
* @return a pointer to the found window if any, NULL otherwise */
Window *FindWindowFromPt(int x, int y)
{
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
if (IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
return w;
}
}
return NULL;
}
/**
* (re)initialize the windowing system
*/
void InitWindowSystem()
{
IConsoleClose();
_z_back_window = NULL;
_z_front_window = NULL;
_focused_window = NULL;
_mouseover_last_w = NULL;
_scrolling_viewport = 0;
}
/**
* Close down the windowing system
*/
void UnInitWindowSystem()
{
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
for (w = _z_front_window; w != NULL; /* nothing */) {
Window *to_del = w;
w = w->z_back;
free(to_del);
}
_z_front_window = NULL;
_z_back_window = NULL;
}
/**
* Reset the windowing system, by means of shutting it down followed by re-initialization
*/
void ResetWindowSystem()
{
UnInitWindowSystem();
InitWindowSystem();
_thd.pos.x = 0;
_thd.pos.y = 0;
_thd.new_pos.x = 0;
_thd.new_pos.y = 0;
}
static void DecreaseWindowCounters()
{
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
/* Unclick scrollbar buttons if they are pressed. */
if (w->flags4 & (WF_SCROLL_DOWN | WF_SCROLL_UP)) {
w->flags4 &= ~(WF_SCROLL_DOWN | WF_SCROLL_UP);
w->SetDirty();
}
w->OnMouseLoop();
}
FOR_ALL_WINDOWS_FROM_FRONT(w) {
if (w->flags4 & WF_TIMEOUT_MASK && !(--w->flags4 & WF_TIMEOUT_MASK)) {
w->OnTimeout();
if (w->desc_flags & WDF_UNCLICK_BUTTONS) w->RaiseButtons();
}
}
}
Window *GetCallbackWnd()
{
return FindWindowById(_thd.window_class, _thd.window_number);
}
static void HandlePlacePresize()
{
if (_special_mouse_mode != WSM_PRESIZE) return;
Window *w = GetCallbackWnd();
if (w == NULL) return;
Point pt = GetTileBelowCursor();
if (pt.x == -1) {
_thd.selend.x = -1;
return;
}
w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
}
static bool HandleDragDrop()
{
if (_special_mouse_mode != WSM_DRAGDROP) return true;
if (_left_button_down) return false;
Window *w = GetCallbackWnd();
if (w != NULL) {
/* send an event in client coordinates. */
Point pt;
pt.x = _cursor.pos.x - w->left;
pt.y = _cursor.pos.y - w->top;
w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
}
ResetObjectToPlace();
return false;
}
static bool HandleMouseOver()
{
Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
/* We changed window, put a MOUSEOVER event to the last window */
if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
/* Reset mouse-over coordinates of previous window */
Point pt = { -1, -1 };
_mouseover_last_w->OnMouseOver(pt, 0);
}
/* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
_mouseover_last_w = w;
if (w != NULL) {
/* send an event in client coordinates. */
Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
int widget = 0;
if (w->widget != NULL) {
widget = GetWidgetFromPos(w, pt.x, pt.y);
}
w->OnMouseOver(pt, widget);
}
/* Mouseover never stops execution */
return true;
}
/**
* Resize the window.
* Update all the widgets of a window based on their resize flags
* Both the areas of the old window and the new sized window are set dirty
* ensuring proper redrawal.
* @param w Window to resize
* @param x delta x-size of changed window (positive if larger, etc.)
* @param y delta y-size of changed window
*/
void ResizeWindow(Window *w, int x, int y)
{
bool resize_height = false;
bool resize_width = false;
if (x == 0 && y == 0) return;
w->SetDirty();
for (Widget *wi = w->widget; wi->type != WWT_LAST; wi++) {
/* Isolate the resizing flags */
byte rsizeflag = GB(wi->display_flags, 0, 4);
if (rsizeflag == RESIZE_NONE) continue;
/* Resize the widget based on its resize-flag */
if (rsizeflag & RESIZE_LEFT) {
wi->left += x;
resize_width = true;
}
if (rsizeflag & RESIZE_RIGHT) {
wi->right += x;
resize_width = true;
}
if (rsizeflag & RESIZE_TOP) {
wi->top += y;
resize_height = true;
}
if (rsizeflag & RESIZE_BOTTOM) {
wi->bottom += y;
resize_height = true;
}
}
/* We resized at least 1 widget, so let's resize the window totally */
if (resize_width) w->width += x;
if (resize_height) w->height += y;
w->SetDirty();
}
static bool _dragging_window; ///< A window is being dragged or resized.
static bool HandleWindowDragging()
{
/* Get out immediately if no window is being dragged at all. */
if (!_dragging_window) return true;
/* Otherwise find the window... */
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->flags4 & WF_DRAGGING) {
const Widget *t = &w->widget[1]; // the title bar ... ugh
/* Stop the dragging if the left mouse button was released */
if (!_left_button_down) {
w->flags4 &= ~WF_DRAGGING;
break;
}
w->SetDirty();
int x = _cursor.pos.x + _drag_delta.x;
int y = _cursor.pos.y + _drag_delta.y;
int nx = x;
int ny = y;
if (_settings_client.gui.window_snap_radius != 0) {
const Window *v;
int hsnap = _settings_client.gui.window_snap_radius;
int vsnap = _settings_client.gui.window_snap_radius;
int delta;
FOR_ALL_WINDOWS_FROM_BACK(v) {
if (v == w) continue; // Don't snap at yourself
if (y + w->height > v->top && y < v->top + v->height) {
/* Your left border <-> other right border */
delta = abs(v->left + v->width - x);
if (delta <= hsnap) {
nx = v->left + v->width;
hsnap = delta;
}
/* Your right border <-> other left border */
delta = abs(v->left - x - w->width);
if (delta <= hsnap) {
nx = v->left - w->width;
hsnap = delta;
}
}
if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
/* Your left border <-> other left border */
delta = abs(v->left - x);
if (delta <= hsnap) {
nx = v->left;
hsnap = delta;
}
/* Your right border <-> other right border */
delta = abs(v->left + v->width - x - w->width);
if (delta <= hsnap) {
nx = v->left + v->width - w->width;
hsnap = delta;
}
}
if (x + w->width > v->left && x < v->left + v->width) {
/* Your top border <-> other bottom border */
delta = abs(v->top + v->height - y);
if (delta <= vsnap) {
ny = v->top + v->height;
vsnap = delta;
}
/* Your bottom border <-> other top border */
delta = abs(v->top - y - w->height);
if (delta <= vsnap) {
ny = v->top - w->height;
vsnap = delta;
}
}
if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
/* Your top border <-> other top border */
delta = abs(v->top - y);
if (delta <= vsnap) {
ny = v->top;
vsnap = delta;
}
/* Your bottom border <-> other bottom border */
delta = abs(v->top + v->height - y - w->height);
if (delta <= vsnap) {
ny = v->top + v->height - w->height;
vsnap = delta;
}
}
}
}
/* Make sure the window doesn't leave the screen
* 13 is the height of the title bar */
nx = Clamp(nx, 13 - t->right, _screen.width - 13 - t->left);
ny = Clamp(ny, 0, _screen.height - 13);
/* Make sure the title bar isn't hidden by behind the main tool bar */
Window *v = FindWindowById(WC_MAIN_TOOLBAR, 0);
if (v != NULL) {
int v_bottom = v->top + v->height;
int v_right = v->left + v->width;
if (ny + t->top >= v->top && ny + t->top < v_bottom) {
if ((v->left < 13 && nx + t->left < v->left) ||
(v_right > _screen.width - 13 && nx + t->right > v_right)) {
ny = v_bottom;
} else {
if (nx + t->left > v->left - 13 &&
nx + t->right < v_right + 13) {
if (w->top >= v_bottom) {
ny = v_bottom;
} else if (w->left < nx) {
nx = v->left - 13 - t->left;
} else {
nx = v_right + 13 - t->right;
}
}
}
}
}
if (w->viewport != NULL) {
w->viewport->left += nx - w->left;
w->viewport->top += ny - w->top;
}
w->left = nx;
w->top = ny;
w->SetDirty();
return false;
} else if (w->flags4 & WF_SIZING) {
int x, y;
/* Stop the sizing if the left mouse button was released */
if (!_left_button_down) {
w->flags4 &= ~WF_SIZING;
w->SetDirty();
break;
}
x = _cursor.pos.x - _drag_delta.x;
y = _cursor.pos.y - _drag_delta.y;
/* X and Y has to go by step.. calculate it.
* The cast to int is necessary else x/y are implicitly casted to
* unsigned int, which won't work. */
if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
/* Check if we don't go below the minimum set size */
if ((int)w->width + x < (int)w->resize.width)
x = w->resize.width - w->width;
if ((int)w->height + y < (int)w->resize.height)
y = w->resize.height - w->height;
/* Window already on size */
if (x == 0 && y == 0) return false;
/* Now find the new cursor pos.. this is NOT _cursor, because
we move in steps. */
_drag_delta.x += x;
_drag_delta.y += y;
/* ResizeWindow sets both pre- and after-size to dirty for redrawal */
ResizeWindow(w, x, y);
Point size;
Point diff;
size.x = x + w->width;
size.y = y + w->height;
diff.x = x;
diff.y = y;
w->OnResize(size, diff);
return false;
}
}
_dragging_window = false;
return false;
}
/**
* Start window dragging
* @param w Window to start dragging
*/
static void StartWindowDrag(Window *w)
{
w->flags4 |= WF_DRAGGING;
_dragging_window = true;
_drag_delta.x = w->left - _cursor.pos.x;
_drag_delta.y = w->top - _cursor.pos.y;
BringWindowToFront(w);
DeleteWindowById(WC_DROPDOWN_MENU, 0);
}
/**
* Start resizing a window
* @param w Window to start resizing
*/
static void StartWindowSizing(Window *w)
{
w->flags4 |= WF_SIZING;
_dragging_window = true;
_drag_delta.x = _cursor.pos.x;
_drag_delta.y = _cursor.pos.y;
BringWindowToFront(w);
DeleteWindowById(WC_DROPDOWN_MENU, 0);
}
static bool HandleScrollbarScrolling()
{
Window *w;
/* Get out quickly if no item is being scrolled */
if (!_scrolling_scrollbar) return true;
/* Find the scrolling window */
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->flags4 & WF_SCROLL_MIDDLE) {
/* Abort if no button is clicked any more. */
if (!_left_button_down) {
w->flags4 &= ~WF_SCROLL_MIDDLE;
w->SetDirty();
break;
}
int i;
Scrollbar *sb;
if (w->flags4 & WF_HSCROLL) {
sb = &w->hscroll;
i = _cursor.pos.x - _cursorpos_drag_start.x;
} else if (w->flags4 & WF_SCROLL2){
sb = &w->vscroll2;
i = _cursor.pos.y - _cursorpos_drag_start.y;
} else {
sb = &w->vscroll;
i = _cursor.pos.y - _cursorpos_drag_start.y;
}
/* Find the item we want to move to and make sure it's inside bounds. */
int pos = min(max(0, i + _scrollbar_start_pos) * sb->count / _scrollbar_size, max(0, sb->count - sb->cap));
if (pos != sb->pos) {
sb->pos = pos;
w->SetDirty();
}
return false;
}
}
_scrolling_scrollbar = false;
return false;
}
static bool HandleViewportScroll()
{
bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
if (!_scrolling_viewport) return true;
Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
if (!(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) || w == NULL) {
_cursor.fix_at = false;
_scrolling_viewport = false;
return true;
}
if (w == FindWindowById(WC_MAIN_WINDOW, 0) && w->viewport->follow_vehicle != INVALID_VEHICLE) {
/* If the main window is following a vehicle, then first let go of it! */
const Vehicle *veh = GetVehicle(w->viewport->follow_vehicle);
ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
return true;
}
Point delta;
if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
delta.x = -_cursor.delta.x;
delta.y = -_cursor.delta.y;
} else {
delta.x = _cursor.delta.x;
delta.y = _cursor.delta.y;
}
if (scrollwheel_scrolling) {
/* We are using scrollwheels for scrolling */
delta.x = _cursor.h_wheel;
delta.y = _cursor.v_wheel;
_cursor.v_wheel = 0;
_cursor.h_wheel = 0;
}
/* Create a scroll-event and send it to the window */
w->OnScroll(delta);
_cursor.delta.x = 0;
_cursor.delta.y = 0;
return false;
}
/** Check if a window can be made top-most window, and if so do
* it. If a window does not obscure any other windows, it will not
* be brought to the foreground. Also if the only obscuring windows
* are so-called system-windows, the window will not be moved.
* The function will return false when a child window of this window is a
* modal-popup; function returns a false and child window gets a white border
* @param w Window to bring on-top
* @return false if the window has an active modal child, true otherwise */
static bool MaybeBringWindowToFront(Window *w)
{
bool bring_to_front = false;
if (w->window_class == WC_MAIN_WINDOW ||
IsVitalWindow(w) ||
w->window_class == WC_TOOLTIPS ||
w->window_class == WC_DROPDOWN_MENU) {
return true;
}
Window *u;
FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
/* A modal child will prevent the activation of the parent window */
if (u->parent == w && (u->desc_flags & WDF_MODAL)) {
u->flags4 |= WF_WHITE_BORDER_MASK;
u->SetDirty();
return false;
}
if (u->window_class == WC_MAIN_WINDOW ||
IsVitalWindow(u) ||
u->window_class == WC_TOOLTIPS ||
u->window_class == WC_DROPDOWN_MENU) {
continue;
}
/* Window sizes don't interfere, leave z-order alone */
if (w->left + w->width <= u->left ||
u->left + u->width <= w->left ||
w->top + w->height <= u->top ||
u->top + u->height <= w->top) {
continue;
}
bring_to_front = true;
}
if (bring_to_front) BringWindowToFront(w);
return true;
}
/** Handle keyboard input.
* @param raw_key Lower 8 bits contain the ASCII character, the higher 16 bits the keycode
*/
void HandleKeypress(uint32 raw_key)
{
/*
* During the generation of the world, there might be
* another thread that is currently building for example
* a road. To not interfere with those tasks, we should
* NOT change the _current_company here.
*
* This is not necessary either, as the only events that
* can be handled are the 'close application' events
*/
if (!IsGeneratingWorld()) _current_company = _local_company;
/* Setup event */
uint16 key = GB(raw_key, 0, 16);
uint16 keycode = GB(raw_key, 16, 16);
/*
* The Unicode standard defines an area called the private use area. Code points in this
* area are reserved for private use and thus not portable between systems. For instance,
* Apple defines code points for the arrow keys in this area, but these are only printable
* on a system running OS X. We don't want these keys to show up in text fields and such,
* and thus we have to clear the unicode character when we encounter such a key.
*/
if (key >= 0xE000 && key <= 0xF8FF) key = 0;
/*
* If both key and keycode is zero, we don't bother to process the event.
*/
if (key == 0 && keycode == 0) return;
/* Check if the focused window has a focused editbox */
if (EditBoxInGlobalFocus()) {
/* All input will in this case go to the focused window */
if (_focused_window->OnKeyPress(key, keycode) == Window::ES_HANDLED) return;
}
/* Call the event, start with the uppermost window. */
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
if (w->OnKeyPress(key, keycode) == Window::ES_HANDLED) return;
}
w = FindWindowById(WC_MAIN_TOOLBAR, 0);
/* When there is no toolbar w is null, check for that */
if (w != NULL) w->OnKeyPress(key, keycode);
}
/**
* State of CONTROL key has changed
*/
void HandleCtrlChanged()
{
/* Call the event, start with the uppermost window. */
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
if (w->OnCTRLStateChange() == Window::ES_HANDLED) return;
}
}
/**
* Local counter that is incremented each time an mouse input event is detected.
* The counter is used to stop auto-scrolling.
* @see HandleAutoscroll()
* @see HandleMouseEvents()
*/
static int _input_events_this_tick = 0;
/**
* If needed and switched on, perform auto scrolling (automatically
* moving window contents when mouse is near edge of the window).
*/
static void HandleAutoscroll()
{
if (_settings_client.gui.autoscroll && _game_mode != GM_MENU && !IsGeneratingWorld()) {
int x = _cursor.pos.x;
int y = _cursor.pos.y;
Window *w = FindWindowFromPt(x, y);
if (w == NULL || w->flags4 & WF_DISABLE_VP_SCROLL) return;
ViewPort *vp = IsPtInWindowViewport(w, x, y);
if (vp != NULL) {
x -= vp->left;
y -= vp->top;
/* here allows scrolling in both x and y axis */
#define scrollspeed 3
if (x - 15 < 0) {
w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
} else if (15 - (vp->width - x) > 0) {
w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
}
if (y - 15 < 0) {
w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
} else if (15 - (vp->height - y) > 0) {
w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
}
#undef scrollspeed
}
}
}
enum MouseClick {
MC_NONE = 0,
MC_LEFT,
MC_RIGHT,
MC_DOUBLE_LEFT,
MAX_OFFSET_DOUBLE_CLICK = 5, ///< How much the mouse is allowed to move to call it a double click
TIME_BETWEEN_DOUBLE_CLICK = 500, ///< Time between 2 left clicks before it becoming a double click, in ms
};
extern bool VpHandlePlaceSizingDrag();
static void ScrollMainViewport(int x, int y)
{
if (_game_mode != GM_MENU) {
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
assert(w);
w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
}
}
/**
* Describes all the different arrow key combinations the game allows
* when it is in scrolling mode.
* The real arrow keys are bitwise numbered as
* 1 = left
* 2 = up
* 4 = right
* 8 = down
*/
static const int8 scrollamt[16][2] = {
{ 0, 0}, ///< no key specified
{-2, 0}, ///< 1 : left
{ 0, -2}, ///< 2 : up
{-2, -1}, ///< 3 : left + up
{ 2, 0}, ///< 4 : right
{ 0, 0}, ///< 5 : left + right = nothing
{ 2, -1}, ///< 6 : right + up
{ 0, -2}, ///< 7 : right + left + up = up
{ 0 ,2}, ///< 8 : down
{-2 ,1}, ///< 9 : down + left
{ 0, 0}, ///< 10 : down + up = nothing
{-2, 0}, ///< 11 : left + up + down = left
{ 2, 1}, ///< 12 : down + right
{ 0, 2}, ///< 13 : left + right + down = down
{ 2, 0}, ///< 14 : right + up + down = right
{ 0, 0}, ///< 15 : left + up + right + down = nothing
};
static void HandleKeyScrolling()
{
/*
* Check that any of the dirkeys is pressed and that the focused window
* dont has an edit-box as focused widget.
*/
if (_dirkeys && !EditBoxInGlobalFocus()) {
int factor = _shift_pressed ? 50 : 10;
ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
}
}
void MouseLoop(MouseClick click, int mousewheel)
{
DecreaseWindowCounters();
HandlePlacePresize();
UpdateTileSelection();
if (!VpHandlePlaceSizingDrag()) return;
if (!HandleDragDrop()) return;
if (!HandleWindowDragging()) return;
if (!HandleScrollbarScrolling()) return;
if (!HandleViewportScroll()) return;
if (!HandleMouseOver()) return;
bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
int x = _cursor.pos.x;
int y = _cursor.pos.y;
Window *w = FindWindowFromPt(x, y);
if (w == NULL) return;
if (!MaybeBringWindowToFront(w)) return;
ViewPort *vp = IsPtInWindowViewport(w, x, y);
/* Don't allow any action in a viewport if either in menu of in generating world */
if (vp != NULL && (_game_mode == GM_MENU || IsGeneratingWorld())) return;
if (mousewheel != 0) {
if (_settings_client.gui.scrollwheel_scrolling == 0) {
/* Send mousewheel event to window */
w->OnMouseWheel(mousewheel);
}
/* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
if (vp == NULL) DispatchMouseWheelEvent(w, GetWidgetFromPos(w, x - w->left, y - w->top), mousewheel);
}
if (vp != NULL) {
if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
switch (click) {
case MC_DOUBLE_LEFT:
case MC_LEFT:
DEBUG(misc, 2, "Cursor: 0x%X (%d)", _cursor.sprite, _cursor.sprite);
if (_thd.place_mode != VHM_NONE &&
/* query button and place sign button work in pause mode */
_cursor.sprite != SPR_CURSOR_QUERY &&
_cursor.sprite != SPR_CURSOR_SIGN &&
_pause_game != 0 &&
!_cheats.build_in_pause.value) {
return;
}
if (_thd.place_mode == VHM_NONE) {
if (!HandleViewportClicked(vp, x, y) &&
!(w->flags4 & WF_DISABLE_VP_SCROLL) &&
_settings_client.gui.left_mouse_btn_scrolling) {
_scrolling_viewport = true;
_cursor.fix_at = false;
}
} else {
PlaceObject();
}
break;
case MC_RIGHT:
if (!(w->flags4 & WF_DISABLE_VP_SCROLL)) {
_scrolling_viewport = true;
_cursor.fix_at = true;
}
break;
default:
break;
}
} else {
switch (click) {
case MC_DOUBLE_LEFT:
DispatchLeftClickEvent(w, x - w->left, y - w->top, true);
if (_mouseover_last_w == NULL) break; // The window got removed.
/* fallthough, and also give a single-click for backwards compatibility */
case MC_LEFT:
DispatchLeftClickEvent(w, x - w->left, y - w->top, false);
break;
default:
if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
/* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
* Simulate a right button click so we can get started. */
/* fallthough */
case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
}
}
}
/**
* Handle a mouse event from the video driver
*/
void HandleMouseEvents()
{
static int double_click_time = 0;
static int double_click_x = 0;
static int double_click_y = 0;
/*
* During the generation of the world, there might be
* another thread that is currently building for example
* a road. To not interfere with those tasks, we should
* NOT change the _current_company here.
*
* This is not necessary either, as the only events that
* can be handled are the 'close application' events
*/
if (!IsGeneratingWorld()) _current_company = _local_company;
/* Mouse event? */
MouseClick click = MC_NONE;
if (_left_button_down && !_left_button_clicked) {
click = MC_LEFT;
if (double_click_time != 0 && _realtime_tick - double_click_time < TIME_BETWEEN_DOUBLE_CLICK &&
double_click_x != 0 && abs(_cursor.pos.x - double_click_x) < MAX_OFFSET_DOUBLE_CLICK &&
double_click_y != 0 && abs(_cursor.pos.y - double_click_y) < MAX_OFFSET_DOUBLE_CLICK) {
click = MC_DOUBLE_LEFT;
}
double_click_time = _realtime_tick;
double_click_x = _cursor.pos.x;
double_click_y = _cursor.pos.y;
_left_button_clicked = true;
_input_events_this_tick++;
} else if (_right_button_clicked) {
_right_button_clicked = false;
click = MC_RIGHT;
_input_events_this_tick++;
}
int mousewheel = 0;
if (_cursor.wheel) {
mousewheel = _cursor.wheel;
_cursor.wheel = 0;
_input_events_this_tick++;
}
MouseLoop(click, mousewheel);
}
/**
* Check the soft limit of deletable (non vital, non sticky) windows.
*/
static void CheckSoftLimit()
{
if (_settings_client.gui.window_soft_limit == 0) return;
for (;;) {
uint deletable_count = 0;
Window *w, *last_deletable = NULL;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags4 & WF_STICKY)) continue;
last_deletable = w;
deletable_count++;
}
/* We've ot reached the soft limit yet */
if (deletable_count <= _settings_client.gui.window_soft_limit) break;
assert(last_deletable != NULL);
delete last_deletable;
}
}
/**
* Regular call from the global game loop
*/
void InputLoop()
{
CheckSoftLimit();
HandleKeyScrolling();
/* Do the actual free of the deleted windows. */
for (Window *v = _z_front_window; v != NULL; /* nothing */) {
Window *w = v;
v = v->z_back;
if (w->window_class != WC_INVALID) continue;
/* Find the window in the z-array, and effectively remove it
* by moving all windows after it one to the left. This must be
* done before removing the child so we cannot cause recursion
* between the deletion of the parent and the child. */
if (w->z_front == NULL) {
_z_front_window = w->z_back;
} else {
w->z_front->z_back = w->z_back;
}
if (w->z_back == NULL) {
_z_back_window = w->z_front;
} else {
w->z_back->z_front = w->z_front;
}
free(w);
}
if (_input_events_this_tick != 0) {
/* The input loop is called only once per GameLoop() - so we can clear the counter here */
_input_events_this_tick = 0;
/* there were some inputs this tick, don't scroll ??? */
return;
}
/* HandleMouseEvents was already called for this tick */
HandleMouseEvents();
HandleAutoscroll();
}
/**
* Update the continuously changing contents of the windows, such as the viewports
*/
void UpdateWindows()
{
Window *w;
static int we4_timer = 0;
int t = we4_timer + 1;
if (t >= 100) {
FOR_ALL_WINDOWS_FROM_FRONT(w) {
w->OnHundredthTick();
}
t = 0;
}
we4_timer = t;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
if (w->flags4 & WF_WHITE_BORDER_MASK) {
w->flags4 -= WF_WHITE_BORDER_ONE;
if (!(w->flags4 & WF_WHITE_BORDER_MASK)) w->SetDirty();
}
}
DrawDirtyBlocks();
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->viewport != NULL) UpdateViewportPosition(w);
}
NetworkDrawChatMessage();
/* Redraw mouse cursor in case it was hidden */
DrawMouseCursor();
}
/**
* Mark window as dirty (in need of repainting)
* @param cls Window class
* @param number Window number in that class
*/
void InvalidateWindow(WindowClass cls, WindowNumber number)
{
const Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == cls && w->window_number == number) w->SetDirty();
}
}
/**
* Mark a particular widget in a particular window as dirty (in need of repainting)
* @param cls Window class
* @param number Window number in that class
* @param widget_index Index number of the widget that needs repainting
*/
void InvalidateWindowWidget(WindowClass cls, WindowNumber number, byte widget_index)
{
const Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == cls && w->window_number == number) {
w->InvalidateWidget(widget_index);
}
}
}
/**
* Mark all windows of a particular class as dirty (in need of repainting)
* @param cls Window class
*/
void InvalidateWindowClasses(WindowClass cls)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == cls) w->SetDirty();
}
}
/**
* Mark window data as invalid (in need of re-computing)
* @param w Window with invalid data
*/
void InvalidateThisWindowData(Window *w, int data)
{
w->OnInvalidateData(data);
w->SetDirty();
}
/**
* Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
* @param cls Window class
* @param number Window number within the class
*/
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == cls && w->window_number == number) InvalidateThisWindowData(w, data);
}
}
/**
* Mark window data of all windows of a given class as invalid (in need of re-computing)
* @param cls Window class
*/
void InvalidateWindowClassesData(WindowClass cls, int data)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class == cls) InvalidateThisWindowData(w, data);
}
}
/**
* Dispatch WE_TICK event over all windows
*/
void CallWindowTickEvent()
{
if (_scroller_click_timeout > 3) {
_scroller_click_timeout -= 3;
} else {
_scroller_click_timeout = 0;
}
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
w->OnTick();
}
}
/**
* Try to delete a non-vital window.
* Non-vital windows are windows other than the game selection, main toolbar,
* status bar, toolbar menu, and tooltip windows. Stickied windows are also
* considered vital.
*/
void DeleteNonVitalWindows()
{
Window *w;
restart_search:
/* When we find the window to delete, we need to restart the search
* as deleting this window could cascade in deleting (many) others
* anywhere in the z-array */
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class != WC_MAIN_WINDOW &&
w->window_class != WC_SELECT_GAME &&
w->window_class != WC_MAIN_TOOLBAR &&
w->window_class != WC_STATUS_BAR &&
w->window_class != WC_TOOLBAR_MENU &&
w->window_class != WC_TOOLTIPS &&
(w->flags4 & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
delete w;
goto restart_search;
}
}
}
/** It is possible that a stickied window gets to a position where the
* 'close' button is outside the gaming area. You cannot close it then; except
* with this function. It closes all windows calling the standard function,
* then, does a little hacked loop of closing all stickied windows. Note
* that standard windows (status bar, etc.) are not stickied, so these aren't affected */
void DeleteAllNonVitalWindows()
{
Window *w;
/* Delete every window except for stickied ones, then sticky ones as well */
DeleteNonVitalWindows();
restart_search:
/* When we find the window to delete, we need to restart the search
* as deleting this window could cascade in deleting (many) others
* anywhere in the z-array */
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->flags4 & WF_STICKY) {
delete w;
goto restart_search;
}
}
}
/**
* Delete all windows that are used for construction of vehicle etc.
* Once done with that invalidate the others to ensure they get refreshed too.
*/
void DeleteConstructionWindows()
{
Window *w;
restart_search:
/* When we find the window to delete, we need to restart the search
* as deleting this window could cascade in deleting (many) others
* anywhere in the z-array */
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->desc_flags & WDF_CONSTRUCTION) {
delete w;
goto restart_search;
}
}
FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
}
/** Delete all always on-top windows to get an empty screen */
void HideVitalWindows()
{
DeleteWindowById(WC_TOOLBAR_MENU, 0);
DeleteWindowById(WC_MAIN_TOOLBAR, 0);
DeleteWindowById(WC_STATUS_BAR, 0);
}
/**
* (Re)position main toolbar window at the screen
* @param w Window structure of the main toolbar window, may also be \c NULL
* @return X coordinate of left edge of the repositioned toolbar window
*/
int PositionMainToolbar(Window *w)
{
DEBUG(misc, 5, "Repositioning Main Toolbar...");
if (w == NULL || w->window_class != WC_MAIN_TOOLBAR) {
w = FindWindowById(WC_MAIN_TOOLBAR, 0);
}
switch (_settings_client.gui.toolbar_pos) {
case 1: w->left = (_screen.width - w->width) / 2; break;
case 2: w->left = _screen.width - w->width; break;
default: w->left = 0;
}
SetDirtyBlocks(0, 0, _screen.width, w->height); // invalidate the whole top part
return w->left;
}
/**
* Set the number of items of the vertical scrollbar.
*
* Function also updates the position of the scrollbar if necessary.
* @param w Window containing the vertical scrollbar
* @param num New number of items
*/
void SetVScrollCount(Window *w, int num)
{
w->vscroll.count = num;
num -= w->vscroll.cap;
if (num < 0) num = 0;
if (num < w->vscroll.pos) w->vscroll.pos = num;
}
/**
* Set the number of items of the second vertical scrollbar.
*
* Function also updates the position of the scrollbar if necessary.
* @param w Window containing the second vertical scrollbar
* @param num New number of items
*/
void SetVScroll2Count(Window *w, int num)
{
w->vscroll2.count = num;
num -= w->vscroll2.cap;
if (num < 0) num = 0;
if (num < w->vscroll2.pos) w->vscroll2.pos = num;
}
/**
* Set the number of items of the horizontal scrollbar.
*
* Function also updates the position of the scrollbar if necessary.
* @param w Window containing the horizontal scrollbar
* @param num New number of items
*/
void SetHScrollCount(Window *w, int num)
{
w->hscroll.count = num;
num -= w->hscroll.cap;
if (num < 0) num = 0;
if (num < w->hscroll.pos) w->hscroll.pos = num;
}
/**
* Relocate all windows to fit the new size of the game application screen
* @param neww New width of the game application screen
* @param newh New height of the game appliction screen
*/
void RelocateAllWindows(int neww, int newh)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
int left, top;
if (w->window_class == WC_MAIN_WINDOW) {
ViewPort *vp = w->viewport;
vp->width = w->width = neww;
vp->height = w->height = newh;
vp->virtual_width = ScaleByZoom(neww, vp->zoom);
vp->virtual_height = ScaleByZoom(newh, vp->zoom);
continue; // don't modify top,left
}
/* XXX - this probably needs something more sane. For example specying
* in a 'backup'-desc that the window should always be centred. */
switch (w->window_class) {
case WC_MAIN_TOOLBAR:
if (neww - w->width != 0) {
ResizeWindow(w, min(neww, 640) - w->width, 0);
Point size;
Point delta;
size.x = w->width;
size.y = w->height;
delta.x = neww - w->width;
delta.y = 0;
w->OnResize(size, delta);
}
top = w->top;
left = PositionMainToolbar(w); // changes toolbar orientation
break;
case WC_SELECT_GAME:
case WC_GAME_OPTIONS:
case WC_NETWORK_WINDOW:
top = (newh - w->height) >> 1;
left = (neww - w->width) >> 1;
break;
case WC_NEWS_WINDOW:
top = newh - w->height;
left = (neww - w->width) >> 1;
break;
case WC_STATUS_BAR:
ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0);
top = newh - w->height;
left = (neww - w->width) >> 1;
break;
case WC_SEND_NETWORK_MSG:
ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0);
top = (newh - 26); // 26 = height of status bar + height of chat bar
left = (neww - w->width) >> 1;
break;
case WC_CONSOLE:
IConsoleResize(w);
continue;
default: {
left = w->left;
if (left + (w->width >> 1) >= neww) left = neww - w->width;
if (left < 0) left = 0;
top = w->top;
if (top + (w->height >> 1) >= newh) top = newh - w->height;
const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
if (wt != NULL) {
if (top < wt->height && wt->left < (w->left + w->width) && (wt->left + wt->width) > w->left) top = wt->height;
if (top >= newh) top = newh - 1;
} else {
if (top < 0) top = 0;
}
} break;
}
if (w->viewport != NULL) {
w->viewport->left += left - w->left;
w->viewport->top += top - w->top;
}
w->left = left;
w->top = top;
}
}
/** Destructor of the base class PickerWindowBase
* Main utility is to stop the base Window destructor from triggering
* a free while the child will already be free, in this case by the ResetObjectToPlace().
*/
PickerWindowBase::~PickerWindowBase()
{
this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
ResetObjectToPlace();
}
| 73,132
|
C++
|
.cpp
| 2,149
| 31.154956
| 139
| 0.674864
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,104
|
highscore_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/highscore_gui.cpp
|
/* $Id$ */
/** @file highscore_gui.cpp Definition of the HighScore and EndGame windows */
#include "highscore.h"
#include "table/strings.h"
#include "gfx_func.h"
#include "table/sprites.h"
#include "window_gui.h"
#include "window_func.h"
#include "network/network.h"
#include "command_func.h"
#include "company_func.h"
#include "company_base.h"
#include "settings_type.h"
#include "strings_func.h"
#include "openttd.h"
struct EndGameHighScoreBaseWindow : Window {
uint32 background_img;
int8 rank;
EndGameHighScoreBaseWindow(const WindowDesc *desc) : Window(desc)
{
}
/* Always draw a maximized window and within there the centered background */
void SetupHighScoreEndWindow(uint *x, uint *y)
{
/* resize window to "full-screen" */
this->width = _screen.width;
this->height = _screen.height;
this->widget[0].right = this->width - 1;
this->widget[0].bottom = this->height - 1;
this->DrawWidgets();
/* Center Highscore/Endscreen background */
*x = max(0, (_screen.width / 2) - (640 / 2));
*y = max(0, (_screen.height / 2) - (480 / 2));
for (uint i = 0; i < 10; i++) { // the image is split into 10 50px high parts
DrawSprite(this->background_img + i, PAL_NONE, *x, *y + (i * 50));
}
}
virtual void OnClick(Point pt, int widget)
{
delete this;
}
};
/** End game window shown at the end of the game */
struct EndGameWindow : EndGameHighScoreBaseWindow {
EndGameWindow(const WindowDesc *desc) : EndGameHighScoreBaseWindow(desc)
{
/* Pause in single-player to have a look at the highscore at your own leisure */
if (!_networking) DoCommandP(0, 1, 0, CMD_PAUSE);
this->background_img = SPR_TYCOON_IMG1_BEGIN;
if (_local_company != COMPANY_SPECTATOR) {
const Company *c = GetCompany(_local_company);
if (c->old_economy[0].performance_history == SCORE_MAX) {
this->background_img = SPR_TYCOON_IMG2_BEGIN;
}
}
/* In a network game show the endscores of the custom difficulty 'network' which is the last one
* as well as generate a TOP5 of that game, and not an all-time top5. */
if (_networking) {
this->window_number = lengthof(_highscore_table) - 1;
this->rank = SaveHighScoreValueNetwork();
} else {
/* in single player _local company is always valid */
const Company *c = GetCompany(_local_company);
this->window_number = _settings_game.difficulty.diff_level;
this->rank = SaveHighScoreValue(c);
}
MarkWholeScreenDirty();
}
~EndGameWindow()
{
if (!_networking) DoCommandP(0, 0, 0, CMD_PAUSE); // unpause
ShowHighscoreTable(this->window_number, this->rank);
}
virtual void OnPaint()
{
const Company *c;
uint x, y;
this->SetupHighScoreEndWindow(&x, &y);
if (!IsValidCompanyID(_local_company)) return;
c = GetCompany(_local_company);
/* We need to get performance from last year because the image is shown
* at the start of the new year when these things have already been copied */
if (this->background_img == SPR_TYCOON_IMG2_BEGIN) { // Tycoon of the century \o/
SetDParam(0, c->index);
SetDParam(1, c->index);
SetDParam(2, EndGameGetPerformanceTitleFromValue(c->old_economy[0].performance_history));
DrawStringMultiCenter(x + (640 / 2), y + 107, STR_021C_OF_ACHIEVES_STATUS, 640);
} else {
SetDParam(0, c->index);
SetDParam(1, EndGameGetPerformanceTitleFromValue(c->old_economy[0].performance_history));
DrawStringMultiCenter(x + (640 / 2), y + 157, STR_021B_ACHIEVES_STATUS, 640);
}
}
};
struct HighScoreWindow : EndGameHighScoreBaseWindow {
HighScoreWindow(const WindowDesc *desc, int difficulty, int8 ranking) : EndGameHighScoreBaseWindow(desc)
{
/* pause game to show the chart */
if (!_networking) DoCommandP(0, 1, 0, CMD_PAUSE);
/* Close all always on-top windows to get a clean screen */
if (_game_mode != GM_MENU) HideVitalWindows();
MarkWholeScreenDirty();
this->window_number = difficulty; // show highscore chart for difficulty...
this->background_img = SPR_HIGHSCORE_CHART_BEGIN; // which background to show
this->rank = ranking;
}
~HighScoreWindow()
{
if (_game_mode != GM_MENU) ShowVitalWindows();
if (!_networking) DoCommandP(0, 0, 0, CMD_PAUSE); // unpause
}
virtual void OnPaint()
{
const HighScore *hs = _highscore_table[this->window_number];
uint x, y;
this->SetupHighScoreEndWindow(&x, &y);
SetDParam(0, ORIGINAL_END_YEAR);
SetDParam(1, this->window_number + STR_6801_EASY);
DrawStringMultiCenter(x + (640 / 2), y + 62, !_networking ? STR_0211_TOP_COMPANIES_WHO_REACHED : STR_TOP_COMPANIES_NETWORK_GAME, 500);
/* Draw Highscore peepz */
for (uint8 i = 0; i < lengthof(_highscore_table[0]); i++) {
SetDParam(0, i + 1);
DrawString(x + 40, y + 140 + (i * 55), STR_0212, TC_BLACK);
if (hs[i].company[0] != '\0') {
TextColour colour = (this->rank == i) ? TC_RED : TC_BLACK; // draw new highscore in red
DoDrawString(hs[i].company, x + 71, y + 140 + (i * 55), colour);
SetDParam(0, hs[i].title);
SetDParam(1, hs[i].score);
DrawString(x + 71, y + 160 + (i * 55), STR_HIGHSCORE_STATS, colour);
}
}
}
};
static const Widget _highscore_widgets[] = {
{ WWT_PANEL, RESIZE_NONE, COLOUR_END, 0, 640, 0, 480, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _highscore_desc(
0, 0, 641, 481, 641, 481,
WC_HIGHSCORE, WC_NONE,
0,
_highscore_widgets
);
static const WindowDesc _endgame_desc(
0, 0, 641, 481, 641, 481,
WC_ENDSCREEN, WC_NONE,
0,
_highscore_widgets
);
/** Show the highscore table for a given difficulty. When called from
* endgame ranking is set to the top5 element that was newly added
* and is thus highlighted */
void ShowHighscoreTable(int difficulty, int8 ranking)
{
DeleteWindowByClass(WC_HIGHSCORE);
new HighScoreWindow(&_highscore_desc, difficulty, ranking);
}
/** Show the endgame victory screen in 2050. Update the new highscore
* if it was high enough */
void ShowEndGameChart()
{
/* Dedicated server doesn't need the highscore window and neither does -v null. */
if (_network_dedicated || (!_networking && !IsValidCompanyID(_local_company))) return;
HideVitalWindows();
DeleteWindowByClass(WC_ENDSCREEN);
new EndGameWindow(&_endgame_desc);
}
| 6,163
|
C++
|
.cpp
| 167
| 34.227545
| 136
| 0.703741
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,106
|
cargopacket.cpp
|
EnergeticBark_OpenTTD-3DS/src/cargopacket.cpp
|
/* $Id$ */
/** @file cargopacket.cpp Implementation of the cargo packets */
#include "stdafx.h"
#include "station_base.h"
#include "oldpool_func.h"
/* Initialize the cargopacket-pool */
DEFINE_OLD_POOL_GENERIC(CargoPacket, CargoPacket)
void InitializeCargoPackets()
{
/* Clean the cargo packet pool and create 1 block in it */
_CargoPacket_pool.CleanPool();
_CargoPacket_pool.AddBlockToPool();
}
CargoPacket::CargoPacket(StationID source, uint16 count)
{
if (source != INVALID_STATION) assert(count != 0);
this->source = source;
this->source_xy = (source != INVALID_STATION) ? GetStation(source)->xy : 0;
this->loaded_at_xy = this->source_xy;
this->count = count;
this->days_in_transit = 0;
this->feeder_share = 0;
this->paid_for = false;
}
CargoPacket::~CargoPacket()
{
this->count = 0;
}
bool CargoPacket::SameSource(const CargoPacket *cp) const
{
return this->source_xy == cp->source_xy && this->days_in_transit == cp->days_in_transit && this->paid_for == cp->paid_for;
}
/*
*
* Cargo list implementation
*
*/
CargoList::~CargoList()
{
while (!packets.empty()) {
delete packets.front();
packets.pop_front();
}
}
const CargoList::List *CargoList::Packets() const
{
return &packets;
}
void CargoList::AgeCargo()
{
if (empty) return;
uint dit = 0;
for (List::const_iterator it = packets.begin(); it != packets.end(); it++) {
if ((*it)->days_in_transit != 0xFF) (*it)->days_in_transit++;
dit += (*it)->days_in_transit * (*it)->count;
}
days_in_transit = dit / count;
}
bool CargoList::Empty() const
{
return empty;
}
uint CargoList::Count() const
{
return count;
}
bool CargoList::UnpaidCargo() const
{
return unpaid_cargo;
}
Money CargoList::FeederShare() const
{
return feeder_share;
}
StationID CargoList::Source() const
{
return source;
}
uint CargoList::DaysInTransit() const
{
return days_in_transit;
}
void CargoList::Append(CargoPacket *cp)
{
assert(cp != NULL);
assert(cp->IsValid());
for (List::iterator it = packets.begin(); it != packets.end(); it++) {
if ((*it)->SameSource(cp) && (*it)->count + cp->count <= 65535) {
(*it)->count += cp->count;
(*it)->feeder_share += cp->feeder_share;
delete cp;
InvalidateCache();
return;
}
}
/* The packet could not be merged with another one */
packets.push_back(cp);
InvalidateCache();
}
void CargoList::Truncate(uint count)
{
for (List::iterator it = packets.begin(); it != packets.end(); it++) {
uint local_count = (*it)->count;
if (local_count <= count) {
count -= local_count;
continue;
}
(*it)->count = count;
count = 0;
}
while (!packets.empty()) {
CargoPacket *cp = packets.back();
if (cp->count != 0) break;
delete cp;
packets.pop_back();
}
InvalidateCache();
}
bool CargoList::MoveTo(CargoList *dest, uint count, CargoList::MoveToAction mta, uint data)
{
assert(mta == MTA_FINAL_DELIVERY || dest != NULL);
CargoList tmp;
while (!packets.empty() && count > 0) {
CargoPacket *cp = *packets.begin();
if (cp->count <= count) {
/* Can move the complete packet */
packets.remove(cp);
switch (mta) {
case MTA_FINAL_DELIVERY:
if (cp->source == data) {
tmp.Append(cp);
} else {
count -= cp->count;
delete cp;
}
break;
case MTA_CARGO_LOAD:
cp->loaded_at_xy = data;
/* When cargo is moved into another vehicle you have *always* paid for it */
cp->paid_for = false;
/* FALL THROUGH */
case MTA_OTHER:
count -= cp->count;
dest->packets.push_back(cp);
break;
}
} else {
/* Can move only part of the packet, so split it into two pieces */
if (mta != MTA_FINAL_DELIVERY) {
CargoPacket *cp_new = new CargoPacket();
Money fs = cp->feeder_share * count / static_cast<uint>(cp->count);
cp->feeder_share -= fs;
cp_new->source = cp->source;
cp_new->source_xy = cp->source_xy;
cp_new->loaded_at_xy = (mta == MTA_CARGO_LOAD) ? data : cp->loaded_at_xy;
cp_new->days_in_transit = cp->days_in_transit;
cp_new->feeder_share = fs;
/* When cargo is moved into another vehicle you have *always* paid for it */
cp_new->paid_for = (mta == MTA_CARGO_LOAD) ? false : cp->paid_for;
cp_new->count = count;
dest->packets.push_back(cp_new);
}
cp->count -= count;
count = 0;
}
}
bool remaining = !packets.empty();
if (mta == MTA_FINAL_DELIVERY && !tmp.Empty()) {
/* There are some packets that could not be delivered at the station, put them back */
tmp.MoveTo(this, UINT_MAX);
tmp.packets.clear();
}
if (dest != NULL) dest->InvalidateCache();
InvalidateCache();
return remaining;
}
void CargoList::InvalidateCache()
{
empty = packets.empty();
count = 0;
unpaid_cargo = false;
feeder_share = 0;
source = INVALID_STATION;
days_in_transit = 0;
if (empty) return;
uint dit = 0;
for (List::const_iterator it = packets.begin(); it != packets.end(); it++) {
count += (*it)->count;
unpaid_cargo |= !(*it)->paid_for;
dit += (*it)->days_in_transit * (*it)->count;
feeder_share += (*it)->feeder_share;
}
days_in_transit = dit / count;
source = (*packets.begin())->source;
}
| 5,218
|
C++
|
.cpp
| 195
| 24.005128
| 123
| 0.64772
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,107
|
highscore.cpp
|
EnergeticBark_OpenTTD-3DS/src/highscore.cpp
|
/* $Id$ */
/** @file highscore.cpp Definition of functions used for highscore handling */
#include "highscore.h"
#include "settings_type.h"
#include "company_base.h"
#include "company_func.h"
#include "cheat_func.h"
#include "string_func.h"
#include "strings_func.h"
#include "table/strings.h"
#include "core/sort_func.hpp"
#include "variables.h"
#include "debug.h"
HighScore _highscore_table[5][5]; // 4 difficulty-settings (+ network); top 5
static const StringID _endgame_perf_titles[] = {
STR_0213_BUSINESSMAN,
STR_0213_BUSINESSMAN,
STR_0213_BUSINESSMAN,
STR_0213_BUSINESSMAN,
STR_0213_BUSINESSMAN,
STR_0214_ENTREPRENEUR,
STR_0214_ENTREPRENEUR,
STR_0215_INDUSTRIALIST,
STR_0215_INDUSTRIALIST,
STR_0216_CAPITALIST,
STR_0216_CAPITALIST,
STR_0217_MAGNATE,
STR_0217_MAGNATE,
STR_0218_MOGUL,
STR_0218_MOGUL,
STR_0219_TYCOON_OF_THE_CENTURY
};
StringID EndGameGetPerformanceTitleFromValue(uint value)
{
value = minu(value / 64, lengthof(_endgame_perf_titles) - 1);
return _endgame_perf_titles[value];
}
/** Save the highscore for the company */
int8 SaveHighScoreValue(const Company *c)
{
HighScore *hs = _highscore_table[_settings_game.difficulty.diff_level];
uint i;
uint16 score = c->old_economy[0].performance_history;
/* Exclude cheaters from the honour of being in the highscore table */
if (CheatHasBeenUsed()) return -1;
for (i = 0; i < lengthof(_highscore_table[0]); i++) {
/* You are in the TOP5. Move all values one down and save us there */
if (hs[i].score <= score) {
/* move all elements one down starting from the replaced one */
memmove(&hs[i + 1], &hs[i], sizeof(HighScore) * (lengthof(_highscore_table[0]) - i - 1));
SetDParam(0, c->index);
SetDParam(1, c->index);
GetString(hs[i].company, STR_HIGHSCORE_NAME, lastof(hs[i].company)); // get manager/company name string
hs[i].score = score;
hs[i].title = EndGameGetPerformanceTitleFromValue(score);
return i;
}
}
return -1; // too bad; we did not make it into the top5
}
/** Sort all companies given their performance */
static int CDECL HighScoreSorter(const Company * const *a, const Company * const *b)
{
return (*b)->old_economy[0].performance_history - (*a)->old_economy[0].performance_history;
}
/* Save the highscores in a network game when it has ended */
#define LAST_HS_ITEM lengthof(_highscore_table) - 1
int8 SaveHighScoreValueNetwork()
{
const Company *c;
const Company *cl[MAX_COMPANIES];
uint count = 0;
int8 company = -1;
/* Sort all active companies with the highest score first */
FOR_ALL_COMPANIES(c) cl[count++] = c;
QSortT(cl, count, &HighScoreSorter);
{
uint i;
memset(_highscore_table[LAST_HS_ITEM], 0, sizeof(_highscore_table[0]));
/* Copy over Top5 companies */
for (i = 0; i < lengthof(_highscore_table[LAST_HS_ITEM]) && i < count; i++) {
HighScore *hs = &_highscore_table[LAST_HS_ITEM][i];
SetDParam(0, cl[i]->index);
SetDParam(1, cl[i]->index);
GetString(hs->company, STR_HIGHSCORE_NAME, lastof(hs->company)); // get manager/company name string
hs->score = cl[i]->old_economy[0].performance_history;
hs->title = EndGameGetPerformanceTitleFromValue(hs->score);
/* get the ranking of the local company */
if (cl[i]->index == _local_company) company = i;
}
}
/* Add top5 companys to highscore table */
return company;
}
/** Save HighScore table to file */
void SaveToHighScore()
{
FILE *fp = fopen(_highscore_file, "wb");
if (fp != NULL) {
uint i;
HighScore *hs;
for (i = 0; i < LAST_HS_ITEM; i++) { // don't save network highscores
for (hs = _highscore_table[i]; hs != endof(_highscore_table[i]); hs++) {
/* First character is a command character, so strlen will fail on that */
byte length = min(sizeof(hs->company), StrEmpty(hs->company) ? 0 : (int)strlen(&hs->company[1]) + 1);
if (fwrite(&length, sizeof(length), 1, fp) != 1 || // write away string length
fwrite(hs->company, length, 1, fp) > 1 || // Yes... could be 0 bytes too
fwrite(&hs->score, sizeof(hs->score), 1, fp) != 1 ||
fwrite(" ", 2, 1, fp) != 1) { // XXX - placeholder for hs->title, not saved anymore; compatibility
DEBUG(misc, 1, "Could not save highscore.");
i = LAST_HS_ITEM;
break;
}
}
}
fclose(fp);
}
}
/** Initialize the highscore table to 0 and if any file exists, load in values */
void LoadFromHighScore()
{
FILE *fp = fopen(_highscore_file, "rb");
memset(_highscore_table, 0, sizeof(_highscore_table));
if (fp != NULL) {
uint i;
HighScore *hs;
for (i = 0; i < LAST_HS_ITEM; i++) { // don't load network highscores
for (hs = _highscore_table[i]; hs != endof(_highscore_table[i]); hs++) {
byte length;
if (fread(&length, sizeof(length), 1, fp) != 1 ||
fread(hs->company, length, 1, fp) > 1 || // Yes... could be 0 bytes too
fread(&hs->score, sizeof(hs->score), 1, fp) != 1 ||
fseek(fp, 2, SEEK_CUR) == -1) { // XXX - placeholder for hs->title, not saved anymore; compatibility
DEBUG(misc, 1, "Highscore corrupted");
i = LAST_HS_ITEM;
break;
}
*lastof(hs->company) = '\0';
hs->title = EndGameGetPerformanceTitleFromValue(hs->score);
}
}
fclose(fp);
}
}
| 5,271
|
C++
|
.cpp
| 144
| 33.722222
| 127
| 0.669347
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,108
|
tunnelbridge_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/tunnelbridge_cmd.cpp
|
/* $Id$ */
/** @file tunnelbridge_cmd.cpp
* This file deals with tunnels and bridges (non-gui stuff)
* @todo seperate this file into two
*/
#include "stdafx.h"
#include "openttd.h"
#include "rail_map.h"
#include "landscape.h"
#include "unmovable_map.h"
#include "viewport_func.h"
#include "command_func.h"
#include "town.h"
#include "variables.h"
#include "train.h"
#include "water_map.h"
#include "yapf/yapf.h"
#include "newgrf_sound.h"
#include "autoslope.h"
#include "tunnelbridge_map.h"
#include "strings_func.h"
#include "date_func.h"
#include "functions.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "tunnelbridge.h"
#include "engine_base.h"
#include "cheat_type.h"
#include "elrail_func.h"
#include "landscape_type.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "table/bridge_land.h"
BridgeSpec _bridge[MAX_BRIDGES];
TileIndex _build_tunnel_endtile;
/** Reset the data been eventually changed by the grf loaded. */
void ResetBridges()
{
/* First, free sprite table data */
for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
if (_bridge[i].sprite_table != NULL) {
for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
free(_bridge[i].sprite_table);
}
}
/* Then, wipe out current bidges */
memset(&_bridge, 0, sizeof(_bridge));
/* And finally, reinstall default data */
memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
}
/** calculate the price factor for building a long bridge.
* basically the cost delta is 1,1, 1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5,5, 6,6,6,6,6,6, 7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,
*/
int CalcBridgeLenCostFactor(int x)
{
int n;
int r;
if (x < 2) return x;
x -= 2;
for (n = 0, r = 2;; n++) {
if (x <= n) return r + x * n;
r += n * n;
x -= n;
}
}
Foundation GetBridgeFoundation(Slope tileh, Axis axis)
{
if ((tileh == SLOPE_FLAT) ||
(((tileh == SLOPE_NE) || (tileh == SLOPE_SW)) && (axis == AXIS_X)) ||
(((tileh == SLOPE_NW) || (tileh == SLOPE_SE)) && (axis == AXIS_Y))) return FOUNDATION_NONE;
return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
}
/**
* Determines if the track on a bridge ramp is flat or goes up/down.
*
* @param tileh Slope of the tile under the bridge head
* @param axis Orientation of bridge
* @return true iff the track is flat.
*/
bool HasBridgeFlatRamp(Slope tileh, Axis axis)
{
ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
/* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
return (tileh != SLOPE_FLAT);
}
static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
{
const BridgeSpec *bridge = GetBridgeSpec(index);
assert(table < BRIDGE_PIECE_INVALID);
if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
return _bridge_sprite_table[index][table];
} else {
return bridge->sprite_table[table];
}
}
/**
* Determines the foundation for the north bridge head, and tests if the resulting slope is valid.
*
* @param axis Axis of the bridge
* @param tileh Slope of the tile under the north bridge head; returns slope on top of foundation
* @param z TileZ corresponding to tileh, gets modified as well
* @return Error or cost for bridge foundation
*/
static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, uint *z)
{
Foundation f = GetBridgeFoundation(*tileh, axis);
*z += ApplyFoundationToSlope(f, tileh);
Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
if (f == FOUNDATION_NONE) return CommandCost();
return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
}
/**
* Determines the foundation for the south bridge head, and tests if the resulting slope is valid.
*
* @param axis Axis of the bridge
* @param tileh Slope of the tile under the south bridge head; returns slope on top of foundation
* @param z TileZ corresponding to tileh, gets modified as well
* @return Error or cost for bridge foundation
*/
static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, uint *z)
{
Foundation f = GetBridgeFoundation(*tileh, axis);
*z += ApplyFoundationToSlope(f, tileh);
Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
if (f == FOUNDATION_NONE) return CommandCost();
return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
}
bool CheckBridge_Stuff(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
{
if (flags & DC_QUERY_COST) {
return bridge_len <= (_settings_game.construction.longbridges ? 100U : 16U);
}
if (bridge_type >= MAX_BRIDGES) return false;
const BridgeSpec *b = GetBridgeSpec(bridge_type);
if (b->avail_year > _cur_year) return false;
uint max = b->max_length;
if (max >= 16 && _settings_game.construction.longbridges) max = 100;
return b->min_length <= bridge_len && bridge_len <= max;
}
/** Build a Bridge
* @param end_tile end tile
* @param flags type of operation
* @param p1 packed start tile coords (~ dx)
* @param p2 various bitstuffed elements
* - p2 = (bit 0- 7) - bridge type (hi bh)
* - p2 = (bit 8-14) - rail type or road types.
* - p2 = (bit 15-16) - transport type.
*/
CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
BridgeType bridge_type;
RailType railtype = INVALID_RAILTYPE;
RoadTypes roadtypes = ROADTYPES_NONE;
uint x;
uint y;
uint sx;
uint sy;
TileIndex tile_start;
TileIndex tile_end;
Slope tileh_start;
Slope tileh_end;
uint z_start;
uint z_end;
TileIndex tile;
TileIndexDiff delta;
uint bridge_len;
Axis direction;
CommandCost cost(EXPENSES_CONSTRUCTION);
CommandCost ret;
bool replace_bridge = false;
BridgeType replaced_bridge_type;
TransportType transport_type;
/* unpack parameters */
bridge_type = GB(p2, 0, 8);
if (p1 >= MapSize()) return CMD_ERROR;
transport_type = (TransportType)GB(p2, 15, 2);
/* type of bridge */
switch (transport_type) {
case TRANSPORT_ROAD:
roadtypes = (RoadTypes)GB(p2, 8, 2);
if (!AreValidRoadTypes(roadtypes) || !HasRoadTypesAvail(_current_company, roadtypes)) return CMD_ERROR;
break;
case TRANSPORT_RAIL:
railtype = (RailType)GB(p2, 8, 7);
if (!ValParamRailtype(railtype)) return CMD_ERROR;
break;
case TRANSPORT_WATER:
break;
default:
/* Airports don't have tunnels. */
return CMD_ERROR;
}
x = TileX(end_tile);
y = TileY(end_tile);
sx = TileX(p1);
sy = TileY(p1);
/* check if valid, and make sure that (x,y) are smaller than (sx,sy) */
if (x == sx) {
if (y == sy) return_cmd_error(STR_5008_CANNOT_START_AND_END_ON);
direction = AXIS_Y;
if (y > sy) Swap(y, sy);
} else if (y == sy) {
direction = AXIS_X;
if (x > sx) Swap(x, sx);
} else {
return_cmd_error(STR_500A_START_AND_END_MUST_BE_IN);
}
bridge_len = sx + sy - x - y - 1;
if (transport_type != TRANSPORT_WATER) {
/* set and test bridge length, availability */
if (!CheckBridge_Stuff(bridge_type, bridge_len, flags)) return_cmd_error(STR_5015_CAN_T_BUILD_BRIDGE_HERE);
}
/* retrieve landscape height and ensure it's on land */
tile_start = TileXY(x, y);
tile_end = TileXY(sx, sy);
if (IsWaterTile(tile_start) || IsWaterTile(tile_end)) {
return_cmd_error(STR_02A0_ENDS_OF_BRIDGE_MUST_BOTH);
}
tileh_start = GetTileSlope(tile_start, &z_start);
tileh_end = GetTileSlope(tile_end, &z_end);
CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end, &z_end);
if (z_start != z_end) return_cmd_error(STR_BRIDGEHEADS_NOT_SAME_HEIGHT);
if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
GetOtherBridgeEnd(tile_start) == tile_end &&
GetTunnelBridgeTransportType(tile_start) == transport_type) {
/* Replace a current bridge. */
/* If this is a railway bridge, make sure the railtypes match. */
if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
}
/* Do not replace town bridges with lower speed bridges. */
if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed) {
Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
if (t == NULL) {
return CMD_ERROR;
} else {
SetDParam(0, t->index);
return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
}
}
/* Do not replace the bridge with the same bridge type. */
if (!(flags & DC_QUERY_COST) && bridge_type == GetBridgeType(tile_start)) {
return_cmd_error(STR_1007_ALREADY_BUILT);
}
/* Do not allow replacing another company's bridges. */
if (!IsTileOwner(tile_start, _current_company) && !IsTileOwner(tile_start, OWNER_TOWN)) {
return_cmd_error(STR_1024_AREA_IS_OWNED_BY_ANOTHER);
}
cost.AddCost((bridge_len + 1) * _price.clear_bridge); // The cost of clearing the current bridge.
replace_bridge = true;
replaced_bridge_type = GetBridgeType(tile_start);
/* Do not remove road types when upgrading a bridge */
roadtypes |= GetRoadTypes(tile_start);
} else {
/* Build a new bridge. */
bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
/* Try and clear the start landscape */
ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return ret;
cost = ret;
if (CmdFailed(terraform_cost_north) || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes))
return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
cost.AddCost(terraform_cost_north);
/* Try and clear the end landscape */
ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return ret;
cost.AddCost(ret);
/* false - end tile slope check */
if (CmdFailed(terraform_cost_south) || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes))
return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
cost.AddCost(terraform_cost_south);
if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
}
if (!replace_bridge) {
TileIndex Heads[] = {tile_start, tile_end};
int i;
for (i = 0; i < 2; i++) {
if (MayHaveBridgeAbove(Heads[i])) {
if (IsBridgeAbove(Heads[i])) {
TileIndex north_head = GetNorthernBridgeEnd(Heads[i]);
if (direction == GetBridgeAxis(Heads[i])) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
if (z_start + TILE_HEIGHT == GetBridgeHeight(north_head)) {
return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
}
}
}
}
}
/* do the drill? */
if (flags & DC_EXEC) {
DiagDirection dir = AxisToDiagDir(direction);
Owner owner = replace_bridge ? GetTileOwner(tile_start) : _current_company;
switch (transport_type) {
case TRANSPORT_RAIL:
MakeRailBridgeRamp(tile_start, owner, bridge_type, dir, railtype);
MakeRailBridgeRamp(tile_end, owner, bridge_type, ReverseDiagDir(dir), railtype);
break;
case TRANSPORT_ROAD:
MakeRoadBridgeRamp(tile_start, owner, bridge_type, dir, roadtypes);
MakeRoadBridgeRamp(tile_end, owner, bridge_type, ReverseDiagDir(dir), roadtypes);
break;
case TRANSPORT_WATER:
MakeAqueductBridgeRamp(tile_start, owner, dir);
MakeAqueductBridgeRamp(tile_end, owner, ReverseDiagDir(dir));
break;
default:
NOT_REACHED();
break;
}
MarkTileDirtyByTile(tile_start);
MarkTileDirtyByTile(tile_end);
}
delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
for (tile = tile_start + delta; tile != tile_end; tile += delta) {
if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_BRIDGE_TOO_LOW_FOR_TERRAIN);
if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) && !replace_bridge) {
/* Disallow crossing bridges for the time being */
return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
}
switch (GetTileType(tile)) {
case MP_WATER:
if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
break;
case MP_RAILWAY:
if (!IsPlainRailTile(tile)) goto not_valid_below;
break;
case MP_ROAD:
if (IsRoadDepot(tile)) goto not_valid_below;
break;
case MP_TUNNELBRIDGE:
if (IsTunnel(tile)) break;
if (replace_bridge) break;
if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
break;
case MP_UNMOVABLE:
if (!IsOwnedLand(tile)) goto not_valid_below;
break;
case MP_CLEAR:
break;
default:
not_valid_below:;
/* try and clear the middle landscape */
ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return ret;
cost.AddCost(ret);
break;
}
if (flags & DC_EXEC) {
SetBridgeMiddle(tile, direction);
MarkTileDirtyByTile(tile);
}
}
if (flags & DC_EXEC && transport_type == TRANSPORT_RAIL) {
Track track = AxisToTrack(direction);
AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, _current_company);
YapfNotifyTrackLayoutChange(tile_start, track);
}
/* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
* It's unnecessary to execute this command every time for every bridge. So it is done only
* and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
*/
if (!(flags & DC_QUERY_COST) || (IsValidCompanyID(_current_company) && GetCompany(_current_company)->is_ai)) {
bridge_len += 2; // begin and end tiles/ramps
if (IsValidCompanyID(_current_company))
bridge_len = CalcBridgeLenCostFactor(bridge_len);
cost.AddCost((int64)bridge_len * _price.build_bridge * GetBridgeSpec(bridge_type)->price >> 8);
/* Aqueducts are a little more expensive. */
if (transport_type == TRANSPORT_WATER) cost.AddCost((int64)bridge_len * _price.clear_water);
}
return cost;
}
/** Build Tunnel.
* @param start_tile start tile of tunnel
* @param flags type of operation
* @param p1 railtype or roadtypes. bit 9 set means road tunnel
* @param p2 unused
*/
CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
TileIndexDiff delta;
TileIndex end_tile;
DiagDirection direction;
Slope start_tileh;
Slope end_tileh;
TransportType transport_type = (TransportType)GB(p1, 9, 1);
uint start_z;
uint end_z;
CommandCost cost(EXPENSES_CONSTRUCTION);
CommandCost ret;
_build_tunnel_endtile = 0;
if (transport_type == TRANSPORT_RAIL) {
if (!ValParamRailtype((RailType)p1)) return CMD_ERROR;
} else {
const RoadTypes rts = (RoadTypes)GB(p1, 0, 2);
if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
}
start_tileh = GetTileSlope(start_tile, &start_z);
direction = GetInclinedSlopeDirection(start_tileh);
if (direction == INVALID_DIAGDIR) return_cmd_error(STR_500B_SITE_UNSUITABLE_FOR_TUNNEL);
if (IsWaterTile(start_tile)) return_cmd_error(STR_3807_CAN_T_BUILD_ON_WATER);
ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return ret;
/* XXX - do NOT change 'ret' in the loop, as it is used as the price
* for the clearing of the entrance of the tunnel. Assigning it to
* cost before the loop will yield different costs depending on start-
* position, because of increased-cost-by-length: 'cost += cost >> 3' */
delta = TileOffsByDiagDir(direction);
DiagDirection tunnel_in_way_dir;
if (DiagDirToAxis(direction) == AXIS_Y) {
tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
} else {
tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
}
end_tile = start_tile;
/** Tile shift coeficient. Will decrease for very long tunnels to avoid exponential growth of price*/
int tiles_coef = 3;
/** Number of tiles from start of tunnel */
int tiles = 0;
/** Number of tiles at which the cost increase coefficient per tile is halved */
int tiles_bump = 25;
for (;;) {
end_tile += delta;
if (!IsValidTile(end_tile)) return_cmd_error(STR_TUNNEL_THROUGH_MAP_BORDER);
end_tileh = GetTileSlope(end_tile, &end_z);
if (start_z == end_z) break;
if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
return_cmd_error(STR_5003_ANOTHER_TUNNEL_IN_THE_WAY);
}
tiles++;
if (tiles == tiles_bump) {
tiles_coef++;
tiles_bump *= 2;
}
cost.AddCost(_price.build_tunnel);
cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
}
/* Add the cost of the entrance */
cost.AddCost(_price.build_tunnel);
cost.AddCost(ret);
/* if the command fails from here on we want the end tile to be highlighted */
_build_tunnel_endtile = end_tile;
if (IsWaterTile(end_tile)) return_cmd_error(STR_3807_CAN_T_BUILD_ON_WATER);
/* slope of end tile must be complementary to the slope of the start tile */
if (end_tileh != ComplementSlope(start_tileh)) {
/* Check if there is a structure on the terraformed tile. Do not add the cost, that will be done by the terraforming
* Note: Currently the town rating is also affected by this clearing-test. So effectivly the player is punished twice for clearing
* the tree on end_tile.
*/
ret = DoCommand(end_tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return_cmd_error(STR_5005_UNABLE_TO_EXCAVATE_LAND);
ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
if (CmdFailed(ret)) return_cmd_error(STR_5005_UNABLE_TO_EXCAVATE_LAND);
} else {
ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(ret)) return ret;
}
cost.AddCost(_price.build_tunnel);
cost.AddCost(ret);
if (flags & DC_EXEC) {
if (transport_type == TRANSPORT_RAIL) {
MakeRailTunnel(start_tile, _current_company, direction, (RailType)GB(p1, 0, 4));
MakeRailTunnel(end_tile, _current_company, ReverseDiagDir(direction), (RailType)GB(p1, 0, 4));
AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, _current_company);
YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
} else {
MakeRoadTunnel(start_tile, _current_company, direction, (RoadTypes)GB(p1, 0, 2));
MakeRoadTunnel(end_tile, _current_company, ReverseDiagDir(direction), (RoadTypes)GB(p1, 0, 2));
}
}
return cost;
}
static inline bool CheckAllowRemoveTunnelBridge(TileIndex tile)
{
/* Floods can remove anything as well as the scenario editor */
if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return true;
switch (GetTunnelBridgeTransportType(tile)) {
case TRANSPORT_ROAD: {
RoadTypes rts = GetRoadTypes(tile);
Owner road_owner = _current_company;
Owner tram_owner = _current_company;
if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
/* We can remove unowned road and if the town allows it */
if (road_owner == OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) return CheckTileOwnership(tile);
if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
if (tram_owner == OWNER_NONE) tram_owner = _current_company;
return CheckOwnership(road_owner) && CheckOwnership(tram_owner);
}
case TRANSPORT_RAIL:
case TRANSPORT_WATER:
return CheckOwnership(GetTileOwner(tile));
default: NOT_REACHED();
}
}
static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
{
Town *t = NULL;
TileIndex endtile;
if (!CheckAllowRemoveTunnelBridge(tile)) return CMD_ERROR;
endtile = GetOtherTunnelEnd(tile);
if (HasVehicleOnTunnelBridge(tile, endtile)) return CMD_ERROR;
_build_tunnel_endtile = endtile;
if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
/* Check if you are allowed to remove the tunnel owned by a town
* Removal depends on difficulty settings */
if (!CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE)) {
SetDParam(0, t->index);
return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
}
}
/* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
* you have a "Poor" (0) town rating */
if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
}
if (flags & DC_EXEC) {
if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
/* We first need to request values before calling DoClearSquare */
DiagDirection dir = GetTunnelBridgeDirection(tile);
Track track = DiagDirToDiagTrack(dir);
Owner owner = GetTileOwner(tile);
Vehicle *v = NULL;
if (GetTunnelBridgeReservation(tile)) {
v = GetTrainForReservation(tile, track);
if (v != NULL) FreeTrainTrackReservation(v);
}
DoClearSquare(tile);
DoClearSquare(endtile);
/* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
AddSideToSignalBuffer(tile, ReverseDiagDir(dir), owner);
AddSideToSignalBuffer(endtile, dir, owner);
YapfNotifyTrackLayoutChange(tile, track);
YapfNotifyTrackLayoutChange(endtile, track);
if (v != NULL) TryPathReserve(v);
} else {
DoClearSquare(tile);
DoClearSquare(endtile);
}
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.clear_tunnel * (GetTunnelBridgeLength(tile, endtile) + 2));
}
static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
{
DiagDirection direction;
TileIndexDiff delta;
TileIndex endtile;
Town *t = NULL;
if (!CheckAllowRemoveTunnelBridge(tile)) return CMD_ERROR;
endtile = GetOtherBridgeEnd(tile);
if (HasVehicleOnTunnelBridge(tile, endtile)) return CMD_ERROR;
direction = GetTunnelBridgeDirection(tile);
delta = TileOffsByDiagDir(direction);
if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
/* Check if you are allowed to remove the bridge owned by a town
* Removal depends on difficulty settings */
if (!CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE)) {
SetDParam(0, t->index);
return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
}
}
/* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
* you have a "Poor" (0) town rating */
if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
}
if (flags & DC_EXEC) {
/* read this value before actual removal of bridge */
bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
Owner owner = GetTileOwner(tile);
uint height = GetBridgeHeight(tile);
Vehicle *v = NULL;
if (rail && GetTunnelBridgeReservation(tile)) {
v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
if (v != NULL) FreeTrainTrackReservation(v);
}
DoClearSquare(tile);
DoClearSquare(endtile);
for (TileIndex c = tile + delta; c != endtile; c += delta) {
/* do not let trees appear from 'nowhere' after removing bridge */
if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
uint minz = GetTileMaxZ(c) + 3 * TILE_HEIGHT;
if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
}
ClearBridgeMiddle(c);
MarkTileDirtyByTile(c);
}
if (rail) {
/* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
AddSideToSignalBuffer(tile, ReverseDiagDir(direction), owner);
AddSideToSignalBuffer(endtile, direction, owner);
Track track = DiagDirToDiagTrack(direction);
YapfNotifyTrackLayoutChange(tile, track);
YapfNotifyTrackLayoutChange(endtile, track);
if (v != NULL) TryPathReserve(v, true);
}
}
return CommandCost(EXPENSES_CONSTRUCTION, (GetTunnelBridgeLength(tile, endtile) + 2) * _price.clear_bridge);
}
static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
{
if (IsTunnel(tile)) {
if (flags & DC_AUTO) return_cmd_error(STR_5006_MUST_DEMOLISH_TUNNEL_FIRST);
return DoClearTunnel(tile, flags);
} else { // IsBridge(tile)
if (flags & DC_AUTO) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
return DoClearBridge(tile, flags);
}
return CMD_ERROR;
}
/**
* Draws the pillars under high bridges.
*
* @param psid Image and palette of a bridge pillar.
* @param ti #TileInfo of current bridge-middle-tile.
* @param axis Orientation of bridge.
* @param type Bridge type.
* @param x Sprite X position of front pillar.
* @param y Sprite Y position of front pillar.
* @param z_bridge Absolute height of bridge bottom.
*/
static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
{
/* Do not draw bridge pillars if they are invisible */
if (IsInvisibilitySet(TO_BRIDGES)) return;
SpriteID image = psid->sprite;
if (image != 0) {
/* "side" specifies the side the pillars stand on.
* The length of the pillars is then set to the height of the bridge over the corners of this edge.
*
* axis==AXIS_X axis==AXIS_Y
* side==false SW NW
* side==true NE SE
*
* I have no clue, why this was done this way.
*/
bool side = HasBit(image, 0);
/* "dir" means the edge the pillars stand on */
DiagDirection dir = AxisToDiagDir(axis);
if (side != (axis == AXIS_Y)) dir = ReverseDiagDir(dir);
/* Determine ground height under pillars */
int front_height = ti->z;
int back_height = ti->z;
GetSlopeZOnEdge(ti->tileh, dir, &front_height, &back_height);
/* x and y size of bounding-box of pillars */
int w = (axis == AXIS_X ? 16 : 2);
int h = (axis == AXIS_X ? 2 : 16);
/* sprite position of back facing pillar */
int x_back = x - (axis == AXIS_X ? 0 : 9);
int y_back = y - (axis == AXIS_X ? 9 : 0);
for (int cur_z = z_bridge; cur_z >= front_height || cur_z >= back_height; cur_z -= TILE_HEIGHT) {
/* Draw front facing pillar */
if (cur_z >= front_height) {
AddSortableSpriteToDraw(image, psid->pal, x, y, w, h, BB_HEIGHT_UNDER_BRIDGE - 5, cur_z, IsTransparencySet(TO_BRIDGES), 0, 0, -5);
}
/* Draw back facing pillar, but not the highest part directly under the bridge-floor */
if (drawfarpillar && cur_z >= back_height && cur_z < z_bridge - TILE_HEIGHT) {
AddSortableSpriteToDraw(image, psid->pal, x_back, y_back, w, h, BB_HEIGHT_UNDER_BRIDGE - 5, cur_z, IsTransparencySet(TO_BRIDGES), 0, 0, -5);
}
}
}
}
/**
* Draws the trambits over an already drawn (lower end) of a bridge.
* @param x the x of the bridge
* @param y the y of the bridge
* @param z the z of the bridge
* @param offset number representing whether to level or sloped and the direction
* @param overlay do we want to still see the road?
* @param head are we drawing bridge head?
*/
static void DrawBridgeTramBits(int x, int y, byte z, int offset, bool overlay, bool head)
{
static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
static const SpriteID back_offsets[6] = { 95, 96, 99, 102, 100, 101 };
static const SpriteID front_offsets[6] = { 97, 98, 103, 106, 104, 105 };
static const uint size_x[6] = { 1, 16, 16, 1, 16, 1 };
static const uint size_y[6] = { 16, 1, 1, 16, 1, 16 };
static const uint front_bb_offset_x[6] = { 15, 0, 0, 15, 0, 15 };
static const uint front_bb_offset_y[6] = { 0, 15, 15, 0, 15, 0 };
/* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
* The bounding boxes here are the same as for bridge front/roof */
if (head || !IsInvisibilitySet(TO_BRIDGES)) {
AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
x, y, size_x[offset], size_y[offset], 0x28, z,
!head && IsTransparencySet(TO_BRIDGES));
}
/* Do not draw catenary if it is set invisible */
if (!IsInvisibilitySet(TO_CATENARY)) {
AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
x, y, size_x[offset], size_y[offset], 0x28, z,
IsTransparencySet(TO_CATENARY));
}
/* Start a new SpriteCombine for the front part */
EndSpriteCombine();
StartSpriteCombine();
/* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
if (!IsInvisibilitySet(TO_CATENARY)) {
AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
}
}
/**
* Draws a tunnel of bridge tile.
* For tunnels, this is rather simple, as you only needa draw the entrance.
* Bridges are a bit more complex. base_offset is where the sprite selection comes into play
* and it works a bit like a bitmask.<p> For bridge heads:
* @param ti TileInfo of the structure to draw
* <ul><li>Bit 0: direction</li>
* <li>Bit 1: northern or southern heads</li>
* <li>Bit 2: Set if the bridge head is sloped</li>
* <li>Bit 3 and more: Railtype Specific subset</li>
* </ul>
* Please note that in this code, "roads" are treated as railtype 1, whilst the real railtypes are 0, 2 and 3
*/
static void DrawTile_TunnelBridge(TileInfo *ti)
{
SpriteID image;
TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
if (IsTunnel(ti->tile)) {
/* Front view of tunnel bounding boxes:
*
* 122223 <- BB_Z_SEPARATOR
* 1 3
* 1 3 1,3 = empty helper BB
* 1 3 2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
*
*/
static const int _tunnel_BB[4][12] = {
/* tunnnel-roof | Z-separator | tram-catenary
* w h bb_x bb_y| x y w h |bb_x bb_y w h */
{ 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // NE
{ 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // SE
{ 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // SW
{ 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // NW
};
const int *BB_data = _tunnel_BB[tunnelbridge_direction];
bool catenary = false;
if (transport_type == TRANSPORT_RAIL) {
image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.tunnel;
} else {
image = SPR_TUNNEL_ENTRY_REAR_ROAD;
}
if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += 32;
image += tunnelbridge_direction * 2;
DrawGroundSprite(image, PAL_NONE);
/* PBS debugging, draw reserved tracks darker */
if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && (transport_type == TRANSPORT_RAIL && GetTunnelBridgeReservation(ti->tile))) {
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_y : rti->base_sprites.single_x, PALETTE_CRASH);
}
if (transport_type == TRANSPORT_ROAD) {
RoadTypes rts = GetRoadTypes(ti->tile);
if (HasBit(rts, ROADTYPE_TRAM)) {
static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, { 5, 76, 77, 4 } };
DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
/* Do not draw wires if they are invisible */
if (!IsInvisibilitySet(TO_CATENARY)) {
catenary = true;
StartSpriteCombine();
AddSortableSpriteToDraw(SPR_TRAMWAY_TUNNEL_WIRES + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, BB_data[10], BB_data[11], TILE_HEIGHT, ti->z, IsTransparencySet(TO_CATENARY), BB_data[8], BB_data[9], BB_Z_SEPARATOR);
}
}
} else if (HasCatenaryDrawn(GetRailType(ti->tile))) {
/* Maybe draw pylons on the entry side */
DrawCatenary(ti);
catenary = true;
StartSpriteCombine();
/* Draw wire above the ramp */
DrawCatenaryOnTunnel(ti);
}
AddSortableSpriteToDraw(image + 1, PAL_NONE, ti->x + TILE_SIZE - 1, ti->y + TILE_SIZE - 1, BB_data[0], BB_data[1], TILE_HEIGHT, ti->z, false, BB_data[2], BB_data[3], BB_Z_SEPARATOR);
if (catenary) EndSpriteCombine();
/* Add helper BB for sprite sorting, that separate the tunnel from things beside of it */
AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x , ti->y , BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x + BB_data[4], ti->y + BB_data[5], BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
DrawBridgeMiddle(ti);
} else { // IsBridge(ti->tile)
const PalSpriteID *psid;
int base_offset;
bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
if (transport_type == TRANSPORT_RAIL) {
base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
assert(base_offset != 8); // This one is used for roads
} else {
base_offset = 8;
}
/* as the lower 3 bits are used for other stuff, make sure they are clear */
assert( (base_offset & 0x07) == 0x00);
DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
/* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
base_offset += (6 - tunnelbridge_direction) % 4;
if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
/* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
if (transport_type != TRANSPORT_WATER) {
psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
} else {
psid = _aqueduct_sprites + base_offset;
}
if (!ice) {
DrawClearLandTile(ti, 3);
} else {
DrawGroundSprite(SPR_FLAT_SNOWY_TILE + _tileh_to_sprite[ti->tileh], PAL_NONE);
}
/* draw ramp */
/* Draw Trambits as SpriteCombine */
if (transport_type == TRANSPORT_ROAD) StartSpriteCombine();
/* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
* it doesn't disappear behind it
*/
/* Bridge heads are drawn solid no matter how invisibility/transparency is set */
AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
if (_settings_client.gui.show_track_reservation && transport_type == TRANSPORT_RAIL && GetTunnelBridgeReservation(ti->tile)) {
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
AddSortableSpriteToDraw(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_y : rti->base_sprites.single_x, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
} else {
AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
}
}
if (transport_type == TRANSPORT_ROAD) {
RoadTypes rts = GetRoadTypes(ti->tile);
if (HasBit(rts, ROADTYPE_TRAM)) {
uint offset = tunnelbridge_direction;
uint z = ti->z;
if (ti->tileh != SLOPE_FLAT) {
offset = (offset + 1) & 1;
z += TILE_HEIGHT;
} else {
offset += 2;
}
/* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
}
EndSpriteCombine();
} else if (transport_type == TRANSPORT_RAIL) {
if (HasCatenaryDrawn(GetRailType(ti->tile))) {
DrawCatenary(ti);
}
}
DrawBridgeMiddle(ti);
}
}
/** Compute bridge piece. Computes the bridge piece to display depending on the position inside the bridge.
* bridges pieces sequence (middle parts).
* Note that it is not covering the bridge heads, which are always referenced by the same sprite table.
* bridge len 1: BRIDGE_PIECE_NORTH
* bridge len 2: BRIDGE_PIECE_NORTH BRIDGE_PIECE_SOUTH
* bridge len 3: BRIDGE_PIECE_NORTH BRIDGE_PIECE_MIDDLE_ODD BRIDGE_PIECE_SOUTH
* bridge len 4: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
* bridge len 5: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_MIDDLE_EVEN BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
* bridge len 6: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
* bridge len 7: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_MIDDLE_ODD BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
* #0 - always as first, #1 - always as last (if len>1)
* #2,#3 are to pair in order
* for odd bridges: #5 is going in the bridge middle if on even position, #4 on odd (counting from 0)
* @param north Northernmost tile of bridge
* @param south Southernmost tile of bridge
* @return Index of bridge piece
*/
static BridgePieces CalcBridgePiece(uint north, uint south)
{
if (north == 1) {
return BRIDGE_PIECE_NORTH;
} else if (south == 1) {
return BRIDGE_PIECE_SOUTH;
} else if (north < south) {
return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
} else if (north > south) {
return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
} else {
return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
}
}
void DrawBridgeMiddle(const TileInfo *ti)
{
/* Sectional view of bridge bounding boxes:
*
* 1 2 1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
* 1 2 3 = empty helper BB
* 1 7 2 4,5 = pillars under higher bridges
* 1 6 88888 6 2 6 = elrail-pylons
* 1 6 88888 6 2 7 = elrail-wire
* 1 6 88888 6 2 <- TILE_HEIGHT 8 = rail-vehicle on bridge
* 3333333333333 <- BB_Z_SEPARATOR
* <- unused
* 4 5 <- BB_HEIGHT_UNDER_BRIDGE
* 4 5
* 4 5
*
*/
/* Z position of the bridge sprites relative to bridge height (downwards) */
static const int BRIDGE_Z_START = 3;
if (!IsBridgeAbove(ti->tile)) return;
TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
Axis axis = GetBridgeAxis(ti->tile);
BridgePieces piece = CalcBridgePiece(
GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
GetTunnelBridgeLength(ti->tile, rampsouth) + 1
);
const PalSpriteID *psid;
bool drawfarpillar;
if (transport_type != TRANSPORT_WATER) {
BridgeType type = GetBridgeType(rampsouth);
drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
uint base_offset;
if (transport_type == TRANSPORT_RAIL) {
base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
} else {
base_offset = 8;
}
psid = base_offset + GetBridgeSpriteTable(type, piece);
} else {
drawfarpillar = true;
psid = _aqueduct_sprites;
}
if (axis != AXIS_X) psid += 4;
int x = ti->x;
int y = ti->y;
uint bridge_z = GetBridgeHeight(rampsouth);
uint z = bridge_z - BRIDGE_Z_START;
/* Add a bounding box, that separates the bridge from things below it. */
AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
/* Draw Trambits as SpriteCombine */
if (transport_type == TRANSPORT_ROAD) StartSpriteCombine();
/* Draw floor and far part of bridge*/
if (!IsInvisibilitySet(TO_BRIDGES)) {
if (axis == AXIS_X) {
AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
} else {
AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
}
}
psid++;
if (transport_type == TRANSPORT_ROAD) {
RoadTypes rts = GetRoadTypes(rampsouth);
if (HasBit(rts, ROADTYPE_TRAM)) {
/* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
} else {
EndSpriteCombine();
StartSpriteCombine();
}
} else if (transport_type == TRANSPORT_RAIL) {
if (HasCatenaryDrawn(GetRailType(rampsouth))) {
DrawCatenaryOnBridge(ti);
}
}
/* draw roof, the component of the bridge which is logically between the vehicle and the camera */
if (!IsInvisibilitySet(TO_BRIDGES)) {
if (axis == AXIS_X) {
y += 12;
if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
} else {
x += 12;
if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
}
}
/* Draw TramFront as SpriteCombine */
if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
/* Do not draw anything more if bridges are invisible */
if (IsInvisibilitySet(TO_BRIDGES)) return;
psid++;
if (ti->z + 5 == z) {
/* draw poles below for small bridges */
if (psid->sprite != 0) {
SpriteID image = psid->sprite;
SpriteID pal = psid->pal;
if (IsTransparencySet(TO_BRIDGES)) {
SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
pal = PALETTE_TO_TRANSPARENT;
}
DrawGroundSpriteAt(image, pal, x, y, z);
}
} else if (_settings_client.gui.bridge_pillars) {
/* draw pillars below for high bridges */
DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
}
}
static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y)
{
uint z;
Slope tileh = GetTileSlope(tile, &z);
x &= 0xF;
y &= 0xF;
if (IsTunnel(tile)) {
uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
/* In the tunnel entrance? */
if (5 <= pos && pos <= 10) return z;
} else { // IsBridge(tile)
DiagDirection dir = GetTunnelBridgeDirection(tile);
uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
/* On the bridge ramp? */
if (5 <= pos && pos <= 10) {
uint delta;
if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
switch (dir) {
default: NOT_REACHED();
case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
case DIAGDIR_SE: delta = y / 2; break;
case DIAGDIR_SW: delta = x / 2; break;
case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
}
return z + 1 + delta;
}
}
return z + GetPartialZ(x, y, tileh);
}
static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
{
return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
}
static void GetAcceptedCargo_TunnelBridge(TileIndex tile, AcceptedCargo ac)
{
/* not used */
}
static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
{
TransportType tt = GetTunnelBridgeTransportType(tile);
if (IsTunnel(tile)) {
td->str = (tt == TRANSPORT_RAIL) ? STR_5017_RAILROAD_TUNNEL : STR_5018_ROAD_TUNNEL;
} else { // IsBridge(tile)
td->str = (tt == TRANSPORT_WATER) ? STR_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
}
td->owner[0] = GetTileOwner(tile);
Owner road_owner = INVALID_OWNER;
Owner tram_owner = INVALID_OWNER;
RoadTypes rts = GetRoadTypes(tile);
if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
/* Is there a mix of owners? */
if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
(road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
uint i = 1;
if (road_owner != INVALID_OWNER) {
td->owner_type[i] = STR_ROAD_OWNER;
td->owner[i] = road_owner;
i++;
}
if (tram_owner != INVALID_OWNER) {
td->owner_type[i] = STR_TRAM_OWNER;
td->owner[i] = tram_owner;
}
}
}
static void AnimateTile_TunnelBridge(TileIndex tile)
{
/* not used */
}
static void TileLoop_TunnelBridge(TileIndex tile)
{
bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC:
if (snow_or_desert != (GetTileZ(tile) > GetSnowLine())) {
SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
MarkTileDirtyByTile(tile);
}
break;
case LT_TROPIC:
if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
SetTunnelBridgeSnowOrDesert(tile, true);
MarkTileDirtyByTile(tile);
}
break;
default:
break;
}
}
static bool ClickTile_TunnelBridge(TileIndex tile)
{
/* not used */
return false;
}
static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
{
TransportType transport_type = GetTunnelBridgeTransportType(tile);
if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
DiagDirection dir = GetTunnelBridgeDirection(tile);
if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
}
static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
{
for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
/* Update all roadtypes, no matter if they are present */
if (GetRoadOwner(tile, rt) == old_owner) {
SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
}
}
if (!IsTileOwner(tile, old_owner)) return;
if (new_owner != INVALID_OWNER) {
SetTileOwner(tile, new_owner);
} else {
if (CmdFailed(DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR))) {
/* When clearing the bridge/tunnel failed there are still vehicles on/in
* the bridge/tunnel. As all *our* vehicles are already removed, they
* must be of another owner. Therefore this can't be rail tunnel/bridge.
* In that case we can safely reassign the ownership to OWNER_NONE. */
assert(GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL);
SetTileOwner(tile, OWNER_NONE);
}
}
}
static const byte _tunnel_fractcoord_1[4] = {0x8E, 0x18, 0x81, 0xE8};
static const byte _tunnel_fractcoord_2[4] = {0x81, 0x98, 0x87, 0x38};
static const byte _tunnel_fractcoord_3[4] = {0x82, 0x88, 0x86, 0x48};
static const byte _exit_tunnel_track[4] = {1, 2, 1, 2};
/** Get the trackdir of the exit of a tunnel */
static const Trackdir _road_exit_tunnel_state[DIAGDIR_END] = {
TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
};
static const byte _road_exit_tunnel_frame[4] = {2, 7, 9, 4};
static const byte _tunnel_fractcoord_4[4] = {0x52, 0x85, 0x98, 0x29};
static const byte _tunnel_fractcoord_5[4] = {0x92, 0x89, 0x58, 0x25};
static const byte _tunnel_fractcoord_6[4] = {0x92, 0x89, 0x56, 0x45};
static const byte _tunnel_fractcoord_7[4] = {0x52, 0x85, 0x96, 0x49};
static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
{
int z = GetSlopeZ(x, y) - v->z_pos;
if (abs(z) > 2) return VETSB_CANNOT_ENTER;
const DiagDirection dir = GetTunnelBridgeDirection(tile);
if (IsTunnel(tile)) {
byte fc;
DiagDirection vdir;
if (v->type == VEH_TRAIN) {
fc = (x & 0xF) + (y << 4);
vdir = DirToDiagDir(v->direction);
if (v->u.rail.track != TRACK_BIT_WORMHOLE && dir == vdir) {
if (IsFrontEngine(v) && fc == _tunnel_fractcoord_1[dir]) {
if (!PlayVehicleSound(v, VSE_TUNNEL) && RailVehInfo(v->engine_type)->engclass == 0) {
SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
}
return VETSB_CONTINUE;
}
if (fc == _tunnel_fractcoord_2[dir]) {
v->tile = tile;
v->u.rail.track = TRACK_BIT_WORMHOLE;
v->vehstatus |= VS_HIDDEN;
return VETSB_ENTERED_WORMHOLE;
}
}
if (dir == ReverseDiagDir(vdir) && fc == _tunnel_fractcoord_3[dir] && z == 0) {
/* We're at the tunnel exit ?? */
v->tile = tile;
v->u.rail.track = (TrackBits)_exit_tunnel_track[dir];
assert(v->u.rail.track);
v->vehstatus &= ~VS_HIDDEN;
return VETSB_ENTERED_WORMHOLE;
}
} else if (v->type == VEH_ROAD) {
fc = (x & 0xF) + (y << 4);
vdir = DirToDiagDir(v->direction);
/* Enter tunnel? */
if (v->u.road.state != RVSB_WORMHOLE && dir == vdir) {
if (fc == _tunnel_fractcoord_4[dir] ||
fc == _tunnel_fractcoord_5[dir]) {
v->tile = tile;
v->u.road.state = RVSB_WORMHOLE;
v->vehstatus |= VS_HIDDEN;
return VETSB_ENTERED_WORMHOLE;
} else {
return VETSB_CONTINUE;
}
}
if (dir == ReverseDiagDir(vdir) && (
/* We're at the tunnel exit ?? */
fc == _tunnel_fractcoord_6[dir] ||
fc == _tunnel_fractcoord_7[dir]
) &&
z == 0) {
v->tile = tile;
v->u.road.state = _road_exit_tunnel_state[dir];
v->u.road.frame = _road_exit_tunnel_frame[dir];
v->vehstatus &= ~VS_HIDDEN;
return VETSB_ENTERED_WORMHOLE;
}
}
} else { // IsBridge(tile)
if (v->IsPrimaryVehicle() && v->type != VEH_SHIP) {
/* modify speed of vehicle */
uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
if (v->type == VEH_ROAD) spd *= 2;
if (v->cur_speed > spd) v->cur_speed = spd;
}
if (DirToDiagDir(v->direction) == dir) {
switch (dir) {
default: NOT_REACHED();
case DIAGDIR_NE: if ((x & 0xF) != 0) return VETSB_CONTINUE; break;
case DIAGDIR_SE: if ((y & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
case DIAGDIR_SW: if ((x & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
case DIAGDIR_NW: if ((y & 0xF) != 0) return VETSB_CONTINUE; break;
}
switch (v->type) {
case VEH_TRAIN:
v->u.rail.track = TRACK_BIT_WORMHOLE;
ClrBit(v->u.rail.flags, VRF_GOINGUP);
ClrBit(v->u.rail.flags, VRF_GOINGDOWN);
break;
case VEH_ROAD:
v->u.road.state = RVSB_WORMHOLE;
break;
case VEH_SHIP:
v->u.ship.state = TRACK_BIT_WORMHOLE;
break;
default: NOT_REACHED();
}
return VETSB_ENTERED_WORMHOLE;
} else if (DirToDiagDir(v->direction) == ReverseDiagDir(dir)) {
v->tile = tile;
switch (v->type) {
case VEH_TRAIN:
if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
return VETSB_ENTERED_WORMHOLE;
}
break;
case VEH_ROAD:
if (v->u.road.state == RVSB_WORMHOLE) {
v->u.road.state = _road_exit_tunnel_state[dir];
v->u.road.frame = 0;
return VETSB_ENTERED_WORMHOLE;
}
break;
case VEH_SHIP:
if (v->u.ship.state == TRACK_BIT_WORMHOLE) {
v->u.ship.state = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
return VETSB_ENTERED_WORMHOLE;
}
break;
default: NOT_REACHED();
}
}
}
return VETSB_CONTINUE;
}
static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
{
if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
DiagDirection direction = GetTunnelBridgeDirection(tile);
Axis axis = DiagDirToAxis(direction);
CommandCost res;
uint z_old;
Slope tileh_old = GetTileSlope(tile, &z_old);
/* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
} else {
CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
}
/* Surface slope is valid and remains unchanged? */
if (!CmdFailed(res) && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
}
return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
}
extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
DrawTile_TunnelBridge, // draw_tile_proc
GetSlopeZ_TunnelBridge, // get_slope_z_proc
ClearTile_TunnelBridge, // clear_tile_proc
GetAcceptedCargo_TunnelBridge, // get_accepted_cargo_proc
GetTileDesc_TunnelBridge, // get_tile_desc_proc
GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
ClickTile_TunnelBridge, // click_tile_proc
AnimateTile_TunnelBridge, // animate_tile_proc
TileLoop_TunnelBridge, // tile_loop_clear
ChangeTileOwner_TunnelBridge, // change_tile_owner_clear
NULL, // get_produced_cargo_proc
VehicleEnter_TunnelBridge, // vehicle_enter_tile_proc
GetFoundation_TunnelBridge, // get_foundation_proc
TerraformTile_TunnelBridge, // terraform_tile_proc
};
| 53,389
|
C++
|
.cpp
| 1,284
| 38.452492
| 222
| 0.693063
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,109
|
news_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/news_gui.cpp
|
/* $Id$ */
/** @file news_gui.cpp GUI functions related to news messages. */
#include "stdafx.h"
#include "openttd.h"
#include "gui.h"
#include "window_gui.h"
#include "viewport_func.h"
#include "news_type.h"
#include "settings_type.h"
#include "transparency.h"
#include "strings_func.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_base.h"
#include "sound_func.h"
#include "string_func.h"
#include "widgets/dropdown_func.h"
#include "statusbar_gui.h"
#include "company_manager_face.h"
#include "table/strings.h"
#define NB_WIDG_PER_SETTING 4
NewsItem _statusbar_news_item;
bool _news_ticker_sound;
static uint MIN_NEWS_AMOUNT = 30; ///< prefered minimum amount of news messages
static uint _total_news = 0; ///< current number of news items
static NewsItem *_oldest_news = NULL; ///< head of news items queue
static NewsItem *_latest_news = NULL; ///< tail of news items queue
/** Forced news item.
* Users can force an item by accessing the history or "last message".
* If the message being shown was forced by the user, a pointer is stored
* in _forced_news. Otherwise, \a _forced_news variable is NULL. */
static NewsItem *_forced_news = NULL; ///< item the user has asked for
/** Current news item (last item shown regularly). */
static NewsItem *_current_news = NULL;
typedef void DrawNewsCallbackProc(struct Window *w, const NewsItem *ni);
void DrawNewsNewVehicleAvail(Window *w, const NewsItem *ni);
static void DrawNewsBankrupcy(Window *w, const NewsItem *ni)
{
const CompanyNewsInformation *cni = (const CompanyNewsInformation*)ni->free_data;
DrawCompanyManagerFace(cni->face, cni->colour, 2, 23);
GfxFillRect(3, 23, 3 + 91, 23 + 118, PALETTE_TO_STRUCT_GREY, FILLRECT_RECOLOUR);
SetDParamStr(0, cni->president_name);
DrawStringMultiCenter(49, 148, STR_JUST_RAW_STRING, 94);
switch (ni->subtype) {
case NS_COMPANY_TROUBLE:
DrawStringCentered(w->width >> 1, 1, STR_7056_TRANSPORT_COMPANY_IN_TROUBLE, TC_FROMSTRING);
SetDParam(0, ni->params[2]);
DrawStringMultiCenter(
((w->width - 101) >> 1) + 98,
90,
STR_7057_WILL_BE_SOLD_OFF_OR_DECLARED,
w->width - 101);
break;
case NS_COMPANY_MERGER:
DrawStringCentered(w->width >> 1, 1, STR_7059_TRANSPORT_COMPANY_MERGER, TC_FROMSTRING);
SetDParam(0, ni->params[2]);
SetDParam(1, ni->params[3]);
SetDParam(2, ni->params[4]);
DrawStringMultiCenter(
((w->width - 101) >> 1) + 98,
90,
ni->params[4] == 0 ? STR_707F_HAS_BEEN_TAKEN_OVER_BY : STR_705A_HAS_BEEN_SOLD_TO_FOR,
w->width - 101);
break;
case NS_COMPANY_BANKRUPT:
DrawStringCentered(w->width >> 1, 1, STR_705C_BANKRUPT, TC_FROMSTRING);
SetDParam(0, ni->params[2]);
DrawStringMultiCenter(
((w->width - 101) >> 1) + 98,
90,
STR_705D_HAS_BEEN_CLOSED_DOWN_BY,
w->width - 101);
break;
case NS_COMPANY_NEW:
DrawStringCentered(w->width >> 1, 1, STR_705E_NEW_TRANSPORT_COMPANY_LAUNCHED, TC_FROMSTRING);
SetDParam(0, ni->params[2]);
SetDParam(1, ni->params[3]);
DrawStringMultiCenter(
((w->width - 101) >> 1) + 98,
90,
STR_705F_STARTS_CONSTRUCTION_NEAR,
w->width - 101);
break;
default:
NOT_REACHED();
}
}
/**
* Data common to all news items of a given subtype (structure)
*/
struct NewsSubtypeData {
NewsType type; ///< News category @see NewsType
NewsMode display_mode; ///< Display mode value @see NewsMode
NewsFlag flags; ///< Initial NewsFlags bits @see NewsFlag
DrawNewsCallbackProc *callback; ///< Call-back function
};
/**
* Data common to all news items of a given subtype (actual data)
*/
static const struct NewsSubtypeData _news_subtype_data[NS_END] = {
/* type, display_mode, flags, callback */
{ NT_ARRIVAL_COMPANY, NM_THIN, NF_VIEWPORT|NF_VEHICLE, NULL }, ///< NS_ARRIVAL_COMPANY
{ NT_ARRIVAL_OTHER, NM_THIN, NF_VIEWPORT|NF_VEHICLE, NULL }, ///< NS_ARRIVAL_OTHER
{ NT_ACCIDENT, NM_THIN, NF_VIEWPORT|NF_TILE, NULL }, ///< NS_ACCIDENT_TILE
{ NT_ACCIDENT, NM_THIN, NF_VIEWPORT|NF_VEHICLE, NULL }, ///< NS_ACCIDENT_VEHICLE
{ NT_COMPANY_INFO, NM_NORMAL, NF_NONE, DrawNewsBankrupcy }, ///< NS_COMPANY_TROUBLE
{ NT_COMPANY_INFO, NM_NORMAL, NF_NONE, DrawNewsBankrupcy }, ///< NS_COMPANY_MERGER
{ NT_COMPANY_INFO, NM_NORMAL, NF_NONE, DrawNewsBankrupcy }, ///< NS_COMPANY_BANKRUPT
{ NT_COMPANY_INFO, NM_NORMAL, NF_TILE, DrawNewsBankrupcy }, ///< NS_COMPANY_NEW
{ NT_INDUSTRY_OPEN, NM_THIN, NF_VIEWPORT|NF_TILE, NULL }, ///< NS_INDUSTRY_OPEN
{ NT_INDUSTRY_CLOSE, NM_THIN, NF_VIEWPORT|NF_TILE, NULL }, ///< NS_INDUSTRY_CLOSE
{ NT_ECONOMY, NM_NORMAL, NF_NONE, NULL }, ///< NS_ECONOMY
{ NT_INDUSTRY_COMPANY, NM_THIN, NF_VIEWPORT|NF_TILE, NULL }, ///< NS_INDUSTRY_COMPANY
{ NT_INDUSTRY_OTHER, NM_THIN, NF_VIEWPORT|NF_TILE, NULL }, ///< NS_INDUSTRY_OTHER
{ NT_INDUSTRY_NOBODY, NM_THIN, NF_VIEWPORT|NF_TILE, NULL }, ///< NS_INDUSTRY_NOBODY
{ NT_ADVICE, NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NULL }, ///< NS_ADVICE
{ NT_NEW_VEHICLES, NM_NORMAL, NF_NONE, DrawNewsNewVehicleAvail }, ///< NS_NEW_VEHICLES
{ NT_ACCEPTANCE, NM_SMALL, NF_VIEWPORT|NF_TILE, NULL }, ///< NS_ACCEPTANCE
{ NT_SUBSIDIES, NM_NORMAL, NF_TILE|NF_TILE2, NULL }, ///< NS_SUBSIDIES
{ NT_GENERAL, NM_NORMAL, NF_TILE, NULL }, ///< NS_GENERAL
};
/**
* Per-NewsType data
*/
NewsTypeData _news_type_data[NT_END] = {
/* name, age, sound, display */
{ "arrival_player", 60, SND_1D_APPLAUSE, ND_FULL }, ///< NT_ARRIVAL_COMPANY
{ "arrival_other", 60, SND_1D_APPLAUSE, ND_FULL }, ///< NT_ARRIVAL_OTHER
{ "accident", 90, SND_BEGIN, ND_FULL }, ///< NT_ACCIDENT
{ "company_info", 60, SND_BEGIN, ND_FULL }, ///< NT_COMPANY_INFO
{ "open", 90, SND_BEGIN, ND_FULL }, ///< NT_INDUSTRY_OPEN
{ "close", 90, SND_BEGIN, ND_FULL }, ///< NT_INDUSTRY_CLOSE
{ "economy", 30, SND_BEGIN, ND_FULL }, ///< NT_ECONOMY
{ "production_player", 30, SND_BEGIN, ND_FULL }, ///< NT_INDUSTRY_COMPANY
{ "production_other", 30, SND_BEGIN, ND_FULL }, ///< NT_INDUSTRY_OTHER
{ "production_nobody", 30, SND_BEGIN, ND_FULL }, ///< NT_INDUSTRY_NOBODY
{ "advice", 150, SND_BEGIN, ND_FULL }, ///< NT_ADVICE
{ "new_vehicles", 30, SND_1E_OOOOH, ND_FULL }, ///< NT_NEW_VEHICLES
{ "acceptance", 90, SND_BEGIN, ND_FULL }, ///< NT_ACCEPTANCE
{ "subsidies", 180, SND_BEGIN, ND_FULL }, ///< NT_SUBSIDIES
{ "general", 60, SND_BEGIN, ND_FULL }, ///< NT_GENERAL
};
struct NewsWindow : Window {
uint16 chat_height;
NewsItem *ni;
static uint duration;
NewsWindow(const WindowDesc *desc, NewsItem *ni) : Window(desc), ni(ni)
{
NewsWindow::duration = 555;
const Window *w = FindWindowById(WC_SEND_NETWORK_MSG, 0);
this->chat_height = (w != NULL) ? w->height : 0;
this->ni = _forced_news == NULL ? _current_news : _forced_news;
this->flags4 |= WF_DISABLE_VP_SCROLL;
this->FindWindowPlacementAndResize(desc);
}
void DrawNewsBorder()
{
int left = 0;
int right = this->width - 1;
int top = 0;
int bottom = this->height - 1;
GfxFillRect(left, top, right, bottom, 0xF);
GfxFillRect(left, top, left, bottom, 0xD7);
GfxFillRect(right, top, right, bottom, 0xD7);
GfxFillRect(left, top, right, top, 0xD7);
GfxFillRect(left, bottom, right, bottom, 0xD7);
DrawString(left + 2, top + 1, STR_00C6, TC_FROMSTRING);
}
virtual void OnPaint()
{
const NewsMode display_mode = _news_subtype_data[this->ni->subtype].display_mode;
switch (display_mode) {
case NM_NORMAL:
case NM_THIN: {
this->DrawNewsBorder();
if (_news_subtype_data[this->ni->subtype].callback != NULL) {
(_news_subtype_data[this->ni->subtype].callback)(this, ni);
break;
}
DrawString(2, 1, STR_00C6, TC_FROMSTRING);
SetDParam(0, this->ni->date);
DrawStringRightAligned(428, 1, STR_01FF, TC_FROMSTRING);
if (!(this->ni->flags & NF_VIEWPORT)) {
CopyInDParam(0, this->ni->params, lengthof(this->ni->params));
DrawStringMultiCenter(215, display_mode == NM_NORMAL ? 76 : 56,
this->ni->string_id, this->width - 4);
} else {
/* Back up transparency options to draw news view */
TransparencyOptionBits to_backup = _transparency_opt;
_transparency_opt = 0;
this->DrawViewport();
_transparency_opt = to_backup;
/* Shade the viewport into gray, or colour*/
ViewPort *vp = this->viewport;
GfxFillRect(vp->left - this->left, vp->top - this->top,
vp->left - this->left + vp->width - 1, vp->top - this->top + vp->height - 1,
(this->ni->flags & NF_INCOLOUR ? PALETTE_TO_TRANSPARENT : PALETTE_TO_STRUCT_GREY), FILLRECT_RECOLOUR
);
CopyInDParam(0, this->ni->params, lengthof(this->ni->params));
DrawStringMultiCenter(this->width / 2, 20, this->ni->string_id, this->width - 4);
}
break;
}
default:
this->DrawWidgets();
if (!(this->ni->flags & NF_VIEWPORT)) {
CopyInDParam(0, this->ni->params, lengthof(this->ni->params));
DrawStringMultiCenter(140, 38, this->ni->string_id, 276);
} else {
this->DrawViewport();
CopyInDParam(0, this->ni->params, lengthof(this->ni->params));
DrawStringMultiCenter(this->width / 2, this->height - 16, this->ni->string_id, this->width - 4);
}
break;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case 1:
NewsWindow::duration = 0;
delete this;
_forced_news = NULL;
break;
case 0:
if (this->ni->flags & NF_VEHICLE) {
const Vehicle *v = GetVehicle(this->ni->data_a);
ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
} else if (this->ni->flags & NF_TILE) {
if (_ctrl_pressed) {
ShowExtraViewPortWindow(this->ni->data_a);
if (this->ni->flags & NF_TILE2) {
ShowExtraViewPortWindow(this->ni->data_b);
}
} else {
if (!ScrollMainWindowToTile(this->ni->data_a) && this->ni->flags & NF_TILE2) {
ScrollMainWindowToTile(this->ni->data_b);
}
}
}
break;
}
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
if (keycode == WKC_SPACE) {
/* Don't continue. */
delete this;
return ES_HANDLED;
}
return ES_NOT_HANDLED;
}
virtual void OnInvalidateData(int data)
{
/* The chatbar has notified us that is was either created or closed */
this->chat_height = data;
}
virtual void OnTick()
{
/* Scroll up newsmessages from the bottom in steps of 4 pixels */
int y = max(this->top - 4, _screen.height - this->height - 12 - this->chat_height);
if (y == this->top) return;
if (this->viewport != NULL) this->viewport->top += y - this->top;
int diff = Delta(this->top, y);
this->top = y;
SetDirtyBlocks(this->left, this->top - diff, this->left + this->width, this->top + this->height);
}
};
/* static */ uint NewsWindow::duration; ///< Remaining time for showing current news message
static const Widget _news_type13_widgets[] = {
{ WWT_PANEL, RESIZE_NONE, COLOUR_WHITE, 0, 429, 0, 169, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_WHITE, 0, 10, 0, 11, 0x0, STR_NULL},
{ WIDGETS_END},
};
static WindowDesc _news_type13_desc(
WDP_CENTER, 476, 430, 170, 430, 170,
WC_NEWS_WINDOW, WC_NONE,
WDF_DEF_WIDGET,
_news_type13_widgets
);
static const Widget _news_type2_widgets[] = {
{ WWT_PANEL, RESIZE_NONE, COLOUR_WHITE, 0, 429, 0, 129, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_WHITE, 0, 10, 0, 11, 0x0, STR_NULL},
{ WIDGETS_END},
};
static WindowDesc _news_type2_desc(
WDP_CENTER, 476, 430, 130, 430, 130,
WC_NEWS_WINDOW, WC_NONE,
WDF_DEF_WIDGET,
_news_type2_widgets
);
static const Widget _news_type0_widgets[] = {
{ WWT_PANEL, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 279, 14, 86, 0x0, STR_NULL},
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_LIGHT_BLUE, 11, 279, 0, 13, STR_012C_MESSAGE, STR_NULL},
{ WWT_INSET, RESIZE_NONE, COLOUR_LIGHT_BLUE, 2, 277, 16, 64, 0x0, STR_NULL},
{ WIDGETS_END},
};
static WindowDesc _news_type0_desc(
WDP_CENTER, 476, 280, 87, 280, 87,
WC_NEWS_WINDOW, WC_NONE,
WDF_DEF_WIDGET,
_news_type0_widgets
);
/** Open up an own newspaper window for the news item */
static void ShowNewspaper(NewsItem *ni)
{
SoundFx sound = _news_type_data[_news_subtype_data[ni->subtype].type].sound;
if (sound != 0) SndPlayFx(sound);
int top = _screen.height;
Window *w;
switch (_news_subtype_data[ni->subtype].display_mode) {
case NM_NORMAL:
_news_type13_desc.top = top;
w = new NewsWindow(&_news_type13_desc, ni);
if (ni->flags & NF_VIEWPORT) {
InitializeWindowViewport(w, 2, 58, 426, 110,
ni->data_a | (ni->flags & NF_VEHICLE ? 0x80000000 : 0), ZOOM_LVL_NEWS);
}
break;
case NM_THIN:
_news_type2_desc.top = top;
w = new NewsWindow(&_news_type2_desc, ni);
if (ni->flags & NF_VIEWPORT) {
InitializeWindowViewport(w, 2, 58, 426, 70,
ni->data_a | (ni->flags & NF_VEHICLE ? 0x80000000 : 0), ZOOM_LVL_NEWS);
}
break;
default:
_news_type0_desc.top = top;
w = new NewsWindow(&_news_type0_desc, ni);
if (ni->flags & NF_VIEWPORT) {
InitializeWindowViewport(w, 3, 17, 274, 47,
ni->data_a | (ni->flags & NF_VEHICLE ? 0x80000000 : 0), ZOOM_LVL_NEWS);
}
break;
}
}
/** Show news item in the ticker */
static void ShowTicker(const NewsItem *ni)
{
if (_news_ticker_sound) SndPlayFx(SND_16_MORSE);
_statusbar_news_item = *ni;
InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SHOW_TICKER);
}
/** Initialize the news-items data structures */
void InitNewsItemStructs()
{
for (NewsItem *ni = _oldest_news; ni != NULL; ) {
NewsItem *next = ni->next;
delete ni;
ni = next;
}
_total_news = 0;
_oldest_news = NULL;
_latest_news = NULL;
_forced_news = NULL;
_current_news = NULL;
}
/**
* Are we ready to show another news item?
* Only if nothing is in the newsticker and no newspaper is displayed
*/
static bool ReadyForNextItem()
{
NewsItem *ni = _forced_news == NULL ? _current_news : _forced_news;
if (ni == NULL) return true;
/* Ticker message
* Check if the status bar message is still being displayed? */
if (IsNewsTickerShown()) return false;
/* Newspaper message, decrement duration counter */
if (NewsWindow::duration != 0) NewsWindow::duration--;
/* neither newsticker nor newspaper are running */
return (NewsWindow::duration == 0 || FindWindowById(WC_NEWS_WINDOW, 0) == NULL);
}
/** Move to the next news item */
static void MoveToNextItem()
{
InvalidateWindowData(WC_STATUS_BAR, 0, SBI_NEWS_DELETED); // invalidate the statusbar
DeleteWindowById(WC_NEWS_WINDOW, 0); // close the newspapers window if shown
_forced_news = NULL;
/* if we're not at the last item, then move on */
if (_current_news != _latest_news) {
_current_news = (_current_news == NULL) ? _oldest_news : _current_news->next;
NewsItem *ni = _current_news;
const NewsType type = _news_subtype_data[ni->subtype].type;
/* check the date, don't show too old items */
if (_date - _news_type_data[type].age > ni->date) return;
switch (_news_type_data[type].display) {
default: NOT_REACHED();
case ND_OFF: // Off - show nothing only a small reminder in the status bar
InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SHOW_REMINDER);
break;
case ND_SUMMARY: // Summary - show ticker
ShowTicker(ni);
break;
case ND_FULL: // Full - show newspaper
ShowNewspaper(ni);
break;
}
}
}
/**
* Add a new newsitem to be shown.
* @param string String to display
* @param subtype news category, any of the NewsSubtype enums (NS_)
* @param data_a news-specific value based on news type
* @param data_b news-specific value based on news type
*
* @see NewsSubype
*/
void AddNewsItem(StringID string, NewsSubtype subtype, uint data_a, uint data_b, void *free_data)
{
if (_game_mode == GM_MENU) return;
/* Create new news item node */
NewsItem *ni = new NewsItem;
ni->string_id = string;
ni->subtype = subtype;
ni->flags = _news_subtype_data[subtype].flags;
/* show this news message in colour? */
if (_cur_year >= _settings_client.gui.coloured_news_year) ni->flags |= NF_INCOLOUR;
ni->data_a = data_a;
ni->data_b = data_b;
ni->free_data = free_data;
ni->date = _date;
CopyOutDParam(ni->params, 0, lengthof(ni->params));
if (_total_news++ == 0) {
assert(_oldest_news == NULL);
_oldest_news = ni;
ni->prev = NULL;
} else {
assert(_latest_news->next == NULL);
_latest_news->next = ni;
ni->prev = _latest_news;
}
ni->next = NULL;
_latest_news = ni;
InvalidateWindow(WC_MESSAGE_HISTORY, 0);
}
/** Delete a news item from the queue */
static void DeleteNewsItem(NewsItem *ni)
{
if (_forced_news == ni || _current_news == ni) {
/* about to remove the currently forced item (shown as newspapers) ||
* about to remove the currently displayed item (newspapers, ticker, or just a reminder) */
MoveToNextItem();
}
/* delete item */
if (ni->prev != NULL) {
ni->prev->next = ni->next;
} else {
assert(_oldest_news == ni);
_oldest_news = ni->next;
}
if (ni->next != NULL) {
ni->next->prev = ni->prev;
} else {
assert(_latest_news == ni);
_latest_news = ni->prev;
}
free(ni->free_data);
if (_current_news == ni) _current_news = ni->prev;
_total_news--;
delete ni;
InvalidateWindow(WC_MESSAGE_HISTORY, 0);
}
void DeleteVehicleNews(VehicleID vid, StringID news)
{
NewsItem *ni = _oldest_news;
while (ni != NULL) {
if (ni->flags & NF_VEHICLE &&
ni->data_a == vid &&
(news == INVALID_STRING_ID || ni->string_id == news)) {
/* grab a pointer to the next item before ni is freed */
NewsItem *p = ni->next;
DeleteNewsItem(ni);
ni = p;
} else {
ni = ni->next;
}
}
}
/** Remove news regarding given station so there are no 'unknown station now accepts Mail'
* or 'First train arrived at unknown station' news items.
* @param sid station to remove news about
*/
void DeleteStationNews(StationID sid)
{
NewsItem *ni = _oldest_news;
while (ni != NULL) {
NewsItem *next = ni->next;
switch (ni->subtype) {
case NS_ARRIVAL_COMPANY:
case NS_ARRIVAL_OTHER:
case NS_ACCEPTANCE:
if (ni->data_b == sid) DeleteNewsItem(ni);
break;
default:
break;
}
ni = next;
}
}
void RemoveOldNewsItems()
{
NewsItem *next;
for (NewsItem *cur = _oldest_news; _total_news > MIN_NEWS_AMOUNT && cur != NULL; cur = next) {
next = cur->next;
if (_date - _news_type_data[_news_subtype_data[cur->subtype].type].age * _settings_client.gui.news_message_timeout > cur->date) DeleteNewsItem(cur);
}
}
void NewsLoop()
{
/* no news item yet */
if (_total_news == 0) return;
static byte _last_clean_month = 0;
if (_last_clean_month != _cur_month) {
RemoveOldNewsItems();
_last_clean_month = _cur_month;
}
if (ReadyForNextItem()) MoveToNextItem();
}
/** Do a forced show of a specific message */
static void ShowNewsMessage(NewsItem *ni)
{
assert(_total_news != 0);
/* Delete the news window */
DeleteWindowById(WC_NEWS_WINDOW, 0);
/* setup forced news item */
_forced_news = ni;
if (_forced_news != NULL) {
DeleteWindowById(WC_NEWS_WINDOW, 0);
ShowNewspaper(ni);
}
}
/** Show previous news item */
void ShowLastNewsMessage()
{
if (_total_news == 0) {
return;
} else if (_forced_news == NULL) {
/* Not forced any news yet, show the current one, unless a news window is
* open (which can only be the current one), then show the previous item */
const Window *w = FindWindowById(WC_NEWS_WINDOW, 0);
ShowNewsMessage((w == NULL || (_current_news == _oldest_news)) ? _current_news : _current_news->prev);
} else if (_forced_news == _oldest_news) {
/* We have reached the oldest news, start anew with the latest */
ShowNewsMessage(_latest_news);
} else {
/* 'Scrolling' through news history show each one in turn */
ShowNewsMessage(_forced_news->prev);
}
}
/**
* Draw an unformatted news message truncated to a maximum length. If
* length exceeds maximum length it will be postfixed by '...'
* @param x,y position of the string
* @param colour the colour the string will be shown in
* @param *ni NewsItem being printed
* @param maxw maximum width of string in pixels
*/
static void DrawNewsString(int x, int y, TextColour colour, const NewsItem *ni, uint maxw)
{
char buffer[512], buffer2[512];
StringID str;
CopyInDParam(0, ni->params, lengthof(ni->params));
str = ni->string_id;
GetString(buffer, str, lastof(buffer));
/* Copy the just gotten string to another buffer to remove any formatting
* from it such as big fonts, etc. */
const char *ptr = buffer;
char *dest = buffer2;
WChar c_last = '\0';
for (;;) {
WChar c = Utf8Consume(&ptr);
if (c == 0) break;
/* Make a space from a newline, but ignore multiple newlines */
if (c == '\n' && c_last != '\n') {
dest[0] = ' ';
dest++;
} else if (c == '\r') {
dest[0] = dest[1] = dest[2] = dest[3] = ' ';
dest += 4;
} else if (IsPrintable(c)) {
dest += Utf8Encode(dest, c);
}
c_last = c;
}
*dest = '\0';
/* Truncate and show string; postfixed by '...' if neccessary */
DoDrawStringTruncated(buffer2, x, y, colour, maxw);
}
struct MessageHistoryWindow : Window {
MessageHistoryWindow(const WindowDesc *desc) : Window(desc)
{
this->vscroll.cap = 10;
this->vscroll.count = _total_news;
this->resize.step_height = 12;
this->resize.height = this->height - 12 * 6; // minimum of 4 items in the list, each item 12 high
this->resize.step_width = 1;
this->resize.width = 200; // can't make window any smaller than 200 pixel
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
int y = 19;
SetVScrollCount(this, _total_news);
this->DrawWidgets();
if (_total_news == 0) return;
NewsItem *ni = _latest_news;
for (int n = this->vscroll.pos; n > 0; n--) {
ni = ni->prev;
if (ni == NULL) return;
}
for (int n = this->vscroll.cap; n > 0; n--) {
SetDParam(0, ni->date);
DrawString(4, y, STR_SHORT_DATE, TC_WHITE);
DrawNewsString(82, y, TC_WHITE, ni, this->width - 95);
y += 12;
ni = ni->prev;
if (ni == NULL) return;
}
}
virtual void OnClick(Point pt, int widget)
{
if (widget == 3) {
NewsItem *ni = _latest_news;
if (ni == NULL) return;
for (int n = (pt.y - 19) / 12 + this->vscroll.pos; n > 0; n--) {
ni = ni->prev;
if (ni == NULL) return;
}
ShowNewsMessage(ni);
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / 12;
}
};
static const Widget _message_history_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_BROWN, 11, 387, 0, 13, STR_MESSAGE_HISTORY, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_BROWN, 388, 399, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_RB, COLOUR_BROWN, 0, 387, 14, 139, 0x0, STR_MESSAGE_HISTORY_TIP},
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_BROWN, 388, 399, 14, 127, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_BROWN, 388, 399, 128, 139, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
static const WindowDesc _message_history_desc(
240, 22, 400, 140, 400, 140,
WC_MESSAGE_HISTORY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_message_history_widgets
);
/** Display window with news messages history */
void ShowMessageHistory()
{
DeleteWindowById(WC_MESSAGE_HISTORY, 0);
new MessageHistoryWindow(&_message_history_desc);
}
/** News settings window widget offset constants */
enum {
WIDGET_NEWSOPT_DROP_SUMMARY = 4, ///< Dropdown that adjusts at once the level for all settings
WIDGET_NEWSOPT_SOUNDTICKER = 6, ///< Button activating sound on events
WIDGET_NEWSOPT_START_OPTION = 8, ///< First widget that is part of a group [<] .. [.]
};
static const StringID _message_opt[] = {STR_OFF, STR_SUMMARY, STR_FULL, INVALID_STRING_ID};
struct MessageOptionsWindow : Window {
int state;
MessageOptionsWindow(const WindowDesc *desc) : Window(desc)
{
NewsDisplay all_val;
/* Set up the initial disabled buttons in the case of 'off' or 'full' */
all_val = _news_type_data[0].display;
for (int i = 0; i < NT_END; i++) {
this->SetMessageButtonStates(_news_type_data[i].display, i);
/* If the value doesn't match the ALL-button value, set the ALL-button value to 'off' */
if (_news_type_data[i].display != all_val) all_val = ND_OFF;
}
/* If all values are the same value, the ALL-button will take over this value */
this->state = all_val;
this->FindWindowPlacementAndResize(desc);
}
/**
* Setup the disabled/enabled buttons in the message window
* If the value is 'off' disable the [<] widget, and enable the [>] one
* Same-wise for all the others. Starting value of 4 is the first widget
* group. These are grouped as [<][>] .. [<][>], etc.
* @param value to set in the widget
* @param element index of the group of widget to set
*/
void SetMessageButtonStates(byte value, int element)
{
element *= NB_WIDG_PER_SETTING;
this->SetWidgetDisabledState(element + WIDGET_NEWSOPT_START_OPTION, value == 0);
this->SetWidgetDisabledState(element + WIDGET_NEWSOPT_START_OPTION + 2, value == 2);
}
virtual void OnPaint()
{
if (_news_ticker_sound) this->LowerWidget(WIDGET_NEWSOPT_SOUNDTICKER);
this->widget[WIDGET_NEWSOPT_DROP_SUMMARY].data = _message_opt[this->state];
this->DrawWidgets();
/* Draw the string of each setting on each button. */
for (int i = 0, y = 26; i < NT_END; i++, y += 12) {
/* 51 comes from 13 + 89 (left and right of the button)+1, shiefted by one as to get division,
* which will give centered position */
DrawStringCentered(51, y + 1, _message_opt[_news_type_data[i].display], TC_BLACK);
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case WIDGET_NEWSOPT_DROP_SUMMARY: // Dropdown menu for all settings
ShowDropDownMenu(this, _message_opt, this->state, WIDGET_NEWSOPT_DROP_SUMMARY, 0, 0);
break;
case WIDGET_NEWSOPT_SOUNDTICKER: // Change ticker sound on/off
_news_ticker_sound ^= 1;
this->ToggleWidgetLoweredState(widget);
this->InvalidateWidget(widget);
break;
default: { // Clicked on the [<] .. [>] widgets
int wid = widget - WIDGET_NEWSOPT_START_OPTION;
if (wid >= 0 && wid < (NB_WIDG_PER_SETTING * NT_END)) {
int element = wid / NB_WIDG_PER_SETTING;
byte val = (_news_type_data[element].display + ((wid % NB_WIDG_PER_SETTING) ? 1 : -1)) % 3;
this->SetMessageButtonStates(val, element);
_news_type_data[element].display = (NewsDisplay)val;
this->SetDirty();
}
break;
}
}
}
virtual void OnDropdownSelect(int widget, int index)
{
this->state = index;
for (int i = 0; i < NT_END; i++) {
this->SetMessageButtonStates(index, i);
_news_type_data[i].display = (NewsDisplay)index;
}
this->SetDirty();
}
};
/*
* The news settings window widgets
*
* Main part of the window is a list of news setting lines, one for each news category.
* Each line is constructed by an expansion of the \c NEWS_SETTINGS_LINE macro
*/
/**
* Macro to construct one news setting line in the news - settings window.
* One line consists of four widgets, namely
* - A [<] button
* - A [...] label
* - A [>] button
* - A text label describing the news category
* Horizontal positions of the widgets are hard coded, vertical start position is (\a basey + \a linenum * \c NEWS_SETTING_BASELINE_SKIP).
* Height of one line is 12, with the text label shifted 1 pixel down.
*
* First line should be widget number WIDGET_NEWSOPT_START_OPTION
*
* @param basey: Base Y coordinate
* @param linenum: Count, news - setting is the \a linenum - th line
* @param text: StringID for the text label to display
*/
#define NEWS_SETTINGS_LINE(basey, linenum, text) \
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_YELLOW, \
4, 12, basey + linenum * NEWS_SETTING_BASELINE_SKIP, basey + 11 + linenum * NEWS_SETTING_BASELINE_SKIP, \
SPR_ARROW_LEFT, STR_HSCROLL_BAR_SCROLLS_LIST}, \
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, \
13, 89, basey + linenum * NEWS_SETTING_BASELINE_SKIP, basey + 11 + linenum * NEWS_SETTING_BASELINE_SKIP, \
STR_EMPTY, STR_NULL}, \
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_YELLOW, \
90, 98, basey + linenum * NEWS_SETTING_BASELINE_SKIP, basey + 11 + linenum * NEWS_SETTING_BASELINE_SKIP, \
SPR_ARROW_RIGHT, STR_HSCROLL_BAR_SCROLLS_LIST}, \
{ WWT_TEXT, RESIZE_NONE, COLOUR_YELLOW, \
103, 409, basey + 1 + linenum * NEWS_SETTING_BASELINE_SKIP, basey + 13 + linenum * NEWS_SETTING_BASELINE_SKIP, \
text, STR_NULL}
static const int NEWS_SETTING_BASELINE_SKIP = 12; ///< Distance between two news-setting lines, should be at least 12
static const Widget _message_options_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13,
STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_BROWN, 11, 409, 0, 13,
STR_0204_MESSAGE_OPTIONS, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_BROWN, 0, 409, 14, 64 + NT_END * NEWS_SETTING_BASELINE_SKIP,
0x0, STR_NULL},
/* Text at the top of the main panel, in black */
{ WWT_LABEL, RESIZE_NONE, COLOUR_BROWN,
0, 409, 13, 26,
STR_0205_MESSAGE_TYPES, STR_NULL},
/* General drop down and sound button, widgets WIDGET_NEWSOPT_BTN_SUMMARY and WIDGET_NEWSOPT_DROP_SUMMARY */
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_YELLOW,
4, 98, 34 + NT_END * NEWS_SETTING_BASELINE_SKIP, 45 + NT_END * NEWS_SETTING_BASELINE_SKIP,
0x0, STR_NULL},
{ WWT_TEXT, RESIZE_NONE, COLOUR_YELLOW,
103, 409, 35 + NT_END * NEWS_SETTING_BASELINE_SKIP, 47 + NT_END * NEWS_SETTING_BASELINE_SKIP,
STR_MESSAGES_ALL, STR_NULL},
/* Below is widget WIDGET_NEWSOPT_SOUNDTICKER */
{ WWT_TEXTBTN_2, RESIZE_NONE, COLOUR_YELLOW,
4, 98, 46 + NT_END * NEWS_SETTING_BASELINE_SKIP, 57 + NT_END * NEWS_SETTING_BASELINE_SKIP,
STR_02DB_OFF, STR_NULL},
{ WWT_TEXT, RESIZE_NONE, COLOUR_YELLOW,
103, 409, 47 + NT_END * NEWS_SETTING_BASELINE_SKIP, 59 + NT_END * NEWS_SETTING_BASELINE_SKIP,
STR_MESSAGE_SOUND, STR_NULL},
/* List of news-setting lines (4 widgets for each line).
* First widget must be number WIDGET_NEWSOPT_START_OPTION
*/
NEWS_SETTINGS_LINE(26, NT_ARRIVAL_COMPANY, STR_0206_ARRIVAL_OF_FIRST_VEHICLE),
NEWS_SETTINGS_LINE(26, NT_ARRIVAL_OTHER, STR_0207_ARRIVAL_OF_FIRST_VEHICLE),
NEWS_SETTINGS_LINE(26, NT_ACCIDENT, STR_0208_ACCIDENTS_DISASTERS),
NEWS_SETTINGS_LINE(26, NT_COMPANY_INFO, STR_0209_COMPANY_INFORMATION),
NEWS_SETTINGS_LINE(26, NT_INDUSTRY_OPEN, STR_NEWS_INDUSTRY_OPEN),
NEWS_SETTINGS_LINE(26, NT_INDUSTRY_CLOSE, STR_NEWS_INDUSTRY_CLOSE),
NEWS_SETTINGS_LINE(26, NT_ECONOMY, STR_020A_ECONOMY_CHANGES),
NEWS_SETTINGS_LINE(26, NT_INDUSTRY_COMPANY, STR_INDUSTRY_CHANGES_SERVED_BY_COMPANY),
NEWS_SETTINGS_LINE(26, NT_INDUSTRY_OTHER, STR_INDUSTRY_CHANGES_SERVED_BY_OTHER),
NEWS_SETTINGS_LINE(26, NT_INDUSTRY_NOBODY, STR_OTHER_INDUSTRY_PRODUCTION_CHANGES),
NEWS_SETTINGS_LINE(26, NT_ADVICE, STR_020B_ADVICE_INFORMATION_ON_COMPANY),
NEWS_SETTINGS_LINE(26, NT_NEW_VEHICLES, STR_020C_NEW_VEHICLES),
NEWS_SETTINGS_LINE(26, NT_ACCEPTANCE, STR_020D_CHANGES_OF_CARGO_ACCEPTANCE),
NEWS_SETTINGS_LINE(26, NT_SUBSIDIES, STR_020E_SUBSIDIES),
NEWS_SETTINGS_LINE(26, NT_GENERAL, STR_020F_GENERAL_INFORMATION),
{ WIDGETS_END},
};
static const WindowDesc _message_options_desc(
270, 22, 410, 65 + NT_END * NEWS_SETTING_BASELINE_SKIP,
410, 65 + NT_END * NEWS_SETTING_BASELINE_SKIP,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_message_options_widgets
);
void ShowMessageOptions()
{
DeleteWindowById(WC_GAME_OPTIONS, 0);
new MessageOptionsWindow(&_message_options_desc);
}
| 32,972
|
C++
|
.cpp
| 837
| 36.531661
| 150
| 0.654824
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,110
|
newgrf_canal.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_canal.cpp
|
/* $Id$ */
/** @file newgrf_canal.cpp Implementation of NewGRF canals. */
#include "stdafx.h"
#include "core/overflowsafe_type.hpp"
#include "tile_type.h"
#include "debug.h"
#include "newgrf_commons.h"
#include "newgrf_spritegroup.h"
#include "newgrf_canal.h"
#include "tile_map.h"
#include "water_map.h"
/** Table of canal 'feature' sprite groups */
WaterFeature _water_feature[CF_END];
/* Random bits and triggers are not supported for canals, so the following
* three functions are stubs. */
static uint32 CanalGetRandomBits(const ResolverObject *object)
{
/* Return random bits only for water tiles, not station tiles */
return IsTileType(object->u.canal.tile, MP_WATER) ? GetWaterTileRandomBits(object->u.canal.tile) : 0;
}
static uint32 CanalGetTriggers(const ResolverObject *object)
{
return 0;
}
static void CanalSetTriggers(const ResolverObject *object, int triggers)
{
return;
}
static uint32 CanalGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
{
TileIndex tile = object->u.canal.tile;
switch (variable) {
/* Height of tile */
case 0x80: return GetTileZ(tile) / TILE_HEIGHT;
/* Terrain type */
case 0x81: return GetTerrainType(tile);
/* Random data for river or canal tiles, otherwise zero */
case 0x83: return GetWaterTileRandomBits(tile);
}
DEBUG(grf, 1, "Unhandled canal property 0x%02X", variable);
*available = false;
return UINT_MAX;
}
static const SpriteGroup *CanalResolveReal(const ResolverObject *object, const SpriteGroup *group)
{
if (group->g.real.num_loaded == 0) return NULL;
return group->g.real.loaded[0];
}
static void NewCanalResolver(ResolverObject *res, TileIndex tile, const GRFFile *grffile)
{
res->GetRandomBits = &CanalGetRandomBits;
res->GetTriggers = &CanalGetTriggers;
res->SetTriggers = &CanalSetTriggers;
res->GetVariable = &CanalGetVariable;
res->ResolveReal = &CanalResolveReal;
res->u.canal.tile = tile;
res->callback = CBID_NO_CALLBACK;
res->callback_param1 = 0;
res->callback_param2 = 0;
res->last_value = 0;
res->trigger = 0;
res->reseed = 0;
res->count = 0;
res->grffile = grffile;
}
SpriteID GetCanalSprite(CanalFeature feature, TileIndex tile)
{
ResolverObject object;
const SpriteGroup *group;
NewCanalResolver(&object, tile, _water_feature[feature].grffile);
group = Resolve(_water_feature[feature].group, &object);
if (group == NULL || group->type != SGT_RESULT) return 0;
return group->g.result.sprite;
}
| 2,530
|
C++
|
.cpp
| 74
| 32.189189
| 108
| 0.742068
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,111
|
newgrf_industries.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_industries.cpp
|
/* $Id$ */
/** @file newgrf_industries.cpp Handling of NewGRF industries. */
#include "stdafx.h"
#include "debug.h"
#include "tile_type.h"
#include "strings_type.h"
#include "company_type.h"
#include "industry_map.h"
#include "newgrf.h"
#include "newgrf_industries.h"
#include "newgrf_commons.h"
#include "newgrf_text.h"
#include "newgrf_town.h"
#include "window_func.h"
#include "town.h"
#include "company_base.h"
#include "command_func.h"
#include "table/strings.h"
static uint32 _industry_creation_random_bits;
/* Since the industry IDs defined by the GRF file don't necessarily correlate
* to those used by the game, the IDs used for overriding old industries must be
* translated when the idustry spec is set. */
IndustryOverrideManager _industry_mngr(NEW_INDUSTRYOFFSET, NUM_INDUSTRYTYPES, INVALID_INDUSTRYTYPE);
IndustryTileOverrideManager _industile_mngr(NEW_INDUSTRYTILEOFFSET, NUM_INDUSTRYTILES, INVALID_INDUSTRYTILE);
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32 grf_id)
{
if (grf_type == IT_INVALID) return IT_INVALID;
if (!HasBit(grf_type, 7)) return GB(grf_type, 0, 6);
return _industry_mngr.GetID(GB(grf_type, 0, 6), grf_id);
}
/**
* Finds the distance for the closest tile with water/land given a tile
* @param tile the tile to find the distance too
* @param water whether to find water or land
* @return distance to nearest water (max 0x7F) / land (max 0x1FF; 0x200 if there is no land)
* @note FAILS when an industry should be seen as water
*/
static uint GetClosestWaterDistance(TileIndex tile, bool water)
{
if (IsTileType(tile, MP_WATER) == water) return 0;
uint max_dist = water ? 0x7F : 0x200;
int x = TileX(tile);
int y = TileY(tile);
uint max_x = MapMaxX();
uint max_y = MapMaxY();
uint min_xy = _settings_game.construction.freeform_edges ? 1 : 0;
/* go in a 'spiral' with increasing manhattan distance in each iteration */
for (uint dist = 1; dist < max_dist; dist++) {
/* next 'diameter' */
y--;
/* going counter-clockwise around this square */
for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
static const int8 ddx[DIAGDIR_END] = { -1, 1, 1, -1};
static const int8 ddy[DIAGDIR_END] = { 1, 1, -1, -1};
int dx = ddx[dir];
int dy = ddy[dir];
/* each side of this square has length 'dist' */
for (uint a = 0; a < dist; a++) {
/* MP_VOID tiles are not checked (interval is [min; max) for IsInsideMM())*/
if (IsInsideMM(x, min_xy, max_x) && IsInsideMM(y, min_xy, max_y)) {
TileIndex t = TileXY(x, y);
if (IsTileType(t, MP_WATER) == water) return dist;
}
x += dx;
y += dy;
}
}
}
if (!water) {
/* no land found - is this a water-only map? */
for (TileIndex t = 0; t < MapSize(); t++) {
if (!IsTileType(t, MP_VOID) && !IsTileType(t, MP_WATER)) return 0x1FF;
}
}
return max_dist;
}
/** Make an analysis of a tile and check for its belonging to the same
* industry, and/or the same grf file
* @param tile TileIndex of the tile to query
* @param i Industry to which to compare the tile to
* @return value encoded as per NFO specs */
uint32 GetIndustryIDAtOffset(TileIndex tile, const Industry *i)
{
if (!IsTileType(tile, MP_INDUSTRY) || GetIndustryIndex(tile) != i->index) {
/* No industry and/or the tile does not have the same industry as the one we match it with */
return 0xFFFF;
}
IndustryGfx gfx = GetCleanIndustryGfx(tile);
const IndustryTileSpec *indtsp = GetIndustryTileSpec(gfx);
const IndustrySpec *indold = GetIndustrySpec(i->type);
if (gfx < NEW_INDUSTRYOFFSET) { // Does it belongs to an old type?
/* It is an old tile. We have to see if it's been overriden */
if (indtsp->grf_prop.override == INVALID_INDUSTRYTILE) { // has it been overridden?
return 0xFF << 8 | gfx; // no. Tag FF + the gfx id of that tile
}
/* Not overriden */
const IndustryTileSpec *tile_ovr = GetIndustryTileSpec(indtsp->grf_prop.override);
if (tile_ovr->grf_prop.grffile->grfid == indold->grf_prop.grffile->grfid) {
return tile_ovr->grf_prop.local_id; // same grf file
} else {
return 0xFFFE; // not the same grf file
}
}
/* Not an 'old type' tile */
if (indtsp->grf_prop.spritegroup != NULL) { // tile has a spritegroup ?
if (indtsp->grf_prop.grffile->grfid == indold->grf_prop.grffile->grfid) { // same industry, same grf ?
return indtsp->grf_prop.local_id;
} else {
return 0xFFFE; // Defined in another grf file
}
}
/* The tile has no spritegroup */
return 0xFF << 8 | indtsp->grf_prop.subst_id; // so just give him the substitute
}
static uint32 GetClosestIndustry(TileIndex tile, IndustryType type, const Industry *current)
{
uint32 best_dist = UINT32_MAX;
const Industry *i;
FOR_ALL_INDUSTRIES(i) {
if (i->type != type || i == current) continue;
best_dist = min(best_dist, DistanceManhattan(tile, i->xy));
}
return best_dist;
}
/** Implementation of both var 67 and 68
* since the mechanism is almost the same, it is easier to regroup them on the same
* function.
* @param param_setID parameter given to the callback, which is the set id, or the local id, in our terminology
* @param layout_filter on what layout do we filter?
* @param current Industry for which the inquiry is made
* @return the formatted answer to the callback : rr(reserved) cc(count) dddd(manhattan distance of closest sister)
*/
static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout_filter, const Industry *current)
{
uint32 GrfID = GetRegister(0x100); ///< Get the GRFID of the definition to look for in register 100h
IndustryType ind_index;
uint32 closest_dist = UINT32_MAX;
byte count = 0;
/* Determine what will be the industry type to look for */
switch (GrfID) {
case 0: // this is a default industry type
ind_index = param_setID;
break;
case 0xFFFFFFFF: // current grf
GrfID = GetIndustrySpec(current->type)->grf_prop.grffile->grfid;
/* Fall through */
default: // use the grfid specified in register 100h
SetBit(param_setID, 7); // bit 7 means it is not an old type
ind_index = MapNewGRFIndustryType(param_setID, GrfID);
break;
}
if (layout_filter == 0) {
/* If the filter is 0, it could be because none was specified as well as being really a 0.
* In either case, just do the regular var67 */
closest_dist = GetClosestIndustry(current->xy, ind_index, current);
count = GetIndustryTypeCount(ind_index);
} else {
/* Count only those who match the same industry type and layout filter
* Unfortunately, we have to do it manually */
const Industry *i;
FOR_ALL_INDUSTRIES(i) {
if (i->type == ind_index && i != current && i->selected_layout == layout_filter) {
closest_dist = min(closest_dist, DistanceManhattan(current->xy, i->xy));
count++;
}
}
}
return count << 16 | GB(closest_dist, 0, 16);
}
/** This function implements the industries variables that newGRF defines.
* @param variable that is queried
* @param parameter unused
* @param available will return false if ever the variable asked for does not exist
* @param ind is of course the industry we are inquiring
* @return the value stored in the corresponding variable*/
uint32 IndustryGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
{
const Industry *industry = object->u.industry.ind;
TileIndex tile = object->u.industry.tile;
IndustryType type = object->u.industry.type;
const IndustrySpec *indspec = GetIndustrySpec(type);
/* Shall the variable get resolved in parent scope and are we not yet in parent scope? */
if (object->u.industry.gfx == INVALID_INDUSTRYTILE && object->scope == VSG_SCOPE_PARENT) {
/* Pass the request on to the town of the industry */
const Town *t;
if (industry != NULL) {
t = industry->town;
} else if (tile != INVALID_TILE) {
t = ClosestTownFromTile(tile, UINT_MAX);
} else {
*available = false;
return UINT_MAX;
}
return TownGetVariable(variable, parameter, available, t);
}
if (industry == NULL) {
/* industry does not exist, only use those variables that are "safe" */
switch (variable) {
/* Manhattan distance of closes dry/water tile */
case 0x43: return GetClosestWaterDistance(tile, (indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
}
DEBUG(grf, 1, "Unhandled property 0x%X (no available industry) in callback 0x%x", variable, object->callback);
*available = false;
return UINT_MAX;
}
switch (variable) {
case 0x40:
case 0x41:
case 0x42: { // waiting cargo, but only if those two callback flags are set
uint16 callback = indspec->callback_flags;
if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
if ((indspec->behaviour & INDUSTRYBEH_PROD_MULTI_HNDLING) != 0) {
return min(industry->incoming_cargo_waiting[variable - 0x40] / industry->prod_level, (uint16)0xFFFF);
} else {
return min(industry->incoming_cargo_waiting[variable - 0x40], (uint16)0xFFFF);
}
} else {
return 0;
}
}
/* Manhattan distance of closes dry/water tile */
case 0x43: return GetClosestWaterDistance(tile, (indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
/* Layout number */
case 0x44: return industry->selected_layout;
/* Company info */
case 0x45: {
byte colours;
bool is_ai = false;
if (IsValidCompanyID(industry->founder)) {
const Company *c = GetCompany(industry->founder);
const Livery *l = &c->livery[LS_DEFAULT];
is_ai = c->is_ai;
colours = l->colour1 + l->colour2 * 16;
} else {
colours = GB(Random(), 0, 8);
}
return industry->founder | (is_ai ? 0x10000 : 0) | (colours << 24);
}
case 0x46: return industry->construction_date; // Date when built - long format - (in days)
/* Get industry ID at offset param */
case 0x60: return GetIndustryIDAtOffset(GetNearbyTile(parameter, industry->xy), industry);
/* Get random tile bits at offset param */
case 0x61:
tile = GetNearbyTile(parameter, tile);
return (IsTileType(tile, MP_INDUSTRY) && GetIndustryByTile(tile) == industry) ? GetIndustryRandomBits(tile) : 0;
/* Land info of nearby tiles */
case 0x62: return GetNearbyIndustryTileInformation(parameter, tile, INVALID_INDUSTRY);
/* Animation stage of nearby tiles */
case 0x63:
tile = GetNearbyTile(parameter, tile);
if (IsTileType(tile, MP_INDUSTRY) && GetIndustryByTile(tile) == industry) {
return GetIndustryAnimationState(tile);
}
return 0xFFFFFFFF;
/* Distance of nearest industry of given type */
case 0x64: return GetClosestIndustry(tile, MapNewGRFIndustryType(parameter, indspec->grf_prop.grffile->grfid), industry);
/* Get town zone and Manhattan distance of closest town */
case 0x65: return GetTownRadiusGroup(industry->town, tile) << 16 | min(DistanceManhattan(tile, industry->town->xy), 0xFFFF);
/* Get square of Euclidian distance of closes town */
case 0x66: return GetTownRadiusGroup(industry->town, tile) << 16 | min(DistanceSquare(tile, industry->town->xy), 0xFFFF);
/* Count of industry, distance of closest instance
* 68 is the same as 67, but with a filtering on selected layout */
case 0x67:
case 0x68: return GetCountAndDistanceOfClosestInstance(parameter, variable == 0x68 ? GB(GetRegister(0x101), 0, 8) : 0, industry);
/* Get a variable from the persistent storage */
case 0x7C: return industry->psa.Get(parameter);
/* Industry structure access*/
case 0x80: return industry->xy;
case 0x81: return GB(industry->xy, 8, 8);
/* Pointer to the town the industry is associated with */
case 0x82: return industry->town->index;
case 0x83:
case 0x84:
case 0x85: DEBUG(grf, 0, "NewGRFs shouldn't be doing pointer magic"); break; // not supported
case 0x86: return industry->width;
case 0x87: return industry->height;// xy dimensions
case 0x88:
case 0x89: return industry->produced_cargo[variable - 0x88];
case 0x8A: return industry->produced_cargo_waiting[0];
case 0x8B: return GB(industry->produced_cargo_waiting[0], 8, 8);
case 0x8C: return industry->produced_cargo_waiting[1];
case 0x8D: return GB(industry->produced_cargo_waiting[1], 8, 8);
case 0x8E:
case 0x8F: return industry->production_rate[variable - 0x8E];
case 0x90:
case 0x91:
case 0x92: return industry->accepts_cargo[variable - 0x90];
case 0x93: return industry->prod_level;
/* amount of cargo produced so far THIS month. */
case 0x94: return industry->this_month_production[0];
case 0x95: return GB(industry->this_month_production[0], 8, 8);
case 0x96: return industry->this_month_production[1];
case 0x97: return GB(industry->this_month_production[1], 8, 8);
/* amount of cargo transported so far THIS month. */
case 0x98: return industry->this_month_transported[0];
case 0x99: return GB(industry->this_month_transported[0], 8, 8);
case 0x9A: return industry->this_month_transported[1];
case 0x9B: return GB(industry->this_month_transported[0], 8, 8);
/* fraction of cargo transported LAST month. */
case 0x9C:
case 0x9D: return industry->last_month_pct_transported[variable - 0x9C];
/* amount of cargo produced LAST month. */
case 0x9E: return industry->last_month_production[0];
case 0x9F: return GB(industry->last_month_production[0], 8, 8);
case 0xA0: return industry->last_month_production[1];
case 0xA1: return GB(industry->last_month_production[1], 8, 8);
/* amount of cargo transported last month. */
case 0xA2: return industry->last_month_transported[0];
case 0xA3: return GB(industry->last_month_transported[0], 8, 8);
case 0xA4: return industry->last_month_transported[1];
case 0xA5: return GB(industry->last_month_transported[0], 8, 8);
case 0xA6: return industry->type;
case 0xA7: return industry->founder;
case 0xA8: return industry->random_colour;
case 0xA9: return Clamp(industry->last_prod_year - ORIGINAL_BASE_YEAR, 0, 255);
case 0xAA: return industry->counter;
case 0xAB: return GB(industry->counter, 8, 8);
case 0xAC: return industry->was_cargo_delivered;
case 0xB0: return Clamp(industry->construction_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Date when built since 1920 (in days)
case 0xB3: return industry->construction_type; // Construction type
case 0xB4: return Clamp(industry->last_cargo_accepted_at - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Date last cargo accepted since 1920 (in days)
}
DEBUG(grf, 1, "Unhandled industry property 0x%X", variable);
*available = false;
return UINT_MAX;
}
static const SpriteGroup *IndustryResolveReal(const ResolverObject *object, const SpriteGroup *group)
{
/* IndustryTile do not have 'real' groups */
return NULL;
}
static uint32 IndustryGetRandomBits(const ResolverObject *object)
{
return object->u.industry.ind == NULL ? 0 : object->u.industry.ind->random;
}
static uint32 IndustryGetTriggers(const ResolverObject *object)
{
return object->u.industry.ind == NULL ? 0 : object->u.industry.ind->random_triggers;
}
static void IndustrySetTriggers(const ResolverObject *object, int triggers)
{
if (object->u.industry.ind == NULL) return;
object->u.industry.ind->random_triggers = triggers;
}
static void NewIndustryResolver(ResolverObject *res, TileIndex tile, Industry *indus, IndustryType type)
{
res->GetRandomBits = IndustryGetRandomBits;
res->GetTriggers = IndustryGetTriggers;
res->SetTriggers = IndustrySetTriggers;
res->GetVariable = IndustryGetVariable;
res->ResolveReal = IndustryResolveReal;
res->psa = &indus->psa;
res->u.industry.tile = tile;
res->u.industry.ind = indus;
res->u.industry.gfx = INVALID_INDUSTRYTILE;
res->u.industry.type = type;
res->callback = CBID_NO_CALLBACK;
res->callback_param1 = 0;
res->callback_param2 = 0;
res->last_value = 0;
res->trigger = 0;
res->reseed = 0;
res->count = 0;
const IndustrySpec *indspec = GetIndustrySpec(type);
res->grffile = (indspec != NULL ? indspec->grf_prop.grffile : NULL);
}
uint16 GetIndustryCallback(CallbackID callback, uint32 param1, uint32 param2, Industry *industry, IndustryType type, TileIndex tile)
{
ResolverObject object;
const SpriteGroup *group;
NewIndustryResolver(&object, tile, industry, type);
object.callback = callback;
object.callback_param1 = param1;
object.callback_param2 = param2;
group = Resolve(GetIndustrySpec(type)->grf_prop.spritegroup, &object);
if (group == NULL || group->type != SGT_CALLBACK) return CALLBACK_FAILED;
return group->g.callback.result;
}
uint32 IndustryLocationGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
{
const Industry *industry = object->u.industry.ind;
TileIndex tile = object->u.industry.tile;
if (object->scope == VSG_SCOPE_PARENT) {
return TownGetVariable(variable, parameter, available, industry->town);
}
switch (variable) {
case 0x80: return tile;
case 0x81: return GB(tile, 8, 8);
/* Pointer to the town the industry is associated with */
case 0x82: return industry->town->index;
case 0x83:
case 0x84:
case 0x85: DEBUG(grf, 0, "NewGRFs shouldn't be doing pointer magic"); break; // not supported
/* Number of the layout */
case 0x86: return industry->selected_layout;
/* Ground type */
case 0x87: return GetTerrainType(tile);
/* Town zone */
case 0x88: return GetTownRadiusGroup(industry->town, tile);
/* Manhattan distance of the closest town */
case 0x89: return min(DistanceManhattan(industry->town->xy, tile), 255);
/* Lowest height of the tile */
case 0x8A: return GetTileZ(tile);
/* Distance to the nearest water/land tile */
case 0x8B: return GetClosestWaterDistance(tile, (GetIndustrySpec(industry->type)->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
/* Square of Euclidian distance from town */
case 0x8D: return min(DistanceSquare(industry->town->xy, tile), 65535);
/* 32 random bits */
case 0x8F: return _industry_creation_random_bits;
}
/* None of the special ones, so try the general ones */
return IndustryGetVariable(object, variable, parameter, available);
}
bool CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, uint itspec_index, uint32 seed)
{
const IndustrySpec *indspec = GetIndustrySpec(type);
ResolverObject object;
const SpriteGroup *group;
Industry ind;
ind.index = INVALID_INDUSTRY;
ind.xy = tile;
ind.width = 0;
ind.type = type;
ind.selected_layout = itspec_index;
ind.town = ClosestTownFromTile(tile, UINT_MAX);
NewIndustryResolver(&object, tile, &ind, type);
object.GetVariable = IndustryLocationGetVariable;
object.callback = CBID_INDUSTRY_LOCATION;
_industry_creation_random_bits = seed;
group = Resolve(GetIndustrySpec(type)->grf_prop.spritegroup, &object);
/* Unlike the "normal" cases, not having a valid result means we allow
* the building of the industry, as that's how it's done in TTDP. */
if (group == NULL || group->type != SGT_CALLBACK || group->g.callback.result == 0x400) return true;
/* Copy some parameters from the registers to the error message text ref. stack */
SwitchToErrorRefStack();
PrepareTextRefStackUsage(4);
SwitchToNormalRefStack();
switch (group->g.callback.result) {
case 0x401: _error_message = STR_0239_SITE_UNSUITABLE; break;
case 0x402: _error_message = STR_0317_CAN_ONLY_BE_BUILT_IN_RAINFOREST; break;
case 0x403: _error_message = STR_0318_CAN_ONLY_BE_BUILT_IN_DESERT; break;
default: _error_message = GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + group->g.callback.result); break;
}
return false;
}
bool CheckIfCallBackAllowsAvailability(IndustryType type, IndustryAvailabilityCallType creation_type)
{
const IndustrySpec *indspec = GetIndustrySpec(type);
if (HasBit(indspec->callback_flags, CBM_IND_AVAILABLE)) {
uint16 res = GetIndustryCallback(CBID_INDUSTRY_AVAILABLE, 0, creation_type, NULL, type, INVALID_TILE);
if (res != CALLBACK_FAILED) {
return (res == 0);
}
}
return true;
}
static int32 DerefIndProd(uint field, bool use_register)
{
return use_register ? (int32)GetRegister(field) : field;
}
/**
* Get the industry production callback and apply it to the industry.
* @param ind the industry this callback has to be called for
* @param reason the reason it is called (0 = incoming cargo, 1 = periodic tick callback)
*/
void IndustryProductionCallback(Industry *ind, int reason)
{
const IndustrySpec *spec = GetIndustrySpec(ind->type);
ResolverObject object;
NewIndustryResolver(&object, ind->xy, ind, ind->type);
if ((spec->behaviour & INDUSTRYBEH_PRODCALLBACK_RANDOM) != 0) object.callback_param1 = Random();
int multiplier = 1;
if ((spec->behaviour & INDUSTRYBEH_PROD_MULTI_HNDLING) != 0) multiplier = ind->prod_level;
object.callback_param2 = reason;
for (uint loop = 0;; loop++) {
SB(object.callback_param2, 8, 16, loop);
const SpriteGroup *group = Resolve(spec->grf_prop.spritegroup, &object);
if (group == NULL || group->type != SGT_INDUSTRY_PRODUCTION) break;
bool deref = (group->g.indprod.version == 1);
for (uint i = 0; i < 3; i++) {
ind->incoming_cargo_waiting[i] = Clamp(ind->incoming_cargo_waiting[i] - DerefIndProd(group->g.indprod.substract_input[i], deref) * multiplier, 0, 0xFFFF);
}
for (uint i = 0; i < 2; i++) {
ind->produced_cargo_waiting[i] = Clamp(ind->produced_cargo_waiting[i] + max(DerefIndProd(group->g.indprod.add_output[i], deref), 0) * multiplier, 0, 0xFFFF);
}
int32 again = DerefIndProd(group->g.indprod.again, deref);
if (again == 0) break;
SB(object.callback_param2, 24, 8, again);
}
InvalidateWindow(WC_INDUSTRY_VIEW, ind->index);
}
| 21,575
|
C++
|
.cpp
| 491
| 41.195519
| 160
| 0.725241
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,112
|
sound.cpp
|
EnergeticBark_OpenTTD-3DS/src/sound.cpp
|
/* $Id$ */
/** @file sound.cpp Handling of playing sounds. */
#include "stdafx.h"
#include "landscape.h"
#include "mixer.h"
#include "fileio_func.h"
#include "newgrf_sound.h"
#include "fios.h"
#include "window_gui.h"
#include "map_func.h"
#include "vehicle_base.h"
#include "debug.h"
static uint _file_count;
static FileEntry *_files;
MusicFileSettings msf;
/* Number of levels of panning per side */
#define PANNING_LEVELS 16
/** The number of sounds in the original sample.cat */
static const uint ORIGINAL_SAMPLE_COUNT = 73;
static void OpenBankFile(const char *filename)
{
FileEntry *fe = CallocT<FileEntry>(ORIGINAL_SAMPLE_COUNT);
_file_count = ORIGINAL_SAMPLE_COUNT;
_files = fe;
FioOpenFile(SOUND_SLOT, filename);
size_t pos = FioGetPos();
uint count = FioReadDword() / 8;
/* Simple check for the correct number of original sounds. */
if (count != ORIGINAL_SAMPLE_COUNT) {
/* Corrupt sample data? Just leave the allocated memory as those tell
* there is no sound to play (size = 0 due to calloc). Not allocating
* the memory disables valid NewGRFs that replace sounds. */
DEBUG(misc, 6, "Incorrect number of sounds in '%s', ignoring.", filename);
return;
}
FioSeekTo(pos, SEEK_SET);
for (uint i = 0; i != ORIGINAL_SAMPLE_COUNT; i++) {
fe[i].file_slot = SOUND_SLOT;
fe[i].file_offset = FioReadDword() + pos;
fe[i].file_size = FioReadDword();
}
for (uint i = 0; i != ORIGINAL_SAMPLE_COUNT; i++, fe++) {
char name[255];
FioSeekTo(fe->file_offset, SEEK_SET);
/* Check for special case, see else case */
FioReadBlock(name, FioReadByte()); // Read the name of the sound
if (strcmp(name, "Corrupt sound") != 0) {
FioSeekTo(12, SEEK_CUR); // Skip past RIFF header
/* Read riff tags */
for (;;) {
uint32 tag = FioReadDword();
uint32 size = FioReadDword();
if (tag == ' tmf') {
FioReadWord(); // wFormatTag
fe->channels = FioReadWord(); // wChannels
FioReadDword(); // samples per second
fe->rate = 11025; // seems like all samples should be played at this rate.
FioReadDword(); // avg bytes per second
FioReadWord(); // alignment
fe->bits_per_sample = FioReadByte(); // bits per sample
FioSeekTo(size - (2 + 2 + 4 + 4 + 2 + 1), SEEK_CUR);
} else if (tag == 'atad') {
fe->file_size = size;
fe->file_slot = SOUND_SLOT;
fe->file_offset = FioGetPos();
break;
} else {
fe->file_size = 0;
break;
}
}
} else {
/*
* Special case for the jackhammer sound
* (name in sample.cat is "Corrupt sound")
* It's no RIFF file, but raw PCM data
*/
fe->channels = 1;
fe->rate = 11025;
fe->bits_per_sample = 8;
fe->file_slot = SOUND_SLOT;
fe->file_offset = FioGetPos();
}
}
}
uint GetNumOriginalSounds()
{
return _file_count;
}
static bool SetBankSource(MixerChannel *mc, const FileEntry *fe)
{
assert(fe != NULL);
if (fe->file_size == 0) return false;
int8 *mem = MallocT<int8>(fe->file_size);
FioSeekToFile(fe->file_slot, fe->file_offset);
FioReadBlock(mem, fe->file_size);
for (uint i = 0; i != fe->file_size; i++) {
mem[i] += -128; // Convert unsigned sound data to signed
}
assert(fe->bits_per_sample == 8 && fe->channels == 1 && fe->file_size != 0 && fe->rate != 0);
MxSetChannelRawSrc(mc, mem, fe->file_size, fe->rate, MX_AUTOFREE);
return true;
}
bool SoundInitialize(const char *filename)
{
OpenBankFile(filename);
return true;
}
/* Low level sound player */
static void StartSound(uint sound, int panning, uint volume)
{
if (volume == 0) return;
const FileEntry *fe = GetSound(sound);
if (fe == NULL) return;
MixerChannel *mc = MxAllocateChannel();
if (mc == NULL) return;
if (!SetBankSource(mc, fe)) return;
/* Apply the sound effect's own volume. */
volume = (fe->volume * volume) / 128;
panning = Clamp(panning, -PANNING_LEVELS, PANNING_LEVELS);
uint left_vol = (volume * PANNING_LEVELS) - (volume * panning);
uint right_vol = (volume * PANNING_LEVELS) + (volume * panning);
MxSetChannelVolume(mc, left_vol * 128 / PANNING_LEVELS, right_vol * 128 / PANNING_LEVELS);
MxActivateChannel(mc);
}
static const byte _vol_factor_by_zoom[] = {255, 190, 134, 87};
assert_compile(lengthof(_vol_factor_by_zoom) == ZOOM_LVL_COUNT);
static const byte _sound_base_vol[] = {
128, 90, 128, 128, 128, 128, 128, 128,
128, 90, 90, 128, 128, 128, 128, 128,
128, 128, 128, 80, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 90, 90, 90, 128, 90, 128,
128, 90, 128, 128, 128, 90, 128, 128,
128, 128, 128, 128, 90, 128, 128, 128,
128, 90, 128, 128, 128, 128, 128, 128,
128, 128, 90, 90, 90, 128, 128, 128,
90,
};
static const byte _sound_idx[] = {
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, 0,
1, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71,
72,
};
void SndCopyToPool()
{
for (uint i = 0; i < _file_count; i++) {
FileEntry *orig = &_files[_sound_idx[i]];
FileEntry *fe = AllocateFileEntry();
*fe = *orig;
fe->volume = _sound_base_vol[i];
fe->priority = 0;
}
}
/**
* Decide 'where' (between left and right speaker) to play the sound effect.
* @param sound Sound effect to play
* @param left Left edge of virtual coordinates where the sound is produced
* @param right Right edge of virtual coordinates where the sound is produced
* @param top Top edge of virtual coordinates where the sound is produced
* @param bottom Bottom edge of virtual coordinates where the sound is produced
*/
static void SndPlayScreenCoordFx(SoundFx sound, int left, int right, int top, int bottom)
{
if (msf.effect_vol == 0) return;
const Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
const ViewPort *vp = w->viewport;
if (vp != NULL &&
left < vp->virtual_left + vp->virtual_width && right > vp->virtual_left &&
top < vp->virtual_top + vp->virtual_height && bottom > vp->virtual_top) {
int screen_x = (left + right) / 2 - vp->virtual_left;
int width = (vp->virtual_width == 0 ? 1 : vp->virtual_width);
int panning = (screen_x * PANNING_LEVELS * 2) / width - PANNING_LEVELS;
StartSound(
sound,
panning,
(msf.effect_vol * _vol_factor_by_zoom[vp->zoom - ZOOM_LVL_BEGIN]) / 256
);
return;
}
}
}
void SndPlayTileFx(SoundFx sound, TileIndex tile)
{
/* emits sound from center of the tile */
int x = min(MapMaxX() - 1, TileX(tile)) * TILE_SIZE + TILE_SIZE / 2;
int y = min(MapMaxY() - 1, TileY(tile)) * TILE_SIZE - TILE_SIZE / 2;
uint z = (y < 0 ? 0 : GetSlopeZ(x, y));
Point pt = RemapCoords(x, y, z);
y += 2 * TILE_SIZE;
Point pt2 = RemapCoords(x, y, GetSlopeZ(x, y));
SndPlayScreenCoordFx(sound, pt.x, pt2.x, pt.y, pt2.y);
}
void SndPlayVehicleFx(SoundFx sound, const Vehicle *v)
{
SndPlayScreenCoordFx(sound,
v->coord.left, v->coord.right,
v->coord.top, v->coord.bottom
);
}
void SndPlayFx(SoundFx sound)
{
StartSound(sound, 0, msf.effect_vol);
}
| 7,086
|
C++
|
.cpp
| 212
| 30.712264
| 94
| 0.658126
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,114
|
toolbar_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/toolbar_gui.cpp
|
/* $Id$ */
/** @file toolbar_gui.cpp Code related to the (main) toolbar. */
#include "stdafx.h"
#include "openttd.h"
#include "gui.h"
#include "window_gui.h"
#include "window_func.h"
#include "viewport_func.h"
#include "command_func.h"
#include "variables.h"
#include "vehicle_gui.h"
#include "rail_gui.h"
#include "road_gui.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "terraform_gui.h"
#include "transparency.h"
#include "strings_func.h"
#include "company_func.h"
#include "company_gui.h"
#include "vehicle_base.h"
#include "cheat_func.h"
#include "transparency_gui.h"
#include "screenshot.h"
#include "signs_func.h"
#include "fios.h"
#include "functions.h"
#include "console_gui.h"
#include "news_gui.h"
#include "ai/ai_gui.hpp"
#include "tilehighlight_func.h"
#include "rail.h"
#include "widgets/dropdown_type.h"
#include "settings_type.h"
#include "newgrf_config.h"
#include "network/network.h"
#include "network/network_gui.h"
#include "network/network_func.h"
#include "table/strings.h"
#include "table/sprites.h"
static void SplitToolbar(Window *w);
RailType _last_built_railtype;
RoadType _last_built_roadtype;
/** This enum gathers properties of both toolbars */
enum ToolBarProperties {
TBP_BUTTONWIDTH = 22, ///< width of a button
TBP_BUTTONHEIGHT = 22, ///< height of a button as well as the toolbars
TBP_DATEPANELWIDTH = 130, ///< used in scenario editor to calculate width of the toolbar.
TBP_TOOLBAR_MINBUTTON = 14, ///< references both toolbars
TBP_NORMAL_MAXBUTTON = 19, ///< normal toolbar has this many buttons
TBP_SCENARIO_MAXBUTTON = 16, ///< while the scenario has these
};
enum ToolbarMode {
TB_NORMAL,
TB_UPPER,
TB_LOWER
};
enum ToolbarNormalWidgets {
TBN_PAUSE = 0,
TBN_FASTFORWARD,
TBN_SETTINGS,
TBN_SAVEGAME,
TBN_SMALLMAP,
TBN_TOWNDIRECTORY,
TBN_SUBSIDIES,
TBN_STATIONS,
TBN_FINANCES,
TBN_COMPANIES,
TBN_GRAPHICS,
TBN_LEAGUE,
TBN_INDUSTRIES,
TBN_VEHICLESTART, ///< trains, actually. So following are trucks, boats and planes
TBN_TRAINS = TBN_VEHICLESTART,
TBN_ROADVEHS,
TBN_SHIPS,
TBN_AIRCRAFTS,
TBN_ZOOMIN,
TBN_ZOOMOUT,
TBN_RAILS,
TBN_ROADS,
TBN_WATER,
TBN_AIR,
TBN_LANDSCAPE,
TBN_MUSICSOUND,
TBN_NEWSREPORT,
TBN_HELP,
TBN_SWITCHBAR, ///< only available when toolbar has been split
};
enum ToolbarScenEditorWidgets {
TBSE_PAUSE = 0,
TBSE_FASTFORWARD,
TBSE_SAVESCENARIO = 3,
TBSE_SPACERPANEL,
TBSE_DATEPANEL,
TBSE_DATEBACKWARD,
TBSE_DATEFORWARD,
TBSE_SMALLMAP,
TBSE_ZOOMIN,
TBSE_ZOOMOUT,
TBSE_LANDGENERATE,
TBSE_TOWNGENERATE,
TBSE_INDUSTRYGENERATE,
TBSE_BUILDROAD,
TBSE_BUILDDOCKS,
TBSE_PLANTTREES,
TBSE_PLACESIGNS,
};
/**
* Drop down list entry for showing a checked/unchecked toggle item.
*/
class DropDownListCheckedItem : public DropDownListStringItem {
public:
bool checked;
DropDownListCheckedItem(StringID string, int result, bool masked, bool checked) : DropDownListStringItem(string, result, masked), checked(checked) {}
virtual ~DropDownListCheckedItem() {}
void Draw(int x, int y, uint width, uint height, bool sel, int bg_colour) const
{
if (checked) {
DrawString(x + 2, y, STR_CHECKMARK, sel ? TC_WHITE : TC_BLACK);
}
DrawStringTruncated(x + 2, y, this->String(), sel ? TC_WHITE : TC_BLACK, width);
}
};
/**
* Drop down list entry for showing a company entry, with companies 'blob'.
*/
class DropDownListCompanyItem : public DropDownListItem {
public:
bool greyed;
DropDownListCompanyItem(int result, bool masked, bool greyed) : DropDownListItem(result, masked), greyed(greyed) {}
virtual ~DropDownListCompanyItem() {}
bool Selectable() const
{
return true;
}
uint Width() const
{
char buffer[512];
CompanyID company = (CompanyID)result;
SetDParam(0, company);
SetDParam(1, company);
GetString(buffer, STR_7021, lastof(buffer));
return GetStringBoundingBox(buffer).width + 19;
}
void Draw(int x, int y, uint width, uint height, bool sel, int bg_colour) const
{
CompanyID company = (CompanyID)result;
DrawCompanyIcon(company, x + 2, y + 1);
SetDParam(0, company);
SetDParam(1, company);
TextColour col;
if (this->greyed) {
col = TC_GREY;
} else {
col = sel ? TC_WHITE : TC_BLACK;
}
DrawStringTruncated(x + 19, y, STR_7021, col, width - 17);
}
};
/**
* Pop up a generic text only menu.
*/
static void PopupMainToolbMenu(Window *w, int widget, StringID string, int count)
{
DropDownList *list = new DropDownList();
for (int i = 0; i < count; i++) {
list->push_back(new DropDownListStringItem(string + i, i, false));
}
ShowDropDownList(w, list, 0, widget, 140, true, true);
SndPlayFx(SND_15_BEEP);
}
/** Enum for the Company Toolbar's network related buttons */
enum {
CTMN_CLIENT_LIST = -1, ///< Show the client list
CTMN_NEW_COMPANY = -2, ///< Create a new company
CTMN_SPECTATE = -3, ///< Become spectator
};
/**
* Pop up a generic company list menu.
*/
static void PopupMainCompanyToolbMenu(Window *w, int widget, int grey = 0)
{
DropDownList *list = new DropDownList();
#ifdef ENABLE_NETWORK
if (widget == TBN_COMPANIES && _networking) {
/* Add the client list button for the companies menu */
list->push_back(new DropDownListStringItem(STR_NETWORK_CLIENT_LIST, CTMN_CLIENT_LIST, false));
if (_local_company == COMPANY_SPECTATOR) {
list->push_back(new DropDownListStringItem(STR_NETWORK_COMPANY_LIST_NEW_COMPANY, CTMN_NEW_COMPANY, NetworkMaxCompaniesReached()));
} else {
list->push_back(new DropDownListStringItem(STR_NETWORK_COMPANY_LIST_SPECTATE, CTMN_SPECTATE, NetworkMaxSpectatorsReached()));
}
}
#endif /* ENABLE_NETWORK */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (!IsValidCompanyID(c)) continue;
list->push_back(new DropDownListCompanyItem(c, false, HasBit(grey, c)));
}
ShowDropDownList(w, list, _local_company == COMPANY_SPECTATOR ? CTMN_CLIENT_LIST : (int)_local_company, widget, 240, true, true);
SndPlayFx(SND_15_BEEP);
}
static ToolbarMode _toolbar_mode;
static void SelectSignTool()
{
if (_cursor.sprite == SPR_CURSOR_SIGN) {
ResetObjectToPlace();
} else {
SetObjectToPlace(SPR_CURSOR_SIGN, PAL_NONE, VHM_RECT, WC_MAIN_TOOLBAR, 0);
_place_proc = PlaceProc_Sign;
}
}
/* --- Pausing --- */
static void ToolbarPauseClick(Window *w)
{
if (_networking && !_network_server) return; // only server can pause the game
if (DoCommandP(0, _pause_game ? 0 : 1, 0, CMD_PAUSE)) SndPlayFx(SND_15_BEEP);
}
/* --- Fast forwarding --- */
static void ToolbarFastForwardClick(Window *w)
{
_fast_forward ^= true;
SndPlayFx(SND_15_BEEP);
}
/* --- Options button menu --- */
enum OptionMenuEntries {
OME_GAMEOPTIONS,
OME_DIFFICULTIES,
OME_SETTINGS,
OME_NEWGRFSETTINGS,
OME_TRANSPARENCIES,
OME_SHOW_TOWNNAMES,
OME_SHOW_STATIONNAMES,
OME_SHOW_SIGNS,
OME_SHOW_WAYPOINTNAMES,
OME_FULL_ANIMATION,
OME_FULL_DETAILS,
OME_TRANSPARENTBUILDINGS,
OME_SHOW_STATIONSIGNS,
};
static void ToolbarOptionsClick(Window *w)
{
DropDownList *list = new DropDownList();
list->push_back(new DropDownListStringItem(STR_02C4_GAME_OPTIONS, OME_GAMEOPTIONS, false));
list->push_back(new DropDownListStringItem(STR_02C6_DIFFICULTY_SETTINGS, OME_DIFFICULTIES, false));
list->push_back(new DropDownListStringItem(STR_MENU_CONFIG_SETTINGS, OME_SETTINGS, false));
list->push_back(new DropDownListStringItem(STR_NEWGRF_SETTINGS, OME_NEWGRFSETTINGS, false));
list->push_back(new DropDownListStringItem(STR_TRANSPARENCY_OPTIONS, OME_TRANSPARENCIES, false));
list->push_back(new DropDownListItem(-1, false));
list->push_back(new DropDownListCheckedItem(STR_02CA_TOWN_NAMES_DISPLAYED, OME_SHOW_TOWNNAMES, false, HasBit(_display_opt, DO_SHOW_TOWN_NAMES)));
list->push_back(new DropDownListCheckedItem(STR_02CC_STATION_NAMES_DISPLAYED, OME_SHOW_STATIONNAMES, false, HasBit(_display_opt, DO_SHOW_STATION_NAMES)));
list->push_back(new DropDownListCheckedItem(STR_02CE_SIGNS_DISPLAYED, OME_SHOW_SIGNS, false, HasBit(_display_opt, DO_SHOW_SIGNS)));
list->push_back(new DropDownListCheckedItem(STR_WAYPOINTS_DISPLAYED2, OME_SHOW_WAYPOINTNAMES, false, HasBit(_display_opt, DO_WAYPOINTS)));
list->push_back(new DropDownListCheckedItem(STR_02D0_FULL_ANIMATION, OME_FULL_ANIMATION, false, HasBit(_display_opt, DO_FULL_ANIMATION)));
list->push_back(new DropDownListCheckedItem(STR_02D2_FULL_DETAIL, OME_FULL_DETAILS, false, HasBit(_display_opt, DO_FULL_DETAIL)));
list->push_back(new DropDownListCheckedItem(STR_02D4_TRANSPARENT_BUILDINGS, OME_TRANSPARENTBUILDINGS, false, IsTransparencySet(TO_HOUSES)));
list->push_back(new DropDownListCheckedItem(STR_TRANSPARENT_SIGNS, OME_SHOW_STATIONSIGNS, false, IsTransparencySet(TO_SIGNS)));
ShowDropDownList(w, list, 0, TBN_SETTINGS, 140, true, true);
SndPlayFx(SND_15_BEEP);
}
static void MenuClickSettings(int index)
{
switch (index) {
case OME_GAMEOPTIONS: ShowGameOptions(); return;
case OME_DIFFICULTIES: ShowGameDifficulty(); return;
case OME_SETTINGS: ShowGameSettings(); return;
case OME_NEWGRFSETTINGS: ShowNewGRFSettings(!_networking, true, true, &_grfconfig); return;
case OME_TRANSPARENCIES: ShowTransparencyToolbar(); break;
case OME_SHOW_TOWNNAMES: ToggleBit(_display_opt, DO_SHOW_TOWN_NAMES); break;
case OME_SHOW_STATIONNAMES: ToggleBit(_display_opt, DO_SHOW_STATION_NAMES); break;
case OME_SHOW_SIGNS: ToggleBit(_display_opt, DO_SHOW_SIGNS); break;
case OME_SHOW_WAYPOINTNAMES: ToggleBit(_display_opt, DO_WAYPOINTS); break;
case OME_FULL_ANIMATION: ToggleBit(_display_opt, DO_FULL_ANIMATION); break;
case OME_FULL_DETAILS: ToggleBit(_display_opt, DO_FULL_DETAIL); break;
case OME_TRANSPARENTBUILDINGS: ToggleTransparency(TO_HOUSES); break;
case OME_SHOW_STATIONSIGNS: ToggleTransparency(TO_SIGNS); break;
}
MarkWholeScreenDirty();
}
/* --- Saving/loading button menu --- */
enum SaveLoadEditorMenuEntries {
SLEME_SAVE_SCENARIO = 0,
SLEME_LOAD_SCENARIO,
SLEME_LOAD_HEIGHTMAP,
SLEME_EXIT_TOINTRO,
SLEME_EXIT_GAME = 5,
SLEME_MENUCOUNT,
};
enum SaveLoadNormalMenuEntries {
SLNME_SAVE_GAME = 0,
SLNME_LOAD_GAME,
SLNME_EXIT_TOINTRO,
SLNME_EXIT_GAME,
SLNME_MENUCOUNT,
};
static void ToolbarSaveClick(Window *w)
{
PopupMainToolbMenu(w, TBN_SAVEGAME, STR_015C_SAVE_GAME, SLNME_MENUCOUNT);
}
static void ToolbarScenSaveOrLoad(Window *w)
{
PopupMainToolbMenu(w, TBSE_SAVESCENARIO, STR_0292_SAVE_SCENARIO, SLEME_MENUCOUNT);
}
static void MenuClickSaveLoad(int index = 0)
{
if (_game_mode == GM_EDITOR) {
switch (index) {
case SLEME_SAVE_SCENARIO: ShowSaveLoadDialog(SLD_SAVE_SCENARIO); break;
case SLEME_LOAD_SCENARIO: ShowSaveLoadDialog(SLD_LOAD_SCENARIO); break;
case SLEME_LOAD_HEIGHTMAP: ShowSaveLoadDialog(SLD_LOAD_HEIGHTMAP); break;
case SLEME_EXIT_TOINTRO: AskExitToGameMenu(); break;
case SLEME_EXIT_GAME: HandleExitGameRequest(); break;
}
} else {
switch (index) {
case SLNME_SAVE_GAME: ShowSaveLoadDialog(SLD_SAVE_GAME); break;
case SLNME_LOAD_GAME: ShowSaveLoadDialog(SLD_LOAD_GAME); break;
case SLNME_EXIT_TOINTRO: AskExitToGameMenu(); break;
case SLNME_EXIT_GAME: HandleExitGameRequest(); break;
}
}
}
/* --- Map button menu --- */
enum MapMenuEntries {
MME_SHOW_SMALLMAP = 0,
MME_SHOW_EXTRAVIEWPORTS,
MME_SHOW_SIGNLISTS,
MME_SHOW_TOWNDIRECTORY, ///< This entry is only used in Editor mode
MME_MENUCOUNT_NORMAL = 3,
MME_MENUCOUNT_EDITOR = 4,
};
static void ToolbarMapClick(Window *w)
{
PopupMainToolbMenu(w, TBN_SMALLMAP, STR_02DE_MAP_OF_WORLD, MME_MENUCOUNT_NORMAL);
}
static void ToolbarScenMapTownDir(Window *w)
{
PopupMainToolbMenu(w, TBSE_SMALLMAP, STR_02DE_MAP_OF_WORLD, MME_MENUCOUNT_EDITOR);
}
static void MenuClickMap(int index)
{
switch (index) {
case MME_SHOW_SMALLMAP: ShowSmallMap(); break;
case MME_SHOW_EXTRAVIEWPORTS: ShowExtraViewPortWindow(); break;
case MME_SHOW_SIGNLISTS: ShowSignList(); break;
case MME_SHOW_TOWNDIRECTORY: if (_game_mode == GM_EDITOR) ShowTownDirectory(); break;
}
}
/* --- Town button menu --- */
static void ToolbarTownClick(Window *w)
{
PopupMainToolbMenu(w, TBN_TOWNDIRECTORY, STR_02BB_TOWN_DIRECTORY, 1);
}
static void MenuClickTown(int index)
{
ShowTownDirectory();
}
/* --- Subidies button menu --- */
static void ToolbarSubsidiesClick(Window *w)
{
PopupMainToolbMenu(w, TBN_SUBSIDIES, STR_02DD_SUBSIDIES, 1);
}
static void MenuClickSubsidies(int index)
{
ShowSubsidiesList();
}
/* --- Stations button menu --- */
static void ToolbarStationsClick(Window *w)
{
PopupMainCompanyToolbMenu(w, TBN_STATIONS);
}
static void MenuClickStations(int index)
{
ShowCompanyStations((CompanyID)index);
}
/* --- Finances button menu --- */
static void ToolbarFinancesClick(Window *w)
{
PopupMainCompanyToolbMenu(w, TBN_FINANCES);
}
static void MenuClickFinances(int index)
{
ShowCompanyFinances((CompanyID)index);
}
/* --- Company's button menu --- */
static void ToolbarCompaniesClick(Window *w)
{
PopupMainCompanyToolbMenu(w, TBN_COMPANIES);
}
static void MenuClickCompany(int index)
{
#ifdef ENABLE_NETWORK
if (_networking) {
switch (index) {
case CTMN_CLIENT_LIST:
ShowClientList();
return;
case CTMN_NEW_COMPANY:
if (_network_server) {
DoCommandP(0, 0, _network_own_client_id, CMD_COMPANY_CTRL);
} else {
NetworkSend_Command(0, 0, 0, CMD_COMPANY_CTRL, NULL, NULL);
}
return;
case CTMN_SPECTATE:
if (_network_server) {
NetworkServerDoMove(CLIENT_ID_SERVER, COMPANY_SPECTATOR);
MarkWholeScreenDirty();
} else {
NetworkClientRequestMove(COMPANY_SPECTATOR);
}
return;
}
}
#endif /* ENABLE_NETWORK */
ShowCompany((CompanyID)index);
}
/* --- Graphs button menu --- */
static void ToolbarGraphsClick(Window *w)
{
PopupMainToolbMenu(w, TBN_GRAPHICS, STR_0154_OPERATING_PROFIT_GRAPH, (_toolbar_mode == TB_NORMAL) ? 6 : 8);
}
static void MenuClickGraphs(int index)
{
switch (index) {
case 0: ShowOperatingProfitGraph(); break;
case 1: ShowIncomeGraph(); break;
case 2: ShowDeliveredCargoGraph(); break;
case 3: ShowPerformanceHistoryGraph(); break;
case 4: ShowCompanyValueGraph(); break;
case 5: ShowCargoPaymentRates(); break;
/* functions for combined graphs/league button */
case 6: ShowCompanyLeagueTable(); break;
case 7: ShowPerformanceRatingDetail(); break;
}
}
/* --- League button menu --- */
static void ToolbarLeagueClick(Window *w)
{
PopupMainToolbMenu(w, TBN_LEAGUE, STR_015A_COMPANY_LEAGUE_TABLE, 2);
}
static void MenuClickLeague(int index)
{
switch (index) {
case 0: ShowCompanyLeagueTable(); break;
case 1: ShowPerformanceRatingDetail(); break;
}
}
/* --- Industries button menu --- */
static void ToolbarIndustryClick(Window *w)
{
/* Disable build-industry menu if we are a spectator */
PopupMainToolbMenu(w, TBN_INDUSTRIES, STR_INDUSTRY_DIR, (_local_company == COMPANY_SPECTATOR) ? 1 : 2);
}
static void MenuClickIndustry(int index)
{
switch (index) {
case 0: ShowIndustryDirectory(); break;
case 1: ShowBuildIndustryWindow(); break;
}
}
/* --- Trains button menu + 1 helper function for all vehicles. --- */
static void ToolbarVehicleClick(Window *w, VehicleType veh)
{
const Vehicle *v;
int dis = ~0;
FOR_ALL_VEHICLES(v) {
if (v->type == veh && v->IsPrimaryVehicle()) ClrBit(dis, v->owner);
}
PopupMainCompanyToolbMenu(w, TBN_VEHICLESTART + veh, dis);
}
static void ToolbarTrainClick(Window *w)
{
ToolbarVehicleClick(w, VEH_TRAIN);
}
static void MenuClickShowTrains(int index)
{
ShowVehicleListWindow((CompanyID)index, VEH_TRAIN);
}
/* --- Road vehicle button menu --- */
static void ToolbarRoadClick(Window *w)
{
ToolbarVehicleClick(w, VEH_ROAD);
}
static void MenuClickShowRoad(int index)
{
ShowVehicleListWindow((CompanyID)index, VEH_ROAD);
}
/* --- Ship button menu --- */
static void ToolbarShipClick(Window *w)
{
ToolbarVehicleClick(w, VEH_SHIP);
}
static void MenuClickShowShips(int index)
{
ShowVehicleListWindow((CompanyID)index, VEH_SHIP);
}
/* --- Aircraft button menu --- */
static void ToolbarAirClick(Window *w)
{
ToolbarVehicleClick(w, VEH_AIRCRAFT);
}
static void MenuClickShowAir(int index)
{
ShowVehicleListWindow((CompanyID)index, VEH_AIRCRAFT);
}
/* --- Zoom in button --- */
static void ToolbarZoomInClick(Window *w)
{
if (DoZoomInOutWindow(ZOOM_IN, FindWindowById(WC_MAIN_WINDOW, 0))) {
w->HandleButtonClick((_game_mode == GM_EDITOR) ? (byte)TBSE_ZOOMIN : (byte)TBN_ZOOMIN);
SndPlayFx(SND_15_BEEP);
}
}
/* --- Zoom out button --- */
static void ToolbarZoomOutClick(Window *w)
{
if (DoZoomInOutWindow(ZOOM_OUT, FindWindowById(WC_MAIN_WINDOW, 0))) {
w->HandleButtonClick((_game_mode == GM_EDITOR) ? (byte)TBSE_ZOOMOUT : (byte)TBN_ZOOMOUT);
SndPlayFx(SND_15_BEEP);
}
}
/* --- Rail button menu --- */
static void ToolbarBuildRailClick(Window *w)
{
const Company *c = GetCompany(_local_company);
DropDownList *list = new DropDownList();
for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
const RailtypeInfo *rti = GetRailTypeInfo(rt);
/* Skip rail type if it has no label */
if (rti->label == 0) continue;
list->push_back(new DropDownListStringItem(rti->strings.menu_text, rt, !HasBit(c->avail_railtypes, rt)));
}
ShowDropDownList(w, list, _last_built_railtype, TBN_RAILS, 140, true, true);
SndPlayFx(SND_15_BEEP);
}
static void MenuClickBuildRail(int index)
{
_last_built_railtype = (RailType)index;
ShowBuildRailToolbar(_last_built_railtype, -1);
}
/* --- Road button menu --- */
static void ToolbarBuildRoadClick(Window *w)
{
const Company *c = GetCompany(_local_company);
DropDownList *list = new DropDownList();
for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
/* The standard road button is *always* available */
list->push_back(new DropDownListStringItem(STR_180A_ROAD_CONSTRUCTION + rt, rt, !(HasBit(c->avail_roadtypes, rt) || rt == ROADTYPE_ROAD)));
}
ShowDropDownList(w, list, _last_built_roadtype, TBN_ROADS, 140, true, true);
SndPlayFx(SND_15_BEEP);
}
static void MenuClickBuildRoad(int index)
{
_last_built_roadtype = (RoadType)index;
ShowBuildRoadToolbar(_last_built_roadtype);
}
/* --- Water button menu --- */
static void ToolbarBuildWaterClick(Window *w)
{
PopupMainToolbMenu(w, TBN_WATER, STR_9800_WATERWAYS_CONSTRUCTION, 1);
}
static void MenuClickBuildWater(int index)
{
ShowBuildDocksToolbar();
}
/* --- Airport button menu --- */
static void ToolbarBuildAirClick(Window *w)
{
PopupMainToolbMenu(w, TBN_AIR, STR_A01D_AIRPORT_CONSTRUCTION, 1);
}
static void MenuClickBuildAir(int index)
{
ShowBuildAirToolbar();
}
/* --- Forest button menu --- */
static void ToolbarForestClick(Window *w)
{
PopupMainToolbMenu(w, TBN_LANDSCAPE, STR_LANDSCAPING, 3);
}
static void MenuClickForest(int index)
{
switch (index) {
case 0: ShowTerraformToolbar(); break;
case 1: ShowBuildTreesToolbar(); break;
case 2: SelectSignTool(); break;
}
}
/* --- Music button menu --- */
static void ToolbarMusicClick(Window *w)
{
PopupMainToolbMenu(w, TBN_MUSICSOUND, STR_01D3_SOUND_MUSIC, 1);
}
static void MenuClickMusicWindow(int index)
{
ShowMusicWindow();
}
/* --- Newspaper button menu --- */
static void ToolbarNewspaperClick(Window *w)
{
PopupMainToolbMenu(w, TBN_NEWSREPORT, STR_0200_LAST_MESSAGE_NEWS_REPORT, 3);
}
static void MenuClickNewspaper(int index)
{
switch (index) {
case 0: ShowLastNewsMessage(); break;
case 1: ShowMessageOptions(); break;
case 2: ShowMessageHistory(); break;
}
}
/* --- Help button menu --- */
static void ToolbarHelpClick(Window *w)
{
PopupMainToolbMenu(w, TBN_HELP, STR_02D5_LAND_BLOCK_INFO, 7);
}
static void MenuClickSmallScreenshot()
{
SetScreenshotType(SC_VIEWPORT);
}
static void MenuClickWorldScreenshot()
{
SetScreenshotType(SC_WORLD);
}
static void MenuClickHelp(int index)
{
switch (index) {
case 0: PlaceLandBlockInfo(); break;
case 2: IConsoleSwitch(); break;
case 3: ShowAIDebugWindow(); break;
case 4: MenuClickSmallScreenshot(); break;
case 5: MenuClickWorldScreenshot(); break;
case 6: ShowAboutWindow(); break;
}
}
/* --- Switch toolbar button --- */
static void ToolbarSwitchClick(Window *w)
{
if (_toolbar_mode != TB_LOWER) {
_toolbar_mode = TB_LOWER;
} else {
_toolbar_mode = TB_UPPER;
}
SplitToolbar(w);
w->HandleButtonClick(TBN_SWITCHBAR);
SetWindowDirty(w);
SndPlayFx(SND_15_BEEP);
}
/* --- Scenario editor specific handlers. */
static void ToolbarScenDateBackward(Window *w)
{
/* don't allow too fast scrolling */
if ((w->flags4 & WF_TIMEOUT_MASK) <= WF_TIMEOUT_TRIGGER) {
w->HandleButtonClick(TBSE_DATEBACKWARD);
w->SetDirty();
_settings_newgame.game_creation.starting_year = Clamp(_settings_newgame.game_creation.starting_year - 1, MIN_YEAR, MAX_YEAR);
SetDate(ConvertYMDToDate(_settings_newgame.game_creation.starting_year, 0, 1));
}
_left_button_clicked = false;
}
static void ToolbarScenDateForward(Window *w)
{
/* don't allow too fast scrolling */
if ((w->flags4 & WF_TIMEOUT_MASK) <= WF_TIMEOUT_TRIGGER) {
w->HandleButtonClick(TBSE_DATEFORWARD);
w->SetDirty();
_settings_newgame.game_creation.starting_year = Clamp(_settings_newgame.game_creation.starting_year + 1, MIN_YEAR, MAX_YEAR);
SetDate(ConvertYMDToDate(_settings_newgame.game_creation.starting_year, 0, 1));
}
_left_button_clicked = false;
}
static void ToolbarScenGenLand(Window *w)
{
w->HandleButtonClick(TBSE_LANDGENERATE);
SndPlayFx(SND_15_BEEP);
ShowEditorTerraformToolbar();
}
static void ToolbarScenGenTown(Window *w)
{
w->HandleButtonClick(TBSE_TOWNGENERATE);
SndPlayFx(SND_15_BEEP);
ShowBuildTownWindow();
}
static void ToolbarScenGenIndustry(Window *w)
{
w->HandleButtonClick(TBSE_INDUSTRYGENERATE);
SndPlayFx(SND_15_BEEP);
ShowBuildIndustryWindow();
}
static void ToolbarScenBuildRoad(Window *w)
{
w->HandleButtonClick(TBSE_BUILDROAD);
SndPlayFx(SND_15_BEEP);
ShowBuildRoadScenToolbar();
}
static void ToolbarScenBuildDocks(Window *w)
{
w->HandleButtonClick(TBSE_BUILDDOCKS);
SndPlayFx(SND_15_BEEP);
ShowBuildDocksScenToolbar();
}
static void ToolbarScenPlantTrees(Window *w)
{
w->HandleButtonClick(TBSE_PLANTTREES);
SndPlayFx(SND_15_BEEP);
ShowBuildTreesToolbar();
}
static void ToolbarScenPlaceSign(Window *w)
{
w->HandleButtonClick(TBSE_PLACESIGNS);
SndPlayFx(SND_15_BEEP);
SelectSignTool();
}
static void ToolbarBtn_NULL(Window *w)
{
}
/* --- Resizing the toolbar */
static void ResizeToolbar(Window *w)
{
/* There are 27 buttons plus some spacings if the space allows it */
uint button_width;
uint spacing;
uint widgetcount = w->widget_count - 1;
if (w->width >= (int)widgetcount * TBP_BUTTONWIDTH) {
button_width = TBP_BUTTONWIDTH;
spacing = w->width - (widgetcount * button_width);
} else {
button_width = w->width / widgetcount;
spacing = 0;
}
static const uint extra_spacing_at[] = { 4, 8, 13, 17, 19, 24, 0 };
uint i = 0;
for (uint x = 0, j = 0; i < widgetcount; i++) {
if (extra_spacing_at[j] == i) {
j++;
uint add = spacing / (lengthof(extra_spacing_at) - j);
spacing -= add;
x += add;
}
w->widget[i].type = WWT_IMGBTN;
w->widget[i].left = x;
x += (spacing != 0) ? button_width : (w->width - x) / (widgetcount - i);
w->widget[i].right = x - 1;
}
w->widget[i].type = WWT_EMPTY; // i now points to the last item
_toolbar_mode = TB_NORMAL;
}
/* --- Split the toolbar */
static void SplitToolbar(Window *w)
{
static const byte arrange14[] = {
0, 1, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 27,
2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 24, 25, 26, 27,
};
static const byte arrange15[] = {
0, 1, 4, 13, 14, 15, 16, 19, 20, 21, 22, 23, 17, 18, 27,
0, 2, 4, 3, 5, 6, 7, 8, 9, 10, 12, 24, 25, 26, 27,
};
static const byte arrange16[] = {
0, 1, 2, 4, 13, 14, 15, 16, 19, 20, 21, 22, 23, 17, 18, 27,
0, 1, 3, 5, 6, 7, 8, 9, 10, 12, 24, 25, 26, 17, 18, 27,
};
static const byte arrange17[] = {
0, 1, 2, 4, 6, 13, 14, 15, 16, 19, 20, 21, 22, 23, 17, 18, 27,
0, 1, 3, 4, 6, 5, 7, 8, 9, 10, 12, 24, 25, 26, 17, 18, 27,
};
static const byte arrange18[] = {
0, 1, 2, 4, 5, 6, 7, 8, 9, 12, 19, 20, 21, 22, 23, 17, 18, 27,
0, 1, 3, 4, 5, 6, 7, 10, 13, 14, 15, 16, 24, 25, 26, 17, 18, 27,
};
static const byte arrange19[] = {
0, 1, 2, 4, 5, 6, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 17, 18, 27,
0, 1, 3, 4, 7, 8, 9, 10, 12, 25, 19, 20, 21, 22, 23, 26, 17, 18, 27,
};
static const byte *arrangements[] = { arrange14, arrange15, arrange16, arrange17, arrange18, arrange19 };
uint max_icons = max(TBP_TOOLBAR_MINBUTTON, (ToolBarProperties)((w->width + TBP_BUTTONWIDTH / 2) / TBP_BUTTONWIDTH));
assert(max_icons >= TBP_TOOLBAR_MINBUTTON && max_icons <= TBP_NORMAL_MAXBUTTON);
/* first hide all icons */
for (uint i = 0; i < w->widget_count - 1; i++) {
w->widget[i].type = WWT_EMPTY;
}
/* now activate them all on their proper positions */
for (uint i = 0, x = 0, n = max_icons - TBP_TOOLBAR_MINBUTTON; i < max_icons; i++) {
uint icon = arrangements[n][i + ((_toolbar_mode == TB_LOWER) ? max_icons : 0)];
w->widget[icon].type = WWT_IMGBTN;
w->widget[icon].left = x;
x += (w->width - x) / (max_icons - i);
w->widget[icon].right = x - 1;
}
}
typedef void MenuClickedProc(int index);
static MenuClickedProc * const _menu_clicked_procs[] = {
NULL, // 0
NULL, // 1
MenuClickSettings, // 2
MenuClickSaveLoad, // 3
MenuClickMap, // 4
MenuClickTown, // 5
MenuClickSubsidies, // 6
MenuClickStations, // 7
MenuClickFinances, // 8
MenuClickCompany, // 9
MenuClickGraphs, // 10
MenuClickLeague, // 11
MenuClickIndustry, // 12
MenuClickShowTrains, // 13
MenuClickShowRoad, // 14
MenuClickShowShips, // 15
MenuClickShowAir, // 16
MenuClickMap, // 17
NULL, // 18
MenuClickBuildRail, // 19
MenuClickBuildRoad, // 20
MenuClickBuildWater, // 21
MenuClickBuildAir, // 22
MenuClickForest, // 23
MenuClickMusicWindow, // 24
MenuClickNewspaper, // 25
MenuClickHelp, // 26
};
/* --- Toolbar handling for the 'normal' case */
typedef void ToolbarButtonProc(Window *w);
static ToolbarButtonProc * const _toolbar_button_procs[] = {
ToolbarPauseClick,
ToolbarFastForwardClick,
ToolbarOptionsClick,
ToolbarSaveClick,
ToolbarMapClick,
ToolbarTownClick,
ToolbarSubsidiesClick,
ToolbarStationsClick,
ToolbarFinancesClick,
ToolbarCompaniesClick,
ToolbarGraphsClick,
ToolbarLeagueClick,
ToolbarIndustryClick,
ToolbarTrainClick,
ToolbarRoadClick,
ToolbarShipClick,
ToolbarAirClick,
ToolbarZoomInClick,
ToolbarZoomOutClick,
ToolbarBuildRailClick,
ToolbarBuildRoadClick,
ToolbarBuildWaterClick,
ToolbarBuildAirClick,
ToolbarForestClick,
ToolbarMusicClick,
ToolbarNewspaperClick,
ToolbarHelpClick,
ToolbarSwitchClick,
};
struct MainToolbarWindow : Window {
MainToolbarWindow(const WindowDesc *desc) : Window(desc)
{
this->SetWidgetDisabledState(TBN_PAUSE, _networking && !_network_server); // if not server, disable pause button
this->SetWidgetDisabledState(TBN_FASTFORWARD, _networking); // if networking, disable fast-forward button
CLRBITS(this->flags4, WF_WHITE_BORDER_MASK);
this->FindWindowPlacementAndResize(desc);
PositionMainToolbar(this);
DoZoomInOutWindow(ZOOM_NONE, this);
}
virtual void OnPaint()
{
/* Draw brown-red toolbar bg. */
GfxFillRect(0, 0, this->width - 1, this->height - 1, 0xB2);
GfxFillRect(0, 0, this->width - 1, this->height - 1, 0xB4, FILLRECT_CHECKER);
/* If spectator, disable all construction buttons
* ie : Build road, rail, ships, airports and landscaping
* Since enabled state is the default, just disable when needed */
this->SetWidgetsDisabledState(_local_company == COMPANY_SPECTATOR, TBN_RAILS, TBN_ROADS, TBN_WATER, TBN_AIR, TBN_LANDSCAPE, WIDGET_LIST_END);
/* disable company list drop downs, if there are no companies */
this->SetWidgetsDisabledState(ActiveCompanyCount() == TBN_PAUSE, TBN_STATIONS, TBN_FINANCES, TBN_TRAINS, TBN_ROADVEHS, TBN_SHIPS, TBN_AIRCRAFTS, WIDGET_LIST_END);
this->SetWidgetDisabledState(TBN_RAILS, !CanBuildVehicleInfrastructure(VEH_TRAIN));
this->SetWidgetDisabledState(TBN_AIR, !CanBuildVehicleInfrastructure(VEH_AIRCRAFT));
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
if (_game_mode != GM_MENU && !this->IsWidgetDisabled(widget)) _toolbar_button_procs[widget](this);
}
virtual void OnDropdownSelect(int widget, int index)
{
_menu_clicked_procs[widget](index);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
switch (keycode) {
case WKC_F1: case WKC_PAUSE: ToolbarPauseClick(this); break;
case WKC_F2: ShowGameOptions(); break;
case WKC_F3: MenuClickSaveLoad(); break;
case WKC_F4: ShowSmallMap(); break;
case WKC_F5: ShowTownDirectory(); break;
case WKC_F6: ShowSubsidiesList(); break;
case WKC_F7: ShowCompanyStations(_local_company); break;
case WKC_F8: ShowCompanyFinances(_local_company); break;
case WKC_F9: ShowCompany(_local_company); break;
case WKC_F10: ShowOperatingProfitGraph(); break;
case WKC_F11: ShowCompanyLeagueTable(); break;
case WKC_F12: ShowBuildIndustryWindow(); break;
case WKC_SHIFT | WKC_F1: ShowVehicleListWindow(_local_company, VEH_TRAIN); break;
case WKC_SHIFT | WKC_F2: ShowVehicleListWindow(_local_company, VEH_ROAD); break;
case WKC_SHIFT | WKC_F3: ShowVehicleListWindow(_local_company, VEH_SHIP); break;
case WKC_SHIFT | WKC_F4: ShowVehicleListWindow(_local_company, VEH_AIRCRAFT); break;
case WKC_NUM_PLUS: // Fall through
case WKC_EQUALS: // Fall through
case WKC_SHIFT | WKC_EQUALS: // Fall through
case WKC_SHIFT | WKC_F5: ToolbarZoomInClick(this); break;
case WKC_NUM_MINUS: // Fall through
case WKC_MINUS: // Fall through
case WKC_SHIFT | WKC_MINUS: // Fall through
case WKC_SHIFT | WKC_F6: ToolbarZoomOutClick(this); break;
case WKC_SHIFT | WKC_F7: if (CanBuildVehicleInfrastructure(VEH_TRAIN)) ShowBuildRailToolbar(_last_built_railtype, -1); break;
case WKC_SHIFT | WKC_F8: ShowBuildRoadToolbar(_last_built_roadtype); break;
case WKC_SHIFT | WKC_F9: ShowBuildDocksToolbar(); break;
case WKC_SHIFT | WKC_F10: if (CanBuildVehicleInfrastructure(VEH_AIRCRAFT)) ShowBuildAirToolbar(); break;
case WKC_SHIFT | WKC_F11: ShowBuildTreesToolbar(); break;
case WKC_SHIFT | WKC_F12: ShowMusicWindow(); break;
case WKC_CTRL | 'S': MenuClickSmallScreenshot(); break;
case WKC_CTRL | 'G': MenuClickWorldScreenshot(); break;
case WKC_CTRL | WKC_ALT | 'C': if (!_networking) ShowCheatWindow(); break;
case 'A': if (CanBuildVehicleInfrastructure(VEH_TRAIN)) ShowBuildRailToolbar(_last_built_railtype, 4); break; // Invoke Autorail
case 'L': ShowTerraformToolbar(); break;
case 'M': ShowSmallMap(); break;
case 'V': ShowExtraViewPortWindow(); break;
default: return ES_NOT_HANDLED;
}
return ES_HANDLED;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_place_proc(tile);
}
virtual void OnTick()
{
if (this->IsWidgetLowered(TBN_PAUSE) != !!_pause_game) {
this->ToggleWidgetLoweredState(TBN_PAUSE);
this->InvalidateWidget(TBN_PAUSE);
}
if (this->IsWidgetLowered(TBN_FASTFORWARD) != !!_fast_forward) {
this->ToggleWidgetLoweredState(TBN_FASTFORWARD);
this->InvalidateWidget(TBN_FASTFORWARD);
}
}
virtual void OnResize(Point new_size, Point delta)
{
if (this->width <= TBP_NORMAL_MAXBUTTON * TBP_BUTTONWIDTH) {
SplitToolbar(this);
} else {
ResizeToolbar(this);
}
}
virtual void OnTimeout()
{
for (uint i = TBN_SETTINGS; i < this->widget_count - 1; i++) {
if (this->IsWidgetLowered(i)) {
this->RaiseWidget(i);
this->InvalidateWidget(i);
}
}
}
virtual void OnInvalidateData(int data)
{
if (FindWindowById(WC_MAIN_WINDOW, 0) != NULL) HandleZoomMessage(this, FindWindowById(WC_MAIN_WINDOW, 0)->viewport, TBN_ZOOMIN, TBN_ZOOMOUT);
}
};
static const Widget _toolb_normal_widgets[] = {
{ WWT_IMGBTN, RESIZE_LEFT, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_PAUSE, STR_0171_PAUSE_GAME}, // TBN_PAUSE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_FASTFORWARD, STR_FAST_FORWARD}, // TBN_FASTFORWARD
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SETTINGS, STR_0187_OPTIONS}, // TBN_SETTINGS
{ WWT_IMGBTN_2, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SAVE, STR_0172_SAVE_GAME_ABANDON_GAME}, // TBN_SAVEGAME
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SMALLMAP, STR_0174_DISPLAY_MAP}, // TBN_SMALLMAP
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_TOWN, STR_0176_DISPLAY_TOWN_DIRECTORY}, // TBN_TOWNDIRECTORY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SUBSIDIES, STR_02DC_DISPLAY_SUBSIDIES}, // TBN_SUBSIDIES
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_COMPANY_LIST, STR_0173_DISPLAY_LIST_OF_COMPANY}, // TBN_STATIONS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_COMPANY_FINANCE, STR_0177_DISPLAY_COMPANY_FINANCES}, // TBN_FINANCES
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_COMPANY_GENERAL, STR_0178_DISPLAY_COMPANY_GENERAL}, // TBN_COMPANIES
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_GRAPHS, STR_0179_DISPLAY_GRAPHS}, // TBN_GRAPHICS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_COMPANY_LEAGUE, STR_017A_DISPLAY_COMPANY_LEAGUE}, // TBN_LEAGUE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_INDUSTRY, STR_0312_FUND_CONSTRUCTION_OF_NEW}, // TBN_INDUSTRIES
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_TRAINLIST, STR_017B_DISPLAY_LIST_OF_COMPANY}, // TBN_TRAINS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_TRUCKLIST, STR_017C_DISPLAY_LIST_OF_COMPANY}, // TBN_ROADVEHS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SHIPLIST, STR_017D_DISPLAY_LIST_OF_COMPANY}, // TBN_SHIPS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_AIRPLANESLIST, STR_017E_DISPLAY_LIST_OF_COMPANY}, // TBN_AIRCRAFTS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_ZOOMIN, STR_017F_ZOOM_THE_VIEW_IN}, // TBN_ZOOMIN
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_ZOOMOUT, STR_0180_ZOOM_THE_VIEW_OUT}, // TBN_ZOOMOUT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_BUILDRAIL, STR_0181_BUILD_RAILROAD_TRACK}, // TBN_RAILS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_BUILDROAD, STR_0182_BUILD_ROADS}, // TBN_ROADS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_BUILDWATER, STR_0183_BUILD_SHIP_DOCKS}, // TBN_WATER
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_BUILDAIR, STR_0184_BUILD_AIRPORTS}, // TBN_AIR
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_LANDSCAPING, STR_LANDSCAPING_TOOLBAR_TIP}, // TBN_LANDSCAPE tree icon is SPR_IMG_PLANTTREES
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_MUSIC, STR_01D4_SHOW_SOUND_MUSIC_WINDOW}, // TBN_MUSICSOUND
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_MESSAGES, STR_0203_SHOW_LAST_MESSAGE_NEWS}, // TBN_NEWSREPORT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_QUERY, STR_0186_LAND_BLOCK_INFORMATION}, // TBN_HELP
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_SWITCH_TOOLBAR, STR_EMPTY}, // TBN_SWITCHBAR
{ WIDGETS_END},
};
static const WindowDesc _toolb_normal_desc(
0, 0, 0, TBP_BUTTONHEIGHT, 640, TBP_BUTTONHEIGHT,
WC_MAIN_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_NO_FOCUS,
_toolb_normal_widgets
);
/* --- Toolbar handling for the scenario editor */
static ToolbarButtonProc * const _scen_toolbar_button_procs[] = {
ToolbarPauseClick,
ToolbarFastForwardClick,
ToolbarOptionsClick,
ToolbarScenSaveOrLoad,
ToolbarBtn_NULL,
ToolbarBtn_NULL,
ToolbarScenDateBackward,
ToolbarScenDateForward,
ToolbarScenMapTownDir,
ToolbarZoomInClick,
ToolbarZoomOutClick,
ToolbarScenGenLand,
ToolbarScenGenTown,
ToolbarScenGenIndustry,
ToolbarScenBuildRoad,
ToolbarScenBuildDocks,
ToolbarScenPlantTrees,
ToolbarScenPlaceSign,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
ToolbarMusicClick,
NULL,
ToolbarHelpClick,
};
struct ScenarioEditorToolbarWindow : Window {
public:
ScenarioEditorToolbarWindow(const WindowDesc *desc) : Window(desc)
{
CLRBITS(this->flags4, WF_WHITE_BORDER_MASK);
this->FindWindowPlacementAndResize(desc);
PositionMainToolbar(this);
DoZoomInOutWindow(ZOOM_NONE, this);
}
virtual void OnPaint()
{
this->SetWidgetDisabledState(TBSE_DATEBACKWARD, _settings_newgame.game_creation.starting_year <= MIN_YEAR);
this->SetWidgetDisabledState(TBSE_DATEFORWARD, _settings_newgame.game_creation.starting_year >= MAX_YEAR);
/* Draw brown-red toolbar bg. */
GfxFillRect(0, 0, this->width - 1, this->height - 1, 0xB2);
GfxFillRect(0, 0, this->width - 1, this->height - 1, 0xB4, FILLRECT_CHECKER);
this->DrawWidgets();
SetDParam(0, ConvertYMDToDate(_settings_newgame.game_creation.starting_year, 0, 1));
DrawStringCenteredTruncated(this->widget[TBSE_DATEBACKWARD].right, this->widget[TBSE_DATEFORWARD].left, 6, STR_00AF, TC_FROMSTRING);
/* We hide this panel when the toolbar space gets too small */
const Widget *panel = &this->widget[TBSE_SPACERPANEL];
if (panel->left != panel->right) {
DrawStringCenteredTruncated(panel->left + 1, panel->right - 1, 1, STR_0221_OPENTTD, TC_FROMSTRING);
DrawStringCenteredTruncated(panel->left + 1, panel->right - 1, 11, STR_0222_SCENARIO_EDITOR, TC_FROMSTRING);
}
}
virtual void OnClick(Point pt, int widget)
{
if (_game_mode == GM_MENU) return;
_scen_toolbar_button_procs[widget](this);
}
virtual void OnDropdownSelect(int widget, int index)
{
/* The map button is in a different location on the scenario
* editor toolbar, so we need to adjust for it. */
if (widget == TBSE_SMALLMAP) widget = TBN_SMALLMAP;
_menu_clicked_procs[widget](index);
SndPlayFx(SND_15_BEEP);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
switch (keycode) {
case WKC_F1: case WKC_PAUSE: ToolbarPauseClick(this); break;
case WKC_F2: ShowGameOptions(); break;
case WKC_F3: MenuClickSaveLoad(); break;
case WKC_F4: ToolbarScenGenLand(this); break;
case WKC_F5: ToolbarScenGenTown(this); break;
case WKC_F6: ToolbarScenGenIndustry(this); break;
case WKC_F7: ToolbarScenBuildRoad(this); break;
case WKC_F8: ToolbarScenBuildDocks(this); break;
case WKC_F9: ToolbarScenPlantTrees(this); break;
case WKC_F10: ToolbarScenPlaceSign(this); break;
case WKC_F11: ShowMusicWindow(); break;
case WKC_F12: PlaceLandBlockInfo(); break;
case WKC_CTRL | 'S': MenuClickSmallScreenshot(); break;
case WKC_CTRL | 'G': MenuClickWorldScreenshot(); break;
/* those following are all fall through */
case WKC_NUM_PLUS:
case WKC_EQUALS:
case WKC_SHIFT | WKC_EQUALS:
case WKC_SHIFT | WKC_F5: ToolbarZoomInClick(this); break;
/* those following are all fall through */
case WKC_NUM_MINUS:
case WKC_MINUS:
case WKC_SHIFT | WKC_MINUS:
case WKC_SHIFT | WKC_F6: ToolbarZoomOutClick(this); break;
case 'L': ShowEditorTerraformToolbar(); break;
case 'M': ShowSmallMap(); break;
case 'V': ShowExtraViewPortWindow(); break;
default: return ES_NOT_HANDLED;
}
return ES_HANDLED;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_place_proc(tile);
}
virtual void OnResize(Point new_size, Point delta)
{
/* There are 16 buttons plus some spacings if the space allows it.
* Furthermore there are two panels of which one is non - essential
* and that one can be removed if the space is too small. */
uint buttons_width;
uint spacing;
static const int normal_min_width = (TBP_SCENARIO_MAXBUTTON * TBP_BUTTONWIDTH) + (2 * TBP_DATEPANELWIDTH);
static const int one_less_panel_min_width = (TBP_SCENARIO_MAXBUTTON * TBP_BUTTONWIDTH) + TBP_DATEPANELWIDTH;
if (this->width >= one_less_panel_min_width) {
buttons_width = TBP_SCENARIO_MAXBUTTON * TBP_BUTTONWIDTH;
spacing = this->width - ((this->width >= normal_min_width) ? normal_min_width : one_less_panel_min_width);
} else {
buttons_width = this->width - TBP_DATEPANELWIDTH;
spacing = 0;
}
static const uint extra_spacing_at[] = { 3, 4, 7, 8, 10, 17, 0 };
for (uint i = 0, x = 0, j = 0, b = 0; i < this->widget_count; i++) {
switch (i) {
case TBSE_SPACERPANEL:
this->widget[i].left = x;
if (this->width < normal_min_width) {
this->widget[i].right = x;
j++;
continue;
}
x += TBP_DATEPANELWIDTH;
this->widget[i].right = x - 1;
break;
case TBSE_DATEPANEL: {
int offset = x - this->widget[i].left;
this->widget[i + 1].left += offset;
this->widget[i + 1].right += offset;
this->widget[i + 2].left += offset;
this->widget[i + 2].right += offset;
this->widget[i].left = x;
x += TBP_DATEPANELWIDTH;
this->widget[i].right = x - 1;
i += 2;
} break;
default:
if (this->widget[i].bottom == 0) continue;
this->widget[i].left = x;
x += buttons_width / (TBP_SCENARIO_MAXBUTTON - b);
this->widget[i].right = x - 1;
buttons_width -= buttons_width / (TBP_SCENARIO_MAXBUTTON - b);
b++;
break;
}
if (extra_spacing_at[j] == i) {
j++;
uint add = spacing / (lengthof(extra_spacing_at) - j);
spacing -= add;
x += add;
}
}
}
virtual void OnTick()
{
if (this->IsWidgetLowered(TBSE_PAUSE) != !!_pause_game) {
this->ToggleWidgetLoweredState(TBSE_PAUSE);
this->SetDirty();
}
if (this->IsWidgetLowered(TBSE_FASTFORWARD) != !!_fast_forward) {
this->ToggleWidgetLoweredState(TBSE_FASTFORWARD);
this->SetDirty();
}
}
virtual void OnInvalidateData(int data)
{
if (FindWindowById(WC_MAIN_WINDOW, 0) != NULL) HandleZoomMessage(this, FindWindowById(WC_MAIN_WINDOW, 0)->viewport, TBSE_ZOOMIN, TBSE_ZOOMOUT);
}
};
static const Widget _toolb_scen_widgets[] = {
{ WWT_IMGBTN, RESIZE_LEFT, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_PAUSE, STR_0171_PAUSE_GAME}, // TBSE_PAUSE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_FASTFORWARD, STR_FAST_FORWARD}, // TBSE_FASTFORWARD
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SETTINGS, STR_0187_OPTIONS},
{WWT_IMGBTN_2, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SAVE, STR_0297_SAVE_SCENARIO_LOAD_SCENARIO}, // TBSE_SAVESCENARIO
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, 0x0, STR_NULL}, // TBSE_SPACERPANEL
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 129, 0, 21, 0x0, STR_NULL}, // TBSE_DATEPANEL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 3, 14, 5, 16, SPR_ARROW_DOWN, STR_029E_MOVE_THE_STARTING_DATE}, // TBSE_DATEBACKWARD
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 113, 125, 5, 16, SPR_ARROW_UP, STR_029F_MOVE_THE_STARTING_DATE}, // TBSE_DATEFORWARD
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SMALLMAP, STR_0175_DISPLAY_MAP_TOWN_DIRECTORY}, // TBSE_SMALLMAP
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_ZOOMIN, STR_017F_ZOOM_THE_VIEW_IN}, // TBSE_ZOOMIN
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_ZOOMOUT, STR_0180_ZOOM_THE_VIEW_OUT}, // TBSE_ZOOMOUT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_LANDSCAPING, STR_022E_LANDSCAPE_GENERATION}, // TBSE_LANDGENERATE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_TOWN, STR_022F_TOWN_GENERATION}, // TBSE_TOWNGENERATE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_INDUSTRY, STR_0230_INDUSTRY_GENERATION}, // TBSE_INDUSTRYGENERATE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_BUILDROAD, STR_0231_ROAD_CONSTRUCTION}, // TBSE_BUILDROAD
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_BUILDWATER, STR_0183_BUILD_SHIP_DOCKS}, // TBSE_BUILDDOCKS
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_PLANTTREES, STR_0288_PLANT_TREES}, // TBSE_PLANTTREES
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_SIGN, STR_0289_PLACE_SIGN}, // TBSE_PLACESIGNS
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_MUSIC, STR_01D4_SHOW_SOUND_MUSIC_WINDOW},
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 21, SPR_IMG_QUERY, STR_0186_LAND_BLOCK_INFORMATION},
{WIDGETS_END},
};
static const WindowDesc _toolb_scen_desc(
0, 0, 130, TBP_BUTTONHEIGHT, 640, TBP_BUTTONHEIGHT,
WC_MAIN_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_NO_FOCUS,
_toolb_scen_widgets
);
/* --- Allocating the toolbar --- */
void AllocateToolbar()
{
/* Clean old GUI values; railtype is (re)set by rail_gui.cpp */
_last_built_roadtype = ROADTYPE_ROAD;
if (_game_mode == GM_EDITOR) {
new ScenarioEditorToolbarWindow(&_toolb_scen_desc);;
} else {
new MainToolbarWindow(&_toolb_normal_desc);
}
}
| 47,291
|
C++
|
.cpp
| 1,230
| 36.096748
| 184
| 0.688978
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,115
|
os_timer.cpp
|
EnergeticBark_OpenTTD-3DS/src/os_timer.cpp
|
/* $Id$ */
/** @file os_timer.cpp OS/compiler dependant real time tick sampling. */
#include "stdafx.h"
#undef RDTSC_AVAILABLE
/* rdtsc for MSC_VER, uses simple inline assembly, or _rdtsc
* from external win64.asm because VS2005 does not support inline assembly */
#if defined(_MSC_VER) && !defined(RDTSC_AVAILABLE) && !defined(WINCE)
#include <intrin.h>
uint64 ottd_rdtsc()
{
return __rdtsc();
}
#define RDTSC_AVAILABLE
#endif
/* rdtsc for OS/2. Hopefully this works, who knows */
#if defined (__WATCOMC__) && !defined(RDTSC_AVAILABLE)
unsigned __int64 ottd_rdtsc();
# pragma aux ottd_rdtsc = 0x0F 0x31 value [edx eax] parm nomemory modify exact [edx eax] nomemory;
# define RDTSC_AVAILABLE
#endif
/* rdtsc for all other *nix-en (hopefully). Use GCC syntax */
#if (defined(__i386__) || defined(__x86_64__)) && !defined(__DJGPP__) && !defined(RDTSC_AVAILABLE)
uint64 ottd_rdtsc()
{
uint32 high, low;
__asm__ __volatile__ ("rdtsc" : "=a" (low), "=d" (high));
return ((uint64)high << 32) | low;
}
# define RDTSC_AVAILABLE
#endif
/* rdtsc for PPC which has this not */
#if (defined(__POWERPC__) || defined(__powerpc__)) && !defined(RDTSC_AVAILABLE)
uint64 ottd_rdtsc()
{
uint32 high = 0, high2 = 0, low;
/* PPC does not have rdtsc, so we cheat by reading the two 32-bit time-counters
* it has, 'Move From Time Base (Upper)'. Since these are two reads, in the
* very unlikely event that the lower part overflows to the upper part while we
* read it; we double-check and reread the registers */
asm volatile (
"mftbu %0\n"
"mftb %1\n"
"mftbu %2\n"
"cmpw %3,%4\n"
"bne- $-16\n"
: "=r" (high), "=r" (low), "=r" (high2)
: "0" (high), "2" (high2)
);
return ((uint64)high << 32) | low;
}
# define RDTSC_AVAILABLE
#endif
/* In all other cases we have no support for rdtsc. No major issue,
* you just won't be able to profile your code with TIC()/TOC() */
#if !defined(RDTSC_AVAILABLE)
/* MSVC (in case of WinCE) can't handle #warning */
# if !defined(_MSC_VER)
#warning "(non-fatal) No support for rdtsc(), you won't be able to profile with TIC/TOC"
# endif
uint64 ottd_rdtsc() {return 0;}
#endif
| 2,158
|
C++
|
.cpp
| 61
| 33.196721
| 98
| 0.673049
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
1,539,116
|
airport_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/airport_gui.cpp
|
/* $Id$ */
/** @file airport_gui.cpp The GUI for airports. */
#include "stdafx.h"
#include "window_gui.h"
#include "station_gui.h"
#include "terraform_gui.h"
#include "airport.h"
#include "sound_func.h"
#include "window_func.h"
#include "strings_func.h"
#include "settings_type.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "company_func.h"
#include "station_type.h"
#include "tilehighlight_func.h"
#include "company_base.h"
#include "table/sprites.h"
#include "table/strings.h"
static byte _selected_airport_type;
static void ShowBuildAirportPicker(Window *parent);
void CcBuildAirport(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_1F_SPLAT, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
}
}
static void PlaceAirport(TileIndex tile)
{
uint32 p2 = _ctrl_pressed;
SB(p2, 16, 16, INVALID_STATION); // no station to join
CommandContainer cmdcont = { tile, _selected_airport_type, p2, CMD_BUILD_AIRPORT | CMD_MSG(STR_A001_CAN_T_BUILD_AIRPORT_HERE), CcBuildAirport, "" };
ShowSelectStationIfNeeded(cmdcont, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE);
}
enum {
ATW_AIRPORT = 3,
ATW_DEMOLISH = 4
};
static void BuildAirClick_Airport(Window *w)
{
if (HandlePlacePushButton(w, ATW_AIRPORT, SPR_CURSOR_AIRPORT, VHM_RECT, PlaceAirport)) ShowBuildAirportPicker(w);
}
static void BuildAirClick_Demolish(Window *w)
{
HandlePlacePushButton(w, ATW_DEMOLISH, ANIMCURSOR_DEMOLISH, VHM_RECT, PlaceProc_DemolishArea);
}
typedef void OnButtonClick(Window *w);
static OnButtonClick * const _build_air_button_proc[] = {
BuildAirClick_Airport,
BuildAirClick_Demolish,
};
struct BuildAirToolbarWindow : Window {
BuildAirToolbarWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->FindWindowPlacementAndResize(desc);
if (_settings_client.gui.link_terraform_toolbar) ShowTerraformToolbar(this);
}
~BuildAirToolbarWindow()
{
if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false);
}
virtual void OnPaint()
{
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
if (widget - 3 >= 0) {
_build_air_button_proc[widget - 3](this);
}
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
switch (keycode) {
case '1': BuildAirClick_Airport(this); break;
case '2': BuildAirClick_Demolish(this); break;
default: return ES_NOT_HANDLED;
}
return ES_HANDLED;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_place_proc(tile);
}
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
{
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
{
if (pt.x != -1 && select_proc == DDSP_DEMOLISH_AREA) {
GUIPlaceProcDragXY(select_proc, start_tile, end_tile);
}
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
DeleteWindowById(WC_BUILD_STATION, 0);
DeleteWindowById(WC_SELECT_STATION, 0);
}
};
static const Widget _air_toolbar_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW },
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 51, 0, 13, STR_A000_AIRPORTS, STR_018C_WINDOW_TITLE_DRAG_THIS },
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 52, 63, 0, 13, 0x0, STR_STICKY_BUTTON },
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 41, 14, 35, SPR_IMG_AIRPORT, STR_A01E_BUILD_AIRPORT },
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 42, 63, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC },
{ WIDGETS_END},
};
static const WindowDesc _air_toolbar_desc(
WDP_ALIGN_TBR, 22, 64, 36, 64, 36,
WC_BUILD_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_air_toolbar_widgets
);
void ShowBuildAirToolbar()
{
if (!IsValidCompanyID(_local_company)) return;
DeleteWindowByClass(WC_BUILD_TOOLBAR);
AllocateWindowDescFront<BuildAirToolbarWindow>(&_air_toolbar_desc, TRANSPORT_AIR);
}
class AirportPickerWindow : public PickerWindowBase {
enum {
BAW_BOTTOMPANEL = 10,
BAW_SMALL_AIRPORT,
BAW_CITY_AIRPORT,
BAW_HELIPORT,
BAW_METRO_AIRPORT,
BAW_STR_INTERNATIONAL_AIRPORT,
BAW_COMMUTER_AIRPORT,
BAW_HELIDEPOT,
BAW_STR_INTERCONTINENTAL_AIRPORT,
BAW_HELISTATION,
BAW_LAST_AIRPORT = BAW_HELISTATION,
BAW_AIRPORT_COUNT = BAW_LAST_AIRPORT - BAW_SMALL_AIRPORT + 1,
BAW_BTN_DONTHILIGHT = BAW_LAST_AIRPORT + 1,
BAW_BTN_DOHILIGHT,
};
public:
AirportPickerWindow(const WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->SetWidgetLoweredState(BAW_BTN_DONTHILIGHT, !_settings_client.gui.station_show_coverage);
this->SetWidgetLoweredState(BAW_BTN_DOHILIGHT, _settings_client.gui.station_show_coverage);
this->LowerWidget(_selected_airport_type + BAW_SMALL_AIRPORT);
if (_settings_game.economy.station_noise_level) {
ResizeWindowForWidget(this, BAW_BOTTOMPANEL, 0, 10);
}
this->FindWindowPlacementAndResize(desc);
}
virtual ~AirportPickerWindow()
{
DeleteWindowById(WC_SELECT_STATION, 0);
}
virtual void OnPaint()
{
int i; // airport enabling loop
uint16 y_noise_offset = 0;
uint32 avail_airports;
const AirportFTAClass *airport;
avail_airports = GetValidAirports();
this->RaiseWidget(_selected_airport_type + BAW_SMALL_AIRPORT);
if (!HasBit(avail_airports, 0) && _selected_airport_type == AT_SMALL) _selected_airport_type = AT_LARGE;
if (!HasBit(avail_airports, 1) && _selected_airport_type == AT_LARGE) _selected_airport_type = AT_SMALL;
this->LowerWidget(_selected_airport_type + BAW_SMALL_AIRPORT);
/* 'Country Airport' starts at widget BAW_SMALL_AIRPORT, and if its bit is set, it is
* available, so take its opposite value to set the disabled state.
* There are 9 buildable airports
* XXX TODO : all airports should be held in arrays, with all relevant data.
* This should be part of newgrf-airports, i suppose
*/
for (i = 0; i < BAW_AIRPORT_COUNT; i++) this->SetWidgetDisabledState(i + BAW_SMALL_AIRPORT, !HasBit(avail_airports, i));
/* select default the coverage area to 'Off' (16) */
airport = GetAirport(_selected_airport_type);
SetTileSelectSize(airport->size_x, airport->size_y);
int rad = _settings_game.station.modified_catchment ? airport->catchment : (uint)CA_UNMODIFIED;
if (_settings_client.gui.station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
this->DrawWidgets();
/* only show the station (airport) noise, if the noise option is activated */
if (_settings_game.economy.station_noise_level) {
/* show the noise of the selected airport */
SetDParam(0, airport->noise_level);
DrawString(2, 206, STR_STATION_NOISE, TC_FROMSTRING);
y_noise_offset = 10;
}
/* strings such as 'Size' and 'Coverage Area' */
int text_end = DrawStationCoverageAreaText(2, this->widget[BAW_BTN_DOHILIGHT].bottom + 4 + y_noise_offset, SCT_ALL, rad, false);
text_end = DrawStationCoverageAreaText(2, text_end + 4, SCT_ALL, rad, true) + 4;
if (text_end != this->widget[BAW_BOTTOMPANEL].bottom) {
this->SetDirty();
ResizeWindowForWidget(this, BAW_BOTTOMPANEL, 0, text_end - this->widget[BAW_BOTTOMPANEL].bottom);
this->SetDirty();
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BAW_SMALL_AIRPORT: case BAW_CITY_AIRPORT: case BAW_HELIPORT: case BAW_METRO_AIRPORT:
case BAW_STR_INTERNATIONAL_AIRPORT: case BAW_COMMUTER_AIRPORT: case BAW_HELIDEPOT:
case BAW_STR_INTERCONTINENTAL_AIRPORT: case BAW_HELISTATION:
this->RaiseWidget(_selected_airport_type + BAW_SMALL_AIRPORT);
_selected_airport_type = widget - BAW_SMALL_AIRPORT;
this->LowerWidget(_selected_airport_type + BAW_SMALL_AIRPORT);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
case BAW_BTN_DONTHILIGHT: case BAW_BTN_DOHILIGHT:
_settings_client.gui.station_show_coverage = (widget != BAW_BTN_DONTHILIGHT);
this->SetWidgetLoweredState(BAW_BTN_DONTHILIGHT, !_settings_client.gui.station_show_coverage);
this->SetWidgetLoweredState(BAW_BTN_DOHILIGHT, _settings_client.gui.station_show_coverage);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
}
}
virtual void OnTick()
{
CheckRedrawStationCoverage(this);
}
};
#ifdef N3DS /* Remove the labels about the type of airport to make room. */
static const Widget _build_airport_picker_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 147, 0, 13, STR_3001_AIRPORT_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 14, 41, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_PALE_GREEN, 0, 0, 13, 13, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 42, 67, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_PALE_GREEN, 0, 0, 13, 13, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 68, 94, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_PALE_GREEN, 0, 0, 13, 13, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 95, 133, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_PALE_GREEN, 0, 0, 13, 13, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 134, 195, 0x0, STR_NULL}, // bottom general box
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 16, 27, STR_SMALL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 43, 54, STR_CITY_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 97, 108, STR_HELIPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 55, 66, STR_METRO_AIRPORT , STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 70, 81, STR_INTERNATIONAL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 28, 39, STR_COMMUTER_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 121, 132, STR_HELIDEPOT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 82, 93, STR_INTERCONTINENTAL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 109, 120, STR_HELISTATION, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 14, 73, 147, 158, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 74, 133, 147, 158, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA},
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 134, 147, STR_3066_COVERAGE_AREA_HIGHLIGHT, STR_NULL},
{ WIDGETS_END},
};
#else
static const Widget _build_airport_picker_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 147, 0, 13, STR_3001_AIRPORT_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 14, 52, 0x0, STR_NULL},
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 14, 27, STR_SMALL_AIRPORTS, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 53, 89, 0x0, STR_NULL},
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 52, 65, STR_LARGE_AIRPORTS, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 90, 127, 0x0, STR_NULL},
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 90, 103, STR_HUB_AIRPORTS, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 128, 177, 0x0, STR_NULL},
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 128, 141, STR_HELIPORTS, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 178, 239, 0x0, STR_NULL}, // bottom general box
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 27, 38, STR_SMALL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 65, 76, STR_CITY_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 141, 152, STR_HELIPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 77, 88, STR_METRO_AIRPORT , STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 103, 114, STR_INTERNATIONAL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 39, 50, STR_COMMUTER_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 165, 176, STR_HELIDEPOT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 115, 126, STR_INTERCONTINENTAL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 145, 153, 164, STR_HELISTATION, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 14, 73, 191, 202, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 74, 133, 191, 202, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA},
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 147, 178, 191, STR_3066_COVERAGE_AREA_HIGHLIGHT, STR_NULL},
{ WIDGETS_END},
};
#endif /* N3DS */
#ifdef N3DS
static const WindowDesc _build_airport_desc(
WDP_AUTO, WDP_AUTO, 148, 196, 148, 196,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_build_airport_picker_widgets
);
#else
static const WindowDesc _build_airport_desc(
WDP_AUTO, WDP_AUTO, 148, 240, 148, 240,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_build_airport_picker_widgets
);
#endif /* N3DS */
static void ShowBuildAirportPicker(Window *parent)
{
new AirportPickerWindow(&_build_airport_desc, parent);
}
void InitializeAirportGui()
{
_selected_airport_type = AT_SMALL;
}
| 16,010
|
C++
|
.cpp
| 299
| 51.267559
| 161
| 0.647972
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,117
|
subsidy_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/subsidy_gui.cpp
|
/* $Id$ */
/** @file subsidy_gui.cpp GUI for subsidies. */
#include "stdafx.h"
#include "station_base.h"
#include "industry.h"
#include "town.h"
#include "economy_func.h"
#include "cargotype.h"
#include "window_gui.h"
#include "strings_func.h"
#include "date_func.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "gui.h"
#include "table/strings.h"
struct SubsidyListWindow : Window {
SubsidyListWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->FindWindowPlacementAndResize(desc);
}
virtual void OnClick(Point pt, int widget)
{
if (widget != 3) return;
int y = pt.y - 25;
if (y < 0) return;
uint num = 0;
for (const Subsidy *s = _subsidies; s != endof(_subsidies); s++) {
if (s->cargo_type != CT_INVALID && s->age < 12) {
y -= 10;
if (y < 0) {
this->HandleClick(s);
return;
}
num++;
}
}
if (num == 0) {
y -= 10; // "None"
if (y < 0) return;
}
y -= 11; // "Services already subsidised:"
if (y < 0) return;
for (const Subsidy *s = _subsidies; s != endof(_subsidies); s++) {
if (s->cargo_type != CT_INVALID && s->age >= 12) {
y -= 10;
if (y < 0) {
this->HandleClick(s);
return;
}
}
}
}
void HandleClick(const Subsidy *s)
{
TownEffect te = GetCargo(s->cargo_type)->town_effect;
TileIndex xy;
/* determine from coordinate for subsidy and try to scroll to it */
uint offs = s->from;
if (s->age >= 12) {
xy = GetStation(offs)->xy;
} else if (te == TE_PASSENGERS || te == TE_MAIL) {
xy = GetTown(offs)->xy;
} else {
xy = GetIndustry(offs)->xy;
}
if (_ctrl_pressed || !ScrollMainWindowToTile(xy)) {
if (_ctrl_pressed) ShowExtraViewPortWindow(xy);
/* otherwise determine to coordinate for subsidy and scroll to it */
offs = s->to;
if (s->age >= 12) {
xy = GetStation(offs)->xy;
} else if (te == TE_PASSENGERS || te == TE_MAIL || te == TE_GOODS || te == TE_FOOD) {
xy = GetTown(offs)->xy;
} else {
xy = GetIndustry(offs)->xy;
}
if (_ctrl_pressed) {
ShowExtraViewPortWindow(xy);
} else {
ScrollMainWindowToTile(xy);
}
}
}
virtual void OnPaint()
{
YearMonthDay ymd;
const Subsidy *s;
this->DrawWidgets();
ConvertDateToYMD(_date, &ymd);
int width = this->width - 13; // scroll bar = 11 + pixel each side
int y = 15;
int x = 1;
/* Section for drawing the offered subisidies */
DrawStringTruncated(x, y, STR_2026_SUBSIDIES_ON_OFFER_FOR, TC_FROMSTRING, width);
y += 10;
uint num = 0;
for (s = _subsidies; s != endof(_subsidies); s++) {
if (s->cargo_type != CT_INVALID && s->age < 12) {
int x2;
/* Displays the two offered towns */
SetupSubsidyDecodeParam(s, 1);
x2 = DrawStringTruncated(x + 2, y, STR_2027_FROM_TO, TC_FROMSTRING, width - 2);
if (width - x2 > 10) {
/* Displays the deadline before voiding the proposal */
SetDParam(0, _date - ymd.day + 384 - s->age * 32);
DrawStringTruncated(x2, y, STR_2028_BY, TC_FROMSTRING, width - x2);
}
y += 10;
num++;
}
}
if (num == 0) {
DrawStringTruncated(x + 2, y, STR_202A_NONE, TC_FROMSTRING, width - 2);
y += 10;
}
/* Section for drawing the already granted subisidies */
DrawStringTruncated(x, y + 1, STR_202B_SERVICES_ALREADY_SUBSIDISED, TC_FROMSTRING, width);
y += 10;
num = 0;
for (s = _subsidies; s != endof(_subsidies); s++) {
if (s->cargo_type != CT_INVALID && s->age >= 12) {
int xt;
SetupSubsidyDecodeParam(s, 1);
SetDParam(3, GetStation(s->to)->owner);
/* Displays the two connected stations */
xt = DrawStringTruncated(x + 2, y, STR_202C_FROM_TO, TC_FROMSTRING, width - 2);
/* Displays the date where the granted subsidy will end */
if ((xt > 3) && (width - xt) > 9 ) { // do not draw if previous drawing failed or if it will overlap on scrollbar
SetDParam(0, _date - ymd.day + 768 - s->age * 32);
DrawStringTruncated(xt, y, STR_202D_UNTIL, TC_FROMSTRING, width - xt);
}
y += 10;
num++;
}
}
if (num == 0) DrawStringTruncated(x + 2, y, STR_202A_NONE, TC_FROMSTRING, width - 2);
}
};
static const Widget _subsidies_list_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_BROWN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_BROWN, 11, 307, 0, 13, STR_2025_SUBSIDIES, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_BROWN, 308, 319, 0, 13, STR_NULL, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_RB, COLOUR_BROWN, 0, 307, 14, 126, 0x0, STR_01FD_CLICK_ON_SERVICE_TO_CENTER},
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_BROWN, 308, 319, 14, 114, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_BROWN, 308, 319, 115, 126, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
static const WindowDesc _subsidies_list_desc(
WDP_AUTO, WDP_AUTO, 320, 127, 320, 127,
WC_SUBSIDIES_LIST, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_subsidies_list_widgets
);
void ShowSubsidiesList()
{
AllocateWindowDescFront<SubsidyListWindow>(&_subsidies_list_desc, 0);
}
| 5,256
|
C++
|
.cpp
| 157
| 30.025478
| 124
| 0.628137
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,118
|
fontcache.cpp
|
EnergeticBark_OpenTTD-3DS/src/fontcache.cpp
|
/* $Id$ */
/** @file fontcache.cpp Cache for characters from fonts. */
#include "stdafx.h"
#include "spritecache.h"
#include "fontcache.h"
#include "blitter/factory.hpp"
#include "gfx_func.h"
#include "core/alloc_func.hpp"
#include "core/math_func.hpp"
#include "table/sprites.h"
#include "table/control_codes.h"
#ifdef WITH_FREETYPE
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#ifdef WITH_FONTCONFIG
#include <fontconfig/fontconfig.h>
#endif
static FT_Library _library = NULL;
static FT_Face _face_small = NULL;
static FT_Face _face_medium = NULL;
static FT_Face _face_large = NULL;
FreeTypeSettings _freetype;
enum {
FACE_COLOUR = 1,
SHADOW_COLOUR = 2,
};
/** Get the font loaded into a Freetype face by using a font-name.
* If no appropiate font is found, the function returns an error */
#ifdef WIN32
#include <windows.h>
#include <shlobj.h> /* SHGetFolderPath */
#include "win32.h"
/**
* Get the short DOS 8.3 format for paths.
* FreeType doesn't support Unicode filenames and Windows' fopen (as used
* by FreeType) doesn't support UTF-8 filenames. So we have to convert the
* filename into something that isn't UTF-8 but represents the Unicode file
* name. This is the short DOS 8.3 format. This does not contain any
* characters that fopen doesn't support.
* @param long_path the path in UTF-8.
* @return the short path in ANSI (ASCII).
*/
char *GetShortPath(const char *long_path)
{
static char short_path[MAX_PATH];
#ifdef UNICODE
/* The non-unicode GetShortPath doesn't support UTF-8...,
* so convert the path to wide chars, then get the short
* path and convert it back again. */
wchar_t long_path_w[MAX_PATH];
MultiByteToWideChar(CP_UTF8, 0, long_path, -1, long_path_w, MAX_PATH);
wchar_t short_path_w[MAX_PATH];
GetShortPathNameW(long_path_w, short_path_w, MAX_PATH);
WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, MAX_PATH, NULL, NULL);
#else
/* Technically not needed, but do it for consistency. */
GetShortPathNameA(long_path, short_path, MAX_PATH);
#endif
return short_path;
}
/* Get the font file to be loaded into Freetype by looping the registry
* location where windows lists all installed fonts. Not very nice, will
* surely break if the registry path changes, but it works. Much better
* solution would be to use CreateFont, and extract the font data from it
* by GetFontData. The problem with this is that the font file needs to be
* kept in memory then until the font is no longer needed. This could mean
* an additional memory usage of 30MB (just for fonts!) when using an eastern
* font for all font sizes */
#define FONT_DIR_NT "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"
#define FONT_DIR_9X "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts"
static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
{
FT_Error err = FT_Err_Cannot_Open_Resource;
HKEY hKey;
LONG ret;
TCHAR vbuffer[MAX_PATH], dbuffer[256];
TCHAR *font_namep;
char *font_path;
uint index;
/* On windows NT (2000, NT3.5, XP, etc.) the fonts are stored in the
* "Windows NT" key, on Windows 9x in the Windows key. To save us having
* to retrieve the windows version, we'll just query both */
ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_NT), 0, KEY_READ, &hKey);
if (ret != ERROR_SUCCESS) ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_9X), 0, KEY_READ, &hKey);
if (ret != ERROR_SUCCESS) {
DEBUG(freetype, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows (NT)\\CurrentVersion\\Fonts");
return err;
}
/* For Unicode we need some conversion between widechar and
* normal char to match the data returned by RegEnumValue,
* otherwise just use parameter */
#if defined(UNICODE)
font_namep = MallocT<TCHAR>(MAX_PATH);
MB_TO_WIDE_BUFFER(font_name, font_namep, MAX_PATH * sizeof(TCHAR));
#else
font_namep = (char*)font_name; // only cast because in unicode pointer is not const
#endif
for (index = 0;; index++) {
TCHAR *s;
DWORD vbuflen = lengthof(vbuffer);
DWORD dbuflen = lengthof(dbuffer);
ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, NULL, NULL, (byte*)dbuffer, &dbuflen);
if (ret != ERROR_SUCCESS) goto registry_no_font_found;
/* The font names in the registry are of the following 3 forms:
* - ADMUI3.fon
* - Book Antiqua Bold (TrueType)
* - Batang & BatangChe & Gungsuh & GungsuhChe (TrueType)
* We will strip the font-type '()' if any and work with the font name
* itself, which must match exactly; if...
* TTC files, font files which contain more than one font are seperated
* byt '&'. Our best bet will be to do substr match for the fontname
* and then let FreeType figure out which index to load */
s = _tcschr(vbuffer, _T('('));
if (s != NULL) s[-1] = '\0';
if (_tcschr(vbuffer, _T('&')) == NULL) {
if (_tcsicmp(vbuffer, font_namep) == 0) break;
} else {
if (_tcsstr(vbuffer, font_namep) != NULL) break;
}
}
if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, vbuffer))) {
DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory");
goto folder_error;
}
/* Some fonts are contained in .ttc files, TrueType Collection fonts. These
* contain multiple fonts inside this single file. GetFontData however
* returns the whole file, so we need to check each font inside to get the
* proper font.
* Also note that FreeType does not support UNICODE filesnames! */
#if defined(UNICODE)
/* We need a cast here back from wide because FreeType doesn't support
* widechar filenames. Just use the buffer we allocated before for the
* font_name search */
font_path = (char*)font_namep;
WIDE_TO_MB_BUFFER(vbuffer, font_path, MAX_PATH * sizeof(TCHAR));
#else
font_path = vbuffer;
#endif
ttd_strlcat(font_path, "\\", MAX_PATH * sizeof(TCHAR));
ttd_strlcat(font_path, WIDE_TO_MB(dbuffer), MAX_PATH * sizeof(TCHAR));
/* Convert the path into something that FreeType understands */
font_path = GetShortPath(font_path);
index = 0;
do {
err = FT_New_Face(_library, font_path, index, face);
if (err != FT_Err_Ok) break;
if (strncasecmp(font_name, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
/* Try english name if font name failed */
if (strncasecmp(font_name + strlen(font_name) + 1, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
err = FT_Err_Cannot_Open_Resource;
} while ((FT_Long)++index != (*face)->num_faces);
folder_error:
registry_no_font_found:
#if defined(UNICODE)
free(font_namep);
#endif
RegCloseKey(hKey);
return err;
}
/**
* Fonts can have localised names and when the system locale is the same as
* one of those localised names Windows will always return that localised name
* instead of allowing to get the non-localised (English US) name of the font.
* This will later on give problems as freetype uses the non-localised name of
* the font and we need to compare based on that name.
* Windows furthermore DOES NOT have an API to get the non-localised name nor
* can we override the system locale. This means that we have to actually read
* the font itself to gather the font name we want.
* Based on: http://blogs.msdn.com/michkap/archive/2006/02/13/530814.aspx
* @param logfont the font information to get the english name of.
* @return the English name (if it could be found).
*/
static const char *GetEnglishFontName(const ENUMLOGFONTEX *logfont)
{
static char font_name[MAX_PATH];
const char *ret_font_name = NULL;
uint pos = 0;
HDC dc;
HGDIOBJ oldfont;
byte *buf;
DWORD dw;
uint16 format, count, stringOffset, platformId, encodingId, languageId, nameId, length, offset;
HFONT font = CreateFontIndirect(&logfont->elfLogFont);
if (font == NULL) goto err1;
dc = GetDC(NULL);
oldfont = SelectObject(dc, font);
dw = GetFontData(dc, 'eman', 0, NULL, 0);
if (dw == GDI_ERROR) goto err2;
buf = MallocT<byte>(dw);
dw = GetFontData(dc, 'eman', 0, buf, dw);
if (dw == GDI_ERROR) goto err3;
format = buf[pos++] << 8;
format += buf[pos++];
assert(format == 0);
count = buf[pos++] << 8;
count += buf[pos++];
stringOffset = buf[pos++] << 8;
stringOffset += buf[pos++];
for (uint i = 0; i < count; i++) {
platformId = buf[pos++] << 8;
platformId += buf[pos++];
encodingId = buf[pos++] << 8;
encodingId += buf[pos++];
languageId = buf[pos++] << 8;
languageId += buf[pos++];
nameId = buf[pos++] << 8;
nameId += buf[pos++];
if (nameId != 1) {
pos += 4; // skip length and offset
continue;
}
length = buf[pos++] << 8;
length += buf[pos++];
offset = buf[pos++] << 8;
offset += buf[pos++];
/* Don't buffer overflow */
length = min(length, MAX_PATH - 1);
for (uint j = 0; j < length; j++) font_name[j] = buf[stringOffset + offset + j];
font_name[length] = '\0';
if ((platformId == 1 && languageId == 0) || // Macintosh English
(platformId == 3 && languageId == 0x0409)) { // Microsoft English (US)
ret_font_name = font_name;
break;
}
}
err3:
free(buf);
err2:
SelectObject(dc, oldfont);
ReleaseDC(NULL, dc);
err1:
DeleteObject(font);
return ret_font_name == NULL ? WIDE_TO_MB((const TCHAR*)logfont->elfFullName) : ret_font_name;
}
struct EFCParam {
FreeTypeSettings *settings;
LOCALESIGNATURE locale;
};
static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXTMETRICEX *metric, DWORD type, LPARAM lParam)
{
EFCParam *info = (EFCParam *)lParam;
/* Only use TrueType fonts */
if (!(type & TRUETYPE_FONTTYPE)) return 1;
/* Don't use SYMBOL fonts */
if (logfont->elfLogFont.lfCharSet == SYMBOL_CHARSET) return 1;
/* The font has to have at least one of the supported locales to be usable. */
if ((metric->ntmFontSig.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (metric->ntmFontSig.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) {
/* On win9x metric->ntmFontSig seems to contain garbage. */
FONTSIGNATURE fs;
memset(&fs, 0, sizeof(fs));
HFONT font = CreateFontIndirect(&logfont->elfLogFont);
if (font != NULL) {
HDC dc = GetDC(NULL);
HGDIOBJ oldfont = SelectObject(dc, font);
GetTextCharsetInfo(dc, &fs, 0);
SelectObject(dc, oldfont);
ReleaseDC(NULL, dc);
DeleteObject(font);
}
if ((fs.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (fs.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) return 1;
}
const char *english_name = GetEnglishFontName(logfont);
const char *font_name = WIDE_TO_MB((const TCHAR*)logfont->elfFullName);
DEBUG(freetype, 1, "Fallback font: %s (%s)", font_name, english_name);
strecpy(info->settings->small_font, font_name, lastof(info->settings->small_font));
strecpy(info->settings->medium_font, font_name, lastof(info->settings->medium_font));
strecpy(info->settings->large_font, font_name, lastof(info->settings->large_font));
/* Add english name after font name */
strecpy(info->settings->small_font + strlen(info->settings->small_font) + 1, english_name, lastof(info->settings->small_font));
strecpy(info->settings->medium_font + strlen(info->settings->medium_font) + 1, english_name, lastof(info->settings->medium_font));
strecpy(info->settings->large_font + strlen(info->settings->large_font) + 1, english_name, lastof(info->settings->large_font));
return 0; // stop enumerating
}
bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid)
{
EFCParam langInfo;
if (GetLocaleInfo(MAKELCID(winlangid, SORT_DEFAULT), LOCALE_FONTSIGNATURE, (LPTSTR)&langInfo.locale, sizeof(langInfo.locale) / sizeof(TCHAR)) == 0) {
/* Invalid langid or some other mysterious error, can't determine fallback font. */
DEBUG(freetype, 1, "Can't get locale info for fallback font (langid=0x%x)", winlangid);
return false;
}
langInfo.settings = settings;
LOGFONT font;
/* Enumerate all fonts. */
font.lfCharSet = DEFAULT_CHARSET;
font.lfFaceName[0] = '\0';
font.lfPitchAndFamily = 0;
HDC dc = GetDC(NULL);
int ret = EnumFontFamiliesEx(dc, &font, (FONTENUMPROC)&EnumFontCallback, (LPARAM)&langInfo, 0);
ReleaseDC(NULL, dc);
return ret == 0;
}
#elif defined(WITH_FONTCONFIG)
static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
{
FT_Error err = FT_Err_Cannot_Open_Resource;
if (!FcInit()) {
ShowInfoF("Unable to load font configuration");
} else {
FcPattern *match;
FcPattern *pat;
FcFontSet *fs;
FcResult result;
char *font_style;
char *font_family;
/* Split & strip the font's style */
font_family = strdup(font_name);
font_style = strchr(font_family, ',');
if (font_style != NULL) {
font_style[0] = '\0';
font_style++;
while (*font_style == ' ' || *font_style == '\t') font_style++;
}
/* Resolve the name and populate the information structure */
pat = FcNameParse((FcChar8*)font_family);
if (font_style != NULL) FcPatternAddString(pat, FC_STYLE, (FcChar8*)font_style);
FcConfigSubstitute(0, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
fs = FcFontSetCreate();
match = FcFontMatch(0, pat, &result);
if (fs != NULL && match != NULL) {
int i;
FcChar8 *family;
FcChar8 *style;
FcChar8 *file;
FcFontSetAdd(fs, match);
for (i = 0; err != FT_Err_Ok && i < fs->nfont; i++) {
/* Try the new filename */
if (FcPatternGetString(fs->fonts[i], FC_FILE, 0, &file) == FcResultMatch &&
FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, &family) == FcResultMatch &&
FcPatternGetString(fs->fonts[i], FC_STYLE, 0, &style) == FcResultMatch) {
/* The correct style? */
if (font_style != NULL && strcasecmp(font_style, (char*)style) != 0) continue;
/* Font config takes the best shot, which, if the family name is spelled
* wrongly a 'random' font, so check whether the family name is the
* same as the supplied name */
if (strcasecmp(font_family, (char*)family) == 0) {
err = FT_New_Face(_library, (char *)file, 0, face);
}
}
}
}
free(font_family);
FcPatternDestroy(pat);
FcFontSetDestroy(fs);
FcFini();
}
return err;
}
bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid)
{
if (!FcInit()) return false;
bool ret = false;
/* Fontconfig doesn't handle full language isocodes, only the part
* before the _ of e.g. en_GB is used, so "remove" everything after
* the _. */
char lang[16];
strecpy(lang, language_isocode, lastof(lang));
char *split = strchr(lang, '_');
if (split != NULL) *split = '\0';
FcPattern *pat;
FcPattern *match;
FcResult result;
FcChar8 *file;
FcFontSet *fs;
FcValue val;
val.type = FcTypeString;
val.u.s = (FcChar8*)lang;
/* First create a pattern to match the wanted language */
pat = FcPatternCreate();
/* And fill it with the language and other defaults */
if (pat == NULL ||
!FcPatternAdd(pat, "lang", val, false) ||
!FcConfigSubstitute(0, pat, FcMatchPattern)) {
goto error_pattern;
}
FcDefaultSubstitute(pat);
/* Then create a font set and match that */
match = FcFontMatch(0, pat, &result);
if (match == NULL) {
goto error_pattern;
}
/* Find all fonts that do match */
fs = FcFontSetCreate();
FcFontSetAdd(fs, match);
/* And take the first, if it exists */
if (fs->nfont <= 0 || FcPatternGetString(fs->fonts[0], FC_FILE, 0, &file)) {
goto error_fontset;
}
strecpy(settings->small_font, (const char*)file, lastof(settings->small_font));
strecpy(settings->medium_font, (const char*)file, lastof(settings->medium_font));
strecpy(settings->large_font, (const char*)file, lastof(settings->large_font));
ret = true;
error_fontset:
FcFontSetDestroy(fs);
error_pattern:
if (pat != NULL) FcPatternDestroy(pat);
FcFini();
return ret;
}
#else /* without WITH_FONTCONFIG */
FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) {return FT_Err_Cannot_Open_Resource;}
bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid) { return false; }
#endif /* WITH_FONTCONFIG */
/**
* Loads the freetype font.
* First type to load the fontname as if it were a path. If that fails,
* try to resolve the filename of the font using fontconfig, where the
* format is 'font family name' or 'font family name, font style'.
*/
static void LoadFreeTypeFont(const char *font_name, FT_Face *face, const char *type)
{
FT_Error error;
if (StrEmpty(font_name)) return;
error = FT_New_Face(_library, font_name, 0, face);
if (error != FT_Err_Ok) error = GetFontByFaceName(font_name, face);
if (error == FT_Err_Ok) {
DEBUG(freetype, 2, "Requested '%s', using '%s %s'", font_name, (*face)->family_name, (*face)->style_name);
/* Attempt to select the unicode character map */
error = FT_Select_Charmap(*face, ft_encoding_unicode);
if (error == FT_Err_Ok) return; // Success
if (error == FT_Err_Invalid_CharMap_Handle) {
/* Try to pick a different character map instead. We default to
* the first map, but platform_id 0 encoding_id 0 should also
* be unicode (strange system...) */
FT_CharMap found = (*face)->charmaps[0];
int i;
for (i = 0; i < (*face)->num_charmaps; i++) {
FT_CharMap charmap = (*face)->charmaps[i];
if (charmap->platform_id == 0 && charmap->encoding_id == 0) {
found = charmap;
}
}
if (found != NULL) {
error = FT_Set_Charmap(*face, found);
if (error == FT_Err_Ok) return;
}
}
}
FT_Done_Face(*face);
*face = NULL;
ShowInfoF("Unable to use '%s' for %s font, FreeType reported error 0x%X, using sprite font instead", font_name, type, error);
}
void InitFreeType()
{
if (StrEmpty(_freetype.small_font) && StrEmpty(_freetype.medium_font) && StrEmpty(_freetype.large_font)) {
DEBUG(freetype, 1, "No font faces specified, using sprite fonts instead");
return;
}
if (FT_Init_FreeType(&_library) != FT_Err_Ok) {
ShowInfoF("Unable to initialize FreeType, using sprite fonts instead");
return;
}
DEBUG(freetype, 2, "Initialized");
/* Load each font */
LoadFreeTypeFont(_freetype.small_font, &_face_small, "small");
LoadFreeTypeFont(_freetype.medium_font, &_face_medium, "medium");
LoadFreeTypeFont(_freetype.large_font, &_face_large, "large");
/* Set each font size */
if (_face_small != NULL) FT_Set_Pixel_Sizes(_face_small, 0, _freetype.small_size);
if (_face_medium != NULL) FT_Set_Pixel_Sizes(_face_medium, 0, _freetype.medium_size);
if (_face_large != NULL) FT_Set_Pixel_Sizes(_face_large, 0, _freetype.large_size);
}
static void ResetGlyphCache();
/**
* Unload a face and set it to NULL.
* @param face the face to unload
*/
static void UnloadFace(FT_Face *face)
{
if (*face == NULL) return;
FT_Done_Face(*face);
*face = NULL;
}
/**
* Free everything allocated w.r.t. fonts.
*/
void UninitFreeType()
{
ResetGlyphCache();
UnloadFace(&_face_small);
UnloadFace(&_face_medium);
UnloadFace(&_face_large);
FT_Done_FreeType(_library);
_library = NULL;
}
static FT_Face GetFontFace(FontSize size)
{
switch (size) {
default: NOT_REACHED();
case FS_NORMAL: return _face_medium;
case FS_SMALL: return _face_small;
case FS_LARGE: return _face_large;
}
}
struct GlyphEntry {
Sprite *sprite;
byte width;
};
/* The glyph cache. This is structured to reduce memory consumption.
* 1) There is a 'segment' table for each font size.
* 2) Each segment table is a discrete block of characters.
* 3) Each block contains 256 (aligned) characters sequential characters.
*
* The cache is accessed in the following way:
* For character 0x0041 ('A'): _glyph_ptr[FS_NORMAL][0x00][0x41]
* For character 0x20AC (Euro): _glyph_ptr[FS_NORMAL][0x20][0xAC]
*
* Currently only 256 segments are allocated, "limiting" us to 65536 characters.
* This can be simply changed in the two functions Get & SetGlyphPtr.
*/
static GlyphEntry **_glyph_ptr[FS_END];
/** Clear the complete cache */
static void ResetGlyphCache()
{
for (int i = 0; i < FS_END; i++) {
if (_glyph_ptr[i] == NULL) continue;
for (int j = 0; j < 256; j++) {
if (_glyph_ptr[i][j] == NULL) continue;
for (int k = 0; k < 256; k++) {
if (_glyph_ptr[i][j][k].sprite == NULL) continue;
free(_glyph_ptr[i][j][k].sprite);
}
free(_glyph_ptr[i][j]);
}
free(_glyph_ptr[i]);
_glyph_ptr[i] = NULL;
}
}
static GlyphEntry *GetGlyphPtr(FontSize size, WChar key)
{
if (_glyph_ptr[size] == NULL) return NULL;
if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) return NULL;
return &_glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)];
}
static void SetGlyphPtr(FontSize size, WChar key, const GlyphEntry *glyph)
{
if (_glyph_ptr[size] == NULL) {
DEBUG(freetype, 3, "Allocating root glyph cache for size %u", size);
_glyph_ptr[size] = CallocT<GlyphEntry*>(256);
}
if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) {
DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), size);
_glyph_ptr[size][GB(key, 8, 8)] = CallocT<GlyphEntry>(256);
}
DEBUG(freetype, 4, "Set glyph for unicode character 0x%04X, size %u", key, size);
_glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].sprite = glyph->sprite;
_glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].width = glyph->width;
}
void *AllocateFont(size_t size)
{
return MallocT<byte>(size);
}
/* Check if a glyph should be rendered with antialiasing */
static bool GetFontAAState(FontSize size)
{
/* AA is only supported for 32 bpp */
if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() != 32) return false;
switch (size) {
default: NOT_REACHED();
case FS_NORMAL: return _freetype.medium_aa;
case FS_SMALL: return _freetype.small_aa;
case FS_LARGE: return _freetype.large_aa;
}
}
const Sprite *GetGlyph(FontSize size, WChar key)
{
FT_Face face = GetFontFace(size);
FT_GlyphSlot slot;
GlyphEntry new_glyph;
GlyphEntry *glyph;
SpriteLoader::Sprite sprite;
int width;
int height;
int x;
int y;
int y_adj;
assert(IsPrintable(key));
/* Bail out if no face loaded, or for our special characters */
if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
SpriteID sprite = GetUnicodeGlyph(size, key);
if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
return GetSprite(sprite, ST_FONT);
}
/* Check for the glyph in our cache */
glyph = GetGlyphPtr(size, key);
if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;
slot = face->glyph;
bool aa = GetFontAAState(size);
FT_Load_Char(face, key, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
/* Despite requesting a normal glyph, FreeType may have returned a bitmap */
aa = (slot->bitmap.palette_mode == FT_PIXEL_MODE_GRAY);
/* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
width = max(1, slot->bitmap.width + (size == FS_NORMAL));
height = max(1, slot->bitmap.rows + (size == FS_NORMAL));
/* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
sprite.AllocateData(width * height);
sprite.width = width;
sprite.height = height;
sprite.x_offs = slot->bitmap_left;
/* XXX 2 should be determined somehow... it's right for the normal face */
y_adj = (size == FS_NORMAL) ? 2 : 0;
sprite.y_offs = GetCharacterHeight(size) - slot->bitmap_top - y_adj;
/* Draw shadow for medium size */
if (size == FS_NORMAL) {
for (y = 0; y < slot->bitmap.rows; y++) {
for (x = 0; x < slot->bitmap.width; x++) {
if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
}
}
}
}
for (y = 0; y < slot->bitmap.rows; y++) {
for (x = 0; x < slot->bitmap.width; x++) {
if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
sprite.data[x + y * sprite.width].m = FACE_COLOUR;
sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
}
}
}
new_glyph.sprite = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
new_glyph.width = (slot->advance.x >> 6) + (size != FS_NORMAL);
SetGlyphPtr(size, key, &new_glyph);
return new_glyph.sprite;
}
uint GetGlyphWidth(FontSize size, WChar key)
{
FT_Face face = GetFontFace(size);
GlyphEntry *glyph;
if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
SpriteID sprite = GetUnicodeGlyph(size, key);
if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
return SpriteExists(sprite) ? GetSprite(sprite, ST_FONT)->width + (size != FS_NORMAL) : 0;
}
glyph = GetGlyphPtr(size, key);
if (glyph == NULL || glyph->sprite == NULL) {
GetGlyph(size, key);
glyph = GetGlyphPtr(size, key);
}
return glyph->width;
}
#endif /* WITH_FREETYPE */
/* Sprite based glyph mapping */
#include "table/unicode.h"
static SpriteID **_unicode_glyph_map[FS_END];
/** Get the SpriteID of the first glyph for the given font size */
static SpriteID GetFontBase(FontSize size)
{
switch (size) {
default: NOT_REACHED();
case FS_NORMAL: return SPR_ASCII_SPACE;
case FS_SMALL: return SPR_ASCII_SPACE_SMALL;
case FS_LARGE: return SPR_ASCII_SPACE_BIG;
}
}
SpriteID GetUnicodeGlyph(FontSize size, uint32 key)
{
if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) return 0;
return _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)];
}
void SetUnicodeGlyph(FontSize size, uint32 key, SpriteID sprite)
{
if (_unicode_glyph_map[size] == NULL) _unicode_glyph_map[size] = CallocT<SpriteID*>(256);
if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) _unicode_glyph_map[size][GB(key, 8, 8)] = CallocT<SpriteID>(256);
_unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)] = sprite;
}
void InitializeUnicodeGlyphMap()
{
for (FontSize size = FS_NORMAL; size != FS_END; size++) {
/* Clear out existing glyph map if it exists */
if (_unicode_glyph_map[size] != NULL) {
for (uint i = 0; i < 256; i++) {
if (_unicode_glyph_map[size][i] != NULL) free(_unicode_glyph_map[size][i]);
}
free(_unicode_glyph_map[size]);
_unicode_glyph_map[size] = NULL;
}
SpriteID base = GetFontBase(size);
for (uint i = ASCII_LETTERSTART; i < 256; i++) {
SpriteID sprite = base + i - ASCII_LETTERSTART;
if (!SpriteExists(sprite)) continue;
SetUnicodeGlyph(size, i, sprite);
SetUnicodeGlyph(size, i + SCC_SPRITE_START, sprite);
}
for (uint i = 0; i < lengthof(_default_unicode_map); i++) {
byte key = _default_unicode_map[i].key;
if (key == CLRA || key == CLRL) {
/* Clear the glyph. This happens if the glyph at this code point
* is non-standard and should be accessed by an SCC_xxx enum
* entry only. */
if (key == CLRA || size == FS_LARGE) {
SetUnicodeGlyph(size, _default_unicode_map[i].code, 0);
}
} else {
SpriteID sprite = base + key - ASCII_LETTERSTART;
SetUnicodeGlyph(size, _default_unicode_map[i].code, sprite);
}
}
}
}
| 27,009
|
C++
|
.cpp
| 704
| 35.786932
| 150
| 0.692425
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,119
|
minilzo.cpp
|
EnergeticBark_OpenTTD-3DS/src/minilzo.cpp
|
/* $Id$ */
/**
* @file minilzo.cpp -- mini subset of the LZO real-time data compression library
*
* This file is part of the LZO real-time data compression library.
*
* Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer
* Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer
* Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer
* Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer
* Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer
* Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer
* Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer
* All Rights Reserved.
*
* The LZO library 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.
*
* The LZO library 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 the LZO library; see the file COPYING.
* If not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Markus F.X.J. Oberhumer
* <markus@oberhumer.com>
* http://www.oberhumer.com/opensource/lzo/
*
* NOTE:
* the full LZO package can be found at
* http://www.oberhumer.com/opensource/lzo/
*/
#define LZO_DISABLE_CHECKS
#define LZO1X
#define __LZO_IN_MINILZO
#define LZO_BUILD
#ifdef MINILZO_HAVE_CONFIG_H
# include <config.h>
#endif
#undef LZO_HAVE_CONFIG_H
#include "minilzo.h"
#if !defined(MINILZO_VERSION) || (MINILZO_VERSION != 0x1080)
# error "version mismatch in miniLZO source files"
#endif
#ifdef MINILZO_HAVE_CONFIG_H
# define LZO_HAVE_CONFIG_H
#endif
#if !defined(LZO_NO_SYS_TYPES_H) && !defined(WINCE)
# include <sys/types.h>
#endif
#include <stdio.h>
#ifndef __LZO_CONF_H
#define __LZO_CONF_H
#if defined(__BOUNDS_CHECKING_ON)
# include <unchecked.h>
#else
# define BOUNDS_CHECKING_OFF_DURING(stmt) stmt
# define BOUNDS_CHECKING_OFF_IN_EXPR(expr) (expr)
#endif
#if !defined(LZO_HAVE_CONFIG_H)
# include <stddef.h>
# include <string.h>
# if !defined(NO_STDLIB_H)
# include <stdlib.h>
# endif
# define HAVE_MEMCMP
# define HAVE_MEMCPY
# define HAVE_MEMMOVE
# define HAVE_MEMSET
#else
# include <sys/types.h>
# if defined(HAVE_STDDEF_H)
# include <stddef.h>
# endif
# if defined(STDC_HEADERS)
# include <string.h>
# include <stdlib.h>
# endif
#endif
#if defined(__LZO_DOS16) || defined(__LZO_WIN16)
# define HAVE_MALLOC_H
# define HAVE_HALLOC
#endif
#undef NDEBUG
#if !defined(LZO_DEBUG)
# define NDEBUG
#endif
#if defined(LZO_DEBUG) || !defined(NDEBUG)
# if !defined(NO_STDIO_H)
# include <stdio.h>
# endif
#endif
#include <assert.h>
#if !defined(LZO_COMPILE_TIME_ASSERT)
# define LZO_COMPILE_TIME_ASSERT(expr) \
{ typedef int __lzo_compile_time_assert_fail[1 - 2 * !(expr)]; }
#endif
#if !defined(LZO_UNUSED)
# if 1
# define LZO_UNUSED(var) ((void)&var)
# elif 0
# define LZO_UNUSED(var) { typedef int __lzo_unused[sizeof(var) ? 2 : 1]; }
# else
# define LZO_UNUSED(parm) (parm = parm)
# endif
#endif
#if !defined(__inline__) && !defined(__GNUC__)
# if defined(__cplusplus)
# define __inline__ inline
# else
# define __inline__
# endif
#endif
#if defined(NO_MEMCMP)
# undef HAVE_MEMCMP
#endif
#if 0
# define LZO_BYTE(x) ((unsigned char) (x))
#else
# define LZO_BYTE(x) ((unsigned char) ((x) & 0xff))
#endif
#define LZO_MAX(a,b) ((a) >= (b) ? (a) : (b))
#define LZO_MIN(a,b) ((a) <= (b) ? (a) : (b))
#define LZO_MAX3(a,b,c) ((a) >= (b) ? LZO_MAX(a,c) : LZO_MAX(b,c))
#define LZO_MIN3(a,b,c) ((a) <= (b) ? LZO_MIN(a,c) : LZO_MIN(b,c))
#define lzo_sizeof(type) ((lzo_uint) (sizeof(type)))
#define LZO_HIGH(array) ((lzo_uint) (sizeof(array)/sizeof(*(array))))
#define LZO_SIZE(bits) (1u << (bits))
#define LZO_MASK(bits) (LZO_SIZE(bits) - 1)
#define LZO_LSIZE(bits) (1ul << (bits))
#define LZO_LMASK(bits) (LZO_LSIZE(bits) - 1)
#define LZO_USIZE(bits) ((lzo_uint) 1 << (bits))
#define LZO_UMASK(bits) (LZO_USIZE(bits) - 1)
#define LZO_STYPE_MAX(b) (((1l << (8*(b)-2)) - 1l) + (1l << (8*(b)-2)))
#define LZO_UTYPE_MAX(b) (((1ul << (8*(b)-1)) - 1ul) + (1ul << (8*(b)-1)))
#if !defined(SIZEOF_UNSIGNED)
# if (UINT_MAX == 0xffff)
# define SIZEOF_UNSIGNED 2
# elif (UINT_MAX == LZO_0xffffffffL)
# define SIZEOF_UNSIGNED 4
# elif (UINT_MAX >= LZO_0xffffffffL)
# define SIZEOF_UNSIGNED 8
# else
# error "SIZEOF_UNSIGNED"
# endif
#endif
#if !defined(SIZEOF_UNSIGNED_LONG)
# if (ULONG_MAX == LZO_0xffffffffL)
# define SIZEOF_UNSIGNED_LONG 4
# elif (ULONG_MAX >= LZO_0xffffffffL)
# define SIZEOF_UNSIGNED_LONG 8
# else
# error "SIZEOF_UNSIGNED_LONG"
# endif
#endif
#if !defined(SIZEOF_SIZE_T)
# define SIZEOF_SIZE_T SIZEOF_UNSIGNED
#endif
#if !defined(SIZE_T_MAX)
# define SIZE_T_MAX LZO_UTYPE_MAX(SIZEOF_SIZE_T)
#endif
#if 1 && defined(__LZO_i386) && (UINT_MAX == LZO_0xffffffffL)
# if !defined(LZO_UNALIGNED_OK_2) && (USHRT_MAX == 0xffff)
# define LZO_UNALIGNED_OK_2
# endif
# if !defined(LZO_UNALIGNED_OK_4) && (LZO_UINT32_MAX == LZO_0xffffffffL)
# define LZO_UNALIGNED_OK_4
# endif
#endif
#if defined(LZO_UNALIGNED_OK_2) || defined(LZO_UNALIGNED_OK_4)
# if !defined(LZO_UNALIGNED_OK)
# define LZO_UNALIGNED_OK
# endif
#endif
#if defined(__LZO_NO_UNALIGNED)
# undef LZO_UNALIGNED_OK
# undef LZO_UNALIGNED_OK_2
# undef LZO_UNALIGNED_OK_4
#endif
#if defined(LZO_UNALIGNED_OK_2) && (USHRT_MAX != 0xffff)
# error "LZO_UNALIGNED_OK_2 must not be defined on this system"
#endif
#if defined(LZO_UNALIGNED_OK_4) && (LZO_UINT32_MAX != LZO_0xffffffffL)
# error "LZO_UNALIGNED_OK_4 must not be defined on this system"
#endif
#if defined(__LZO_NO_ALIGNED)
# undef LZO_ALIGNED_OK_4
#endif
#if defined(LZO_ALIGNED_OK_4) && (LZO_UINT32_MAX != LZO_0xffffffffL)
# error "LZO_ALIGNED_OK_4 must not be defined on this system"
#endif
#define LZO_LITTLE_ENDIAN 1234
#define LZO_BIG_ENDIAN 4321
#define LZO_PDP_ENDIAN 3412
#if !defined(LZO_BYTE_ORDER)
# if defined(MFX_BYTE_ORDER)
# define LZO_BYTE_ORDER MFX_BYTE_ORDER
# elif defined(__LZO_i386)
# define LZO_BYTE_ORDER LZO_LITTLE_ENDIAN
# elif defined(BYTE_ORDER)
# define LZO_BYTE_ORDER BYTE_ORDER
# elif defined(__BYTE_ORDER)
# define LZO_BYTE_ORDER __BYTE_ORDER
# endif
#endif
#if defined(LZO_BYTE_ORDER)
# if (LZO_BYTE_ORDER != LZO_LITTLE_ENDIAN) && \
(LZO_BYTE_ORDER != LZO_BIG_ENDIAN)
# error "invalid LZO_BYTE_ORDER"
# endif
#endif
#if defined(LZO_UNALIGNED_OK) && !defined(LZO_BYTE_ORDER)
# error "LZO_BYTE_ORDER is not defined"
#endif
#define LZO_OPTIMIZE_GNUC_i386_IS_BUGGY
#if defined(NDEBUG) && !defined(LZO_DEBUG) && !defined(__LZO_CHECKER)
# if defined(__GNUC__) && defined(__i386__)
# if !defined(LZO_OPTIMIZE_GNUC_i386_IS_BUGGY)
# define LZO_OPTIMIZE_GNUC_i386
# endif
# endif
#endif
__LZO_EXTERN_C int __lzo_init_done;
__LZO_EXTERN_C const lzo_byte __lzo_copyright[];
LZO_EXTERN(const lzo_byte *) lzo_copyright();
__LZO_EXTERN_C const lzo_uint32 _lzo_crc32_table[256];
#define _LZO_STRINGIZE(x) #x
#define _LZO_MEXPAND(x) _LZO_STRINGIZE(x)
#define _LZO_CONCAT2(a,b) a ## b
#define _LZO_CONCAT3(a,b,c) a ## b ## c
#define _LZO_CONCAT4(a,b,c,d) a ## b ## c ## d
#define _LZO_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e
#define _LZO_ECONCAT2(a,b) _LZO_CONCAT2(a,b)
#define _LZO_ECONCAT3(a,b,c) _LZO_CONCAT3(a,b,c)
#define _LZO_ECONCAT4(a,b,c,d) _LZO_CONCAT4(a,b,c,d)
#define _LZO_ECONCAT5(a,b,c,d,e) _LZO_CONCAT5(a,b,c,d,e)
#ifndef __LZO_PTR_H
#define __LZO_PTR_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__LZO_DOS16) || defined(__LZO_WIN16)
# include <dos.h>
# if 1 && defined(__WATCOMC__)
# include <i86.h>
__LZO_EXTERN_C unsigned char _HShift;
# define __LZO_HShift _HShift
# elif 1 && defined(_MSC_VER)
__LZO_EXTERN_C unsigned short __near _AHSHIFT;
# define __LZO_HShift ((unsigned) &_AHSHIFT)
# elif defined(__LZO_WIN16)
# define __LZO_HShift 3
# else
# define __LZO_HShift 12
# endif
# if !defined(_FP_SEG) && defined(FP_SEG)
# define _FP_SEG FP_SEG
# endif
# if !defined(_FP_OFF) && defined(FP_OFF)
# define _FP_OFF FP_OFF
# endif
#endif
#if !defined(lzo_ptrdiff_t)
# if (UINT_MAX >= LZO_0xffffffffL)
typedef ptrdiff_t lzo_ptrdiff_t;
# else
typedef long lzo_ptrdiff_t;
# endif
#endif
#if !defined(__LZO_HAVE_PTR_T)
# if defined(lzo_ptr_t)
# define __LZO_HAVE_PTR_T
# endif
#endif
#if !defined(__LZO_HAVE_PTR_T)
# if defined(_WIN64)
typedef unsigned __int64 lzo_ptr_t;
typedef signed __int64 lzo_sptr_r;
# define __LZO_HAVE_PTR_T
# endif
#endif
#if !defined(__LZO_HAVE_PTR_T)
# if defined(SIZEOF_CHAR_P) && defined(SIZEOF_UNSIGNED_LONG)
# if (SIZEOF_CHAR_P == SIZEOF_UNSIGNED_LONG)
typedef unsigned long lzo_ptr_t;
typedef long lzo_sptr_t;
# define __LZO_HAVE_PTR_T
# endif
# endif
#endif
#if !defined(__LZO_HAVE_PTR_T)
# if defined(SIZEOF_CHAR_P) && defined(SIZEOF_UNSIGNED)
# if (SIZEOF_CHAR_P == SIZEOF_UNSIGNED)
typedef unsigned int lzo_ptr_t;
typedef int lzo_sptr_t;
# define __LZO_HAVE_PTR_T
# endif
# endif
#endif
#if !defined(__LZO_HAVE_PTR_T)
# if defined(SIZEOF_CHAR_P) && defined(SIZEOF_UNSIGNED_SHORT)
# if (SIZEOF_CHAR_P == SIZEOF_UNSIGNED_SHORT)
typedef unsigned short lzo_ptr_t;
typedef short lzo_sptr_t;
# define __LZO_HAVE_PTR_T
# endif
# endif
#endif
#if !defined(__LZO_HAVE_PTR_T)
# if defined(LZO_HAVE_CONFIG_H) || defined(SIZEOF_CHAR_P)
# error "no suitable type for lzo_ptr_t"
# else
typedef unsigned long lzo_ptr_t;
typedef long lzo_sptr_t;
# define __LZO_HAVE_PTR_T
# endif
#endif
#if defined(__LZO_DOS16) || defined(__LZO_WIN16)
#define PTR(a) ((lzo_bytep) (a))
#define PTR_ALIGNED_4(a) ((_FP_OFF(a) & 3) == 0)
#define PTR_ALIGNED2_4(a,b) (((_FP_OFF(a) | _FP_OFF(b)) & 3) == 0)
#else
#define PTR(a) ((lzo_ptr_t) (a))
#define PTR_LINEAR(a) PTR(a)
#define PTR_ALIGNED_4(a) ((PTR_LINEAR(a) & 3) == 0)
#define PTR_ALIGNED_8(a) ((PTR_LINEAR(a) & 7) == 0)
#define PTR_ALIGNED2_4(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 3) == 0)
#define PTR_ALIGNED2_8(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 7) == 0)
#endif
#define PTR_LT(a,b) (PTR(a) < PTR(b))
#define PTR_GE(a,b) (PTR(a) >= PTR(b))
#define PTR_DIFF(a,b) ((lzo_ptrdiff_t) (PTR(a) - PTR(b)))
#define pd(a,b) ((lzo_uint) ((a)-(b)))
LZO_EXTERN(lzo_ptr_t)
__lzo_ptr_linear(const lzo_voidp ptr);
typedef union
{
char a_char;
unsigned char a_uchar;
short a_short;
unsigned short a_ushort;
int a_int;
unsigned int a_uint;
long a_long;
unsigned long a_ulong;
lzo_int a_lzo_int;
lzo_uint a_lzo_uint;
lzo_int32 a_lzo_int32;
lzo_uint32 a_lzo_uint32;
ptrdiff_t a_ptrdiff_t;
lzo_ptrdiff_t a_lzo_ptrdiff_t;
lzo_ptr_t a_lzo_ptr_t;
lzo_voidp a_lzo_voidp;
void * a_void_p;
lzo_bytep a_lzo_bytep;
lzo_bytepp a_lzo_bytepp;
lzo_uintp a_lzo_uintp;
lzo_uint * a_lzo_uint_p;
lzo_uint32p a_lzo_uint32p;
lzo_uint32 * a_lzo_uint32_p;
unsigned char * a_uchar_p;
char * a_char_p;
}
lzo_full_align_t;
#ifdef __cplusplus
}
#endif
#endif
#define LZO_DETERMINISTIC
#define LZO_DICT_USE_PTR
#if defined(__LZO_DOS16) || defined(__LZO_WIN16) || defined(__LZO_STRICT_16BIT)
# undef LZO_DICT_USE_PTR
#endif
#if defined(LZO_DICT_USE_PTR)
# define lzo_dict_t const lzo_bytep
# define lzo_dict_p lzo_dict_t __LZO_MMODEL *
#else
# define lzo_dict_t lzo_uint
# define lzo_dict_p lzo_dict_t __LZO_MMODEL *
#endif
#if !defined(lzo_moff_t)
#define lzo_moff_t lzo_uint
#endif
#endif
#ifndef __LZO_UTIL_H
#define __LZO_UTIL_H
#ifndef __LZO_CONF_H
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if 1 && defined(HAVE_MEMCPY)
#if !defined(__LZO_DOS16) && !defined(__LZO_WIN16)
#define MEMCPY8_DS(dest,src,len) \
memcpy(dest,src,len); \
dest += len; \
src += len
#endif
#endif
#if 0 && !defined(MEMCPY8_DS)
#define MEMCPY8_DS(dest,src,len) \
{ do { \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
len -= 8; \
} while (len > 0); }
#endif
#if !defined(MEMCPY8_DS)
#define MEMCPY8_DS(dest,src,len) \
{ register lzo_uint __l = (len) / 8; \
do { \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
*dest++ = *src++; \
} while (--__l > 0); }
#endif
#define MEMCPY_DS(dest,src,len) \
do *dest++ = *src++; \
while (--len > 0)
#define MEMMOVE_DS(dest,src,len) \
do *dest++ = *src++; \
while (--len > 0)
#if 0 && defined(LZO_OPTIMIZE_GNUC_i386)
#define BZERO8_PTR(s,l,n) \
__asm__ __volatile__( \
"movl %0,%%eax \n" \
"movl %1,%%edi \n" \
"movl %2,%%ecx \n" \
"cld \n" \
"rep \n" \
"stosl %%eax,(%%edi) \n" \
: \
:"g" (0),"g" (s),"g" (n) \
:"eax","edi","ecx", "memory", "cc" \
)
#elif (LZO_UINT_MAX <= SIZE_T_MAX) && defined(HAVE_MEMSET)
#if 1
#define BZERO8_PTR(s,l,n) memset((s),0,(lzo_uint)(l)*(n))
#else
#define BZERO8_PTR(s,l,n) memset((lzo_voidp)(s),0,(lzo_uint)(l)*(n))
#endif
#else
#define BZERO8_PTR(s,l,n) \
lzo_memset((lzo_voidp)(s),0,(lzo_uint)(l)*(n))
#endif
#if 0
#if defined(__GNUC__) && defined(__i386__)
unsigned char lzo_rotr8(unsigned char value, int shift);
extern __inline__ unsigned char lzo_rotr8(unsigned char value, int shift)
{
unsigned char result;
__asm__ __volatile__ ("movb %b1, %b0; rorb %b2, %b0"
: "=a"(result) : "g"(value), "c"(shift));
return result;
}
unsigned short lzo_rotr16(unsigned short value, int shift);
extern __inline__ unsigned short lzo_rotr16(unsigned short value, int shift)
{
unsigned short result;
__asm__ __volatile__ ("movw %b1, %b0; rorw %b2, %b0"
: "=a"(result) : "g"(value), "c"(shift));
return result;
}
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif
/* If you use the LZO library in a product, you *must* keep this
* copyright string in the executable of your product.
*/
const lzo_byte __lzo_copyright[] =
#if !defined(__LZO_IN_MINLZO)
LZO_VERSION_STRING;
#else
"\n\n\n"
"LZO real-time data compression library.\n"
"Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002 Markus Franz Xaver Johannes Oberhumer\n"
"<markus.oberhumer@jk.uni-linz.ac.at>\n"
"http://www.oberhumer.com/opensource/lzo/\n"
"\n"
"LZO version: v" LZO_VERSION_STRING ", " LZO_VERSION_DATE "\n"
"LZO build date: " __DATE__ " " __TIME__ "\n\n"
"LZO special compilation options:\n"
#ifdef __cplusplus
" __cplusplus\n"
#endif
#if defined(__PIC__)
" __PIC__\n"
#elif defined(__pic__)
" __pic__\n"
#endif
#if (UINT_MAX < LZO_0xffffffffL)
" 16BIT\n"
#endif
#if defined(__LZO_STRICT_16BIT)
" __LZO_STRICT_16BIT\n"
#endif
#if (UINT_MAX > LZO_0xffffffffL)
" UINT_MAX=" _LZO_MEXPAND(UINT_MAX) "\n"
#endif
#if (ULONG_MAX > LZO_0xffffffffL)
" ULONG_MAX=" _LZO_MEXPAND(ULONG_MAX) "\n"
#endif
#if defined(LZO_BYTE_ORDER)
" LZO_BYTE_ORDER=" _LZO_MEXPAND(LZO_BYTE_ORDER) "\n"
#endif
#if defined(LZO_UNALIGNED_OK_2)
" LZO_UNALIGNED_OK_2\n"
#endif
#if defined(LZO_UNALIGNED_OK_4)
" LZO_UNALIGNED_OK_4\n"
#endif
#if defined(LZO_ALIGNED_OK_4)
" LZO_ALIGNED_OK_4\n"
#endif
#if defined(LZO_DICT_USE_PTR)
" LZO_DICT_USE_PTR\n"
#endif
#if defined(__LZO_QUERY_COMPRESS)
" __LZO_QUERY_COMPRESS\n"
#endif
#if defined(__LZO_QUERY_DECOMPRESS)
" __LZO_QUERY_DECOMPRESS\n"
#endif
#if defined(__LZO_IN_MINILZO)
" __LZO_IN_MINILZO\n"
#endif
"\n\n"
"$Id: LZO " LZO_VERSION_STRING " built " __DATE__ " " __TIME__
#if defined(__GNUC__) && defined(__VERSION__)
" by gcc " __VERSION__
#elif defined(__BORLANDC__)
" by Borland C " _LZO_MEXPAND(__BORLANDC__)
#elif defined(_MSC_VER)
" by Microsoft C " _LZO_MEXPAND(_MSC_VER)
#elif defined(__PUREC__)
" by Pure C " _LZO_MEXPAND(__PUREC__)
#elif defined(__SC__)
" by Symantec C " _LZO_MEXPAND(__SC__)
#elif defined(__TURBOC__)
" by Turbo C " _LZO_MEXPAND(__TURBOC__)
#elif defined(__WATCOMC__)
" by Watcom C " _LZO_MEXPAND(__WATCOMC__)
#endif
" $\n"
"$Copyright: LZO (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002 Markus Franz Xaver Johannes Oberhumer $\n";
#endif
#define LZO_BASE 65521u
#define LZO_NMAX 5552
#define LZO_DO1(buf,i) {s1 += buf[i]; s2 += s1;}
#define LZO_DO2(buf,i) LZO_DO1(buf,i); LZO_DO1(buf,i+1);
#define LZO_DO4(buf,i) LZO_DO2(buf,i); LZO_DO2(buf,i+2);
#define LZO_DO8(buf,i) LZO_DO4(buf,i); LZO_DO4(buf,i+4);
#define LZO_DO16(buf,i) LZO_DO8(buf,i); LZO_DO8(buf,i+8);
LZO_PUBLIC(lzo_uint32)
lzo_adler32(lzo_uint32 adler, const lzo_byte *buf, lzo_uint len)
{
lzo_uint32 s1 = adler & 0xffff;
lzo_uint32 s2 = (adler >> 16) & 0xffff;
int k;
if (buf == NULL)
return 1;
while (len > 0)
{
k = len < LZO_NMAX ? (int) len : LZO_NMAX;
len -= k;
if (k >= 16) do
{
LZO_DO16(buf,0);
buf += 16;
k -= 16;
} while (k >= 16);
if (k != 0) do
{
s1 += *buf++;
s2 += s1;
} while (--k > 0);
s1 %= LZO_BASE;
s2 %= LZO_BASE;
}
return (s2 << 16) | s1;
}
#if 0
# define IS_SIGNED(type) (((type) (1ul << (8 * sizeof(type) - 1))) < 0)
# define IS_UNSIGNED(type) (((type) (1ul << (8 * sizeof(type) - 1))) > 0)
#else
# define IS_SIGNED(type) (((type) (-1)) < ((type) 0))
# define IS_UNSIGNED(type) (((type) (-1)) > ((type) 0))
#endif
#define IS_POWER_OF_2(x) (((x) & ((x) - 1)) == 0)
// static lzo_bool schedule_insns_bug();
// static lzo_bool strength_reduce_bug(int *);
#if 0 || defined(LZO_DEBUG)
#include <stdio.h>
static lzo_bool __lzo_assert_fail(const char *s, unsigned line)
{
#if defined(__palmos__)
printf("LZO assertion failed in line %u: '%s'\n",line,s);
#else
fprintf(stderr,"LZO assertion failed in line %u: '%s'\n",line,s);
#endif
return 0;
}
# define __lzo_assert(x) ((x) ? 1 : __lzo_assert_fail(#x,__LINE__))
#else
# define __lzo_assert(x) ((x) ? 1 : 0)
#endif
#undef COMPILE_TIME_ASSERT
#if 0
# define COMPILE_TIME_ASSERT(expr) r &= __lzo_assert(expr)
#else
# define COMPILE_TIME_ASSERT(expr) LZO_COMPILE_TIME_ASSERT(expr)
#endif
#define do_compress _lzo1x_1_do_compress
#define LZO_NEED_DICT_H
#define D_BITS 12
#define D_INDEX1(d,p) d = DM((0x21*DX3(p,5,5,6)) >> 5)
#define D_INDEX2(d,p) d = (d & (D_MASK & 0x7ff)) ^ (D_HIGH | 0x1f)
#ifndef __LZO_CONFIG1X_H
#define __LZO_CONFIG1X_H
#define LZO_EOF_CODE
#undef LZO_DETERMINISTIC
#define M1_MAX_OFFSET 0x0400
#ifndef M2_MAX_OFFSET
#define M2_MAX_OFFSET 0x0800
#endif
#define M3_MAX_OFFSET 0x4000
#define M4_MAX_OFFSET 0xbfff
#define MX_MAX_OFFSET (M1_MAX_OFFSET + M2_MAX_OFFSET)
#define M1_MIN_LEN 2
#define M1_MAX_LEN 2
#define M2_MIN_LEN 3
#ifndef M2_MAX_LEN
#define M2_MAX_LEN 8
#endif
#define M3_MIN_LEN 3
#define M3_MAX_LEN 33
#define M4_MIN_LEN 3
#define M4_MAX_LEN 9
#define M1_MARKER 0
#define M2_MARKER 64
#define M3_MARKER 32
#define M4_MARKER 16
#ifndef MIN_LOOKAHEAD
#define MIN_LOOKAHEAD (M2_MAX_LEN + 1)
#endif
#if defined(LZO_NEED_DICT_H)
#ifndef LZO_HASH
#define LZO_HASH LZO_HASH_LZO_INCREMENTAL_B
#endif
#define DL_MIN_LEN M2_MIN_LEN
#ifndef __LZO_DICT_H
#define __LZO_DICT_H
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(D_BITS) && defined(DBITS)
# define D_BITS DBITS
#endif
#if !defined(D_BITS)
# error "D_BITS is not defined"
#endif
#if (D_BITS < 16)
# define D_SIZE LZO_SIZE(D_BITS)
# define D_MASK LZO_MASK(D_BITS)
#else
# define D_SIZE LZO_USIZE(D_BITS)
# define D_MASK LZO_UMASK(D_BITS)
#endif
#define D_HIGH ((D_MASK >> 1) + 1)
#if !defined(DD_BITS)
# define DD_BITS 0
#endif
#define DD_SIZE LZO_SIZE(DD_BITS)
#define DD_MASK LZO_MASK(DD_BITS)
#if !defined(DL_BITS)
# define DL_BITS (D_BITS - DD_BITS)
#endif
#if (DL_BITS < 16)
# define DL_SIZE LZO_SIZE(DL_BITS)
# define DL_MASK LZO_MASK(DL_BITS)
#else
# define DL_SIZE LZO_USIZE(DL_BITS)
# define DL_MASK LZO_UMASK(DL_BITS)
#endif
#if (D_BITS != DL_BITS + DD_BITS)
# error "D_BITS does not match"
#endif
#if (D_BITS < 8 || D_BITS > 18)
# error "invalid D_BITS"
#endif
#if (DL_BITS < 8 || DL_BITS > 20)
# error "invalid DL_BITS"
#endif
#if (DD_BITS < 0 || DD_BITS > 6)
# error "invalid DD_BITS"
#endif
#if !defined(DL_MIN_LEN)
# define DL_MIN_LEN 3
#endif
#if !defined(DL_SHIFT)
# define DL_SHIFT ((DL_BITS + (DL_MIN_LEN - 1)) / DL_MIN_LEN)
#endif
#define LZO_HASH_GZIP 1
#define LZO_HASH_GZIP_INCREMENTAL 2
#define LZO_HASH_LZO_INCREMENTAL_A 3
#define LZO_HASH_LZO_INCREMENTAL_B 4
#if !defined(LZO_HASH)
# error "choose a hashing strategy"
#endif
#if (DL_MIN_LEN == 3)
# define _DV2_A(p,shift1,shift2) \
(((( (lzo_uint32)((p)[0]) << shift1) ^ (p)[1]) << shift2) ^ (p)[2])
# define _DV2_B(p,shift1,shift2) \
(((( (lzo_uint32)((p)[2]) << shift1) ^ (p)[1]) << shift2) ^ (p)[0])
# define _DV3_B(p,shift1,shift2,shift3) \
((_DV2_B((p)+1,shift1,shift2) << (shift3)) ^ (p)[0])
#elif (DL_MIN_LEN == 2)
# define _DV2_A(p,shift1,shift2) \
(( (lzo_uint32)(p[0]) << shift1) ^ p[1])
# define _DV2_B(p,shift1,shift2) \
(( (lzo_uint32)(p[1]) << shift1) ^ p[2])
#else
# error "invalid DL_MIN_LEN"
#endif
#define _DV_A(p,shift) _DV2_A(p,shift,shift)
#define _DV_B(p,shift) _DV2_B(p,shift,shift)
#define DA2(p,s1,s2) \
(((((lzo_uint32)((p)[2]) << (s2)) + (p)[1]) << (s1)) + (p)[0])
#define DS2(p,s1,s2) \
(((((lzo_uint32)((p)[2]) << (s2)) - (p)[1]) << (s1)) - (p)[0])
#define DX2(p,s1,s2) \
(((((lzo_uint32)((p)[2]) << (s2)) ^ (p)[1]) << (s1)) ^ (p)[0])
#define DA3(p,s1,s2,s3) ((DA2((p)+1,s2,s3) << (s1)) + (p)[0])
#define DS3(p,s1,s2,s3) ((DS2((p)+1,s2,s3) << (s1)) - (p)[0])
#define DX3(p,s1,s2,s3) ((DX2((p)+1,s2,s3) << (s1)) ^ (p)[0])
#define DMS(v,s) ((lzo_uint) (((v) & (D_MASK >> (s))) << (s)))
#define DM(v) DMS(v,0)
#if (LZO_HASH == LZO_HASH_GZIP)
# define _DINDEX(dv,p) (_DV_A((p),DL_SHIFT))
#elif (LZO_HASH == LZO_HASH_GZIP_INCREMENTAL)
# define __LZO_HASH_INCREMENTAL
# define DVAL_FIRST(dv,p) dv = _DV_A((p),DL_SHIFT)
# define DVAL_NEXT(dv,p) dv = (((dv) << DL_SHIFT) ^ p[2])
# define _DINDEX(dv,p) (dv)
# define DVAL_LOOKAHEAD DL_MIN_LEN
#elif (LZO_HASH == LZO_HASH_LZO_INCREMENTAL_A)
# define __LZO_HASH_INCREMENTAL
# define DVAL_FIRST(dv,p) dv = _DV_A((p),5)
# define DVAL_NEXT(dv,p) \
dv ^= (lzo_uint32)(p[-1]) << (2*5); dv = (((dv) << 5) ^ p[2])
# define _DINDEX(dv,p) ((0x9f5f * (dv)) >> 5)
# define DVAL_LOOKAHEAD DL_MIN_LEN
#elif (LZO_HASH == LZO_HASH_LZO_INCREMENTAL_B)
# define __LZO_HASH_INCREMENTAL
# define DVAL_FIRST(dv,p) dv = _DV_B((p),5)
# define DVAL_NEXT(dv,p) \
dv ^= p[-1]; dv = (((dv) >> 5) ^ ((lzo_uint32)(p[2]) << (2*5)))
# define _DINDEX(dv,p) ((0x9f5f * (dv)) >> 5)
# define DVAL_LOOKAHEAD DL_MIN_LEN
#else
# error "choose a hashing strategy"
#endif
#ifndef DINDEX
#define DINDEX(dv,p) ((lzo_uint)((_DINDEX(dv,p)) & DL_MASK) << DD_BITS)
#endif
#if !defined(DINDEX1) && defined(D_INDEX1)
#define DINDEX1 D_INDEX1
#endif
#if !defined(DINDEX2) && defined(D_INDEX2)
#define DINDEX2 D_INDEX2
#endif
#if !defined(__LZO_HASH_INCREMENTAL)
# define DVAL_FIRST(dv,p) ((void) 0)
# define DVAL_NEXT(dv,p) ((void) 0)
# define DVAL_LOOKAHEAD 0
#endif
#if !defined(DVAL_ASSERT)
#if defined(__LZO_HASH_INCREMENTAL) && !defined(NDEBUG)
static void DVAL_ASSERT(lzo_uint32 dv, const lzo_byte *p)
{
lzo_uint32 df;
DVAL_FIRST(df,(p));
assert(DINDEX(dv,p) == DINDEX(df,p));
}
#else
# define DVAL_ASSERT(dv,p) ((void) 0)
#endif
#endif
#if defined(LZO_DICT_USE_PTR)
# define DENTRY(p,in) (p)
# define GINDEX(m_pos,m_off,dict,dindex,in) m_pos = dict[dindex]
#else
# define DENTRY(p,in) ((lzo_uint) ((p)-(in)))
# define GINDEX(m_pos,m_off,dict,dindex,in) m_off = dict[dindex]
#endif
#if (DD_BITS == 0)
# define UPDATE_D(dict,drun,dv,p,in) dict[ DINDEX(dv,p) ] = DENTRY(p,in)
# define UPDATE_I(dict,drun,index,p,in) dict[index] = DENTRY(p,in)
# define UPDATE_P(ptr,drun,p,in) (ptr)[0] = DENTRY(p,in)
#else
# define UPDATE_D(dict,drun,dv,p,in) \
dict[ DINDEX(dv,p) + drun++ ] = DENTRY(p,in); drun &= DD_MASK
# define UPDATE_I(dict,drun,index,p,in) \
dict[ (index) + drun++ ] = DENTRY(p,in); drun &= DD_MASK
# define UPDATE_P(ptr,drun,p,in) \
(ptr) [ drun++ ] = DENTRY(p,in); drun &= DD_MASK
#endif
#if defined(LZO_DICT_USE_PTR)
#define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \
(m_pos == NULL || (m_off = (lzo_moff_t) (ip - m_pos)) > max_offset)
#define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \
(BOUNDS_CHECKING_OFF_IN_EXPR( \
(PTR_LT(m_pos,in) || \
(m_off = (lzo_moff_t) PTR_DIFF(ip,m_pos)) <= 0 || \
m_off > max_offset) ))
#else
#define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \
(m_off == 0 || \
((m_off = (lzo_moff_t) ((ip)-(in)) - m_off) > max_offset) || \
(m_pos = (ip) - (m_off), 0) )
#define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \
((lzo_moff_t) ((ip)-(in)) <= m_off || \
((m_off = (lzo_moff_t) ((ip)-(in)) - m_off) > max_offset) || \
(m_pos = (ip) - (m_off), 0) )
#endif
#if defined(LZO_DETERMINISTIC)
# define LZO_CHECK_MPOS LZO_CHECK_MPOS_DET
#else
# define LZO_CHECK_MPOS LZO_CHECK_MPOS_NON_DET
#endif
#ifdef __cplusplus
}
#endif
#endif
#endif
#endif
#define DO_COMPRESS lzo1x_1_compress
static
lzo_uint do_compress ( const lzo_byte *in , lzo_uint in_len,
lzo_byte *out, lzo_uintp out_len,
lzo_voidp wrkmem )
{
register const lzo_byte *ip;
lzo_byte *op;
const lzo_byte * const in_end = in + in_len;
const lzo_byte * const ip_end = in + in_len - M2_MAX_LEN - 5;
const lzo_byte *ii;
lzo_dict_p const dict = (lzo_dict_p) wrkmem;
op = out;
ip = in;
ii = ip;
ip += 4;
for (;;)
{
register const lzo_byte *m_pos;
lzo_moff_t m_off;
lzo_ptrdiff_t m_len;
lzo_uint dindex;
DINDEX1(dindex,ip);
GINDEX(m_pos,m_off,dict,dindex,in);
if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET))
goto literal;
if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3])
goto try_match;
DINDEX2(dindex,ip);
GINDEX(m_pos,m_off,dict,dindex,in);
if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET))
goto literal;
if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3])
goto try_match;
goto literal;
try_match:
#if 1 && defined(LZO_UNALIGNED_OK_2)
if (* (const lzo_ushortp) m_pos != * (const lzo_ushortp) ip)
#else
if (m_pos[0] != ip[0] || m_pos[1] != ip[1])
#endif
{
}
else
{
if (m_pos[2] == ip[2])
{
goto match;
}
}
literal:
UPDATE_I(dict,0,dindex,ip,in);
++ip;
if (ip >= ip_end)
break;
continue;
match:
UPDATE_I(dict,0,dindex,ip,in);
if (pd(ip,ii) > 0)
{
register lzo_uint t = pd(ip,ii);
if (t <= 3)
{
assert(op - 2 > out);
op[-2] |= LZO_BYTE(t);
}
else if (t <= 18)
*op++ = LZO_BYTE(t - 3);
else
{
register lzo_uint tt = t - 18;
*op++ = 0;
while (tt > 255)
{
tt -= 255;
*op++ = 0;
}
assert(tt > 0);
*op++ = LZO_BYTE(tt);
}
do *op++ = *ii++; while (--t > 0);
}
assert(ii == ip);
ip += 3;
if (m_pos[3] != *ip++ || m_pos[4] != *ip++ || m_pos[5] != *ip++ ||
m_pos[6] != *ip++ || m_pos[7] != *ip++ || m_pos[8] != *ip++) {
--ip;
m_len = ip - ii;
assert(m_len >= 3); assert(m_len <= M2_MAX_LEN);
if (m_off <= M2_MAX_OFFSET)
{
m_off -= 1;
*op++ = LZO_BYTE(((m_len - 1) << 5) | ((m_off & 7) << 2));
*op++ = LZO_BYTE(m_off >> 3);
}
else if (m_off <= M3_MAX_OFFSET)
{
m_off -= 1;
*op++ = LZO_BYTE(M3_MARKER | (m_len - 2));
goto m3_m4_offset;
}
else
{
m_off -= 0x4000;
assert(m_off > 0); assert(m_off <= 0x7fff);
*op++ = LZO_BYTE(M4_MARKER |
((m_off & 0x4000) >> 11) | (m_len - 2));
goto m3_m4_offset;
}
}
else
{
{
const lzo_byte *end = in_end;
const lzo_byte *m = m_pos + M2_MAX_LEN + 1;
while (ip < end && *m == *ip)
m++, ip++;
m_len = (ip - ii);
}
assert(m_len > M2_MAX_LEN);
if (m_off <= M3_MAX_OFFSET)
{
m_off -= 1;
if (m_len <= 33)
*op++ = LZO_BYTE(M3_MARKER | (m_len - 2));
else
{
m_len -= 33;
*op++ = M3_MARKER | 0;
goto m3_m4_len;
}
}
else
{
m_off -= 0x4000;
assert(m_off > 0); assert(m_off <= 0x7fff);
if (m_len <= M4_MAX_LEN)
*op++ = LZO_BYTE(M4_MARKER |
((m_off & 0x4000) >> 11) | (m_len - 2));
else
{
m_len -= M4_MAX_LEN;
*op++ = LZO_BYTE(M4_MARKER | ((m_off & 0x4000) >> 11));
m3_m4_len:
while (m_len > 255)
{
m_len -= 255;
*op++ = 0;
}
assert(m_len > 0);
*op++ = LZO_BYTE(m_len);
}
}
m3_m4_offset:
*op++ = LZO_BYTE((m_off & 63) << 2);
*op++ = LZO_BYTE(m_off >> 6);
}
ii = ip;
if (ip >= ip_end)
break;
}
*out_len = (lzo_uint)(op - out);
return pd(in_end,ii);
}
LZO_PUBLIC(int)
DO_COMPRESS ( const lzo_byte *in , lzo_uint in_len,
lzo_byte *out, lzo_uintp out_len,
lzo_voidp wrkmem )
{
lzo_byte *op = out;
lzo_uint t;
if (in_len <= M2_MAX_LEN + 5)
t = in_len;
else
{
t = do_compress(in,in_len,op,out_len,wrkmem);
op += *out_len;
}
if (t > 0)
{
const lzo_byte *ii = in + in_len - t;
if (op == out && t <= 238)
*op++ = LZO_BYTE(17 + t);
else if (t <= 3)
op[-2] |= LZO_BYTE(t);
else if (t <= 18)
*op++ = LZO_BYTE(t - 3);
else
{
lzo_uint tt = t - 18;
*op++ = 0;
while (tt > 255)
{
tt -= 255;
*op++ = 0;
}
assert(tt > 0);
*op++ = LZO_BYTE(tt);
}
do *op++ = *ii++; while (--t > 0);
}
*op++ = M4_MARKER | 1;
*op++ = 0;
*op++ = 0;
*out_len = (lzo_uint)(op - out);
return LZO_E_OK;
}
#undef do_compress
#undef DO_COMPRESS
#undef LZO_HASH
#undef LZO_TEST_DECOMPRESS_OVERRUN
#undef LZO_TEST_DECOMPRESS_OVERRUN_INPUT
#undef LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT
#undef LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND
#undef DO_DECOMPRESS
#define DO_DECOMPRESS lzo1x_decompress
#if defined(LZO_TEST_DECOMPRESS_OVERRUN)
# if !defined(LZO_TEST_DECOMPRESS_OVERRUN_INPUT)
# define LZO_TEST_DECOMPRESS_OVERRUN_INPUT 2
# endif
# if !defined(LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT)
# define LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT 2
# endif
# if !defined(LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND)
# define LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND
# endif
#endif
#undef TEST_IP
#undef TEST_OP
#undef TEST_LOOKBEHIND
#undef NEED_IP
#undef NEED_OP
#undef HAVE_TEST_IP
#undef HAVE_TEST_OP
#undef HAVE_NEED_IP
#undef HAVE_NEED_OP
#undef HAVE_ANY_IP
#undef HAVE_ANY_OP
#if defined(LZO_TEST_DECOMPRESS_OVERRUN_INPUT)
# if (LZO_TEST_DECOMPRESS_OVERRUN_INPUT >= 1)
# define TEST_IP (ip < ip_end)
# endif
# if (LZO_TEST_DECOMPRESS_OVERRUN_INPUT >= 2)
# define NEED_IP(x) \
if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun
# endif
#endif
#if defined(LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT)
# if (LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT >= 1)
# define TEST_OP (op <= op_end)
# endif
# if (LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT >= 2)
# undef TEST_OP
# define NEED_OP(x) \
if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun
# endif
#endif
#if defined(LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND)
# define TEST_LOOKBEHIND(m_pos,out) if (m_pos < out) goto lookbehind_overrun
#else
# define TEST_LOOKBEHIND(m_pos,op) ((void) 0)
#endif
#if !defined(LZO_EOF_CODE) && !defined(TEST_IP)
# define TEST_IP (ip < ip_end)
#endif
#if defined(TEST_IP)
# define HAVE_TEST_IP
#else
# define TEST_IP 1
#endif
#if defined(TEST_OP)
# define HAVE_TEST_OP
#else
# define TEST_OP 1
#endif
#if defined(NEED_IP)
# define HAVE_NEED_IP
#else
# define NEED_IP(x) ((void) 0)
#endif
#if defined(NEED_OP)
# define HAVE_NEED_OP
#else
# define NEED_OP(x) ((void) 0)
#endif
#if defined(HAVE_TEST_IP) || defined(HAVE_NEED_IP)
# define HAVE_ANY_IP
#endif
#if defined(HAVE_TEST_OP) || defined(HAVE_NEED_OP)
# define HAVE_ANY_OP
#endif
#undef __COPY4
#define __COPY4(dst,src) * (lzo_uint32p)(dst) = * (const lzo_uint32p)(src)
#undef COPY4
#if defined(LZO_UNALIGNED_OK_4)
# define COPY4(dst,src) __COPY4(dst,src)
#elif defined(LZO_ALIGNED_OK_4)
# define COPY4(dst,src) __COPY4((lzo_ptr_t)(dst),(lzo_ptr_t)(src))
#endif
#if defined(DO_DECOMPRESS)
LZO_PUBLIC(int)
DO_DECOMPRESS ( const lzo_byte *in , lzo_uint in_len,
lzo_byte *out, lzo_uintp out_len,
lzo_voidp wrkmem )
#endif
{
register lzo_byte *op;
register const lzo_byte *ip;
register lzo_uint t;
register const lzo_byte *m_pos;
const lzo_byte * const ip_end = in + in_len;
#if defined(HAVE_ANY_OP)
lzo_byte * const op_end = out + *out_len;
#endif
LZO_UNUSED(wrkmem);
*out_len = 0;
op = out;
ip = in;
if (*ip > 17)
{
t = *ip++ - 17;
if (t < 4)
goto match_next;
assert(t > 0); NEED_OP(t); NEED_IP(t+1);
do *op++ = *ip++; while (--t > 0);
goto first_literal_run;
}
while (TEST_IP && TEST_OP)
{
t = *ip++;
if (t >= 16)
goto match;
if (t == 0)
{
NEED_IP(1);
while (*ip == 0)
{
t += 255;
ip++;
NEED_IP(1);
}
t += 15 + *ip++;
}
assert(t > 0); NEED_OP(t+3); NEED_IP(t+4);
#if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4)
#if !defined(LZO_UNALIGNED_OK_4)
if (PTR_ALIGNED2_4(op,ip))
{
#endif
COPY4(op,ip);
op += 4; ip += 4;
if (--t > 0)
{
if (t >= 4)
{
do {
COPY4(op,ip);
op += 4; ip += 4; t -= 4;
} while (t >= 4);
if (t > 0) do *op++ = *ip++; while (--t > 0);
}
else
do *op++ = *ip++; while (--t > 0);
}
#if !defined(LZO_UNALIGNED_OK_4)
}
else
#endif
#endif
#if !defined(LZO_UNALIGNED_OK_4)
{
*op++ = *ip++; *op++ = *ip++; *op++ = *ip++;
do *op++ = *ip++; while (--t > 0);
}
#endif
first_literal_run:
t = *ip++;
if (t >= 16)
goto match;
m_pos = op - (1 + M2_MAX_OFFSET);
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
TEST_LOOKBEHIND(m_pos,out); NEED_OP(3);
*op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos;
goto match_done;
while (TEST_IP && TEST_OP)
{
match:
if (t >= 64)
{
#if defined(LZO1X)
m_pos = op - 1;
m_pos -= (t >> 2) & 7;
m_pos -= *ip++ << 3;
t = (t >> 5) - 1;
#endif
TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1);
goto copy_match;
}
else if (t >= 32)
{
t &= 31;
if (t == 0)
{
NEED_IP(1);
while (*ip == 0)
{
t += 255;
ip++;
NEED_IP(1);
}
t += 31 + *ip++;
}
#if defined(LZO_UNALIGNED_OK_2) && (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN)
m_pos = op - 1;
m_pos -= (* (const lzo_ushortp) ip) >> 2;
#else
m_pos = op - 1;
m_pos -= (ip[0] >> 2) + (ip[1] << 6);
#endif
ip += 2;
}
else if (t >= 16)
{
m_pos = op;
m_pos -= (t & 8) << 11;
t &= 7;
if (t == 0)
{
NEED_IP(1);
while (*ip == 0)
{
t += 255;
ip++;
NEED_IP(1);
}
t += 7 + *ip++;
}
#if defined(LZO_UNALIGNED_OK_2) && (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN)
m_pos -= (* (const lzo_ushortp) ip) >> 2;
#else
m_pos -= (ip[0] >> 2) + (ip[1] << 6);
#endif
ip += 2;
if (m_pos == op)
goto eof_found;
m_pos -= 0x4000;
}
else
{
m_pos = op - 1;
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
TEST_LOOKBEHIND(m_pos,out); NEED_OP(2);
*op++ = *m_pos++; *op++ = *m_pos;
goto match_done;
}
TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1);
#if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4)
#if !defined(LZO_UNALIGNED_OK_4)
if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos))
{
assert((op - m_pos) >= 4);
#else
if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4)
{
#endif
COPY4(op,m_pos);
op += 4; m_pos += 4; t -= 4 - (3 - 1);
do {
COPY4(op,m_pos);
op += 4; m_pos += 4; t -= 4;
} while (t >= 4);
if (t > 0) do *op++ = *m_pos++; while (--t > 0);
}
else
#endif
{
copy_match:
*op++ = *m_pos++; *op++ = *m_pos++;
do *op++ = *m_pos++; while (--t > 0);
}
match_done:
t = ip[-2] & 3;
if (t == 0)
break;
match_next:
assert(t > 0); NEED_OP(t); NEED_IP(t+1);
do *op++ = *ip++; while (--t > 0);
t = *ip++;
}
}
#if defined(HAVE_TEST_IP) || defined(HAVE_TEST_OP)
*out_len = op - out;
return LZO_E_EOF_NOT_FOUND;
#endif
eof_found:
assert(t == 1);
*out_len = (lzo_uint)(op - out);
return (ip == ip_end ? LZO_E_OK :
(ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN));
#if defined(HAVE_NEED_IP)
input_overrun:
*out_len = op - out;
return LZO_E_INPUT_OVERRUN;
#endif
#if defined(HAVE_NEED_OP)
output_overrun:
*out_len = op - out;
return LZO_E_OUTPUT_OVERRUN;
#endif
#if defined(LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND)
lookbehind_overrun:
*out_len = op - out;
return LZO_E_LOOKBEHIND_OVERRUN;
#endif
}
#define LZO_TEST_DECOMPRESS_OVERRUN
#undef DO_DECOMPRESS
#define DO_DECOMPRESS lzo1x_decompress_safe
#if defined(LZO_TEST_DECOMPRESS_OVERRUN)
# if !defined(LZO_TEST_DECOMPRESS_OVERRUN_INPUT)
# define LZO_TEST_DECOMPRESS_OVERRUN_INPUT 2
# endif
# if !defined(LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT)
# define LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT 2
# endif
# if !defined(LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND)
# define LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND
# endif
#endif
#undef TEST_IP
#undef TEST_OP
#undef TEST_LOOKBEHIND
#undef NEED_IP
#undef NEED_OP
#undef HAVE_TEST_IP
#undef HAVE_TEST_OP
#undef HAVE_NEED_IP
#undef HAVE_NEED_OP
#undef HAVE_ANY_IP
#undef HAVE_ANY_OP
#if 0
#if defined(LZO_TEST_DECOMPRESS_OVERRUN_INPUT)
# if (LZO_TEST_DECOMPRESS_OVERRUN_INPUT >= 1)
# define TEST_IP (ip < ip_end)
# endif
# if (LZO_TEST_DECOMPRESS_OVERRUN_INPUT >= 2)
# define NEED_IP(x) \
if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun
# endif
#endif
#if defined(LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT)
# if (LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT >= 1)
# define TEST_OP (op <= op_end)
# endif
# if (LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT >= 2)
# undef TEST_OP
# define NEED_OP(x) \
if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun
# endif
#endif
#if defined(LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND)
# define TEST_LOOKBEHIND(m_pos,out) if (m_pos < out) goto lookbehind_overrun
#else
# define TEST_LOOKBEHIND(m_pos,op) ((void) 0)
#endif
#if !defined(LZO_EOF_CODE) && !defined(TEST_IP)
# define TEST_IP (ip < ip_end)
#endif
#if defined(TEST_IP)
# define HAVE_TEST_IP
#else
# define TEST_IP 1
#endif
#if defined(TEST_OP)
# define HAVE_TEST_OP
#else
# define TEST_OP 1
#endif
#if defined(NEED_IP)
# define HAVE_NEED_IP
#else
# define NEED_IP(x) ((void) 0)
#endif
#if defined(NEED_OP)
# define HAVE_NEED_OP
#else
# define NEED_OP(x) ((void) 0)
#endif
#if defined(HAVE_TEST_IP) || defined(HAVE_NEED_IP)
# define HAVE_ANY_IP
#endif
#if defined(HAVE_TEST_OP) || defined(HAVE_NEED_OP)
# define HAVE_ANY_OP
#endif
#undef __COPY4
#define __COPY4(dst,src) * (lzo_uint32p)(dst) = * (const lzo_uint32p)(src)
#undef COPY4
#if defined(LZO_UNALIGNED_OK_4)
# define COPY4(dst,src) __COPY4(dst,src)
#elif defined(LZO_ALIGNED_OK_4)
# define COPY4(dst,src) __COPY4((lzo_ptr_t)(dst),(lzo_ptr_t)(src))
#endif
#if defined(DO_DECOMPRESS)
LZO_PUBLIC(int)
DO_DECOMPRESS ( const lzo_byte *in , lzo_uint in_len,
lzo_byte *out, lzo_uintp out_len,
lzo_voidp wrkmem )
#endif
{
register lzo_byte *op;
register const lzo_byte *ip;
register lzo_uint t;
register const lzo_byte *m_pos;
const lzo_byte * const ip_end = in + in_len;
#if defined(HAVE_ANY_OP)
lzo_byte * const op_end = out + *out_len;
#endif
LZO_UNUSED(wrkmem);
*out_len = 0;
op = out;
ip = in;
if (*ip > 17)
{
t = *ip++ - 17;
if (t < 4)
goto match_next;
assert(t > 0); NEED_OP(t); NEED_IP(t+1);
do *op++ = *ip++; while (--t > 0);
goto first_literal_run;
}
while (TEST_IP && TEST_OP)
{
t = *ip++;
if (t >= 16)
goto match;
if (t == 0)
{
NEED_IP(1);
while (*ip == 0)
{
t += 255;
ip++;
NEED_IP(1);
}
t += 15 + *ip++;
}
assert(t > 0); NEED_OP(t+3); NEED_IP(t+4);
#if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4)
#if !defined(LZO_UNALIGNED_OK_4)
if (PTR_ALIGNED2_4(op,ip))
{
#endif
COPY4(op,ip);
op += 4; ip += 4;
if (--t > 0)
{
if (t >= 4)
{
do {
COPY4(op,ip);
op += 4; ip += 4; t -= 4;
} while (t >= 4);
if (t > 0) do *op++ = *ip++; while (--t > 0);
}
else
do *op++ = *ip++; while (--t > 0);
}
#if !defined(LZO_UNALIGNED_OK_4)
}
else
#endif
#endif
#if !defined(LZO_UNALIGNED_OK_4)
{
*op++ = *ip++; *op++ = *ip++; *op++ = *ip++;
do *op++ = *ip++; while (--t > 0);
}
#endif
first_literal_run:
t = *ip++;
if (t >= 16)
goto match;
#if defined(LZO1Z)
t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2);
m_pos = op - t;
last_m_off = t;
#else
m_pos = op - (1 + M2_MAX_OFFSET);
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
#endif
TEST_LOOKBEHIND(m_pos,out); NEED_OP(3);
*op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos;
goto match_done;
while (TEST_IP && TEST_OP)
{
match:
if (t >= 64)
{
#if defined(LZO1X)
m_pos = op - 1;
m_pos -= (t >> 2) & 7;
m_pos -= *ip++ << 3;
t = (t >> 5) - 1;
#elif defined(LZO1Y)
m_pos = op - 1;
m_pos -= (t >> 2) & 3;
m_pos -= *ip++ << 2;
t = (t >> 4) - 3;
#elif defined(LZO1Z)
{
lzo_uint off = t & 0x1f;
m_pos = op;
if (off >= 0x1c)
{
assert(last_m_off > 0);
m_pos -= last_m_off;
}
else
{
off = 1 + (off << 6) + (*ip++ >> 2);
m_pos -= off;
last_m_off = off;
}
}
t = (t >> 5) - 1;
#endif
TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1);
goto copy_match;
}
else if (t >= 32)
{
t &= 31;
if (t == 0)
{
NEED_IP(1);
while (*ip == 0)
{
t += 255;
ip++;
NEED_IP(1);
}
t += 31 + *ip++;
}
#if defined(LZO1Z)
{
lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2);
m_pos = op - off;
last_m_off = off;
}
#elif defined(LZO_UNALIGNED_OK_2) && (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN)
m_pos = op - 1;
m_pos -= (* (const lzo_ushortp) ip) >> 2;
#else
m_pos = op - 1;
m_pos -= (ip[0] >> 2) + (ip[1] << 6);
#endif
ip += 2;
}
else if (t >= 16)
{
m_pos = op;
m_pos -= (t & 8) << 11;
t &= 7;
if (t == 0)
{
NEED_IP(1);
while (*ip == 0)
{
t += 255;
ip++;
NEED_IP(1);
}
t += 7 + *ip++;
}
#if defined(LZO1Z)
m_pos -= (ip[0] << 6) + (ip[1] >> 2);
#elif defined(LZO_UNALIGNED_OK_2) && (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN)
m_pos -= (* (const lzo_ushortp) ip) >> 2;
#else
m_pos -= (ip[0] >> 2) + (ip[1] << 6);
#endif
ip += 2;
if (m_pos == op)
goto eof_found;
m_pos -= 0x4000;
#if defined(LZO1Z)
last_m_off = op - m_pos;
#endif
}
else
{
#if defined(LZO1Z)
t = 1 + (t << 6) + (*ip++ >> 2);
m_pos = op - t;
last_m_off = t;
#else
m_pos = op - 1;
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
#endif
TEST_LOOKBEHIND(m_pos,out); NEED_OP(2);
*op++ = *m_pos++; *op++ = *m_pos;
goto match_done;
}
TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1);
#if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4)
#if !defined(LZO_UNALIGNED_OK_4)
if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos))
{
assert((op - m_pos) >= 4);
#else
if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4)
{
#endif
COPY4(op,m_pos);
op += 4; m_pos += 4; t -= 4 - (3 - 1);
do {
COPY4(op,m_pos);
op += 4; m_pos += 4; t -= 4;
} while (t >= 4);
if (t > 0) do *op++ = *m_pos++; while (--t > 0);
}
else
#endif
{
copy_match:
*op++ = *m_pos++; *op++ = *m_pos++;
do *op++ = *m_pos++; while (--t > 0);
}
match_done:
#if defined(LZO1Z)
t = ip[-1] & 3;
#else
t = ip[-2] & 3;
#endif
if (t == 0)
break;
match_next:
assert(t > 0); NEED_OP(t); NEED_IP(t+1);
do *op++ = *ip++; while (--t > 0);
t = *ip++;
}
}
#if defined(HAVE_TEST_IP) || defined(HAVE_TEST_OP)
*out_len = op - out;
return LZO_E_EOF_NOT_FOUND;
#endif
eof_found:
assert(t == 1);
*out_len = op - out;
return (ip == ip_end ? LZO_E_OK :
(ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN));
#if defined(HAVE_NEED_IP)
input_overrun:
*out_len = op - out;
return LZO_E_INPUT_OVERRUN;
#endif
#if defined(HAVE_NEED_OP)
output_overrun:
*out_len = op - out;
return LZO_E_OUTPUT_OVERRUN;
#endif
#if defined(LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND)
lookbehind_overrun:
*out_len = op - out;
return LZO_E_LOOKBEHIND_OVERRUN;
#endif
}
#endif
/***** End of minilzo.c *****/
| 44,741
|
C++
|
.cpp
| 1,729
| 23.495084
| 106
| 0.61184
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,120
|
ship_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/ship_gui.cpp
|
/* $Id$ */
/** @file ship_gui.cpp GUI for ships. */
#include "stdafx.h"
#include "vehicle_base.h"
#include "window_gui.h"
#include "gfx_func.h"
#include "vehicle_gui.h"
#include "strings_func.h"
#include "vehicle_func.h"
#include "table/strings.h"
void DrawShipImage(const Vehicle *v, int x, int y, VehicleID selection)
{
DrawSprite(v->GetImage(DIR_W), GetVehiclePalette(v), x + 32, y + 10);
if (v->index == selection) {
DrawFrameRect(x - 5, y - 1, x + 67, y + 21, COLOUR_WHITE, FR_BORDERONLY);
}
}
void CcBuildShip(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
const Vehicle *v;
if (!success) return;
v = GetVehicle(_new_vehicle_id);
if (v->tile == _backup_orders_tile) {
_backup_orders_tile = 0;
RestoreVehicleOrders(v);
}
ShowVehicleViewWindow(v);
}
/**
* Draw the details for the given vehicle at the position (x, y)
*
* @param v current vehicle
* @param x The x coordinate
* @param y The y coordinate
*/
void DrawShipDetails(const Vehicle *v, int x, int y)
{
SetDParam(0, v->engine_type);
SetDParam(1, v->build_year);
SetDParam(2, v->value);
DrawString(x, y, STR_9816_BUILT_VALUE, TC_FROMSTRING);
SetDParam(0, v->cargo_type);
SetDParam(1, v->cargo_cap);
SetDParam(2, GetCargoSubtypeText(v));
DrawString(x, y + 10, STR_9817_CAPACITY, TC_FROMSTRING);
StringID str = STR_8812_EMPTY;
if (!v->cargo.Empty()) {
SetDParam(0, v->cargo_type);
SetDParam(1, v->cargo.Count());
SetDParam(2, v->cargo.Source());
str = STR_8813_FROM;
}
DrawString(x, y + 21, str, TC_FROMSTRING);
/* Draw Transfer credits text */
SetDParam(0, v->cargo.FeederShare());
DrawString(x, y + 33, STR_FEEDER_CARGO_VALUE, TC_FROMSTRING);
}
| 1,668
|
C++
|
.cpp
| 57
| 27.298246
| 75
| 0.696875
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,121
|
roadveh_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/roadveh_cmd.cpp
|
/* $Id$ */
/** @file roadveh_cmd.cpp Handling of road vehicles. */
#include "stdafx.h"
#include "landscape.h"
#include "roadveh.h"
#include "station_map.h"
#include "command_func.h"
#include "news_func.h"
#include "pathfind.h"
#include "npf.h"
#include "company_func.h"
#include "vehicle_gui.h"
#include "articulated_vehicles.h"
#include "newgrf_engine.h"
#include "newgrf_sound.h"
#include "yapf/yapf.h"
#include "strings_func.h"
#include "tunnelbridge_map.h"
#include "functions.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "variables.h"
#include "autoreplace_gui.h"
#include "gfx_func.h"
#include "ai/ai.hpp"
#include "depot_base.h"
#include "effectvehicle_func.h"
#include "settings_type.h"
#include "table/strings.h"
#include "table/sprites.h"
static const uint16 _roadveh_images[63] = {
0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
};
static const uint16 _roadveh_full_adder[63] = {
0, 88, 0, 0, 0, 0, 48, 48,
48, 48, 0, 0, 64, 64, 0, 16,
16, 0, 88, 0, 0, 0, 0, 48,
48, 48, 48, 0, 0, 64, 64, 0,
16, 16, 0, 88, 0, 0, 0, 0,
48, 48, 48, 48, 0, 0, 64, 64,
0, 16, 16, 0, 8, 8, 8, 8,
0, 0, 0, 8, 8, 8, 8
};
/** 'Convert' the DiagDirection where a road vehicle enters to the trackdirs it can drive onto */
static const TrackdirBits _road_enter_dir_to_reachable_trackdirs[DIAGDIR_END] = {
TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_X_NE, // Enter from north east
TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_UPPER_E | TRACKDIR_BIT_Y_SE, // Enter from south east
TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_RIGHT_S, // Enter from south west
TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_W | TRACKDIR_BIT_Y_NW // Enter from north west
};
static const Trackdir _road_reverse_table[DIAGDIR_END] = {
TRACKDIR_RVREV_NE, TRACKDIR_RVREV_SE, TRACKDIR_RVREV_SW, TRACKDIR_RVREV_NW
};
/** 'Convert' the DiagDirection where a road vehicle should exit to
* the trackdirs it can use to drive to the exit direction*/
static const TrackdirBits _road_exit_dir_to_incoming_trackdirs[DIAGDIR_END] = {
TRACKDIR_BIT_LOWER_W | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_LEFT_S,
TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_Y_NW,
TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_UPPER_E | TRACKDIR_BIT_X_NE,
TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_Y_SE
};
/** Converts the exit direction of a depot to trackdir the vehicle is going to drive to */
static const Trackdir _roadveh_depot_exit_trackdir[DIAGDIR_END] = {
TRACKDIR_X_NE, TRACKDIR_Y_SE, TRACKDIR_X_SW, TRACKDIR_Y_NW
};
static SpriteID GetRoadVehIcon(EngineID engine)
{
uint8 spritenum = RoadVehInfo(engine)->image_index;
if (is_custom_sprite(spritenum)) {
SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W);
if (sprite != 0) return sprite;
spritenum = GetEngine(engine)->image_index;
}
return 6 + _roadveh_images[spritenum];
}
SpriteID RoadVehicle::GetImage(Direction direction) const
{
uint8 spritenum = this->spritenum;
SpriteID sprite;
if (is_custom_sprite(spritenum)) {
sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)));
if (sprite != 0) return sprite;
spritenum = GetEngine(this->engine_type)->image_index;
}
sprite = direction + _roadveh_images[spritenum];
if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
return sprite;
}
void DrawRoadVehEngine(int x, int y, EngineID engine, SpriteID pal)
{
DrawSprite(GetRoadVehIcon(engine), pal, x, y);
}
byte GetRoadVehLength(const Vehicle *v)
{
byte length = 8;
uint16 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
if (veh_len != CALLBACK_FAILED) {
length -= Clamp(veh_len, 0, 7);
}
return length;
}
void RoadVehUpdateCache(Vehicle *v)
{
assert(v->type == VEH_ROAD);
assert(IsRoadVehFront(v));
for (Vehicle *u = v; u != NULL; u = u->Next()) {
/* Check the v->first cache. */
assert(u->First() == v);
/* Update the 'first engine' */
u->u.road.first_engine = (v == u) ? INVALID_ENGINE : v->engine_type;
/* Update the length of the vehicle. */
u->u.road.cached_veh_length = GetRoadVehLength(u);
/* Invalidate the vehicle colour map */
u->colourmap = PAL_NONE;
}
}
/** Build a road vehicle.
* @param tile tile of depot where road vehicle is built
* @param flags operation to perform
* @param p1 bus/truck type being built (engine)
* @param p2 unused
*/
CommandCost CmdBuildRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v;
UnitID unit_num;
if (!IsEngineBuildable(p1, VEH_ROAD, _current_company)) return_cmd_error(STR_ROAD_VEHICLE_NOT_AVAILABLE);
const Engine *e = GetEngine(p1);
/* Engines without valid cargo should not be available */
if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
CommandCost cost(EXPENSES_NEW_VEHICLES, e->GetCost());
if (flags & DC_QUERY_COST) return cost;
/* The ai_new queries the vehicle cost before building the route,
* so we must check against cheaters no sooner than now. --pasky */
if (!IsRoadDepotTile(tile)) return CMD_ERROR;
if (!IsTileOwner(tile, _current_company)) return CMD_ERROR;
if (HasTileRoadType(tile, ROADTYPE_TRAM) != HasBit(EngInfo(p1)->misc_flags, EF_ROAD_TRAM)) return_cmd_error(STR_DEPOT_WRONG_DEPOT_TYPE);
uint num_vehicles = 1 + CountArticulatedParts(p1, false);
/* Allow for the front and the articulated parts, plus one to "terminate" the list. */
Vehicle **vl = AllocaM(Vehicle*, num_vehicles + 1);
memset(vl, 0, sizeof(*vl) * (num_vehicles + 1));
if (!Vehicle::AllocateList(vl, num_vehicles)) {
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
}
v = vl[0];
/* find the first free roadveh id */
unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_ROAD);
if (unit_num > _settings_game.vehicle.max_roadveh)
return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
if (flags & DC_EXEC) {
int x;
int y;
const RoadVehicleInfo *rvi = RoadVehInfo(p1);
v = new (v) RoadVehicle();
v->unitnumber = unit_num;
v->direction = DiagDirToDir(GetRoadDepotDirection(tile));
v->owner = _current_company;
v->tile = tile;
x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
v->x_pos = x;
v->y_pos = y;
v->z_pos = GetSlopeZ(x, y);
v->running_ticks = 0;
v->u.road.state = RVSB_IN_DEPOT;
v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
v->spritenum = rvi->image_index;
v->cargo_type = e->GetDefaultCargoType();
v->cargo_subtype = 0;
v->cargo_cap = rvi->capacity;
// v->cargo_count = 0;
v->value = cost.GetCost();
// v->day_counter = 0;
// v->next_order_param = v->next_order = 0;
// v->load_unload_time_rem = 0;
// v->progress = 0;
// v->u.road.overtaking = 0;
v->last_station_visited = INVALID_STATION;
v->max_speed = rvi->max_speed;
v->engine_type = (EngineID)p1;
v->reliability = e->reliability;
v->reliability_spd_dec = e->reliability_spd_dec;
v->max_age = e->lifelength * DAYS_IN_LEAP_YEAR;
_new_vehicle_id = v->index;
v->name = NULL;
v->service_interval = _settings_game.vehicle.servint_roadveh;
v->date_of_last_service = _date;
v->build_year = _cur_year;
v->cur_image = 0xC15;
v->random_bits = VehicleRandomBits();
SetRoadVehFront(v);
v->u.road.roadtype = HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
v->u.road.compatible_roadtypes = RoadTypeToRoadTypes(v->u.road.roadtype);
v->u.road.cached_veh_length = 8;
v->vehicle_flags = 0;
if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
v->cargo_cap = rvi->capacity;
AddArticulatedParts(vl, VEH_ROAD);
/* Call various callbacks after the whole consist has been constructed */
for (Vehicle *u = v; u != NULL; u = u->Next()) {
u->u.road.cached_veh_length = GetRoadVehLength(u);
/* Cargo capacity is zero if and only if the vehicle cannot carry anything */
if (u->cargo_cap != 0) u->cargo_cap = GetVehicleProperty(u, 0x0F, u->cargo_cap);
}
VehicleMove(v, false);
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
InvalidateWindow(WC_COMPANY, v->owner);
if (IsLocalCompany()) {
InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Road window
}
GetCompany(_current_company)->num_engines[p1]++;
CheckConsistencyOfArticulatedVehicle(v);
}
return cost;
}
void ClearSlot(Vehicle *v)
{
RoadStop *rs = v->u.road.slot;
if (v->u.road.slot == NULL) return;
v->u.road.slot = NULL;
v->u.road.slot_age = 0;
assert(rs->num_vehicles != 0);
rs->num_vehicles--;
DEBUG(ms, 3, "Clearing slot at 0x%X", rs->xy);
}
bool RoadVehicle::IsStoppedInDepot() const
{
TileIndex tile = this->tile;
if (!IsRoadDepotTile(tile)) return false;
if (IsRoadVehFront(this) && !(this->vehstatus & VS_STOPPED)) return false;
for (const Vehicle *v = this; v != NULL; v = v->Next()) {
if (v->u.road.state != RVSB_IN_DEPOT || v->tile != tile) return false;
}
return true;
}
/** Sell a road vehicle.
* @param tile unused
* @param flags operation to perform
* @param p1 vehicle ID to be sold
* @param p2 unused
*/
CommandCost CmdSellRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v;
if (!IsValidVehicleID(p1)) return CMD_ERROR;
v = GetVehicle(p1);
if (v->type != VEH_ROAD || !CheckOwnership(v->owner)) return CMD_ERROR;
if (HASBITS(v->vehstatus, VS_CRASHED)) return_cmd_error(STR_CAN_T_SELL_DESTROYED_VEHICLE);
if (!v->IsStoppedInDepot()) {
return_cmd_error(STR_9013_MUST_BE_STOPPED_INSIDE);
}
CommandCost ret(EXPENSES_NEW_VEHICLES, -v->value);
if (flags & DC_EXEC) {
delete v;
}
return ret;
}
struct RoadFindDepotData {
uint best_length;
TileIndex tile;
OwnerByte owner;
};
static const DiagDirection _road_pf_directions[] = {
DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, INVALID_DIAGDIR, INVALID_DIAGDIR,
DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, INVALID_DIAGDIR, INVALID_DIAGDIR
};
static bool EnumRoadSignalFindDepot(TileIndex tile, void *data, Trackdir trackdir, uint length)
{
RoadFindDepotData *rfdd = (RoadFindDepotData*)data;
tile += TileOffsByDiagDir(_road_pf_directions[trackdir]);
if (IsRoadDepotTile(tile) &&
IsTileOwner(tile, rfdd->owner) &&
length < rfdd->best_length) {
rfdd->best_length = length;
rfdd->tile = tile;
}
return false;
}
static const Depot *FindClosestRoadDepot(const Vehicle *v)
{
switch (_settings_game.pf.pathfinder_for_roadvehs) {
case VPF_YAPF: // YAPF
return YapfFindNearestRoadDepot(v);
case VPF_NPF: { // NPF
/* See where we are now */
Trackdir trackdir = GetVehicleTrackdir(v);
NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, v->tile, ReverseTrackdir(trackdir), false, TRANSPORT_ROAD, v->u.road.compatible_roadtypes, v->owner, INVALID_RAILTYPES, 0);
if (ftd.best_bird_dist == 0) return GetDepotByTile(ftd.node.tile); // Target found
} break;
default:
case VPF_OPF: { // OPF
RoadFindDepotData rfdd;
rfdd.owner = v->owner;
rfdd.best_length = UINT_MAX;
/* search in all directions */
for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
FollowTrack(v->tile, PATHFIND_FLAGS_NONE, TRANSPORT_ROAD, v->u.road.compatible_roadtypes, d, EnumRoadSignalFindDepot, NULL, &rfdd);
}
if (rfdd.best_length != UINT_MAX) return GetDepotByTile(rfdd.tile);
} break;
}
return NULL; // Target not found
}
bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
{
const Depot *depot = FindClosestRoadDepot(this);
if (depot == NULL) return false;
if (location != NULL) *location = depot->xy;
if (destination != NULL) *destination = depot->index;
return true;
}
/** Send a road vehicle to the depot.
* @param tile unused
* @param flags operation to perform
* @param p1 vehicle ID to send to the depot
* @param p2 various bitmasked elements
* - p2 bit 0-3 - DEPOT_ flags (see vehicle.h)
* - p2 bit 8-10 - VLW flag (for mass goto depot)
*/
CommandCost CmdSendRoadVehToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (p2 & DEPOT_MASS_SEND) {
/* Mass goto depot requested */
if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
return SendAllVehiclesToDepot(VEH_ROAD, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
}
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_ROAD) return CMD_ERROR;
return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
}
/** Turn a roadvehicle around.
* @param tile unused
* @param flags operation to perform
* @param p1 vehicle ID to turn
* @param p2 unused
*/
CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v;
if (!IsValidVehicleID(p1)) return CMD_ERROR;
v = GetVehicle(p1);
if (v->type != VEH_ROAD || !CheckOwnership(v->owner)) return CMD_ERROR;
if (v->vehstatus & VS_STOPPED ||
v->vehstatus & VS_CRASHED ||
v->breakdown_ctr != 0 ||
v->u.road.overtaking != 0 ||
v->u.road.state == RVSB_WORMHOLE ||
v->IsInDepot() ||
v->cur_speed < 5) {
return CMD_ERROR;
}
if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) return CMD_ERROR;
if (IsTileType(v->tile, MP_TUNNELBRIDGE) && DirToDiagDir(v->direction) == GetTunnelBridgeDirection(v->tile)) return CMD_ERROR;
if (flags & DC_EXEC) v->u.road.reverse_ctr = 180;
return CommandCost();
}
void RoadVehicle::MarkDirty()
{
for (Vehicle *v = this; v != NULL; v = v->Next()) {
v->cur_image = v->GetImage(v->direction);
MarkSingleVehicleDirty(v);
}
}
void RoadVehicle::UpdateDeltaXY(Direction direction)
{
#define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
static const uint32 _delta_xy_table[8] = {
MKIT(3, 3, -1, -1),
MKIT(3, 7, -1, -3),
MKIT(3, 3, -1, -1),
MKIT(7, 3, -3, -1),
MKIT(3, 3, -1, -1),
MKIT(3, 7, -1, -3),
MKIT(3, 3, -1, -1),
MKIT(7, 3, -3, -1),
};
#undef MKIT
uint32 x = _delta_xy_table[direction];
this->x_offs = GB(x, 0, 8);
this->y_offs = GB(x, 8, 8);
this->x_extent = GB(x, 16, 8);
this->y_extent = GB(x, 24, 8);
this->z_extent = 6;
}
static void ClearCrashedStation(Vehicle *v)
{
RoadStop *rs = GetRoadStopByTile(v->tile, GetRoadStopType(v->tile));
/* Mark the station entrance as not busy */
rs->SetEntranceBusy(false);
/* Free the parking bay */
rs->FreeBay(HasBit(v->u.road.state, RVS_USING_SECOND_BAY));
}
static void DeleteLastRoadVeh(Vehicle *v)
{
Vehicle *u = v;
for (; v->Next() != NULL; v = v->Next()) u = v;
u->SetNext(NULL);
if (IsTileType(v->tile, MP_STATION)) ClearCrashedStation(v);
delete v;
}
static byte SetRoadVehPosition(Vehicle *v, int x, int y)
{
byte new_z, old_z;
/* need this hint so it returns the right z coordinate on bridges. */
v->x_pos = x;
v->y_pos = y;
new_z = GetSlopeZ(x, y);
old_z = v->z_pos;
v->z_pos = new_z;
VehicleMove(v, true);
return old_z;
}
static void RoadVehSetRandomDirection(Vehicle *v)
{
static const DirDiff delta[] = {
DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
};
do {
uint32 r = Random();
v->direction = ChangeDir(v->direction, delta[r & 3]);
v->UpdateDeltaXY(v->direction);
v->cur_image = v->GetImage(v->direction);
SetRoadVehPosition(v, v->x_pos, v->y_pos);
} while ((v = v->Next()) != NULL);
}
static void RoadVehIsCrashed(Vehicle *v)
{
v->u.road.crashed_ctr++;
if (v->u.road.crashed_ctr == 2) {
CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
} else if (v->u.road.crashed_ctr <= 45) {
if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
} else if (v->u.road.crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
DeleteLastRoadVeh(v);
}
}
static Vehicle *EnumCheckRoadVehCrashTrain(Vehicle *v, void *data)
{
const Vehicle *u = (Vehicle*)data;
return
v->type == VEH_TRAIN &&
abs(v->z_pos - u->z_pos) <= 6 &&
abs(v->x_pos - u->x_pos) <= 4 &&
abs(v->y_pos - u->y_pos) <= 4 ?
v : NULL;
}
static void RoadVehCrash(Vehicle *v)
{
uint16 pass = 1;
v->u.road.crashed_ctr++;
for (Vehicle *u = v; u != NULL; u = u->Next()) {
if (IsCargoInClass(u->cargo_type, CC_PASSENGERS)) pass += u->cargo.Count();
u->vehstatus |= VS_CRASHED;
MarkSingleVehicleDirty(u);
}
ClearSlot(v);
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
SetDParam(0, pass);
AddNewsItem(
(pass == 1) ?
STR_9031_ROAD_VEHICLE_CRASH_DRIVER : STR_9032_ROAD_VEHICLE_CRASH_DIE,
NS_ACCIDENT_VEHICLE,
v->index,
0
);
ModifyStationRatingAround(v->tile, v->owner, -160, 22);
SndPlayVehicleFx(SND_12_EXPLOSION, v);
}
static bool RoadVehCheckTrainCrash(Vehicle *v)
{
for (Vehicle *u = v; u != NULL; u = u->Next()) {
if (u->u.road.state == RVSB_WORMHOLE) continue;
TileIndex tile = u->tile;
if (!IsLevelCrossingTile(tile)) continue;
if (HasVehicleOnPosXY(v->x_pos, v->y_pos, u, EnumCheckRoadVehCrashTrain)) {
RoadVehCrash(v);
return true;
}
}
return false;
}
static void HandleBrokenRoadVeh(Vehicle *v)
{
if (v->breakdown_ctr != 1) {
v->breakdown_ctr = 1;
v->cur_speed = 0;
if (v->breakdowns_since_last_service != 255)
v->breakdowns_since_last_service++;
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
SND_0F_VEHICLE_BREAKDOWN : SND_35_COMEDY_BREAKDOWN, v);
}
if (!(v->vehstatus & VS_HIDDEN)) {
Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
if (u != NULL) u->u.effect.animation_state = v->breakdown_delay * 2;
}
}
if ((v->tick_counter & 1) == 0) {
if (--v->breakdown_delay == 0) {
v->breakdown_ctr = 0;
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
}
}
}
TileIndex RoadVehicle::GetOrderStationLocation(StationID station)
{
if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
TileIndex dest = INVALID_TILE;
const RoadStop *rs = GetStation(station)->GetPrimaryRoadStop(this);
if (rs != NULL) {
uint mindist = UINT_MAX;
for (; rs != NULL; rs = rs->GetNextRoadStop(this)) {
uint dist = DistanceManhattan(this->tile, rs->xy);
if (dist < mindist) {
mindist = dist;
dest = rs->xy;
}
}
}
if (dest != INVALID_TILE) {
return dest;
} else {
/* There is no stop left at the station, so don't even TRY to go there */
this->cur_order_index++;
return 0;
}
}
static void StartRoadVehSound(const Vehicle *v)
{
if (!PlayVehicleSound(v, VSE_START)) {
SoundFx s = RoadVehInfo(v->engine_type)->sfx;
if (s == SND_19_BUS_START_PULL_AWAY && (v->tick_counter & 3) == 0)
s = SND_1A_BUS_START_PULL_AWAY_WITH_HORN;
SndPlayVehicleFx(s, v);
}
}
struct RoadVehFindData {
int x;
int y;
const Vehicle *veh;
Vehicle *best;
uint best_diff;
Direction dir;
};
static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data)
{
static const int8 dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
static const int8 dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
RoadVehFindData *rvf = (RoadVehFindData*)data;
short x_diff = v->x_pos - rvf->x;
short y_diff = v->y_pos - rvf->y;
if (v->type == VEH_ROAD &&
!v->IsInDepot() &&
abs(v->z_pos - rvf->veh->z_pos) < 6 &&
v->direction == rvf->dir &&
rvf->veh->First() != v->First() &&
(dist_x[v->direction] >= 0 || (x_diff > dist_x[v->direction] && x_diff <= 0)) &&
(dist_x[v->direction] <= 0 || (x_diff < dist_x[v->direction] && x_diff >= 0)) &&
(dist_y[v->direction] >= 0 || (y_diff > dist_y[v->direction] && y_diff <= 0)) &&
(dist_y[v->direction] <= 0 || (y_diff < dist_y[v->direction] && y_diff >= 0))) {
uint diff = abs(x_diff) + abs(y_diff);
if (diff < rvf->best_diff || (diff == rvf->best_diff && v->index < rvf->best->index)) {
rvf->best = v;
rvf->best_diff = diff;
}
}
return NULL;
}
static Vehicle *RoadVehFindCloseTo(Vehicle *v, int x, int y, Direction dir)
{
RoadVehFindData rvf;
Vehicle *front = v->First();
if (front->u.road.reverse_ctr != 0) return NULL;
rvf.x = x;
rvf.y = y;
rvf.dir = dir;
rvf.veh = v;
rvf.best_diff = UINT_MAX;
if (front->u.road.state == RVSB_WORMHOLE) {
FindVehicleOnPos(v->tile, &rvf, EnumCheckRoadVehClose);
FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &rvf, EnumCheckRoadVehClose);
} else {
FindVehicleOnPosXY(x, y, &rvf, EnumCheckRoadVehClose);
}
/* This code protects a roadvehicle from being blocked for ever
* If more than 1480 / 74 days a road vehicle is blocked, it will
* drive just through it. The ultimate backup-code of TTD.
* It can be disabled. */
if (rvf.best_diff == UINT_MAX) {
front->u.road.blocked_ctr = 0;
return NULL;
}
if (++front->u.road.blocked_ctr > 1480) return NULL;
return rvf.best;
}
static void RoadVehArrivesAt(const Vehicle *v, Station *st)
{
if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) {
/* Check if station was ever visited before */
if (!(st->had_vehicle_of_type & HVOT_BUS)) {
st->had_vehicle_of_type |= HVOT_BUS;
SetDParam(0, st->index);
AddNewsItem(
v->u.road.roadtype == ROADTYPE_ROAD ? STR_902F_CITIZENS_CELEBRATE_FIRST : STR_CITIZENS_CELEBRATE_FIRST_PASSENGER_TRAM,
(v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
v->index,
st->index
);
AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
}
} else {
/* Check if station was ever visited before */
if (!(st->had_vehicle_of_type & HVOT_TRUCK)) {
st->had_vehicle_of_type |= HVOT_TRUCK;
SetDParam(0, st->index);
AddNewsItem(
v->u.road.roadtype == ROADTYPE_ROAD ? STR_9030_CITIZENS_CELEBRATE_FIRST : STR_CITIZENS_CELEBRATE_FIRST_CARGO_TRAM,
(v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
v->index,
st->index
);
AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
}
}
}
static int RoadVehAccelerate(Vehicle *v)
{
uint oldspeed = v->cur_speed;
uint accel = 256 + (v->u.road.overtaking != 0 ? 256 : 0);
uint spd = v->subspeed + accel;
v->subspeed = (uint8)spd;
int tempmax = v->max_speed;
if (v->cur_speed > v->max_speed) {
tempmax = v->cur_speed - (v->cur_speed / 10) - 1;
}
v->cur_speed = spd = Clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax);
/* Apply bridge speed limit */
if (v->u.road.state == RVSB_WORMHOLE && !(v->vehstatus & VS_HIDDEN)) {
v->cur_speed = min(v->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed * 2);
}
/* Update statusbar only if speed has changed to save CPU time */
if (oldspeed != v->cur_speed) {
if (_settings_client.gui.vehicle_speed) {
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
}
/* Speed is scaled in the same manner as for trains. @see train_cmd.cpp */
int scaled_spd = spd * 3 >> 2;
scaled_spd += v->progress;
v->progress = 0;
return scaled_spd;
}
static Direction RoadVehGetNewDirection(const Vehicle *v, int x, int y)
{
static const Direction _roadveh_new_dir[] = {
DIR_N , DIR_NW, DIR_W , INVALID_DIR,
DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
DIR_E , DIR_SE, DIR_S
};
x = x - v->x_pos + 1;
y = y - v->y_pos + 1;
if ((uint)x > 2 || (uint)y > 2) return v->direction;
return _roadveh_new_dir[y * 4 + x];
}
static Direction RoadVehGetSlidingDirection(const Vehicle *v, int x, int y)
{
Direction new_dir = RoadVehGetNewDirection(v, x, y);
Direction old_dir = v->direction;
DirDiff delta;
if (new_dir == old_dir) return old_dir;
delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
return ChangeDir(old_dir, delta);
}
struct OvertakeData {
const Vehicle *u;
const Vehicle *v;
TileIndex tile;
Trackdir trackdir;
};
static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data)
{
const OvertakeData *od = (OvertakeData*)data;
return
v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v ?
v : NULL;
}
/**
* Check if overtaking is possible on a piece of track
*
* @param od Information about the tile and the involved vehicles
* @return true if we have to abort overtaking
*/
static bool CheckRoadBlockedForOvertaking(OvertakeData *od)
{
TrackStatus ts = GetTileTrackStatus(od->tile, TRANSPORT_ROAD, od->v->u.road.compatible_roadtypes);
TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts);
TrackdirBits red_signals = TrackStatusToRedSignals(ts); // barred level crossing
TrackBits trackbits = TrackdirBitsToTrackBits(trackdirbits);
/* Track does not continue along overtaking direction || track has junction || levelcrossing is barred */
if (!HasBit(trackdirbits, od->trackdir) || (trackbits & ~TRACK_BIT_CROSS) || (red_signals != TRACKDIR_BIT_NONE)) return true;
/* Are there more vehicles on the tile except the two vehicles involved in overtaking */
return HasVehicleOnPos(od->tile, od, EnumFindVehBlockingOvertake);
}
static void RoadVehCheckOvertake(Vehicle *v, Vehicle *u)
{
OvertakeData od;
od.v = v;
od.u = u;
if (u->max_speed >= v->max_speed &&
!(u->vehstatus & VS_STOPPED) &&
u->cur_speed != 0) {
return;
}
/* Trams can't overtake other trams */
if (v->u.road.roadtype == ROADTYPE_TRAM) return;
/* Don't overtake in stations */
if (IsTileType(v->tile, MP_STATION)) return;
/* For now, articulated road vehicles can't overtake anything. */
if (RoadVehHasArticPart(v)) return;
/* Vehicles are not driving in same direction || direction is not a diagonal direction */
if (v->direction != u->direction || !(v->direction & 1)) return;
/* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
if (v->u.road.state >= RVSB_IN_ROAD_STOP || !IsStraightRoadTrackdir((Trackdir)(v->u.road.state & RVSB_TRACKDIR_MASK))) return;
od.trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
/* Are the current and the next tile suitable for overtaking?
* - Does the track continue along od.trackdir
* - No junctions
* - No barred levelcrossing
* - No other vehicles in the way
*/
od.tile = v->tile;
if (CheckRoadBlockedForOvertaking(&od)) return;
od.tile = v->tile + TileOffsByDiagDir(DirToDiagDir(v->direction));
if (CheckRoadBlockedForOvertaking(&od)) return;
if (od.u->cur_speed == 0 || od.u->vehstatus& VS_STOPPED) {
v->u.road.overtaking_ctr = 0x11;
v->u.road.overtaking = 0x10;
} else {
// if (CheckRoadBlockedForOvertaking(&od)) return;
v->u.road.overtaking_ctr = 0;
v->u.road.overtaking = 0x10;
}
}
static void RoadZPosAffectSpeed(Vehicle *v, byte old_z)
{
if (old_z == v->z_pos) return;
if (old_z < v->z_pos) {
v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
} else {
uint16 spd = v->cur_speed + 2;
if (spd <= v->max_speed) v->cur_speed = spd;
}
}
static int PickRandomBit(uint bits)
{
uint i;
uint num = RandomRange(CountBits(bits));
for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {}
return i;
}
struct FindRoadToChooseData {
TileIndex dest;
uint maxtracklen;
uint mindist;
};
static bool EnumRoadTrackFindDist(TileIndex tile, void *data, Trackdir trackdir, uint length)
{
FindRoadToChooseData *frd = (FindRoadToChooseData*)data;
uint dist = DistanceManhattan(tile, frd->dest);
if (dist <= frd->mindist) {
if (dist != frd->mindist || length < frd->maxtracklen) {
frd->maxtracklen = length;
}
frd->mindist = dist;
}
return false;
}
static inline NPFFoundTargetData PerfNPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, NPFFindStationOrTileData *target, TransportType type, uint sub_type, Owner owner, RailTypes railtypes)
{
void *perf = NpfBeginInterval();
NPFFoundTargetData ret = NPFRouteToStationOrTile(tile, trackdir, ignore_start_tile, target, type, sub_type, owner, railtypes);
int t = NpfEndInterval(perf);
DEBUG(yapf, 4, "[NPFR] %d us - %d rounds - %d open - %d closed -- ", t, 0, _aystar_stats_open_size, _aystar_stats_closed_size);
return ret;
}
/**
* Returns direction to for a road vehicle to take or
* INVALID_TRACKDIR if the direction is currently blocked
* @param v the Vehicle to do the pathfinding for
* @param tile the where to start the pathfinding
* @param enterdir the direction the vehicle enters the tile from
* @return the Trackdir to take
*/
static Trackdir RoadFindPathToDest(Vehicle *v, TileIndex tile, DiagDirection enterdir)
{
#define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
TileIndex desttile;
FindRoadToChooseData frd;
Trackdir best_track;
TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_ROAD, v->u.road.compatible_roadtypes);
TrackdirBits red_signals = TrackStatusToRedSignals(ts); // crossing
TrackdirBits trackdirs = TrackStatusToTrackdirBits(ts);
if (IsTileType(tile, MP_ROAD)) {
if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir || (GetRoadTypes(tile) & v->u.road.compatible_roadtypes) == 0)) {
/* Road depot owned by another company or with the wrong orientation */
trackdirs = TRACKDIR_BIT_NONE;
}
} else if (IsTileType(tile, MP_STATION) && IsStandardRoadStopTile(tile)) {
/* Standard road stop (drive-through stops are treated as normal road) */
if (!IsTileOwner(tile, v->owner) || GetRoadStopDir(tile) == enterdir || RoadVehHasArticPart(v)) {
/* different station owner or wrong orientation or the vehicle has articulated parts */
trackdirs = TRACKDIR_BIT_NONE;
} else {
/* Our station */
RoadStopType rstype = IsCargoInClass(v->cargo_type, CC_PASSENGERS) ? ROADSTOP_BUS : ROADSTOP_TRUCK;
if (GetRoadStopType(tile) != rstype) {
/* Wrong station type */
trackdirs = TRACKDIR_BIT_NONE;
} else {
/* Proper station type, check if there is free loading bay */
if (!_settings_game.pf.roadveh_queue && IsStandardRoadStopTile(tile) &&
!GetRoadStopByTile(tile, rstype)->HasFreeBay()) {
/* Station is full and RV queuing is off */
trackdirs = TRACKDIR_BIT_NONE;
}
}
}
}
/* The above lookups should be moved to GetTileTrackStatus in the
* future, but that requires more changes to the pathfinder and other
* stuff, probably even more arguments to GTTS.
*/
/* Remove tracks unreachable from the enter dir */
trackdirs &= _road_enter_dir_to_reachable_trackdirs[enterdir];
if (trackdirs == TRACKDIR_BIT_NONE) {
/* No reachable tracks, so we'll reverse */
return_track(_road_reverse_table[enterdir]);
}
if (v->u.road.reverse_ctr != 0) {
bool reverse = true;
if (v->u.road.roadtype == ROADTYPE_TRAM) {
/* Trams may only reverse on a tile if it contains at least the straight
* trackbits or when it is a valid turning tile (i.e. one roadbit) */
RoadBits rb = GetAnyRoadBits(tile, ROADTYPE_TRAM);
RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
reverse = ((rb & straight) == straight) ||
(rb == DiagDirToRoadBits(enterdir));
}
if (reverse) {
v->u.road.reverse_ctr = 0;
if (v->tile != tile) {
return_track(_road_reverse_table[enterdir]);
}
}
}
desttile = v->dest_tile;
if (desttile == 0) {
/* We've got no destination, pick a random track */
return_track(PickRandomBit(trackdirs));
}
/* Only one track to choose between? */
if (KillFirstBit(trackdirs) == TRACKDIR_BIT_NONE) {
return_track(FindFirstBit2x64(trackdirs));
}
switch (_settings_game.pf.pathfinder_for_roadvehs) {
case VPF_YAPF: { // YAPF
Trackdir trackdir = YapfChooseRoadTrack(v, tile, enterdir);
if (trackdir != INVALID_TRACKDIR) return_track(trackdir);
return_track(PickRandomBit(trackdirs));
} break;
case VPF_NPF: { // NPF
NPFFindStationOrTileData fstd;
NPFFillWithOrderData(&fstd, v);
Trackdir trackdir = DiagDirToDiagTrackdir(enterdir);
/* debug("Finding path. Enterdir: %d, Trackdir: %d", enterdir, trackdir); */
NPFFoundTargetData ftd = PerfNPFRouteToStationOrTile(tile - TileOffsByDiagDir(enterdir), trackdir, true, &fstd, TRANSPORT_ROAD, v->u.road.compatible_roadtypes, v->owner, INVALID_RAILTYPES);
if (ftd.best_trackdir == INVALID_TRACKDIR) {
/* We are already at our target. Just do something
* @todo: maybe display error?
* @todo: go straight ahead if possible? */
return_track(FindFirstBit2x64(trackdirs));
} else {
/* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
* the direction we need to take to get there, if ftd.best_bird_dist is not 0,
* we did not find our target, but ftd.best_trackdir contains the direction leading
* to the tile closest to our target. */
return_track(ftd.best_trackdir);
}
} break;
default:
case VPF_OPF: { // OPF
DiagDirection dir;
if (IsTileType(desttile, MP_ROAD)) {
if (IsRoadDepot(desttile)) {
dir = GetRoadDepotDirection(desttile);
goto do_it;
}
} else if (IsTileType(desttile, MP_STATION)) {
/* For drive-through stops we can head for the actual station tile */
if (IsStandardRoadStopTile(desttile)) {
dir = GetRoadStopDir(desttile);
do_it:;
/* When we are heading for a depot or station, we just
* pretend we are heading for the tile in front, we'll
* see from there */
desttile += TileOffsByDiagDir(dir);
if (desttile == tile && trackdirs & _road_exit_dir_to_incoming_trackdirs[dir]) {
/* If we are already in front of the
* station/depot and we can get in from here,
* we enter */
return_track(FindFirstBit2x64(trackdirs & _road_exit_dir_to_incoming_trackdirs[dir]));
}
}
}
/* Do some pathfinding */
frd.dest = desttile;
best_track = INVALID_TRACKDIR;
uint best_dist = UINT_MAX;
uint best_maxlen = UINT_MAX;
uint bitmask = (uint)trackdirs;
uint i;
FOR_EACH_SET_BIT(i, bitmask) {
if (best_track == INVALID_TRACKDIR) best_track = (Trackdir)i; // in case we don't find the path, just pick a track
frd.maxtracklen = UINT_MAX;
frd.mindist = UINT_MAX;
FollowTrack(tile, PATHFIND_FLAGS_NONE, TRANSPORT_ROAD, v->u.road.compatible_roadtypes, _road_pf_directions[i], EnumRoadTrackFindDist, NULL, &frd);
if (frd.mindist < best_dist || (frd.mindist == best_dist && frd.maxtracklen < best_maxlen)) {
best_dist = frd.mindist;
best_maxlen = frd.maxtracklen;
best_track = (Trackdir)i;
}
}
} break;
}
found_best_track:;
if (HasBit(red_signals, best_track)) return INVALID_TRACKDIR;
return best_track;
}
static uint RoadFindPathToStop(const Vehicle *v, TileIndex tile)
{
if (_settings_game.pf.pathfinder_for_roadvehs == VPF_YAPF) {
/* use YAPF */
return YapfRoadVehDistanceToTile(v, tile);
}
/* use NPF */
Trackdir trackdir = GetVehicleTrackdir(v);
assert(trackdir != INVALID_TRACKDIR);
NPFFindStationOrTileData fstd;
fstd.dest_coords = tile;
fstd.station_index = INVALID_STATION; // indicates that the destination is a tile, not a station
uint dist = NPFRouteToStationOrTile(v->tile, trackdir, false, &fstd, TRANSPORT_ROAD, v->u.road.compatible_roadtypes, v->owner, INVALID_RAILTYPES).best_path_dist;
/* change units from NPF_TILE_LENGTH to # of tiles */
if (dist != UINT_MAX) dist = (dist + NPF_TILE_LENGTH - 1) / NPF_TILE_LENGTH;
return dist;
}
struct RoadDriveEntry {
byte x, y;
};
#include "table/roadveh_movement.h"
static const byte _road_veh_data_1[] = {
20, 20, 16, 16, 0, 0, 0, 0,
19, 19, 15, 15, 0, 0, 0, 0,
16, 16, 12, 12, 0, 0, 0, 0,
15, 15, 11, 11
};
static bool RoadVehLeaveDepot(Vehicle *v, bool first)
{
/* Don't leave if not all the wagons are in the depot. */
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
if (u->u.road.state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
}
DiagDirection dir = GetRoadDepotDirection(v->tile);
v->direction = DiagDirToDir(dir);
Trackdir tdir = _roadveh_depot_exit_trackdir[dir];
const RoadDriveEntry *rdp = _road_drive_data[v->u.road.roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + tdir];
int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
if (first) {
if (RoadVehFindCloseTo(v, x, y, v->direction) != NULL) return true;
VehicleServiceInDepot(v);
StartRoadVehSound(v);
/* Vehicle is about to leave a depot */
v->cur_speed = 0;
}
v->vehstatus &= ~VS_HIDDEN;
v->u.road.state = tdir;
v->u.road.frame = RVC_DEPOT_START_FRAME;
v->UpdateDeltaXY(v->direction);
SetRoadVehPosition(v, x, y);
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
return true;
}
static Trackdir FollowPreviousRoadVehicle(const Vehicle *v, const Vehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
{
if (prev->tile == v->tile && !already_reversed) {
/* If the previous vehicle is on the same tile as this vehicle is
* then it must have reversed. */
return _road_reverse_table[entry_dir];
}
byte prev_state = prev->u.road.state;
Trackdir dir;
if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
DiagDirection diag_dir = INVALID_DIAGDIR;
if (IsTileType(tile, MP_TUNNELBRIDGE)) {
diag_dir = GetTunnelBridgeDirection(tile);
} else if (IsRoadDepotTile(tile)) {
diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
}
if (diag_dir == INVALID_DIAGDIR) return INVALID_TRACKDIR;
dir = DiagDirToDiagTrackdir(diag_dir);
} else {
if (already_reversed && prev->tile != tile) {
/*
* The vehicle has reversed, but did not go straight back.
* It immediatelly turn onto another tile. This means that
* the roadstate of the previous vehicle cannot be used
* as the direction we have to go with this vehicle.
*
* Next table is build in the following way:
* - first row for when the vehicle in front went to the northern or
* western tile, second for southern and eastern.
* - columns represent the entry direction.
* - cell values are determined by the Trackdir one has to take from
* the entry dir (column) to the tile in north or south by only
* going over the trackdirs used for turning 90 degrees, i.e.
* TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
*/
Trackdir reversed_turn_lookup[2][DIAGDIR_END] = {
{ TRACKDIR_UPPER_W, TRACKDIR_RIGHT_N, TRACKDIR_LEFT_N, TRACKDIR_UPPER_E },
{ TRACKDIR_RIGHT_S, TRACKDIR_LOWER_W, TRACKDIR_LOWER_E, TRACKDIR_LEFT_S }};
dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)];
} else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
} else if (prev_state < TRACKDIR_END) {
dir = (Trackdir)prev_state;
} else {
return INVALID_TRACKDIR;
}
}
/* Do some sanity checking. */
static const RoadBits required_roadbits[] = {
ROAD_X, ROAD_Y, ROAD_NW | ROAD_NE, ROAD_SW | ROAD_SE,
ROAD_NW | ROAD_SW, ROAD_NE | ROAD_SE, ROAD_X, ROAD_Y
};
RoadBits required = required_roadbits[dir & 0x07];
if ((required & GetAnyRoadBits(tile, v->u.road.roadtype, true)) == ROAD_NONE) {
dir = INVALID_TRACKDIR;
}
return dir;
}
/**
* Can a tram track build without destruction on the given tile?
* @param c the company that would be building the tram tracks
* @param t the tile to build on.
* @param r the road bits needed.
* @return true when a track track can be build on 't'
*/
static bool CanBuildTramTrackOnTile(CompanyID c, TileIndex t, RoadBits r)
{
/* The 'current' company is not necessarily the owner of the vehicle. */
CompanyID original_company = _current_company;
_current_company = c;
CommandCost ret = DoCommand(t, ROADTYPE_TRAM << 4 | r, 0, DC_NONE, CMD_BUILD_ROAD);
_current_company = original_company;
return CmdSucceeded(ret);
}
static bool IndividualRoadVehicleController(Vehicle *v, const Vehicle *prev)
{
if (v->u.road.overtaking != 0) {
if (IsTileType(v->tile, MP_STATION)) {
/* Force us to be not overtaking! */
v->u.road.overtaking = 0;
} else if (++v->u.road.overtaking_ctr >= 35) {
/* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
* if the vehicle started a corner. To protect that, only allow an abort of
* overtake if we are on straight roads */
if (v->u.road.state < RVSB_IN_ROAD_STOP && IsStraightRoadTrackdir((Trackdir)v->u.road.state)) {
v->u.road.overtaking = 0;
}
}
}
/* If this vehicle is in a depot and we've reached this point it must be
* one of the articulated parts. It will stay in the depot until activated
* by the previous vehicle in the chain when it gets to the right place. */
if (v->IsInDepot()) return true;
if (v->u.road.state == RVSB_WORMHOLE) {
/* Vehicle is entering a depot or is on a bridge or in a tunnel */
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
if (IsRoadVehFront(v)) {
const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
if (u != NULL) {
v->cur_speed = u->First()->cur_speed;
return false;
}
}
if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
/* Vehicle has just entered a bridge or tunnel */
v->UpdateDeltaXY(v->direction);
SetRoadVehPosition(v, gp.x, gp.y);
return true;
}
v->x_pos = gp.x;
v->y_pos = gp.y;
VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
return true;
}
/* Get move position data for next frame.
* For a drive-through road stop use 'straight road' move data.
* In this case v->u.road.state is masked to give the road stop entry direction. */
RoadDriveEntry rd = _road_drive_data[v->u.road.roadtype][(
(HasBit(v->u.road.state, RVS_IN_DT_ROAD_STOP) ? v->u.road.state & RVSB_ROAD_STOP_TRACKDIR_MASK : v->u.road.state) +
(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->u.road.overtaking][v->u.road.frame + 1];
if (rd.x & RDE_NEXT_TILE) {
TileIndex tile = v->tile + TileOffsByDiagDir((DiagDirection)(rd.x & 3));
Trackdir dir;
if (IsRoadVehFront(v)) {
/* If this is the front engine, look for the right path. */
dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3));
} else {
dir = FollowPreviousRoadVehicle(v, prev, tile, (DiagDirection)(rd.x & 3), false);
}
if (dir == INVALID_TRACKDIR) {
if (!IsRoadVehFront(v)) error("Disconnecting road vehicle.");
v->cur_speed = 0;
return false;
}
again:
uint start_frame = RVC_DEFAULT_START_FRAME;
if (IsReversingRoadTrackdir(dir)) {
/* Turning around */
if (v->u.road.roadtype == ROADTYPE_TRAM) {
/* Determine the road bits the tram needs to be able to turn around
* using the 'big' corner loop. */
RoadBits needed;
switch (dir) {
default: NOT_REACHED();
case TRACKDIR_RVREV_NE: needed = ROAD_SW; break;
case TRACKDIR_RVREV_SE: needed = ROAD_NW; break;
case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
}
if ((v->Previous() != NULL && v->Previous()->tile == tile) ||
(IsRoadVehFront(v) && IsNormalRoadTile(tile) && !HasRoadWorks(tile) &&
(needed & GetRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE)) {
/*
* Taking the 'big' corner for trams only happens when:
* - The previous vehicle in this (articulated) tram chain is
* already on the 'next' tile, we just follow them regardless of
* anything. When it is NOT on the 'next' tile, the tram started
* doing a reversing turn when the piece of tram track on the next
* tile did not exist yet. Do not use the big tram loop as that is
* going to cause the tram to split up.
* - Or the front of the tram can drive over the next tile.
*/
} else if (!IsRoadVehFront(v) || !CanBuildTramTrackOnTile(v->owner, tile, needed) || ((~needed & GetAnyRoadBits(v->tile, ROADTYPE_TRAM, false)) == ROAD_NONE)) {
/*
* Taking the 'small' corner for trams only happens when:
* - We are not the from vehicle of an articulated tram.
* - Or when the company cannot build on the next tile.
*
* The 'small' corner means that the vehicle is on the end of a
* tram track and needs to start turning there. To do this properly
* the tram needs to start at an offset in the tram turning 'code'
* for 'big' corners. It furthermore does not go to the next tile,
* so that needs to be fixed too.
*/
tile = v->tile;
start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
} else {
/* The company can build on the next tile, so wait till (s)he does. */
v->cur_speed = 0;
return false;
}
} else if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
v->cur_speed = 0;
return false;
} else {
tile = v->tile;
}
}
/* Get position data for first frame on the new tile */
const RoadDriveEntry *rdp = _road_drive_data[v->u.road.roadtype][(dir + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->u.road.overtaking];
int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
if (IsRoadVehFront(v)) {
Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
if (u != NULL) {
v->cur_speed = u->First()->cur_speed;
return false;
}
}
uint32 r = VehicleEnterTile(v, tile, x, y);
if (HasBit(r, VETS_CANNOT_ENTER)) {
if (!IsTileType(tile, MP_TUNNELBRIDGE)) {
v->cur_speed = 0;
return false;
}
/* Try an about turn to re-enter the previous tile */
dir = _road_reverse_table[rd.x & 3];
goto again;
}
if (IsInsideMM(v->u.road.state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, MP_STATION)) {
if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->u.road.state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
/* New direction is trying to turn vehicle around.
* We can't turn at the exit of a road stop so wait.*/
v->cur_speed = 0;
return false;
}
if (IsRoadStop(v->tile)) {
RoadStop *rs = GetRoadStopByTile(v->tile, GetRoadStopType(v->tile));
/* Vehicle is leaving a road stop tile, mark bay as free
* For drive-through stops, only do it if the vehicle stopped here */
if (IsStandardRoadStopTile(v->tile) || HasBit(v->u.road.state, RVS_IS_STOPPING)) {
rs->FreeBay(HasBit(v->u.road.state, RVS_USING_SECOND_BAY));
ClrBit(v->u.road.state, RVS_IS_STOPPING);
}
if (IsStandardRoadStopTile(v->tile)) rs->SetEntranceBusy(false);
}
}
if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
v->tile = tile;
v->u.road.state = (byte)dir;
v->u.road.frame = start_frame;
}
if (new_dir != v->direction) {
v->direction = new_dir;
v->cur_speed -= v->cur_speed >> 2;
}
v->UpdateDeltaXY(v->direction);
RoadZPosAffectSpeed(v, SetRoadVehPosition(v, x, y));
return true;
}
if (rd.x & RDE_TURNED) {
/* Vehicle has finished turning around, it will now head back onto the same tile */
Trackdir dir;
uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
RoadBits tram;
if (v->u.road.roadtype == ROADTYPE_TRAM && !IsRoadDepotTile(v->tile) && CountBits(tram = GetAnyRoadBits(v->tile, ROADTYPE_TRAM, true)) == 1) {
/*
* The tram is turning around with one tram 'roadbit'. This means that
* it is using the 'big' corner 'drive data'. However, to support the
* trams to take a small corner, there is a 'turned' marker in the middle
* of the turning 'drive data'. When the tram took the long corner, we
* will still use the 'big' corner drive data, but we advance it one
* frame. We furthermore set the driving direction so the turning is
* going to be properly shown.
*/
turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
switch (rd.x & 0x3) {
default: NOT_REACHED();
case DIAGDIR_NW: dir = TRACKDIR_RVREV_SE; break;
case DIAGDIR_NE: dir = TRACKDIR_RVREV_SW; break;
case DIAGDIR_SE: dir = TRACKDIR_RVREV_NW; break;
case DIAGDIR_SW: dir = TRACKDIR_RVREV_NE; break;
}
} else {
if (IsRoadVehFront(v)) {
/* If this is the front engine, look for the right path. */
dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
} else {
dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
}
}
if (dir == INVALID_TRACKDIR) {
v->cur_speed = 0;
return false;
}
const RoadDriveEntry *rdp = _road_drive_data[v->u.road.roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + dir];
int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
if (IsRoadVehFront(v) && RoadVehFindCloseTo(v, x, y, new_dir) != NULL) return false;
uint32 r = VehicleEnterTile(v, v->tile, x, y);
if (HasBit(r, VETS_CANNOT_ENTER)) {
v->cur_speed = 0;
return false;
}
v->u.road.state = dir;
v->u.road.frame = turn_around_start_frame;
if (new_dir != v->direction) {
v->direction = new_dir;
v->cur_speed -= v->cur_speed >> 2;
}
v->UpdateDeltaXY(v->direction);
RoadZPosAffectSpeed(v, SetRoadVehPosition(v, x, y));
return true;
}
/* This vehicle is not in a wormhole and it hasn't entered a new tile. If
* it's on a depot tile, check if it's time to activate the next vehicle in
* the chain yet. */
if (v->Next() != NULL && IsRoadDepotTile(v->tile)) {
if (v->u.road.frame == v->u.road.cached_veh_length + RVC_DEPOT_START_FRAME) {
RoadVehLeaveDepot(v->Next(), false);
}
}
/* Calculate new position for the vehicle */
int x = (v->x_pos & ~15) + (rd.x & 15);
int y = (v->y_pos & ~15) + (rd.y & 15);
Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
if (IsRoadVehFront(v) && !IsInsideMM(v->u.road.state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
/* Vehicle is not in a road stop.
* Check for another vehicle to overtake */
Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
if (u != NULL) {
u = u->First();
/* There is a vehicle in front overtake it if possible */
if (v->u.road.overtaking == 0) RoadVehCheckOvertake(v, u);
if (v->u.road.overtaking == 0) v->cur_speed = u->cur_speed;
return false;
}
}
Direction old_dir = v->direction;
if (new_dir != old_dir) {
v->direction = new_dir;
v->cur_speed -= (v->cur_speed >> 2);
if (old_dir != v->u.road.state) {
/* The vehicle is in a road stop */
v->UpdateDeltaXY(v->direction);
SetRoadVehPosition(v, v->x_pos, v->y_pos);
/* Note, return here means that the frame counter is not incremented
* for vehicles changing direction in a road stop. This causes frames to
* be repeated. (XXX) Is this intended? */
return true;
}
}
/* If the vehicle is in a normal road stop and the frame equals the stop frame OR
* if the vehicle is in a drive-through road stop and this is the destination station
* and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
* (the station test and stop type test ensure that other vehicles, using the road stop as
* a through route, do not stop) */
if (IsRoadVehFront(v) && ((IsInsideMM(v->u.road.state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
_road_veh_data_1[v->u.road.state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)] == v->u.road.frame) ||
(IsInsideMM(v->u.road.state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile)) &&
v->owner == GetTileOwner(v->tile) &&
GetRoadStopType(v->tile) == (IsCargoInClass(v->cargo_type, CC_PASSENGERS) ? ROADSTOP_BUS : ROADSTOP_TRUCK) &&
v->u.road.frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
RoadStop *rs = GetRoadStopByTile(v->tile, GetRoadStopType(v->tile));
Station *st = GetStationByTile(v->tile);
/* Vehicle is at the stop position (at a bay) in a road stop.
* Note, if vehicle is loading/unloading it has already been handled,
* so if we get here the vehicle has just arrived or is just ready to leave. */
if (!v->current_order.IsType(OT_LEAVESTATION)) {
/* Vehicle has arrived at a bay in a road stop */
if (IsDriveThroughStopTile(v->tile)) {
TileIndex next_tile = TILE_ADD(v->tile, TileOffsByDir(v->direction));
RoadStopType type = IsCargoInClass(v->cargo_type, CC_PASSENGERS) ? ROADSTOP_BUS : ROADSTOP_TRUCK;
/* Check if next inline bay is free */
if (IsDriveThroughStopTile(next_tile) && (GetRoadStopType(next_tile) == type) && GetStationIndex(v->tile) == GetStationIndex(next_tile)) {
RoadStop *rs_n = GetRoadStopByTile(next_tile, type);
if (rs_n->IsFreeBay(HasBit(v->u.road.state, RVS_USING_SECOND_BAY)) && rs_n->num_vehicles < RoadStop::MAX_VEHICLES) {
/* Bay in next stop along is free - use it */
ClearSlot(v);
rs_n->num_vehicles++;
v->u.road.slot = rs_n;
v->dest_tile = rs_n->xy;
v->u.road.slot_age = 14;
v->u.road.frame++;
RoadZPosAffectSpeed(v, SetRoadVehPosition(v, x, y));
return true;
}
}
}
rs->SetEntranceBusy(false);
v->last_station_visited = st->index;
if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
RoadVehArrivesAt(v, st);
v->BeginLoading();
return false;
}
} else {
/* Vehicle is ready to leave a bay in a road stop */
if (rs->IsEntranceBusy()) {
/* Road stop entrance is busy, so wait as there is nowhere else to go */
v->cur_speed = 0;
return false;
}
v->current_order.Free();
ClearSlot(v);
}
if (IsStandardRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
if (rs == v->u.road.slot) {
/* We are leaving the correct station */
ClearSlot(v);
} else if (v->u.road.slot != NULL) {
/* We are leaving the wrong station
* XXX The question is .. what to do? Actually we shouldn't be here
* but I guess we need to clear the slot */
DEBUG(ms, 0, "Vehicle %d (index %d) arrived at wrong stop", v->unitnumber, v->index);
if (v->tile != v->dest_tile) {
DEBUG(ms, 2, " current tile 0x%X is not destination tile 0x%X. Route problem", v->tile, v->dest_tile);
}
if (v->dest_tile != v->u.road.slot->xy) {
DEBUG(ms, 2, " stop tile 0x%X is not destination tile 0x%X. Multistop desync", v->u.road.slot->xy, v->dest_tile);
}
if (!v->current_order.IsType(OT_GOTO_STATION)) {
DEBUG(ms, 2, " current order type (%d) is not OT_GOTO_STATION", v->current_order.GetType());
} else {
if (v->current_order.GetDestination() != st->index)
DEBUG(ms, 2, " current station %d is not target station in current_order.station (%d)",
st->index, v->current_order.GetDestination());
}
DEBUG(ms, 2, " force a slot clearing");
ClearSlot(v);
}
StartRoadVehSound(v);
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
/* Check tile position conditions - i.e. stop position in depot,
* entry onto bridge or into tunnel */
uint32 r = VehicleEnterTile(v, v->tile, x, y);
if (HasBit(r, VETS_CANNOT_ENTER)) {
v->cur_speed = 0;
return false;
}
if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
v->current_order.Free();
ClearSlot(v);
}
/* Move to next frame unless vehicle arrived at a stop position
* in a depot or entered a tunnel/bridge */
if (!HasBit(r, VETS_ENTERED_WORMHOLE)) v->u.road.frame++;
v->UpdateDeltaXY(v->direction);
RoadZPosAffectSpeed(v, SetRoadVehPosition(v, x, y));
return true;
}
static void RoadVehController(Vehicle *v)
{
/* decrease counters */
v->tick_counter++;
v->current_order_time++;
if (v->u.road.reverse_ctr != 0) v->u.road.reverse_ctr--;
/* handle crashed */
if (v->vehstatus & VS_CRASHED) {
RoadVehIsCrashed(v);
return;
}
RoadVehCheckTrainCrash(v);
/* road vehicle has broken down? */
if (v->breakdown_ctr != 0) {
if (v->breakdown_ctr <= 2) {
HandleBrokenRoadVeh(v);
return;
}
if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
}
if (v->vehstatus & VS_STOPPED) return;
ProcessOrders(v);
v->HandleLoading();
if (v->current_order.IsType(OT_LOADING)) return;
if (v->IsInDepot() && RoadVehLeaveDepot(v, true)) return;
/* Check how far the vehicle needs to proceed */
int j = RoadVehAccelerate(v);
int adv_spd = (v->direction & 1) ? 192 : 256;
while (j >= adv_spd) {
j -= adv_spd;
Vehicle *u = v;
for (Vehicle *prev = NULL; u != NULL; prev = u, u = u->Next()) {
if (!IndividualRoadVehicleController(u, prev)) break;
}
/* 192 spd used for going straight, 256 for going diagonally. */
adv_spd = (v->direction & 1) ? 192 : 256;
/* Test for a collision, but only if another movement will occur. */
if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
}
for (Vehicle *u = v; u != NULL; u = u->Next()) {
if ((u->vehstatus & VS_HIDDEN) != 0) continue;
uint16 old_image = u->cur_image;
u->cur_image = u->GetImage(u->direction);
if (old_image != u->cur_image) VehicleMove(u, true);
}
if (v->progress == 0) v->progress = j;
}
static void AgeRoadVehCargo(Vehicle *v)
{
if (_age_cargo_skip_counter != 0) return;
v->cargo.AgeCargo();
}
void RoadVehicle::Tick()
{
AgeRoadVehCargo(this);
if (IsRoadVehFront(this)) {
if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
RoadVehController(this);
}
}
static void CheckIfRoadVehNeedsService(Vehicle *v)
{
/* If we already got a slot at a stop, use that FIRST, and go to a depot later */
if (v->u.road.slot != NULL || _settings_game.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
if (v->IsInDepot()) {
VehicleServiceInDepot(v);
return;
}
/* XXX If we already have a depot order, WHY do we search over and over? */
const Depot *depot = FindClosestRoadDepot(v);
if (depot == NULL || DistanceManhattan(v->tile, depot->xy) > 12) {
if (v->current_order.IsType(OT_GOTO_DEPOT)) {
v->current_order.MakeDummy();
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
return;
}
if (v->current_order.IsType(OT_GOTO_DEPOT) &&
v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS &&
!Chance16(1, 20)) {
return;
}
if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
ClearSlot(v);
v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
v->dest_tile = depot->xy;
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
void RoadVehicle::OnNewDay()
{
if (!IsRoadVehFront(this)) return;
if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
if (this->u.road.blocked_ctr == 0) CheckVehicleBreakdown(this);
AgeVehicle(this);
CheckIfRoadVehNeedsService(this);
CheckOrders(this);
/* Current slot has expired */
if (this->current_order.IsType(OT_GOTO_STATION) && this->u.road.slot != NULL && this->u.road.slot_age-- == 0) {
DEBUG(ms, 3, "Slot expired for vehicle %d (index %d) at stop 0x%X",
this->unitnumber, this->index, this->u.road.slot->xy);
ClearSlot(this);
}
/* update destination */
if (!(this->vehstatus & VS_STOPPED) && this->current_order.IsType(OT_GOTO_STATION) && !(this->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) && this->u.road.slot == NULL && !(this->vehstatus & VS_CRASHED)) {
Station *st = GetStation(this->current_order.GetDestination());
RoadStop *rs = st->GetPrimaryRoadStop(this);
RoadStop *best = NULL;
if (rs != NULL) {
/* We try to obtain a slot if:
* 1) we're reasonably close to the primary road stop
* or
* 2) we're somewhere close to the station rectangle (to make sure we do assign
* slots even if the station and its road stops are incredibly spread out)
*/
if (DistanceManhattan(this->tile, rs->xy) < 16 || st->rect.PtInExtendedRect(TileX(this->tile), TileY(this->tile), 2)) {
uint dist, badness;
uint minbadness = UINT_MAX;
DEBUG(ms, 2, "Attempting to obtain a slot for vehicle %d (index %d) at station %d (0x%X)",
this->unitnumber, this->index, st->index, st->xy
);
/* Now we find the nearest road stop that has a free slot */
for (; rs != NULL; rs = rs->GetNextRoadStop(this)) {
if (rs->num_vehicles >= RoadStop::MAX_VEHICLES) {
DEBUG(ms, 4, " stop 0x%X's queue is full, not treating further", rs->xy);
continue;
}
dist = RoadFindPathToStop(this, rs->xy);
if (dist == UINT_MAX) {
DEBUG(ms, 4, " stop 0x%X is unreachable, not treating further", rs->xy);
continue;
}
badness = (rs->num_vehicles + 1) * (rs->num_vehicles + 1) + dist;
DEBUG(ms, 4, " stop 0x%X has %d vehicle%s waiting", rs->xy, rs->num_vehicles, rs->num_vehicles == 1 ? "":"s");
DEBUG(ms, 4, " distance is %u", dist);
DEBUG(ms, 4, " badness %u", badness);
if (badness < minbadness) {
best = rs;
minbadness = badness;
}
}
if (best != NULL) {
best->num_vehicles++;
DEBUG(ms, 3, "Assigned to stop 0x%X", best->xy);
this->u.road.slot = best;
this->dest_tile = best->xy;
this->u.road.slot_age = 14;
} else {
DEBUG(ms, 3, "Could not find a suitable stop");
}
} else {
DEBUG(ms, 5, "Distance from station too far. Postponing slotting for vehicle %d (index %d) at station %d, (0x%X)",
this->unitnumber, this->index, st->index, st->xy);
}
} else {
DEBUG(ms, 4, "No road stop for vehicle %d (index %d) at station %d (0x%X)",
this->unitnumber, this->index, st->index, st->xy);
}
}
if (this->running_ticks == 0) return;
CommandCost cost(EXPENSES_ROADVEH_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
this->profit_this_year -= cost.GetCost();
this->running_ticks = 0;
SubtractMoneyFromCompanyFract(this->owner, cost);
InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
InvalidateWindowClasses(WC_ROADVEH_LIST);
}
/** Refit a road vehicle to the specified cargo type
* @param tile unused
* @param flags operation to perform
* @param p1 Vehicle ID of the vehicle to refit
* @param p2 Bitstuffed elements
* - p2 = (bit 0-7) - the new cargo type to refit to
* - p2 = (bit 8-15) - the new cargo subtype to refit to
* - p2 = (bit 16) - refit only this vehicle
* @return cost of refit or error
*/
CommandCost CmdRefitRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v;
CommandCost cost(EXPENSES_ROADVEH_RUN);
CargoID new_cid = GB(p2, 0, 8);
byte new_subtype = GB(p2, 8, 8);
bool only_this = HasBit(p2, 16);
uint16 capacity = CALLBACK_FAILED;
uint total_capacity = 0;
if (!IsValidVehicleID(p1)) return CMD_ERROR;
v = GetVehicle(p1);
if (v->type != VEH_ROAD || !CheckOwnership(v->owner)) return CMD_ERROR;
if (!v->IsStoppedInDepot()) return_cmd_error(STR_9013_MUST_BE_STOPPED_INSIDE);
if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_CAN_T_REFIT_DESTROYED_VEHICLE);
if (new_cid >= NUM_CARGO) return CMD_ERROR;
for (; v != NULL; v = (only_this ? NULL : v->Next())) {
/* XXX: We refit all the attached wagons en-masse if they can be
* refitted. This is how TTDPatch does it. TODO: Have some nice
* [Refit] button near each wagon. */
if (!CanRefitTo(v->engine_type, new_cid)) continue;
const Engine *e = GetEngine(v->engine_type);
if (!e->CanCarryCargo()) continue;
if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
/* Back up the cargo type */
CargoID temp_cid = v->cargo_type;
byte temp_subtype = v->cargo_subtype;
v->cargo_type = new_cid;
v->cargo_subtype = new_subtype;
/* Check the refit capacity callback */
capacity = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
/* Restore the original cargo type */
v->cargo_type = temp_cid;
v->cargo_subtype = temp_subtype;
}
if (capacity == CALLBACK_FAILED) {
/* callback failed or not used, use default capacity */
CargoID old_cid = e->GetDefaultCargoType();
/* normally, the capacity depends on the cargo type, a vehicle can
* carry twice as much mail/goods as normal cargo, and four times as
* many passengers
*/
capacity = GetVehicleProperty(v, 0x0F, e->u.road.capacity);
switch (old_cid) {
case CT_PASSENGERS: break;
case CT_MAIL:
case CT_GOODS: capacity *= 2; break;
default: capacity *= 4; break;
}
switch (new_cid) {
case CT_PASSENGERS: break;
case CT_MAIL:
case CT_GOODS: capacity /= 2; break;
default: capacity /= 4; break;
}
}
total_capacity += capacity;
if (new_cid != v->cargo_type) {
cost.AddCost(GetRefitCost(v->engine_type));
}
if (flags & DC_EXEC) {
v->cargo_cap = capacity;
v->cargo.Truncate((v->cargo_type == new_cid) ? capacity : 0);
v->cargo_type = new_cid;
v->cargo_subtype = new_subtype;
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
}
}
if (flags & DC_EXEC) RoadVehUpdateCache(GetVehicle(p1)->First());
_returned_refit_capacity = total_capacity;
return cost;
}
| 66,056
|
C++
|
.cpp
| 1,690
| 35.951479
| 231
| 0.682065
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,122
|
road_map.cpp
|
EnergeticBark_OpenTTD-3DS/src/road_map.cpp
|
/* $Id$ */
/** @file road_map.cpp Complex road accessors. */
#include "stdafx.h"
#include "station_map.h"
#include "tunnelbridge_map.h"
RoadBits GetAnyRoadBits(TileIndex tile, RoadType rt, bool straight_tunnel_bridge_entrance)
{
if (!HasTileRoadType(tile, rt)) return ROAD_NONE;
switch (GetTileType(tile)) {
case MP_ROAD:
switch (GetRoadTileType(tile)) {
default:
case ROAD_TILE_NORMAL: return GetRoadBits(tile, rt);
case ROAD_TILE_CROSSING: return GetCrossingRoadBits(tile);
case ROAD_TILE_DEPOT: return DiagDirToRoadBits(GetRoadDepotDirection(tile));
}
case MP_STATION:
if (!IsRoadStopTile(tile)) return ROAD_NONE;
if (IsDriveThroughStopTile(tile)) return (GetRoadStopDir(tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y;
return DiagDirToRoadBits(GetRoadStopDir(tile));
case MP_TUNNELBRIDGE:
if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return ROAD_NONE;
return straight_tunnel_bridge_entrance ?
AxisToRoadBits(DiagDirToAxis(GetTunnelBridgeDirection(tile))) :
DiagDirToRoadBits(ReverseDiagDir(GetTunnelBridgeDirection(tile)));
default: return ROAD_NONE;
}
}
TrackBits GetAnyRoadTrackBits(TileIndex tile, RoadType rt)
{
/* Don't allow local authorities to build roads through road depots or road stops. */
if (IsRoadDepotTile(tile) || (IsTileType(tile, MP_STATION) && !IsDriveThroughStopTile(tile)) || !HasTileRoadType(tile, rt)) {
return TRACK_BIT_NONE;
}
return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_ROAD, RoadTypeToRoadTypes(rt)));
}
| 1,541
|
C++
|
.cpp
| 36
| 39.722222
| 126
| 0.762383
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,123
|
cheat.cpp
|
EnergeticBark_OpenTTD-3DS/src/cheat.cpp
|
/* $Id$ */
/** @file cheat.cpp Handling (loading/saving/initializing) of cheats. */
#include "stdafx.h"
#include "cheat_type.h"
Cheats _cheats;
void InitializeCheats()
{
memset(&_cheats, 0, sizeof(Cheats));
}
bool CheatHasBeenUsed()
{
/* Cannot use lengthof because _cheats is of type Cheats, not Cheat */
const Cheat *cht = (Cheat*)&_cheats;
const Cheat *cht_last = &cht[sizeof(_cheats) / sizeof(Cheat)];
for (; cht != cht_last; cht++) {
if (cht->been_used) return true;
}
return false;
}
| 506
|
C++
|
.cpp
| 19
| 24.789474
| 72
| 0.691667
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
1,539,124
|
ini.cpp
|
EnergeticBark_OpenTTD-3DS/src/ini.cpp
|
/* $Id$ */
/** @file ini.cpp Definition of the IniItem class, related to reading/writing '*.ini' files. */
#include "stdafx.h"
#include "core/alloc_func.hpp"
#include "core/math_func.hpp"
#include "core/mem_func.hpp"
#include "debug.h"
#include "ini_type.h"
#include "string_func.h"
#include "fileio_func.h"
#ifndef N3DS
#if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 500)
# define WITH_FDATASYNC
# include <unistd.h>
#endif
#endif /* N3DS */
#ifdef WIN32
# include <shellapi.h>
#endif
IniItem::IniItem(IniGroup *parent, const char *name, size_t len) : next(NULL), value(NULL), comment(NULL)
{
if (len == 0) len = strlen(name);
this->name = strndup(name, len);
*parent->last_item = this;
parent->last_item = &this->next;
}
IniItem::~IniItem()
{
free(this->name);
free(this->value);
free(this->comment);
delete this->next;
}
void IniItem::SetValue(const char *value)
{
free(this->value);
this->value = strdup(value);
}
IniGroup::IniGroup(IniFile *parent, const char *name, size_t len) : next(NULL), type(IGT_VARIABLES), item(NULL), comment(NULL)
{
if (len == 0) len = strlen(name);
this->name = strndup(name, len);
this->last_item = &this->item;
*parent->last_group = this;
parent->last_group = &this->next;
if (parent->list_group_names == NULL) return;
for (uint i = 0; parent->list_group_names[i] != NULL; i++) {
if (strcmp(this->name, parent->list_group_names[i]) == 0) {
this->type = IGT_LIST;
return;
}
}
}
IniGroup::~IniGroup()
{
free(this->name);
free(this->comment);
delete this->item;
delete this->next;
}
IniItem *IniGroup::GetItem(const char *name, bool create)
{
for (IniItem *item = this->item; item != NULL; item = item->next) {
if (strcmp(item->name, name) == 0) return item;
}
if (!create) return NULL;
/* otherwise make a new one */
return new IniItem(this, name, strlen(name));
}
void IniGroup::Clear()
{
delete this->item;
this->item = NULL;
this->last_item = &this->item;
}
IniFile::IniFile(const char **list_group_names) : group(NULL), comment(NULL), list_group_names(list_group_names)
{
this->last_group = &this->group;
}
IniFile::~IniFile()
{
free(this->comment);
delete this->group;
}
IniGroup *IniFile::GetGroup(const char *name, size_t len)
{
if (len == 0) len = strlen(name);
/* does it exist already? */
for (IniGroup *group = this->group; group != NULL; group = group->next) {
if (!memcmp(group->name, name, len) && group->name[len] == 0) {
return group;
}
}
/* otherwise make a new one */
IniGroup *group = new IniGroup(this, name, len);
group->comment = strdup("\n");
return group;
}
void IniFile::RemoveGroup(const char *name)
{
size_t len = strlen(name);
IniGroup *prev = NULL;
IniGroup *group;
/* does it exist already? */
for (group = this->group; group != NULL; prev = group, group = group->next) {
if (memcmp(group->name, name, len) == 0) {
break;
}
}
if (group == NULL) return;
if (prev != NULL) {
prev->next = prev->next->next;
if (this->last_group == &group->next) this->last_group = &prev->next;
} else {
this->group = this->group->next;
if (this->last_group == &group->next) this->last_group = &this->group;
}
group->next = NULL;
delete group;
}
void IniFile::LoadFromDisk(const char *filename)
{
assert(this->last_group == &this->group);
char buffer[1024];
IniGroup *group = NULL;
char *comment = NULL;
uint comment_size = 0;
uint comment_alloc = 0;
size_t end;
/*
* Now we are going to open a file that contains no more than simple
* plain text. That would raise the question: "why open the file as
* if it is a binary file?". That's simple... Microsoft, in all
* their greatness and wisdom decided it would be useful if ftell
* is aware of '\r\n' and "sees" that as a single character. The
* easiest way to test for that situation is by searching for '\n'
* and decrease the value every time you encounter a '\n'. This will
* thus also make ftell "see" the '\r' when it is not there, so the
* result of ftell will be highly unreliable. So to work around this
* marvel of wisdom we have to open in as a binary file.
*/
FILE *in = FioFOpenFile(filename, "rb", DATA_DIR, &end);
if (in == NULL) return;
end += ftell(in);
/* for each line in the file */
while ((size_t)ftell(in) < end && fgets(buffer, sizeof(buffer), in)) {
char c, *s;
/* trim whitespace from the left side */
for (s = buffer; *s == ' ' || *s == '\t'; s++) {}
/* trim whitespace from right side. */
char *e = s + strlen(s);
while (e > s && ((c = e[-1]) == '\n' || c == '\r' || c == ' ' || c == '\t')) e--;
*e = '\0';
/* skip comments and empty lines */
if (*s == '#' || *s == ';' || *s == '\0') {
uint ns = comment_size + (e - s + 1);
uint a = comment_alloc;
/* add to comment */
if (ns > a) {
a = max(a, 128U);
do a *= 2; while (a < ns);
comment = ReallocT(comment, comment_alloc = a);
}
uint pos = comment_size;
comment_size += (e - s + 1);
comment[pos + e - s] = '\n'; // comment newline
memcpy(comment + pos, s, e - s); // copy comment contents
continue;
}
/* it's a group? */
if (s[0] == '[') {
if (e[-1] != ']') {
ShowInfoF("ini: invalid group name '%s'", buffer);
} else {
e--;
}
s++; // skip [
group = new IniGroup(this, s, e - s);
if (comment_size) {
group->comment = strndup(comment, comment_size);
comment_size = 0;
}
} else if (group) {
char *t;
/* find end of keyname */
if (*s == '\"') {
s++;
for (t = s; *t != '\0' && *t != '\"'; t++) {}
if (*t == '\"') *t = ' ';
} else {
for (t = s; *t != '\0' && *t != '=' && *t != '\t' && *t != ' '; t++) {}
}
/* it's an item in an existing group */
IniItem *item = new IniItem(group, s, t - s);
if (comment_size) {
item->comment = strndup(comment, comment_size);
comment_size = 0;
}
/* find start of parameter */
while (*t == '=' || *t == ' ' || *t == '\t') t++;
/* remove starting quotation marks */
if (*t == '\"') t++;
/* remove ending quotation marks */
e = t + strlen(t);
if (e > t && e[-1] == '\"') e--;
*e = '\0';
item->value = strndup(t, e - t);
} else {
/* it's an orphan item */
ShowInfoF("ini: '%s' outside of group", buffer);
}
}
if (comment_size > 0) {
this->comment = strndup(comment, comment_size);
comment_size = 0;
}
free(comment);
fclose(in);
}
bool IniFile::SaveToDisk(const char *filename)
{
/*
* First write the configuration to a (temporary) file and then rename
* that file. This to prevent that when OpenTTD crashes during the save
* you end up with a truncated configuration file.
*/
char file_new[MAX_PATH];
strecpy(file_new, filename, lastof(file_new));
strecat(file_new, ".new", lastof(file_new));
FILE *f = fopen(file_new, "w");
if (f == NULL) return false;
for (const IniGroup *group = this->group; group != NULL; group = group->next) {
if (group->comment) fputs(group->comment, f);
fprintf(f, "[%s]\n", group->name);
for (const IniItem *item = group->item; item != NULL; item = item->next) {
assert(item->value != NULL);
if (item->comment != NULL) fputs(item->comment, f);
/* protect item->name with quotes if needed */
if (strchr(item->name, ' ') != NULL) {
fprintf(f, "\"%s\"", item->name);
} else {
fprintf(f, "%s", item->name);
}
fprintf(f, " = %s\n", item->value);
}
}
if (this->comment) fputs(this->comment, f);
/*
* POSIX (and friends) do not guarantee that when a file is closed it is
* flushed to the disk. So we manually flush it do disk if we have the
* APIs to do so. We only need to flush the data as the metadata itself
* (modification date etc.) is not important to us; only the real data is.
*/
#ifdef WITH_FDATASYNC
int ret = fdatasync(fileno(f));
fclose(f);
if (ret != 0) return false;
#else
fclose(f);
#endif
#if defined(WIN32) || defined(WIN64)
/* Allocate space for one more \0 character. */
TCHAR tfilename[MAX_PATH + 1], tfile_new[MAX_PATH + 1];
_tcsncpy(tfilename, OTTD2FS(filename), MAX_PATH);
_tcsncpy(tfile_new, OTTD2FS(file_new), MAX_PATH);
/* SHFileOperation wants a double '\0' terminated string. */
tfilename[MAX_PATH - 1] = '\0';
tfile_new[MAX_PATH - 1] = '\0';
tfilename[_tcslen(tfilename) + 1] = '\0';
tfile_new[_tcslen(tfile_new) + 1] = '\0';
/* Rename file without any user confirmation. */
SHFILEOPSTRUCT shfopt;
MemSetT(&shfopt, 0);
shfopt.wFunc = FO_MOVE;
shfopt.fFlags = FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_NOERRORUI | FOF_SILENT;
shfopt.pFrom = tfile_new;
shfopt.pTo = tfilename;
SHFileOperation(&shfopt);
#else
rename(file_new, filename);
#endif
return true;
}
| 8,730
|
C++
|
.cpp
| 283
| 28.222615
| 126
| 0.630049
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,125
|
vehicle.cpp
|
EnergeticBark_OpenTTD-3DS/src/vehicle.cpp
|
/* $Id$ */
/** @file vehicle.cpp Base implementations of all vehicles. */
#include "stdafx.h"
#include "gui.h"
#include "openttd.h"
#include "debug.h"
#include "roadveh.h"
#include "ship.h"
#include "spritecache.h"
#include "landscape.h"
#include "timetable.h"
#include "viewport_func.h"
#include "news_func.h"
#include "command_func.h"
#include "company_func.h"
#include "vehicle_gui.h"
#include "train.h"
#include "aircraft.h"
#include "newgrf_engine.h"
#include "newgrf_sound.h"
#include "newgrf_station.h"
#include "group.h"
#include "group_gui.h"
#include "strings_func.h"
#include "zoom_func.h"
#include "functions.h"
#include "date_func.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "autoreplace_func.h"
#include "autoreplace_gui.h"
#include "oldpool_func.h"
#include "ai/ai.hpp"
#include "core/smallmap_type.hpp"
#include "depot_func.h"
#include "settings_type.h"
#include "network/network.h"
#include "table/sprites.h"
#include "table/strings.h"
#define GEN_HASH(x, y) ((GB((y), 6, 6) << 6) + GB((x), 7, 6))
VehicleID _vehicle_id_ctr_day;
const Vehicle *_place_clicked_vehicle;
VehicleID _new_vehicle_id;
uint16 _returned_refit_capacity;
/* Initialize the vehicle-pool */
DEFINE_OLD_POOL_GENERIC(Vehicle, Vehicle)
/** Function to tell if a vehicle needs to be autorenewed
* @param *c The vehicle owner
* @return true if the vehicle is old enough for replacement
*/
bool Vehicle::NeedsAutorenewing(const Company *c) const
{
/* We can always generate the Company pointer when we have the vehicle.
* However this takes time and since the Company pointer is often present
* when this function is called then it's faster to pass the pointer as an
* argument rather than finding it again. */
assert(c == GetCompany(this->owner));
if (!c->engine_renew) return false;
if (this->age - this->max_age < (c->engine_renew_months * 30)) return false;
if (this->age == 0) return false; // rail cars don't age and lacks a max age
return true;
}
void VehicleServiceInDepot(Vehicle *v)
{
v->date_of_last_service = _date;
v->breakdowns_since_last_service = 0;
v->reliability = GetEngine(v->engine_type)->reliability;
InvalidateWindow(WC_VEHICLE_DETAILS, v->index); // ensure that last service date and reliability are updated
}
bool Vehicle::NeedsServicing() const
{
if (this->vehstatus & (VS_STOPPED | VS_CRASHED)) return false;
if (_settings_game.order.no_servicing_if_no_breakdowns && _settings_game.difficulty.vehicle_breakdowns == 0) {
/* Vehicles set for autoreplacing needs to go to a depot even if breakdowns are turned off.
* Note: If servicing is enabled, we postpone replacement till next service. */
return EngineHasReplacementForCompany(GetCompany(this->owner), this->engine_type, this->group_id);
}
return _settings_game.vehicle.servint_ispercent ?
(this->reliability < GetEngine(this->engine_type)->reliability * (100 - this->service_interval) / 100) :
(this->date_of_last_service + this->service_interval < _date);
}
bool Vehicle::NeedsAutomaticServicing() const
{
if (_settings_game.order.gotodepot && VehicleHasDepotOrders(this)) return false;
if (this->current_order.IsType(OT_LOADING)) return false;
if (this->current_order.IsType(OT_GOTO_DEPOT) && this->current_order.GetDepotOrderType() != ODTFB_SERVICE) return false;
return NeedsServicing();
}
/**
* Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
* @param engine The engine that caused the problem
* @param part1 Part 1 of the error message, taking the grfname as parameter 1
* @param part2 Part 2 of the error message, taking the engine as parameter 2
* @param bug_type Flag to check and set in grfconfig
* @param critical Shall the "OpenTTD might crash"-message be shown when the player tries to unpause?
*/
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBugs bug_type, bool critical)
{
const Engine *e = GetEngine(engine);
uint32 grfid = e->grffile->grfid;
GRFConfig *grfconfig = GetGRFConfig(grfid);
if (!HasBit(grfconfig->grf_bugs, bug_type)) {
SetBit(grfconfig->grf_bugs, bug_type);
SetDParamStr(0, grfconfig->name);
SetDParam(1, engine);
ShowErrorMessage(part2, part1, 0, 0);
if (!_networking) _pause_game = (critical ? -1 : 1);
}
/* debug output */
char buffer[512];
SetDParamStr(0, grfconfig->name);
GetString(buffer, part1, lastof(buffer));
DEBUG(grf, 0, "%s", buffer + 3);
SetDParam(1, engine);
GetString(buffer, part2, lastof(buffer));
DEBUG(grf, 0, "%s", buffer + 3);
}
StringID VehicleInTheWayErrMsg(const Vehicle *v)
{
switch (v->type) {
case VEH_TRAIN: return STR_8803_TRAIN_IN_THE_WAY;
case VEH_ROAD: return STR_9000_ROAD_VEHICLE_IN_THE_WAY;
case VEH_AIRCRAFT: return STR_A015_AIRCRAFT_IN_THE_WAY;
default: return STR_980E_SHIP_IN_THE_WAY;
}
}
static Vehicle *EnsureNoVehicleProcZ(Vehicle *v, void *data)
{
byte z = *(byte*)data;
if (v->type == VEH_DISASTER || (v->type == VEH_AIRCRAFT && v->subtype == AIR_SHADOW)) return NULL;
if (v->z_pos > z) return NULL;
_error_message = VehicleInTheWayErrMsg(v);
return v;
}
bool EnsureNoVehicleOnGround(TileIndex tile)
{
byte z = GetTileMaxZ(tile);
return !HasVehicleOnPos(tile, &z, &EnsureNoVehicleProcZ);
}
/** Procedure called for every vehicle found in tunnel/bridge in the hash map */
static Vehicle *GetVehicleTunnelBridgeProc(Vehicle *v, void *data)
{
if (v->type != VEH_TRAIN && v->type != VEH_ROAD && v->type != VEH_SHIP) return NULL;
if (v == (const Vehicle *)data) return NULL;
_error_message = VehicleInTheWayErrMsg(v);
return v;
}
/**
* Finds vehicle in tunnel / bridge
* @param tile first end
* @param endtile second end
* @param ignore Ignore this vehicle when searching
* @return true if the bridge has a vehicle
*/
bool HasVehicleOnTunnelBridge(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
{
return HasVehicleOnPos(tile, (void *)ignore, &GetVehicleTunnelBridgeProc) ||
HasVehicleOnPos(endtile, (void *)ignore, &GetVehicleTunnelBridgeProc);
}
Vehicle::Vehicle()
{
this->type = VEH_INVALID;
this->coord.left = INVALID_COORD;
this->group_id = DEFAULT_GROUP;
this->fill_percent_te_id = INVALID_TE_ID;
this->first = this;
this->colourmap = PAL_NONE;
}
/**
* Get a value for a vehicle's random_bits.
* @return A random value from 0 to 255.
*/
byte VehicleRandomBits()
{
return GB(Random(), 0, 8);
}
/* static */ bool Vehicle::AllocateList(Vehicle **vl, int num)
{
if (!Vehicle::CanAllocateItem(num)) return false;
if (vl == NULL) return true;
uint counter = _Vehicle_pool.first_free_index;
for (int i = 0; i != num; i++) {
vl[i] = new (AllocateRaw(counter)) InvalidVehicle();
counter++;
}
return true;
}
/* Size of the hash, 6 = 64 x 64, 7 = 128 x 128. Larger sizes will (in theory) reduce hash
* lookup times at the expense of memory usage. */
const int HASH_BITS = 7;
const int HASH_SIZE = 1 << HASH_BITS;
const int HASH_MASK = HASH_SIZE - 1;
const int TOTAL_HASH_SIZE = 1 << (HASH_BITS * 2);
const int TOTAL_HASH_MASK = TOTAL_HASH_SIZE - 1;
/* Resolution of the hash, 0 = 1*1 tile, 1 = 2*2 tiles, 2 = 4*4 tiles, etc.
* Profiling results show that 0 is fastest. */
const int HASH_RES = 0;
static Vehicle *_new_vehicle_position_hash[TOTAL_HASH_SIZE];
static Vehicle *VehicleFromHash(int xl, int yl, int xu, int yu, void *data, VehicleFromPosProc *proc, bool find_first)
{
for (int y = yl; ; y = (y + (1 << HASH_BITS)) & (HASH_MASK << HASH_BITS)) {
for (int x = xl; ; x = (x + 1) & HASH_MASK) {
Vehicle *v = _new_vehicle_position_hash[(x + y) & TOTAL_HASH_MASK];
for (; v != NULL; v = v->next_new_hash) {
Vehicle *a = proc(v, data);
if (find_first && a != NULL) return a;
}
if (x == xu) break;
}
if (y == yu) break;
}
return NULL;
}
/**
* Helper function for FindVehicleOnPos/HasVehicleOnPos.
* @note Do not call this function directly!
* @param x The X location on the map
* @param y The Y location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
* @param find_first Whether to return on the first found or iterate over
* all vehicles
* @return the best matching or first vehicle (depending on find_first).
*/
static Vehicle *VehicleFromPosXY(int x, int y, void *data, VehicleFromPosProc *proc, bool find_first)
{
const int COLL_DIST = 6;
/* Hash area to scan is from xl,yl to xu,yu */
int xl = GB((x - COLL_DIST) / TILE_SIZE, HASH_RES, HASH_BITS);
int xu = GB((x + COLL_DIST) / TILE_SIZE, HASH_RES, HASH_BITS);
int yl = GB((y - COLL_DIST) / TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
int yu = GB((y + COLL_DIST) / TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
return VehicleFromHash(xl, yl, xu, yu, data, proc, find_first);
}
/**
* Find a vehicle from a specific location. It will call proc for ALL vehicles
* on the tile and YOU must make SURE that the "best one" is stored in the
* data value and is ALWAYS the same regardless of the order of the vehicles
* where proc was called on!
* When you fail to do this properly you create an almost untraceable DESYNC!
* @note The return value of proc will be ignored.
* @note Use this when you have the intention that all vehicles
* should be iterated over.
* @param x The X location on the map
* @param y The Y location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
*/
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
{
VehicleFromPosXY(x, y, data, proc, false);
}
/**
* Checks whether a vehicle in on a specific location. It will call proc for
* vehicles until it returns non-NULL.
* @note Use FindVehicleOnPosXY when you have the intention that all vehicles
* should be iterated over.
* @param x The X location on the map
* @param y The Y location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
* @return True if proc returned non-NULL.
*/
bool HasVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
{
return VehicleFromPosXY(x, y, data, proc, true) != NULL;
}
/**
* Helper function for FindVehicleOnPos/HasVehicleOnPos.
* @note Do not call this function directly!
* @param tile The location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
* @param find_first Whether to return on the first found or iterate over
* all vehicles
* @return the best matching or first vehicle (depending on find_first).
*/
static Vehicle *VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc, bool find_first)
{
int x = GB(TileX(tile), HASH_RES, HASH_BITS);
int y = GB(TileY(tile), HASH_RES, HASH_BITS) << HASH_BITS;
Vehicle *v = _new_vehicle_position_hash[(x + y) & TOTAL_HASH_MASK];
for (; v != NULL; v = v->next_new_hash) {
if (v->tile != tile) continue;
Vehicle *a = proc(v, data);
if (find_first && a != NULL) return a;
}
return NULL;
}
/**
* Find a vehicle from a specific location. It will call proc for ALL vehicles
* on the tile and YOU must make SURE that the "best one" is stored in the
* data value and is ALWAYS the same regardless of the order of the vehicles
* where proc was called on!
* When you fail to do this properly you create an almost untraceable DESYNC!
* @note The return value of proc will be ignored.
* @note Use this when you have the intention that all vehicles
* should be iterated over.
* @param tile The location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
*/
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
{
VehicleFromPos(tile, data, proc, false);
}
/**
* Checks whether a vehicle in on a specific location. It will call proc for
* vehicles until it returns non-NULL.
* @note Use FindVehicleOnPos when you have the intention that all vehicles
* should be iterated over.
* @param tile The location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
* @return True if proc returned non-NULL.
*/
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
{
return VehicleFromPos(tile, data, proc, true) != NULL;
}
static void UpdateNewVehiclePosHash(Vehicle *v, bool remove)
{
Vehicle **old_hash = v->old_new_hash;
Vehicle **new_hash;
if (remove) {
new_hash = NULL;
} else {
int x = GB(TileX(v->tile), HASH_RES, HASH_BITS);
int y = GB(TileY(v->tile), HASH_RES, HASH_BITS) << HASH_BITS;
new_hash = &_new_vehicle_position_hash[(x + y) & TOTAL_HASH_MASK];
}
if (old_hash == new_hash) return;
/* Remove from the old position in the hash table */
if (old_hash != NULL) {
Vehicle *last = NULL;
Vehicle *u = *old_hash;
while (u != v) {
last = u;
u = u->next_new_hash;
assert(u != NULL);
}
if (last == NULL) {
*old_hash = v->next_new_hash;
} else {
last->next_new_hash = v->next_new_hash;
}
}
/* Insert vehicle at beginning of the new position in the hash table */
if (new_hash != NULL) {
v->next_new_hash = *new_hash;
*new_hash = v;
assert(v != v->next_new_hash);
}
/* Remember current hash position */
v->old_new_hash = new_hash;
}
static Vehicle *_vehicle_position_hash[0x1000];
static void UpdateVehiclePosHash(Vehicle *v, int x, int y)
{
UpdateNewVehiclePosHash(v, x == INVALID_COORD);
Vehicle **old_hash, **new_hash;
int old_x = v->coord.left;
int old_y = v->coord.top;
new_hash = (x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(x, y)];
old_hash = (old_x == INVALID_COORD) ? NULL : &_vehicle_position_hash[GEN_HASH(old_x, old_y)];
if (old_hash == new_hash) return;
/* remove from hash table? */
if (old_hash != NULL) {
Vehicle *last = NULL;
Vehicle *u = *old_hash;
while (u != v) {
last = u;
u = u->next_hash;
assert(u != NULL);
}
if (last == NULL) {
*old_hash = v->next_hash;
} else {
last->next_hash = v->next_hash;
}
}
/* insert into hash table? */
if (new_hash != NULL) {
v->next_hash = *new_hash;
*new_hash = v;
}
}
void ResetVehiclePosHash()
{
Vehicle *v;
FOR_ALL_VEHICLES(v) { v->old_new_hash = NULL; }
memset(_vehicle_position_hash, 0, sizeof(_vehicle_position_hash));
memset(_new_vehicle_position_hash, 0, sizeof(_new_vehicle_position_hash));
}
void ResetVehicleColourMap()
{
Vehicle *v;
FOR_ALL_VEHICLES(v) { v->colourmap = PAL_NONE; }
}
/**
* List of vehicles that should check for autoreplace this tick.
* Mapping of vehicle -> leave depot immediatelly after autoreplace.
*/
typedef SmallMap<Vehicle *, bool, 4> AutoreplaceMap;
static AutoreplaceMap _vehicles_to_autoreplace;
void InitializeVehicles()
{
_Vehicle_pool.CleanPool();
_Vehicle_pool.AddBlockToPool();
_vehicles_to_autoreplace.Reset();
ResetVehiclePosHash();
}
Vehicle *GetLastVehicleInChain(Vehicle *v)
{
while (v->Next() != NULL) v = v->Next();
return v;
}
const Vehicle *GetLastVehicleInChain(const Vehicle *v)
{
while (v->Next() != NULL) v = v->Next();
return v;
}
uint CountVehiclesInChain(const Vehicle *v)
{
uint count = 0;
do count++; while ((v = v->Next()) != NULL);
return count;
}
/** Check if a vehicle is counted in num_engines in each company struct
* @param *v Vehicle to test
* @return true if the vehicle is counted in num_engines
*/
bool IsEngineCountable(const Vehicle *v)
{
switch (v->type) {
case VEH_AIRCRAFT: return IsNormalAircraft(v); // don't count plane shadows and helicopter rotors
case VEH_TRAIN:
return !IsArticulatedPart(v) && // tenders and other articulated parts
!IsRearDualheaded(v); // rear parts of multiheaded engines
case VEH_ROAD: return IsRoadVehFront(v);
case VEH_SHIP: return true;
default: return false; // Only count company buildable vehicles
}
}
void Vehicle::PreDestructor()
{
if (CleaningPool()) return;
if (IsValidStationID(this->last_station_visited)) {
GetStation(this->last_station_visited)->loading_vehicles.remove(this);
HideFillingPercent(&this->fill_percent_te_id);
}
if (IsEngineCountable(this)) {
GetCompany(this->owner)->num_engines[this->engine_type]--;
if (this->owner == _local_company) InvalidateAutoreplaceWindow(this->engine_type, this->group_id);
DeleteGroupHighlightOfVehicle(this);
if (IsValidGroupID(this->group_id)) GetGroup(this->group_id)->num_engines[this->engine_type]--;
if (this->IsPrimaryVehicle()) DecreaseGroupNumVehicle(this->group_id);
}
if (this->type == VEH_ROAD) ClearSlot(this);
if (this->type == VEH_AIRCRAFT && this->IsPrimaryVehicle()) {
Station *st = GetTargetAirportIfValid(this);
if (st != NULL) {
const AirportFTA *layout = st->Airport()->layout;
CLRBITS(st->airport_flags, layout[this->u.air.previous_pos].block | layout[this->u.air.pos].block);
}
}
if (this->type != VEH_TRAIN || (this->type == VEH_TRAIN && (IsFrontEngine(this) || IsFreeWagon(this)))) {
InvalidateWindowData(WC_VEHICLE_DEPOT, this->tile);
}
if (this->IsPrimaryVehicle()) {
DeleteWindowById(WC_VEHICLE_VIEW, this->index);
DeleteWindowById(WC_VEHICLE_ORDERS, this->index);
DeleteWindowById(WC_VEHICLE_REFIT, this->index);
DeleteWindowById(WC_VEHICLE_DETAILS, this->index);
DeleteWindowById(WC_VEHICLE_TIMETABLE, this->index);
InvalidateWindow(WC_COMPANY, this->owner);
}
InvalidateWindowClassesData(GetWindowClassForVehicleType(this->type), 0);
this->cargo.Truncate(0);
DeleteVehicleOrders(this);
DeleteDepotHighlightOfVehicle(this);
extern void StopGlobalFollowVehicle(const Vehicle *v);
StopGlobalFollowVehicle(this);
}
Vehicle::~Vehicle()
{
free(this->name);
if (CleaningPool()) return;
/* sometimes, eg. for disaster vehicles, when company bankrupts, when removing crashed/flooded vehicles,
* it may happen that vehicle chain is deleted when visible */
if (!(this->vehstatus & VS_HIDDEN)) MarkSingleVehicleDirty(this);
Vehicle *v = this->Next();
this->SetNext(NULL);
delete v;
UpdateVehiclePosHash(this, INVALID_COORD, 0);
this->next_hash = NULL;
this->next_new_hash = NULL;
DeleteVehicleNews(this->index, INVALID_STRING_ID);
this->type = VEH_INVALID;
}
/** Adds a vehicle to the list of vehicles, that visited a depot this tick
* @param *v vehicle to add
*/
void VehicleEnteredDepotThisTick(Vehicle *v)
{
/* Vehicle should stop in the depot if it was in 'stopping' state or
* when the vehicle is ordered to halt in the depot. */
_vehicles_to_autoreplace[v] = !(v->vehstatus & VS_STOPPED) &&
(!v->current_order.IsType(OT_GOTO_DEPOT) ||
!(v->current_order.GetDepotActionType() & ODATFB_HALT));
/* We ALWAYS set the stopped state. Even when the vehicle does not plan on
* stopping in the depot, so we stop it to ensure that it will not reserve
* the path out of the depot before we might autoreplace it to a different
* engine. The new engine would not own the reserved path we store that we
* stopped the vehicle, so autoreplace can start it again */
v->vehstatus |= VS_STOPPED;
}
void CallVehicleTicks()
{
_vehicles_to_autoreplace.Clear();
Station *st;
FOR_ALL_STATIONS(st) LoadUnloadStation(st);
Vehicle *v;
FOR_ALL_VEHICLES(v) {
v->Tick();
switch (v->type) {
default: break;
case VEH_TRAIN:
case VEH_ROAD:
case VEH_AIRCRAFT:
case VEH_SHIP:
if (v->type == VEH_TRAIN && IsTrainWagon(v)) continue;
if (v->type == VEH_AIRCRAFT && v->subtype != AIR_HELICOPTER) continue;
if (v->type == VEH_ROAD && !IsRoadVehFront(v)) continue;
v->motion_counter += (v->direction & 1) ? (v->cur_speed * 3) / 4 : v->cur_speed;
/* Play a running sound if the motion counter passes 256 (Do we not skip sounds?) */
if (GB(v->motion_counter, 0, 8) < v->cur_speed) PlayVehicleSound(v, VSE_RUNNING);
/* Play an alterate running sound every 16 ticks */
if (GB(v->tick_counter, 0, 4) == 0) PlayVehicleSound(v, v->cur_speed > 0 ? VSE_RUNNING_16 : VSE_STOPPED_16);
}
}
for (AutoreplaceMap::iterator it = _vehicles_to_autoreplace.Begin(); it != _vehicles_to_autoreplace.End(); it++) {
v = it->first;
/* Autoreplace needs the current company set as the vehicle owner */
_current_company = v->owner;
/* Start vehicle if we stopped them in VehicleEnteredDepotThisTick()
* We need to stop them between VehicleEnteredDepotThisTick() and here or we risk that
* they are already leaving the depot again before being replaced. */
if (it->second) v->vehstatus &= ~VS_STOPPED;
/* Store the position of the effect as the vehicle pointer will become invalid later */
int x = v->x_pos;
int y = v->y_pos;
int z = v->z_pos;
const Company *c = GetCompany(_current_company);
SubtractMoneyFromCompany(CommandCost(EXPENSES_NEW_VEHICLES, (Money)c->engine_renew_money));
CommandCost res = DoCommand(0, v->index, 0, DC_EXEC, CMD_AUTOREPLACE_VEHICLE);
SubtractMoneyFromCompany(CommandCost(EXPENSES_NEW_VEHICLES, -(Money)c->engine_renew_money));
if (!IsLocalCompany()) continue;
if (res.Succeeded()) {
ShowCostOrIncomeAnimation(x, y, z, res.GetCost());
continue;
}
StringID error_message = res.GetErrorMessage();
if (error_message == STR_AUTOREPLACE_NOTHING_TO_DO || error_message == INVALID_STRING_ID) continue;
if (error_message == STR_0003_NOT_ENOUGH_CASH_REQUIRES) error_message = STR_AUTOREPLACE_MONEY_LIMIT;
StringID message;
if (error_message == STR_TRAIN_TOO_LONG_AFTER_REPLACEMENT) {
message = error_message;
} else {
message = STR_VEHICLE_AUTORENEW_FAILED;
}
SetDParam(0, v->index);
SetDParam(1, error_message);
AddNewsItem(message, NS_ADVICE, v->index, 0);
}
_current_company = OWNER_NONE;
}
/** Check if a given engine type can be refitted to a given cargo
* @param engine_type Engine type to check
* @param cid_to check refit to this cargo-type
* @return true if it is possible, false otherwise
*/
bool CanRefitTo(EngineID engine_type, CargoID cid_to)
{
return HasBit(EngInfo(engine_type)->refit_mask, cid_to);
}
/** Find the first cargo type that an engine can be refitted to.
* @param engine_type Which engine to find cargo for.
* @return A climate dependent cargo type. CT_INVALID is returned if not refittable.
*/
CargoID FindFirstRefittableCargo(EngineID engine_type)
{
uint32 refit_mask = EngInfo(engine_type)->refit_mask;
if (refit_mask != 0) {
for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
if (HasBit(refit_mask, cid)) return cid;
}
}
return CT_INVALID;
}
/** Learn the price of refitting a certain engine
* @param engine_type Which engine to refit
* @return Price for refitting
*/
CommandCost GetRefitCost(EngineID engine_type)
{
Money base_cost;
ExpensesType expense_type;
switch (GetEngine(engine_type)->type) {
case VEH_SHIP:
base_cost = _price.ship_base;
expense_type = EXPENSES_SHIP_RUN;
break;
case VEH_ROAD:
base_cost = _price.roadveh_base;
expense_type = EXPENSES_ROADVEH_RUN;
break;
case VEH_AIRCRAFT:
base_cost = _price.aircraft_base;
expense_type = EXPENSES_AIRCRAFT_RUN;
break;
case VEH_TRAIN:
base_cost = 2 * ((RailVehInfo(engine_type)->railveh_type == RAILVEH_WAGON) ?
_price.build_railwagon : _price.build_railvehicle);
expense_type = EXPENSES_TRAIN_RUN;
break;
default: NOT_REACHED();
}
return CommandCost(expense_type, (EngInfo(engine_type)->refit_cost * base_cost) >> 10);
}
static void DoDrawVehicle(const Vehicle *v)
{
SpriteID image = v->cur_image;
SpriteID pal = PAL_NONE;
if (v->vehstatus & VS_DEFPAL) pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
AddSortableSpriteToDraw(image, pal, v->x_pos + v->x_offs, v->y_pos + v->y_offs,
v->x_extent, v->y_extent, v->z_extent, v->z_pos, (v->vehstatus & VS_SHADOW) != 0);
}
void ViewportAddVehicles(DrawPixelInfo *dpi)
{
/* The bounding rectangle */
const int l = dpi->left;
const int r = dpi->left + dpi->width;
const int t = dpi->top;
const int b = dpi->top + dpi->height;
/* The hash area to scan */
int xl, xu, yl, yu;
if (dpi->width + 70 < (1 << (7 + 6))) {
xl = GB(l - 70, 7, 6);
xu = GB(r, 7, 6);
} else {
/* scan whole hash row */
xl = 0;
xu = 0x3F;
}
if (dpi->height + 70 < (1 << (6 + 6))) {
yl = GB(t - 70, 6, 6) << 6;
yu = GB(b, 6, 6) << 6;
} else {
/* scan whole column */
yl = 0;
yu = 0x3F << 6;
}
for (int y = yl;; y = (y + (1 << 6)) & (0x3F << 6)) {
for (int x = xl;; x = (x + 1) & 0x3F) {
const Vehicle *v = _vehicle_position_hash[x + y]; // already masked & 0xFFF
while (v != NULL) {
if (!(v->vehstatus & VS_HIDDEN) &&
l <= v->coord.right &&
t <= v->coord.bottom &&
r >= v->coord.left &&
b >= v->coord.top) {
DoDrawVehicle(v);
}
v = v->next_hash;
}
if (x == xu) break;
}
if (y == yu) break;
}
}
Vehicle *CheckClickOnVehicle(const ViewPort *vp, int x, int y)
{
Vehicle *found = NULL, *v;
uint dist, best_dist = UINT_MAX;
if ((uint)(x -= vp->left) >= (uint)vp->width || (uint)(y -= vp->top) >= (uint)vp->height) return NULL;
x = ScaleByZoom(x, vp->zoom) + vp->virtual_left;
y = ScaleByZoom(y, vp->zoom) + vp->virtual_top;
FOR_ALL_VEHICLES(v) {
if ((v->vehstatus & (VS_HIDDEN | VS_UNCLICKABLE)) == 0 &&
x >= v->coord.left && x <= v->coord.right &&
y >= v->coord.top && y <= v->coord.bottom) {
dist = max(
abs(((v->coord.left + v->coord.right) >> 1) - x),
abs(((v->coord.top + v->coord.bottom) >> 1) - y)
);
if (dist < best_dist) {
found = v;
best_dist = dist;
}
}
}
return found;
}
void CheckVehicle32Day(Vehicle *v)
{
if ((v->day_counter & 0x1F) != 0) return;
uint16 callback = GetVehicleCallback(CBID_VEHICLE_32DAY_CALLBACK, 0, 0, v->engine_type, v);
if (callback == CALLBACK_FAILED) return;
if (HasBit(callback, 0)) TriggerVehicle(v, VEHICLE_TRIGGER_CALLBACK_32); // Trigger vehicle trigger 10
if (HasBit(callback, 1)) v->colourmap = PAL_NONE; // Update colourmap via callback 2D
}
void DecreaseVehicleValue(Vehicle *v)
{
v->value -= v->value >> 8;
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
}
static const byte _breakdown_chance[64] = {
3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 5, 5, 6, 6, 7, 7,
8, 8, 9, 9, 10, 10, 11, 11,
12, 13, 13, 13, 13, 14, 15, 16,
17, 19, 21, 25, 28, 31, 34, 37,
40, 44, 48, 52, 56, 60, 64, 68,
72, 80, 90, 100, 110, 120, 130, 140,
150, 170, 190, 210, 230, 250, 250, 250,
};
void CheckVehicleBreakdown(Vehicle *v)
{
int rel, rel_old;
/* decrease reliability */
v->reliability = rel = max((rel_old = v->reliability) - v->reliability_spd_dec, 0);
if ((rel_old >> 8) != (rel >> 8)) InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
if (v->breakdown_ctr != 0 || v->vehstatus & VS_STOPPED ||
_settings_game.difficulty.vehicle_breakdowns < 1 ||
v->cur_speed < 5 || _game_mode == GM_MENU) {
return;
}
uint32 r = Random();
/* increase chance of failure */
int chance = v->breakdown_chance + 1;
if (Chance16I(1, 25, r)) chance += 25;
v->breakdown_chance = min(255, chance);
/* calculate reliability value to use in comparison */
rel = v->reliability;
if (v->type == VEH_SHIP) rel += 0x6666;
/* reduced breakdowns? */
if (_settings_game.difficulty.vehicle_breakdowns == 1) rel += 0x6666;
/* check if to break down */
if (_breakdown_chance[(uint)min(rel, 0xffff) >> 10] <= v->breakdown_chance) {
v->breakdown_ctr = GB(r, 16, 6) + 0x3F;
v->breakdown_delay = GB(r, 24, 7) + 0x80;
v->breakdown_chance = 0;
}
}
void AgeVehicle(Vehicle *v)
{
if (v->age < 65535) v->age++;
int age = v->age - v->max_age;
if (age == DAYS_IN_LEAP_YEAR * 0 || age == DAYS_IN_LEAP_YEAR * 1 ||
age == DAYS_IN_LEAP_YEAR * 2 || age == DAYS_IN_LEAP_YEAR * 3 || age == DAYS_IN_LEAP_YEAR * 4) {
v->reliability_spd_dec <<= 1;
}
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
/* Don't warn about non-primary or not ours vehicles */
if (v->Previous() != NULL || v->owner != _local_company) return;
/* Don't warn if a renew is active */
if (GetCompany(v->owner)->engine_renew && GetEngine(v->engine_type)->company_avail != 0) return;
StringID str;
if (age == -DAYS_IN_LEAP_YEAR) {
str = STR_01A0_IS_GETTING_OLD;
} else if (age == 0) {
str = STR_01A1_IS_GETTING_VERY_OLD;
} else if (age > 0 && (age % DAYS_IN_LEAP_YEAR) == 0) {
str = STR_01A2_IS_GETTING_VERY_OLD_AND;
} else {
return;
}
SetDParam(0, v->index);
AddNewsItem(str, NS_ADVICE, v->index, 0);
}
/**
* Calculates how full a vehicle is.
* @param v The Vehicle to check. For trains, use the first engine.
* @param colour The string to show depending on if we are unloading or loading
* @return A percentage of how full the Vehicle is.
*/
uint8 CalcPercentVehicleFilled(const Vehicle *v, StringID *colour)
{
int count = 0;
int max = 0;
int cars = 0;
int unloading = 0;
bool loading = false;
const Vehicle *u = v;
const Station *st = v->last_station_visited != INVALID_STATION ? GetStation(v->last_station_visited) : NULL;
/* Count up max and used */
for (; v != NULL; v = v->Next()) {
count += v->cargo.Count();
max += v->cargo_cap;
if (v->cargo_cap != 0 && colour != NULL) {
unloading += HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) ? 1 : 0;
loading |= !(u->current_order.GetUnloadType() & OUFB_UNLOAD) && st->goods[v->cargo_type].days_since_pickup != 255;
cars++;
}
}
if (colour != NULL) {
if (unloading == 0 && loading) {
*colour = STR_PERCENT_UP;
} else if (cars == unloading || !loading) {
*colour = STR_PERCENT_DOWN;
} else {
*colour = STR_PERCENT_UP_DOWN;
}
}
/* Train without capacity */
if (max == 0) return 100;
/* Return the percentage */
return (count * 100) / max;
}
void VehicleEnterDepot(Vehicle *v)
{
switch (v->type) {
case VEH_TRAIN:
InvalidateWindowClasses(WC_TRAINS_LIST);
/* Clear path reservation */
SetDepotWaypointReservation(v->tile, false);
if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
if (!IsFrontEngine(v)) v = v->First();
UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
v->load_unload_time_rem = 0;
ClrBit(v->u.rail.flags, VRF_TOGGLE_REVERSE);
TrainConsistChanged(v, true);
break;
case VEH_ROAD:
InvalidateWindowClasses(WC_ROADVEH_LIST);
if (!IsRoadVehFront(v)) v = v->First();
break;
case VEH_SHIP:
InvalidateWindowClasses(WC_SHIPS_LIST);
v->u.ship.state = TRACK_BIT_DEPOT;
RecalcShipStuff(v);
break;
case VEH_AIRCRAFT:
InvalidateWindowClasses(WC_AIRCRAFT_LIST);
HandleAircraftEnterHangar(v);
break;
default: NOT_REACHED();
}
if (v->type != VEH_TRAIN) {
/* Trains update the vehicle list when the first unit enters the depot and calls VehicleEnterDepot() when the last unit enters.
* We only increase the number of vehicles when the first one enters, so we will not need to search for more vehicles in the depot */
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
}
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
v->vehstatus |= VS_HIDDEN;
v->cur_speed = 0;
VehicleServiceInDepot(v);
TriggerVehicle(v, VEHICLE_TRIGGER_DEPOT);
if (v->current_order.IsType(OT_GOTO_DEPOT)) {
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
Order t = v->current_order;
v->current_order.MakeDummy();
if (t.IsRefit()) {
_current_company = v->owner;
CommandCost cost = DoCommand(v->tile, v->index, t.GetRefitCargo() | t.GetRefitSubtype() << 8, DC_EXEC, GetCmdRefitVeh(v));
if (CmdFailed(cost)) {
_vehicles_to_autoreplace[v] = false;
if (v->owner == _local_company) {
/* Notify the user that we stopped the vehicle */
SetDParam(0, v->index);
AddNewsItem(STR_ORDER_REFIT_FAILED, NS_ADVICE, v->index, 0);
}
} else if (v->owner == _local_company && cost.GetCost() != 0) {
ShowCostOrIncomeAnimation(v->x_pos, v->y_pos, v->z_pos, cost.GetCost());
}
}
if (t.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) {
/* Part of orders */
UpdateVehicleTimetable(v, true);
v->cur_order_index++;
}
if (t.GetDepotActionType() & ODATFB_HALT) {
/* Force depot visit */
v->vehstatus |= VS_STOPPED;
if (v->owner == _local_company) {
StringID string;
switch (v->type) {
case VEH_TRAIN: string = STR_8814_TRAIN_IS_WAITING_IN_DEPOT; break;
case VEH_ROAD: string = STR_9016_ROAD_VEHICLE_IS_WAITING; break;
case VEH_SHIP: string = STR_981C_SHIP_IS_WAITING_IN_DEPOT; break;
case VEH_AIRCRAFT: string = STR_A014_AIRCRAFT_IS_WAITING_IN; break;
default: NOT_REACHED(); string = STR_EMPTY; // Set the string to something to avoid a compiler warning
}
SetDParam(0, v->index);
AddNewsItem(string, NS_ADVICE, v->index, 0);
}
AI::NewEvent(v->owner, new AIEventVehicleWaitingInDepot(v->index));
}
}
}
/**
* Move a vehicle in the game state; that is moving it's position in
* the position hashes and marking it's location in the viewport dirty
* if requested.
* @param v vehicle to move
* @param update_viewport whether to dirty the viewport
*/
void VehicleMove(Vehicle *v, bool update_viewport)
{
int img = v->cur_image;
Point pt = RemapCoords(v->x_pos + v->x_offs, v->y_pos + v->y_offs, v->z_pos);
const Sprite *spr = GetSprite(img, ST_NORMAL);
pt.x += spr->x_offs;
pt.y += spr->y_offs;
UpdateVehiclePosHash(v, pt.x, pt.y);
Rect old_coord = v->coord;
v->coord.left = pt.x;
v->coord.top = pt.y;
v->coord.right = pt.x + spr->width + 2;
v->coord.bottom = pt.y + spr->height + 2;
if (update_viewport) {
MarkAllViewportsDirty(
min(old_coord.left, v->coord.left),
min(old_coord.top, v->coord.top),
max(old_coord.right, v->coord.right) + 1,
max(old_coord.bottom, v->coord.bottom) + 1
);
}
}
/**
* Marks viewports dirty where the vehicle's image is
* In fact, it equals
* BeginVehicleMove(v); EndVehicleMove(v);
* @param v vehicle to mark dirty
* @see BeginVehicleMove()
* @see EndVehicleMove()
*/
void MarkSingleVehicleDirty(const Vehicle *v)
{
MarkAllViewportsDirty(v->coord.left, v->coord.top, v->coord.right + 1, v->coord.bottom + 1);
}
/**
* Get position information of a vehicle when moving one pixel in the direction it is facing
* @param v Vehicle to move
* @return Position information after the move */
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
{
static const int8 _delta_coord[16] = {
-1,-1,-1, 0, 1, 1, 1, 0, /* x */
-1, 0, 1, 1, 1, 0,-1,-1, /* y */
};
int x = v->x_pos + _delta_coord[v->direction];
int y = v->y_pos + _delta_coord[v->direction + 8];
GetNewVehiclePosResult gp;
gp.x = x;
gp.y = y;
gp.old_tile = v->tile;
gp.new_tile = TileVirtXY(x, y);
return gp;
}
static const Direction _new_direction_table[] = {
DIR_N , DIR_NW, DIR_W ,
DIR_NE, DIR_SE, DIR_SW,
DIR_E , DIR_SE, DIR_S
};
Direction GetDirectionTowards(const Vehicle *v, int x, int y)
{
int i = 0;
if (y >= v->y_pos) {
if (y != v->y_pos) i += 3;
i += 3;
}
if (x >= v->x_pos) {
if (x != v->x_pos) i++;
i++;
}
Direction dir = v->direction;
DirDiff dirdiff = DirDifference(_new_direction_table[i], dir);
if (dirdiff == DIRDIFF_SAME) return dir;
return ChangeDir(dir, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
}
Trackdir GetVehicleTrackdir(const Vehicle *v)
{
if (v->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
switch (v->type) {
case VEH_TRAIN:
if (v->u.rail.track == TRACK_BIT_DEPOT) // We'll assume the train is facing outwards
return DiagDirToDiagTrackdir(GetRailDepotDirection(v->tile)); // Train in depot
if (v->u.rail.track == TRACK_BIT_WORMHOLE) // train in tunnel or on bridge, so just use his direction and assume a diagonal track
return DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
return TrackDirectionToTrackdir(FindFirstTrack(v->u.rail.track), v->direction);
case VEH_SHIP:
if (v->IsInDepot())
/* We'll assume the ship is facing outwards */
return DiagDirToDiagTrackdir(GetShipDepotDirection(v->tile));
if (v->u.ship.state == TRACK_BIT_WORMHOLE) // ship on aqueduct, so just use his direction and assume a diagonal track
return DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
return TrackDirectionToTrackdir(FindFirstTrack(v->u.ship.state), v->direction);
case VEH_ROAD:
if (v->IsInDepot()) // We'll assume the road vehicle is facing outwards
return DiagDirToDiagTrackdir(GetRoadDepotDirection(v->tile));
if (IsStandardRoadStopTile(v->tile)) // We'll assume the road vehicle is facing outwards
return DiagDirToDiagTrackdir(GetRoadStopDir(v->tile)); // Road vehicle in a station
if (IsDriveThroughStopTile(v->tile)) return DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
/* If vehicle's state is a valid track direction (vehicle is not turning around) return it */
if (!IsReversingRoadTrackdir((Trackdir)v->u.road.state)) return (Trackdir)v->u.road.state;
/* Vehicle is turning around, get the direction from vehicle's direction */
return DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
/* case VEH_AIRCRAFT: case VEH_EFFECT: case VEH_DISASTER: */
default: return INVALID_TRACKDIR;
}
}
/**
* Call the tile callback function for a vehicle entering a tile
* @param v Vehicle entering the tile
* @param tile Tile entered
* @param x X position
* @param y Y position
* @return Some meta-data over the to be entered tile.
* @see VehicleEnterTileStatus to see what the bits in the return value mean.
*/
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
{
return _tile_type_procs[GetTileType(tile)]->vehicle_enter_tile_proc(v, tile, x, y);
}
FreeUnitIDGenerator::FreeUnitIDGenerator(VehicleType type, CompanyID owner) : cache(NULL), maxid(0), curid(0)
{
/* Find maximum */
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == type && v->owner == owner) {
this->maxid = max<UnitID>(this->maxid, v->unitnumber);
}
}
if (this->maxid == 0) return;
this->maxid++; // so there is space for last item (with v->unitnumber == maxid)
this->maxid++; // this one will always be free (well, it will fail when there are 65535 units, so this overflows)
this->cache = CallocT<bool>(this->maxid);
/* Fill the cache */
FOR_ALL_VEHICLES(v) {
if (v->type == type && v->owner == owner) {
this->cache[v->unitnumber] = true;
}
}
}
UnitID FreeUnitIDGenerator::NextID()
{
if (this->maxid <= this->curid) return ++this->curid;
while (this->cache[++this->curid]) { } // it will stop, we reserved more space than needed
return this->curid;
}
UnitID GetFreeUnitNumber(VehicleType type)
{
FreeUnitIDGenerator gen(type, _current_company);
return gen.NextID();
}
/**
* Check whether we can build infrastructure for the given
* vehicle type. This to disable building stations etc. when
* you are not allowed/able to have the vehicle type yet.
* @param type the vehicle type to check this for
* @return true if there is any reason why you may build
* the infrastructure for the given vehicle type
*/
bool CanBuildVehicleInfrastructure(VehicleType type)
{
assert(IsCompanyBuildableVehicleType(type));
if (!IsValidCompanyID(_local_company)) return false;
if (_settings_client.gui.always_build_infrastructure) return true;
UnitID max;
switch (type) {
case VEH_TRAIN: max = _settings_game.vehicle.max_trains; break;
case VEH_ROAD: max = _settings_game.vehicle.max_roadveh; break;
case VEH_SHIP: max = _settings_game.vehicle.max_ships; break;
case VEH_AIRCRAFT: max = _settings_game.vehicle.max_aircraft; break;
default: NOT_REACHED();
}
/* We can build vehicle infrastructure when we may build the vehicle type */
if (max > 0) {
/* Can we actually build the vehicle type? */
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, type) {
if (HasBit(e->company_avail, _local_company)) return true;
}
return false;
}
/* We should be able to build infrastructure when we have the actual vehicle type */
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->owner == _local_company && v->type == type) return true;
}
return false;
}
const Livery *GetEngineLivery(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v)
{
const Company *c = GetCompany(company);
LiveryScheme scheme = LS_DEFAULT;
CargoID cargo_type = v == NULL ? (CargoID)CT_INVALID : v->cargo_type;
/* The default livery is always available for use, but its in_use flag determines
* whether any _other_ liveries are in use. */
if (c->livery[LS_DEFAULT].in_use && (_settings_client.gui.liveries == 2 || (_settings_client.gui.liveries == 1 && company == _local_company))) {
/* Determine the livery scheme to use */
const Engine *e = GetEngine(engine_type);
switch (e->type) {
default: NOT_REACHED();
case VEH_TRAIN: {
const RailVehicleInfo *rvi = RailVehInfo(engine_type);
if (v != NULL && parent_engine_type != INVALID_ENGINE && (UsesWagonOverride(v) || (IsArticulatedPart(v) && rvi->railveh_type != RAILVEH_WAGON))) {
/* Wagonoverrides use the coloir scheme of the front engine.
* Articulated parts use the colour scheme of the first part. (Not supported for articulated wagons) */
engine_type = parent_engine_type;
e = GetEngine(engine_type);
rvi = RailVehInfo(engine_type);
/* Note: Luckily cargo_type is not needed for engines */
}
if (cargo_type == CT_INVALID) cargo_type = e->GetDefaultCargoType();
if (cargo_type == CT_INVALID) cargo_type = CT_GOODS; // The vehicle does not carry anything, let's pick some freight cargo
if (rvi->railveh_type == RAILVEH_WAGON) {
if (!GetCargo(cargo_type)->is_freight) {
if (parent_engine_type == INVALID_ENGINE) {
scheme = LS_PASSENGER_WAGON_STEAM;
} else {
switch (RailVehInfo(parent_engine_type)->engclass) {
default: NOT_REACHED();
case EC_STEAM: scheme = LS_PASSENGER_WAGON_STEAM; break;
case EC_DIESEL: scheme = LS_PASSENGER_WAGON_DIESEL; break;
case EC_ELECTRIC: scheme = LS_PASSENGER_WAGON_ELECTRIC; break;
case EC_MONORAIL: scheme = LS_PASSENGER_WAGON_MONORAIL; break;
case EC_MAGLEV: scheme = LS_PASSENGER_WAGON_MAGLEV; break;
}
}
} else {
scheme = LS_FREIGHT_WAGON;
}
} else {
bool is_mu = HasBit(EngInfo(engine_type)->misc_flags, EF_RAIL_IS_MU);
switch (rvi->engclass) {
default: NOT_REACHED();
case EC_STEAM: scheme = LS_STEAM; break;
case EC_DIESEL: scheme = is_mu ? LS_DMU : LS_DIESEL; break;
case EC_ELECTRIC: scheme = is_mu ? LS_EMU : LS_ELECTRIC; break;
case EC_MONORAIL: scheme = LS_MONORAIL; break;
case EC_MAGLEV: scheme = LS_MAGLEV; break;
}
}
break;
}
case VEH_ROAD: {
/* Always use the livery of the front */
if (v != NULL && parent_engine_type != INVALID_ENGINE) {
engine_type = parent_engine_type;
e = GetEngine(engine_type);
cargo_type = v->First()->cargo_type;
}
if (cargo_type == CT_INVALID) cargo_type = e->GetDefaultCargoType();
if (cargo_type == CT_INVALID) cargo_type = CT_GOODS; // The vehicle does not carry anything, let's pick some freight cargo
/* Important: Use Tram Flag of front part. Luckily engine_type refers to the front part here. */
if (HasBit(EngInfo(engine_type)->misc_flags, EF_ROAD_TRAM)) {
/* Tram */
scheme = IsCargoInClass(cargo_type, CC_PASSENGERS) ? LS_PASSENGER_TRAM : LS_FREIGHT_TRAM;
} else {
/* Bus or truck */
scheme = IsCargoInClass(cargo_type, CC_PASSENGERS) ? LS_BUS : LS_TRUCK;
}
break;
}
case VEH_SHIP: {
if (cargo_type == CT_INVALID) cargo_type = e->GetDefaultCargoType();
if (cargo_type == CT_INVALID) cargo_type = CT_GOODS; // The vehicle does not carry anything, let's pick some freight cargo
scheme = IsCargoInClass(cargo_type, CC_PASSENGERS) ? LS_PASSENGER_SHIP : LS_FREIGHT_SHIP;
break;
}
case VEH_AIRCRAFT: {
switch (e->u.air.subtype) {
case AIR_HELI: scheme = LS_HELICOPTER; break;
case AIR_CTOL: scheme = LS_SMALL_PLANE; break;
case AIR_CTOL | AIR_FAST: scheme = LS_LARGE_PLANE; break;
}
break;
}
}
/* Switch back to the default scheme if the resolved scheme is not in use */
if (!c->livery[scheme].in_use) scheme = LS_DEFAULT;
}
return &c->livery[scheme];
}
static SpriteID GetEngineColourMap(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v)
{
SpriteID map = (v != NULL) ? v->colourmap : PAL_NONE;
/* Return cached value if any */
if (map != PAL_NONE) return map;
/* Check if we should use the colour map callback */
if (HasBit(EngInfo(engine_type)->callbackmask, CBM_VEHICLE_COLOUR_REMAP)) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_COLOUR_MAPPING, 0, 0, engine_type, v);
/* A return value of 0xC000 is stated to "use the default two-colour
* maps" which happens to be the failure action too... */
if (callback != CALLBACK_FAILED && callback != 0xC000) {
map = GB(callback, 0, 14);
/* If bit 14 is set, then the company colours are applied to the
* map else it's returned as-is. */
if (!HasBit(callback, 14)) {
/* Update cache */
if (v != NULL) ((Vehicle*)v)->colourmap = map;
return map;
}
}
}
bool twocc = HasBit(EngInfo(engine_type)->misc_flags, EF_USES_2CC);
if (map == PAL_NONE) map = twocc ? (SpriteID)SPR_2CCMAP_BASE : (SpriteID)PALETTE_RECOLOUR_START;
const Livery *livery = GetEngineLivery(engine_type, company, parent_engine_type, v);
map += livery->colour1;
if (twocc) map += livery->colour2 * 16;
/* Update cache */
if (v != NULL) ((Vehicle*)v)->colourmap = map;
return map;
}
SpriteID GetEnginePalette(EngineID engine_type, CompanyID company)
{
return GetEngineColourMap(engine_type, company, INVALID_ENGINE, NULL);
}
SpriteID GetVehiclePalette(const Vehicle *v)
{
if (v->type == VEH_TRAIN) {
return GetEngineColourMap(v->engine_type, v->owner, v->u.rail.first_engine, v);
} else if (v->type == VEH_ROAD) {
return GetEngineColourMap(v->engine_type, v->owner, v->u.road.first_engine, v);
}
return GetEngineColourMap(v->engine_type, v->owner, INVALID_ENGINE, v);
}
void Vehicle::BeginLoading()
{
assert(IsTileType(tile, MP_STATION) || type == VEH_SHIP);
if (this->current_order.IsType(OT_GOTO_STATION) &&
this->current_order.GetDestination() == this->last_station_visited) {
current_order.MakeLoading(true);
UpdateVehicleTimetable(this, true);
/* Furthermore add the Non Stop flag to mark that this station
* is the actual destination of the vehicle, which is (for example)
* necessary to be known for HandleTrainLoading to determine
* whether the train is lost or not; not marking a train lost
* that arrives at random stations is bad. */
this->current_order.SetNonStopType(ONSF_NO_STOP_AT_ANY_STATION);
} else {
current_order.MakeLoading(false);
}
GetStation(this->last_station_visited)->loading_vehicles.push_back(this);
VehiclePayment(this);
InvalidateWindow(GetWindowClassForVehicleType(this->type), this->owner);
InvalidateWindowWidget(WC_VEHICLE_VIEW, this->index, VVW_WIDGET_START_STOP_VEH);
InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
InvalidateWindow(WC_STATION_VIEW, this->last_station_visited);
GetStation(this->last_station_visited)->MarkTilesDirty(true);
this->MarkDirty();
}
void Vehicle::LeaveStation()
{
assert(current_order.IsType(OT_LOADING));
/* Only update the timetable if the vehicle was supposed to stop here. */
if (current_order.GetNonStopType() != ONSF_STOP_EVERYWHERE) UpdateVehicleTimetable(this, false);
current_order.MakeLeaveStation();
Station *st = GetStation(this->last_station_visited);
st->loading_vehicles.remove(this);
HideFillingPercent(&this->fill_percent_te_id);
if (this->type == VEH_TRAIN) {
/* Trigger station animation (trains only) */
if (IsTileType(this->tile, MP_STATION)) StationAnimationTrigger(st, this->tile, STAT_ANIM_TRAIN_DEPARTS);
/* Try to reserve a path when leaving the station as we
* might not be marked as wanting a reservation, e.g.
* when an overlength train gets turned around in a station. */
if (UpdateSignalsOnSegment(this->tile, TrackdirToExitdir(GetVehicleTrackdir(this)), this->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
TryPathReserve(this, true, true);
}
}
}
void Vehicle::HandleLoading(bool mode)
{
switch (this->current_order.GetType()) {
case OT_LOADING: {
uint wait_time = max(this->current_order.wait_time - this->lateness_counter, 0);
/* Not the first call for this tick, or still loading */
if (mode || !HasBit(this->vehicle_flags, VF_LOADING_FINISHED) ||
(_settings_game.order.timetabling && this->current_order_time < wait_time)) return;
this->PlayLeaveStationSound();
bool at_destination_station = this->current_order.GetNonStopType() != ONSF_STOP_EVERYWHERE;
this->LeaveStation();
/* If this was not the final order, don't remove it from the list. */
if (!at_destination_station) return;
break;
}
case OT_DUMMY: break;
default: return;
}
this->cur_order_index++;
InvalidateVehicleOrder(this, 0);
}
CommandCost Vehicle::SendToDepot(DoCommandFlag flags, DepotCommand command)
{
if (!CheckOwnership(this->owner)) return CMD_ERROR;
if (this->vehstatus & VS_CRASHED) return CMD_ERROR;
if (this->IsStoppedInDepot()) return CMD_ERROR;
if (this->current_order.IsType(OT_GOTO_DEPOT)) {
bool halt_in_depot = this->current_order.GetDepotActionType() & ODATFB_HALT;
if (!!(command & DEPOT_SERVICE) == halt_in_depot) {
/* We called with a different DEPOT_SERVICE setting.
* Now we change the setting to apply the new one and let the vehicle head for the same depot.
* Note: the if is (true for requesting service == true for ordered to stop in depot) */
if (flags & DC_EXEC) {
this->current_order.SetDepotOrderType(ODTF_MANUAL);
this->current_order.SetDepotActionType(halt_in_depot ? ODATF_SERVICE_ONLY : ODATFB_HALT);
InvalidateWindowWidget(WC_VEHICLE_VIEW, this->index, VVW_WIDGET_START_STOP_VEH);
}
return CommandCost();
}
if (command & DEPOT_DONT_CANCEL) return CMD_ERROR; // Requested no cancelation of depot orders
if (flags & DC_EXEC) {
/* If the orders to 'goto depot' are in the orders list (forced servicing),
* then skip to the next order; effectively cancelling this forced service */
if (this->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) this->cur_order_index++;
this->current_order.MakeDummy();
InvalidateWindowWidget(WC_VEHICLE_VIEW, this->index, VVW_WIDGET_START_STOP_VEH);
}
return CommandCost();
}
TileIndex location;
DestinationID destination;
bool reverse;
static const StringID no_depot[] = {STR_883A_UNABLE_TO_FIND_ROUTE_TO, STR_9019_UNABLE_TO_FIND_LOCAL_DEPOT, STR_981A_UNABLE_TO_FIND_LOCAL_DEPOT, STR_A012_CAN_T_SEND_AIRCRAFT_TO};
if (!this->FindClosestDepot(&location, &destination, &reverse)) return_cmd_error(no_depot[this->type]);
if (flags & DC_EXEC) {
if (this->current_order.IsType(OT_LOADING)) this->LeaveStation();
this->dest_tile = location;
this->current_order.MakeGoToDepot(destination, ODTF_MANUAL);
if (!(command & DEPOT_SERVICE)) this->current_order.SetDepotActionType(ODATFB_HALT);
InvalidateWindowWidget(WC_VEHICLE_VIEW, this->index, VVW_WIDGET_START_STOP_VEH);
/* If there is no depot in front, reverse automatically (trains only) */
if (this->type == VEH_TRAIN && reverse) DoCommand(this->tile, this->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
if (this->type == VEH_AIRCRAFT && this->u.air.state == FLYING && this->u.air.targetairport != destination) {
/* The aircraft is now heading for a different hangar than the next in the orders */
extern void AircraftNextAirportPos_and_Order(Vehicle *v);
AircraftNextAirportPos_and_Order(this);
}
}
return CommandCost();
}
void Vehicle::SetNext(Vehicle *next)
{
if (this->next != NULL) {
/* We had an old next vehicle. Update the first and previous pointers */
for (Vehicle *v = this->next; v != NULL; v = v->Next()) {
v->first = this->next;
}
this->next->previous = NULL;
}
this->next = next;
if (this->next != NULL) {
/* A new next vehicle. Update the first and previous pointers */
if (this->next->previous != NULL) this->next->previous->next = NULL;
this->next->previous = this;
for (Vehicle *v = this->next; v != NULL; v = v->Next()) {
v->first = this->first;
}
}
}
void Vehicle::AddToShared(Vehicle *shared_chain)
{
assert(this->previous_shared == NULL && this->next_shared == NULL);
if (!shared_chain->orders.list) {
assert(shared_chain->previous_shared == NULL);
assert(shared_chain->next_shared == NULL);
this->orders.list = shared_chain->orders.list = new OrderList(NULL, shared_chain);
}
this->next_shared = shared_chain->next_shared;
this->previous_shared = shared_chain;
shared_chain->next_shared = this;
if (this->next_shared != NULL) this->next_shared->previous_shared = this;
shared_chain->orders.list->AddVehicle(this);
}
void Vehicle::RemoveFromShared()
{
/* Remember if we were first and the old window number before RemoveVehicle()
* as this changes first if needed. */
bool were_first = (this->FirstShared() == this);
uint32 old_window_number = (this->FirstShared()->index << 16) | (this->type << 11) | VLW_SHARED_ORDERS | this->owner;
this->orders.list->RemoveVehicle(this);
if (!were_first) {
/* We are not the first shared one, so only relink our previous one. */
this->previous_shared->next_shared = this->NextShared();
}
if (this->next_shared != NULL) this->next_shared->previous_shared = this->previous_shared;
if (this->orders.list->GetNumVehicles() == 1) {
/* When there is only one vehicle, remove the shared order list window. */
DeleteWindowById(GetWindowClassForVehicleType(this->type), old_window_number);
InvalidateVehicleOrder(this->FirstShared(), 0);
} else if (were_first) {
/* If we were the first one, update to the new first one.
* Note: FirstShared() is already the new first */
InvalidateWindowData(GetWindowClassForVehicleType(this->type), old_window_number, (this->FirstShared()->index << 16) | (1 << 15));
}
this->next_shared = NULL;
this->previous_shared = NULL;
}
void StopAllVehicles()
{
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* Code ripped from CmdStartStopTrain. Can't call it, because of
* ownership problems, so we'll duplicate some code, for now */
v->vehstatus |= VS_STOPPED;
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
}
}
void VehiclesYearlyLoop()
{
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->IsPrimaryVehicle()) {
/* show warning if vehicle is not generating enough income last 2 years (corresponds to a red icon in the vehicle list) */
Money profit = v->GetDisplayProfitThisYear();
if (v->age >= 730 && profit < 0) {
if (_settings_client.gui.vehicle_income_warn && v->owner == _local_company) {
SetDParam(0, v->index);
SetDParam(1, profit);
AddNewsItem(
STR_VEHICLE_IS_UNPROFITABLE,
NS_ADVICE,
v->index,
0);
}
AI::NewEvent(v->owner, new AIEventVehicleUnprofitable(v->index));
}
v->profit_last_year = v->profit_this_year;
v->profit_this_year = 0;
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
}
}
}
/**
* Can this station be used by the given engine type?
* @param engine_type the type of vehicles to test
* @param st the station to test for
* @return true if and only if the vehicle of the type can use this station.
* @note For road vehicles the Vehicle is needed to determine whether it can
* use the station. This function will return true for road vehicles
* when at least one of the facilities is available.
*/
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
{
assert(IsEngineIndex(engine_type));
const Engine *e = GetEngine(engine_type);
switch (e->type) {
case VEH_TRAIN:
return (st->facilities & FACIL_TRAIN) != 0;
case VEH_ROAD:
/* For road vehicles we need the vehicle to know whether it can actually
* use the station, but if it doesn't have facilities for RVs it is
* certainly not possible that the station can be used. */
return (st->facilities & (FACIL_BUS_STOP | FACIL_TRUCK_STOP)) != 0;
case VEH_SHIP:
return (st->facilities & FACIL_DOCK) != 0;
case VEH_AIRCRAFT:
return (st->facilities & FACIL_AIRPORT) != 0 &&
(st->Airport()->flags & (e->u.air.subtype & AIR_CTOL ? AirportFTAClass::AIRPLANES : AirportFTAClass::HELICOPTERS)) != 0;
default:
return false;
}
}
/**
* Can this station be used by the given vehicle?
* @param v the vehicle to test
* @param st the station to test for
* @return true if and only if the vehicle can use this station.
*/
bool CanVehicleUseStation(const Vehicle *v, const Station *st)
{
if (v->type == VEH_ROAD) return st->GetPrimaryRoadStop(v) != NULL;
return CanVehicleUseStation(v->engine_type, st);
}
| 57,255
|
C++
|
.cpp
| 1,479
| 35.917512
| 178
| 0.69646
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,127
|
signs_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/signs_gui.cpp
|
/* $Id$ */
/** @file signs_gui.cpp The GUI for signs. */
#include "stdafx.h"
#include "company_gui.h"
#include "company_func.h"
#include "signs_base.h"
#include "signs_func.h"
#include "debug.h"
#include "command_func.h"
#include "strings_func.h"
#include "window_func.h"
#include "map_func.h"
#include "gfx_func.h"
#include "viewport_func.h"
#include "querystring_gui.h"
#include "sortlist_type.h"
#include "string_func.h"
#include "table/strings.h"
struct SignList {
typedef GUIList<const Sign *> GUISignList;
static const Sign *last_sign;
GUISignList signs;
void BuildSignsList()
{
if (!this->signs.NeedRebuild()) return;
DEBUG(misc, 3, "Building sign list");
this->signs.Clear();
const Sign *si;
FOR_ALL_SIGNS(si) *this->signs.Append() = si;
this->signs.Compact();
this->signs.RebuildDone();
}
/** Sort signs by their name */
static int CDECL SignNameSorter(const Sign * const *a, const Sign * const *b)
{
static char buf_cache[64];
char buf[64];
SetDParam(0, (*a)->index);
GetString(buf, STR_SIGN_NAME, lastof(buf));
if (*b != last_sign) {
last_sign = *b;
SetDParam(0, (*b)->index);
GetString(buf_cache, STR_SIGN_NAME, lastof(buf_cache));
}
return strcasecmp(buf, buf_cache);
}
void SortSignsList()
{
if (!this->signs.Sort(&SignNameSorter)) return;
/* Reset the name sorter sort cache */
this->last_sign = NULL;
}
};
const Sign *SignList::last_sign = NULL;
struct SignListWindow : Window, SignList {
SignListWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->vscroll.cap = 12;
this->resize.step_height = 10;
this->resize.height = this->height - 10 * 7; // minimum if 5 in the list
this->signs.ForceRebuild();
this->signs.NeedResort();
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
BuildSignsList();
SortSignsList();
SetVScrollCount(this, this->signs.Length());
SetDParam(0, this->vscroll.count);
this->DrawWidgets();
/* No signs? */
int y = 16; // offset from top of widget
if (this->vscroll.count == 0) {
DrawString(2, y, STR_304A_NONE, TC_FROMSTRING);
return;
}
/* Start drawing the signs */
for (uint16 i = this->vscroll.pos; i < this->vscroll.cap + this->vscroll.pos && i < this->vscroll.count; i++) {
const Sign *si = this->signs[i];
if (si->owner != OWNER_NONE) DrawCompanyIcon(si->owner, 4, y + 1);
SetDParam(0, si->index);
DrawString(22, y, STR_SIGN_NAME, TC_YELLOW);
y += 10;
}
}
virtual void OnClick(Point pt, int widget)
{
if (widget == 3) {
uint32 id_v = (pt.y - 15) / 10;
if (id_v >= this->vscroll.cap) return;
id_v += this->vscroll.pos;
if (id_v >= this->vscroll.count) return;
const Sign *si = this->signs[id_v];
ScrollMainWindowToTile(TileVirtXY(si->x, si->y));
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / 10;
}
virtual void OnInvalidateData(int data)
{
if (data == 0) {
this->signs.ForceRebuild();
} else {
this->signs.ForceResort();
}
}
};
static const Widget _sign_list_widget[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 345, 0, 13, STR_SIGN_LIST_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 346, 357, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 345, 14, 137, 0x0, STR_NULL},
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 346, 357, 14, 125, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 346, 357, 126, 137, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
static const WindowDesc _sign_list_desc(
WDP_AUTO, WDP_AUTO, 358, 138, 358, 138,
WC_SIGN_LIST, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_sign_list_widget
);
void ShowSignList()
{
AllocateWindowDescFront<SignListWindow>(&_sign_list_desc, 0);
}
/**
* Actually rename the sign.
* @param index the sign to rename.
* @param text the new name.
* @return true if the window will already be removed after returning.
*/
static bool RenameSign(SignID index, const char *text)
{
bool remove = StrEmpty(text);
DoCommandP(0, index, 0, CMD_RENAME_SIGN | (StrEmpty(text) ? CMD_MSG(STR_CAN_T_DELETE_SIGN) : CMD_MSG(STR_280C_CAN_T_CHANGE_SIGN_NAME)), NULL, text);
return remove;
}
enum QueryEditSignWidgets {
QUERY_EDIT_SIGN_WIDGET_TEXT = 3,
QUERY_EDIT_SIGN_WIDGET_OK,
QUERY_EDIT_SIGN_WIDGET_CANCEL,
QUERY_EDIT_SIGN_WIDGET_DELETE,
QUERY_EDIT_SIGN_WIDGET_PREVIOUS = QUERY_EDIT_SIGN_WIDGET_DELETE + 2,
QUERY_EDIT_SIGN_WIDGET_NEXT,
};
struct SignWindow : QueryStringBaseWindow, SignList {
SignID cur_sign;
SignWindow(const WindowDesc *desc, const Sign *si) : QueryStringBaseWindow(MAX_LENGTH_SIGN_NAME_BYTES, desc)
{
this->caption = STR_280B_EDIT_SIGN_TEXT;
this->afilter = CS_ALPHANUMERAL;
this->LowerWidget(QUERY_EDIT_SIGN_WIDGET_TEXT);
UpdateSignEditWindow(si);
this->SetFocusedWidget(QUERY_EDIT_SIGN_WIDGET_TEXT);
this->FindWindowPlacementAndResize(desc);
}
void UpdateSignEditWindow(const Sign *si)
{
char *last_of = &this->edit_str_buf[this->edit_str_size - 1]; // points to terminating '\0'
/* Display an empty string when the sign hasnt been edited yet */
if (si->name != NULL) {
SetDParam(0, si->index);
GetString(this->edit_str_buf, STR_SIGN_NAME, last_of);
} else {
GetString(this->edit_str_buf, STR_EMPTY, last_of);
}
*last_of = '\0';
this->cur_sign = si->index;
InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, MAX_LENGTH_SIGN_NAME_PIXELS);
this->InvalidateWidget(QUERY_EDIT_SIGN_WIDGET_TEXT);
this->SetFocusedWidget(QUERY_EDIT_SIGN_WIDGET_TEXT);
}
/**
* Returns a pointer to the (alphabetically) previous or next sign of the current sign.
* @param next false if the previous sign is wanted, true if the next sign is wanted
* @return pointer to the previous/next sign
*/
const Sign *PrevNextSign(bool next)
{
/* Rebuild the sign list */
this->signs.ForceRebuild();
this->signs.NeedResort();
this->BuildSignsList();
this->SortSignsList();
/* Search through the list for the current sign, excluding
* - the first sign if we want the previous sign or
* - the last sign if we want the next sign */
uint end = this->signs.Length() - (next ? 1 : 0);
for (uint i = next ? 0 : 1; i < end; i++) {
if (this->cur_sign == this->signs[i]->index) {
/* We've found the current sign, so return the sign before/after it */
return this->signs[i + (next ? 1 : -1)];
}
}
/* If we haven't found the current sign by now, return the last/first sign */
return this->signs[next ? 0 : this->signs.Length() - 1];
}
virtual void OnPaint()
{
SetDParam(0, this->caption);
this->DrawWidgets();
this->DrawEditBox(QUERY_EDIT_SIGN_WIDGET_TEXT);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case QUERY_EDIT_SIGN_WIDGET_PREVIOUS:
case QUERY_EDIT_SIGN_WIDGET_NEXT: {
const Sign *si = this->PrevNextSign(widget == QUERY_EDIT_SIGN_WIDGET_NEXT);
/* Rebuild the sign list */
this->signs.ForceRebuild();
this->signs.NeedResort();
this->BuildSignsList();
this->SortSignsList();
/* Scroll to sign and reopen window */
ScrollMainWindowToTile(TileVirtXY(si->x, si->y));
UpdateSignEditWindow(si);
break;
}
case QUERY_EDIT_SIGN_WIDGET_DELETE:
/* Only need to set the buffer to null, the rest is handled as the OK button */
RenameSign(this->cur_sign, "");
/* don't delete this, we are deleted in Sign::~Sign() -> DeleteRenameSignWindow() */
break;
case QUERY_EDIT_SIGN_WIDGET_OK:
if (RenameSign(this->cur_sign, this->text.buf)) break;
/* FALL THROUGH */
case QUERY_EDIT_SIGN_WIDGET_CANCEL:
delete this;
break;
}
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
EventState state = ES_NOT_HANDLED;
switch (this->HandleEditBoxKey(QUERY_EDIT_SIGN_WIDGET_TEXT, key, keycode, state)) {
default: break;
case HEBR_CONFIRM:
if (RenameSign(this->cur_sign, this->text.buf)) break;
/* FALL THROUGH */
case HEBR_CANCEL: // close window, abandon changes
delete this;
break;
}
return state;
}
virtual void OnMouseLoop()
{
this->HandleEditBox(QUERY_EDIT_SIGN_WIDGET_TEXT);
}
virtual void OnOpenOSKWindow(int wid)
{
ShowOnScreenKeyboard(this, wid, QUERY_EDIT_SIGN_WIDGET_CANCEL, QUERY_EDIT_SIGN_WIDGET_OK);
}
};
static const Widget _query_sign_edit_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 259, 0, 13, STR_012D, STR_NULL },
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 259, 14, 29, STR_NULL, STR_NULL },
{ WWT_EDITBOX, RESIZE_NONE, COLOUR_GREY, 2, 257, 16, 27, STR_SIGN_OSKTITLE, STR_NULL }, // Text field
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 60, 30, 41, STR_012F_OK, STR_NULL },
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 61, 120, 30, 41, STR_012E_CANCEL, STR_NULL },
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 121, 180, 30, 41, STR_0290_DELETE, STR_NULL },
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 181, 237, 30, 41, STR_NULL, STR_NULL },
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 238, 248, 30, 41, STR_6819, STR_PREVIOUS_SIGN_TOOLTIP },
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 249, 259, 30, 41, STR_681A, STR_NEXT_SIGN_TOOLTIP },
{ WIDGETS_END },
};
static const WindowDesc _query_sign_edit_desc(
190, 170, 260, 42, 260, 42,
WC_QUERY_STRING, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_query_sign_edit_widgets
);
void HandleClickOnSign(const Sign *si)
{
if (_ctrl_pressed && si->owner == _local_company) {
RenameSign(si->index, NULL);
return;
}
ShowRenameSignWindow(si);
}
void ShowRenameSignWindow(const Sign *si)
{
/* Delete all other edit windows */
DeleteWindowById(WC_QUERY_STRING, 0);
new SignWindow(&_query_sign_edit_desc, si);
}
void DeleteRenameSignWindow(SignID sign)
{
SignWindow *w = dynamic_cast<SignWindow *>(FindWindowById(WC_QUERY_STRING, 0));
if (w != NULL && w->cur_sign == sign) delete w;
}
| 10,506
|
C++
|
.cpp
| 297
| 32.626263
| 149
| 0.676033
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,129
|
timetable_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/timetable_gui.cpp
|
/* $Id$ */
/** @file timetable_gui.cpp GUI for time tabling. */
#include "stdafx.h"
#include "command_func.h"
#include "gui.h"
#include "window_gui.h"
#include "window_func.h"
#include "textbuf_gui.h"
#include "strings_func.h"
#include "vehicle_base.h"
#include "string_func.h"
#include "gfx_func.h"
#include "company_func.h"
#include "settings_type.h"
#include "table/strings.h"
enum TimetableViewWindowWidgets {
TTV_WIDGET_CLOSEBOX = 0,
TTV_CAPTION,
TTV_ORDER_VIEW,
TTV_STICKY,
TTV_TIMETABLE_PANEL,
TTV_SCROLLBAR,
TTV_SUMMARY_PANEL,
TTV_CHANGE_TIME,
TTV_CLEAR_TIME,
TTV_RESET_LATENESS,
TTV_AUTOFILL,
TTV_EMPTY,
TTV_RESIZE,
};
void SetTimetableParams(int param1, int param2, uint32 time)
{
if (_settings_client.gui.timetable_in_ticks) {
SetDParam(param1, STR_TIMETABLE_TICKS);
SetDParam(param2, time);
} else {
SetDParam(param1, STR_TIMETABLE_DAYS);
SetDParam(param2, time / DAY_TICKS);
}
}
struct TimetableWindow : Window {
int sel_index;
const Vehicle *vehicle;
TimetableWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->vehicle = GetVehicle(window_number);
this->owner = this->vehicle->owner;
this->vscroll.cap = 8;
this->resize.step_height = 10;
this->sel_index = -1;
this->FindWindowPlacementAndResize(desc);
}
int GetOrderFromTimetableWndPt(int y, const Vehicle *v)
{
/*
* Calculation description:
* 15 = 14 (this->widget[TTV_ORDER_VIEW].top) + 1 (frame-line)
* 10 = order text hight
*/
int sel = (y - 15) / 10;
if ((uint)sel >= this->vscroll.cap) return INVALID_ORDER;
sel += this->vscroll.pos;
return (sel < v->GetNumOrders() * 2 && sel >= 0) ? sel : INVALID_ORDER;
}
virtual void OnInvalidateData(int data)
{
switch (data) {
case 0:
/* Autoreplace replaced the vehicle */
this->vehicle = GetVehicle(this->window_number);
break;
case -1:
/* Removed / replaced all orders (after deleting / sharing) */
if (this->sel_index == -1) break;
this->DeleteChildWindows();
this->sel_index = -1;
break;
default: {
/* Moving an order. If one of these is INVALID_VEH_ORDER_ID, then
* the order is being created / removed */
if (this->sel_index == -1) break;
VehicleOrderID from = GB(data, 0, 8);
VehicleOrderID to = GB(data, 8, 8);
if (from == to) break; // no need to change anything
/* if from == INVALID_VEH_ORDER_ID, one order was added; if to == INVALID_VEH_ORDER_ID, one order was removed */
uint old_num_orders = this->vehicle->GetNumOrders() - (uint)(from == INVALID_VEH_ORDER_ID) + (uint)(to == INVALID_VEH_ORDER_ID);
VehicleOrderID selected_order = (this->sel_index + 1) / 2;
if (selected_order == old_num_orders) selected_order = 0; // when last travel time is selected, it belongs to order 0
bool travel = HasBit(this->sel_index, 0);
if (from != selected_order) {
/* Moving from preceeding order? */
selected_order -= (int)(from <= selected_order);
/* Moving to preceeding order? */
selected_order += (int)(to <= selected_order);
} else {
/* Now we are modifying the selected order */
if (to == INVALID_VEH_ORDER_ID) {
/* Deleting selected order */
this->DeleteChildWindows();
this->sel_index = -1;
break;
} else {
/* Moving selected order */
selected_order = to;
}
}
/* recompute new sel_index */
this->sel_index = 2 * selected_order - (int)travel;
/* travel time of first order needs special handling */
if (this->sel_index == -1) this->sel_index = this->vehicle->GetNumOrders() * 2 - 1;
} break;
}
}
virtual void OnPaint()
{
const Vehicle *v = this->vehicle;
int selected = this->sel_index;
SetVScrollCount(this, v->GetNumOrders() * 2);
if (v->owner == _local_company) {
bool disable = true;
if (selected != -1) {
const Order *order = GetVehicleOrder(v, ((selected + 1) / 2) % v->GetNumOrders());
if (selected % 2 == 1) {
disable = order != NULL && order->IsType(OT_CONDITIONAL);
} else {
disable = order == NULL || ((!order->IsType(OT_GOTO_STATION) || (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION)) && !order->IsType(OT_CONDITIONAL));
}
}
this->SetWidgetDisabledState(TTV_CHANGE_TIME, disable);
this->SetWidgetDisabledState(TTV_CLEAR_TIME, disable);
this->EnableWidget(TTV_RESET_LATENESS);
this->EnableWidget(TTV_AUTOFILL);
} else {
this->DisableWidget(TTV_CHANGE_TIME);
this->DisableWidget(TTV_CLEAR_TIME);
this->DisableWidget(TTV_RESET_LATENESS);
this->DisableWidget(TTV_AUTOFILL);
}
this->SetWidgetLoweredState(TTV_AUTOFILL, HasBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE));
SetDParam(0, v->index);
this->DrawWidgets();
int y = 15;
int i = this->vscroll.pos;
VehicleOrderID order_id = (i + 1) / 2;
bool final_order = false;
const Order *order = GetVehicleOrder(v, order_id);
while (order != NULL) {
/* Don't draw anything if it extends past the end of the window. */
if (i - this->vscroll.pos >= this->vscroll.cap) break;
if (i % 2 == 0) {
DrawOrderString(v, order, order_id, y, i == selected, true, this->widget[TTV_TIMETABLE_PANEL].right - 4);
order_id++;
if (order_id >= v->GetNumOrders()) {
order = GetVehicleOrder(v, 0);
final_order = true;
} else {
order = order->next;
}
} else {
StringID string;
if (order->IsType(OT_CONDITIONAL)) {
string = STR_TIMETABLE_NO_TRAVEL;
} else if (order->travel_time == 0) {
string = STR_TIMETABLE_TRAVEL_NOT_TIMETABLED;
} else {
SetTimetableParams(0, 1, order->travel_time);
string = STR_TIMETABLE_TRAVEL_FOR;
}
DrawStringTruncated(2, y, string, (i == selected) ? TC_WHITE : TC_BLACK, this->widget[TTV_TIMETABLE_PANEL].right - 4);
if (final_order) break;
}
i++;
y += 10;
}
y = this->widget[TTV_SUMMARY_PANEL].top + 1;
{
uint total_time = 0;
bool complete = true;
for (const Order *order = GetVehicleOrder(v, 0); order != NULL; order = order->next) {
total_time += order->travel_time + order->wait_time;
if (order->travel_time == 0 && !order->IsType(OT_CONDITIONAL)) complete = false;
if (order->wait_time == 0 && order->IsType(OT_GOTO_STATION) && !(order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION)) complete = false;
}
if (total_time != 0) {
SetTimetableParams(0, 1, total_time);
DrawString(2, y, complete ? STR_TIMETABLE_TOTAL_TIME : STR_TIMETABLE_TOTAL_TIME_INCOMPLETE, TC_BLACK);
}
}
y += 10;
if (v->lateness_counter == 0 || (!_settings_client.gui.timetable_in_ticks && v->lateness_counter / DAY_TICKS == 0)) {
DrawString(2, y, STR_TIMETABLE_STATUS_ON_TIME, TC_BLACK);
} else {
SetTimetableParams(0, 1, abs(v->lateness_counter));
DrawString(2, y, v->lateness_counter < 0 ? STR_TIMETABLE_STATUS_EARLY : STR_TIMETABLE_STATUS_LATE, TC_BLACK);
}
}
static inline uint32 PackTimetableArgs(const Vehicle *v, uint selected)
{
uint order_number = (selected + 1) / 2;
uint is_journey = (selected % 2 == 1) ? 1 : 0;
if (order_number >= v->GetNumOrders()) order_number = 0;
return v->index | (order_number << 16) | (is_journey << 24);
}
virtual void OnClick(Point pt, int widget)
{
const Vehicle *v = this->vehicle;
switch (widget) {
case TTV_ORDER_VIEW: // Order view button
ShowOrdersWindow(v);
break;
case TTV_TIMETABLE_PANEL: { // Main panel.
int selected = GetOrderFromTimetableWndPt(pt.y, v);
this->DeleteChildWindows();
this->sel_index = (selected == INVALID_ORDER || selected == this->sel_index) ? -1 : selected;
} break;
case TTV_CHANGE_TIME: { // "Wait For" button.
int selected = this->sel_index;
VehicleOrderID real = (selected + 1) / 2;
if (real >= v->GetNumOrders()) real = 0;
const Order *order = GetVehicleOrder(v, real);
StringID current = STR_EMPTY;
if (order != NULL) {
uint time = (selected % 2 == 1) ? order->travel_time : order->wait_time;
if (!_settings_client.gui.timetable_in_ticks) time /= DAY_TICKS;
if (time != 0) {
SetDParam(0, time);
current = STR_CONFIG_SETTING_INT32;
}
}
ShowQueryString(current, STR_TIMETABLE_CHANGE_TIME, 31, 150, this, CS_NUMERAL, QSF_NONE);
} break;
case TTV_CLEAR_TIME: { // Clear waiting time button.
uint32 p1 = PackTimetableArgs(v, this->sel_index);
DoCommandP(0, p1, 0, CMD_CHANGE_TIMETABLE | CMD_MSG(STR_CAN_T_TIMETABLE_VEHICLE));
} break;
case TTV_RESET_LATENESS: // Reset the vehicle's late counter.
DoCommandP(0, v->index, 0, CMD_SET_VEHICLE_ON_TIME | CMD_MSG(STR_CAN_T_TIMETABLE_VEHICLE));
break;
case TTV_AUTOFILL: { // Autofill the timetable.
uint32 p2 = 0;
if (!HasBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE)) SetBit(p2, 0);
if (_ctrl_pressed) SetBit(p2, 1);
DoCommandP(0, v->index, p2, CMD_AUTOFILL_TIMETABLE | CMD_MSG(STR_CAN_T_TIMETABLE_VEHICLE));
} break;
}
this->SetDirty();
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
const Vehicle *v = this->vehicle;
uint32 p1 = PackTimetableArgs(v, this->sel_index);
uint64 time = StrEmpty(str) ? 0 : strtoul(str, NULL, 10);
if (!_settings_client.gui.timetable_in_ticks) time *= DAY_TICKS;
uint32 p2 = minu(time, UINT16_MAX);
DoCommandP(0, p1, p2, CMD_CHANGE_TIMETABLE | CMD_MSG(STR_CAN_T_TIMETABLE_VEHICLE));
}
virtual void OnResize(Point new_size, Point delta)
{
/* Update the scroll + matrix */
this->vscroll.cap = (this->widget[TTV_TIMETABLE_PANEL].bottom - this->widget[TTV_TIMETABLE_PANEL].top) / 10;
}
};
static const Widget _timetable_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // TTV_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 326, 0, 13, STR_TIMETABLE_TITLE, STR_018C_WINDOW_TITLE_DRAG_THIS}, // TTV_CAPTION
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_GREY, 327, 387, 0, 13, STR_ORDER_VIEW, STR_ORDER_VIEW_TOOLTIP}, // TTV_ORDER_VIEW
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 388, 399, 0, 13, STR_NULL, STR_STICKY_BUTTON}, // TTV_STICKY
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 387, 14, 95, STR_NULL, STR_TIMETABLE_TOOLTIP}, // TTV_TIMETABLE_PANEL
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 388, 399, 14, 95, STR_NULL, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // TTV_SCROLLBAR
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 0, 399, 96, 117, STR_NULL, STR_NULL}, // TTV_SUMMARY_PANEL
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 109, 118, 129, STR_TIMETABLE_CHANGE_TIME, STR_TIMETABLE_WAIT_TIME_TOOLTIP}, // TTV_CHANGE_TIME
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 110, 219, 118, 129, STR_CLEAR_TIME, STR_TIMETABLE_CLEAR_TIME_TOOLTIP}, // TTV_CLEAR_TIME
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 220, 337, 118, 129, STR_RESET_LATENESS, STR_TIMETABLE_RESET_LATENESS_TOOLTIP}, // TTV_RESET_LATENESS
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 338, 387, 118, 129, STR_TIMETABLE_AUTOFILL, STR_TIMETABLE_AUTOFILL_TOOLTIP}, // TTV_AUTOFILL
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 388, 387, 118, 129, STR_NULL, STR_NULL}, // TTV_EMPTY
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 388, 399, 118, 129, STR_NULL, STR_RESIZE_BUTTON}, // TTV_RESIZE
{ WIDGETS_END }
};
static const WindowDesc _timetable_desc(
WDP_AUTO, WDP_AUTO, 400, 130, 400, 130,
WC_VEHICLE_TIMETABLE, WC_VEHICLE_VIEW,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE | WDF_CONSTRUCTION,
_timetable_widgets
);
void ShowTimetableWindow(const Vehicle *v)
{
DeleteWindowById(WC_VEHICLE_DETAILS, v->index, false);
DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
AllocateWindowDescFront<TimetableWindow>(&_timetable_desc, v->index);
}
| 12,351
|
C++
|
.cpp
| 291
| 38.639175
| 169
| 0.642714
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,130
|
articulated_vehicles.cpp
|
EnergeticBark_OpenTTD-3DS/src/articulated_vehicles.cpp
|
/* $Id$ */
/** @file articulated_vehicles.cpp Implementation of articulated vehicles. */
#include "stdafx.h"
#include "train.h"
#include "roadveh.h"
#include "newgrf_engine.h"
#include "vehicle_func.h"
#include "table/strings.h"
static const uint MAX_ARTICULATED_PARTS = 100; ///< Maximum of articulated parts per vehicle, i.e. when to abort calling the articulated vehicle callback.
uint CountArticulatedParts(EngineID engine_type, bool purchase_window)
{
if (!HasBit(EngInfo(engine_type)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) return 0;
/* If we can't allocate a vehicle now, we can't allocate it in the command
* either, so it doesn't matter how many articulated parts there are. */
if (!Vehicle::CanAllocateItem()) return 0;
Vehicle *v = NULL;;
if (!purchase_window) {
v = new InvalidVehicle();
v->engine_type = engine_type;
}
uint i;
for (i = 1; i < MAX_ARTICULATED_PARTS; i++) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_ARTIC_ENGINE, i, 0, engine_type, v);
if (callback == CALLBACK_FAILED || GB(callback, 0, 8) == 0xFF) break;
}
delete v;
return i - 1;
}
/**
* Returns the default (non-refitted) capacity of a specific EngineID.
* @param engine the EngineID of iterest
* @param type the type of the engine
* @param cargo_type returns the default cargo type, if needed
* @return capacity
*/
static inline uint16 GetVehicleDefaultCapacity(EngineID engine, VehicleType type, CargoID *cargo_type)
{
const Engine *e = GetEngine(engine);
CargoID cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
if (cargo_type != NULL) *cargo_type = cargo;
if (cargo == CT_INVALID) return 0;
return e->GetDisplayDefaultCapacity();
}
/**
* Returns all cargos a vehicle can carry.
* @param engine the EngineID of iterest
* @param type the type of the engine
* @param include_initial_cargo_type if true the default cargo type of the vehicle is included; if false only the refit_mask
* @return bit set of CargoIDs
*/
static inline uint32 GetAvailableVehicleCargoTypes(EngineID engine, VehicleType type, bool include_initial_cargo_type)
{
uint32 cargos = 0;
CargoID initial_cargo_type;
if (GetVehicleDefaultCapacity(engine, type, &initial_cargo_type) > 0) {
if (type != VEH_SHIP || ShipVehInfo(engine)->refittable) {
const EngineInfo *ei = EngInfo(engine);
cargos = ei->refit_mask;
}
if (include_initial_cargo_type && initial_cargo_type < NUM_CARGO) SetBit(cargos, initial_cargo_type);
}
return cargos;
}
uint16 *GetCapacityOfArticulatedParts(EngineID engine, VehicleType type)
{
static uint16 capacity[NUM_CARGO];
memset(capacity, 0, sizeof(capacity));
CargoID cargo_type;
uint16 cargo_capacity = GetVehicleDefaultCapacity(engine, type, &cargo_type);
if (cargo_type < NUM_CARGO) capacity[cargo_type] = cargo_capacity;
if (type != VEH_TRAIN && type != VEH_ROAD) return capacity;
if (!HasBit(EngInfo(engine)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) return capacity;
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_ARTIC_ENGINE, i, 0, engine, NULL);
if (callback == CALLBACK_FAILED || GB(callback, 0, 8) == 0xFF) break;
EngineID artic_engine = GetNewEngineID(GetEngineGRF(engine), type, GB(callback, 0, 7));
cargo_capacity = GetVehicleDefaultCapacity(artic_engine, type, &cargo_type);
if (cargo_type < NUM_CARGO) capacity[cargo_type] += cargo_capacity;
}
return capacity;
}
/**
* Checks whether any of the articulated parts is refittable
* @param engine the first part
* @return true if refittable
*/
bool IsArticulatedVehicleRefittable(EngineID engine)
{
if (IsEngineRefittable(engine)) return true;
const Engine *e = GetEngine(engine);
if (e->type != VEH_TRAIN && e->type != VEH_ROAD) return false;
if (!HasBit(e->info.callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) return false;
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_ARTIC_ENGINE, i, 0, engine, NULL);
if (callback == CALLBACK_FAILED || GB(callback, 0, 8) == 0xFF) break;
EngineID artic_engine = GetNewEngineID(GetEngineGRF(engine), e->type, GB(callback, 0, 7));
if (IsEngineRefittable(artic_engine)) return true;
}
return false;
}
/**
* Ors the refit_masks of all articulated parts.
* @param engine the first part
* @param type the vehicle type
* @param include_initial_cargo_type if true the default cargo type of the vehicle is included; if false only the refit_mask
* @return bit mask of CargoIDs which are a refit option for at least one articulated part
*/
uint32 GetUnionOfArticulatedRefitMasks(EngineID engine, VehicleType type, bool include_initial_cargo_type)
{
uint32 cargos = GetAvailableVehicleCargoTypes(engine, type, include_initial_cargo_type);
if (type != VEH_TRAIN && type != VEH_ROAD) return cargos;
if (!HasBit(EngInfo(engine)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) return cargos;
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_ARTIC_ENGINE, i, 0, engine, NULL);
if (callback == CALLBACK_FAILED || GB(callback, 0, 8) == 0xFF) break;
EngineID artic_engine = GetNewEngineID(GetEngineGRF(engine), type, GB(callback, 0, 7));
cargos |= GetAvailableVehicleCargoTypes(artic_engine, type, include_initial_cargo_type);
}
return cargos;
}
/**
* Ands the refit_masks of all articulated parts.
* @param engine the first part
* @param type the vehicle type
* @param include_initial_cargo_type if true the default cargo type of the vehicle is included; if false only the refit_mask
* @return bit mask of CargoIDs which are a refit option for every articulated part (with default capacity > 0)
*/
uint32 GetIntersectionOfArticulatedRefitMasks(EngineID engine, VehicleType type, bool include_initial_cargo_type)
{
uint32 cargos = UINT32_MAX;
uint32 veh_cargos = GetAvailableVehicleCargoTypes(engine, type, include_initial_cargo_type);
if (veh_cargos != 0) cargos &= veh_cargos;
if (type != VEH_TRAIN && type != VEH_ROAD) return cargos;
if (!HasBit(EngInfo(engine)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) return cargos;
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_ARTIC_ENGINE, i, 0, engine, NULL);
if (callback == CALLBACK_FAILED || GB(callback, 0, 8) == 0xFF) break;
EngineID artic_engine = GetNewEngineID(GetEngineGRF(engine), type, GB(callback, 0, 7));
veh_cargos = GetAvailableVehicleCargoTypes(artic_engine, type, include_initial_cargo_type);
if (veh_cargos != 0) cargos &= veh_cargos;
}
return cargos;
}
/**
* Tests if all parts of an articulated vehicle are refitted to the same cargo.
* Note: Vehicles not carrying anything are ignored
* @param v the first vehicle in the chain
* @param cargo_type returns the common CargoID if needed. (CT_INVALID if no part is carrying something or they are carrying different things)
* @return true if some parts are carrying different cargos, false if all parts are carrying the same (nothing is also the same)
*/
bool IsArticulatedVehicleCarryingDifferentCargos(const Vehicle *v, CargoID *cargo_type)
{
CargoID first_cargo = CT_INVALID;
do {
if (v->cargo_cap > 0 && v->cargo_type != CT_INVALID) {
if (first_cargo == CT_INVALID) first_cargo = v->cargo_type;
if (first_cargo != v->cargo_type) {
if (cargo_type != NULL) *cargo_type = CT_INVALID;
return true;
}
}
switch (v->type) {
case VEH_TRAIN:
v = (EngineHasArticPart(v) ? GetNextArticPart(v) : NULL);
break;
case VEH_ROAD:
v = (RoadVehHasArticPart(v) ? v->Next() : NULL);
break;
default:
v = NULL;
break;
}
} while (v != NULL);
if (cargo_type != NULL) *cargo_type = first_cargo;
return false;
}
/**
* Checks whether the specs of freshly build articulated vehicles are consistent with the information specified in the purchase list.
* Only essential information is checked to leave room for magic tricks/workarounds to grfcoders.
* It checks:
* For autoreplace/-renew:
* - Default cargo type (without capacity)
* - intersection and union of refit masks.
*/
void CheckConsistencyOfArticulatedVehicle(const Vehicle *v)
{
const Engine *engine = GetEngine(v->engine_type);
uint32 purchase_refit_union = GetUnionOfArticulatedRefitMasks(v->engine_type, v->type, true);
uint32 purchase_refit_intersection = GetIntersectionOfArticulatedRefitMasks(v->engine_type, v->type, true);
uint16 *purchase_default_capacity = GetCapacityOfArticulatedParts(v->engine_type, v->type);
uint32 real_refit_union = 0;
uint32 real_refit_intersection = UINT_MAX;
uint16 real_default_capacity[NUM_CARGO];
memset(real_default_capacity, 0, sizeof(real_default_capacity));
do {
uint32 refit_mask = GetAvailableVehicleCargoTypes(v->engine_type, v->type, true);
real_refit_union |= refit_mask;
if (refit_mask != 0) real_refit_intersection &= refit_mask;
assert(v->cargo_type < NUM_CARGO);
real_default_capacity[v->cargo_type] += v->cargo_cap;
switch (v->type) {
case VEH_TRAIN:
v = (EngineHasArticPart(v) ? GetNextArticPart(v) : NULL);
break;
case VEH_ROAD:
v = (RoadVehHasArticPart(v) ? v->Next() : NULL);
break;
default:
v = NULL;
break;
}
} while (v != NULL);
/* Check whether the vehicle carries more cargos than expected */
bool carries_more = false;
for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
if (real_default_capacity[cid] != 0 && purchase_default_capacity[cid] == 0) {
carries_more = true;
break;
}
}
/* show a warning once for each GRF after each game load */
if (real_refit_union != purchase_refit_union || real_refit_intersection != purchase_refit_intersection || carries_more) {
ShowNewGrfVehicleError(engine->index, STR_NEWGRF_BUGGY, STR_NEWGRF_BUGGY_ARTICULATED_CARGO, GBUG_VEH_REFIT, false);
}
}
void AddArticulatedParts(Vehicle **vl, VehicleType type)
{
const Vehicle *v = vl[0];
Vehicle *u = vl[0];
if (!HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) return;
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_ARTIC_ENGINE, i, 0, v->engine_type, v);
if (callback == CALLBACK_FAILED || GB(callback, 0, 8) == 0xFF) return;
/* Attempt to use pre-allocated vehicles until they run out. This can happen
* if the callback returns different values depending on the cargo type. */
u->SetNext(vl[i]);
if (u->Next() == NULL) return;
Vehicle *previous = u;
u = u->Next();
EngineID engine_type = GetNewEngineID(GetEngineGRF(v->engine_type), type, GB(callback, 0, 7));
bool flip_image = HasBit(callback, 7);
const Engine *e_artic = GetEngine(engine_type);
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN:
u = new (u) Train();
u->subtype = 0;
previous->SetNext(u);
u->u.rail.track = v->u.rail.track;
u->u.rail.railtype = v->u.rail.railtype;
u->u.rail.first_engine = v->engine_type;
u->spritenum = e_artic->u.rail.image_index;
if (e_artic->CanCarryCargo()) {
u->cargo_type = e_artic->GetDefaultCargoType();
u->cargo_cap = e_artic->u.rail.capacity; // Callback 36 is called when the consist is finished
} else {
u->cargo_type = v->cargo_type; // Needed for livery selection
u->cargo_cap = 0;
}
SetArticulatedPart(u);
break;
case VEH_ROAD:
u = new (u) RoadVehicle();
u->subtype = 0;
previous->SetNext(u);
u->u.road.first_engine = v->engine_type;
u->u.road.cached_veh_length = 8; // Callback is called when the consist is finished
u->u.road.state = RVSB_IN_DEPOT;
u->u.road.roadtype = v->u.road.roadtype;
u->u.road.compatible_roadtypes = v->u.road.compatible_roadtypes;
u->spritenum = e_artic->u.road.image_index;
if (e_artic->CanCarryCargo()) {
u->cargo_type = e_artic->GetDefaultCargoType();
u->cargo_cap = e_artic->u.road.capacity; // Callback 36 is called when the consist is finished
} else {
u->cargo_type = v->cargo_type; // Needed for livery selection
u->cargo_cap = 0;
}
SetRoadVehArticPart(u);
break;
}
/* get common values from first engine */
u->direction = v->direction;
u->owner = v->owner;
u->tile = v->tile;
u->x_pos = v->x_pos;
u->y_pos = v->y_pos;
u->z_pos = v->z_pos;
u->build_year = v->build_year;
u->vehstatus = v->vehstatus & ~VS_STOPPED;
u->cargo_subtype = 0;
u->max_speed = 0;
u->max_age = 0;
u->engine_type = engine_type;
u->value = 0;
u->cur_image = 0xAC2;
u->random_bits = VehicleRandomBits();
if (flip_image) u->spritenum++;
VehicleMove(u, false);
}
}
| 12,630
|
C++
|
.cpp
| 301
| 39.006645
| 154
| 0.716699
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,132
|
signs.cpp
|
EnergeticBark_OpenTTD-3DS/src/signs.cpp
|
/* $Id$ */
/** @file signs.cpp Handling of signs. */
#include "stdafx.h"
#include "landscape.h"
#include "signs_base.h"
#include "signs_func.h"
#include "strings_func.h"
#include "viewport_func.h"
#include "zoom_func.h"
#include "functions.h"
#include "oldpool_func.h"
#include "table/strings.h"
/* Initialize the sign-pool */
DEFINE_OLD_POOL_GENERIC(Sign, Sign)
Sign::Sign(Owner owner)
{
this->owner = owner;
}
Sign::~Sign()
{
free(this->name);
if (CleaningPool()) return;
DeleteRenameSignWindow(this->index);
this->owner = INVALID_OWNER;
}
/**
*
* Update the coordinate of one sign
* @param si Pointer to the Sign
*
*/
void UpdateSignVirtCoords(Sign *si)
{
Point pt = RemapCoords(si->x, si->y, si->z);
SetDParam(0, si->index);
UpdateViewportSignPos(&si->sign, pt.x, pt.y - 6, STR_2806);
}
/** Update the coordinates of all signs */
void UpdateAllSignVirtCoords()
{
Sign *si;
FOR_ALL_SIGNS(si) UpdateSignVirtCoords(si);
}
/**
* Marks the region of a sign as dirty.
*
* This function marks the sign in all viewports as dirty for repaint.
*
* @param si Pointer to the Sign
* @ingroup dirty
*/
void MarkSignDirty(Sign *si)
{
/* We use ZOOM_LVL_MAX here, as every viewport can have an other zoom,
* and there is no way for us to know which is the biggest. So make the
* biggest area dirty, and we are safe for sure. */
MarkAllViewportsDirty(
si->sign.left - 6,
si->sign.top - 3,
si->sign.left + ScaleByZoom(si->sign.width_1 + 12, ZOOM_LVL_MAX),
si->sign.top + ScaleByZoom(12, ZOOM_LVL_MAX));
}
/**
*
* Initialize the signs
*
*/
void InitializeSigns()
{
_Sign_pool.CleanPool();
_Sign_pool.AddBlockToPool();
}
| 1,664
|
C++
|
.cpp
| 72
| 21.347222
| 73
| 0.70741
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.