1
0
mirror of https://github.com/OpenTTD/OpenTTD.git synced 2025-08-13 01:29:10 +00:00

Compare commits

..

1 Commits

Author SHA1 Message Date
orudge
001b12b742 (svn r2355) Tagged 0.4.0.1 2005-05-21 19:42:12 +00:00
503 changed files with 96796 additions and 186379 deletions

7
BUGS
View File

@@ -1,7 +0,0 @@
/* $Id$ */
KNOWN BUGS / PROBLEMS:
Normal and elrail depots look the same. Use 'X' (transparent buildings)
to distinguish between them
Missing curors / icons for construction (currently using the conventional ones)

39
COPYING
View File

@@ -1,12 +1,12 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
@@ -15,7 +15,7 @@ software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
@@ -55,8 +55,8 @@ patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
@@ -110,7 +110,7 @@ above, provided that you also meet all of these conditions:
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
@@ -168,7 +168,7 @@ access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
@@ -225,7 +225,7 @@ impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
@@ -255,7 +255,7 @@ make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
@@ -277,9 +277,9 @@ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
@@ -303,9 +303,10 @@ the "copyright" line and a pointer to where the full notice is found.
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 this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
@@ -335,5 +336,5 @@ necessary. Here is a sample; alter the names:
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.

233
Doxyfile
View File

@@ -1,233 +0,0 @@
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
PROJECT_NAME = openttd
OUTPUT_DIRECTORY = docs/source/
CREATE_SUBDIRS = NO
OUTPUT_LANGUAGE = English
USE_WINDOWS_ENCODING = NO
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
ABBREVIATE_BRIEF = "The $name class" \
"The $name widget" \
"The $name file" \
is \
provides \
specifies \
contains \
represents \
a \
an \
the
ALWAYS_DETAILED_SEC = NO
INLINE_INHERITED_MEMB = NO
FULL_PATH_NAMES = YES
STRIP_FROM_PATH = ./
STRIP_FROM_INC_PATH =
SHORT_NAMES = NO
JAVADOC_AUTOBRIEF = YES
MULTILINE_CPP_IS_BRIEF = NO
DETAILS_AT_TOP = NO
INHERIT_DOCS = YES
DISTRIBUTE_GROUP_DOC = NO
TAB_SIZE = 2
ALIASES =
OPTIMIZE_OUTPUT_FOR_C = YES
OPTIMIZE_OUTPUT_JAVA = NO
SUBGROUPING = YES
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL = NO
EXTRACT_PRIVATE = YES
EXTRACT_STATIC = YES
EXTRACT_LOCAL_CLASSES = YES
EXTRACT_LOCAL_METHODS = YES
HIDE_UNDOC_MEMBERS = NO
HIDE_UNDOC_CLASSES = NO
HIDE_FRIEND_COMPOUNDS = NO
HIDE_IN_BODY_DOCS = NO
INTERNAL_DOCS = NO
CASE_SENSE_NAMES = YES
HIDE_SCOPE_NAMES = NO
SHOW_INCLUDE_FILES = YES
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
SORT_BRIEF_DOCS = NO
SORT_BY_SCOPE_NAME = NO
GENERATE_TODOLIST = YES
GENERATE_TESTLIST = YES
GENERATE_BUGLIST = YES
GENERATE_DEPRECATEDLIST= YES
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = YES
SHOW_DIRECTORIES = YES
FILE_VERSION_FILTER =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
WARN_IF_DOC_ERROR = YES
WARN_NO_PARAMDOC = NO
WARN_FORMAT = "$file:$line: $text"
WARN_LOGFILE =
#---------------------------------------------------------------------------
# configuration options related to the input files
#---------------------------------------------------------------------------
INPUT = ./
FILE_PATTERNS = *.c \
*.cc \
*.cxx \
*.cpp \
*.c++ \
*.h \
table/*.h
RECURSIVE = YES
EXCLUDE =
EXCLUDE_SYMLINKS = NO
EXCLUDE_PATTERNS =
EXAMPLE_PATH =
EXAMPLE_PATTERNS = *
EXAMPLE_RECURSIVE = NO
IMAGE_PATH =
INPUT_FILTER =
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
#---------------------------------------------------------------------------
# configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER = YES
INLINE_SOURCES = NO
STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = YES
REFERENCES_RELATION = YES
VERBATIM_HEADERS = YES
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX = NO
COLS_IN_ALPHA_INDEX = 5
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML = YES
HTML_OUTPUT = html
HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
HTML_ALIGN_MEMBERS = YES
GENERATE_HTMLHELP = YES
CHM_FILE =
HHC_LOCATION =
GENERATE_CHI = NO
BINARY_TOC = NO
TOC_EXPAND = YES
DISABLE_INDEX = NO
ENUM_VALUES_PER_LINE = 4
GENERATE_TREEVIEW = YES
TREEVIEW_WIDTH = 250
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX = NO
LATEX_OUTPUT = latex
LATEX_CMD_NAME = latex
MAKEINDEX_CMD_NAME = makeindex
COMPACT_LATEX = NO
PAPER_TYPE = a4wide
EXTRA_PACKAGES =
LATEX_HEADER =
PDF_HYPERLINKS = NO
USE_PDFLATEX = NO
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
#---------------------------------------------------------------------------
# configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF = NO
RTF_OUTPUT = rtf
COMPACT_RTF = NO
RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN = YES
MAN_OUTPUT = man
MAN_EXTENSION = .3
MAN_LINKS = NO
#---------------------------------------------------------------------------
# configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML = NO
XML_OUTPUT = xml
XML_SCHEMA =
XML_DTD =
XML_PROGRAMLISTING = YES
#---------------------------------------------------------------------------
# configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
PERLMOD_PRETTY = YES
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
ENABLE_PREPROCESSING = YES
MACRO_EXPANSION = NO
EXPAND_ONLY_PREDEF = NO
SEARCH_INCLUDES = YES
INCLUDE_PATH =
INCLUDE_FILE_PATTERNS =
PREDEFINED =
EXPAND_AS_DEFINED =
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration::additions related to external references
#---------------------------------------------------------------------------
TAGFILES =
GENERATE_TAGFILE = openttd.tag
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
PERL_PATH = /usr/bin/perl
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS = YES
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = NO
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
GROUP_GRAPHS = YES
UML_LOOK = NO
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
CALL_GRAPH = NO
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DOT_IMAGE_FORMAT = png
DOT_PATH =
DOTFILE_DIRS =
MAX_DOT_GRAPH_WIDTH = 1024
MAX_DOT_GRAPH_HEIGHT = 1024
MAX_DOT_GRAPH_DEPTH = 1000
DOT_TRANSPARENT = NO
DOT_MULTI_TARGETS = NO
GENERATE_LEGEND = YES
DOT_CLEANUP = YES
#---------------------------------------------------------------------------
# Configuration::additions related to the search engine
#---------------------------------------------------------------------------
SEARCHENGINE = NO

905
Makefile

File diff suppressed because it is too large Load Diff

8
StdAfx.c Normal file
View File

@@ -0,0 +1,8 @@
// stdafx.cpp : source file that includes just the standard includes
// ttd.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,7 @@
/* $Id$ */
#ifndef AI_H
#define AI_H
#ifndef AI_TROLLY_H
#define AI_TROLLY_H
#include "../../aystar.h"
#include "../../player.h"
#include "aystar.h"
/*
* These defines can be altered to change the behavoir of the AI
@@ -166,34 +163,33 @@
// This stops 90degrees curves
static const byte _illegal_curves[6] = {
255, 255, // Horz and vert, don't have the effect
5, // upleft and upright are not valid
4, // downright and downleft are not valid
2, // downleft and upleft are not valid
3, // upright and downright are not valid
255, 255, // Horz and vert, don't have the effect
5, // upleft and upright are not valid
4, // downright and downleft are not valid
2, // downleft and upleft are not valid
3, // upright and downright are not valid
};
enum {
AI_STATE_STARTUP = 0,
AI_STATE_FIRST_TIME,
AI_STATE_NOTHING,
AI_STATE_WAKE_UP,
AI_STATE_LOCATE_ROUTE,
AI_STATE_FIND_STATION,
AI_STATE_FIND_PATH,
AI_STATE_FIND_DEPOT,
AI_STATE_VERIFY_ROUTE,
AI_STATE_BUILD_STATION,
AI_STATE_BUILD_PATH,
AI_STATE_BUILD_DEPOT,
AI_STATE_BUILD_VEHICLE,
AI_STATE_WAIT_FOR_BUILD,
AI_STATE_GIVE_ORDERS,
AI_STATE_START_VEHICLE,
AI_STATE_REPAY_MONEY,
AI_STATE_STARTUP = 0,
AI_STATE_FIRST_TIME,
AI_STATE_NOTHING,
AI_STATE_WAKE_UP,
AI_STATE_LOCATE_ROUTE,
AI_STATE_FIND_STATION,
AI_STATE_FIND_PATH,
AI_STATE_FIND_DEPOT,
AI_STATE_VERIFY_ROUTE,
AI_STATE_BUILD_STATION,
AI_STATE_BUILD_PATH,
AI_STATE_BUILD_DEPOT,
AI_STATE_BUILD_VEHICLE,
AI_STATE_GIVE_ORDERS,
AI_STATE_START_VEHICLE,
AI_STATE_REPAY_MONEY,
AI_STATE_CHECK_ALL_VEHICLES,
AI_STATE_ACTION_DONE,
AI_STATE_STOP, // Temporary function to stop the AI
AI_STATE_ACTION_DONE,
AI_STATE_STOP, // Temporary function to stop the AI
};
// Used for tbt (train/bus/truck)
@@ -213,7 +209,7 @@ enum {
// Used for from_type/to_type
enum {
AI_NO_TYPE = 0,
AI_NO_TYPE = 0,
AI_CITY,
AI_INDUSTRY,
};
@@ -226,7 +222,7 @@ enum {
#define AI_NO_CARGO 0xFF // Means that there is no cargo defined yet (used for industry)
#define AI_NEED_CARGO 0xFE // Used when the AI needs to find out a cargo for the route
#define AI_STATION_RANGE TileXY(MapMaxX(), MapMaxY())
#define AI_STATION_RANGE TILE_XY(MapMaxX(), MapMaxY())
#define AI_PATHFINDER_NO_DIRECTION (byte)-1
@@ -244,19 +240,20 @@ AyStar *new_AyStar_AiPathFinder(int max_tiles_around, Ai_PathFinderInfo *PathFin
void clean_AyStar_AiPathFinder(AyStar *aystar, Ai_PathFinderInfo *PathFinderInfo);
// ai_shared.c
int AiNew_GetRailDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c);
int AiNew_GetRoadDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c);
DiagDirection AiNew_GetDirection(TileIndex tile_a, TileIndex tile_b);
int AiNew_GetRailDirection(uint tile_a, uint tile_b, uint tile_c);
int AiNew_GetRoadDirection(uint tile_a, uint tile_b, uint tile_c);
int AiNew_GetDirection(uint tile_a, uint tile_b);
bool AiNew_SetSpecialVehicleFlag(Player *p, Vehicle *v, uint flag);
uint AiNew_GetSpecialVehicleFlag(Player *p, Vehicle *v);
// ai_build.c
bool AiNew_Build_CompanyHQ(Player *p, TileIndex tile);
int AiNew_Build_Station(Player *p, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag);
int AiNew_Build_Bridge(Player *p, TileIndex tile_a, TileIndex tile_b, byte flag);
bool AiNew_Build_CompanyHQ(Player *p, uint tile);
int AiNew_Build_Station(Player *p, byte type, uint tile, byte length, byte numtracks, byte direction, byte flag);
int AiNew_Build_Bridge(Player *p, uint tile_a, uint tile_b, byte flag);
int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte flag);
EngineID AiNew_PickVehicle(Player *p);
int AiNew_Build_Vehicle(Player *p, TileIndex tile, byte flag);
int AiNew_Build_Depot(Player* p, TileIndex tile, DiagDirection direction, byte flag);
int AiNew_PickVehicle(Player *p);
int AiNew_Build_Vehicle(Player *p, uint tile, byte flag);
int AiNew_Build_Depot(Player *p, uint tile, byte direction, byte flag);
#endif /* AI_TROLLY_H */
#endif

247
ai/ai.c
View File

@@ -1,247 +0,0 @@
/* $Id$ */
#include "../stdafx.h"
#include "../openttd.h"
#include "../variables.h"
#include "../command.h"
#include "../network.h"
#include "ai.h"
#include "default/default.h"
/**
* Dequeues commands put in the queue via AI_PutCommandInQueue.
*/
static void AI_DequeueCommands(PlayerID player)
{
AICommand *com, *entry_com;
entry_com = _ai_player[player].queue;
/* It happens that DoCommandP issues a new DoCommandAI which adds a new command
* to this very same queue (don't argue about this, if it currently doesn't
* happen I can tell you it will happen with AIScript -- TrueLight). If we
* do not make the queue NULL, that commands will be dequeued immediatly.
* Therefor we safe the entry-point to entry_com, and make the queue NULL, so
* the new queue can be safely built up. */
_ai_player[player].queue = NULL;
_ai_player[player].queue_tail = NULL;
/* Dequeue all commands */
while ((com = entry_com) != NULL) {
_current_player = player;
_cmd_text = com->text;
DoCommandP(com->tile, com->p1, com->p2, com->callback, com->procc);
/* Free item */
entry_com = com->next;
free(com->text);
free(com);
}
}
/**
* Needed for SP; we need to delay DoCommand with 1 tick, because else events
* will make infinite loops (AIScript).
*/
static void AI_PutCommandInQueue(PlayerID player, TileIndex tile, uint32 p1, uint32 p2, uint procc, CommandCallback* callback)
{
AICommand *com;
if (_ai_player[player].queue_tail == NULL) {
/* There is no item in the queue yet, create the queue */
_ai_player[player].queue = malloc(sizeof(AICommand));
_ai_player[player].queue_tail = _ai_player[player].queue;
} else {
/* Add an item at the end */
_ai_player[player].queue_tail->next = malloc(sizeof(AICommand));
_ai_player[player].queue_tail = _ai_player[player].queue_tail->next;
}
/* This is our new item */
com = _ai_player[player].queue_tail;
/* Assign the info */
com->tile = tile;
com->p1 = p1;
com->p2 = p2;
com->procc = procc;
com->callback = callback;
com->next = NULL;
com->text = NULL;
/* Copy the cmd_text, if needed */
if (_cmd_text != NULL) {
com->text = strdup(_cmd_text);
_cmd_text = NULL;
}
}
/**
* Executes a raw DoCommand for the AI.
*/
int32 AI_DoCommandCc(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc, CommandCallback* callback)
{
PlayerID old_lp;
int32 res = 0;
const char* tmp_cmdtext;
/* If you enable DC_EXEC with DC_QUERY_COST you are a really strange
* person.. should we check for those funny jokes?
*/
/* The test already resets _cmd_text, so backup the pointer */
tmp_cmdtext = _cmd_text;
/* First, do a test-run to see if we can do this */
res = DoCommand(tile, p1, p2, flags & ~DC_EXEC, procc);
/* The command failed, or you didn't want to execute, or you are quering, return */
if (CmdFailed(res) || !(flags & DC_EXEC) || (flags & DC_QUERY_COST)) {
return res;
}
/* Restore _cmd_text */
_cmd_text = tmp_cmdtext;
/* If we did a DC_EXEC, and the command did not return an error, execute it
* over the network */
if (flags & DC_AUTO) procc |= CMD_AUTO;
if (flags & DC_NO_WATER) procc |= CMD_NO_WATER;
/* NetworkSend_Command needs _local_player to be set correctly, so
* adjust it, and put it back right after the function */
old_lp = _local_player;
_local_player = _current_player;
#ifdef ENABLE_NETWORK
/* Send the command */
if (_networking) {
/* Network is easy, send it to his handler */
NetworkSend_Command(tile, p1, p2, procc, callback);
} else {
#else
{
#endif
/* If we execute BuildCommands directly in SP, we have a big problem with events
* so we need to delay is for 1 tick */
AI_PutCommandInQueue(_current_player, tile, p1, p2, procc, callback);
}
/* Set _local_player back */
_local_player = old_lp;
return res;
}
int32 AI_DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc)
{
return AI_DoCommandCc(tile, p1, p2, flags, procc, NULL);
}
/**
* Run 1 tick of the AI. Don't overdo it, keep it realistic.
*/
static void AI_RunTick(PlayerID player)
{
extern void AiNewDoGameLoop(Player *p);
Player *p = GetPlayer(player);
_current_player = player;
if (_patches.ainew_active) {
AiNewDoGameLoop(p);
} else {
/* Enable all kind of cheats the old AI needs in order to operate correctly... */
_is_old_ai_player = true;
AiDoGameLoop(p);
_is_old_ai_player = false;
}
}
/**
* The gameloop for AIs.
* Handles one tick for all the AIs.
*/
void AI_RunGameLoop(void)
{
/* Don't do anything if ai is disabled */
if (!_ai.enabled) return;
/* Don't do anything if we are a network-client, or the AI has been disabled */
if (_networking && (!_network_server || !_patches.ai_in_multiplayer)) return;
/* New tick */
_ai.tick++;
/* Make sure the AI follows the difficulty rule.. */
assert(_opt.diff.competitor_speed <= 4);
if ((_ai.tick & ((1 << (4 - _opt.diff.competitor_speed)) - 1)) != 0) return;
/* Check for AI-client (so joining a network with an AI) */
if (!_networking || _network_server) {
/* Check if we want to run AIs (server or SP only) */
const Player* p;
FOR_ALL_PLAYERS(p) {
if (p->is_active && p->is_ai) {
/* This should always be true, else something went wrong... */
assert(_ai_player[p->index].active);
/* Run the script */
AI_DequeueCommands(p->index);
AI_RunTick(p->index);
}
}
}
_current_player = OWNER_NONE;
}
/**
* A new AI sees the day of light. You can do here what ever you think is needed.
*/
void AI_StartNewAI(PlayerID player)
{
assert(IsValidPlayer(player));
/* Called if a new AI is booted */
_ai_player[player].active = true;
}
/**
* This AI player died. Give it some chance to make a final puf.
*/
void AI_PlayerDied(PlayerID player)
{
/* Called if this AI died */
_ai_player[player].active = false;
}
/**
* Initialize some AI-related stuff.
*/
void AI_Initialize(void)
{
/* First, make sure all AIs are DEAD! */
AI_Uninitialize();
memset(&_ai, 0, sizeof(_ai));
memset(&_ai_player, 0, sizeof(_ai_player));
_ai.enabled = true;
}
/**
* Deinitializer for AI-related stuff.
*/
void AI_Uninitialize(void)
{
const Player* p;
FOR_ALL_PLAYERS(p) {
if (p->is_active && p->is_ai) AI_PlayerDied(p->index);
}
}

111
ai/ai.h
View File

@@ -1,111 +0,0 @@
#ifndef AI_H
#define AI_H
#include "../functions.h"
#include "../network.h"
#include "../player.h"
#include "../command.h"
/* How DoCommands look like for an AI */
typedef struct AICommand {
uint32 tile;
uint32 p1;
uint32 p2;
uint32 procc;
CommandCallback* callback;
char *text;
uint uid;
struct AICommand *next;
} AICommand;
/* The struct for an AIScript Player */
typedef struct AIPlayer {
bool active; ///< Is this AI active?
AICommand *queue; ///< The commands that he has in his queue
AICommand *queue_tail; ///< The tail of this queue
} AIPlayer;
/* The struct to keep some data about the AI in general */
typedef struct AIStruct {
/* General */
bool enabled; ///< Is AI enabled?
uint tick; ///< The current tick (something like _frame_counter, only for AIs)
} AIStruct;
VARDEF AIStruct _ai;
VARDEF AIPlayer _ai_player[MAX_PLAYERS];
// ai.c
void AI_StartNewAI(PlayerID player);
void AI_PlayerDied(PlayerID player);
void AI_RunGameLoop(void);
void AI_Initialize(void);
void AI_Uninitialize(void);
int32 AI_DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc);
int32 AI_DoCommandCc(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc, CommandCallback* callback);
/** Is it allowed to start a new AI.
* This function checks some boundries to see if we should launch a new AI.
* @return True if we can start a new AI.
*/
static inline bool AI_AllowNewAI(void)
{
/* If disabled, no AI */
if (!_ai.enabled)
return false;
/* If in network, but no server, no AI */
if (_networking && !_network_server)
return false;
/* If in network, and server, possible AI */
if (_networking && _network_server) {
/* Do we want AIs in multiplayer? */
if (!_patches.ai_in_multiplayer)
return false;
/* Only the NewAI is allowed... sadly enough the old AI just doesn't support this
* system, because all commands are delayed by at least 1 tick, which causes
* a big problem, because it uses variables that are only set AFTER the command
* is really executed... */
if (!_patches.ainew_active)
return false;
}
return true;
}
#define AI_CHANCE16(a,b) ((uint16) AI_Random() <= (uint16)((65536 * a) / b))
#define AI_CHANCE16R(a,b,r) ((uint16)(r = AI_Random()) <= (uint16)((65536 * a) / b))
/**
* The random-function that should be used by ALL AIs.
*/
static inline uint AI_RandomRange(uint max)
{
/* We pick RandomRange if we are in SP (so when saved, we do the same over and over)
* but we pick InteractiveRandomRange if we are a network_server or network-client.
*/
if (_networking)
return InteractiveRandomRange(max);
else
return RandomRange(max);
}
/**
* The random-function that should be used by ALL AIs.
*/
static inline uint32 AI_Random(void)
{
/* We pick RandomRange if we are in SP (so when saved, we do the same over and over)
* but we pick InteractiveRandomRange if we are a network_server or network-client.
*/
if (_networking)
return InteractiveRandom();
else
return Random();
}
#endif /* AI_H */

View File

@@ -1,8 +0,0 @@
/* $Id$ */
#ifndef DEFAULT_H
#define DEFAULT_H
void AiDoGameLoop(Player*);
#endif

View File

@@ -1,324 +0,0 @@
/* $Id$ */
#include "../../stdafx.h"
#include "../../openttd.h"
#include "../../debug.h"
#include "../../functions.h"
#include "../../map.h"
#include "../../road_map.h"
#include "../../tile.h"
#include "../../vehicle.h"
#include "../../command.h"
#include "trolly.h"
#include "../../engine.h"
#include "../../station.h"
#include "../../variables.h"
#include "../../bridge.h"
#include "../ai.h"
// Build HQ
// Params:
// tile : tile where HQ is going to be build
bool AiNew_Build_CompanyHQ(Player *p, TileIndex tile)
{
if (CmdFailed(AI_DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ)))
return false;
AI_DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ);
return true;
}
// Build station
// Params:
// type : AI_TRAIN/AI_BUS/AI_TRUCK : indicates the type of station
// tile : tile where station is going to be build
// length : in case of AI_TRAIN: length of station
// numtracks : in case of AI_TRAIN: tracks of station
// direction : the direction of the station
// flag : flag passed to DoCommand (normally 0 to get the cost or DC_EXEC to build it)
int AiNew_Build_Station(Player *p, byte type, TileIndex tile, byte length, byte numtracks, byte direction, byte flag)
{
if (type == AI_TRAIN)
return AI_DoCommand(tile, direction + (numtracks << 8) + (length << 16), 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_RAILROAD_STATION);
if (type == AI_BUS)
return AI_DoCommand(tile, direction, RS_BUS, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_STOP);
return AI_DoCommand(tile, direction, RS_TRUCK, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_STOP);
}
// Builds a brdige. The second best out of the ones available for this player
// Params:
// tile_a : starting point
// tile_b : end point
// flag : flag passed to DoCommand
int AiNew_Build_Bridge(Player *p, TileIndex tile_a, TileIndex tile_b, byte flag)
{
int bridge_type, bridge_len, type, type2;
// Find a good bridgetype (the best money can buy)
bridge_len = GetBridgeLength(tile_a, tile_b);
type = type2 = 0;
for (bridge_type = MAX_BRIDGES-1; bridge_type >= 0; bridge_type--) {
if (CheckBridge_Stuff(bridge_type, bridge_len)) {
type2 = type;
type = bridge_type;
// We found two bridges, exit
if (type2 != 0) break;
}
}
// There is only one bridge that can be built
if (type2 == 0 && type != 0) type2 = type;
// Now, simply, build the bridge!
if (p->ainew.tbt == AI_TRAIN) {
return AI_DoCommand(tile_a, tile_b, (0x00 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
} else {
return AI_DoCommand(tile_a, tile_b, (0x80 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
}
}
// Build the route part by part
// Basicly what this function do, is build that amount of parts of the route
// that go in the same direction. It sets 'part' to the last part of the route builded.
// The return value is the cost for the builded parts
//
// Params:
// PathFinderInfo : Pointer to the PathFinderInfo used for AiPathFinder
// part : Which part we need to build
//
// TODO: skip already builded road-pieces (e.g.: cityroad)
int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte flag)
{
int part = PathFinderInfo->position;
byte *route_extra = PathFinderInfo->route_extra;
TileIndex *route = PathFinderInfo->route;
int dir;
int old_dir = -1;
int cost = 0;
int res;
// We need to calculate the direction with the parent of the parent.. so we skip
// the first pieces and the last piece
if (part < 1) part = 1;
// When we are done, stop it
if (part >= PathFinderInfo->route_length - 1) {
PathFinderInfo->position = -2;
return 0;
}
if (PathFinderInfo->rail_or_road) {
// Tunnel code
if ((AI_PATHFINDER_FLAG_TUNNEL & route_extra[part]) != 0) {
cost += AI_DoCommand(route[part], 0, 0, flag, CMD_BUILD_TUNNEL);
PathFinderInfo->position++;
// TODO: problems!
if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be built!");
return 0;
}
return cost;
}
// Bridge code
if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
cost += AiNew_Build_Bridge(p, route[part], route[part-1], flag);
PathFinderInfo->position++;
// TODO: problems!
if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be built!");
return 0;
}
return cost;
}
// Build normal rail
// Keep it doing till we go an other way
if (route_extra[part - 1] == 0 && route_extra[part] == 0) {
while (route_extra[part] == 0) {
// Get the current direction
dir = AiNew_GetRailDirection(route[part-1], route[part], route[part+1]);
// Is it the same as the last one?
if (old_dir != -1 && old_dir != dir) break;
old_dir = dir;
// Build the tile
res = AI_DoCommand(route[part], 0, dir, flag, CMD_BUILD_SINGLE_RAIL);
if (CmdFailed(res)) {
// Problem.. let's just abort it all!
p->ainew.state = AI_STATE_NOTHING;
return 0;
}
cost += res;
// Go to the next tile
part++;
// Check if it is still in range..
if (part >= PathFinderInfo->route_length - 1) break;
}
part--;
}
// We want to return the last position, so we go back one
PathFinderInfo->position = part;
} else {
// Tunnel code
if ((AI_PATHFINDER_FLAG_TUNNEL & route_extra[part]) != 0) {
cost += AI_DoCommand(route[part], 0x200, 0, flag, CMD_BUILD_TUNNEL);
PathFinderInfo->position++;
// TODO: problems!
if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be built!");
return 0;
}
return cost;
}
// Bridge code
if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
cost += AiNew_Build_Bridge(p, route[part], route[part+1], flag);
PathFinderInfo->position++;
// TODO: problems!
if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be built!");
return 0;
}
return cost;
}
// Build normal road
// Keep it doing till we go an other way
// EnsureNoVehicle makes sure we don't build on a tile where a vehicle is. This way
// it will wait till the vehicle is gone..
if (route_extra[part-1] == 0 && route_extra[part] == 0 && (flag != DC_EXEC || EnsureNoVehicle(route[part]))) {
while (route_extra[part] == 0 && (flag != DC_EXEC || EnsureNoVehicle(route[part]))) {
// Get the current direction
dir = AiNew_GetRoadDirection(route[part-1], route[part], route[part+1]);
// Is it the same as the last one?
if (old_dir != -1 && old_dir != dir) break;
old_dir = dir;
// There is already some road, and it is a bridge.. don't build!!!
if (!IsTileType(route[part], MP_TUNNELBRIDGE)) {
// Build the tile
res = AI_DoCommand(route[part], dir, 0, flag | DC_NO_WATER, CMD_BUILD_ROAD);
// Currently, we ignore CMD_ERRORs!
if (CmdFailed(res) && flag == DC_EXEC && !IsTileType(route[part], MP_STREET) && !EnsureNoVehicle(route[part])) {
// Problem.. let's just abort it all!
DEBUG(ai,0)("Darn, the route could not be built.. aborting!");
p->ainew.state = AI_STATE_NOTHING;
return 0;
}
if (!CmdFailed(res)) cost += res;
}
// Go to the next tile
part++;
// Check if it is still in range..
if (part >= PathFinderInfo->route_length - 1) break;
}
part--;
// We want to return the last position, so we go back one
}
if (!EnsureNoVehicle(route[part]) && flag == DC_EXEC) part--;
PathFinderInfo->position = part;
}
return cost;
}
// This functions tries to find the best vehicle for this type of cargo
// It returns INVALID_ENGINE if not suitable engine is found
EngineID AiNew_PickVehicle(Player *p)
{
if (p->ainew.tbt == AI_TRAIN) {
// Not supported yet
return INVALID_ENGINE;
} else {
EngineID best_veh_index = INVALID_ENGINE;
int32 best_veh_rating = 0;
EngineID start = ROAD_ENGINES_INDEX;
EngineID end = ROAD_ENGINES_INDEX + NUM_ROAD_ENGINES;
EngineID i;
/* Loop through all road vehicles */
for (i = start; i != end; i++) {
const RoadVehicleInfo *rvi = RoadVehInfo(i);
const Engine* e = GetEngine(i);
int32 rating;
int32 ret;
/* Skip vehicles which can't take our cargo type */
if (rvi->cargo_type != p->ainew.cargo && !CanRefitTo(i, p->ainew.cargo)) continue;
// Is it availiable?
// Also, check if the reliability of the vehicle is above the AI_VEHICLE_MIN_RELIABILTY
if (!HASBIT(e->player_avail, _current_player) || e->reliability * 100 < AI_VEHICLE_MIN_RELIABILTY << 16) continue;
/* Rate and compare the engine by speed & capacity */
rating = rvi->max_speed * rvi->capacity;
if (rating <= best_veh_rating) continue;
// Can we build it?
ret = AI_DoCommand(0, i, 0, DC_QUERY_COST, CMD_BUILD_ROAD_VEH);
if (CmdFailed(ret)) continue;
best_veh_rating = rating;
best_veh_index = i;
}
return best_veh_index;
}
}
void CcAI(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
Player* p = GetPlayer(_current_player);
if (success) {
p->ainew.state = AI_STATE_GIVE_ORDERS;
p->ainew.veh_id = _new_vehicle_id;
if (GetVehicle(p->ainew.veh_id)->cargo_type != p->ainew.cargo) {
/* Cargo type doesn't match, so refit it */
if (CmdFailed(DoCommand(tile, p->ainew.veh_id, p->ainew.cargo, DC_EXEC, CMD_REFIT_ROAD_VEH))) {
/* Refit failed, so sell the vehicle */
DoCommand(tile, p->ainew.veh_id, 0, DC_EXEC, CMD_SELL_ROAD_VEH);
p->ainew.state = AI_STATE_NOTHING;
}
}
} else {
/* XXX this should be handled more gracefully */
p->ainew.state = AI_STATE_NOTHING;
}
}
// Builds the best vehicle possible
int AiNew_Build_Vehicle(Player *p, TileIndex tile, byte flag)
{
EngineID i = AiNew_PickVehicle(p);
if (i == INVALID_ENGINE) return CMD_ERROR;
if (p->ainew.tbt == AI_TRAIN) return CMD_ERROR;
if (flag & DC_EXEC) {
return AI_DoCommandCc(tile, i, 0, flag, CMD_BUILD_ROAD_VEH, CcAI);
} else {
return AI_DoCommand(tile, i, 0, flag, CMD_BUILD_ROAD_VEH);
}
}
int AiNew_Build_Depot(Player* p, TileIndex tile, DiagDirection direction, byte flag)
{
int ret, ret2;
if (p->ainew.tbt == AI_TRAIN) {
return AI_DoCommand(tile, 0, direction, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_TRAIN_DEPOT);
} else {
ret = AI_DoCommand(tile, direction, 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_DEPOT);
if (CmdFailed(ret)) return ret;
// Try to build the road from the depot
ret2 = AI_DoCommand(tile + TileOffsByDiagDir(direction), DiagDirToRoadBits(ReverseDiagDir(direction)), 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD);
// If it fails, ignore it..
if (CmdFailed(ret2)) return ret;
return ret + ret2;
}
}

View File

@@ -1,118 +0,0 @@
/* $Id$ */
#include "../../stdafx.h"
#include "../../openttd.h"
#include "../../debug.h"
#include "../../map.h"
#include "trolly.h"
#include "../../vehicle.h"
int AiNew_GetRailDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c)
{
// 0 = vert
// 1 = horz
// 2 = dig up-left
// 3 = dig down-right
// 4 = dig down-left
// 5 = dig up-right
uint x1 = TileX(tile_a);
uint x2 = TileX(tile_b);
uint x3 = TileX(tile_c);
uint y1 = TileY(tile_a);
uint y2 = TileY(tile_b);
uint y3 = TileY(tile_c);
if (y1 == y2 && y2 == y3) return 0;
if (x1 == x2 && x2 == x3) return 1;
if (y2 > y1) return x2 > x3 ? 2 : 4;
if (x2 > x1) return y2 > y3 ? 2 : 5;
if (y1 > y2) return x2 > x3 ? 5 : 3;
if (x1 > x2) return y2 > y3 ? 4 : 3;
return 0;
}
int AiNew_GetRoadDirection(TileIndex tile_a, TileIndex tile_b, TileIndex tile_c)
{
int x1, x2, x3;
int y1, y2, y3;
int r;
x1 = TileX(tile_a);
x2 = TileX(tile_b);
x3 = TileX(tile_c);
y1 = TileY(tile_a);
y2 = TileY(tile_b);
y3 = TileY(tile_c);
r = 0;
if (x1 < x2) r += 8;
if (y1 < y2) r += 1;
if (x1 > x2) r += 2;
if (y1 > y2) r += 4;
if (x2 < x3) r += 2;
if (y2 < y3) r += 4;
if (x2 > x3) r += 8;
if (y2 > y3) r += 1;
return r;
}
// Get's the direction between 2 tiles seen from tile_a
DiagDirection AiNew_GetDirection(TileIndex tile_a, TileIndex tile_b)
{
if (TileY(tile_a) < TileY(tile_b)) return DIAGDIR_SE;
if (TileY(tile_a) > TileY(tile_b)) return DIAGDIR_NW;
if (TileX(tile_a) < TileX(tile_b)) return DIAGDIR_SW;
return DIAGDIR_NE;
}
// This functions looks up if this vehicle is special for this AI
// and returns his flag
uint AiNew_GetSpecialVehicleFlag(Player* p, Vehicle* v)
{
uint i;
for (i = 0; i < AI_MAX_SPECIAL_VEHICLES; i++) {
if (p->ainew.special_vehicles[i].veh_id == v->index) {
return p->ainew.special_vehicles[i].flag;
}
}
// Not found :(
return 0;
}
bool AiNew_SetSpecialVehicleFlag(Player* p, Vehicle* v, uint flag)
{
int new_id = -1;
uint i;
for (i = 0; i < AI_MAX_SPECIAL_VEHICLES; i++) {
if (p->ainew.special_vehicles[i].veh_id == v->index) {
p->ainew.special_vehicles[i].flag |= flag;
return true;
}
if (new_id == -1 &&
p->ainew.special_vehicles[i].veh_id == 0 &&
p->ainew.special_vehicles[i].flag == 0) {
new_id = i;
}
}
// Out of special_vehicle spots :s
if (new_id == -1) {
DEBUG(ai, 1)("special_vehicles list is too small :(");
return false;
}
p->ainew.special_vehicles[new_id].veh_id = v->index;
p->ainew.special_vehicles[new_id].flag = flag;
return true;
}

File diff suppressed because it is too large Load Diff

260
ai_build.c Normal file
View File

@@ -0,0 +1,260 @@
#include "stdafx.h"
#include "ttd.h"
#include "debug.h"
#include "map.h"
#include "tile.h"
#include "command.h"
#include "ai.h"
#include "engine.h"
#include "station.h"
// Build HQ
// Params:
// tile : tile where HQ is going to be build
bool AiNew_Build_CompanyHQ(Player *p, uint tile) {
if (CmdFailed(DoCommandByTile(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ)))
return false;
DoCommandByTile(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ);
return true;
}
// Build station
// Params:
// type : AI_TRAIN/AI_BUS/AI_TRUCK : indicates the type of station
// tile : tile where station is going to be build
// length : in case of AI_TRAIN: length of station
// numtracks : in case of AI_TRAIN: tracks of station
// direction : the direction of the station
// flag : flag passed to DoCommand (normally 0 to get the cost or DC_EXEC to build it)
int AiNew_Build_Station(Player *p, byte type, uint tile, byte length, byte numtracks, byte direction, byte flag) {
if (type == AI_TRAIN)
return DoCommandByTile(tile, direction + (numtracks << 8) + (length << 16), 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_RAILROAD_STATION);
if (type == AI_BUS)
return DoCommandByTile(tile, direction, RS_BUS, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_STOP);
return DoCommandByTile(tile, direction, RS_TRUCK, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_STOP);
}
// Builds a brdige. The second best out of the ones available for this player
// Params:
// tile_a : starting point
// tile_b : end point
// flag : flag passed to DoCommand
int AiNew_Build_Bridge(Player *p, uint tile_a, uint tile_b, byte flag) {
int bridge_type, bridge_len, type, type2;
// Find a good bridgetype (the best money can buy)
bridge_len = GetBridgeLength(tile_a, tile_b);
type = type2 = 0;
for (bridge_type = MAX_BRIDGES-1; bridge_type >= 0; bridge_type--) {
if (CheckBridge_Stuff(bridge_type, bridge_len)) {
type2 = type;
type = bridge_type;
// We found two bridges, exit
if (type2 != 0)
break;
}
}
// There is only one bridge that can be build..
if (type2 == 0 && type != 0) type2 = type;
// Now, simply, build the bridge!
if (p->ainew.tbt == AI_TRAIN)
return DoCommandByTile(tile_a, tile_b, (0<<8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
return DoCommandByTile(tile_a, tile_b, (0x80 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
}
// Build the route part by part
// Basicly what this function do, is build that amount of parts of the route
// that go in the same direction. It sets 'part' to the last part of the route builded.
// The return value is the cost for the builded parts
//
// Params:
// PathFinderInfo : Pointer to the PathFinderInfo used for AiPathFinder
// part : Which part we need to build
//
// TODO: skip already builded road-pieces (e.g.: cityroad)
int AiNew_Build_RoutePart(Player *p, Ai_PathFinderInfo *PathFinderInfo, byte flag) {
int part = PathFinderInfo->position;
byte *route_extra = PathFinderInfo->route_extra;
TileIndex *route = PathFinderInfo->route;
int dir;
int old_dir = -1;
int cost = 0;
int res;
// We need to calculate the direction with the parent of the parent.. so we skip
// the first pieces and the last piece
if (part < 1) part = 1;
// When we are done, stop it
if (part >= PathFinderInfo->route_length - 1) { PathFinderInfo->position = -2; return 0; }
if (PathFinderInfo->rail_or_road) {
// Tunnel code
if ((AI_PATHFINDER_FLAG_TUNNEL & route_extra[part]) != 0) {
cost += DoCommandByTile(route[part], 0, 0, flag, CMD_BUILD_TUNNEL);
PathFinderInfo->position++;
// TODO: problems!
if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be build!");
return 0;
}
return cost;
}
// Bridge code
if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
cost += AiNew_Build_Bridge(p, route[part], route[part-1], flag);
PathFinderInfo->position++;
// TODO: problems!
if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be build!");
return 0;
}
return cost;
}
// Build normal rail
// Keep it doing till we go an other way
if (route_extra[part-1] == 0 && route_extra[part] == 0) {
while (route_extra[part] == 0) {
// Get the current direction
dir = AiNew_GetRailDirection(route[part-1], route[part], route[part+1]);
// Is it the same as the last one?
if (old_dir != -1 && old_dir != dir) break;
old_dir = dir;
// Build the tile
res = DoCommandByTile(route[part], 0, dir, flag, CMD_BUILD_SINGLE_RAIL);
if (CmdFailed(res)) {
// Problem.. let's just abort it all!
p->ainew.state = AI_STATE_NOTHING;
return 0;
}
cost += res;
// Go to the next tile
part++;
// Check if it is still in range..
if (part >= PathFinderInfo->route_length - 1) break;
}
part--;
}
// We want to return the last position, so we go back one
PathFinderInfo->position = part;
} else {
// Tunnel code
if ((AI_PATHFINDER_FLAG_TUNNEL & route_extra[part]) != 0) {
cost += DoCommandByTile(route[part], 0x200, 0, flag, CMD_BUILD_TUNNEL);
PathFinderInfo->position++;
// TODO: problems!
if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be build!");
return 0;
}
return cost;
}
// Bridge code
if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
cost += AiNew_Build_Bridge(p, route[part], route[part+1], flag);
PathFinderInfo->position++;
// TODO: problems!
if (CmdFailed(cost)) {
DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be build!");
return 0;
}
return cost;
}
// Build normal road
// Keep it doing till we go an other way
// EnsureNoVehicle makes sure we don't build on a tile where a vehicle is. This way
// it will wait till the vehicle is gone..
if (route_extra[part-1] == 0 && route_extra[part] == 0 && (flag != DC_EXEC || EnsureNoVehicle(route[part]))) {
while (route_extra[part] == 0 && (flag != DC_EXEC || EnsureNoVehicle(route[part]))) {
// Get the current direction
dir = AiNew_GetRoadDirection(route[part-1], route[part], route[part+1]);
// Is it the same as the last one?
if (old_dir != -1 && old_dir != dir) break;
old_dir = dir;
// There is already some road, and it is a bridge.. don't build!!!
if (!IsTileType(route[part], MP_TUNNELBRIDGE)) {
// Build the tile
res = DoCommandByTile(route[part], dir, 0, flag | DC_NO_WATER, CMD_BUILD_ROAD);
// Currently, we ignore CMD_ERRORs!
if (CmdFailed(res) && flag == DC_EXEC && !IsTileType(route[part], MP_STREET) && !EnsureNoVehicle(route[part])) {
// Problem.. let's just abort it all!
DEBUG(ai,0)("Darn, the route could not be builded.. aborting!");
p->ainew.state = AI_STATE_NOTHING;
return 0;
}
if (!CmdFailed(res)) cost += res;
}
// Go to the next tile
part++;
// Check if it is still in range..
if (part >= PathFinderInfo->route_length - 1) break;
}
part--;
// We want to return the last position, so we go back one
}
if (!EnsureNoVehicle(route[part]) && flag == DC_EXEC) part--;
PathFinderInfo->position = part;
}
return cost;
}
// This functions tries to find the best vehicle for this type of cargo
// It returns vehicle_id or -1 if not found
int AiNew_PickVehicle(Player *p) {
if (p->ainew.tbt == AI_TRAIN) {
// Not supported yet
return -1;
} else {
int start, count, i, ret = CMD_ERROR;
start = _cargoc.ai_roadveh_start[p->ainew.cargo];
count = _cargoc.ai_roadveh_count[p->ainew.cargo];
// Let's check it backwards.. we simply want to best engine available..
for (i=start+count-1;i>=start;i--) {
// Is it availiable?
// Also, check if the reliability of the vehicle is above the AI_VEHICLE_MIN_RELIABILTY
if (!HASBIT(_engines[i].player_avail, _current_player) || _engines[i].reliability * 100 < AI_VEHICLE_MIN_RELIABILTY << 16) continue;
// Can we build it?
ret = DoCommandByTile(0, i, 0, DC_QUERY_COST, CMD_BUILD_ROAD_VEH);
if (!CmdFailed(ret)) break;
}
// We did not find a vehicle :(
if (CmdFailed(ret)) { return -1; }
return i;
}
}
// Builds the best vehicle possible
int AiNew_Build_Vehicle(Player *p, uint tile, byte flag) {
int i = AiNew_PickVehicle(p);
if (i == -1) return CMD_ERROR;
if (p->ainew.tbt == AI_TRAIN)
return CMD_ERROR;
return DoCommandByTile(tile, i, 0, flag, CMD_BUILD_ROAD_VEH);
}
int AiNew_Build_Depot(Player *p, uint tile, byte direction, byte flag)
{
static const byte _roadbits_by_dir[4] = {2,1,8,4};
int ret, ret2;
if (p->ainew.tbt == AI_TRAIN)
return DoCommandByTile(tile, 0, direction, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_TRAIN_DEPOT);
ret = DoCommandByTile(tile, direction, 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD_DEPOT);
if (CmdFailed(ret)) return ret;
// Try to build the road from the depot
ret2 = DoCommandByTile(tile + TileOffsByDir(direction), _roadbits_by_dir[direction], 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD);
// If it fails, ignore it..
if (CmdFailed(ret2)) return ret;
return ret + ret2;
}

1322
ai_new.c Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,26 +1,19 @@
/* $Id$ */
#include "../../stdafx.h"
#include "../../openttd.h"
#include "../../bridge_map.h"
#include "../../debug.h"
#include "../../functions.h"
#include "../../map.h"
#include "../../tile.h"
#include "../../command.h"
#include "trolly.h"
#include "../../depot.h"
#include "../../tunnel_map.h"
#include "../../bridge.h"
#include "../ai.h"
#include "stdafx.h"
#include "ttd.h"
#include "debug.h"
#include "map.h"
#include "tile.h"
#include "command.h"
#include "ai.h"
#include "depot.h"
#define TEST_STATION_NO_DIR 0xFF
// Tests if a station can be build on the given spot
// TODO: make it train compatible
static bool TestCanBuildStationHere(TileIndex tile, byte dir)
static bool TestCanBuildStationHere(uint tile, byte dir)
{
Player *p = GetPlayer(_current_player);
Player *p = DEREF_PLAYER(_current_player);
if (dir == TEST_STATION_NO_DIR) {
int32 ret;
@@ -44,8 +37,10 @@ static bool IsRoad(TileIndex tile)
// MP_STREET, but not a road depot?
(IsTileType(tile, MP_STREET) && !IsTileDepotType(tile, TRANSPORT_ROAD)) ||
(IsTileType(tile, MP_TUNNELBRIDGE) && (
(IsTunnel(tile) && GetTunnelTransportType(tile) == TRANSPORT_ROAD) ||
(IsBridge(tile) && GetBridgeTransportType(tile) == TRANSPORT_ROAD)
// road tunnel?
((_map5[tile] & 0x80) == 0 && (_map5[tile] & 0x4) == 0x4) ||
// road bridge?
((_map5[tile] & 0x80) != 0 && (_map5[tile] & 0x2) == 0x2)
));
}
@@ -53,12 +48,10 @@ static bool IsRoad(TileIndex tile)
// Checks if a tile 'a' is between the tiles 'b' and 'c'
#define TILES_BETWEEN(a, b, c) (TileX(a) >= TileX(b) && TileX(a) <= TileX(c) && TileY(a) >= TileY(b) && TileY(a) <= TileY(c))
// Check if the current tile is in our end-area
static int32 AyStar_AiPathFinder_EndNodeCheck(AyStar *aystar, OpenListNode *current)
{
const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target;
Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
// It is not allowed to have a station on the end of a bridge or tunnel ;)
if (current->path.node.user_data[0] != 0) return AYSTAR_DONE;
if (TILES_BETWEEN(current->path.node.tile, PathFinderInfo->end_tile_tl, PathFinderInfo->end_tile_br))
@@ -69,7 +62,6 @@ static int32 AyStar_AiPathFinder_EndNodeCheck(AyStar *aystar, OpenListNode *curr
return AYSTAR_DONE;
}
// Calculates the hash
// Currently it is a 10 bit hash, so the hash array has a max depth of 6 bits (so 64)
static uint AiPathFinder_Hash(uint key1, uint key2)
@@ -77,7 +69,6 @@ static uint AiPathFinder_Hash(uint key1, uint key2)
return (TileX(key1) & 0x1F) + ((TileY(key1) & 0x1F) << 5);
}
// Clear the memory of all the things
static void AyStar_AiPathFinder_Free(AyStar *aystar)
{
@@ -85,13 +76,11 @@ static void AyStar_AiPathFinder_Free(AyStar *aystar)
free(aystar);
}
static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current, OpenListNode *parent);
static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent);
static void AyStar_AiPathFinder_FoundEndNode(AyStar *aystar, OpenListNode *current);
static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *current);
// This creates the AiPathFinder
AyStar *new_AyStar_AiPathFinder(int max_tiles_around, Ai_PathFinderInfo *PathFinderInfo)
{
@@ -126,7 +115,7 @@ AyStar *new_AyStar_AiPathFinder(int max_tiles_around, Ai_PathFinderInfo *PathFin
// Now we add all the starting tiles
for (x = TileX(PathFinderInfo->start_tile_tl); x <= TileX(PathFinderInfo->start_tile_br); x++) {
for (y = TileY(PathFinderInfo->start_tile_tl); y <= TileY(PathFinderInfo->start_tile_br); y++) {
start_node.node.tile = TileXY(x, y);
start_node.node.tile = TILE_XY(x, y);
result->addstart(result, &start_node.node, 0);
}
}
@@ -134,7 +123,6 @@ AyStar *new_AyStar_AiPathFinder(int max_tiles_around, Ai_PathFinderInfo *PathFin
return result;
}
// To reuse AyStar we sometimes have to clean all the memory
void clean_AyStar_AiPathFinder(AyStar *aystar, Ai_PathFinderInfo *PathFinderInfo)
{
@@ -156,27 +144,23 @@ void clean_AyStar_AiPathFinder(AyStar *aystar, Ai_PathFinderInfo *PathFinderInfo
// Now we add all the starting tiles
for (x = TileX(PathFinderInfo->start_tile_tl); x <= TileX(PathFinderInfo->start_tile_br); x++) {
for (y = TileY(PathFinderInfo->start_tile_tl); y <= TileY(PathFinderInfo->start_tile_br); y++) {
TileIndex tile = TileXY(x, y);
if (!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) continue;
if (!TestCanBuildStationHere(tile, TEST_STATION_NO_DIR)) continue;
start_node.node.tile = tile;
if (!(IsTileType(TILE_XY(x, y), MP_CLEAR) || IsTileType(TILE_XY(x, y), MP_TREES))) continue;
if (!TestCanBuildStationHere(TILE_XY(x, y), TEST_STATION_NO_DIR)) continue;
start_node.node.tile = TILE_XY(x, y);
aystar->addstart(aystar, &start_node.node, 0);
}
}
}
// The h-value, simple calculation
static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
{
const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target;
Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
int r, r2;
if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION) {
// The station is pointing to a direction, add a tile towards that direction, so the H-value is more accurate
r = DistanceManhattan(current->tile, PathFinderInfo->end_tile_tl + TileOffsByDiagDir(PathFinderInfo->end_direction));
r2 = DistanceManhattan(current->tile, PathFinderInfo->end_tile_br + TileOffsByDiagDir(PathFinderInfo->end_direction));
r = DistanceManhattan(current->tile, PathFinderInfo->end_tile_tl + TileOffsByDir(PathFinderInfo->end_direction));
r2 = DistanceManhattan(current->tile, PathFinderInfo->end_tile_br + TileOffsByDir(PathFinderInfo->end_direction));
} else {
// No direction, so just get the fastest route to the station
r = DistanceManhattan(current->tile, PathFinderInfo->end_tile_tl);
@@ -187,7 +171,6 @@ static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current,
return r * AI_PATHFINDER_H_MULTIPLER;
}
// We found the end.. let's get the route back and put it in an array
static void AyStar_AiPathFinder_FoundEndNode(AyStar *aystar, OpenListNode *current)
{
@@ -210,7 +193,6 @@ static void AyStar_AiPathFinder_FoundEndNode(AyStar *aystar, OpenListNode *curre
DEBUG(ai, 1)("[Ai-PathFinding] Found route of %d nodes long in %d nodes of searching", i, Hash_Size(&aystar->ClosedListHash));
}
// What tiles are around us.
static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *current)
{
@@ -225,7 +207,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
// Go through all surrounding tiles and check if they are within the limits
for (i = 0; i < 4; i++) {
TileIndex ctile = current->path.node.tile; // Current tile
TileIndex atile = ctile + TileOffsByDiagDir(i); // Adjacent tile
TileIndex atile = ctile + TileOffsByDir(i); // Adjacent tile
if (TileX(atile) > 1 && TileX(atile) < MapMaxX() - 1 &&
TileY(atile) > 1 && TileY(atile) < MapMaxY() - 1) {
@@ -235,10 +217,12 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
// If the next step is a bridge, we have to enter it the right way
if (!PathFinderInfo->rail_or_road && IsRoad(atile)) {
if (IsTileType(atile, MP_TUNNELBRIDGE)) {
if (IsTunnel(atile)) {
if (GetTunnelDirection(atile) != i) continue;
} else {
if ((_m[atile].m5 & 1U) != DiagDirToAxis(i)) continue;
// An existing bridge... let's test the direction ;)
if ((_map5[atile] & 1U) != (i & 1)) continue;
// This problem only is valid for tunnels:
// When the last tile was not yet a tunnel, check if we enter from the right side..
if ((_map5[atile] & 0x80) == 0) {
if (i != (_map5[atile] & 3U)) continue;
}
}
}
@@ -246,7 +230,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
if (!PathFinderInfo->rail_or_road && IsRoad(ctile)) {
if (IsTileType(ctile, MP_TUNNELBRIDGE)) {
// An existing bridge/tunnel... let's test the direction ;)
if ((_m[ctile].m5 & 1U) != (i & 1)) continue;
if ((_map5[ctile] & 1U) != (i & 1)) continue;
}
}
@@ -272,7 +256,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
if (PathFinderInfo->rail_or_road) {
// Rail check
dir = AiNew_GetRailDirection(current->path.parent->node.tile, ctile, atile);
ret = AI_DoCommand(ctile, 0, dir, DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL);
ret = DoCommandByTile(ctile, 0, dir, DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL);
if (CmdFailed(ret)) continue;
#ifdef AI_PATHFINDER_NO_90DEGREES_TURN
if (current->path.parent->parent != NULL) {
@@ -292,9 +276,9 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
dir = 0;
} else {
// It already has road.. check if we miss any bits!
if ((_m[ctile].m5 & dir) != dir) {
if ((_map5[ctile] & dir) != dir) {
// We do miss some pieces :(
dir &= ~_m[ctile].m5;
dir &= ~_map5[ctile];
} else {
dir = 0;
}
@@ -302,7 +286,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
}
// Only destruct things if it is MP_CLEAR of MP_TREES
if (dir != 0) {
ret = AI_DoCommand(ctile, dir, 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD);
ret = DoCommandByTile(ctile, dir, 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD);
if (CmdFailed(ret)) continue;
}
}
@@ -317,20 +301,23 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
// Next step, check for bridges and tunnels
if (current->path.parent != NULL && current->path.node.user_data[0] == 0) {
TileInfo ti;
// First we get the dir from this tile and his parent
DiagDirection dir = AiNew_GetDirection(current->path.parent->node.tile, current->path.node.tile);
int dir = AiNew_GetDirection(current->path.parent->node.tile, current->path.node.tile);
// It means we can only walk with the track, so the bridge has to be in the same direction
TileIndex tile = current->path.node.tile;
TileIndex new_tile = tile;
Slope tileh = GetTileSlope(tile, NULL);
FindLandscapeHeightByTile(&ti, tile);
// Bridges can only be build on land that is not flat
// And if there is a road or rail blocking
if (tileh != SLOPE_FLAT ||
(PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDiagDir(dir), MP_STREET)) ||
(!PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDiagDir(dir), MP_RAILWAY))) {
if (ti.tileh != 0 ||
(PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDir(dir), MP_STREET)) ||
(!PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDir(dir), MP_RAILWAY))) {
for (;;) {
new_tile += TileOffsByDiagDir(dir);
new_tile += TileOffsByDir(dir);
// Precheck, is the length allowed?
if (!CheckBridge_Stuff(0, GetBridgeLength(tile, new_tile))) break;
@@ -339,7 +326,7 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
if (TILES_BETWEEN(new_tile, PathFinderInfo->end_tile_tl, PathFinderInfo->end_tile_br)) break;
// Try building the bridge..
ret = AI_DoCommand(tile, new_tile, (0 << 8) + (MAX_BRIDGES / 2), DC_AUTO, CMD_BUILD_BRIDGE);
ret = DoCommandByTile(tile, new_tile, (0 << 8) + (MAX_BRIDGES / 2), DC_AUTO, CMD_BUILD_BRIDGE);
if (CmdFailed(ret)) continue;
// We can build a bridge here.. add him to the neighbours
aystar->neighbours[aystar->num_neighbours].tile = new_tile;
@@ -351,16 +338,16 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
}
// Next, check for tunnels!
// Tunnels can only be built on slopes corresponding to the direction
// Tunnels can only be build with tileh of 3, 6, 9 or 12, depending on the direction
// For now, we check both sides for this tile.. terraforming gives fuzzy result
if ((dir == DIAGDIR_NE && tileh == SLOPE_NE) ||
(dir == DIAGDIR_SE && tileh == SLOPE_SE) ||
(dir == DIAGDIR_SW && tileh == SLOPE_SW) ||
(dir == DIAGDIR_NW && tileh == SLOPE_NW)) {
if ((dir == 0 && ti.tileh == 12) ||
(dir == 1 && ti.tileh == 6) ||
(dir == 2 && ti.tileh == 3) ||
(dir == 3 && ti.tileh == 9)) {
// Now simply check if a tunnel can be build
ret = AI_DoCommand(tile, (PathFinderInfo->rail_or_road?0:0x200), 0, DC_AUTO, CMD_BUILD_TUNNEL);
tileh = GetTileSlope(_build_tunnel_endtile, NULL);
if (!CmdFailed(ret) && (tileh == SLOPE_SW || tileh == SLOPE_SE || tileh == SLOPE_NW || tileh == SLOPE_NE)) {
ret = DoCommandByTile(tile, (PathFinderInfo->rail_or_road?0:0x200), 0, DC_AUTO, CMD_BUILD_TUNNEL);
FindLandscapeHeightByTile(&ti, _build_tunnel_endtile);
if (!CmdFailed(ret) && (ti.tileh == 3 || ti.tileh == 6 || ti.tileh == 9 || ti.tileh == 12)) {
aystar->neighbours[aystar->num_neighbours].tile = _build_tunnel_endtile;
aystar->neighbours[aystar->num_neighbours].user_data[0] = AI_PATHFINDER_FLAG_TUNNEL + (dir << 8);
aystar->neighbours[aystar->num_neighbours++].direction = 0;
@@ -369,10 +356,9 @@ static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *curr
}
}
extern uint GetRailFoundation(Slope tileh, TrackBits bits); // XXX function declaration in .c
extern uint GetRoadFoundation(Slope tileh, uint bits); // XXX function declaration in .c
extern uint GetBridgeFoundation(Slope tileh, Axis); // XXX function declaration in .c
extern uint GetRailFoundation(uint tileh, uint bits);
extern uint GetRoadFoundation(uint tileh, uint bits);
extern uint GetBridgeFoundation(uint tileh, byte direction);
enum {
BRIDGE_NO_FOUNDATION = 1 << 0 | 1 << 3 | 1 << 6 | 1 << 9 | 1 << 12,
};
@@ -382,16 +368,18 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current,
{
Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
int r, res = 0;
Slope tileh = GetTileSlope(current->tile, NULL);
Slope parent_tileh = GetTileSlope(parent->path.node.tile, NULL);
TileInfo ti, parent_ti;
// Gather some information about the tile..
FindLandscapeHeightByTile(&ti, current->tile);
FindLandscapeHeightByTile(&parent_ti, parent->path.node.tile);
// Check if we hit the end-tile
if (TILES_BETWEEN(current->tile, PathFinderInfo->end_tile_tl, PathFinderInfo->end_tile_br)) {
// We are at the end-tile, check if we had a direction or something...
if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION && AiNew_GetDirection(current->tile, parent->path.node.tile) != PathFinderInfo->end_direction) {
if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION && AiNew_GetDirection(current->tile, parent->path.node.tile) != PathFinderInfo->end_direction)
// We are not pointing the right way, invalid tile
return AYSTAR_INVALID_NODE;
}
// If it was valid, drop out.. we don't build on the endtile
return 0;
}
@@ -413,25 +401,24 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current,
// when there is a flat land all around, they are more expensive to build, and
// especially they essentially block the ability to connect or cross the road
// from one side.
if (parent_tileh != SLOPE_FLAT && parent->path.parent != NULL) {
if (parent_ti.tileh != 0 && parent->path.parent != NULL) {
// Skip if the tile was from a bridge or tunnel
if (parent->path.node.user_data[0] == 0 && current->user_data[0] == 0) {
if (PathFinderInfo->rail_or_road) {
r = GetRailFoundation(parent_tileh, 1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
r = GetRailFoundation(parent_ti.tileh, 1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
// Maybe is BRIDGE_NO_FOUNDATION a bit strange here, but it contains just the right information..
if (r >= 15 || (r == 0 && HASBIT(BRIDGE_NO_FOUNDATION, tileh))) {
if (r >= 15 || (r == 0 && (BRIDGE_NO_FOUNDATION & (1 << ti.tileh)))) {
res += AI_PATHFINDER_TILE_GOES_UP_PENALTY;
} else {
res += AI_PATHFINDER_FOUNDATION_PENALTY;
}
} else {
if (!IsRoad(parent->path.node.tile) || !IsTileType(parent->path.node.tile, MP_TUNNELBRIDGE)) {
r = GetRoadFoundation(parent_tileh, AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
if (r >= 15 || r == 0) {
if (!(IsRoad(parent->path.node.tile) && IsTileType(parent->path.node.tile, MP_TUNNELBRIDGE))) {
r = GetRoadFoundation(parent_ti.tileh, AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
if (r >= 15 || r == 0)
res += AI_PATHFINDER_TILE_GOES_UP_PENALTY;
} else {
else
res += AI_PATHFINDER_FOUNDATION_PENALTY;
}
}
}
}
@@ -451,19 +438,19 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current,
res += AI_PATHFINDER_BRIDGE_PENALTY * GetBridgeLength(current->tile, parent->path.node.tile);
// Check if we are going up or down, first for the starting point
// In user_data[0] is at the 8th bit the direction
if (!HASBIT(BRIDGE_NO_FOUNDATION, parent_tileh)) {
if (GetBridgeFoundation(parent_tileh, (current->user_data[0] >> 8) & 1) < 15) {
if (!(BRIDGE_NO_FOUNDATION & (1 << parent_ti.tileh))) {
if (GetBridgeFoundation(parent_ti.tileh, (current->user_data[0] >> 8) & 1) < 15)
res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
}
}
// Second for the end point
if (!HASBIT(BRIDGE_NO_FOUNDATION, tileh)) {
if (GetBridgeFoundation(tileh, (current->user_data[0] >> 8) & 1) < 15) {
if (!(BRIDGE_NO_FOUNDATION & (1 << ti.tileh))) {
if (GetBridgeFoundation(ti.tileh, (current->user_data[0] >> 8) & 1) < 15)
res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
}
}
if (parent_tileh == SLOPE_FLAT) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
if (tileh == SLOPE_FLAT) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
if (parent_ti.tileh == 0)
res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
if (ti.tileh == 0)
res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
}
// To prevent the AI from taking the fastest way in tiles, but not the fastest way
@@ -471,13 +458,12 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current,
// This way, we get almost the fastest way in tiles, and a very good speed on the track
if (!PathFinderInfo->rail_or_road) {
if (parent->path.parent != NULL &&
AiNew_GetDirection(current->tile, parent->path.node.tile) != AiNew_GetDirection(parent->path.node.tile, parent->path.parent->node.tile)) {
AiNew_GetDirection(current->tile, parent->path.node.tile) != AiNew_GetDirection(parent->path.node.tile, parent->path.parent->node.tile)) {
// When road exists, we don't like turning, but its free, so don't be to piggy about it
if (IsRoad(parent->path.node.tile)) {
if (IsRoad(parent->path.node.tile))
res += AI_PATHFINDER_DIRECTION_CHANGE_ON_EXISTING_ROAD_PENALTY;
} else {
else
res += AI_PATHFINDER_DIRECTION_CHANGE_PENALTY;
}
}
} else {
// For rail we have 1 exeption: diagonal rail..
@@ -486,7 +472,7 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current,
int dir1 = AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile);
int dir2 = AiNew_GetRailDirection(parent->path.parent->parent->node.tile, parent->path.parent->node.tile, parent->path.node.tile);
// First, see if we are on diagonal path, that is better than straight path
if (dir1 > 1) res -= AI_PATHFINDER_DIAGONAL_BONUS;
if (dir1 > 1) { res -= AI_PATHFINDER_DIAGONAL_BONUS; }
// First see if they are different
if (dir1 != dir2) {
@@ -506,5 +492,9 @@ static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current,
}
}
return (res < 0) ? 0 : res;
// Res should never be below zero.. if so, make it zero!
if (res < 0) { res = 0; }
// Return our value
return res;
}

119
ai_shared.c Normal file
View File

@@ -0,0 +1,119 @@
#include "stdafx.h"
#include "ttd.h"
#include "debug.h"
#include "map.h"
#include "ai.h"
#include "vehicle.h"
int AiNew_GetRailDirection(uint tile_a, uint tile_b, uint tile_c) {
// 0 = vert
// 1 = horz
// 2 = dig up-left
// 3 = dig down-right
// 4 = dig down-left
// 5 = dig up-right
int x1, x2, x3;
int y1, y2, y3;
x1 = TileX(tile_a);
x2 = TileX(tile_b);
x3 = TileX(tile_c);
y1 = TileY(tile_a);
y2 = TileY(tile_b);
y3 = TileY(tile_c);
if (y1 == y2 && y2 == y3) return 0;
if (x1 == x2 && x2 == x3) return 1;
if (y2 > y1) {
if (x2 > x3) return 2;
else return 4;
}
if (x2 > x1) {
if (y2 > y3) return 2;
else return 5;
}
if (y1 > y2) {
if (x2 > x3) return 5;
else return 3;
}
if (x1 > x2) {
if (y2 > y3) return 4;
else return 3;
}
return 0;
}
int AiNew_GetRoadDirection(uint tile_a, uint tile_b, uint tile_c) {
int x1, x2, x3;
int y1, y2, y3;
int r;
x1 = TileX(tile_a);
x2 = TileX(tile_b);
x3 = TileX(tile_c);
y1 = TileY(tile_a);
y2 = TileY(tile_b);
y3 = TileY(tile_c);
r = 0;
if (x1 < x2) r += 8;
if (y1 < y2) r += 1;
if (x1 > x2) r += 2;
if (y1 > y2) r += 4;
if (x2 < x3) r += 2;
if (y2 < y3) r += 4;
if (x2 > x3) r += 8;
if (y2 > y3) r += 1;
return r;
}
// Get's the direction between 2 tiles seen from tile_a
int AiNew_GetDirection(uint tile_a, uint tile_b) {
if (TileY(tile_a) < TileY(tile_b)) return 1;
if (TileY(tile_a) > TileY(tile_b)) return 3;
if (TileX(tile_a) < TileX(tile_b)) return 2;
return 0;
}
// This functions looks up if this vehicle is special for this AI
// and returns his flag
uint AiNew_GetSpecialVehicleFlag(Player *p, Vehicle *v) {
int i;
for (i=0;i<AI_MAX_SPECIAL_VEHICLES;i++) {
if (p->ainew.special_vehicles[i].veh_id == v->index) {
return p->ainew.special_vehicles[i].flag;
}
}
// Not found :(
return 0;
}
bool AiNew_SetSpecialVehicleFlag(Player *p, Vehicle *v, uint flag) {
int i, new_id = -1;
for (i=0;i<AI_MAX_SPECIAL_VEHICLES;i++) {
if (p->ainew.special_vehicles[i].veh_id == v->index) {
p->ainew.special_vehicles[i].flag |= flag;
return true;
}
if (new_id == -1 && p->ainew.special_vehicles[i].veh_id == 0 &&
p->ainew.special_vehicles[i].flag == 0)
new_id = i;
}
// Out of special_vehicle spots :s
if (new_id == -1) {
DEBUG(ai, 1)("special_vehicles list is too small :(");
return false;
}
p->ainew.special_vehicles[new_id].veh_id = v->index;
p->ainew.special_vehicles[new_id].flag = flag;
return true;
}

View File

@@ -1,26 +0,0 @@
/* $Id$ */
#ifndef AIRCRAFT_H
#define AIRCRAFT_H
#include "station_map.h"
#include "vehicle.h"
static inline bool IsAircraftInHangar(const Vehicle* v)
{
assert(v->type == VEH_Aircraft);
return v->vehstatus & VS_HIDDEN && IsHangarTile(v->tile);
}
static inline bool IsAircraftInHangarStopped(const Vehicle* v)
{
return IsAircraftInHangar(v) && v->vehstatus & VS_STOPPED;
}
uint16 AircraftDefaultCargoCapacity(CargoID cid, EngineID engine_type);
void CcCloneAircraft(bool success, TileIndex tile, uint32 p1, uint32 p2);
void HandleAircraftEnterHangar(Vehicle *v);
#endif /* AIRCRAFT_H */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

500
airport.c
View File

@@ -1,50 +1,27 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "debug.h"
#include "map.h"
#include "airport.h"
#include "macros.h"
#include "variables.h"
#include "airport_movement.h"
#include "date.h"
/* Uncomment this to print out a full report of the airport-structure
* You should either use
* - true: full-report, print out every state and choice with string-names
* OR
* - false: give a summarized report which only shows current and next position */
//#define DEBUG_AIRPORT false
AirportFTAClass *CountryAirport;
AirportFTAClass *CityAirport;
AirportFTAClass *Heliport, *Oilrig;
AirportFTAClass *MetropolitanAirport;
AirportFTAClass *InternationalAirport;
static AirportFTAClass *CountryAirport;
static AirportFTAClass *CityAirport;
static AirportFTAClass *Oilrig;
static AirportFTAClass *Heliport;
static AirportFTAClass *MetropolitanAirport;
static AirportFTAClass *InternationalAirport;
static AirportFTAClass *CommuterAirport;
static AirportFTAClass *HeliDepot;
static AirportFTAClass *IntercontinentalAirport;
static AirportFTAClass *HeliStation;
static void AirportFTAClass_Constructor(AirportFTAClass *Airport,
const byte *terminals, const byte *helipads,
const byte entry_point, const byte acc_planes,
const AirportFTAbuildup *FA,
const TileIndexDiffC *depots, const byte nof_depots);
static void AirportFTAClass_Destructor(AirportFTAClass *Airport);
static void AirportFTAClass_Constructor(AirportFTAClass *apc,
const byte *terminals, const byte *helipads,
const byte entry_point, const byte acc_planes,
const AirportFTAbuildup *apFA,
const TileIndexDiffC *depots, const byte nof_depots,
uint size_x, uint size_y
);
static void AirportFTAClass_Destructor(AirportFTAClass *apc);
static uint16 AirportGetNofElements(const AirportFTAbuildup *apFA);
static void AirportBuildAutomata(AirportFTAClass *apc, const AirportFTAbuildup *apFA);
static byte AirportGetTerminalCount(const byte *terminals, byte *groups);
static byte AirportTestFTA(const AirportFTAClass *apc);
#ifdef DEBUG_AIRPORT
static void AirportPrintOut(const AirportFTAClass *apc, bool full_report);
#endif /* DEBUG_AIRPORT */
static uint16 AirportGetNofElements(const AirportFTAbuildup *FA);
static void AirportBuildAutomata(AirportFTAClass *Airport, const AirportFTAbuildup *FA);
static byte AirportTestFTA(const AirportFTAClass *Airport);
/*static void AirportPrintOut(const AirportFTAClass *Airport, const bool full_report);
static byte AirportBlockToString(uint32 block);*/
void InitializeAirports(void)
{
@@ -59,8 +36,7 @@ void InitializeAirports(void)
ALL,
_airport_fta_country,
_airport_depots_country,
lengthof(_airport_depots_country),
4, 3
lengthof(_airport_depots_country)
);
// city airport
@@ -74,8 +50,7 @@ void InitializeAirports(void)
ALL,
_airport_fta_city,
_airport_depots_city,
lengthof(_airport_depots_city),
6, 6
lengthof(_airport_depots_city)
);
// metropolitan airport
@@ -89,8 +64,7 @@ void InitializeAirports(void)
ALL,
_airport_fta_metropolitan,
_airport_depots_metropolitan,
lengthof(_airport_depots_metropolitan),
6, 6
lengthof(_airport_depots_metropolitan)
);
// international airport
@@ -104,23 +78,7 @@ void InitializeAirports(void)
ALL,
_airport_fta_international,
_airport_depots_international,
lengthof(_airport_depots_international),
7, 7
);
// intercontintental airport
IntercontinentalAirport = (AirportFTAClass *)malloc(sizeof(AirportFTAClass));
AirportFTAClass_Constructor(
IntercontinentalAirport,
_airport_terminal_intercontinental,
_airport_helipad_intercontinental,
43,
ALL,
_airport_fta_intercontinental,
_airport_depots_intercontinental,
lengthof(_airport_depots_intercontinental),
9,11
lengthof(_airport_depots_international)
);
// heliport, oilrig
@@ -134,57 +92,10 @@ void InitializeAirports(void)
HELICOPTERS_ONLY,
_airport_fta_heliport_oilrig,
NULL,
0,
1, 1
0
);
Oilrig = Heliport; // exactly the same structure for heliport/oilrig, so share state machine
// commuter airport
CommuterAirport = malloc(sizeof(AirportFTAClass));
AirportFTAClass_Constructor(
CommuterAirport,
_airport_terminal_commuter,
_airport_helipad_commuter,
22,
ALL,
_airport_fta_commuter,
_airport_depots_commuter,
lengthof(_airport_depots_commuter),
5,4
);
// helidepot airport
HeliDepot = malloc(sizeof(AirportFTAClass));
AirportFTAClass_Constructor(
HeliDepot,
NULL,
_airport_helipad_helidepot,
4,
HELICOPTERS_ONLY,
_airport_fta_helidepot,
_airport_depots_helidepot,
lengthof(_airport_depots_helidepot),
2,2
);
// helistation airport
HeliStation = malloc(sizeof(AirportFTAClass));
AirportFTAClass_Constructor(
HeliStation,
NULL,
_airport_helipad_helistation,
25,
HELICOPTERS_ONLY,
_airport_fta_helistation,
_airport_depots_helistation,
lengthof(_airport_depots_helistation),
4,2
);
}
void UnInitializeAirports(void)
@@ -194,200 +105,177 @@ void UnInitializeAirports(void)
AirportFTAClass_Destructor(Heliport);
AirportFTAClass_Destructor(MetropolitanAirport);
AirportFTAClass_Destructor(InternationalAirport);
AirportFTAClass_Destructor(CommuterAirport);
AirportFTAClass_Destructor(HeliDepot);
AirportFTAClass_Destructor(IntercontinentalAirport);
AirportFTAClass_Destructor(HeliStation);
}
static void AirportFTAClass_Constructor(AirportFTAClass *apc,
const byte *terminals, const byte *helipads,
const byte entry_point, const byte acc_planes,
const AirportFTAbuildup *apFA,
const TileIndexDiffC *depots, const byte nof_depots,
uint size_x, uint size_y
)
static void AirportFTAClass_Constructor(AirportFTAClass *Airport,
const byte *terminals, const byte *helipads,
const byte entry_point, const byte acc_planes,
const AirportFTAbuildup *FA,
const TileIndexDiffC *depots, const byte nof_depots)
{
byte nofterminals, nofhelipads;
byte nofterminalgroups, nofhelipadgroups;
byte nofterminalgroups = 0;
byte nofhelipadgroups = 0;
const byte * curr;
int i;
nofterminals = nofhelipads = 0;
apc->size_x = size_x;
apc->size_y = size_y;
//now we read the number of terminals we have
if (terminals != NULL) {
i = terminals[0];
nofterminalgroups = i;
curr = terminals;
while (i-- > 0) {
curr++;
assert(*curr != 0); //we don't want to have an empty group
nofterminals += *curr;
}
/* Set up the terminal and helipad count for an airport.
* TODO: If there are more than 10 terminals or 4 helipads, internal variables
* need to be changed, so don't allow that for now */
nofterminals = AirportGetTerminalCount(terminals, &nofterminalgroups);
if (nofterminals > MAX_TERMINALS) {
DEBUG(misc, 0) ("[Ap] Currently only maximum of %d terminals are supported (you wanted %d)", MAX_TERMINALS, nofterminals);
assert(nofterminals <= MAX_TERMINALS);
}
apc->terminals = terminals;
Airport->terminals = terminals;
//read helipads
if (helipads != NULL) {
i = helipads[0];
nofhelipadgroups = i;
curr = helipads;
while (i-- > 0) {
curr++;
assert(*curr != 0); //no empty groups please
nofhelipads += *curr;
}
nofhelipads = AirportGetTerminalCount(helipads, &nofhelipadgroups);
if (nofhelipads > MAX_HELIPADS) {
DEBUG(misc, 0) ("[Ap] Currently only maximum of %d helipads are supported (you wanted %d)", MAX_HELIPADS, nofhelipads);
assert(nofhelipads <= MAX_HELIPADS);
}
apc->helipads = helipads;
Airport->helipads = helipads;
/* Get the number of elements from the source table. We also double check this
* with the entry point which must be within bounds and use this information
* later on to build and validate the state machine */
apc->nofelements = AirportGetNofElements(apFA);
if (entry_point >= apc->nofelements) {
DEBUG(misc, 0) ("[Ap] Entry (%d) must be within the airport (maximum %d)", entry_point, apc->nofelements);
assert(entry_point < apc->nofelements);
// if there are more terminals than 6, internal variables have to be changed, so don't allow that
// same goes for helipads
if (nofterminals > MAX_TERMINALS) { printf("Currently only maximum of %2d terminals are supported (you wanted %2d)\n", MAX_TERMINALS, nofterminals);}
if (nofhelipads > MAX_HELIPADS) { printf("Currently only maximum of %2d helipads are supported (you wanted %2d)\n", MAX_HELIPADS, nofhelipads);}
// terminals/helipads are divided into groups. Groups are computed by dividing the number
// of terminals by the number of groups. Half in half. If #terminals is uneven, first group
// will get the less # of terminals
assert(nofterminals <= MAX_TERMINALS);
assert(nofhelipads <= MAX_HELIPADS);
Airport->nofelements = AirportGetNofElements(FA);
// check
if (entry_point >= Airport->nofelements) {printf("Entry point (%2d) must be within the airport positions (which is max %2d)\n", entry_point, Airport->nofelements);}
assert(entry_point < Airport->nofelements);
Airport->acc_planes = acc_planes;
Airport->entry_point = entry_point;
Airport->airport_depots = depots;
Airport->nof_depots = nof_depots;
// build the state machine
AirportBuildAutomata(Airport, FA);
DEBUG(misc, 1) ("#Elements %2d; #Terminals %2d in %d group(s); #Helipads %2d in %d group(s); Entry Point %d", Airport->nofelements,
nofterminals, nofterminalgroups, nofhelipads, nofhelipadgroups, Airport->entry_point);
{
byte _retval = AirportTestFTA(Airport);
if (_retval != MAX_ELEMENTS) {printf("ERROR with element: %d\n", _retval-1);}
assert(_retval == MAX_ELEMENTS);
}
apc->acc_planes = acc_planes;
apc->entry_point = entry_point;
apc->airport_depots = depots;
apc->nof_depots = nof_depots;
/* Build the state machine itself */
AirportBuildAutomata(apc, apFA);
DEBUG(misc, 1) ("[Ap] #count %3d; #term %2d (%dgrp); #helipad %2d (%dgrp); entry %3d",
apc->nofelements, nofterminals, nofterminalgroups, nofhelipads, nofhelipadgroups, apc->entry_point);
/* Test if everything went allright. This is only a rude static test checking
* the symantic correctness. By no means does passing the test mean that the
* airport is working correctly or will not deadlock for example */
{ byte ret = AirportTestFTA(apc);
if (ret != MAX_ELEMENTS) DEBUG(misc, 0) ("[Ap] ERROR with element: %d", ret - 1);
assert(ret == MAX_ELEMENTS);
}
#ifdef DEBUG_AIRPORT
AirportPrintOut(apc, DEBUG_AIRPORT);
#endif
// print out full information
// true -- full info including heading, block, etc
// false -- short info, only position and next position
//AirportPrintOut(Airport, false);
}
static void AirportFTAClass_Destructor(AirportFTAClass *apc)
static void AirportFTAClass_Destructor(AirportFTAClass *Airport)
{
int i;
AirportFTA *current, *next;
for (i = 0; i < apc->nofelements; i++) {
current = apc->layout[i].next;
for (i = 0; i < Airport->nofelements; i++) {
current = Airport->layout[i].next_in_chain;
while (current != NULL) {
next = current->next;
next = current->next_in_chain;
free(current);
current = next;
};
}
free(apc->layout);
free(apc);
free(Airport->layout);
free(Airport);
}
/** Get the number of elements of a source Airport state automata
* Since it is actually just a big array of AirportFTA types, we only
* know one element from the other by differing 'position' identifiers */
static uint16 AirportGetNofElements(const AirportFTAbuildup *apFA)
static uint16 AirportGetNofElements(const AirportFTAbuildup *FA)
{
int i;
uint16 nofelements = 0;
int temp = apFA[0].position;
int temp = FA[0].position;
for (i = 0; i < MAX_ELEMENTS; i++) {
if (temp != apFA[i].position) {
if (temp != FA[i].position) {
nofelements++;
temp = apFA[i].position;
temp = FA[i].position;
}
if (apFA[i].position == MAX_ELEMENTS) break;
if (FA[i].position == MAX_ELEMENTS) {break;}
}
return nofelements;
}
/* We calculate the terminal/helipod count based on the data passed to us
* This data (terminals) contains an index as a first element as to how many
* groups there are, and then the number of terminals for each group */
static byte AirportGetTerminalCount(const byte *terminals, byte *groups)
{
byte i;
byte nof_terminals = 0;
*groups = 0;
if (terminals != NULL) {
i = terminals[0];
*groups = i;
while (i-- > 0) {
terminals++;
assert(*terminals != 0); // no empty groups please
nof_terminals += *terminals;
}
}
return nof_terminals;
}
static void AirportBuildAutomata(AirportFTAClass *apc, const AirportFTAbuildup *apFA)
static void AirportBuildAutomata(AirportFTAClass *Airport, const AirportFTAbuildup *FA)
{
AirportFTA *FAutomata;
AirportFTA *current;
AirportFTA *FAutomata = malloc(sizeof(AirportFTA) * apc->nofelements);
uint16 internalcounter = 0;
uint16 i;
uint16 internalcounter, i;
FAutomata = (AirportFTA *)malloc(sizeof(AirportFTA) * Airport->nofelements);
Airport->layout = FAutomata;
internalcounter = 0;
apc->layout = FAutomata;
for (i = 0; i < apc->nofelements; i++) {
current = &apc->layout[i];
current->position = apFA[internalcounter].position;
current->heading = apFA[internalcounter].heading;
current->block = apFA[internalcounter].block;
current->next_position = apFA[internalcounter].next;
for (i = 0; i < Airport->nofelements; i++) {
current = &Airport->layout[i];
current->position = FA[internalcounter].position;
current->heading = FA[internalcounter].heading;
current->block = FA[internalcounter].block;
current->next_position = FA[internalcounter].next_in_chain;
// outgoing nodes from the same position, create linked list
while (current->position == apFA[internalcounter + 1].position) {
AirportFTA *newNode = malloc(sizeof(AirportFTA));
newNode->position = apFA[internalcounter + 1].position;
newNode->heading = apFA[internalcounter + 1].heading;
newNode->block = apFA[internalcounter + 1].block;
newNode->next_position = apFA[internalcounter + 1].next;
while (current->position == FA[internalcounter+1].position) {
AirportFTA *newNode = (AirportFTA *)malloc(sizeof(AirportFTA));
newNode->position = FA[internalcounter+1].position;
newNode->heading = FA[internalcounter+1].heading;
newNode->block = FA[internalcounter+1].block;
newNode->next_position = FA[internalcounter+1].next_in_chain;
// create link
current->next = newNode;
current = current->next;
current->next_in_chain = newNode;
current = current->next_in_chain;
internalcounter++;
} // while
current->next = NULL;
current->next_in_chain = NULL;
internalcounter++;
}
}
static byte AirportTestFTA(const AirportFTAClass *apc)
static byte AirportTestFTA(const AirportFTAClass *Airport)
{
byte position, i, next_position;
AirportFTA *current, *first;
next_position = 0;
byte position, i, next_element;
AirportFTA *temp;
next_element = 0;
for (i = 0; i < apc->nofelements; i++) {
position = apc->layout[i].position;
if (position != next_position) return i;
current = first = &apc->layout[i];
for (i = 0; i < Airport->nofelements; i++) {
position = Airport->layout[i].position;
if (position != next_element) {return i;}
temp = &Airport->layout[i];
for (; current != NULL; current = current->next) {
/* A heading must always be valid. The only exceptions are
* - multiple choices as start, identified by a special value of 255
* - terminal group which is identified by a special value of 255 */
if (current->heading > MAX_HEADINGS) {
if (current->heading != 255) return i;
if (current == first && current->next == NULL) return i;
if (current != first && current->next_position > apc->terminals[0]) return i;
}
/* If there is only one choice, it must be at the end */
if (current->heading == 0 && current->next != NULL) return i;
/* Obviously the elements of the linked list must have the same identifier */
if (position != current->position) return i;
/* A next position must be within bounds */
if (current->next_position >= apc->nofelements) return i;
}
next_position++;
do {
if (temp->heading > MAX_HEADINGS && temp->heading != 255) {return i;}
if (temp->heading == 0 && temp->next_in_chain != 0) {return i;}
if (position != temp->position) {return i;}
if (temp->next_position >= Airport->nofelements) {return i;}
temp = temp->next_in_chain;
} while (temp != NULL);
next_element++;
}
return MAX_ELEMENTS;
}
#ifdef DEBUG_AIRPORT
static const char* const _airport_heading_strings[] = {
static const char* const _airport_heading_strings[MAX_HEADINGS+2] = {
"TO_ALL",
"HANGAR",
"TERM1",
@@ -407,83 +295,67 @@ static const char* const _airport_heading_strings[] = {
"ENDLANDING",
"HELILANDING",
"HELIENDLANDING",
"TERM7",
"TERM8",
"HELIPAD3",
"HELIPAD4",
"DUMMY" // extra heading for 255
"DUMMY" // extra heading for 255
};
static uint AirportBlockToString(uint32 block)
{
uint i = 0;
if (block & 0xffff0000) { block >>= 16; i += 16; }
if (block & 0x0000ff00) { block >>= 8; i += 8; }
if (block & 0x000000f0) { block >>= 4; i += 4; }
if (block & 0x0000000c) { block >>= 2; i += 2; }
if (block & 0x00000002) { i += 1; }
return i;
}
static void AirportPrintOut(const AirportFTAClass *apc, bool full_report)
/*
static void AirportPrintOut(const AirportFTAClass *Airport, const bool full_report)
{
AirportFTA *temp;
uint16 i;
byte heading;
if (!full_report) printf("(P = Current Position; NP = Next Position)\n");
for (i = 0; i < apc->nofelements; i++) {
AirportFTA *current = &apc->layout[i];
for (; current != NULL; current = current->next) {
printf("(P = Current Position; NP = Next Position)\n");
for (i = 0; i < Airport->nofelements; i++) {
temp = &Airport->layout[i];
if (full_report) {
heading = (temp->heading == 255) ? MAX_HEADINGS+1 : temp->heading;
printf("Pos:%2d NPos:%2d Heading:%15s Block:%2d\n", temp->position, temp->next_position,
_airport_heading_strings[heading], AirportBlockToString(temp->block));
}
else { printf("P:%2d NP:%2d", temp->position, temp->next_position);}
while (temp->next_in_chain != NULL) {
temp = temp->next_in_chain;
if (full_report) {
byte heading = (current->heading == 255) ? MAX_HEADINGS + 1 : current->heading;
printf("\tPos:%2d NPos:%2d Heading:%15s Block:%2d\n", current->position,
current->next_position, _airport_heading_strings[heading],
AirportBlockToString(current->block));
} else {
printf("P:%2d NP:%2d", current->position, current->next_position);
heading = (temp->heading == 255) ? MAX_HEADINGS+1 : temp->heading;
printf("Pos:%2d NPos:%2d Heading:%15s Block:%2d\n", temp->position, temp->next_position,
_airport_heading_strings[heading], AirportBlockToString(temp->block));
}
else { printf("P:%2d NP:%2d", temp->position, temp->next_position);}
}
printf("\n");
}
}
#endif
const AirportFTAClass *GetAirport(const byte airport_type)
static byte AirportBlockToString(uint32 block)
{
byte i = 0;
if (block & 0xffff0000) { block >>= 16; i += 16; }
if (block & 0x0000ff00) { block >>= 8; i += 8; }
if (block & 0x000000f0) { block >>= 4; i += 4; }
if (block & 0x0000000c) { block >>= 2; i += 2; }
if (block & 0x00000002) { i += 1; }
return i;
}*/
const AirportFTAClass* GetAirport(const byte airport_type)
{
AirportFTAClass *Airport = NULL;
//FIXME -- AircraftNextAirportPos_and_Order -> Needs something nicer, don't like this code
// needs constant change if more airports are added
switch (airport_type) {
default: NOT_REACHED();
case AT_SMALL: return CountryAirport;
case AT_LARGE: return CityAirport;
case AT_METROPOLITAN: return MetropolitanAirport;
case AT_HELIPORT: return Heliport;
case AT_OILRIG: return Oilrig;
case AT_INTERNATIONAL: return InternationalAirport;
case AT_COMMUTER: return CommuterAirport;
case AT_HELIDEPOT: return HeliDepot;
case AT_INTERCON: return IntercontinentalAirport;
case AT_HELISTATION: return HeliStation;
case AT_SMALL: Airport = CountryAirport; break;
case AT_LARGE: Airport = CityAirport; break;
case AT_METROPOLITAN: Airport = MetropolitanAirport; break;
case AT_HELIPORT: Airport = Heliport; break;
case AT_OILRIG: Airport = Oilrig; break;
case AT_INTERNATIONAL: Airport = InternationalAirport; break;
default:
#ifdef DEBUG__
printf("Airport AircraftNextAirportPos_and_Order not yet implemented\n");
#endif
assert(airport_type <= AT_INTERNATIONAL);
}
}
const AirportMovingData *GetAirportMovingData(byte airport_type, byte position)
{
assert(airport_type < lengthof(_airport_moving_datas));
assert(position < GetAirport(airport_type)->nofelements);
return &_airport_moving_datas[airport_type][position];
}
uint32 GetValidAirports(void)
{
uint32 bytemask = _avail_aircraft; /// sets the first 3 bytes, 0 - 2, @see AdjustAvailAircraft()
if (_cur_year >= 1980) SETBIT(bytemask, 3); // metropolitan airport
if (_cur_year >= 1990) SETBIT(bytemask, 4); // international airport
if (_cur_year >= 1983) SETBIT(bytemask, 5); // commuter airport
if (_cur_year >= 1976) SETBIT(bytemask, 6); // helidepot
if (_cur_year >= 2002) SETBIT(bytemask, 7); // intercontinental airport
if (_cur_year >= 1980) SETBIT(bytemask, 8); // helistation
return bytemask;
return Airport;
}

166
airport.h
View File

@@ -1,163 +1,67 @@
/* $Id$ */
#ifndef AIRPORT_H
#define AIRPORT_H
enum {MAX_TERMINALS = 10};
enum {MAX_HELIPADS = 4};
enum {MAX_ELEMENTS = 255};
enum {MAX_HEADINGS = 22};
#include "airport_movement.h"
enum {MAX_TERMINALS = 6};
enum {MAX_HELIPADS = 2};
// Airport types
enum {
AT_SMALL = 0,
AT_LARGE = 1,
AT_HELIPORT = 2,
AT_METROPOLITAN = 3,
AT_INTERNATIONAL = 4,
AT_COMMUTER = 5,
AT_HELIDEPOT = 6,
AT_INTERCON = 7,
AT_HELISTATION = 8,
AT_OILRIG = 15
AT_SMALL = 0,
AT_LARGE = 1,
AT_HELIPORT = 2,
AT_METROPOLITAN = 3,
AT_INTERNATIONAL = 4,
AT_OILRIG = 15
};
// do not change unless you change v->subtype too. This aligns perfectly with its current setting
enum {
AIRCRAFT_ONLY = 0,
ALL = 1,
HELICOPTERS_ONLY = 2,
AIRCRAFT_ONLY = 0,
ALL = 1,
HELICOPTERS_ONLY = 2
};
enum {
AMED_NOSPDCLAMP = 1 << 0,
AMED_TAKEOFF = 1 << 1,
AMED_SLOWTURN = 1 << 2,
AMED_LAND = 1 << 3,
AMED_EXACTPOS = 1 << 4,
AMED_BRAKE = 1 << 5,
AMED_HELI_RAISE = 1 << 6,
AMED_HELI_LOWER = 1 << 7,
};
/* Movement States on Airports (headings target) */
enum {
TO_ALL = 0,
HANGAR = 1,
TERM1 = 2,
TERM2 = 3,
TERM3 = 4,
TERM4 = 5,
TERM5 = 6,
TERM6 = 7,
HELIPAD1 = 8,
HELIPAD2 = 9,
TAKEOFF = 10,
STARTTAKEOFF = 11,
ENDTAKEOFF = 12,
HELITAKEOFF = 13,
FLYING = 14,
LANDING = 15,
ENDLANDING = 16,
HELILANDING = 17,
HELIENDLANDING = 18,
TERM7 = 19,
TERM8 = 20,
HELIPAD3 = 21,
HELIPAD4 = 22
};
// 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};
/* Movement Blocks on Airports */
// blocks (eg_airport_flags)
enum {
TERM1_block = 1 << 0,
TERM2_block = 1 << 1,
TERM3_block = 1 << 2,
TERM4_block = 1 << 3,
TERM5_block = 1 << 4,
TERM6_block = 1 << 5,
HELIPAD1_block = 1 << 6,
HELIPAD2_block = 1 << 7,
RUNWAY_IN_OUT_block = 1 << 8,
RUNWAY_IN_block = 1 << 8,
AIRPORT_BUSY_block = 1 << 8,
RUNWAY_OUT_block = 1 << 9,
TAXIWAY_BUSY_block = 1 << 10,
OUT_WAY_block = 1 << 11,
IN_WAY_block = 1 << 12,
AIRPORT_ENTRANCE_block = 1 << 13,
TERM_GROUP1_block = 1 << 14,
TERM_GROUP2_block = 1 << 15,
HANGAR2_AREA_block = 1 << 16,
TERM_GROUP2_ENTER1_block = 1 << 17,
TERM_GROUP2_ENTER2_block = 1 << 18,
TERM_GROUP2_EXIT1_block = 1 << 19,
TERM_GROUP2_EXIT2_block = 1 << 20,
PRE_HELIPAD_block = 1 << 21,
// blocks for new airports
TERM7_block = 1 << 22,
TERM8_block = 1 << 23,
TERM9_block = 1 << 24,
HELIPAD3_block = 1 << 24,
TERM10_block = 1 << 25,
HELIPAD4_block = 1 << 25,
HANGAR1_AREA_block = 1 << 26,
OUT_WAY2_block = 1 << 27,
IN_WAY2_block = 1 << 28,
RUNWAY_IN2_block = 1 << 29,
RUNWAY_OUT2_block = 1 << 10, // note re-uses TAXIWAY_BUSY
HELIPAD_GROUP_block = 1 << 13, // note re-uses AIRPORT_ENTRANCE
OUT_WAY_block2 = 1 << 31,
// end of new blocks
NOTHING_block = 1 << 30
};
typedef struct AirportMovingData {
int x,y;
byte flag;
byte direction;
} AirportMovingData;
// Finite sTate mAchine --> FTA
typedef struct AirportFTAClass {
byte nofelements; // number of positions the airport consists of
byte nofelements; // number of positions the airport consists of
const byte *terminals;
const byte *helipads;
byte entry_point; // when an airplane arrives at this airport, enter it at position entry_point
byte acc_planes; // accept airplanes or helicopters or both
const TileIndexDiffC *airport_depots; // gives the position of the depots on the airports
byte nof_depots; // number of depots this airport has
struct AirportFTA *layout; // state machine for airport
byte size_x;
byte size_y;
byte entry_point; // when an airplane arrives at this airport, enter it at position entry_point
byte acc_planes; // accept airplanes or helicopters or both
const TileIndexDiffC *airport_depots; // gives the position of the depots on the airports
byte nof_depots; // number of depots this airport has
struct AirportFTA *layout; // state machine for airport
} AirportFTAClass;
// internal structure used in openttd - Finite sTate mAchine --> FTA
typedef struct AirportFTA {
byte position; // the position that an airplane is at
byte next_position; // next position from this position
uint32 block; // 32 bit blocks (st->airport_flags), should be enough for the most complex airports
byte heading; // heading (current orders), guiding an airplane to its target on an airport
struct AirportFTA *next; // possible extra movement choices from this position
byte position; // the position that an airplane is at
byte next_position; // next position from this position
uint32 block; // 32 bit blocks (st->airport_flags), should be enough for the most complex airports
byte heading; // heading (current orders), guiding an airplane to its target on an airport
struct AirportFTA *next_in_chain; // possible extra movement choices from this position
} AirportFTA;
void InitializeAirports(void);
void UnInitializeAirports(void);
const AirportFTAClass *GetAirport(const byte airport_type);
const AirportMovingData *GetAirportMovingData(byte airport_type, byte position);
const AirportFTAClass* GetAirport(const byte airport_type);
/** Get buildable airport bitmask.
* @return get all buildable airports at this given time, bitmasked.
* Bit 0 means the small airport is buildable, etc.
* @todo set availability of airports by year, instead of airplane
*/
uint32 GetValidAirports(void);
static inline uint32 GetValidAirports(void)
{
uint32 bytemask = _avail_aircraft; /// sets the first 3 bytes, 0 - 2, @see AdjustAvailAircraft()
// 1980-1-1 is --> 21915
// 1990-1-1 is --> 25568
if (_date >= 21915) {SETBIT(bytemask, 3);} // metropilitan airport 1980
if (_date >= 25568) {SETBIT(bytemask, 4);} // international airport 1990
return bytemask;
}
#endif /* AIRPORT_H */

View File

@@ -1,10 +1,7 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "functions.h"
#include "map.h"
#include "window.h"
#include "gui.h"
@@ -22,7 +19,7 @@ static byte _selected_airport_type;
static void ShowBuildAirportPicker(void);
void CcBuildAirport(bool success, TileIndex tile, uint32 p1, uint32 p2)
void CcBuildAirport(bool success, uint tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_1F_SPLAT, tile);
@@ -30,31 +27,25 @@ void CcBuildAirport(bool success, TileIndex tile, uint32 p1, uint32 p2)
}
}
static void PlaceAirport(TileIndex tile)
static void PlaceAirport(uint tile)
{
DoCommandP(tile, _selected_airport_type, 0, CcBuildAirport, CMD_BUILD_AIRPORT | CMD_AUTO | CMD_NO_WATER | CMD_MSG(STR_A001_CAN_T_BUILD_AIRPORT_HERE));
}
static void PlaceAir_DemolishArea(TileIndex tile)
static void PlaceAir_DemolishArea(uint tile)
{
VpStartPlaceSizing(tile, 4);
}
enum {
ATW_AIRPORT = 3,
ATW_DEMOLISH = 4
};
static void BuildAirClick_Airport(Window *w)
{
if (HandlePlacePushButton(w, ATW_AIRPORT, SPR_CURSOR_AIRPORT, 1, PlaceAirport)) ShowBuildAirportPicker();
if (HandlePlacePushButton(w, 3, 0xAA4, 1, PlaceAirport)) ShowBuildAirportPicker();
}
static void BuildAirClick_Demolish(Window *w)
{
HandlePlacePushButton(w, ATW_DEMOLISH, ANIMCURSOR_DEMOLISH, 1, PlaceAir_DemolishArea);
HandlePlacePushButton(w, 4, ANIMCURSOR_DEMOLISH, 1, PlaceAir_DemolishArea);
}
static void BuildAirClick_Landscaping(Window *w)
@@ -71,67 +62,65 @@ static OnButtonClick * const _build_air_button_proc[] = {
static void BuildAirToolbWndProc(Window *w, WindowEvent *e)
{
switch (e->event) {
switch(e->event) {
case WE_PAINT:
DrawWindowWidgets(w);
break;
case WE_CLICK:
if (e->we.click.widget - 3 >= 0)
_build_air_button_proc[e->we.click.widget - 3](w);
if (e->click.widget - 3 >= 0)
_build_air_button_proc[e->click.widget - 3](w);
break;
case WE_KEYPRESS: {
switch (e->we.keypress.keycode) {
switch (e->keypress.keycode) {
case '1': BuildAirClick_Airport(w); break;
case '2': BuildAirClick_Demolish(w); break;
case 'l': BuildAirClick_Landscaping(w); break;
default: return;
default:
return;
}
} break;
case WE_PLACE_OBJ:
_place_proc(e->we.place.tile);
_place_proc(e->place.tile);
break;
case WE_PLACE_DRAG:
VpSelectTilesWithMethod(e->we.place.pt.x, e->we.place.pt.y, e->we.place.userdata);
break;
case WE_PLACE_DRAG: {
VpSelectTilesWithMethod(e->place.pt.x, e->place.pt.y, e->place.userdata);
return;
}
case WE_PLACE_MOUSEUP:
if (e->we.place.pt.x != -1) {
DoCommandP(e->we.place.tile, e->we.place.starttile, 0, CcPlaySound10, CMD_CLEAR_AREA | CMD_MSG(STR_00B5_CAN_T_CLEAR_THIS_AREA));
if (e->place.pt.x != -1) {
DoCommandP(e->place.tile, e->place.starttile, 0, CcPlaySound10, CMD_CLEAR_AREA | CMD_MSG(STR_00B5_CAN_T_CLEAR_THIS_AREA));
}
break;
case WE_ABORT_PLACE_OBJ:
RaiseWindowButtons(w);
UnclickWindowButtons(w);
SetWindowDirty(w);
w = FindWindowById(WC_BUILD_STATION, 0);
if (w != 0)
WP(w,def_d).close = true;
break;
case WE_DESTROY:
if (_patches.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0);
break;
}
}
static const Widget _air_toolbar_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW },
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 73, 0, 13, STR_A000_AIRPORTS, STR_018C_WINDOW_TITLE_DRAG_THIS },
{ WWT_STICKYBOX, RESIZE_NONE, 7, 74, 85, 0, 13, 0x0, STR_STICKY_BUTTON },
{ WWT_IMGBTN, RESIZE_NONE, 7, 0, 41, 14, 35, SPR_IMG_AIRPORT, STR_A01E_BUILD_AIRPORT },
{ WWT_IMGBTN, RESIZE_NONE, 7, 42, 63, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC },
{ WWT_IMGBTN, RESIZE_NONE, 7, 64, 85, 14, 35, SPR_IMG_LANDSCAPING, STR_LANDSCAPING_TOOLBAR_TIP },
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 73, 0, 13, STR_A000_AIRPORTS, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_NONE, 7, 74, 85, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 41, 14, 35, 0x2E8, STR_A01E_BUILD_AIRPORT},
{ WWT_PANEL, RESIZE_NONE, 7, 42, 63, 14, 35, 0x2BF, STR_018D_DEMOLISH_BUILDINGS_ETC},
{ WWT_PANEL, RESIZE_NONE, 7, 64, 85, 14, 35, SPR_IMG_LANDSCAPING, STR_LANDSCAPING_TOOLBAR_TIP},
{ WIDGETS_END},
};
static const WindowDesc _air_toolbar_desc = {
WDP_ALIGN_TBR, 22, 86, 36,
WC_BUILD_TOOLBAR, 0,
640-86, 22, 86, 36,
WC_BUILD_TOOLBAR,0,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
_air_toolbar_widgets,
BuildAirToolbWndProc
@@ -139,86 +128,67 @@ static const WindowDesc _air_toolbar_desc = {
void ShowBuildAirToolbar(void)
{
if (!IsValidPlayer(_current_player)) return;
if (_current_player == OWNER_SPECTATOR) return;
DeleteWindowById(WC_BUILD_TOOLBAR, 0);
AllocateWindowDescFront(&_air_toolbar_desc, 0);
if (_patches.link_terraform_toolbar) ShowTerraformToolbar();
}
static void BuildAirportPickerWndProc(Window *w, WindowEvent *e)
{
switch (e->event) {
case WE_CREATE:
SetWindowWidgetLoweredState(w, 16, !_station_show_coverage);
SetWindowWidgetLoweredState(w, 17, _station_show_coverage);
LowerWindowWidget(w, _selected_airport_type + 7);
break;
case WE_PAINT: {
int i; // airport enabling loop
int sel;
int rad = 4; // default catchment radious
uint32 avail_airports;
const AirportFTAClass *airport;
if (WP(w,def_d).close) return;
sel = _selected_airport_type;
avail_airports = GetValidAirports();
RaiseWindowWidget(w, _selected_airport_type + 7);
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;
LowerWindowWidget(w, _selected_airport_type + 7);
if (!HASBIT(avail_airports, 0) && sel == AT_SMALL) sel = AT_LARGE;
if (!HASBIT(avail_airports, 1) && sel == AT_LARGE) sel = AT_SMALL;
/* 'Country Airport' starts at widget 7, 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 < 9; i++) SetWindowWidgetDisabledState(w, i + 7, !HASBIT(avail_airports, i));
/* 'Country Airport' starts at widget 3, and if its bit is set, it is available,
* so take its opposite value to set the disabled_state. There are only 5 available
* airports, so XOr with 0x1F (1 1111) */
w->disabled_state = (avail_airports ^ 0x1F) << 3;
// select default the coverage area to 'Off' (16)
airport = GetAirport(_selected_airport_type);
SetTileSelectSize(airport->size_x, airport->size_y);
_selected_airport_type = sel;
// select default the coverage area to 'Off' (8)
w->click_state = ((1<<3) << sel) | ((1<<8) << _station_show_coverage);
SetTileSelectSize(_airport_size_x[sel],_airport_size_y[sel]);
if (_patches.modified_catchment) {
switch (_selected_airport_type) {
case AT_OILRIG: rad = CA_AIR_OILPAD; break;
case AT_HELIPORT: rad = CA_AIR_HELIPORT; break;
case AT_SMALL: rad = CA_AIR_SMALL; break;
case AT_LARGE: rad = CA_AIR_LARGE; break;
case AT_METROPOLITAN: rad = CA_AIR_METRO; break;
case AT_INTERNATIONAL: rad = CA_AIR_INTER; break;
case AT_COMMUTER: rad = CA_AIR_COMMUTER; break;
case AT_HELIDEPOT: rad = CA_AIR_HELIDEPOT; break;
case AT_INTERCON: rad = CA_AIR_INTERCON; break;
case AT_HELISTATION: rad = CA_AIR_HELISTATION; break;
}
}
if (_patches.modified_catchment) {
switch (sel) {
case AT_OILRIG: rad = CA_AIR_OILPAD; break;
case AT_HELIPORT: rad = CA_AIR_HELIPORT; break;
case AT_SMALL: rad = CA_AIR_SMALL; break;
case AT_LARGE: rad = CA_AIR_LARGE; break;
case AT_METROPOLITAN: rad = CA_AIR_METRO; break;
case AT_INTERNATIONAL: rad = CA_AIR_INTER; break;
}
}
if (_station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
if (_station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
DrawWindowWidgets(w);
// strings such as 'Size' and 'Coverage Area'
// 'Coverage Area'
DrawStationCoverageAreaText(2, 206, (uint)-1, rad);
// strings such as 'Size' and 'Coverage Area'
DrawStringCentered(74, 16, STR_305B_SIZE, 0);
DrawStringCentered(74, 78, STR_3066_COVERAGE_AREA_HIGHLIGHT, 0);
DrawStationCoverageAreaText(2, 104, (uint)-1, rad);
break;
}
case WE_CLICK: {
switch (e->we.click.widget) {
case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15:
RaiseWindowWidget(w, _selected_airport_type + 7);
_selected_airport_type = e->we.click.widget - 7;
LowerWindowWidget(w, _selected_airport_type + 7);
switch(e->click.widget) {
case 3: case 4: case 5: case 6: case 7:
_selected_airport_type = e->click.widget - 3;
SndPlayFx(SND_15_BEEP);
SetWindowDirty(w);
break;
case 16: case 17:
_station_show_coverage = e->we.click.widget - 16;
SetWindowWidgetLoweredState(w, 16, !_station_show_coverage);
SetWindowWidgetLoweredState(w, 17, _station_show_coverage);
case 8: case 9:
_station_show_coverage = e->click.widget - 8;
SndPlayFx(SND_15_BEEP);
SetWindowDirty(w);
break;
@@ -235,41 +205,29 @@ static void BuildAirportPickerWndProc(Window *w, WindowEvent *e)
} break;
case WE_DESTROY:
if (!WP(w,def_d).close) ResetObjectToPlace();
if (!WP(w,def_d).close)
ResetObjectToPlace();
break;
}
}
static const Widget _build_airport_picker_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 147, 0, 13, STR_3001_AIRPORT_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 147, 14, 52, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 147, 53, 89, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 147, 90, 127, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 147, 128, 177, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 147, 178, 239, 0x0, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 27, 38, STR_SMALL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 65, 76, STR_CITY_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 141, 152, STR_HELIPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 77, 88, STR_METRO_AIRPORT , STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 103, 114, STR_INTERNATIONAL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 39, 50, STR_COMMUTER_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 165, 176, STR_HELIDEPOT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 115, 126, STR_INTERCONTINENTAL_AIRPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 2, 145, 153, 164, STR_HELISTATION, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 14, 73, 191, 202, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 74, 133, 191, 202, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA},
{ WWT_LABEL, RESIZE_NONE, 7, 0, 147, 14, 27, STR_SMALL_AIRPORTS, STR_NULL},
{ WWT_LABEL, RESIZE_NONE, 7, 0, 147, 52, 65, STR_LARGE_AIRPORTS, STR_NULL},
{ WWT_LABEL, RESIZE_NONE, 7, 0, 147, 90, 103, STR_HUB_AIRPORTS, STR_NULL},
{ WWT_LABEL, RESIZE_NONE, 7, 0, 147, 128, 141, STR_HELIPORTS, STR_NULL},
{ WWT_LABEL, RESIZE_NONE, 7, 0, 147, 178, 191, STR_3066_COVERAGE_AREA_HIGHLIGHT, STR_NULL},
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 147, 0, 13, STR_3001_AIRPORT_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 147, 14, 130, 0x0, STR_NULL},
{WWT_NODISTXTBTN, RESIZE_NONE, 14, 2, 73, 27, 38, STR_3059_SMALL, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{WWT_NODISTXTBTN, RESIZE_NONE, 14, 74, 145, 27, 38, STR_305A_LARGE, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{WWT_NODISTXTBTN, RESIZE_NONE, 14, 2, 145, 63, 74, STR_306B_HELIPORT, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{WWT_NODISTXTBTN, RESIZE_NONE, 14, 2, 145, 39, 50, STR_305AA_LARGE, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{WWT_NODISTXTBTN, RESIZE_NONE, 14, 2, 145, 51, 62, STR_305AB_LARGE, STR_3058_SELECT_SIZE_TYPE_OF_AIRPORT},
{ WWT_CLOSEBOX, RESIZE_NONE, 14, 14, 73, 88, 98, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE},
{ WWT_CLOSEBOX, RESIZE_NONE, 14, 74, 133, 88, 98, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA},
{ WIDGETS_END},
};
static const WindowDesc _build_airport_desc = {
WDP_AUTO, WDP_AUTO, 148, 240,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
-1, -1, 148, 131, // height, 130+1
WC_BUILD_STATION,WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_build_airport_picker_widgets,
BuildAirportPickerWndProc
@@ -283,4 +241,5 @@ static void ShowBuildAirportPicker(void)
void InitializeAirportGui(void)
{
_selected_airport_type = AT_SMALL;
_last_built_aircraft_depot_tile = 0;
}

File diff suppressed because it is too large Load Diff

118
aystar.c
View File

@@ -1,5 +1,3 @@
/* $Id$ */
/*
* This file has the core function for AyStar
* AyStar is a fast pathfinding routine and is used for things like
@@ -17,32 +15,28 @@
*/
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "aystar.h"
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)
static PathNode *AyStarMain_ClosedList_IsInList(AyStar *aystar, 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)
static void AyStarMain_ClosedList_Add(AyStar *aystar, PathNode *node)
{
// Add a node to the ClosedList
PathNode *new_node = malloc(sizeof(*new_node));
PathNode *new_node = malloc(sizeof(PathNode));
*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)
static OpenListNode *AyStarMain_OpenList_IsInList(AyStar *aystar, AyStarNode *node)
{
return (OpenListNode*)Hash_Get(&aystar->OpenListHash, node->tile, node->direction);
}
@@ -53,20 +47,19 @@ static OpenListNode *AyStarMain_OpenList_IsInList(AyStar *aystar, const AyStarNo
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) {
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)
static void AyStarMain_OpenList_Add(AyStar *aystar, PathNode *parent, AyStarNode *node, int f, int g)
{
// Add a new Node to the OpenList
OpenListNode *new_node = malloc(sizeof(*new_node));
OpenListNode* new_node = malloc(sizeof(OpenListNode));
new_node->g = g;
new_node->path.parent = parent;
new_node->path.node = *node;
@@ -79,10 +72,9 @@ static void AyStarMain_OpenList_Add(AyStar *aystar, PathNode *parent, const AySt
/*
* Checks one tile and calculate his f-value
* return values:
* AYSTAR_DONE : indicates we are done
* AYSTAR_DONE : indicates we are done
*/
int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
{
int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *parent) {
int new_f, new_g, new_h;
PathNode *closedlist_parent;
OpenListNode *check;
@@ -113,8 +105,7 @@ int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *pare
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) {
if ((check = AyStarMain_OpenList_IsInList(aystar, current)) != NULL) {
uint i;
// Yes, check if this g value is lower..
if (new_g > check->g) return AYSTAR_DONE;
@@ -123,9 +114,8 @@ int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *pare
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++) {
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 {
@@ -140,15 +130,14 @@ int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *pare
* 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.
* 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 AyStarMain_Loop(AyStar *aystar) {
int i, r;
// Get the best node from OpenList
@@ -171,7 +160,7 @@ int AyStarMain_Loop(AyStar *aystar)
aystar->GetNeighbours(aystar, current);
// Go through all neighbours
for (i = 0; i < aystar->num_neighbours; i++) {
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);
}
@@ -179,20 +168,18 @@ int AyStarMain_Loop(AyStar *aystar)
// Free the node
free(current);
if (aystar->max_search_nodes != 0 && Hash_Size(&aystar->ClosedListHash) >= aystar->max_search_nodes) {
if (aystar->max_search_nodes != 0 && Hash_Size(&aystar->ClosedListHash) >= aystar->max_search_nodes)
/* We've expanded enough nodes */
return AYSTAR_LIMIT_REACHED;
} else {
else
// Return that we are still busy
return AYSTAR_STILL_BUSY;
}
}
/*
* This function frees the memory it allocated
*/
void AyStarMain_Free(AyStar *aystar)
{
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 */
@@ -207,8 +194,7 @@ void AyStarMain_Free(AyStar *aystar)
* 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)
{
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);
@@ -224,9 +210,9 @@ void AyStarMain_Clear(AyStar *aystar)
/*
* 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.
* 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!
@@ -237,26 +223,24 @@ int AyStarMain_Main(AyStar *aystar) {
// 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;
}
if (r == AYSTAR_FOUND_END_NODE)
printf("[AyStar] Found path!\n");
else if (r == AYSTAR_EMPTY_OPENLIST)
printf("[AyStar] OpenList run dry, no path found\n");
else if (r == AYSTAR_LIMIT_REACHED)
printf("[AyStar] Exceeded search_nodes, no path found\n");
#endif
if (r != AYSTAR_STILL_BUSY) {
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;
}
// Check result-value
if (r == AYSTAR_FOUND_END_NODE) return AYSTAR_FOUND_END_NODE;
// Check if we have some left in the OpenList
if (r == AYSTAR_EMPTY_OPENLIST || r == AYSTAR_LIMIT_REACHED) return AYSTAR_NO_PATH;
// Return we are still busy
return AYSTAR_STILL_BUSY;
}
/*
@@ -266,8 +250,7 @@ int AyStarMain_Main(AyStar *aystar) {
* 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)
{
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);
@@ -275,8 +258,7 @@ void AyStarMain_AddStartNode(AyStar *aystar, AyStarNode *start_node, uint g)
AyStarMain_OpenList_Add(aystar, NULL, start_node, 0, g);
}
void init_AyStar(AyStar *aystar, Hash_HashProc hash, uint num_buckets)
{
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);
@@ -287,10 +269,10 @@ void init_AyStar(AyStar *aystar, Hash_HashProc hash, uint num_buckets)
// 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;
aystar->addstart = AyStarMain_AddStartNode;
aystar->main = AyStarMain_Main;
aystar->loop = AyStarMain_Loop;
aystar->free = AyStarMain_Free;
aystar->clear = AyStarMain_Clear;
aystar->checktile = AyStarMain_CheckTile;
}

View File

@@ -1,11 +1,9 @@
/* $Id$ */
/*
* This file has the header 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
* http://en.wikipedia.org/wiki/A-star_search_algorithm
*/
#ifndef AYSTAR_H
@@ -29,7 +27,7 @@ enum{
typedef struct AyStarNode AyStarNode;
struct AyStarNode {
TileIndex tile;
uint tile;
uint direction;
uint user_data[2];
};
@@ -55,8 +53,8 @@ typedef struct AyStar AyStar;
/*
* This function is called to check if the end-tile is found
* return values can be:
* AYSTAR_FOUND_END_NODE : indicates this is the end tile
* AYSTAR_DONE : indicates this is not the end tile (or direction was wrong)
* AYSTAR_FOUND_END_NODE : indicates this is the end tile
* AYSTAR_DONE : indicates this is not the end tile (or direction was wrong)
*/
/*
* The 2nd parameter should be OpenListNode, and NOT AyStarNode. AyStarNode is
@@ -71,8 +69,8 @@ typedef int32 AyStar_EndNodeCheck(AyStar *aystar, OpenListNode *current);
/*
* This function is called to calculate the G-value for AyStar Algorithm.
* return values can be:
* AYSTAR_INVALID_NODE : indicates an item is not valid (e.g.: unwalkable)
* Any value >= 0 : the g-value for this tile
* AYSTAR_INVALID_NODE : indicates an item is not valid (e.g.: unwalkable)
* Any value >= 0 : the g-value for this tile
*/
typedef int32 AyStar_CalculateG(AyStar *aystar, AyStarNode *current, OpenListNode *parent);
@@ -81,7 +79,7 @@ typedef int32 AyStar_CalculateG(AyStar *aystar, AyStarNode *current, OpenListNod
* Mostly, this must result the distance (Manhattan way) between the
* current point and the end point
* return values can be:
* Any value >= 0 : the h-value for this tile
* Any value >= 0 : the h-value for this tile
*/
typedef int32 AyStar_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent);
@@ -99,7 +97,7 @@ typedef void AyStar_GetNeighbours(AyStar *aystar, OpenListNode *current);
typedef void AyStar_FoundEndNode(AyStar *aystar, OpenListNode *current);
// For internal use, see aystar.c
typedef void AyStar_AddStartNode(AyStar *aystar, AyStarNode *start_node, uint g);
typedef void AyStar_AddStartNode(AyStar *aystar, AyStarNode* start_node, uint g);
typedef int AyStar_Main(AyStar *aystar);
typedef int AyStar_Loop(AyStar *aystar);
typedef int AyStar_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *parent);
@@ -112,11 +110,11 @@ struct AyStar {
/* These should point to the application specific routines that do the
* actual work */
AyStar_CalculateG *CalculateG;
AyStar_CalculateH *CalculateH;
AyStar_GetNeighbours *GetNeighbours;
AyStar_EndNodeCheck *EndNodeCheck;
AyStar_FoundEndNode *FoundEndNode;
AyStar_CalculateG* CalculateG;
AyStar_CalculateH* CalculateH;
AyStar_GetNeighbours* GetNeighbours;
AyStar_EndNodeCheck* EndNodeCheck;
AyStar_FoundEndNode* FoundEndNode;
/* These are completely untouched by AyStar, they can be accesed by
* the application specific routines to input and output data.
@@ -144,12 +142,12 @@ struct AyStar {
/* These will contain the methods for manipulating the AyStar. Only
* main() should be called externally */
AyStar_AddStartNode *addstart;
AyStar_Main *main;
AyStar_Loop *loop;
AyStar_Free *free;
AyStar_Clear *clear;
AyStar_CheckTile *checktile;
AyStar_AddStartNode* addstart;
AyStar_Main* main;
AyStar_Loop* loop;
AyStar_Free* free;
AyStar_Clear* clear;
AyStar_CheckTile* checktile;
/* These will contain the open and closed lists */
@@ -173,7 +171,7 @@ void AyStarMain_Clear(AyStar *aystar);
/* Initialize an AyStar. You should fill all appropriate fields before
* callling init_AyStar (see the declaration of AyStar for which fields are
* internal */
void init_AyStar(AyStar *aystar, Hash_HashProc hash, uint num_buckets);
void init_AyStar(AyStar* aystar, Hash_HashProc hash, uint num_buckets);
#endif /* AYSTAR_H */
#endif

378
bmp.c
View File

@@ -1,378 +0,0 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "gfx.h"
#include "bmp.h"
#include "macros.h"
void BmpInitializeBuffer(BmpBuffer *buffer, FILE *file) {
buffer->pos = -1;
buffer->file = file;
buffer->read = 0;
buffer->real_pos = ftell(file);
}
static inline void AdvanceBuffer(BmpBuffer *buffer)
{
buffer->read = (int)fread(buffer->data, 1, BMP_BUFFER_SIZE, buffer->file);
buffer->pos = 0;
}
static inline bool EndOfBuffer(BmpBuffer *buffer)
{
if (buffer->pos == buffer->read || buffer->pos < 0) AdvanceBuffer(buffer);
return buffer->pos == buffer->read;
}
static inline byte ReadByte(BmpBuffer *buffer)
{
if (buffer->pos == buffer->read || buffer->pos < 0) AdvanceBuffer(buffer);
buffer->real_pos++;
return buffer->data[buffer->pos++];
}
static inline uint16 ReadWord(BmpBuffer *buffer)
{
uint16 var = ReadByte(buffer);
return var | (ReadByte(buffer) << 8);
}
static inline uint32 ReadDword(BmpBuffer *buffer)
{
uint32 var = ReadWord(buffer);
return var | (ReadWord(buffer) << 16);
}
static inline void SkipBytes(BmpBuffer *buffer, int bytes)
{
int i;
for (i = 0; i < bytes; i++) ReadByte(buffer);
}
static inline void SetStreamOffset(BmpBuffer *buffer, int offset)
{
fseek(buffer->file, offset, SEEK_SET);
buffer->pos = -1;
buffer->real_pos = offset;
AdvanceBuffer(buffer);
}
/**
* Reads a 1 bpp uncompressed bitmap
* The bitmap is converted to a 8 bpp bitmap
*/
static inline bool BmpRead1(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y, i;
byte pad = GB(4 - info->width / 8, 0, 2);
byte *pixel_row;
byte b;
for (y = info->height; y > 0; y--) {
x = 0;
pixel_row = &data->bitmap[(y - 1) * info->width];
while (x < info->width) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
b = ReadByte(buffer);
for (i = 8; i > 0; i--) {
if (x < info->width) *pixel_row++ = GB(b, i - 1, 1);
x++;
}
}
/* Padding for 32 bit align */
SkipBytes(buffer, pad);
}
return true;
}
/**
* Reads a 4 bpp uncompressed bitmap
* The bitmap is converted to a 8 bpp bitmap
*/
static inline bool BmpRead4(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y;
byte pad = GB(4 - info->width / 2, 0, 2);
byte *pixel_row;
byte b;
for (y = info->height; y > 0; y--) {
x = 0;
pixel_row = &data->bitmap[(y - 1) * info->width];
while (x < info->width) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
b = ReadByte(buffer);
*pixel_row++ = GB(b, 4, 4);
x++;
if (x < info->width) {
*pixel_row++ = GB(b, 0, 4);
x++;
}
}
/* Padding for 32 bit align */
SkipBytes(buffer, pad);
}
return true;
}
/**
* Reads a 4-bit RLE compressed bitmap
* The bitmap is converted to a 8 bpp bitmap
*/
static inline bool BmpRead4Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint i;
uint x = 0;
uint y = info->height - 1;
byte n, c, b;
byte *pixel = &data->bitmap[y * info->width];
while (y != 0 || x < info->width) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
n = ReadByte(buffer);
c = ReadByte(buffer);
if (n == 0) {
switch (c) {
case 0: // end of line
x = 0;
pixel = &data->bitmap[--y * info->width];
break;
case 1: // end of bitmap
x = info->width;
y = 0;
pixel = NULL;
break;
case 2: // delta
x += ReadByte(buffer);
i = ReadByte(buffer);
if (x >= info->width || (y == 0 && i > 0)) return false;
y -= i;
pixel = &data->bitmap[y * info->width + x];
break;
default: // uncompressed
i = 0;
while (i++ < c) {
if (EndOfBuffer(buffer) || x >= info->width) return false;
b = ReadByte(buffer);
*pixel++ = GB(b, 4, 4);
x++;
if (x < info->width && i++ < c) {
*pixel++ = GB(b, 0, 4);
x++;
}
}
/* Padding for 16 bit align */
SkipBytes(buffer, ((c + 1) / 2) % 2);
break;
}
} else {
i = 0;
while (i++ < n) {
if (EndOfBuffer(buffer) || x >= info->width) return false;
*pixel++ = GB(c, 4, 4);
x++;
if (x < info->width && i++ < n) {
*pixel++ = GB(c, 0, 4);
x++;
}
}
}
}
return true;
}
/**
* Reads a 8 bpp bitmap
*/
static inline bool BmpRead8(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint i;
uint y;
byte pad = GB(4 - info->width, 0, 2);
byte *pixel;
for (y = info->height; y > 0; y--) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
pixel = &data->bitmap[(y - 1) * info->width];
for (i = 0; i < info->width; i++) *pixel++ = ReadByte(buffer);
/* Padding for 32 bit align */
SkipBytes(buffer, pad);
}
return true;
}
/**
* Reads a 8-bit RLE compressed bpp bitmap
*/
static inline bool BmpRead8Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint i;
uint x = 0;
uint y = info->height - 1;
byte n, c;
byte *pixel = &data->bitmap[y * info->width];
while (y != 0 || x < info->width) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
n = ReadByte(buffer);
c = ReadByte(buffer);
if (n == 0) {
switch (c) {
case 0: // end of line
x = 0;
pixel = &data->bitmap[--y * info->width];
break;
case 1: // end of bitmap
x = info->width;
y = 0;
pixel = NULL;
break;
case 2: // delta
x += ReadByte(buffer);
i = ReadByte(buffer);
if (x >= info->width || (y == 0 && i > 0)) return false;
y -= i;
pixel = &data->bitmap[y * info->width + x];
break;
default: // uncompressed
if ((x += c) > info->width) return false;
for (i = 0; i < c; i++) *pixel++ = ReadByte(buffer);
/* Padding for 16 bit align */
SkipBytes(buffer, c % 2);
break;
}
} else {
for (i = 0; i < n; i++) {
if (x >= info->width) return false;
*pixel++ = c;
x++;
}
}
}
return true;
}
/**
* Reads a 24 bpp uncompressed bitmap
*/
static inline bool BmpRead24(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y;
byte pad = GB(4 - info->width * 3, 0, 2);
byte *pixel_row;
for (y = info->height; y > 0; y--) {
pixel_row = &data->bitmap[(y - 1) * info->width * 3];
for (x = 0; x < info->width; x++) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
*(pixel_row + 2) = ReadByte(buffer); // green
*(pixel_row + 1) = ReadByte(buffer); // blue
*pixel_row = ReadByte(buffer); // red
pixel_row += 3;
}
/* Padding for 32 bit align */
SkipBytes(buffer, pad);
}
return true;
}
/*
* Reads bitmap headers, and palette (if any)
*/
bool BmpReadHeader(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint32 header_size;
assert(info != NULL);
/* Reading BMP header */
if (ReadWord(buffer) != 0x4D42) return false; // signature should be 'BM'
SkipBytes(buffer, 8); // skip file size and reserved
info->offset = ReadDword(buffer);
/* Reading info header */
header_size = ReadDword(buffer);
if (header_size < 12) return false; // info header should be at least 12 bytes long
info->os2_bmp = (header_size == 12); // OS/2 1.x or windows 2.x info header is 12 bytes long
if (info->os2_bmp) {
info->width = ReadWord(buffer);
info->height = ReadWord(buffer);
header_size -= 8;
} else {
info->width = ReadDword(buffer);
info->height = ReadDword(buffer);
header_size -= 12;
}
if (ReadWord(buffer) != 1) return false; // BMP can have only 1 plane
info->bpp = ReadWord(buffer);
if (info->bpp != 1 && info->bpp != 4 && info->bpp != 8 && info->bpp != 24) {
/* Only 1 bpp, 4 bpp, 8bpp and 24 bpp bitmaps are supported */
return false;
}
/* Reads compression method if available in info header*/
if ((header_size -= 4) >= 4) {
info->compression = ReadDword(buffer);
header_size -= 4;
}
/* Only 4-bit and 8-bit rle compression is supported */
if (info->compression > 2 || (info->compression > 0 && !(info->bpp == 4 || info->bpp == 8))) return false;
if (info->bpp <= 8) {
uint i;
/* Reads number of colors if available in info header */
if (header_size >= 16) {
SkipBytes(buffer, 12); // skip image size and resolution
info->palette_size = ReadDword(buffer); // number of colors in palette
SkipBytes(buffer, header_size - 16); // skip the end of info header
}
if (info->palette_size == 0) info->palette_size = 1 << info->bpp;
data->palette = calloc(info->palette_size, sizeof(*(data->palette)));
if (data->palette == NULL) return false;
for (i = 0; i < info->palette_size; i++) {
data->palette[i].b = ReadByte(buffer);
data->palette[i].g = ReadByte(buffer);
data->palette[i].r = ReadByte(buffer);
if (!info->os2_bmp) SkipBytes(buffer, 1); // unused
}
}
return buffer->real_pos <= info->offset;
}
/*
* Reads the bitmap
* 1 bpp and 4 bpp bitmaps are converted to 8 bpp bitmaps
*/
bool BmpReadBitmap(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
assert(info != NULL && data != NULL);
data->bitmap = calloc(info->width * info->height, ((info->bpp == 24) ? 3 : 1) * sizeof(byte));
if (data->bitmap == NULL) return false;
/* Load image */
SetStreamOffset(buffer, info->offset);
switch (info->compression) {
case 0: // no compression
switch (info->bpp) {
case 1: return BmpRead1(buffer, info, data);
case 4: return BmpRead4(buffer, info, data);
case 8: return BmpRead8(buffer, info, data);
case 24: return BmpRead24(buffer, info, data);
default: NOT_REACHED(); return false;
}
case 1: return BmpRead8Rle(buffer, info, data); // 8-bit RLE compression
case 2: return BmpRead4Rle(buffer, info, data); // 4-bit RLE compression
default: NOT_REACHED(); return false;
}
}
void BmpDestroyData(BmpData *data)
{
assert(data != NULL);
free(data->palette);
free(data->bitmap);
}

36
bmp.h
View File

@@ -1,36 +0,0 @@
/* $Id$ */
#ifndef BMP_H
#define BMP_H
typedef struct {
uint32 offset; ///< offset of bitmap data from .bmp file begining
uint32 width; ///< bitmap width
uint32 height; ///< bitmap height
bool os2_bmp; ///< true if OS/2 1.x or windows 2.x bitmap
uint16 bpp; ///< bits per pixel
uint32 compression; ///< compression method (0 = none, 1 = 8-bit RLE, 2 = 4-bit RLE)
uint32 palette_size; ///< number of colors in palette
} BmpInfo;
typedef struct {
Colour *palette;
byte *bitmap;
} BmpData;
#define BMP_BUFFER_SIZE 1024
typedef struct {
byte data[BMP_BUFFER_SIZE];
int pos;
int read;
FILE *file;
uint real_pos;
} BmpBuffer;
void BmpInitializeBuffer(BmpBuffer *buffer, FILE *file);
bool BmpReadHeader(BmpBuffer *buffer, BmpInfo *info, BmpData *data);
bool BmpReadBitmap(BmpBuffer *buffer, BmpInfo *info, BmpData *data);
void BmpDestroyData(BmpData *data);
#endif /* BMP_H */

View File

@@ -1,32 +0,0 @@
/* $Id$ */
/** @file bridge.h Header file for bridges */
#ifndef BRIDGE_H
#define BRIDGE_H
enum {
MAX_BRIDGES = 13
};
/** Struct containing information about a single bridge type
*/
typedef struct Bridge {
Year avail_year; ///< the year in which the bridge becomes available
byte min_length; ///< the minimum length of the bridge (not counting start and end tile)
byte max_length; ///< the maximum length of the bridge (not counting start and end tile)
uint16 price; ///< the relative price of the bridge
uint16 speed; ///< maximum travel speed
PalSpriteID sprite; ///< the sprite which is used in the GUI (possibly with a recolor sprite)
StringID material; ///< the string that contains the bridge description
PalSpriteID **sprite_table; ///< table of sprites for drawing the bridge
byte flags; ///< bit 0 set: disable drawing of far pillars.
} Bridge;
extern const Bridge orig_bridge[MAX_BRIDGES];
extern Bridge _bridge[MAX_BRIDGES];
uint GetBridgeFoundation(Slope tileh, Axis axis);
uint GetBridgeHeightRamp(TileIndex t);
#endif /* BRIDGE_H */

View File

@@ -1,11 +1,6 @@
/* $Id$ */
/** @file bridge_gui.c Graphical user interface for bridge construction*/
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "table/strings.h"
#include "functions.h"
#include "map.h"
#include "window.h"
#include "gui.h"
@@ -13,19 +8,23 @@
#include "gfx.h"
#include "command.h"
#include "sound.h"
#include "variables.h"
#include "bridge.h"
static struct BridgeData {
uint count;
int count;
TileIndex start_tile;
TileIndex end_tile;
byte type;
byte indexes[MAX_BRIDGES];
int32 costs[MAX_BRIDGES];
} _bridgedata;
} _bridge;
void CcBuildBridge(bool success, TileIndex tile, uint32 p1, uint32 p2)
extern const uint16 _bridge_type_price_mod[MAX_BRIDGES];
extern const PalSpriteID _bridge_sprites[MAX_BRIDGES];
extern const uint16 _bridge_speeds[MAX_BRIDGES];
extern const StringID _bridge_material[MAX_BRIDGES];
void CcBuildBridge(bool success, uint tile, uint32 p1, uint32 p2)
{
if (success) SndPlayTileFx(SND_27_BLACKSMITH_ANVIL, tile);
}
@@ -33,35 +32,34 @@ void CcBuildBridge(bool success, TileIndex tile, uint32 p1, uint32 p2)
static void BuildBridge(Window *w, int i)
{
DeleteWindow(w);
DoCommandP(_bridgedata.end_tile, _bridgedata.start_tile,
_bridgedata.indexes[i] | (_bridgedata.type << 8), CcBuildBridge,
DoCommandP(_bridge.end_tile, _bridge.start_tile, _bridge.indexes[i] | (_bridge.type << 8), CcBuildBridge,
CMD_BUILD_BRIDGE | CMD_AUTO | CMD_MSG(STR_5015_CAN_T_BUILD_BRIDGE_HERE));
}
static void BuildBridgeWndProc(Window *w, WindowEvent *e)
{
switch (e->event) {
switch(e->event) {
case WE_PAINT: {
uint i;
int i;
DrawWindowWidgets(w);
for (i = 0; i < 4 && i + w->vscroll.pos < _bridgedata.count; i++) {
const Bridge *b = &_bridge[_bridgedata.indexes[i + w->vscroll.pos]];
for(i=0; i < 4 && i + w->vscroll.pos < _bridge.count; i++) {
int ind = _bridge.indexes[i + w->vscroll.pos];
SetDParam(2, _bridgedata.costs[i + w->vscroll.pos]);
SetDParam(1, b->speed);
SetDParam(0, b->material);
DrawSprite(b->sprite, 3, 15 + i * 22);
SetDParam(2, _bridge.costs[i + w->vscroll.pos]);
SetDParam(1, (_bridge_speeds[ind] >> 4) * 10);
SetDParam(0, _bridge_material[ind]);
DrawSprite(_bridge_sprites[ind], 3, 15 + i * 22);
DrawString(44, 15 + i * 22 , STR_500D, 0);
DrawString(44, 15 + i*22 , STR_500D, 0);
}
} break;
case WE_KEYPRESS: {
uint i = e->we.keypress.keycode - '1';
if (i < 9 && i < _bridgedata.count) {
e->we.keypress.cont = false;
uint i = e->keypress.keycode - '1';
if (i < 9 && i < (uint)_bridge.count) {
e->keypress.cont = false;
BuildBridge(w, i);
}
@@ -69,9 +67,9 @@ static void BuildBridgeWndProc(Window *w, WindowEvent *e)
}
case WE_CLICK:
if (e->we.click.widget == 2) {
uint ind = ((int)e->we.click.pt.y - 14) / 22;
if (ind < 4 && (ind += w->vscroll.pos) < _bridgedata.count)
if (e->click.widget == 2) {
uint ind = ((int)e->click.pt.y - 14) / 22;
if (ind < 4 && (ind += w->vscroll.pos) < (uint)_bridge.count)
BuildBridge(w, ind);
}
break;
@@ -79,16 +77,16 @@ static void BuildBridgeWndProc(Window *w, WindowEvent *e)
}
static const Widget _build_bridge_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 199, 0, 13, STR_100D_SELECT_RAIL_BRIDGE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_MATRIX, RESIZE_NONE, 7, 0, 187, 14, 101, 0x401, STR_101F_BRIDGE_SELECTION_CLICK},
{ WWT_SCROLLBAR, RESIZE_NONE, 7, 188, 199, 14, 101, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 199, 0, 13, STR_100D_SELECT_RAIL_BRIDGE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_MATRIX, RESIZE_NONE, 7, 0, 187, 14, 101, 0x401, STR_101F_BRIDGE_SELECTION_CLICK},
{ WWT_SCROLLBAR, RESIZE_NONE, 7, 188, 199, 14, 101, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WIDGETS_END},
};
static const WindowDesc _build_bridge_desc = {
WDP_AUTO, WDP_AUTO, 200, 102,
WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
-1, -1, 200, 102,
WC_BUILD_BRIDGE,WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_build_bridge_widgets,
BuildBridgeWndProc
@@ -96,72 +94,73 @@ static const WindowDesc _build_bridge_desc = {
static const Widget _build_road_bridge_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 199, 0, 13, STR_1803_SELECT_ROAD_BRIDGE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_MATRIX, RESIZE_NONE, 7, 0, 187, 14, 101, 0x401, STR_101F_BRIDGE_SELECTION_CLICK},
{ WWT_SCROLLBAR, RESIZE_NONE, 7, 188, 199, 14, 101, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 199, 0, 13, STR_1803_SELECT_ROAD_BRIDGE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_MATRIX, RESIZE_NONE, 7, 0, 187, 14, 101, 0x401, STR_101F_BRIDGE_SELECTION_CLICK},
{ WWT_SCROLLBAR, RESIZE_NONE, 7, 188, 199, 14, 101, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WIDGETS_END},
};
static const WindowDesc _build_road_bridge_desc = {
WDP_AUTO, WDP_AUTO, 200, 102,
WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
-1, -1, 200, 102,
WC_BUILD_BRIDGE,WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_build_road_bridge_widgets,
BuildBridgeWndProc
};
void ShowBuildBridgeWindow(TileIndex start, TileIndex end, byte bridge_type)
void ShowBuildBridgeWindow(uint start, uint end, byte bridge_type)
{
uint j = 0;
int j = 0;
int32 ret;
StringID errmsg;
uint16 errmsg;
DeleteWindowById(WC_BUILD_BRIDGE, 0);
_bridgedata.type = bridge_type;
_bridgedata.start_tile = start;
_bridgedata.end_tile = end;
_bridge.type = bridge_type;
_bridge.start_tile = start;
_bridge.end_tile = end;
errmsg = INVALID_STRING_ID;
errmsg = 0xFFFF;
// only query bridge building possibility once, result is the same for all bridges!
// returns CMD_ERROR on failure, and price on success
ret = DoCommand(end, start, (bridge_type << 8), DC_AUTO | DC_QUERY_COST, CMD_BUILD_BRIDGE);
// returns CMD_ERROR on failure, and priCe on success
ret = DoCommandByTile(end, start, (bridge_type << 8), DC_AUTO | DC_QUERY_COST, CMD_BUILD_BRIDGE);
if (CmdFailed(ret)) {
if (ret == CMD_ERROR) {
errmsg = _error_message;
} else {
// check which bridges can be built
int bridge_len; // length of the middle parts of the bridge
int tot_bridgedata_len; // total length of bridge
}
// check which bridges can be built
else {
int bridge_len; // length of the middle parts of the bridge
int tot_bridge_len; // total length of bridge
// get absolute bridge length
bridge_len = GetBridgeLength(start, end);
tot_bridgedata_len = bridge_len + 2;
tot_bridge_len = bridge_len + 2;
tot_bridgedata_len = CalcBridgeLenCostFactor(tot_bridgedata_len);
tot_bridge_len = CalcBridgeLenCostFactor(tot_bridge_len);
for (bridge_type = 0; bridge_type != MAX_BRIDGES; bridge_type++) { // loop for all bridgetypes
for (bridge_type = 0; bridge_type != MAX_BRIDGES; bridge_type++) { // loop for all bridgetypes
if (CheckBridge_Stuff(bridge_type, bridge_len)) {
const Bridge *b = &_bridge[bridge_type];
// bridge is accepted, add to list
// add to terraforming & bulldozing costs the cost of the bridge itself (not computed with DC_QUERY_COST)
_bridgedata.costs[j] = ret + (((int64)tot_bridgedata_len * _price.build_bridge * b->price) >> 8);
_bridgedata.indexes[j] = bridge_type;
_bridge.costs[j] = ret + (((int64)tot_bridge_len * _price.build_bridge * _bridge_type_price_mod[bridge_type]) >> 8);
_bridge.indexes[j] = bridge_type;
j++;
}
}
}
_bridgedata.count = j;
_bridge.count = j;
if (j != 0) {
Window *w = AllocateWindowDesc((_bridgedata.type & 0x80) ? &_build_road_bridge_desc : &_build_bridge_desc);
Window *w = AllocateWindowDesc((_bridge.type & 0x80) ? &_build_road_bridge_desc : &_build_bridge_desc);
w->vscroll.cap = 4;
w->vscroll.count = (byte)j;
} else {
ShowErrorMessage(errmsg, STR_5015_CAN_T_BUILD_BRIDGE_HERE, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);
ShowErrorMessage(errmsg, STR_5015_CAN_T_BUILD_BRIDGE_HERE, TileX(end) * 16, TileY(end) * 16);
}
}

View File

@@ -1,37 +0,0 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "bridge_map.h"
TileIndex GetBridgeEnd(TileIndex tile, DiagDirection dir)
{
TileIndexDiff delta = TileOffsByDiagDir(dir);
assert(DiagDirToAxis(dir) == GetBridgeAxis(tile));
do {
tile += delta;
} while (!IsBridgeRamp(tile));
return tile;
}
TileIndex GetSouthernBridgeEnd(TileIndex t)
{
return GetBridgeEnd(t, AxisToDiagDir(GetBridgeAxis(t)));
}
TileIndex GetOtherBridgeEnd(TileIndex tile)
{
TileIndexDiff delta = TileOffsByDiagDir(GetBridgeRampDirection(tile));
do {
tile += delta;
} while (!IsBridgeRamp(tile));
return tile;
}

View File

@@ -1,235 +0,0 @@
/* $Id$ */
#ifndef BRIDGE_MAP_H
#define BRIDGE_MAP_H
#include "direction.h"
#include "macros.h"
#include "map.h"
#include "rail.h"
#include "road_map.h"
#include "tile.h"
static inline bool IsBridge(TileIndex t)
{
assert(IsTileType(t, MP_TUNNELBRIDGE));
return HASBIT(_m[t].m5, 7);
}
static inline bool IsBridgeTile(TileIndex t)
{
return IsTileType(t, MP_TUNNELBRIDGE) && IsBridge(t);
}
static inline bool IsBridgeRamp(TileIndex t)
{
assert(IsBridgeTile(t));
return !HASBIT(_m[t].m5, 6);
}
static inline bool IsBridgeMiddle(TileIndex t)
{
assert(IsBridgeTile(t));
return HASBIT(_m[t].m5, 6);
}
/**
* Determines which piece of a bridge is contained in the current tile
* @param tile The tile to analyze
* @return the piece
*/
static inline uint GetBridgePiece(TileIndex t)
{
assert(IsBridgeMiddle(t));
return GB(_m[t].m2, 0, 4);
}
/**
* Determines the type of bridge on a tile
* @param tile The tile to analyze
* @return The bridge type
*/
static inline uint GetBridgeType(TileIndex t)
{
assert(IsBridgeTile(t));
return GB(_m[t].m2, 4, 4);
}
/**
* Get the direction pointing onto the bridge
*/
static inline DiagDirection GetBridgeRampDirection(TileIndex t)
{
assert(IsBridgeRamp(t));
return ReverseDiagDir(XYNSToDiagDir((Axis)GB(_m[t].m5, 0, 1), GB(_m[t].m5, 5, 1)));
}
static inline Axis GetBridgeAxis(TileIndex t)
{
assert(IsBridgeMiddle(t));
return (Axis)GB(_m[t].m5, 0, 1);
}
static inline TransportType GetBridgeTransportType(TileIndex t)
{
assert(IsBridgeTile(t));
return (TransportType)GB(_m[t].m5, 1, 2);
}
static inline bool IsClearUnderBridge(TileIndex t)
{
assert(IsBridgeMiddle(t));
return GB(_m[t].m5, 3, 3) == 0;
}
static inline bool IsWaterUnderBridge(TileIndex t)
{
assert(IsBridgeMiddle(t));
return GB(_m[t].m5, 3, 3) == 1;
}
static inline bool IsTransportUnderBridge(TileIndex t)
{
assert(IsBridgeMiddle(t));
return HASBIT(_m[t].m5, 5);
}
static inline TransportType GetTransportTypeUnderBridge(TileIndex t)
{
assert(IsTransportUnderBridge(t));
return (TransportType)GB(_m[t].m5, 3, 2);
}
static inline RoadBits GetRoadBitsUnderBridge(TileIndex t)
{
assert(GetTransportTypeUnderBridge(t) == TRANSPORT_ROAD);
return GetBridgeAxis(t) == AXIS_X ? ROAD_Y : ROAD_X;
}
static inline Track GetRailUnderBridge(TileIndex t)
{
assert(GetTransportTypeUnderBridge(t) == TRANSPORT_RAIL);
return AxisToTrack(OtherAxis(GetBridgeAxis(t)));
}
static inline TrackBits GetRailBitsUnderBridge(TileIndex t)
{
return TrackToTrackBits(GetRailUnderBridge(t));
}
/**
* Finds the end of a bridge in the specified direction starting at a middle tile
*/
TileIndex GetBridgeEnd(TileIndex, DiagDirection);
/**
* Finds the southern end of a bridge starting at a middle tile
*/
TileIndex GetSouthernBridgeEnd(TileIndex t);
/**
* Starting at one bridge end finds the other bridge end
*/
TileIndex GetOtherBridgeEnd(TileIndex);
uint GetBridgeHeight(TileIndex t);
static inline void SetClearUnderBridge(TileIndex t)
{
assert(IsBridgeMiddle(t));
SetTileOwner(t, OWNER_NONE);
SB(_m[t].m5, 3, 3, 0 << 2 | 0);
SB(_m[t].m3, 0, 4, 0);
}
static inline void SetWaterUnderBridge(TileIndex t)
{
assert(IsBridgeMiddle(t));
SetTileOwner(t, OWNER_WATER);
SB(_m[t].m5, 3, 3, 0 << 2 | 1);
SB(_m[t].m3, 0, 4, 0);
}
static inline void SetCanalUnderBridge(TileIndex t, Owner o)
{
assert(IsBridgeMiddle(t));
SetTileOwner(t, o);
SB(_m[t].m5, 3, 3, 0 << 2 | 1);
SB(_m[t].m3, 0, 4, 0);
}
static inline void SetRailUnderBridge(TileIndex t, Owner o, RailType r)
{
assert(IsBridgeMiddle(t));
SetTileOwner(t, o);
SB(_m[t].m5, 3, 3, 1 << 2 | TRANSPORT_RAIL);
SB(_m[t].m3, 0, 4, r);
}
static inline void SetRoadUnderBridge(TileIndex t, Owner o)
{
assert(IsBridgeMiddle(t));
SetTileOwner(t, o);
SB(_m[t].m5, 3, 3, 1 << 2 | TRANSPORT_ROAD);
SB(_m[t].m3, 0, 4, 0);
}
static inline void MakeBridgeRamp(TileIndex t, Owner o, uint bridgetype, DiagDirection d, TransportType tt)
{
uint northsouth = (d == DIAGDIR_NE || d == DIAGDIR_NW);
SetTileType(t, MP_TUNNELBRIDGE);
SetTileOwner(t, o);
_m[t].m2 = bridgetype << 4;
_m[t].m4 = 0;
_m[t].m5 = 1 << 7 | 0 << 6 | northsouth << 5 | tt << 1 | DiagDirToAxis(d);
}
static inline void MakeRoadBridgeRamp(TileIndex t, Owner o, uint bridgetype, DiagDirection d)
{
MakeBridgeRamp(t, o, bridgetype, d, TRANSPORT_ROAD);
_m[t].m3 = 0;
}
static inline void MakeRailBridgeRamp(TileIndex t, Owner o, uint bridgetype, DiagDirection d, RailType r)
{
MakeBridgeRamp(t, o, bridgetype, d, TRANSPORT_RAIL);
_m[t].m3 = r;
}
static inline void MakeBridgeMiddle(TileIndex t, uint bridgetype, uint piece, Axis a, TransportType tt)
{
SetTileType(t, MP_TUNNELBRIDGE);
SetTileOwner(t, OWNER_NONE);
_m[t].m2 = bridgetype << 4 | piece;
_m[t].m3 = 0;
_m[t].m4 = 0;
_m[t].m5 = 1 << 7 | 1 << 6 | 0 << 5 | 0 << 3 | tt << 1 | a;
}
static inline void MakeRoadBridgeMiddle(TileIndex t, uint bridgetype, uint piece, Axis a)
{
MakeBridgeMiddle(t, bridgetype, piece, a, TRANSPORT_ROAD);
}
static inline void MakeRailBridgeMiddle(TileIndex t, uint bridgetype, uint piece, Axis a, RailType r)
{
MakeBridgeMiddle(t, bridgetype, piece, a, TRANSPORT_RAIL);
SB(_m[t].m3, 4, 4, r);
}
#endif /* BRIDGE_MAP_H */

View File

@@ -1,492 +0,0 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "aircraft.h"
#include "debug.h"
#include "functions.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "window.h"
#include "gui.h"
#include "vehicle.h"
#include "gfx.h"
#include "station.h"
#include "command.h"
#include "engine.h"
#include "player.h"
#include "depot.h"
#include "airport.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "date.h"
#include "strings.h"
enum BuildVehicleWidgets {
BUILD_VEHICLE_WIDGET_CLOSEBOX = 0,
BUILD_VEHICLE_WIDGET_CAPTION,
BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING,
BUILD_VEHICLE_WIDGET_SORT_TEXT,
BUILD_VEHICLE_WIDGET_SORT_DROPDOWN,
BUILD_VEHICLE_WIDGET_LIST,
BUILD_VEHICLE_WIDGET_SCROLLBAR,
BUILD_VEHICLE_WIDGET_PANEL,
BUILD_VEHICLE_WIDGET_BUILD,
BUILD_VEHICLE_WIDGET_RENAME,
BUILD_VEHICLE_WIDGET_RESIZE,
};
static const Widget _build_vehicle_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 14, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW },
{ WWT_CAPTION, RESIZE_NONE, 14, 11, 239, 0, 13, STR_A005_NEW_AIRCRAFT, STR_018C_WINDOW_TITLE_DRAG_THIS },
{ WWT_PUSHTXTBTN, RESIZE_NONE, 14, 0, 80, 14, 25, STR_SORT_BY, STR_SORT_ORDER_TIP},
{ WWT_PANEL, RESIZE_NONE, 14, 81, 227, 14, 25, 0x0, STR_SORT_CRITERIA_TIP},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 228, 239, 14, 25, STR_0225, STR_SORT_CRITERIA_TIP},
{ WWT_MATRIX, RESIZE_BOTTOM, 14, 0, 227, 26, 121, 0x401, STR_A025_AIRCRAFT_SELECTION_LIST },
{ WWT_SCROLLBAR, RESIZE_BOTTOM, 14, 228, 239, 26, 121, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST },
{ WWT_PANEL, RESIZE_TB, 14, 0, 239, 122, 213, 0x0, STR_NULL },
{ WWT_PUSHTXTBTN, RESIZE_TB, 14, 0, 114, 214, 225, STR_A006_BUILD_AIRCRAFT, STR_A026_BUILD_THE_HIGHLIGHTED_AIRCRAFT },
{ WWT_PUSHTXTBTN, RESIZE_TB, 14, 115, 227, 214, 225, STR_A037_RENAME, STR_A038_RENAME_AIRCRAFT_TYPE },
{ WWT_RESIZEBOX, RESIZE_TB, 14, 228, 239, 214, 225, 0x0, STR_RESIZE_BUTTON },
{ WIDGETS_END},
};
static bool _internal_sort_order; // descending/ascending
static byte _last_sort_criteria = 0;
static bool _last_sort_order = false;
static int CDECL EngineNumberSorter(const void *a, const void *b)
{
const EngineID va = *(const EngineID*)a;
const EngineID vb = *(const EngineID*)b;
int r = va - vb;
return _internal_sort_order ? -r : r;
}
static int CDECL EngineIntroDateSorter(const void *a, const void *b)
{
const int va = GetEngine(*(const EngineID*)a)->intro_date;
const int vb = GetEngine(*(const EngineID*)b)->intro_date;
const int r = va - vb;
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
}
return _internal_sort_order ? -r : r;
}
static int CDECL EngineNameSorter(const void *a, const void *b)
{
static EngineID last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE };
static char last_name[2][64] = { "\0", "\0" };
const EngineID va = *(const EngineID*)a;
const EngineID vb = *(const EngineID*)b;
int r;
if (va != last_engine[0]) {
last_engine[0] = va;
GetString(last_name[0], GetCustomEngineName(va), lastof(last_name[0]));
}
if (vb != last_engine[1]) {
last_engine[1] = vb;
GetString(last_name[1], GetCustomEngineName(vb), lastof(last_name[1]));
}
r = strcmp(last_name[0], last_name[1]); // sort by name
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
}
return _internal_sort_order ? -r : r;
}
static int CDECL EngineReliabilitySorter(const void *a, const void *b)
{
const int va = GetEngine(*(const EngineID*)a)->reliability;
const int vb = GetEngine(*(const EngineID*)b)->reliability;
const int r = va - vb;
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
}
return _internal_sort_order ? -r : r;
}
/* Aircraft sorting functions */
static int CDECL AircraftEngineCostSorter(const void *a, const void *b)
{
const int va = AircraftVehInfo(*(const EngineID*)a)->base_cost;
const int vb = AircraftVehInfo(*(const EngineID*)b)->base_cost;
int r = va - vb;
return _internal_sort_order ? -r : r;
}
static int CDECL AircraftEngineSpeedSorter(const void *a, const void *b)
{
const int va = AircraftVehInfo(*(const EngineID*)a)->max_speed;
const int vb = AircraftVehInfo(*(const EngineID*)b)->max_speed;
const int r = va - vb;
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
}
return _internal_sort_order ? -r : r;
}
static int CDECL AircraftEngineRunningCostSorter(const void *a, const void *b)
{
const int va = AircraftVehInfo(*(const EngineID*)a)->running_cost;
const int vb = AircraftVehInfo(*(const EngineID*)b)->running_cost;
const int r = va - vb;
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
}
return _internal_sort_order ? -r : r;
}
static int CDECL AircraftEngineCargoSorter(const void *a, const void *b)
{
const int va = AircraftVehInfo(*(const EngineID*)a)->passenger_capacity;
const int vb = AircraftVehInfo(*(const EngineID*)b)->passenger_capacity;
const int r = va - vb;
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
}
return _internal_sort_order ? -r : r;
}
static EngList_SortTypeFunction * const _aircraft_sorter[] = {
&EngineNumberSorter,
&AircraftEngineCostSorter,
&AircraftEngineSpeedSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&AircraftEngineRunningCostSorter,
&EngineReliabilitySorter,
&AircraftEngineCargoSorter,
};
static const StringID _aircraft_sort_listing[] = {
STR_ENGINE_SORT_ENGINE_ID,
STR_ENGINE_SORT_COST,
STR_SORT_BY_MAX_SPEED,
STR_ENGINE_SORT_INTRO_DATE,
STR_SORT_BY_DROPDOWN_NAME,
STR_ENGINE_SORT_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_ENGINE_SORT_CARGO_CAPACITY,
INVALID_STRING_ID
};
/**
* Draw the purchase info details of an aircraft at a given location.
* @param x,y location where to draw the info
* @param engine_number the engine of which to draw the info of
*/
void DrawAircraftPurchaseInfo(int x, int y, uint w, EngineID engine_number)
{
const AircraftVehicleInfo *avi = AircraftVehInfo(engine_number);
const Engine *e = GetEngine(engine_number);
CargoID cargo;
YearMonthDay ymd;
ConvertDateToYMD(e->intro_date, &ymd);
/* Purchase cost - Max speed */
SetDParam(0, avi->base_cost * (_price.aircraft_base>>3)>>5);
SetDParam(1, avi->max_speed * 128 / 10);
DrawString(x, y, STR_PURCHASE_INFO_COST_SPEED, 0);
y += 10;
/* Cargo capacity */
cargo = FindFirstRefittableCargo(engine_number);
if (cargo == CT_INVALID || cargo == CT_PASSENGERS) {
SetDParam(0, avi->passenger_capacity);
SetDParam(1, avi->mail_capacity);
DrawString(x, y, STR_PURCHASE_INFO_AIRCRAFT_CAPACITY, 0);
} else {
/* Note, if the default capacity is selected by the refit capacity
* callback, then the capacity shown is likely to be incorrect. */
SetDParam(0, cargo);
SetDParam(1, AircraftDefaultCargoCapacity(cargo, engine_number));
SetDParam(2, STR_9842_REFITTABLE);
DrawString(x, y, STR_PURCHASE_INFO_CAPACITY, 0);
}
y += 10;
/* Running cost */
SetDParam(0, avi->running_cost * _price.aircraft_running >> 8);
DrawString(x, y, STR_PURCHASE_INFO_RUNNINGCOST, 0);
y += 10;
/* Design date - Life length */
SetDParam(0, ymd.year);
SetDParam(1, e->lifelength);
DrawString(x, y, STR_PURCHASE_INFO_DESIGNED_LIFE, 0);
y += 10;
/* Reliability */
SetDParam(0, e->reliability * 100 >> 16);
DrawString(x, y, STR_PURCHASE_INFO_RELIABILITY, 0);
y += 10;
/* Additional text from NewGRF */
y += ShowAdditionalText(x, y, w, engine_number);
y += ShowRefitOptionsList(x, y, w, engine_number);
}
void DrawAircraftImage(const Vehicle *v, int x, int y, VehicleID selection)
{
PalSpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
DrawSprite(GetAircraftImage(v, DIR_W) | pal, x + 25, y + 10);
if (v->subtype == 0) {
SpriteID rotor_sprite = GetCustomRotorSprite(v, true);
if (rotor_sprite == 0) rotor_sprite = SPR_ROTOR_STOPPED;
DrawSprite(rotor_sprite, x + 25, y + 5);
}
if (v->index == selection) {
DrawFrameRect(x - 1, y - 1, x + 58, y + 21, 0xF, FR_BORDERONLY);
}
}
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, _backup_orders_data);
}
ShowAircraftViewWindow(v);
}
}
static void GenerateBuildAircraftList(Window *w)
{
EngineID eid, sel_id;
buildvehicle_d *bv = &WP(w, buildvehicle_d);
EngList_RemoveAll(&bv->eng_list);
/* Make list of all available planes.
* Also check to see if the previously selected plane is still available,
* and if not, reset selection to INVALID_ENGINE. This could be the case
* when planes become obsolete and are removed */
sel_id = INVALID_ENGINE;
for (eid = AIRCRAFT_ENGINES_INDEX; eid < AIRCRAFT_ENGINES_INDEX + NUM_AIRCRAFT_ENGINES; eid++) {
if (IsEngineBuildable(eid, VEH_Aircraft, _local_player)) {
const AircraftVehicleInfo *avi = AircraftVehInfo(eid);
switch (bv->filter.acc_planes) {
case HELICOPTERS_ONLY:
if (avi->subtype != 0) continue; // if not helicopter
break;
case AIRCRAFT_ONLY:
if (avi->subtype == 0) continue; // if helicopter
break;
case ALL: break;
}
EngList_Add(&bv->eng_list, eid);
if (eid == bv->sel_engine) sel_id = eid;
}
}
bv->sel_engine = sel_id;
}
static void GenerateBuildList(Window *w)
{
buildvehicle_d *bv = &WP(w, buildvehicle_d);
switch (bv->vehicle_type) {
case VEH_Aircraft:
GenerateBuildAircraftList(w);
_internal_sort_order = bv->descending_sort_order;
EngList_Sort(&bv->eng_list, _aircraft_sorter[bv->sort_criteria]);
break;
default: NOT_REACHED();
}
}
static void DrawBuildAircraftWindow(Window *w)
{
const buildvehicle_d *bv = &WP(w, buildvehicle_d);
SetWindowWidgetDisabledState(w, BUILD_VEHICLE_WIDGET_BUILD, w->window_number == 0);
SetVScrollCount(w, EngList_Count(&bv->eng_list));
DrawWindowWidgets(w);
{
int x = 2;
int y = 27;
EngineID selected_id = bv->sel_engine;
EngineID eid = w->vscroll.pos;
uint16 max = min(w->vscroll.pos + w->vscroll.cap, EngList_Count(&bv->eng_list));
for (; eid < max; eid++) {
const EngineID engine = bv->eng_list[eid];
DrawString(x + 62, y + 7, GetCustomEngineName(engine), engine == selected_id ? 0xC : 0x10);
DrawAircraftEngine(x + 29, y + 10, engine, GetEnginePalette(engine, _local_player));
y += 24;
}
if (selected_id != INVALID_ENGINE) {
const Widget *wi = &w->widget[BUILD_VEHICLE_WIDGET_PANEL];
DrawAircraftPurchaseInfo(x, wi->top + 1, wi->right - wi->left - 2, selected_id);
}
}
DrawString(85, 15, _aircraft_sort_listing[bv->sort_criteria], 0x10);
DoDrawString(bv->descending_sort_order ? DOWNARROW : UPARROW, 69, 15, 0x10);
}
static void BuildAircraftClickEvent(Window *w, WindowEvent *e)
{
buildvehicle_d *bv = &WP(w, buildvehicle_d);
switch (e->we.click.widget) {
case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING:
bv->descending_sort_order ^= true;
_last_sort_order = bv->descending_sort_order;
GenerateBuildList(w);
SetWindowDirty(w);
break;
case BUILD_VEHICLE_WIDGET_LIST: {
uint i = (e->we.click.pt.y - 26) / 24 + w->vscroll.pos;
uint num_items = EngList_Count(&bv->eng_list);
bv->sel_engine = (i < num_items) ? bv->eng_list[i] : INVALID_ENGINE;
SetWindowDirty(w);
break;
}
case BUILD_VEHICLE_WIDGET_SORT_TEXT: case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN:/* Select sorting criteria dropdown menu */
ShowDropDownMenu(w, _aircraft_sort_listing, bv->sort_criteria, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN, 0, 0);
return;
case BUILD_VEHICLE_WIDGET_BUILD: {
EngineID sel_eng = bv->sel_engine;
if (sel_eng != INVALID_ENGINE) {
DoCommandP(w->window_number, sel_eng, 0, CcBuildAircraft, CMD_BUILD_AIRCRAFT | CMD_MSG(STR_A008_CAN_T_BUILD_AIRCRAFT));
}
break;
}
case BUILD_VEHICLE_WIDGET_RENAME: {
EngineID sel_eng = bv->sel_engine;
if (sel_eng != INVALID_ENGINE) {
bv->rename_engine = sel_eng;
ShowQueryString(GetCustomEngineName(sel_eng), STR_A039_RENAME_AIRCRAFT_TYPE, 31, 160, w->window_class, w->window_number, CS_ALPHANUMERAL);
}
break;
}
}
}
static void NewAircraftWndProc(Window *w, WindowEvent *e)
{
buildvehicle_d *bv = &WP(w, buildvehicle_d);
switch (e->event) {
case WE_INVALIDATE_DATA:
GenerateBuildList(w);
break;
case WE_DESTROY:
EngList_Destroy(&bv->eng_list);
break;
case WE_PAINT:
DrawBuildAircraftWindow(w);
break;
case WE_CLICK:
BuildAircraftClickEvent(w, e);
break;
case WE_ON_EDIT_TEXT: {
if (e->we.edittext.str[0] != '\0') {
_cmd_text = e->we.edittext.str;
DoCommandP(0, bv->rename_engine, 0, NULL, CMD_RENAME_ENGINE | CMD_MSG(STR_A03A_CAN_T_RENAME_AIRCRAFT_TYPE));
}
break;
}
case WE_DROPDOWN_SELECT: /* we have selected a dropdown item in the list */
if (bv->sort_criteria != e->we.dropdown.index) {
bv->sort_criteria = _last_sort_criteria = e->we.dropdown.index;
GenerateBuildList(w);
}
SetWindowDirty(w);
break;
case WE_RESIZE:
w->vscroll.cap += e->we.sizing.diff.y / 24;
w->widget[BUILD_VEHICLE_WIDGET_LIST].data = (w->vscroll.cap << 8) + 1;
break;
}
}
static const WindowDesc _build_vehicle_desc = {
WDP_AUTO, WDP_AUTO, 240, 226,
WC_BUILD_VEHICLE,0,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_build_vehicle_widgets,
NewAircraftWndProc
};
void ShowBuildVehicleWindow(TileIndex tile, byte type)
{
buildvehicle_d *bv;
Window *w;
DeleteWindowById(WC_BUILD_VEHICLE, tile);
w = AllocateWindowDescFront(&_build_vehicle_desc, tile);
if (w == NULL) return;
w->caption_color = (tile != 0) ? GetTileOwner(tile) : _local_player;
w->resize.step_height = GetVehicleListHeight(type);
w->vscroll.cap = 4;
w->widget[BUILD_VEHICLE_WIDGET_LIST].data = (w->vscroll.cap << 8) + 1;
bv = &WP(w, buildvehicle_d);
EngList_Create(&bv->eng_list);
bv->sel_engine = INVALID_ENGINE;
bv->sort_criteria = _last_sort_criteria;
bv->descending_sort_order = _last_sort_order;
bv->vehicle_type = type;
switch (type) {
case VEH_Aircraft: {
byte acc_planes = (tile == 0) ? ALL : GetAirport(GetStationByTile(tile)->airport_type)->acc_planes;
bv->filter.acc_planes = acc_planes;
break;
}
default: NOT_REACHED();
}
GenerateBuildList(w);
/* Select the first plane in the list as default when opening the window */
if (EngList_Count(&bv->eng_list) > 0) bv->sel_engine = bv->eng_list[0];
}

View File

@@ -1,8 +1,5 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "callback_table.h"
#include "ttd.h"
#include "functions.h"
// If you add a callback for DoCommandP, also add the callback in here
@@ -11,7 +8,6 @@
/* aircraft_gui.c */
CommandCallback CcBuildAircraft;
CommandCallback CcCloneAircraft;
/* airport_gui.c */
CommandCallback CcBuildAirport;
@@ -23,15 +19,12 @@ CommandCallback CcBuildBridge;
CommandCallback CcBuildDocks;
CommandCallback CcBuildCanal;
/* depot_gui.c */
CommandCallback CcCloneVehicle;
/* main_gui.c */
CommandCallback CcPlaySound10;
CommandCallback CcPlaceSign;
CommandCallback CcTerraform;
//CommandCallback CcDemolish;
CommandCallback CcBuildTown;
CommandCallback CcGiveMoney;
/* rail_gui.c */
CommandCallback CcPlaySound1E;
@@ -46,18 +39,13 @@ CommandCallback CcRoadDepot;
/* roadveh_gui.c */
CommandCallback CcBuildRoadVeh;
CommandCallback CcCloneRoadVeh;
/* ship_gui.c */
CommandCallback CcBuildShip;
CommandCallback CcCloneShip;
/* train_gui.c */
CommandCallback CcBuildWagon;
CommandCallback CcBuildLoco;
CommandCallback CcCloneTrain;
CommandCallback CcAI;
CommandCallback *_callback_table[] = {
/* 0x00 */ NULL,
@@ -80,14 +68,7 @@ CommandCallback *_callback_table[] = {
/* 0x11 */ CcPlaySound1D,
/* 0x12 */ CcPlaySound1E,
/* 0x13 */ CcStation,
/* 0x14 */ CcTerraform,
/* 0x15 */ CcCloneAircraft,
/* 0x16 */ CcCloneRoadVeh,
/* 0x17 */ CcCloneShip,
/* 0x18 */ CcCloneTrain,
/* 0x19 */ CcAI,
/* 0x1A */ CcCloneVehicle,
/* 0x1B */ CcGiveMoney,
/* 0x14 */ CcTerraform
};
const int _callback_table_count = lengthof(_callback_table);

View File

@@ -1,11 +1,7 @@
/* $Id$ */
#ifndef CALLBACK_TABLE_H
#define CALLBACK_TABLE_H
#include "command.h"
extern CommandCallback *_callback_table[];
extern const int _callback_table_count;
#endif /* CALLBACK_TABLE_H */
#endif

View File

@@ -1,667 +1,3 @@
0.5.3-RC2 (2007-07-07)
------------------------------------------------------------------------
- Fix: Visual glitches when a window is resized in the WE_CREATE callback (r10465)
- Fix: [Windows] _wnd.has_focus was not properly set after using ALT-TAB [FS#962] (r10399)
0.5.3-RC1 (2007-06-28)
------------------------------------------------------------------------
- Feature: Make the client list window (for network games) stickyable (r10293)
- Feature: console command to get the current game date (r10137)
- Fix: Waypoints could be renamed when you are not the owner (r10368)
- Fix: Smooth economy did not close primary industries and it allowed increasing of production of industries that should not have rising productions (r10348, r10347, r10290)
- Fix: Acceleration for trains on slopes is not calculated properly [FS#786] (r10344, r10317)
- Fix: The 'old' pathfinders (OPF and NPF) for road vehicles could not find a path when in a tunnel [FS#290] (r10345)
- Fix: Only add the autoreplace menu when autoreplace actually knows about the group [FS#880] (r10337)
- Fix: Signal state sometimes not properly set when the signal "pathfinder" reached the end of a line [FS#910] (r10336)
- Fix: News messages were shown over the endgame/highscore windows [FS#943] (r10333)
- Fix: Rail could be destroyed when building tunnels (r10306)
- Fix: Flush the output of the dedicated server console (r10295)
- Fix: The "pause" key did not work in the scenario editor (r10294)
- Fix: Age non-front engines too (so when you move engines around in the depot they do not get age 0 when they are much older [FS#202] (r10288)
- Fix: Do not make everyone spectator if 1 joining client failed to create new company (r10284)
- Fix: Remove invalid characters (for the file system) from savegame names [FS#916, FS#850] (r10272, r10116)
- Fix: Some old savegames could have the wrong bits unset (r10268, r10147)
- Fix: Do not look in every direction for tunnels when building one, one direction is enough (r10258)
- Fix: [Windows] Do not mess desktop when using ALT-TAB [FS#876] (r10251, r10186)
- Fix: Take the age of the front vehicle for station rating (r10246)
- Fix: Terraforming wipes out canals. Now you always have to remove the canal before terraforming, instead of "just" removing the canal [FS#594] (r10240)
- Fix: Only 2 trains could crash at one time as collision checking stopped on the first hit. This could technically cause desyncs in network games as the collision hash order is not guaranteed [FS#892] (r10222)
- Fix: Land under foundations was terraform when it shouldn't be terraformed [FS#882, FS#890] (r10219)
- Fix: Do not make a 270 degree turn on the international airport when a 90 degree turn is enough (r10187)
- Fix: Crash when trying to get the aircraft movement state of an aircraft going to a just deleted airport [FS#874] (r10165)
- Fix: Airports did not flood when there are aircraft on the airport [FS#601] (r10155)
- Fix: Some vehicles were not drawn when having a high resolution and a high zoom-out level [FS#870] (r10154)
- Fix: Vehicles disappear when crossing certain tiles [FS#869] (r10153)
- Fix: Train disconnects in some old TTD savegames [FS#862] (10151)
- Fix: OpenTTD assumes that the resolution is at least 1 by 1, so force the resolution to be always at least 1 by 1 (r10139)
- Fix: When you got a sufficiently small resolution, there is a possibility for a division by zero when a sound is played (r10138)
- Fix: When removing a dock, a ship will always try to reach the old location of the dock even when it cannot anymore because it the old location of the dock is now land instead of water [FS#810] (r10131)
- Fix: SetCurrentGrfLangID returned the wrong language ids for most languages (r10130)
- Fix: Some NewGRFs use the same (unused in the "current" climate) sprite IDs. Normally this gives some artefacts, but when one NewGRF expects it to be a sprite and another NewGRF overwrites it with a non-sprite nasty things happen (drawing a non-sprite crashes OTTD) [FS#838] (r10109)
- Fix: Multiple subsequent "give money" actions could result in duplicate messages that money has been transfered when it only happened once, or tell you paid money when you did not [FS#834, FS#839] (r10087, r10085)
- Fix: "Deactivate Electrified Railways" did not work [FS#836] (10083)
- Fix: Memory leaks in the networking code [FS#846, FS#844] (r10082, r10075)
- Fix: Coverage area highlight was still show when it was turned off for docks [FS#835] (r10068)
- Fix: Do not use override engine type for articulated wagon parts (r10048)
- Fix: Sprite resulting from '?' substitution was reloaded into the cache entry for SPR_IMG_QUERY instead of the original sprite cache entry. This resulted in unaccounted missing sprite cache memory, and was exacerbated because the original missing sprite was not cached, so it did it again and again and again. Slowdowns and boom (r10038)
- Fix: One could build on (some) slopes when building on slopes was disabled [FS#823] (r10030)
- Fix: When deleting the first engine of a train with multiple engines, only reopen the train window if the player had the original train window open. This fixes 'random' windows opening for multiple players of the same company (r10028)
- Fix: When selling trains, if there were no wagons between multiheaded engines the rear part could be checked despite having already been deleted (10023)
0.5.2 (2007-05-29)
------------------------------------------------------------------------
- Feature: Add threading support for MorphOS (r9759)
- Fix: Bridges and tunnels were not always removed on bankruptcy, thus leaving tunnels/bridges with an invalid owner that would crash the game when clicking with the query tool on them (r9966)
- Fix: Null pointer dereference under MorphOS and AmigaOS (r9861)
0.5.2-RC1 (2007-05-16)
------------------------------------------------------------------------
- Feature: Windows 95/98/ME check in Windows 2000/XP/2003/Vista builds (r9834)
- Feature: Add password protected status to 'players' (network server) console command (r9771)
- Feature: Add server_lang in [network] section of openttd.cfg (r9716)
- Fix: Loading some TTDP savegames caused an instant assertion on loading (r9857)
- Fix: [NewGRF] Catch occurance of division-by-zero in varaction handling (r9837)
- Fix: Only non dedicated servers cannot have 0 players [FS#765] (r9785)
- Fix: Remove arbitrary limit on length of NewGRF strings (r9775)
- Fix: [NewGRF] Ignore axis-bit of station tile layouts [FS#756] (r9758)
- Fix: [win32] Dead key and open/close console. (r9728)
- Fix: When you have closed the "Load game"/"New game" windows which you started from the "start server" menu, you shouldn't start a server when starting a new game [SF#1244842] (r9757)
- Fix: Trains were lost after autorenewal/autoreplace [FS#732] (r9753)
- Fix: Stop flooded towns from building roads on water [FS#598] (r9743)
- Fix: Station signs were not resized when the language changed [FS#672] (r9741)
- Fix: In news history, newlines were not replaced with spaces [FS#677] (r9731)
- Fix: Crash when destroying bridge with train partially on it [FS#738] (r9726)
- Fix: Planes made a 270 degree turn instead of a 90 degree turn on the southern runway of the intercontinental airport [FS#743] (r9725)
- Fix: In-game private messages did not work for clients with high ClientIDs (r9719)
- Fix: Do not allow building of rail vehicles whose railtype is not available (r9718)
- Fix: [YAPF] The guessed path was ignored for ships [FS#736] (r9694)
0.5.1 (2007-04-20)
------------------------------------------------------------------------
(None)
0.5.1-RC3 (2007-04-17)
------------------------------------------------------------------------
- Feature: Add list_patches to console commands; shows all patches and values (r9565)
- Fix: Select "Custom" in the difficulty settings gui when changing a setting [FS#733] (r9647)
- Fix: Building rail on steep slopes ignored build_on_slopes patch setting (r9602)
- Fix: Wrong characters in Finnish town names (r9641)
- Fix: When checking for no vehicle on ground-tiles, do not take into account vehicles that are in the air (r9542)
- Fix: Bankrupt AIs no longer buy over themselves (also added safeguards to prevent in future) (r9540 / r9541)
- Fix: When company is removed, sell all shares of the and in the company (r9533)
- Fix: Crash when 2 or more clients joined at roughly the same time (r9529)
- Fix: Custom currency was overwritten and fix euro introduction (r9467, r9469)
- Fix: Values of diff_custom and snow_line in .cfg were not checked properly (r9455)
- Fix: When deleting a vehicle which has shared orders with one more vehicle and no orders, segfaulted (r9429)
0.5.1-RC2 (2007-03-23)
------------------------------------------------------------------------
- Fix: crashes when the chatbox would be drawn outside of the main window [FS#701] (r9420)
- Fix: reading out of an array caused a segmentation fault [FS#694] (r9394)
0.5.1-RC1 (2007-03-20)
------------------------------------------------------------------------
- Feature: Translation dependant formatting of dates (r8906)
- Feature: Kick inactive initial network connections after some time [FS#115] (r9038, r9061)
- Feature: Add an extra news group for opening and closing of industries (r9097)
- Codechange: Disable shares by default and increase the default maximum distance from edge for oil refineries (r9339)
- Codechange: When you started openttd with '-g' you got the same map every run (r9205)
- Codechange: When all news-setting buttons are 'full', make the for-all button show 'full' too (r9137)
- Codechange: Disable the ability to make flooding water with the canal build tool. In the scenario editor you can still make both canals and flood water at height level 0 [FS#622, FS#629] (r9105, r9115)
- Codechange: The station list, sorted by cargo rating, now takes stations into account that have no cargo waiting [FS#595] (r9062)
- Fix: Close the Shared Order Vehicle List if you remove the shared link with only 2 vehicles (r9338)
- Fix: A34-1000, Z-Shuttle, and Kelling K1 are now listed as small aircraft (r9298)
- Fix: Shared orders got messed up when the 'first' trains got removed in the depot [FS#685] (r9277)
- Fix: Use a less CPU-intensive algorithm to find a random industry for the AI to prevent it slowing down the game [FS#644] (r9251)
- Fix: When loading games, enroute_from was updated in the wrong place, causing issues with TTD savegames/scenarios (r9147)
- Fix: "Train is lost" message is generated incorrectly [FS#676] (r9146)
- Fix: Difficulty level button was not selected when opening the difficulty window (r9117)
- Fix: The wrong catenary wires were drawn for tunnel entrances [FS#612] (r9077)
- Fix: The intercontinental airport used 'T-junction' runway sprites when there is no exit in the middle of the runway as in the city airport [FS#529] (r9076)
- Fix: [win] dedicated console now doesn't need an extra 'enter' to fully quit [FS#459] (r9074)
- Fix: Take over companies properly in multiplayer games [FS#459] (r9071)
- Fix: When a bribe failed and you haven't picked up cargo yet, you would never be able to do so for a given station [FS#404] (r9070)
- Fix: Don't keep on scrolling for non-numeric values in settings, but require reclick [FS#663] (r9064)
- Fix: The personal (.openttd) directories were hidden in the load/save directory listings [FS#652] (r9043)
- Fix: Desync caused by buffer overflow [FS#664] (r9027)
- Fix: When cutting strings into multiple lines also take into consideration whitespace characters of more than 1 byte length. (r9012)
- Fix: Play the correct engine sound based on the engine type instead of the sprite (r9009)
- Fix: New locomotive names were not announced in the news, it said "new railway locomotive available - railway locomotive" [FS#581] (r9000, r9001)
- Fix: [NewGRF] Do not select a disabled platform length/number of track count when going out of drag-drop mode [FS#450] (r8999)
- Fix: [win] Resolution doubled in cfg file when fullscreen mode used [FS#642] (r8994)
- Fix: The industry list should also be (re)set when the number of industries is 0 [FS#656] (r8980)
- Fix: [win] Possible buffer overflow if unicode text is pasted into an input box and needs trimming. (r8975)
- Fix: [win] Support compilation with the Vista Platform SDK (r8974)
- Fix: Crash on loading savegames with GRFs that do not have their GRF info/name set (r8955)
- Fix: [NewGRF] support for vehicle variable 48 was wrong (r8943)
0.5.0 (2007-02-27)
------------------------------------------------------------------------
- Feature: Add the ability to load newer TTDP games (the tile information for coasts has changed) (r8738)
- Feature: Selecting "end of orders" and deleting will delete all the vehicle's orders (shared mode unchanged) (r8685)
- Codechange: Call GetFirstVehicleInChain only for trains thus increasing performance in large games (r8744)
- Fix: Possible crashes, problems with aircraft and airport removal (r8921)
- Fix: Do not show the 'edit sign' window for spectators (r8808)
- Fix: Adhere order types for ship order insertion to determine destination type (r8802)
- Fix: It was possible to take over buoys by building a station next to them (r8794)
- Fix: Cloning unaware of articulated locomotives that could refit without refitting the front unit (r8777)
- Fix: Loading times for overhanging trains are miscomputed (r8709)
0.5.0-RC5 (2007-02-08)
------------------------------------------------------------------------
- Feature: Requery gameservers that did not respond to their first query (r8520, r8542)
- Feature: Logging of the IP address and port of invalid/illegal UDP packets (r8490)
- Codechange: Replace missing sprites with a red question mark (r8634)
- Codechange: Add Korean, Simplified Chinese and Traditional Chinese languages as an official translation (r8286, r8324, r8616)
- Codechange: Increase the size of the sound/video/music-drivers to 32 bytes (instead of 16) so their actual parameters can be passed. Sound has for example bufsize' and 'hz' (r8497)
- Codechange: Be more strict about language generation and fail any languages not having the mandatory ##name, ##ownname and ##isocode pragma's (r8253)
- Fix: Draw canal edges under buoys that are in a canal (r8635)
- Fix: Buoys on canal tiles do not flood anymore (r8620)
- Fix: Store the ownership of a water tile in the buoy tile and set the ownership of the water tile when the buoy is removed. Prevents certain abuses (r8619)
- Fix: When the currently selected player in the performance details window is no longer active, choose the first active player instead of the first player as that may also be inactive [FS#582] (r8612)
- Fix: Road vehicle very close after another (slower) road vehicle gets its speed reset to 0 when entering a tunnel, which causes a traffic jam outside of the tunnel (r8609)
- Fix: Bridges do not get destroyed when the bridge head gets flooded and there is a vehicle on the bridge [FS#564] (r8593)
- Fix: Road Vehicles now can obtain a slot even if the station is very spread out [FS#577] (r8536)
- Fix: Segmentation fault when the toolbar gets removed and you have selected one of the items in a submenu of the toolbar (r8533)
- Fix: Deleting a vehicle with shared orders, but no orders would fail to reset prev_shared and next_shared (r8294)
0.5.0-RC4 (2007-01-18)
------------------------------------------------------------------------
- Feature: Increase spritecache size to 2MB, will increase performance in games using newgrf files (r8218)
- Feature: OS/2 support with GCC (Watcom is dropped) (r8042)
- Codechange: Add Japanese, Slovenian language as an official translation and split Norwegian into Bokmal and Nynorsk (r7987, r8084, r8069)
- Codechange: Show error messages about our own data files as a popup, or to stderr if console is available (and not to stdout) (r8013, r8134)
- Codechange: Change the ordering of the network list, compatible servers just missing grf files are below fully compatible servers, not on the bottom (r8118)
- Fix: Return proper error value when unthreaded save fails, prevents server sending 0-sized files (r8171)
- Fix: Network client crashes when a server sends a 0-sized savegame [FS#556] (r8167)
- Fix: Several desync fixes (incorrect roadstop update of old games, autoreplace bugs) [FS#551] (r8137, r8147, r8157)
- Fix: Some disaster-events fixed: combat chopper shoots from right position, submarine once again moves around (r8140, r8158)
- Fix: "out of sprite memory" warning messages due to incorrect assumption of requested memory for sprites (r8133)
- Fix: Bouys are now built and numbered 1..9 not 9..1 [FS#538] (r8123)
- Fix: Clicking for more news properly cycles through the news history backwards, and doesn't show the first item doubly if it's already open (r8049)
- Fix: Crash when removing a town in the scenario editor while the query window is open for one of the town's tiles (r8030)
- Fix: Overflow of system-ticks was not handled properly, resulting in a possibly unresponsive server/client (r8028)
- Fix: Automatic pause interfering with 'pause_on_join setting' in MP when <shift> is pressed [FS#486] (r8027)
- Fix: Picking up en-route cargo will also have virtual profit deducted for trains aswell (r8026)
- Fix: Out-of-bounds read access on _clients array (harmless) (r7984)
0.5.0-RC3 (2007-01-07)
------------------------------------------------------------------------
- Codechange: Add Lithuanian language as an official translation (r7806)
- Fix: The configure script did not work work for dash, a sh compatible shell [FS#485] (r7893)
- Fix: [OSX] control + enter no longer fullscreens, interfered with team-chat (r7886)
- Fix: Offset engines/wagons by half width in details window; fixes overflowing for display (r7864)
- Fix: [OSX] Remove incorrect debug message about missing grf files. (r7766)
- Fix: [sdl] sometimes ALT-TAB could trigger the fast forward (r7727)
0.5.0-RC2 (2006-12-31)
------------------------------------------------------------------------
- General Removed support for OSX older than 10.3.9. Either upgrade, or use 0.4.8 (compatible with OSX 10.2)
- Codechange: Drastically reduce the CPU usage in certain cases (AI using CheckStationSpreadOut()) (r7585)
- Fix: Internal bug in updating the animated_tiles table caused desyncs between (different endian) machines in MP (r7631)
- Fix: Signal update got propagated through incompatible railtypes and under certain circumstances tunnels and rail on top (r7620)
- Fix: Remove landscaping toolbar option from road consturction toolbar in scenario editor [FS#473] (r7586)
- Fix: The server could under certain circumstances tell a client too late to start syncing if it has been waiting to join (r7566)
- Fix: Removing towns in scenario editor didn't remove their subsidies causing possible crashes [FS#468] (r7563)
- Fix: Internal and (patches) GUI were disagreeing about autorenew settings [FS#431] (r7561)
- Fix: No new company could be created if more than 8 clients were connected, even if not all 8 companies were used (r7560)
- Fix; Clicking 'full load' could under certain circumstances change the current depot order [FS#456] (r7559)
- Fix: Do not wait till a crashed vehicle is removed before starting to load other vehicles [FS#464] (r7558)
- Fix: MorhpOS compile and install fixes (r7548)
- Fix: Removing rail station cost was calculated on occupied area not on number of tiles with an actual station on (r7547)
0.5.0-RC1 (2006-12-21)
------------------------------------------------------------------------
- General fixes and improvements to TTDPatch's newgrf format, most noticable are newstations, newsounds, more callbacks and I18n
- Added languages: Bulgarian, Esperanto, Russian, Ukrainian, Languages with proper diacretics: Czech, Hungarian, Turkish
- Feature: Show NewGRF compatability of network games; green for full compatibility, yellow for missing newgrfs and red for invalid revision (r7505)
- Feature: Load a list of NewGRFs from the config (in the [newgrf-static] section) that should always be loaded (r7490)
- Feature: Double the length of the cargo and rating indicators in the station list window for better visibility (r7466)
- Feature: NewGRF set up window and browser which allows modification and viewing of NewGRF settings ingame or the main menu (r7357)
- Feature: Support for saving NewGRF settings with savegames (r7348)
- Feature: Add support for gradual (un)loading of vehicles (r7326)
- Feature: Add freight trains patch option which is a multiplier for the weight of cargo on freight trains, to simulate longer heavier trains (r7269)
- Feature: UNICODE/UTF8 support, with (optional) usage of fonts rendered by Freetype instead of sprites. This means full unicode support (input, rendering, file/io) and greatly enhanced internationalization for non-latin languages (utf8) (r7182)
- Feature: Add Slovak, Brazil and Slovenian currency [SF 1243657, 1171147; FS#131] (r7160, r5964)
- Feature: Allow towns to be built on top of trees in the scenario editor [FS#396] (r7152)
- Feature: Allow over-building of compatible railtypes, i.e. normal and electrified rail. If building electrified rail, normal rail is upgraded for you (at a cost) (r7106)
- Feature: Additional positioning for long dropdown lists with scrollbar support if dropdown list wouldn't fit (r7086)
- Feature: [win32] Remember the window size between restarts when quit in fullscreen mode (r7061)
- Feature: Increase the chatbuffer of chat messages, messages longer than the graphical box will be wrapped to a new line (r6956)
- Feature: Allow typing longer text than visible for an editbox; it will scroll properly now (r6954)
- Feature: Allow spectators to team-speak to eachother (r6933)
- Feature: Allow for " to be in console tokens. Escape them with \. eg \" (r6875)
- Feature: Change the functionality of the chat window. SHIFT+ENTER (SHIFT+T) sends a message to all players, CTRL+ENTER (CTRL+T) sends a message to all team mates and ENTER (T) is customizable (r6824)
- Feature: (Train is) lost message is now generated immediately when pathfinder can't find the path (r6800)
- Feature: Add a measurement tool that will show dimensions and height differences of various draggable tools (r6758)
- Feature: Added sort options to the build aircraft and train windows (r6708)
- Feature: Depot lists are now sorted, so vehicle 1 is always first and so on (r6652)
- Feature: Ability to pause a server if not enough players are connected. The setting for this is 'min_players' (r6628)
- Feature: Ability for servers to execute a script just after a client has connected, e.g. for a MOTD, etc (r6625)
- Feature: Add refit commands to vehicle orders (can only be done in goto depot orders) (r6624)
- Feature: Support cargo subtypes in the refit window. The refit window has been altered to support resizing and scrolling (r6601)
- Feature: Depot and vehicle list windows reworked a bit with more buttons to include 'Autoreplace all' (instantly), 'Sell all', 'Start all' and 'Stop all' (r6542, r6552, r6515)
- Feature: Using goto depot with a different control selection will now alter the service/stopping in depot flag instead of cancelling the goto depot order (r6295)
- Feature: When automatically detecting the language try to first match language+territory (e.g. de_CH), then just language (e.g. de) and fall back to en_GB otherwise (r6290)
- Feature: Add a "goto depot" button to various vehicle list windows (r6229, r6246)
- Feature: Save max_companies/clients/spectators in the config file (r6170)
- Feature: Vehicle status bar will show the heading string in different colours to visually discern the difference between a service and a forced stop (r6165, r6414)
- Feature: Control clicking Goto Depot will now make the vehicle service instead of stop in depot (r6165)
- Feature: List of vehicles with the same shared orders, accessible from the orders-window of a given vehicle (r6161)
- Feature: Added -s (source) and -d (destination) to strgen to specify paths for input and output files (r6089)
- Feature: After removing a farm, its farmland is removed too (over time) [FS#82]
- Feature: Clicking twice on the location button in the smallmap centers to your position, clicking twice centres your viewport [FS#54] (r6040)
- Feature: Change the original date format to a 32 bits format based at the year 0. Highest date is the year 5.000.000AC (r5999)
- Feature: Auto-completion in chat-window. It completes Player and Town names (in that order) using <tab> (r5968)
- Feature: Catalan Town Names generator [FS#261] (r5965)
- Feature: Possibility to generate scenarios by importing heightmaps. It can be in PNG or BMP format
- Feature: New (optional) landscape generator based on TerraGenesis Perlin noise with GUI, progress bar and fine-tuning options (r5946)
- Feature: Filter for textboxes to only allow input of certain patterns (like numbers only) (r5944)
- Feature: [win32] Remember the maximized state of the game window and restore on start [FS#234] (r5874)
- Feature: Add an icon to the SDL openttd executable (r5872)
- Feature: Also allow horizontal and vertical rails on steep slopes (r5864)
- Feature: Allow building of (certain) rails, roads and bridge ramps on steep sloped tiles (r5833)
- Feature: Replacing from a train engine without cargo capacity to one with cargo capacity will now make autoreplace refit the engine to carry the cargo type from the last wagon in the train (r5465)
- Feature: [OSX] Macs with touchpads that support two finger scrolling can now use this "scrollwheel" to scroll up/down (r5460)
- Feature: Allow building canals at sea-level, using ctrl to toggle canal or plain water tile. This allows building of non-raisable sea-level water ways (useful in multiplayer) and dikes for low-level areas (r5403)
- Feature: Add 4 new airports. 2 for aircraft, 2 for helicopters (r5346)
- Feature: Implement smooth horizontal depot and, vehicle list scrolling for trains (r5046)
- Feature: Add new pathfinder, YAPF. Has greatly improved performance and better, fully configurable, pathfinding (yapf) (r4987)
- Feature: Add a new console command "players" that lists current players along with basic stats [FS#150] (r4828)
- Feature: Station List View can now be sorted and filtered (by waiting cargo type and facilities) (r4822)
- Feature: The integer-list parser now accepts a space character as an item seperator next to the comma for openttd.cfg (r4490)
- Feature: Add support for electric railways as a seperate tracktype. Electric trains will not run on non-electrfied track unless otherwise controlled by patch option (elrails) (r4150)
- Feature: A new multi-lingual multi-measuring-unit system (r4126)
- Feature: Add proper OPENTTD <> LOCALCODE conversion using iconv. Savegames with special characters will be legible in filesystem (r4105)
- Feature: Undraw the mouse when it leaves the window and draw it again when it enters (r4075, r4083)
- Feature: It is now possible to turn a single unit in a train (CTRL+Click on unit in depot) (r3944)
- Feature: Delete news items about vehicles when they get stale (r3757)
- Feature: Save patch settings with the savegame so you are presented with the same behaviour when loading the game on another machine/installment (r3726)
- Feature: Add 2cc (two company colours) livery schemes. This replaces the original colour selection window (r3717, r6455)
- Feature: [OSX] Added support for tripple binaries (binaries optimised for G3, G5 and i686) (r3674)
- Feature: Allow autoreplacing of train wagons (r3535)
- Feature: Allow sorting of vehicle lists by model or value (r3528)
- Feature: Allow trains details view to be resized (r3521)
- Codechange: Improve the usability of the signal-dragger, do not bail out at (certain) errors, just silently ignore them [FS#149] (r7127)
- Codechange: Make the zoom in/out buttons of the extra viewport into proper push-buttons (r7078)
- Codechange: Make the AI choose road vehicles based on a rating (currently max speed * capacity) instead of either the cost or the index of the vehicle (r7070)
- Codechange: Truncate text in window captions to prevent overflow (r7058)
- Codechange: Allow standard ini-file style comments (;) (r6972)
- Codechange: Send server messages with format NETWORK_ACTION_SERVER_MESSAGE so it is general colour like the rest of the server messages. Spectators speak in grey (r6932)
- Codechange: Change textmessage format a bit. Only the sender's name and target are in the sender's colour, the actual message is in white. Should improve readability (r6932)
- Codechange: Add an MD5 sum check of our own data files, and warn if they don't match (r6921)
- Codechange: Add strict bounds checking in string formatting system to check for possible buffer overflows (r6884)
- Codechange: Have the dropdown menus fall fully inside the top toolbar (r6745)
- Codechange: Determine the length of the main toolbar dropdown list based on the length of the strings in that list (r6744)
- Codechange: When vehicles never expire they will stay at peak reliability instead of the lowest to make them useful even when old (r6681)
- Codechange: Show more correct capacity of articulated wagons in the train purchase list (r6650)
- Codechange: When showing tooltips, properly position the tooltip taking into account window dimensions and cursor (r6405)
- Codechange: Speed up the animated cursors a bit so they move once in a while at least (r6367)
- Codechange: Remove the "unsorted" vehicle sorter, because it's plain useless (r6270)
- Codechange: Remove MSVC6 support. The compiler was too stupid and too many workarounds were needed. Please switch to mingw or VC2005++ express (r5286)
- Codechange: Allow a switch in Makefile.config to disable threads in OpenTTD (r5978)
- Codechange: [win32] Add native x64 target to VS2005 project files (r5813)
- Codechange: [win32]The exception dialog showed the last modification-date of win32.c instead of the last compilation-date (r5801)
- Codechange: Add owner attribute to canals and locks. This makes them more useful in multiplayer games, as only the owner can delete them. Does not affect usage (r5084)
- Codechange: Add MSVC2005 support, project and solution files are in the _vs80.* files (r4581)
- Codechange: [OSX] Shark (Xcode's profiling tool) can now relate CPU usage to lines (r3611)
- Codechange: Rewrite the multistop slot assignment system. More resource-friendly, several slot-assignment improvements (r3730, r4259)
- Codechange: Completely remove the deprecated -p parameter (is superseded by -n) (r3508)
- Fix: Town ratings were not reset when a company went bankrupt (r7433)
- Fix: With realistic acceleration, guarantee a minimum braking force is applied. This ensures trains will stop when going down hill (r7425)
- Fix: Changed "kick off" acceleration resulted in only a small amount of power being applied; this resulted in a perceived delay before trains moved. (r7421)
- Fix: Long delay for message windows to appear. Immediately show a new message if present if no news window is open, or has just been closed instead of waiting for the timer of the current news to time out [FS#255] (r7402)
- Fix: Deleting Train in depot with autoreplace fails [FS#418] (r7385)
- Fix: Don't update vehicle images when turning a train around. During this procedure the train is split into parts which can result in incorrect images being used (r7378)
- Fix: OpenTTD could crash under certain circumstances when a vehicle as autoreplaced and a news window was open [FS#332] (r7368)
- Fix: Segmentation fault in the SDL video driver when one goes to fullscreen and there are no suitable resolutions (r7332)
- Fix: When loading a game from a dedicated server the local player set to 0, theoretically enabling the dedicated server to also play (r7312)
- Fix: TTDPatch vars are little endian (r7282)
- Fix: Always display the excavation of roadworks even when fully zoomed out or "full details" are off (r7240)
- Fix: Window allocation and deletion messed with the actual window pointer, possibly crashing OpenTTD [FS#350, SF#1560913] (r7205)
- Fix: Callback not executed for non-player based patch changes in multiplayer for all clients; possible desync issue (r7190)
- Fix: Station sign (and base station coordinates) didn't move along with station when station moved by walking. [FS#388] (r7169)
- Fix: MiniMap was misplacing vehicles sometimes [FS#402] (r7166)
- Fix: Some mouse events possibly lost under high CPU load, handle mouse input right away instead of waiting for GameLoop. [FS#221, SF1168820] (r7157)
- Fix: Some keyboard events possibly lost under high CPU load, handle keyboard input in place instead of global variables magic. [FS#279] (r7153)
- Fix: "Position of Main Toolbar" option isn't honored when starting new game or loading saved [FS#172] (r7130)
- Fix: Synchronize the engine-renew settings of a player when joining a multiplayer game (r7126)
- Fix: Several errors/glitches related to multiplayer and bankrupcy (mainly server), and non-updated company-information (r7125)
- Fix: Cloning a vehicle that has been refitted would incur the expense as running costs, not new vehicles [FS#371] (r7115)
- Fix: Do not let ships enter partial water tiles under bridges; they will travel up land... (r7110)
- Fix: AI tried to build road from the back or side of road stop/depot (r7069)
- Fix: Zooming out near map-borders would previously fail because the new centre would be outside the map [FS#317] (r7047)
- Fix: 'Goto' button in orders window got depressed along with all other buttons when an existing order was modified [FS#311] (r7046)
- Fix: Scenario bridges/tunnels cannot be demolished [FS#200] (r7028)
- Fix: Pressing F1 in scenario editor did not work (r7023)
- Fix: Properly guard against viewing company-sensitive information from invalid players (eg spectators) which could lead to crashes [FS#292] (r7022)
- Fix: In the replace vehicle window, the left vehicle list was not drawn when an engine was not selected (r7009)
- Fix: Crash at game end when server company is bankrupt [FS#369] (r7008)
- Fix: List of actions panel in the town authority window went underneath its scrollbar (r6885)
- Fix: Pressing ^D (EOF) at a dedicated console caused it to repeat the last command, instead of doing nothing (r6835)
- Fix: Don't add up running cost of articulated engine parts (r6765)
- Fix: If a rail is not available, don't show toolbar even with hotkey 'A' (r6740)
- Fix: Only apply the virtual transfer profit if the order is a transfer order, rather than to any unload order (r6738)
- Fix: Disable main toolbar buttons showing company list drop downs when there are no companies [FS#356] (r6695)
- Fix: Autoreplace can now use the money for selling the old vehicle to build the new one (r6640)
- Fix: A loop-hole that allowed docks to be built regardless of town authority rating (r6477)
- Fix: [win32] The dedicated server could overwrite the keyboard input buffer before it was handled by OpenTTD (r6449)
- Fix: Reset the location of the last sound as that location can be outside the map when you are loading another, (smaller) map (r6437)
- Fix: Show an error message when executing 'scrollto x' with x < 0 or >= MapSize() instead of asserting later on [FS#340] (r6435)
- Fix: Station catchment area persists after switching tools [FS#136] (r6368)
- Fix: Do not reset the current cursor action when centering on a depot/hangar (r6360)
- Fix: Go to hangar orders for aircraft could get spuriously removed when a road or rail depot got deleted (r6355)
- Fix: Due to some off-by-one errors the width or height of a clipping rectangle could become 0, which isn't sensible. This should fix a very rare and hard to trigger assertion in GfxFillRect() (r6351)
- Fix: Never allow scrolling the map in the main menu (scroll-settings weren't reset if switched to mainmenu) (r6037)
- Fix: Never set I-am-a-thread bool to true IN the thread, dual-core machines could flip [FS#78] (r5977)
- Fix: Town-growth removed houses under construction to make way for road; unwanted behaviour [FS#49] (r5970)
- Fix: Cloned toad vehicles are not refitted to correct cargo [FS#275] (r5917)
- Fix: Bugfix for errors in FindNearestHangar function in aircraft_cmd.c [FS#235] (r5914)
- Fix: Sort order for produced amount and transported percentage was reversed in the industry list (r5912)
- Fix: Changing patch settings through the console didn't accept on/off or true/false [FS#170] (r5903)
- Fix: Differing price calculation for tunnels depending on starting point [FS#253] (r5901)
- Fix: Goto sepot not always working for road vehicles [FS#249] (r5898)
- Fix: Bus trying to service in depot of other company [SF1519167] (r5897)
- Fix: If vehicles break down and service is turned off, the vehicles failed to enter any depots; now they will quickly go to a depot if set to be replaced (r5888)
- Fix: Incomplete removal of player owned property due to lack of money [FS#273] (r5886)
- Fix: < > boxes in patch-settings didn't grey out when they hit the limit of their range (r5714)
- Fix: Check the configuration file for valid values and clamp them to their ingame minimum/maximum [SF1288024] (r3726)
- Fix: Remove the restriction that the 'patch' console command can only be run from network games [SF1366446] (r3723)
0.4.8 (2006-08-12)
------------------------------------------------------------------------
- Fix: A ship in a depot must be stopped before it can be cloned.
- Fix: After changing directory in 'Play Scenario', the default scenarios didn't show up in 'New Game'
0.4.8-RC2 (2006-07-31)
------------------------------------------------------------------------
- Feature: Add Italian town names as we have an official Italian translation
- Codechange: Verify the presence of music files in the gm/ folder. This should also solve some 100% CPU buildup for some users.
- Fix: Certain combinations of trains crash when moved around inside the depot.
- Fix: Reversed arrow-sign in the multiplayer list column headers on sort by name
- Fix: Industry production change button doesn't work for oilrig passangers.
- Fix: Helicopters stopping in depot after autorenew/autoreplace
- Fix: MorphOS crashes when you go a level up in the root level
- Fix: UDP sockets were used even if network-availability was set to false
- Fix: Crash when trying to build a vehicle type that is set to a max of zero
0.4.8-RC1 (2006-06-28)
------------------------------------------------------------------------
- Feature: Add Turkish town names as we have an official Turkish translation
- Feature: Add a fully optional configure script that is a wrapper around the cumbersome makefile.config
- Codechange: [NPF] Disable NPF totally for ships as it wholly kills performance (blathijs). Only for 0.4/ branch and 0.4.8.
- Fix: Redraw the screen when switching the signal side in the patches window
- Fix: It was possible to dig into a tunnel if certain rail combinations were ontop of it
- Fix: A HQ could only be flooded at its northern tile, the other 3 were immune to water
- Fix: Fix several glitches concerning foundations. Houses, property (rail/road/bridge/etc.) and cursor are now aligned properly
- Fix: Prohibit altering a road tile while road works are in progress. This fixes some glitches like "turning" the excavation by adding/removing road bits or removing the road piece
- Fix: Only advertise the server to your external IP/network (eg not to 127.0.0.1) and use proper broadcast addresses
- Fix: '-f' switch is not valid on windows, so don't show it in help
- Fix: [autoreplace] Autoreplaced trains can leave all wagons in depot under certain circumstances
- Fix: The wrong IP could get unbanned, e.g. 'unban 1.2.3.42' could result in unbanning 1.2.3.4
- Fix: It was possible to convert the railtype of a bridge while a train was on it
- Fix: It was possible to rename signs or waypoints with the chat box
- Fix: Be more strict what it means for an aircraft to be in a hangar: It's not just being stopped on a hangar tile
- Fix: If a road vehicle is on a road depot tile and stopped doesn't mean it's in the depot. Use the proper test for this
- Fix: [AI] The AI should send a plane into a hangar if it's not in a hangar _or_ not stopped, not when it's not in a hangar _and_ not stopped
- Fix: [AI] The trolly AI used information from the wrong industry when calculating the amount of to be transported goods
- Fix: [NTP] Fix NTP over bridges: don't check the rail type when on a bridge
- Fix: Truncate text in dropdown lists to stop text overflowing.
- Fix: "Erroneous train reversal on waypoints". When processing the next train order, do not even consider reversing the train if the last order was to a waypoint.
- Fix: Starting a new scenario did not adhere to local difficulty settings but took it from the scenario itself. That mode is for 'play scenario'
- Fix: Vehicles on a sloped tile under a bridge were affected by the bridge speed limit
- Fix: Issue with train pathfinding over level crossings.
- Fix: [AI] The AI no longer attempts to build signals under bridges.
- Fix: Refresh build vehicle window (if opened) when converting rail depot
- Fix: Crash when sorting an empty server list.
- Fix: The build-tree window button defaulted to a place-push-button on opening where no treetype is selected.
- Fix: Game crashes when cloning/autoreplace reaches train-limit
- Fix: [NTP] properly check for railtypes on non-plain-rail-tiles
- Fix: Trains could enter certain sloped rail tiles under bridges with incompatible rail type
- Fix: Ensure the map memory is cleared after it is allocated. This fixes random deserts that sometimes occurred.
- Fix: Some weird behaviour with tile selection near bridges
- Fix: Don't allow PF to enter train depot from the back (signal updates)
- Fix: Game no longer crashes when the last vehicle servicing a station has been deleted
- Fix: Reset the last built railtype when starting a new game
- Fix: Cloned vehicles get the same service interval as the original vehicle
- Fix: Game no longer errors out when "Many random towns" is selected in the scenario editor.
- Fix: Obscure road dragging bug. The road build command did not return the appropiate error message of invalid-slope when building road.
- Fix: Temperate bank will no longer appear (during game) in tropic landscape. This bug is from the original game.
- Fix: Specify the 'stopall' console command as a debug command.
- Fix: Fixed a problem that caused DeliverGoodsToIndustry to not work as intended
- Fix: Ships and aircraft can now be used as feeders as well
- Fix: When a multiheaded train is sold the pointers were not updated correctly causing sporadious crashes/disconnects.
- Fix: New plantations now cause the correct ".. being planted .." news item
- Fix: Danish town names were saved/loaded as Swiss
- Fix: Removing roads on crossings was done without a check for ownership
- Fix: [autoreplace] Fix drawing of train list for outdated engines
- Fix: Malicious clients/servers could crash the game
- Fix: [autoreplace] allow replacement of wagons even when the engine fails to be replaced
- Fix: Certain operations involving trains inside a depot could cause a crash
- Fix: [autoreplace] cost for refitting a new vehicle is added to the cost animation (player always paid for it, it just wasn't shown)
- Fix: [OSX] Save/Load issues solved for OSX 10.3.9 universal binaries
- Fix: Illegal servers in the master-server list could kick the client back to the main menu, effectively making Multiplayer impossible
- Fix: [NPF] Don't mark tiles when debugging in multiplayer, this will cause desyncs
- Fix: Several fixes to chatbox code, mainly plug a buffer overflow
0.4.7 (2006-03-26)
------------------------------------------------------------------------
- Feature: [OSX] Add support for triple-binaries (PPC, PPC970, i386) (r4102)
- Fix: [OSX] crash when going to fullscreen (r4100)
- Fix: Allow unused wagons to have their first cache set. Fixes faulty cache-warning message and noticably speeds up depot operations (r4094)
- Fix: [NPF] Trains & busses were unable to find a route when leaving a depot or bus stop. (r4072)
0.4.6 (2006-03-22)
------------------------------------------------------------------------
- Codechange: [win32] Show the revision in crash.txt and enable the button to show the crash text in the crash-window (r3965)
- Codechange: Add additional linker information to release builds to help figure out crashes more easily (r3526)
- Fix: [OSX 10.3 and newer] [ 1157244 ] Can't save game if name contains german umlauts (loading savegames with certain chars still look odd) (r4038)
- Fix: [OSX] major speedup for PPC fullscreen (r4034)
- Fix: [Makefile] Make sure the ICON_DIR gets created before copying files there. (r4032)
- Fix: [win32] Change compiler settings to use the multithreaded CRT. This prevents certain crashes on multi-threaded machines. (r4031)
- Fix: [ 1453646 NPF ] Road vehicles planning through the back of depots and stations. (r4029)
- Fix: Use the title of a savegame in the saveload dialog-editbox. (r4018)
- Fix: Improper resolution written to the configuration file when exiting from fullscreen. (r4017)
- Fix: When removing rail track from a tile where only X and Y pieces exist, explicitly update signals in both directions. (r4016)
- Fix: Default the patch-setting 'pause_on_join' to true. (r4015)
- Fix: Slope and height information returned for some tile types is wrong (r4014)
- Fix: Fixes a bug introduced by r3228 which allowed steep rail tiles resulting in ... unwanted effects such as display artifacts. (r4012)
- Fix: Update french translation (r3978)
- Fix: FS#56 - [Crash] Missing glyph(s) in big-font. Added several missing glyphs for the big font. (r3970)
- Fix: [ 1439907 ] Increase client list window width so at least most languages fit. (r3969)
- Fix: Update german and finnish languages. (r3968)
- Fix: Properly set back the owner of a crossing/road-under bridge after removing it. (r3967)
- Fix: [autoreplace]: (FS#67) autoreplacing trains now keep their tile length instead of their pixel length. (r3964)
- Fix: Mark the right tile as dirty. It's just a graphical glitch which happend in r1592. (r3962)
- Fix: Fix crash when resizing news history window. (r3961)
- Fix: Correctly implement minimum search, so road vehicles head twoards the closest station, not the last one in the list. (r3960)
- Fix: [FS#61] The tooltips for raising and lowering land buttons in the scenario editor are interchanged (r3959)
- Fix: Correctly restore the roadside after roadworks are finished. (r3957)
- Fix: [Multistop] Check the status of the destination road stop instead of a station's first road stop. This only has effect with road vehicle queuing disabled. (r3956)
- Fix: validate the setting of max_companies/spectators through the console. (r3955)
- Fix: Improve game-load times. (r3954)
- Fix: On loading a game, GetPlayerRailtypes() didn't account for the fact that vehicles are introduced a year after their introduction date. This will also relieve possible (rare) network desyncs. (r3952)
- Fix: Restore plural forms of cargo types for several languages. (r3951)
- Fix: [win32] Add directives to allow Visual Studio 2005 compilation. (r3950)
- Fix: [ 1415782 ] crash in string code with openbsd/zaurus; alignment issues (r3948)
0.4.5 (2006-01-31)
------------------------------------------------------------------------
- Feature: [newgrf] Implement varaction2 property 0x41 and 0xDA. (2361)
- Feature: giving server_ip a value of 'all' will make the server listen on any interface (2374)
- Feature: shortcut CTRL + U that clears the current input-box (2385)
- Feature: [newgrf] Implement the mechanism for handling newgrf callbacks (2389)
- Feature: [newgrf] Implement the 'refit capacity' callback (2389)
- Feature: saving games happen in a seperate thread (2391)
- Feature: [newgrf] Implement powered wagons, and the callback that goes with it (2414)
- Feature: [newgrf] Implement shorter train vehicles (2428)
- Feature: New display option: 'transparent station signs' (2438)
- Feature: You can now give transfer order to set up feeder systems (2441)
- Feature: Removing tracks with the 'remove' tool, automatically removes signals on the tracks (2469)
- Feature: [localisation] Allow changing the order of parameters in translated strings (2573)
- Feature: [localisation] New way to specify plural forms (2592)
- Feature: [localisation] Support genders (2594)
- Feature: [localisation] Support cases (2597)
- Feature: add support for truncating strings to a given (pixel) length (2607)
- Feature: Overhaul DirectMusic MIDI backend, remove "experimental" status (2712)
- Feature: Change the driver probing algorithm: Use the first music/sound/video which succeeds initialising instead of bailing out after the first. No need to specify -snull if no soundcard is present anymore (2728)
- Feature: The Main Toolbar Dropdown Menu can now display disabled items (2734)
- Feature: Clone vehicles (2764)
- Feature: When starting without a config file determine the language on basis of the current locale (2777)
- Feature: [NewGRF] Add support for "extended bytes" (2872)
- Feature: [localisation] Major step twoards ISO-8859-15: Implement missing characters (2879)
- Feature: Implement the console command rm to remove savegames (2941)
- Feature: Danish town names (2957)
- Feature: Menu option to toggle console (2958)
- Feature: Calculate proportions of non-square giant screenshot correctly (2963)
- Feature: [newgrf] Implement current set of action D (ParamSet) operations (2968)
- Feature: [newgrf] Show a wagon's speed limit in purchase list (2969)
- Feature: [newgrf] Support loading VarAction2 parameter for variables 0x60-0x7F (2971)
- Feature: [newgrf] Add patch option for wagon speed limits (2982)
- Feature: [newgrf] Support loading of bridge attributes and tables from GRF (3004)
- Feature: Native Support for Win64 (3008)
- Feature: OSX now uses quicktime to play midi files (3022)
- Feature: [OSX] Command+Q now works in main menu (3027)
- Feature: Allow unbanning players based on banlist-id (as well as IP) (3067)
- Feature: 'status' and 'clients' now show the IP of the players (3067)
- Feature: Make it possible to create a screenshot from the console that is both big and has no console, or any combination of (3068)
- Feature: [newgrf] Add support for rail vehicle weight greater than 255 tons (3071)
- Feature: 'HOME' icon to saveload dialogs that jumps to the default save/load directory based on the dialog (3096)
- Feature: Turkish translation (3120)
- Feature: [newgrf] Support positioning of rail vehicle visual effects (3132)
- Feature: [newgrf] Support for articulated rail vehicles (3139)
- Feature: [newgrf] Add support for cargo refitting specification by cargo classes (3148)
- Feature: [newgrf] Action 7/9 new value : is it TTDPatch or OpenTTD? (3152)
- Feature: Drag and drop rocky areas in scenario editor (3153)
- Feature: Added patch option to link the terraform toolbar to the rail, road, water and airport toolbars (3157)
- Feature: Right-Click-Scrolling optionally moves in the opposite direction (3222)
- Feature: Native cocoa sound and video drivers for OSX (3281)
- Feature: [newgrf] Allow train running cost class to differ from engine class (3388)
- Feature: Kick and ban now with IP numbers (3407)
- Feature: Allow seeing and setting the maximum amount of companies and spectators for a server. This can be changed/viewed during runtime as well in the console (3427)
- Feature: Allow the network game list to be sorted (by name/clients/compatibility ascending/descending) (3441)
- Feature: Make it possible to ban offline clients (3469)
- Fix: The refit window now shows the correct refit options (2365)
- Fix: Refitting to a cargo which is already carried by some vehicles takes their capacities into account for display (2365)
- Fix: Add 'multihead' TTDPatch option to OpenTTD newgrf flags-emulation (2368)
- Fix: make install tried to install scenarios in the (non-existing) personal dir when USE_HOMEDIR is specified (2371)
- Fix: [console] update the example scripts in the scripts/ directory to reflect the new console functionality (2372)
- Fix: [console] any line starting with a '#' is a comment so ignore it (2372)
- Fix: [console] The special variables whose value can only be set by a custom process should, also print out their newly set value there (2372)
- Fix: [newgrf] Ignore action 0 prop 0x20 (air drag) (2377)
- Fix: [newgrf] Further property stubs, help prevents subsequent incorrect reading of newgrf data (2378)
- Fix: Build year for mail compartment of planes was not set correctly, affected station ratings (2380)
- Fix: Endgame window on easy difficulty resulted in infinite loop (2381)
- Fix: Check the airport type when building an airport (2382)
- Fix: Monkey-testing turned up some command crashes (2383)
- Fix: Check selling land and setting player colour. Also an extra map-bounds check for terraforming (2384)
- Fix: [realistic accel] Very slow trains no longer get an increase in maximum speed when part of them is in a depot (2388)
- Fix: [newgrf] Load power for dual-headed engines correctly (2400)
- Fix: [newgrf] When resolving callbacks, dont ignore wagon overrides (2410)
- Fix: Station ratings aren't affected by speed limits from realistic acceleration anymore (2411)
- Fix: building vehicles without depot crashed the game (2412)
- Fix: certain resolutions caused a crash when minimap was partly dragged outside the game window (2424)
- Fix: Deleting canals under bridges removed bridges first in certain configurations (2436)
- Fix: [NPF] Vehicles try to drive into a tunnel entrance from above (2471)
- Fix: [newgrf] Some road vehicle action 0 properties were loaded as the wrong type (int8,int16,int32) causing undefined results. (like cargo types being wrong) (2474)
- Fix: The console variable autoclean_unprotected was linked to the variable _network_autoclean_protected (2498)
- Fix: Old bug in the PCX writer: The first pixel column contained garbage, the picture was shifted one to the right, and the last column was dropped (2512)
- Fix: Using the mouse wheel could lead to a crash if mouse was not over a widget (2530)
- Fix: blinking 'lock' gfx in multiplayer games (2548)
- Fix: Remove original train pathfinder. Enhanced old pathfinder. (2553)
- Fix: Spaces in the path to the MIDI files caused the win32 MIDI player to fail (2563)
- Fix: set server map name to the loaded name of the game/scenario (2610)
- Fix: Improve the old pathfinder. Changed it to A* instead of Dijkstra. Benchmark shows that NTP is now around 10x faster than NPF (2635)
- Fix: Correctly save and load company_value, it's 64 bits wide, not 32 bits (2684)
- Fix: Volume control works now for the DirectMusic MIDI backend (2712)
- Fix: Change the fence algorithm so it removes fences when no farm tile is adjacent (2739)
- Fix: Tree tiles above the snow line got redrawn disproportionately often (2750)
- Fix: Depots could build trains of the wrong track type (2764)
- Fix: Sort the directories in the scenarion/savegame list (2860)
- Fix: On OS/2 show the trailing \ if the current directory is a root directory (2860)
- Fix: Return a proper version number, when testing the TTDPatch version in the SkipIf action (2862)
- Fix: Change the way NewGRFs are loaded, this saves quite some sprite slots - about 2000 for DBSetXL for example (2868)
- Fix: Several format string vulnerabilities and buffer overflows in the network code (2899)
- Fix: fixed issue where autorenewed vehicles didn't get all stats updated (2912)
- Fix: Exit the child of the extmidi backend with _exit() instead of exit(), because we don't want any atexit handlers - especially flushing output streams - to run, if exec() fails (2938)
- Fix: Server crash with "say"-command (2950)
- Fix: Fix win32 midi volume level control which didn't work (2960)
- Fix: [OSX] quitting the game no longer leaves a process behind that eats all the CPU power (3281)
- Fix: Fix for [ 1216203 ] UFO-broken waypoint (2961)
- Fix: [newgrf] Include missing grf feature canal
- Fix: [newgrf] Add bounds checking to VehicleChangeInfo for vehicles
- Fix: [newgrf] Wagon speed limits don't apply for wagons with livery overrides
- Fix: Align settings pool items to the size of void* to fix bus errors on 64bit architectures which require aligned variables (2976)
- Fix: restart_game_date is an UINT16, not a BYTE. Now setting the game restart year via the console should work (2987)
- Fix: [newgrf] Some GRF files don't specify a name or description, in which case the Action 8 is 8 bytes, not 9 (3005)
- Fix: The finnish markka was never abbreviated with capital letters (3021)
- Fix: Improve handling of non-existent sprite sets (3044)
- Fix: Don't attempt to map and empty sprite group to a vehicle (3045)
- Fix: Fixed typo and hang for BeOS Networking (3053)
- Fix: On Win98 and lower when you go to the root directory of a drive (eg. C:\) you were stuck there indefinitely and couldn't change any directories or see any files (3056)
- Fix: Complete rewrite of autoreplace; multiheaded train engines are replaced correctly (3081)
- Fix: A new train is now made if the front unit is an engine and the former front engine is moved away (3144)
- Fix: There are only 2 possible directions for ship depots, not 4 (3199)
- Fix: Allow bribing up to the maximum rating for bribing, don't disable this option at some arbitrary value early (3201)
- Fix: Don't lower land on tunnel, even with diag tracks on it (3228)
- Fix: Crash when making a screenshotin the main menu (3235)
- Fix: Crash when starting a scenarion via 'New Game' fails (3235)
- Fix: Determine clicked status of sticky icon from window flags rather than the widget click state (3247)
- Fix: Graphical glitch with autorail tool on a certain tile-types (3254)
- Fix: Center the X of the window close button (3302)
- Fix: [newgrf] Unload engine names before loading grf files (3316)
- Fix: Network window crash when it receives invalid information for example from the integrated nightly, so validate the network-input when it is received (3322)
- Fix: Build failed if SDL is built without pthread support (3326)
- Fix: Move initialization of vehicle random_bits to DC_EXEC blocks to allow use of Random() instead of InteractiveRandom(), which will alleviate some possib le network desyncs (3352)
- Fix: The default AI tried to change the service intervals of vehicles via the CMD_CHANGE_TRAIN_SERVICE_INT command - regardless of the type of the vehicle (3367)
- Fix: Out-of-bounds array access when road vehicles overtook in a curve caused desyncs (3371)
- Fix: Update signal states when building or removing rail station blocks (3372)
- Fix: Don't allow trains to get bigger than 100 via drag and drop (3374)
- Fix: Don't reset date in the scenario editor when pressing RandomLand (3376)
- Fix: [newgrf] Running cost should be halved for dual head vehicles (3384)
- Fix: No fence was placed when placing fences and the neighbouring tile is a rail configuration which permits a fence but has a signal (3389)
- Fix: [newgrf] Ignore non-climate dependent cargo types (3394)
- Fix: [newgrf] Only add a random number of days to an engine's base introduction date if that date is not 0 (3410)
- Fix: When changing the server password via the console, actually set the password as well as flag whether it is required (3411)
- Fix: Under certain conditions placing a road tile parallel under a bridge would, instead of failing, succeed and place a perpendicular piece (3413)
- Fix: Disable the Fund New Industry menu item and window when connected to a server as a spectator (3414)
- Fix: Disable the clone and refit buttons in the train view when viewing another player's vehicles, or as a spectator (3415)
- Fix: Disallow building an oil rig above sea level (3416)
- Fix: When removing a town-owned tunnel the player's rating was not reduced (3418)
- Fix: (Possible) game crash on removing track/road under bridge if a vehicle was on the track/road under the bridge and the track/road sloped (3419)
- Fix: [newgrf] Only power should decide whether a rail vehicle is an engine or a wagon. (fixes SHIKI 810 in jpsetw.grf) (3424)
- Fix: Incorrect validating of tree-planting command which can allow a buffer-overflow (3446)
- Fix: [newgrf] When changing the sprite ID of a vehicle, if it is not FD (custom graphics), the value needs to changed from a 16bit array offset to an array index. (fixes tropicstw.grf) (3449)
- Fix: You couldn't remove an item from a list-type of config ingame from the configuration file (3475)
- Fix: [newgrf] Always reinitialize the ttdpatch flags as patch settings may have changed (3486)
- Fix: Price for demolishing a bridge was dependent on orientation and map size (3487)
0.4.0.1 (2005-05-21)
------------------------------------------------------------------------
@@ -1250,7 +586,6 @@
0.3.2.1 (2004-05-23)
------------------------------------------------------------------------
- Fix: use english.lng by default
- Fix: No bridges available in 1920
- Fix: czech file was missing
@@ -1259,7 +594,6 @@
0.3.2 (2004-05-22)
------------------------------------------------------------------------
- Feature: HP for trians limited to 16bit int
- Feature: added Czech translation
- Feature: train refitting
@@ -1318,7 +652,6 @@
0.3.1 (2004-04-26)
------------------------------------------------------------------------
- Fix: shift+arrows keys scrolls faster (by pasky)
- Feature: bridge pillars for higher bridges
- Fix: [ 941880 ] "monorail in 1985" which allowed you to build monorail/maglev at any year
@@ -1359,9 +692,7 @@
- Fix: buffer overflow caused by too long string in english.lng
- Fix: destroying things with no money
0.3.0 (2004-04-14)
------------------------------------------------------------------------
- Change: don't slow down trains as much on hills
- Fix: aircraft terminal wasn't properly freed if aircraft crashed
- Fix: fixed station acceptance bug
@@ -1436,9 +767,7 @@
- Feature: (OSX build) distribution now uses Apples package system for easier updates
- Feature: (OSX build) Application is now a proper bundle application
0.2.1 (2004-04-04)
------------------------------------------------------------------------
- Fix: copy orders crashed if you clicked on a wagon
- Feature: 'A' hotkey now always opens autorail
- Change: Moved autorail button
@@ -1448,9 +777,8 @@
- Feature: Hotkeys 1-9 can be used to build a bridge in the bridge window
- Feature: Added more hotkeys in the road build window
0.2 (2004-04-03)
------------------------------------------------------------------------
- Feature: autoscroll (only works to left/right)
- Feature: train checkpoints, instead of ttdpatch's nonstop handling
- Feature: ttdpatch compatible nonstop handling
@@ -1508,9 +836,8 @@
- Feature: on-the-fly language selection
- Feature: load old premade ttd maps (must be renamed to .sv1 extension)
0.1.4
0.1.4 (2004-03-25)
------------------------------------------------------------------------
- Feature: crash submit system on win32
- Fix: train smoke clouds
- Fix: train engine sounds
@@ -1548,9 +875,8 @@
- Fix: Get remaining disk space on most Unix-en (rob)
- Fix: screen went black when resizing
0.1.3
0.1.3 (2004-03-18)
------------------------------------------------------------------------
- Fixed message options window
- Fixed company takeover/purchase
- Feature: Improved mouse scroll zooming
@@ -1571,16 +897,14 @@
- Possibility to use either semaphores or signals (Ctrl key)
- Limited the scrolling rate for year selector in scenario editor
0.1.2
0.1.2 (2004-03-15)
------------------------------------------------------------------------
- Mouse wheel can be used to zoom in out on win32 (ludde)
- Implemented some support for resizing the window dynamically in win32 (ludde)
- Fixed tunnel mouse icon for maglev and monorail
0.1.1
0.1.1 (2004-03-14)
------------------------------------------------------------------------
- Preliminary presignal support
- Added external MIDI driver for unix version (by robertnorris)
- Added DirectMusic driver for Win32 version

File diff suppressed because it is too large Load Diff

View File

@@ -1,145 +0,0 @@
/* $Id$ */
#ifndef CLEAR_MAP_H
#define CLEAR_MAP_H
#include "macros.h"
#include "tile.h"
/* ground type, m5 bits 2...4
* valid densities (bits 0...1) in comments after the enum
*/
typedef enum ClearGround {
CLEAR_GRASS = 0, // 0-3
CLEAR_ROUGH = 1, // 3
CLEAR_ROCKS = 2, // 3
CLEAR_FIELDS = 3, // 3
CLEAR_SNOW = 4, // 0-3
CLEAR_DESERT = 5 // 1,3
} ClearGround;
static inline ClearGround GetClearGround(TileIndex t)
{
assert(IsTileType(t, MP_CLEAR));
return GB(_m[t].m5, 2, 3);
}
static inline bool IsClearGround(TileIndex t, ClearGround ct)
{
return GetClearGround(t) == ct;
}
static inline uint GetClearDensity(TileIndex t)
{
assert(IsTileType(t, MP_CLEAR));
return GB(_m[t].m5, 0, 2);
}
static inline void AddClearDensity(TileIndex t, int d)
{
assert(IsTileType(t, MP_CLEAR)); // XXX incomplete
_m[t].m5 += d;
}
static inline uint GetClearCounter(TileIndex t)
{
assert(IsTileType(t, MP_CLEAR));
return GB(_m[t].m5, 5, 3);
}
static inline void AddClearCounter(TileIndex t, int c)
{
assert(IsTileType(t, MP_CLEAR)); // XXX incomplete
_m[t].m5 += c << 5;
}
static inline void SetClearCounter(TileIndex t, uint c)
{
assert(IsTileType(t, MP_CLEAR)); // XXX incomplete
SB(_m[t].m5, 5, 3, c);
}
/* Sets type and density in one go, also sets the counter to 0 */
static inline void SetClearGroundDensity(TileIndex t, ClearGround type, uint density)
{
assert(IsTileType(t, MP_CLEAR)); // XXX incomplete
_m[t].m5 = 0 << 5 | type << 2 | density;
}
static inline uint GetFieldType(TileIndex t)
{
assert(GetClearGround(t) == CLEAR_FIELDS);
return GB(_m[t].m3, 0, 4);
}
static inline void SetFieldType(TileIndex t, uint f)
{
assert(GetClearGround(t) == CLEAR_FIELDS); // XXX incomplete
SB(_m[t].m3, 0, 4, f);
}
static inline uint16 GetIndustryIndexOfField(TileIndex t)
{
assert(GetClearGround(t) == CLEAR_FIELDS);
return _m[t].m2;
}
static inline void SetIndustryIndexOfField(TileIndex t, uint16 i)
{
assert(GetClearGround(t) == CLEAR_FIELDS);
_m[t].m2 = i;
}
/* Is used by tree tiles, too */
static inline uint GetFenceSE(TileIndex t)
{
assert(IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES));
return GB(_m[t].m4, 2, 3);
}
static inline void SetFenceSE(TileIndex t, uint h)
{
assert(IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)); // XXX incomplete
SB(_m[t].m4, 2, 3, h);
}
static inline uint GetFenceSW(TileIndex t)
{
assert(IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES));
return GB(_m[t].m4, 5, 3);
}
static inline void SetFenceSW(TileIndex t, uint h)
{
assert(IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)); // XXX incomplete
SB(_m[t].m4, 5, 3, h);
}
static inline void MakeClear(TileIndex t, ClearGround g, uint density)
{
SetTileType(t, MP_CLEAR);
SetTileOwner(t, OWNER_NONE);
_m[t].m2 = 0;
_m[t].m3 = 0;
_m[t].m4 = 0 << 5 | 0 << 2;
SetClearGroundDensity(t, g, density);
}
static inline void MakeField(TileIndex t, uint field_type, uint16 industry)
{
SetTileType(t, MP_CLEAR);
SetTileOwner(t, OWNER_NONE);
_m[t].m2 = industry;
_m[t].m3 = field_type;
_m[t].m4 = 0 << 5 | 0 << 2;
SetClearGroundDensity(t, CLEAR_FIELDS, 3);
}
#endif /* CLEAR_MAP_H */

147
command.c
View File

@@ -1,20 +1,15 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "table/strings.h"
#include "functions.h"
#include "map.h"
#include "gui.h"
#include "command.h"
#include "player.h"
#include "network.h"
#include "variables.h"
#include "genworld.h"
const char* _cmd_text = NULL;
#define DEF_COMMAND(yyyy) int32 yyyy(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
#define DEF_COMMAND(yyyy) int32 yyyy(int x, int y, uint32 flags, uint32 p1, uint32 p2)
DEF_COMMAND(CmdBuildRailroadTrack);
DEF_COMMAND(CmdRemoveRailroadTrack);
@@ -78,7 +73,7 @@ DEF_COMMAND(CmdModifyOrder);
DEF_COMMAND(CmdSkipOrder);
DEF_COMMAND(CmdDeleteOrder);
DEF_COMMAND(CmdInsertOrder);
DEF_COMMAND(CmdChangeServiceInt);
DEF_COMMAND(CmdChangeTrainServiceInt);
DEF_COMMAND(CmdRestoreOrderIndex);
DEF_COMMAND(CmdBuildIndustry);
@@ -104,6 +99,7 @@ DEF_COMMAND(CmdSellAircraft);
DEF_COMMAND(CmdStartStopAircraft);
DEF_COMMAND(CmdBuildAircraft);
DEF_COMMAND(CmdSendAircraftToHangar);
DEF_COMMAND(CmdChangeAircraftServiceInt);
DEF_COMMAND(CmdRefitAircraft);
DEF_COMMAND(CmdPlaceSign);
@@ -114,7 +110,7 @@ DEF_COMMAND(CmdStartStopRoadVeh);
DEF_COMMAND(CmdSellRoadVeh);
DEF_COMMAND(CmdSendRoadVehToDepot);
DEF_COMMAND(CmdTurnRoadVeh);
DEF_COMMAND(CmdRefitRoadVeh);
DEF_COMMAND(CmdChangeRoadVehServiceInt);
DEF_COMMAND(CmdPause);
@@ -136,9 +132,9 @@ DEF_COMMAND(CmdStartStopShip);
DEF_COMMAND(CmdSellShip);
DEF_COMMAND(CmdBuildShip);
DEF_COMMAND(CmdSendShipToDepot);
DEF_COMMAND(CmdChangeShipServiceInt);
DEF_COMMAND(CmdRefitShip);
DEF_COMMAND(CmdOrderRefit);
DEF_COMMAND(CmdCloneOrder);
DEF_COMMAND(CmdClearArea);
@@ -157,12 +153,7 @@ DEF_COMMAND(CmdRefitRailVehicle);
DEF_COMMAND(CmdBuildSignalTrack);
DEF_COMMAND(CmdRemoveSignalTrack);
DEF_COMMAND(CmdSetAutoReplace);
DEF_COMMAND(CmdCloneVehicle);
DEF_COMMAND(CmdMassStartStopVehicle);
DEF_COMMAND(CmdDepotSellAllVehicles);
DEF_COMMAND(CmdDepotMassAutoReplace);
DEF_COMMAND(CmdReplaceVehicle);
/* The master command table */
static const Command _command_proc_table[] = {
@@ -214,7 +205,7 @@ static const Command _command_proc_table[] = {
{CmdDeleteOrder, 0}, /* 44 */
{CmdInsertOrder, 0}, /* 45 */
{CmdChangeServiceInt, 0}, /* 46 */
{CmdChangeTrainServiceInt, 0}, /* 46 */
{CmdBuildIndustry, 0}, /* 47 */
{CmdBuildCompanyHQ, 0}, /* 48 */
@@ -239,7 +230,7 @@ static const Command _command_proc_table[] = {
{CmdBuildAircraft, 0}, /* 61 */
{CmdSendAircraftToHangar, 0}, /* 62 */
{NULL, 0}, /* 63 */
{CmdChangeAircraftServiceInt, 0}, /* 63 */
{CmdRefitAircraft, 0}, /* 64 */
{CmdPlaceSign, 0}, /* 65 */
@@ -250,7 +241,7 @@ static const Command _command_proc_table[] = {
{CmdSellRoadVeh, 0}, /* 69 */
{CmdSendRoadVehToDepot, 0}, /* 70 */
{CmdTurnRoadVeh, 0}, /* 71 */
{CmdRefitRoadVeh, 0}, /* 72 */
{CmdChangeRoadVehServiceInt, 0}, /* 72 */
{CmdPause, CMD_SERVER}, /* 73 */
@@ -273,7 +264,7 @@ static const Command _command_proc_table[] = {
{CmdSellShip, 0}, /* 87 */
{CmdBuildShip, 0}, /* 88 */
{CmdSendShipToDepot, 0}, /* 89 */
{NULL, 0}, /* 90 */
{CmdChangeShipServiceInt, 0}, /* 90 */
{CmdRefitShip, 0}, /* 91 */
{NULL, 0}, /* 92 */
@@ -282,8 +273,8 @@ static const Command _command_proc_table[] = {
{NULL, 0}, /* 95 */
{NULL, 0}, /* 96 */
{NULL, 0}, /* 97 */
{NULL, 0}, /* 98 */
{CmdOrderRefit, 0}, /* 98 */
{CmdCloneOrder, 0}, /* 99 */
{CmdClearArea, 0}, /* 100 */
@@ -304,61 +295,64 @@ static const Command _command_proc_table[] = {
{NULL, 0}, /* 112 */
{CmdGiveMoney, 0}, /* 113 */
{CmdChangePatchSetting, CMD_SERVER}, /* 114 */
{CmdSetAutoReplace, 0}, /* 115 */
{CmdCloneVehicle, 0}, /* 116 */
{CmdMassStartStopVehicle, 0}, /* 117 */
{CmdDepotSellAllVehicles, 0}, /* 118 */
{CmdDepotMassAutoReplace, 0}, /* 119 */
{CmdReplaceVehicle, 0}, /* 115 */
};
/* This function range-checks a cmd, and checks if the cmd is not NULL */
bool IsValidCommand(uint cmd)
{
cmd &= 0xFF;
cmd = cmd & 0xFF;
return
cmd < lengthof(_command_proc_table) &&
_command_proc_table[cmd].proc != NULL;
if (cmd >= lengthof(_command_proc_table) || _command_proc_table[cmd].proc == NULL)
return false;
return true;
}
byte GetCommandFlags(uint cmd)
byte GetCommandFlags(uint cmd) {return _command_proc_table[cmd & 0xFF].flags;}
int32 DoCommandByTile(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc)
{
return _command_proc_table[cmd & 0xFF].flags;
return DoCommand(TileX(tile) * 16, TileY(tile) * 16, p1, p2, flags, procc);
}
static int _docommand_recursive;
//extern void _stdcall Sleep(int s);
int32 DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc)
int32 DoCommand(int x, int y, uint32 p1, uint32 p2, uint32 flags, uint procc)
{
int32 res;
CommandProc *proc;
/* Do not even think about executing out-of-bounds tile-commands */
if (tile >= MapSize() || IsTileType(tile, MP_VOID)) {
if (TILE_FROM_XY(x,y) > MapSize()) {
_cmd_text = NULL;
return CMD_ERROR;
}
proc = _command_proc_table[procc].proc;
if (_docommand_recursive == 0) _error_message = INVALID_STRING_ID;
if (_docommand_recursive == 0) {
_error_message = INVALID_STRING_ID;
// update last build coord of player
if ( (x|y) != 0 && _current_player < MAX_PLAYERS) {
DEREF_PLAYER(_current_player)->last_build_coordinate = TILE_FROM_XY(x,y);
}
}
_docommand_recursive++;
// only execute the test call if it's toplevel, or we're not execing.
if (_docommand_recursive == 1 || !(flags & DC_EXEC) || (flags & DC_FORCETEST) ) {
res = proc(tile, flags & ~DC_EXEC, p1, p2);
res = proc(x, y, flags&~DC_EXEC, p1, p2);
if (CmdFailed(res)) {
if (res & 0xFFFF) _error_message = res & 0xFFFF;
goto error;
}
if (_docommand_recursive == 1 &&
!(flags & DC_QUERY_COST) &&
res != 0 &&
!CheckPlayerHasMoney(res)) {
goto error;
if (_docommand_recursive == 1) {
if (!(flags&DC_QUERY_COST) && res != 0 && !CheckPlayerHasMoney(res))
goto error;
}
if (!(flags & DC_EXEC)) {
@@ -370,7 +364,7 @@ int32 DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc)
/* Execute the command here. All cost-relevant functions set the expenses type
* themselves with "SET_EXPENSES_TYPE(...);" at the beginning of the function */
res = proc(tile, flags, p1, p2);
res = proc(x, y, flags, p1, p2);
if (CmdFailed(res)) {
if (res & 0xFFFF) _error_message = res & 0xFFFF;
error:
@@ -382,10 +376,6 @@ error:
// if toplevel, subtract the money.
if (--_docommand_recursive == 0) {
SubtractMoneyFromPlayer(res);
// XXX - Old AI hack which doesn't use DoCommandDP; update last build coord of player
if (tile != 0 && IsValidPlayer(_current_player)) {
GetPlayer(_current_player)->last_build_coordinate = tile;
}
}
_cmd_text = NULL;
@@ -395,8 +385,8 @@ error:
int32 GetAvailableMoneyForCommand(void)
{
PlayerID pid = _current_player;
if (!IsValidPlayer(pid)) return 0x7FFFFFFF; // max int
return GetPlayer(pid)->player_money;
if (pid >= MAX_PLAYERS) return 0x7FFFFFFF; // max int
return DEREF_PLAYER(pid)->player_money;
}
// toplevel network safe docommand function for the current player. must not be called recursively.
@@ -407,13 +397,12 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
CommandProc *proc;
uint32 flags;
bool notest;
StringID error_part1;
int x = TileX(tile) * TILE_SIZE;
int y = TileY(tile) * TILE_SIZE;
int x = TileX(tile) * 16;
int y = TileY(tile) * 16;
/* Do not even think about executing out-of-bounds tile-commands */
if (tile >= MapSize() || IsTileType(tile, MP_VOID)) {
if (tile > MapSize()) {
_cmd_text = NULL;
return false;
}
@@ -421,13 +410,13 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
assert(_docommand_recursive == 0);
_error_message = INVALID_STRING_ID;
error_part1 = GB(cmd, 16, 16);
_error_message_2 = cmd >> 16;
_additional_cash_required = 0;
/** Spectator has no rights except for the (dedicated) server which
* is/can be a spectator but as the server it can do anything */
if (_current_player == PLAYER_SPECTATOR && !_network_server) {
ShowErrorMessage(_error_message, error_part1, x, y);
/** Spectator has no rights except for the dedicated server which
* is a spectator but is the server, so can do anything */
if (_current_player == OWNER_SPECTATOR && !_network_dedicated) {
ShowErrorMessage(_error_message, _error_message_2, x, y);
_cmd_text = NULL;
return false;
}
@@ -439,10 +428,6 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
// get pointer to command handler
assert((cmd & 0xFF) < lengthof(_command_proc_table));
proc = _command_proc_table[cmd & 0xFF].proc;
if (proc == NULL) {
_cmd_text = NULL;
return false;
}
// Some commands have a different output in dryrun than the realrun
// e.g.: if you demolish a whole town, the dryrun would say okay.
@@ -463,16 +448,12 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
_docommand_recursive = 1;
// cost estimation only?
if (!IsGeneratingWorld() &&
_shift_pressed &&
IsLocalPlayer() &&
!(cmd & (CMD_NETWORK_COMMAND | CMD_SHOW_NO_ERROR)) &&
(cmd & 0xFF) != CMD_PAUSE) {
if (_shift_pressed && _current_player == _local_player && !(cmd & (CMD_NETWORK_COMMAND | CMD_SHOW_NO_ERROR))) {
// estimate the cost.
res = proc(tile, flags, p1, p2);
res = proc(x, y, flags, p1, p2);
if (CmdFailed(res)) {
if (res & 0xFFFF) _error_message = res & 0xFFFF;
ShowErrorMessage(_error_message, error_part1, x, y);
ShowErrorMessage(_error_message, _error_message_2, x, y);
} else {
ShowEstimatedCostOrIncome(res, x, y);
}
@@ -485,7 +466,7 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
if (!((cmd & CMD_NO_TEST_IF_IN_NETWORK) && _networking)) {
// first test if the command can be executed.
res = proc(tile, flags, p1, p2);
res = proc(x,y, flags, p1, p2);
if (CmdFailed(res)) {
if (res & 0xFFFF) _error_message = res & 0xFFFF;
goto show_error;
@@ -499,14 +480,12 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
* send it to the command-queue and abort execution
* If we are a dedicated server temporarily switch local player, 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!
* @todo Rewrite dedicated server to something more than a dirty hack!
*/
if (_networking && !(cmd & CMD_NETWORK_COMMAND)) {
PlayerID pbck = _local_player;
if (_network_dedicated || (_network_server && pbck == PLAYER_SPECTATOR)) _local_player = 0;
if (_network_dedicated) _local_player = 0;
NetworkSend_Command(tile, p1, p2, cmd, callback);
if (_network_dedicated || (_network_server && pbck == PLAYER_SPECTATOR)) _local_player = pbck;
if (_network_dedicated) _local_player = OWNER_SPECTATOR;
_docommand_recursive = 0;
_cmd_text = NULL;
return true;
@@ -514,14 +493,12 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
#endif /* ENABLE_NETWORK */
// update last build coordinate of player.
if (tile != 0 && IsValidPlayer(_current_player)) {
GetPlayer(_current_player)->last_build_coordinate = tile;
}
if ( tile != 0 && _current_player < MAX_PLAYERS) DEREF_PLAYER(_current_player)->last_build_coordinate = tile;
/* Actually try and execute the command. If no cost-type is given
* use the construction one */
_yearly_expenses_type = EXPENSES_CONSTRUCTION;
res2 = proc(tile, flags | DC_EXEC, p1, p2);
res2 = proc(x,y, flags|DC_EXEC, p1, p2);
// If notest is on, it means the result of the test can be different than
// the real command.. so ignore the test
@@ -536,11 +513,12 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
SubtractMoneyFromPlayer(res2);
if (IsLocalPlayer() && _game_mode != GM_EDITOR) {
if (res2 != 0) ShowCostOrIncomeAnimation(x, y, GetSlopeZ(x, y), res2);
if (_current_player == _local_player && _game_mode != GM_EDITOR) {
if (res2 != 0)
ShowCostOrIncomeAnimation(x, y, GetSlopeZ(x, y), res2);
if (_additional_cash_required) {
SetDParam(0, _additional_cash_required);
ShowErrorMessage(STR_0003_NOT_ENOUGH_CASH_REQUIRES, error_part1, x,y);
ShowErrorMessage(STR_0003_NOT_ENOUGH_CASH_REQUIRES, _error_message_2, x,y);
if (res2 == 0) goto callb_err;
}
}
@@ -553,9 +531,8 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback,
show_error:
// show error message if the command fails?
if (IsLocalPlayer() && error_part1 != 0) {
ShowErrorMessage(_error_message, error_part1, x,y);
}
if (_current_player == _local_player && _error_message_2 != 0)
ShowErrorMessage(_error_message, _error_message_2, x,y);
callb_err:
_docommand_recursive = 0;

236
command.h
View File

@@ -1,156 +1,150 @@
/* $Id$ */
#ifndef COMMAND_H
#define COMMAND_H
enum {
CMD_BUILD_RAILROAD_TRACK = 0,
CMD_REMOVE_RAILROAD_TRACK = 1,
CMD_BUILD_SINGLE_RAIL = 2,
CMD_REMOVE_SINGLE_RAIL = 3,
CMD_LANDSCAPE_CLEAR = 4,
CMD_BUILD_BRIDGE = 5,
CMD_BUILD_RAILROAD_STATION = 6,
CMD_BUILD_TRAIN_DEPOT = 7,
CMD_BUILD_SIGNALS = 8,
CMD_REMOVE_SIGNALS = 9,
CMD_TERRAFORM_LAND = 10,
CMD_PURCHASE_LAND_AREA = 11,
CMD_SELL_LAND_AREA = 12,
CMD_BUILD_TUNNEL = 13,
CMD_BUILD_RAILROAD_TRACK = 0,
CMD_REMOVE_RAILROAD_TRACK = 1,
CMD_BUILD_SINGLE_RAIL = 2,
CMD_REMOVE_SINGLE_RAIL = 3,
CMD_LANDSCAPE_CLEAR = 4,
CMD_BUILD_BRIDGE = 5,
CMD_BUILD_RAILROAD_STATION = 6,
CMD_BUILD_TRAIN_DEPOT = 7,
CMD_BUILD_SIGNALS = 8,
CMD_REMOVE_SIGNALS = 9,
CMD_TERRAFORM_LAND = 10,
CMD_PURCHASE_LAND_AREA = 11,
CMD_SELL_LAND_AREA = 12,
CMD_BUILD_TUNNEL = 13,
CMD_REMOVE_FROM_RAILROAD_STATION = 14,
CMD_CONVERT_RAIL = 15,
CMD_REMOVE_FROM_RAILROAD_STATION = 14,
CMD_CONVERT_RAIL = 15,
CMD_BUILD_TRAIN_WAYPOINT = 16,
CMD_RENAME_WAYPOINT = 17,
CMD_REMOVE_TRAIN_WAYPOINT = 18,
CMD_BUILD_TRAIN_WAYPOINT = 16,
CMD_RENAME_WAYPOINT = 17,
CMD_REMOVE_TRAIN_WAYPOINT = 18,
CMD_BUILD_ROAD_STOP = 21,
CMD_BUILD_LONG_ROAD = 23,
CMD_REMOVE_LONG_ROAD = 24,
CMD_BUILD_ROAD = 25,
CMD_REMOVE_ROAD = 26,
CMD_BUILD_ROAD_DEPOT = 27,
CMD_BUILD_ROAD_STOP = 21,
CMD_BUILD_LONG_ROAD = 23,
CMD_REMOVE_LONG_ROAD = 24,
CMD_BUILD_ROAD = 25,
CMD_REMOVE_ROAD = 26,
CMD_BUILD_ROAD_DEPOT = 27,
CMD_BUILD_AIRPORT = 29,
CMD_BUILD_AIRPORT = 29,
CMD_BUILD_DOCK = 30,
CMD_BUILD_DOCK = 30,
CMD_BUILD_SHIP_DEPOT = 31,
CMD_BUILD_BUOY = 32,
CMD_BUILD_SHIP_DEPOT = 31,
CMD_BUILD_BUOY = 32,
CMD_PLANT_TREE = 33,
CMD_PLANT_TREE = 33,
CMD_BUILD_RAIL_VEHICLE = 34,
CMD_MOVE_RAIL_VEHICLE = 35,
CMD_BUILD_RAIL_VEHICLE = 34,
CMD_MOVE_RAIL_VEHICLE = 35,
CMD_START_STOP_TRAIN = 36,
CMD_START_STOP_TRAIN = 36,
CMD_SELL_RAIL_WAGON = 38,
CMD_SELL_RAIL_WAGON = 38,
CMD_SEND_TRAIN_TO_DEPOT = 39,
CMD_FORCE_TRAIN_PROCEED = 40,
CMD_REVERSE_TRAIN_DIRECTION = 41,
CMD_TRAIN_GOTO_DEPOT = 39,
CMD_FORCE_TRAIN_PROCEED = 40,
CMD_REVERSE_TRAIN_DIRECTION = 41,
CMD_MODIFY_ORDER = 42,
CMD_SKIP_ORDER = 43,
CMD_DELETE_ORDER = 44,
CMD_INSERT_ORDER = 45,
CMD_MODIFY_ORDER = 42,
CMD_SKIP_ORDER = 43,
CMD_DELETE_ORDER = 44,
CMD_INSERT_ORDER = 45,
CMD_CHANGE_SERVICE_INT = 46,
CMD_CHANGE_TRAIN_SERVICE_INT = 46,
CMD_BUILD_INDUSTRY = 47,
CMD_BUILD_INDUSTRY = 47,
CMD_BUILD_COMPANY_HQ = 48,
CMD_SET_PLAYER_FACE = 49,
CMD_SET_PLAYER_COLOR = 50,
CMD_BUILD_COMPANY_HQ = 48,
CMD_SET_PLAYER_FACE = 49,
CMD_SET_PLAYER_COLOR = 50,
CMD_INCREASE_LOAN = 51,
CMD_DECREASE_LOAN = 52,
CMD_INCREASE_LOAN = 51,
CMD_DECREASE_LOAN = 52,
CMD_WANT_ENGINE_PREVIEW = 53,
CMD_WANT_ENGINE_PREVIEW = 53,
CMD_NAME_VEHICLE = 54,
CMD_RENAME_ENGINE = 55,
CMD_CHANGE_COMPANY_NAME = 56,
CMD_CHANGE_PRESIDENT_NAME = 57,
CMD_RENAME_STATION = 58,
CMD_NAME_VEHICLE = 54,
CMD_RENAME_ENGINE = 55,
CMD_CHANGE_COMPANY_NAME = 56,
CMD_CHANGE_PRESIDENT_NAME = 57,
CMD_RENAME_STATION = 58,
CMD_SELL_AIRCRAFT = 59,
CMD_START_STOP_AIRCRAFT = 60,
CMD_BUILD_AIRCRAFT = 61,
CMD_SEND_AIRCRAFT_TO_HANGAR = 62,
CMD_REFIT_AIRCRAFT = 64,
CMD_SELL_AIRCRAFT = 59,
CMD_START_STOP_AIRCRAFT = 60,
CMD_BUILD_AIRCRAFT = 61,
CMD_SEND_AIRCRAFT_TO_HANGAR = 62,
CMD_CHANGE_AIRCRAFT_SERVICE_INT = 63,
CMD_REFIT_AIRCRAFT = 64,
CMD_PLACE_SIGN = 65,
CMD_RENAME_SIGN = 66,
CMD_PLACE_SIGN = 65,
CMD_RENAME_SIGN = 66,
CMD_BUILD_ROAD_VEH = 67,
CMD_START_STOP_ROADVEH = 68,
CMD_SELL_ROAD_VEH = 69,
CMD_SEND_ROADVEH_TO_DEPOT = 70,
CMD_TURN_ROADVEH = 71,
CMD_REFIT_ROAD_VEH = 72,
CMD_BUILD_ROAD_VEH = 67,
CMD_START_STOP_ROADVEH = 68,
CMD_SELL_ROAD_VEH = 69,
CMD_SEND_ROADVEH_TO_DEPOT = 70,
CMD_TURN_ROADVEH = 71,
CMD_CHANGE_ROADVEH_SERVICE_INT = 72,
CMD_PAUSE = 73,
CMD_PAUSE = 73,
CMD_BUY_SHARE_IN_COMPANY = 74,
CMD_SELL_SHARE_IN_COMPANY = 75,
CMD_BUY_COMPANY = 76,
CMD_BUY_SHARE_IN_COMPANY = 74,
CMD_SELL_SHARE_IN_COMPANY = 75,
CMD_BUY_COMPANY = 76,
CMD_BUILD_TOWN = 77,
CMD_BUILD_TOWN = 77,
CMD_RENAME_TOWN = 80,
CMD_DO_TOWN_ACTION = 81,
CMD_RENAME_TOWN = 80,
CMD_DO_TOWN_ACTION = 81,
CMD_SET_ROAD_DRIVE_SIDE = 82,
CMD_SET_ROAD_DRIVE_SIDE = 82,
CMD_CHANGE_DIFFICULTY_LEVEL = 85,
CMD_CHANGE_DIFFICULTY_LEVEL = 85,
CMD_START_STOP_SHIP = 86,
CMD_SELL_SHIP = 87,
CMD_BUILD_SHIP = 88,
CMD_SEND_SHIP_TO_DEPOT = 89,
CMD_REFIT_SHIP = 91,
CMD_START_STOP_SHIP = 86,
CMD_SELL_SHIP = 87,
CMD_BUILD_SHIP = 88,
CMD_SEND_SHIP_TO_DEPOT = 89,
CMD_CHANGE_SHIP_SERVICE_INT = 90,
CMD_REFIT_SHIP = 91,
CMD_ORDER_REFIT = 98,
CMD_CLONE_ORDER = 99,
CMD_CLEAR_AREA = 100,
CMD_CLONE_ORDER = 99,
CMD_CLEAR_AREA = 100,
CMD_MONEY_CHEAT = 102,
CMD_BUILD_CANAL = 103,
CMD_MONEY_CHEAT = 102,
CMD_BUILD_CANAL = 103,
CMD_PLAYER_CTRL = 104, // used in multiplayer to create a new player etc.
CMD_LEVEL_LAND = 105, // level land
CMD_PLAYER_CTRL = 104, // used in multiplayer to create a new player etc.
CMD_LEVEL_LAND = 105, // level land
CMD_REFIT_RAIL_VEHICLE = 106,
CMD_RESTORE_ORDER_INDEX = 107,
CMD_BUILD_LOCK = 108,
CMD_REFIT_RAIL_VEHICLE = 106,
CMD_RESTORE_ORDER_INDEX = 107,
CMD_BUILD_LOCK = 108,
CMD_BUILD_SIGNAL_TRACK = 110,
CMD_REMOVE_SIGNAL_TRACK = 111,
CMD_BUILD_SIGNAL_TRACK = 110,
CMD_REMOVE_SIGNAL_TRACK = 111,
CMD_GIVE_MONEY = 113,
CMD_CHANGE_PATCH_SETTING = 114,
CMD_GIVE_MONEY = 113,
CMD_CHANGE_PATCH_SETTING = 114,
CMD_SET_AUTOREPLACE = 115,
CMD_CLONE_VEHICLE = 116,
CMD_MASS_START_STOP = 117,
CMD_DEPOT_SELL_ALL_VEHICLES = 118,
CMD_DEPOT_MASS_AUTOREPLACE = 119,
CMD_REPLACE_VEHICLE = 115,
};
enum {
DC_EXEC = 0x01,
DC_AUTO = 0x02, // don't allow building on structures
DC_QUERY_COST = 0x04, // query cost only, don't build.
DC_NO_WATER = 0x08, // don't allow building on water
DC_NO_RAIL_OVERLAP = 0x10, // don't allow overlap of rails (used in buildrail)
DC_AI_BUILDING = 0x20, // special building rules for AI
DC_NO_TOWN_RATING = 0x40, // town rating does not disallow you from building
DC_FORCETEST = 0x80, // force test too.
DC_EXEC = 1,
DC_AUTO = 2, // don't allow building on structures
DC_QUERY_COST = 4, // query cost only, don't build.
DC_NO_WATER = 8, // don't allow building on water
DC_NO_RAIL_OVERLAP = 0x10, // don't allow overlap of rails (used in buildrail)
DC_AI_BUILDING = 0x20, // special building rules for AI
DC_NO_TOWN_RATING = 0x40, // town rating does not disallow you from building
DC_FORCETEST = 0x80, // force test too.
CMD_ERROR = ((int32)0x80000000),
};
@@ -158,11 +152,11 @@ enum {
#define CMD_MSG(x) ((x)<<16)
enum {
CMD_AUTO = 0x0200,
CMD_NO_WATER = 0x0400,
CMD_NETWORK_COMMAND = 0x0800, // execute the command without sending it on the network
CMD_AUTO = 0x200,
CMD_NO_WATER = 0x400,
CMD_NETWORK_COMMAND = 0x800, // execute the command without sending it on the network
CMD_NO_TEST_IF_IN_NETWORK = 0x1000, // When enabled, the command will bypass the no-DC_EXEC round if in network
CMD_SHOW_NO_ERROR = 0x2000,
CMD_SHOW_NO_ERROR = 0x2000,
};
/** Command flags for the command table
@@ -173,8 +167,6 @@ enum {
CMD_OFFLINE = 0x2, /// the command cannot be executed in a multiplayer game; single-player only
};
typedef int32 CommandProc(TileIndex tile, uint32 flags, uint32 p1, uint32 p2);
typedef struct Command {
CommandProc *proc;
byte flags;
@@ -195,14 +187,8 @@ static inline bool CmdFailed(int32 res)
}
/* command.c */
typedef void CommandCallback(bool success, TileIndex tile, uint32 p1, uint32 p2);
int32 DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc);
bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, CommandCallback *callback, uint32 cmd);
#ifdef ENABLE_NETWORK
void NetworkSend_Command(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback);
#endif /* ENABLE_NETWORK */
int32 DoCommand(int x, int y, uint32 p1, uint32 p2, uint32 flags, uint procc);
int32 DoCommandByTile(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc);
extern const char* _cmd_text; // Text, which gets sent with a command

323
configure vendored
View File

@@ -1,323 +0,0 @@
#!/bin/sh
# This 'configure' script is a very easy wrapper around 'make updateconf'
# It allows cross-compilers to do their job much more easy.
showhelp() {
echo "Configure for OpenTTD"
echo ""
echo "Usage:"
echo " $0 --your_options"
echo ""
echo "Params:"
echo " --debug Create debug-release [no]"
echo " --profile Create profile-release [no]"
echo " --dedicated Make a dedicated build [no]"
echo " --revision Set the revision of the compilation [detected]"
echo " --target-cc Sets the target-compiler [\$CC]"
echo " --target-cxx Sets the C++ target-compiler []"
echo " --host-cc Sets the host-compiler [\$CC]"
echo " --host-cxx Sets the C++ host-compiler []"
echo " --os Sets the OS. Listens to: [detected]"
echo " UNIX, OSX, FREEBSD, MORPHOS"
echo " BEOS, SUNOS, CYGWIN, MINGW, OS2"
echo " --windres Sets the windres (Windows) [windres]"
echo " --force-le Force LE platform [no]"
echo " --force-be Force BE platform [no]"
echo ""
echo "Params that can be used with --with or --without"
echo " (e.g.: --without-static disables static (default))"
echo " static Do you want a static build? [no]"
echo " directmusic Do you want direct-music? [no]"
echo " zlib Do you want zlib-support? [yes]"
echo " sdl Do you want SDL-support? [yes]"
echo " png Do you want PNG-support? [yes]"
echo " iconv Do you want iconv-support? [no]"
echo " network Do you want network-support? [yes]"
echo " cocoa Do you want cocoa-support? (MacOSX) [no]"
echo " freetype Do you want freetype-support? [yes]"
echo " fontconfig Do you want fontconfig-support? [yes]"
echo ""
echo "Params used to configure external libs:"
echo " --static-zlib-path Set the path to your static zlib []"
echo " --sdl-config Where is your sdl-config [sdl-config]"
echo " --libpng-config Where is your libpng-config [libpng-config]"
echo " --freetype-config Where is your freetype-config [freetype-config]"
echo " --fontconfig-config Where is your fontconfig-config [pkg-config fontconfig]"
echo " --with-iconv Set the path to your iconv headers []"
echo " "
}
handle() {
PARAM="$PARAM \"$1=`awk 'BEGIN { FS="="; $0="'"$2"'"; print $2;}'`\""
}
# The things you can use inside this case:
# handle NAME VALUE - Sets the value to give the 'make upgradeconf'
# Value is in form: tag=REAL_VALUE
# ITEM="NAME" - Will set the value as above, only with the next param
# SITEM="NAME" - Will set the var $NAME to the next param
for n in "$@"
do
case "$n" in
--help | -h)
showhelp
exit 0
;;
--debug)
DEBUG_SET=1
ITEM="DEBUG"
;;
--debug=*)
handle "DEBUG" "$n"
;;
--profile)
PARAM="$PARAM PROFILE=1"
;;
--dedicated)
PARAM="$PARAM DEDICATED=1"
;;
--revision=*)
RELEASE=`awk 'BEGIN { FS="="; $0="'"$n"'"; print $2;}'`
;;
--revision)
SITEM="RELEASE"
;;
--target-cc=*)
handle "CC_TARGET" "$n"
;;
--target-cc)
ITEM="CC_TARGET"
;;
--target-cxx=*)
handle "CXX_TARGET" "$n"
;;
--target-cxx)
SITEM="CXX_TARGET"
;;
--host-cc=*)
handle "CC_HOST" "$n"
;;
--host-cc)
ITEM="CC_HOST"
;;
--host-cxx=*)
handle "CXX_HOST" "$n"
;;
--host-cxx)
ITEM="CXX_HOST"
;;
--host-cflags=*)
handle CFLAGS_HOST "$n"
;;
--host-cflags)
ITEM="CFLAGS_HOST"
;;
--os=*)
TARGET_OS=`awk 'BEGIN { FS="="; $0="'"$n"'"; print $2;}'`
;;
--os)
SITEM="TARGET_OS"
;;
--windres=*)
handle WINDRES "$n"
;;
--windres)
ITEM="WINDRES"
;;
--force-le)
PARAM="$PARAM ENDIAN_FORCE=LE"
;;
--force-be)
PARAM="$PARAM ENDIAN_FORCE=BE"
;;
--with-static)
PARAM="$PARAM STATIC=1"
;;
--without-static)
PARAM="$PARAM STATIC="
;;
--with-directmusic)
PARAM="$PARAM WITH_DIRECTMUSIC=1"
;;
--without-directmusic)
PARAM="$PARAM WITH_DIRECTMUSIC="
;;
--with-zlib)
PARAM="$PARAM WITH_ZLIB=1"
;;
--without-zlib)
PARAM="$PARAM WITH_ZLIB="
;;
--with-sdl)
PARAM="$PARAM WITH_SDL=1"
;;
--without-sdl)
PARAM="$PARAM WITH_SDL="
;;
--with-png)
PARAM="$PARAM WITH_PNG=1"
;;
--without-png)
PARAM="$PARAM WITH_PNG="
;;
--with-iconv)
PARAM="$PARAM WITH_ICONV=1"
;;
--with-iconv=*)
PARAM="$PARAM WITH_ICONV=1"
handle WITH_ICONV_PATH "$n"
;;
--without-iconv)
PARAM="$PARAM WITH_ICONV="
;;
--with-cocoa)
PARAM="$PARAM WITH_COCOA=1"
;;
--with-network)
PARAM="$PARAM WITH_NETWORK=1"
;;
--without-network)
PARAM="$PARAM WITH_NETWORK="
;;
--without-cocoa)
PARAM="$PARAM WITH_COCOA="
;;
--with-freetype)
PARAM="$PARAM WITH_FREETYPE=1"
;;
--without-freetype)
PARAM="$PARAM WITH_FREETYPE="
;;
--with-fontconfig)
PARAM="$PARAM WITH_FONTCONFIG=1"
;;
--without-fontconfig)
PARAM="$PARAM WITH_FONTCONFIG="
;;
--static-zlib-path=*)
handle STATIC_ZLIB_PATH "$n"
;;
--static-zlib-path)
ITEM="STATIC_ZLIB_PATH"
;;
--sdl-config=*)
handle SDL_CONFIG "$n"
;;
--sdl-config)
ITEM="SDL_CONFIG"
;;
--libpng-config=*)
handle LIBPNG_CONFIG "$n"
;;
--libpng-config)
ITEM="LIBPNG_CONFIG"
;;
--freetype-config=*)
handle FREETYPE_CONFIG "$n"
;;
--freetype-config)
ITEM="FREETYPE_CONFIG"
;;
--fontconfig-config=*)
handle FONTCONFIG_CONFIG "$n"
;;
--fontconfig-config)
ITEM="FONTCONFIG_CONFIG"
;;
--*=*)
echo -n "Unknown switch "
echo `awk 'BEGIN { FS="="; $0="'"$n"'"; print $1;}'`
exit 1
;;
-*)
echo "Unknown switch $n"
exit 1
;;
*)
if ! test -z "$ITEM"
then
PARAM="$PARAM $ITEM=\"$n\""
ITEM="";
elif ! test -z "$SITEM"
then
export $SITEM="$n"
SITEM=""
else
echo "Unknown switch $n"
exit 1
fi
;;
esac
done
if ! test -z "$TARGET_OS"
then
TARGET_OS=`echo $TARGET_OS | tr '[:lower:]' '[:upper:]'`
case "$TARGET_OS" in
WIN32)
PARAM="$PARAM WIN32=1"
;;
UNIX)
PARAM="$PARAM UNIX=1"
;;
OSX)
PARAM="$PARAM OSX=1 UNIX=1"
;;
FREEBSD)
PARAM="$PARAM FREEBSD=1"
;;
MORPHOS)
PARAM="$PARAM MORPHOS=1 UNIX=1"
;;
BEOS)
PARAM="$PARAM BEOS=1 UNIX=1"
;;
OS2)
PARAM="$PARAM OS2=1 UNIX=1"
;;
SUNOS)
PARAM="$PARAM SUNOS=1 UNIX=1"
;;
CYGWIN)
PARAM="$PARAM CYGWIN=1 WIN32=1"
;;
MINGW)
PARAM="$PARAM MINGW=1 WIN32=1"
;;
*)
echo "Unknown OS: $TARGET_OS"
exit 1
;;
esac
PARAM="$PARAM BYPASS_OS_DETECT=1"
fi
if ! test -z "$DEBUG_SET"
then
if test -z "`echo $PARAM | grep "DEBUG="`"
then
# Someone did --debug, without assigning a value, assume 1
PARAM="$PARAM DEBUG=1"
fi
fi
# First remove the Makefile.config, else you can have double entries
rm -f Makefile.config
echo "make upgradeconf $PARAM" > ./Makefile.run
. ./Makefile.run
rm -f ./Makefile.run
# Makefile.config currently doesn't support custom RELEASE (revision), so, we add the line
# yourself!
if ! test -z "$RELEASE"
then
echo "RELEASE=$RELEASE" >> Makefile.config
fi

312
console.c
View File

@@ -1,15 +1,13 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "table/strings.h"
#include "functions.h"
#include "window.h"
#include "gui.h"
#include "gfx.h"
#include "player.h"
#include "variables.h"
#include "string.h"
#include "hal.h"
#include <stdarg.h>
#include <string.h>
#include "console.h"
@@ -26,9 +24,12 @@
#define ICON_TOKEN_COUNT 20
// ** main console ** //
static Window *_iconsole_win; // Pointer to console window
static bool _iconsole_inited;
static char *_iconsole_buffer[ICON_BUFFER + 1];
static uint16 _iconsole_cbuffer[ICON_BUFFER + 1];
static Textbuf _iconsole_cmdline;
static byte _iconsole_scroll;
// ** stdlib ** //
byte _stdlib_developer = 1;
@@ -50,29 +51,23 @@ static void IConsoleClearCommand(void)
_iconsole_cmdline.width = 0;
_iconsole_cmdline.caretpos = 0;
_iconsole_cmdline.caretxoffs = 0;
SetWindowDirty(FindWindowById(WC_CONSOLE, 0));
SetWindowDirty(_iconsole_win);
}
static inline void IConsoleResetHistoryPos(void) {_iconsole_historypos = ICON_HISTORY_SIZE - 1;}
static void IConsoleHistoryAdd(const char *cmd);
static void IConsoleHistoryNavigate(int direction);
// ** console window ** //
static void IConsoleWndProc(Window *w, WindowEvent *e)
static void IConsoleWndProc(Window* w, WindowEvent* e)
{
static byte iconsole_scroll = ICON_BUFFER;
switch (e->event) {
case WE_PAINT: {
int i = iconsole_scroll;
int i = _iconsole_scroll;
int max = (w->height / ICON_LINE_HEIGHT) - 1;
int delta = 0;
GfxFillRect(w->left, w->top, w->width, w->height - 1, 0);
while ((i > 0) && (i > iconsole_scroll - max) && (_iconsole_buffer[i] != NULL)) {
while ((i > 0) && (i > _iconsole_scroll - max) && (_iconsole_buffer[i] != NULL)) {
DoDrawString(_iconsole_buffer[i], 5,
w->height - (iconsole_scroll + 2 - i) * ICON_LINE_HEIGHT, _iconsole_cbuffer[i]);
w->height - (_iconsole_scroll + 2 - i) * ICON_LINE_HEIGHT, _iconsole_cbuffer[i]);
i--;
}
/* If the text is longer than the window, don't show the starting ']' */
@@ -93,11 +88,12 @@ static void IConsoleWndProc(Window *w, WindowEvent *e)
SetWindowDirty(w);
break;
case WE_DESTROY:
_iconsole_win = NULL;
_iconsole_mode = ICONSOLE_CLOSED;
break;
case WE_KEYPRESS:
e->we.keypress.cont = false;
switch (e->we.keypress.keycode) {
e->keypress.cont = false;
switch (e->keypress.keycode) {
case WKC_UP:
IConsoleHistoryNavigate(+1);
SetWindowDirty(w);
@@ -107,35 +103,31 @@ static void IConsoleWndProc(Window *w, WindowEvent *e)
SetWindowDirty(w);
break;
case WKC_SHIFT | WKC_PAGEUP:
if (iconsole_scroll - (w->height / ICON_LINE_HEIGHT) - 1 < 0) {
iconsole_scroll = 0;
} else {
iconsole_scroll -= (w->height / ICON_LINE_HEIGHT) - 1;
}
if (_iconsole_scroll - (w->height / ICON_LINE_HEIGHT) - 1 < 0)
_iconsole_scroll = 0;
else
_iconsole_scroll -= (w->height / ICON_LINE_HEIGHT) - 1;
SetWindowDirty(w);
break;
case WKC_SHIFT | WKC_PAGEDOWN:
if (iconsole_scroll + (w->height / ICON_LINE_HEIGHT) - 1 > ICON_BUFFER) {
iconsole_scroll = ICON_BUFFER;
} else {
iconsole_scroll += (w->height / ICON_LINE_HEIGHT) - 1;
}
if (_iconsole_scroll + (w->height / ICON_LINE_HEIGHT) - 1 > ICON_BUFFER)
_iconsole_scroll = ICON_BUFFER;
else
_iconsole_scroll += (w->height / ICON_LINE_HEIGHT) - 1;
SetWindowDirty(w);
break;
case WKC_SHIFT | WKC_UP:
if (iconsole_scroll <= 0) {
iconsole_scroll = 0;
} else {
--iconsole_scroll;
}
if (_iconsole_scroll <= 0)
_iconsole_scroll = 0;
else
--_iconsole_scroll;
SetWindowDirty(w);
break;
case WKC_SHIFT | WKC_DOWN:
if (iconsole_scroll >= ICON_BUFFER) {
iconsole_scroll = ICON_BUFFER;
} else {
++iconsole_scroll;
}
if (_iconsole_scroll >= ICON_BUFFER)
_iconsole_scroll = ICON_BUFFER;
else
++_iconsole_scroll;
SetWindowDirty(w);
break;
case WKC_BACKQUOTE:
@@ -150,7 +142,7 @@ static void IConsoleWndProc(Window *w, WindowEvent *e)
break;
case WKC_CTRL | WKC_RETURN:
_iconsole_mode = (_iconsole_mode == ICONSOLE_FULL) ? ICONSOLE_OPENED : ICONSOLE_FULL;
IConsoleResize(w);
IConsoleResize();
MarkWholeScreenDirty();
break;
case (WKC_CTRL | 'V'):
@@ -159,34 +151,29 @@ static void IConsoleWndProc(Window *w, WindowEvent *e)
SetWindowDirty(w);
}
break;
case (WKC_CTRL | 'L'):
case (WKC_CTRL | 'L'):
IConsoleCmdExec("clear");
break;
case (WKC_CTRL | 'U'):
DeleteTextBufferAll(&_iconsole_cmdline);
SetWindowDirty(w);
break;
case WKC_BACKSPACE: case WKC_DELETE:
if (DeleteTextBufferChar(&_iconsole_cmdline, e->we.keypress.keycode)) {
if (DeleteTextBufferChar(&_iconsole_cmdline, e->keypress.keycode)) {
IConsoleResetHistoryPos();
SetWindowDirty(w);
}
break;
case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
if (MoveTextBufferPos(&_iconsole_cmdline, e->we.keypress.keycode)) {
if (MoveTextBufferPos(&_iconsole_cmdline, e->keypress.keycode)) {
IConsoleResetHistoryPos();
SetWindowDirty(w);
}
break;
default:
if (IsValidChar(e->we.keypress.key, CS_ALPHANUMERAL)) {
iconsole_scroll = ICON_BUFFER;
InsertTextBufferChar(&_iconsole_cmdline, e->we.keypress.key);
if (IsValidAsciiChar(e->keypress.ascii)) {
_iconsole_scroll = ICON_BUFFER;
InsertTextBufferChar(&_iconsole_cmdline, e->keypress.ascii);
IConsoleResetHistoryPos();
SetWindowDirty(w);
} else {
e->we.keypress.cont = true;
}
} else
e->keypress.cont = true;
break;
}
}
@@ -213,8 +200,11 @@ void IConsoleInit(void)
_icolour_warn = 13;
_icolour_dbg = 5;
_icolour_cmd = 2;
_iconsole_scroll = ICON_BUFFER;
_iconsole_historypos = ICON_HISTORY_SIZE - 1;
_iconsole_inited = true;
_iconsole_mode = ICONSOLE_CLOSED;
_iconsole_win = NULL;
#ifdef ENABLE_NETWORK /* Initialize network only variables */
_redirect_console_to_client = 0;
@@ -224,7 +214,7 @@ void IConsoleInit(void)
memset(_iconsole_buffer, 0, sizeof(_iconsole_buffer));
memset(_iconsole_cbuffer, 0, sizeof(_iconsole_cbuffer));
_iconsole_cmdline.buf = calloc(ICON_CMDLN_SIZE, sizeof(*_iconsole_cmdline.buf)); // create buffer and zero it
_iconsole_cmdline.maxlength = ICON_CMDLN_SIZE;
_iconsole_cmdline.maxlength = ICON_CMDLN_SIZE - 1;
IConsolePrintF(13, "OpenTTD Game Console Revision 7 - %s", _openttd_revision);
IConsolePrint(12, "------------------------------------");
@@ -250,7 +240,7 @@ static void IConsoleClear(void)
IConsoleClearBuffer();
}
static void IConsoleWriteToLogFile(const char *string)
static void IConsoleWriteToLogFile(const char* string)
{
if (_iconsole_output_file != NULL) {
// if there is an console output file ... also print it there
@@ -273,22 +263,25 @@ bool CloseConsoleLogIfActive(void)
void IConsoleFree(void)
{
_iconsole_inited = false;
IConsoleClear();
CloseConsoleLogIfActive();
}
void IConsoleResize(Window *w)
void IConsoleResize(void)
{
_iconsole_win = FindWindowById(WC_CONSOLE, 0);
switch (_iconsole_mode) {
case ICONSOLE_OPENED:
w->height = _screen.height / 3;
w->width = _screen.width;
_iconsole_win->height = _screen.height / 3;
_iconsole_win->width = _screen.width;
break;
case ICONSOLE_FULL:
w->height = _screen.height - ICON_BOTTOM_BORDERWIDTH;
w->width = _screen.width;
_iconsole_win->height = _screen.height - ICON_BOTTOM_BORDERWIDTH;
_iconsole_win->width = _screen.width;
break;
default: return;
default: break;
}
MarkWholeScreenDirty();
@@ -297,15 +290,16 @@ void IConsoleResize(Window *w)
void IConsoleSwitch(void)
{
switch (_iconsole_mode) {
case ICONSOLE_CLOSED: {
Window *w = AllocateWindowDesc(&_iconsole_window_desc);
w->height = _screen.height / 3;
w->width = _screen.width;
case ICONSOLE_CLOSED:
_iconsole_win = AllocateWindowDesc(&_iconsole_window_desc);
_iconsole_win->height = _screen.height / 3;
_iconsole_win->width = _screen.width;
_iconsole_mode = ICONSOLE_OPENED;
SETBIT(_no_scroll, SCROLL_CON); // override cursor arrows; the gamefield will not scroll
} break;
break;
case ICONSOLE_OPENED: case ICONSOLE_FULL:
DeleteWindowById(WC_CONSOLE, 0);
_iconsole_win = NULL;
_iconsole_mode = ICONSOLE_CLOSED;
CLRBIT(_no_scroll, SCROLL_CON);
break;
@@ -322,7 +316,7 @@ void IConsoleOpen(void) {if (_iconsole_mode == ICONSOLE_CLOSED) IConsoleSwitch(
* 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)
void IConsoleHistoryAdd(const char *cmd)
{
free(_iconsole_history[ICON_HISTORY_SIZE - 1]);
@@ -335,7 +329,7 @@ static void IConsoleHistoryAdd(const char *cmd)
* 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)
void IConsoleHistoryNavigate(signed char direction)
{
int i = _iconsole_historypos + direction;
@@ -367,9 +361,8 @@ static void IConsoleHistoryNavigate(int direction)
* @param color_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(uint16 color_code, const char *string)
void IConsolePrint(uint16 color_code, const char* string)
{
char *str;
#ifdef ENABLE_NETWORK
if (_redirect_console_to_client != 0) {
/* Redirect the string to the client */
@@ -378,32 +371,32 @@ void IConsolePrint(uint16 color_code, const char *string)
}
#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);
if (_network_dedicated) {
fprintf(stdout, "%s\n", str);
fflush(stdout);
IConsoleWriteToLogFile(str);
free(str); // free duplicated string since it's not used anymore
printf("%s\n", string);
IConsoleWriteToLogFile(string);
return;
}
if (!_iconsole_inited) return;
/* move up all the strings in the buffer one place and do the same for colour
* to accomodate for the new command/message */
free(_iconsole_buffer[0]);
memmove(&_iconsole_buffer[0], &_iconsole_buffer[1], sizeof(_iconsole_buffer[0]) * ICON_BUFFER);
_iconsole_buffer[ICON_BUFFER] = str;
_iconsole_buffer[ICON_BUFFER] = strdup(string);
{ // filter out unprintable characters
char *i;
for (i = _iconsole_buffer[ICON_BUFFER]; *i != '\0'; i++)
if (!IsValidAsciiChar((byte)*i)) *i = ' ';
}
memmove(&_iconsole_cbuffer[0], &_iconsole_cbuffer[1], sizeof(_iconsole_cbuffer[0]) * ICON_BUFFER);
_iconsole_cbuffer[ICON_BUFFER] = color_code;
IConsoleWriteToLogFile(_iconsole_buffer[ICON_BUFFER]);
IConsoleWriteToLogFile(string);
SetWindowDirty(FindWindowById(WC_CONSOLE, 0));
if (_iconsole_win != NULL) SetWindowDirty(_iconsole_win);
}
/**
@@ -429,7 +422,7 @@ void CDECL IConsolePrintF(uint16 color_code, const char *s, ...)
* @debug() in debug.c. You need at least a level 2 (developer) for debugging
* messages to show up
*/
void IConsoleDebug(const char *string)
void IConsoleDebug(const char* string)
{
if (_stdlib_developer > 1)
IConsolePrintF(_icolour_dbg, "dbg: %s", string);
@@ -440,7 +433,7 @@ void IConsoleDebug(const char *string)
* 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)
void IConsoleWarning(const char* string)
{
if (_stdlib_developer > 0)
IConsolePrintF(_icolour_warn, "WARNING: %s", string);
@@ -450,7 +443,7 @@ void IConsoleWarning(const char *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)
void IConsoleError(const char* string)
{
IConsolePrintF(_icolour_err, "ERROR: %s", string);
}
@@ -476,7 +469,7 @@ bool GetArgumentInteger(uint32 *value, const char *arg)
}
*value = strtoul(arg, &endptr, 0);
return arg != endptr;
return (arg == endptr) ? false : true;
}
// * ************************* * //
@@ -502,7 +495,7 @@ static void IConsoleHookAdd(IConsoleHooks *hooks, IConsoleHookTypes type, IConso
case ICONSOLE_HOOK_POST_ACTION:
hooks->post = proc;
break;
default: NOT_REACHED();
default: NOT_REACHED();
}
}
@@ -529,7 +522,7 @@ static bool IConsoleHookHandle(const IConsoleHooks *hooks, IConsoleHookTypes typ
case ICONSOLE_HOOK_POST_ACTION:
proc = hooks->post;
break;
default: NOT_REACHED();
default: NOT_REACHED();
}
return (proc == NULL) ? true : proc();
@@ -566,41 +559,40 @@ void IConsoleVarHookAdd(const char *name, IConsoleHookTypes type, IConsoleHook *
* 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 */ \
#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 */ \
}
/**
@@ -676,7 +668,7 @@ IConsoleAlias *IConsoleAliasGet(const char *name)
/** copy in an argument into the aliasstream */
static inline int IConsoleCopyInParams(char *dst, const char *src, uint bufpos)
{
int len = min(ICON_MAX_STREAMSIZE - bufpos, (uint)strlen(src));
int len = min(ICON_MAX_STREAMSIZE - bufpos, strlen(src));
strncpy(dst, src, len);
return len;
@@ -689,19 +681,16 @@ static inline int IConsoleCopyInParams(char *dst, const char *src, uint bufpos)
* @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])
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;
int i;
uint a_index, astream_i;
memset(&aliases, 0, sizeof(aliases));
memset(&aliasstream, 0, sizeof(aliasstream));
if (_stdlib_con_developer)
IConsolePrintF(_icolour_dbg, "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;
@@ -756,7 +745,7 @@ static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char
}
}
for (i = 0; i <= a_index; i++) IConsoleCmdExec(aliases[i]); // execute each alias in turn
for (i = 0; i <= (int)a_index; i++) IConsoleCmdExec(aliases[i]); // execute each alias in turn
}
/**
@@ -831,7 +820,7 @@ static void IConsoleVarSetValue(const IConsoleVar *var, uint32 value)
*(byte*)var->addr = (byte)value;
break;
case ICONSOLE_VAR_UINT16:
*(uint16*)var->addr = (uint16)value;
*(uint16*)var->addr = (byte)value;
break;
case ICONSOLE_VAR_INT16:
*(int16*)var->addr = (int16)value;
@@ -855,12 +844,12 @@ static void IConsoleVarSetValue(const IConsoleVar *var, uint32 value)
* @param *var the variable in question
* @param *value the new value
*/
static void IConsoleVarSetStringvalue(const IConsoleVar *var, const char *value)
static void IConsoleVarSetStringvalue(const IConsoleVar *var, char *value)
{
if (var->type != ICONSOLE_VAR_STRING || var->addr == NULL) return;
IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_PRE_ACTION);
ttd_strlcpy(var->addr, value, var->size);
ttd_strlcpy((char*)var->addr, (char*)value, var->size);
IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_POST_ACTION);
IConsoleVarPrintSetValue(var); // print out the new value, giving feedback
return;
@@ -929,7 +918,6 @@ static char *IConsoleVarGetStringValue(const IConsoleVar *var)
break;
case ICONSOLE_VAR_STRING:
value = (char*)var->addr;
break;
default: NOT_REACHED();
}
@@ -976,9 +964,6 @@ void IConsoleVarExec(const IConsoleVar *var, byte tokencount, char *token[ICON_T
byte t_index = tokencount;
uint32 value;
if (_stdlib_con_developer)
IConsolePrintF(_icolour_dbg, "condbg: requested command is a variable");
if (tokencount == 0) { /* Just print out value */
IConsoleVarPrintGetValue(var);
return;
@@ -991,6 +976,7 @@ void IConsoleVarExec(const IConsoleVar *var, byte tokencount, char *token[ICON_T
/* 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
var->proc(0, NULL); // print out new value
return;
}
/* Strings need special processing. No need to convert the argument to
@@ -1049,10 +1035,8 @@ void IConsoleCmdExec(const char *cmdstr)
bool longtoken = false;
bool foundtoken = false;
if (cmdstr[0] == '#') return; // comments
for (cmdptr = cmdstr; *cmdptr != '\0'; cmdptr++) {
if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
if (!IsValidAsciiChar(*cmdptr)) {
IConsoleError("command contains malformed characters, aborting");
IConsolePrintF(_icolour_err, "ERROR: command was: '%s'", cmdstr);
return;
@@ -1087,12 +1071,6 @@ void IConsoleCmdExec(const char *cmdstr)
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;
@@ -1106,10 +1084,8 @@ void IConsoleCmdExec(const char *cmdstr)
if (_stdlib_con_developer) {
uint i;
for (i = 0; tokens[i] != NULL; i++) {
for (i = 0; tokens[i] != NULL; i++)
IConsolePrintF(_icolour_dbg, "condbg: token %d is: '%s'", i, tokens[i]);
}
}
if (tokens[0] == '\0') return; // don't execute empty commands
@@ -1117,33 +1093,31 @@ void IConsoleCmdExec(const char *cmdstr)
* 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) {
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
}
} else cmd->proc(0, NULL); // if command failed, give help
}
return;
}
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;
}
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;
}
var = IConsoleVarGet(tokens[0]);
if (var != NULL) {
if (IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_ACCESS))
IConsoleVarExec(var, t_index, &tokens[1]);
IConsoleError("command or variable not found");
return;
}
IConsoleError("command or variable not found");
}

View File

@@ -1,5 +1,3 @@
/* $Id$ */
#ifndef CONSOLE_H
#define CONSOLE_H
@@ -101,12 +99,12 @@ typedef struct IConsoleAlias {
char *cmdline; // command(s) that is/are being aliased
} IConsoleAlias;
/* console parser */
VARDEF IConsoleCmd *_iconsole_cmds; // list of registred commands
VARDEF IConsoleVar *_iconsole_vars; // list of registred vars
VARDEF IConsoleAlias *_iconsole_aliases; // list of registred aliases
// ** console parser ** //
IConsoleCmd *_iconsole_cmds; // list of registred commands
IConsoleVar *_iconsole_vars; // list of registred vars
IConsoleAlias *_iconsole_aliases; // list of registred aliases
/* console colors/modes */
// ** console colors/modes ** //
VARDEF byte _icolour_def;
VARDEF byte _icolour_err;
VARDEF byte _icolour_warn;
@@ -114,47 +112,52 @@ VARDEF byte _icolour_dbg;
VARDEF byte _icolour_cmd;
VARDEF IConsoleModes _iconsole_mode;
/* console functions */
// ** console functions ** //
void IConsoleInit(void);
void IConsoleFree(void);
void IConsoleClearBuffer(void);
void IConsoleResize(Window *w);
void IConsoleResize(void);
void IConsoleSwitch(void);
void IConsoleClose(void);
void IConsoleOpen(void);
/* console output */
// ** console cmd buffer ** //
void IConsoleHistoryAdd(const char *cmd);
void IConsoleHistoryNavigate(signed char direction);
// ** console output ** //
void IConsolePrint(uint16 color_code, const char *string);
void CDECL IConsolePrintF(uint16 color_code, const char *s, ...);
void IConsoleDebug(const char *string);
void IConsoleWarning(const char *string);
void IConsoleError(const char *string);
/* Commands */
// *** Commands *** //
void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc);
void IConsoleAliasRegister(const char *name, const char *cmd);
IConsoleCmd *IConsoleCmdGet(const char *name);
IConsoleAlias *IConsoleAliasGet(const char *name);
/* Variables */
// *** Variables *** //
void IConsoleVarRegister(const char *name, void *addr, IConsoleVarTypes type, const char *help);
void IConsoleVarStringRegister(const char *name, void *addr, uint32 size, const char *help);
IConsoleVar* IConsoleVarGet(const char *name);
void IConsoleVarPrintGetValue(const IConsoleVar *var);
void IConsoleVarPrintSetValue(const IConsoleVar *var);
/* Parser */
// *** Parser *** //
void IConsoleCmdExec(const char *cmdstr);
void IConsoleVarExec(const IConsoleVar *var, byte tokencount, char *token[]);
void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[]);
/* console std lib (register ingame commands/aliases/variables) */
// ** console std lib (register ingame commands/aliases/variables) ** //
void IConsoleStdLibRegister(void);
/* Hooking code */
// ** Hooking code ** //
void IConsoleCmdHookAdd(const char *name, IConsoleHookTypes type, IConsoleHook *proc);
void IConsoleVarHookAdd(const char *name, IConsoleHookTypes type, IConsoleHook *proc);
void IConsoleVarProcAdd(const char *name, IConsoleCmdProc *proc);
/* Supporting functions */
// ** Supporting functions **//
bool GetArgumentInteger(uint32 *value, const char *arg);
#endif /* CONSOLE_H */

File diff suppressed because it is too large Load Diff

View File

@@ -1,187 +0,0 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "currency.h"
#include "news.h"
#include "variables.h"
#include "table/strings.h"
#include "date.h"
// exchange rate prefix symbol_pos
// | separator | postfix |
// | | Euro year | | | name
// | | | | | | |
static const CurrencySpec origin_currency_specs[NUM_CURRENCY] = {
{ 1, ',', CF_NOEURO, "£", "", 0, STR_CURR_GBP }, // british pounds
{ 2, ',', CF_NOEURO, "$", "", 0, STR_CURR_USD }, // us dollars
{ 2, ',', CF_ISEURO, "", "", 0, STR_CURR_EUR }, // Euro
{ 220, ',', CF_NOEURO, "¥", "", 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, "", "", 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, ',', 2010, "", " 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, '.', CF_NOEURO, "", " SIT", 1, STR_CURR_SIT }, // slovenian tolar
{ 13, '.', CF_NOEURO, "", " Kr", 1, STR_CURR_SEK }, // swedish krona
{ 3, '.', CF_NOEURO, "", " YTL", 1, STR_CURR_YTL }, // turkish lira
{ 52, ',', CF_NOEURO, "", " Sk", 1, STR_CURR_SKK }, // slovak koruna
{ 4, ',', CF_NOEURO, "R$ ", "", 0, STR_CURR_BRR }, // brazil real
{ 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,
};
/**
* 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 then the array,
* it is a grf written for ottd, thus returning the same id.
* Only called from newgrf.c
* @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 */
uint GetMaskOfAllowedCurrencies(void)
{
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(void)
{
if (_currency_specs[_opt.currency].to_euro != CF_NOEURO &&
_currency_specs[_opt.currency].to_euro != CF_ISEURO &&
_cur_year >= _currency_specs[_opt.currency].to_euro) {
_opt.currency = 2; // this is the index of euro above.
AddNewsItem(STR_EURO_INTRODUCE, NEWS_FLAGS(NM_NORMAL, 0, NT_ECONOMY, 0), 0, 0);
}
}
/**
* Will fill _currency_specs array with
* default values from origin_currency_specs
* Called only from newgrf.c and settings.c.
* @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)
*/
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(void)
{
/* 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;
}

View File

@@ -1,45 +0,0 @@
/* $Id$ */
#ifndef CURRENCY_H
#define CURRENCY_H
enum {
CF_NOEURO = 0,
CF_ISEURO = 1,
NUM_CURRENCY = 28,
CUSTOM_CURRENCY_ID = NUM_CURRENCY - 1
};
typedef struct {
uint16 rate;
char separator;
Year to_euro;
char prefix[16];
char suffix[16];
/**
* The currency symbol is represented by two possible values, prefix and suffix
* Usage of one or the other is determined by symbol_pos.
* 0 = prefix
* 1 = suffix
* 2 = both : Special case only for custom currency.
* It is not a spec from Newgrf,
* rather a way to let users do what they want with custom curency
*/
byte symbol_pos;
StringID name;
} CurrencySpec;
extern CurrencySpec _currency_specs[NUM_CURRENCY];
// XXX small hack, but makes the rest of the code a bit nicer to read
#define _custom_currency (_currency_specs[CUSTOM_CURRENCY_ID])
#define _currency ((const CurrencySpec*)&_currency_specs[_opt_ptr->currency])
uint GetMaskOfAllowedCurrencies(void);
void CheckSwitchToEuro(void);
void ResetCurrencies(bool preserve_custom);
StringID* BuildCurrencyDropdown(void);
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id);
#endif /* CURRENCY_H */

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
data/signalsw.grf Normal file

Binary file not shown.

304
date.c
View File

@@ -1,304 +0,0 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "date.h"
#include "variables.h"
#include "macros.h"
#include "vehicle.h"
#include "network.h"
#include "network_data.h"
#include "network_server.h"
#include "functions.h"
#include "currency.h"
Year _cur_year;
Month _cur_month;
Date _date;
DateFract _date_fract;
void SetDate(Date date)
{
YearMonthDay ymd;
_date = date;
ConvertDateToYMD(date, &ymd);
_cur_year = ymd.year;
_cur_month = ymd.month;
#ifdef ENABLE_NETWORK
_network_last_advertise_frame = 0;
_network_need_advertise = true;
#endif /* ENABLE_NETWORK */
}
#define M(a, b) ((a << 5) | b)
static const uint16 _month_date_from_year_day[] = {
M( 0, 1), M( 0, 2), M( 0, 3), M( 0, 4), M( 0, 5), M( 0, 6), M( 0, 7), M( 0, 8), M( 0, 9), M( 0, 10), M( 0, 11), M( 0, 12), M( 0, 13), M( 0, 14), M( 0, 15), M( 0, 16), M( 0, 17), M( 0, 18), M( 0, 19), M( 0, 20), M( 0, 21), M( 0, 22), M( 0, 23), M( 0, 24), M( 0, 25), M( 0, 26), M( 0, 27), M( 0, 28), M( 0, 29), M( 0, 30), M( 0, 31),
M( 1, 1), M( 1, 2), M( 1, 3), M( 1, 4), M( 1, 5), M( 1, 6), M( 1, 7), M( 1, 8), M( 1, 9), M( 1, 10), M( 1, 11), M( 1, 12), M( 1, 13), M( 1, 14), M( 1, 15), M( 1, 16), M( 1, 17), M( 1, 18), M( 1, 19), M( 1, 20), M( 1, 21), M( 1, 22), M( 1, 23), M( 1, 24), M( 1, 25), M( 1, 26), M( 1, 27), M( 1, 28), M( 1, 29),
M( 2, 1), M( 2, 2), M( 2, 3), M( 2, 4), M( 2, 5), M( 2, 6), M( 2, 7), M( 2, 8), M( 2, 9), M( 2, 10), M( 2, 11), M( 2, 12), M( 2, 13), M( 2, 14), M( 2, 15), M( 2, 16), M( 2, 17), M( 2, 18), M( 2, 19), M( 2, 20), M( 2, 21), M( 2, 22), M( 2, 23), M( 2, 24), M( 2, 25), M( 2, 26), M( 2, 27), M( 2, 28), M( 2, 29), M( 2, 30), M( 2, 31),
M( 3, 1), M( 3, 2), M( 3, 3), M( 3, 4), M( 3, 5), M( 3, 6), M( 3, 7), M( 3, 8), M( 3, 9), M( 3, 10), M( 3, 11), M( 3, 12), M( 3, 13), M( 3, 14), M( 3, 15), M( 3, 16), M( 3, 17), M( 3, 18), M( 3, 19), M( 3, 20), M( 3, 21), M( 3, 22), M( 3, 23), M( 3, 24), M( 3, 25), M( 3, 26), M( 3, 27), M( 3, 28), M( 3, 29), M( 3, 30),
M( 4, 1), M( 4, 2), M( 4, 3), M( 4, 4), M( 4, 5), M( 4, 6), M( 4, 7), M( 4, 8), M( 4, 9), M( 4, 10), M( 4, 11), M( 4, 12), M( 4, 13), M( 4, 14), M( 4, 15), M( 4, 16), M( 4, 17), M( 4, 18), M( 4, 19), M( 4, 20), M( 4, 21), M( 4, 22), M( 4, 23), M( 4, 24), M( 4, 25), M( 4, 26), M( 4, 27), M( 4, 28), M( 4, 29), M( 4, 30), M( 4, 31),
M( 5, 1), M( 5, 2), M( 5, 3), M( 5, 4), M( 5, 5), M( 5, 6), M( 5, 7), M( 5, 8), M( 5, 9), M( 5, 10), M( 5, 11), M( 5, 12), M( 5, 13), M( 5, 14), M( 5, 15), M( 5, 16), M( 5, 17), M( 5, 18), M( 5, 19), M( 5, 20), M( 5, 21), M( 5, 22), M( 5, 23), M( 5, 24), M( 5, 25), M( 5, 26), M( 5, 27), M( 5, 28), M( 5, 29), M( 5, 30),
M( 6, 1), M( 6, 2), M( 6, 3), M( 6, 4), M( 6, 5), M( 6, 6), M( 6, 7), M( 6, 8), M( 6, 9), M( 6, 10), M( 6, 11), M( 6, 12), M( 6, 13), M( 6, 14), M( 6, 15), M( 6, 16), M( 6, 17), M( 6, 18), M( 6, 19), M( 6, 20), M( 6, 21), M( 6, 22), M( 6, 23), M( 6, 24), M( 6, 25), M( 6, 26), M( 6, 27), M( 6, 28), M( 6, 29), M( 6, 30), M( 6, 31),
M( 7, 1), M( 7, 2), M( 7, 3), M( 7, 4), M( 7, 5), M( 7, 6), M( 7, 7), M( 7, 8), M( 7, 9), M( 7, 10), M( 7, 11), M( 7, 12), M( 7, 13), M( 7, 14), M( 7, 15), M( 7, 16), M( 7, 17), M( 7, 18), M( 7, 19), M( 7, 20), M( 7, 21), M( 7, 22), M( 7, 23), M( 7, 24), M( 7, 25), M( 7, 26), M( 7, 27), M( 7, 28), M( 7, 29), M( 7, 30), M( 7, 31),
M( 8, 1), M( 8, 2), M( 8, 3), M( 8, 4), M( 8, 5), M( 8, 6), M( 8, 7), M( 8, 8), M( 8, 9), M( 8, 10), M( 8, 11), M( 8, 12), M( 8, 13), M( 8, 14), M( 8, 15), M( 8, 16), M( 8, 17), M( 8, 18), M( 8, 19), M( 8, 20), M( 8, 21), M( 8, 22), M( 8, 23), M( 8, 24), M( 8, 25), M( 8, 26), M( 8, 27), M( 8, 28), M( 8, 29), M( 8, 30),
M( 9, 1), M( 9, 2), M( 9, 3), M( 9, 4), M( 9, 5), M( 9, 6), M( 9, 7), M( 9, 8), M( 9, 9), M( 9, 10), M( 9, 11), M( 9, 12), M( 9, 13), M( 9, 14), M( 9, 15), M( 9, 16), M( 9, 17), M( 9, 18), M( 9, 19), M( 9, 20), M( 9, 21), M( 9, 22), M( 9, 23), M( 9, 24), M( 9, 25), M( 9, 26), M( 9, 27), M( 9, 28), M( 9, 29), M( 9, 30), M( 9, 31),
M(10, 1), M(10, 2), M(10, 3), M(10, 4), M(10, 5), M(10, 6), M(10, 7), M(10, 8), M(10, 9), M(10, 10), M(10, 11), M(10, 12), M(10, 13), M(10, 14), M(10, 15), M(10, 16), M(10, 17), M(10, 18), M(10, 19), M(10, 20), M(10, 21), M(10, 22), M(10, 23), M(10, 24), M(10, 25), M(10, 26), M(10, 27), M(10, 28), M(10, 29), M(10, 30),
M(11, 1), M(11, 2), M(11, 3), M(11, 4), M(11, 5), M(11, 6), M(11, 7), M(11, 8), M(11, 9), M(11, 10), M(11, 11), M(11, 12), M(11, 13), M(11, 14), M(11, 15), M(11, 16), M(11, 17), M(11, 18), M(11, 19), M(11, 20), M(11, 21), M(11, 22), M(11, 23), M(11, 24), M(11, 25), M(11, 26), M(11, 27), M(11, 28), M(11, 29), M(11, 30), M(11, 31),
};
#undef M
enum {
ACCUM_JAN = 0,
ACCUM_FEB = ACCUM_JAN + 31,
ACCUM_MAR = ACCUM_FEB + 29,
ACCUM_APR = ACCUM_MAR + 31,
ACCUM_MAY = ACCUM_APR + 30,
ACCUM_JUN = ACCUM_MAY + 31,
ACCUM_JUL = ACCUM_JUN + 30,
ACCUM_AUG = ACCUM_JUL + 31,
ACCUM_SEP = ACCUM_AUG + 31,
ACCUM_OCT = ACCUM_SEP + 30,
ACCUM_NOV = ACCUM_OCT + 31,
ACCUM_DEC = ACCUM_NOV + 30,
};
static const uint16 _accum_days_for_month[] = {
ACCUM_JAN, ACCUM_FEB, ACCUM_MAR, ACCUM_APR,
ACCUM_MAY, ACCUM_JUN, ACCUM_JUL, ACCUM_AUG,
ACCUM_SEP, ACCUM_OCT, ACCUM_NOV, ACCUM_DEC,
};
static inline bool IsLeapYear(Year yr)
{
return yr % 4 == 0 && (yr % 100 != 0 || yr % 400 == 0);
}
/**
* Converts a Date to a Year, Month & Day.
* @param date the date to convert from
* @param ymd the year, month and day to write to
*/
void ConvertDateToYMD(Date date, YearMonthDay *ymd)
{
/*
* Year determination in multiple steps to account for leap
* years. First do the large steps, then the smaller ones.
*/
/* There are 97 leap years in 400 years */
Year yr = 400 * (date / (365 * 400 + 97));
int rem = date % (365 * 400 + 97);
uint16 x;
if (rem >= 365 * 100 + 25) {
/* There are 25 leap years in the first 100 years after
* every 400th year, as every 400th year is a leap year */
yr += 100;
rem -= 365 * 100 + 25;
/* There are 24 leap years in the next couple of 100 years */
yr += 100 * (rem / (365 * 100 + 24));
rem = (rem % (365 * 100 + 24));
}
if (!IsLeapYear(yr) && rem >= 365 * 4) {
/* The first 4 year of the century are not always a leap year */
yr += 4;
rem -= 365 * 4;
}
/* There is 1 leap year every 4 years */
yr += 4 * (rem / (365 * 4 + 1));
rem = rem % (365 * 4 + 1);
/* The last (max 3) years to account for; the first one
* can be, but is not necessarily a leap year */
while (rem >= (IsLeapYear(yr) ? 366 : 365)) {
rem -= IsLeapYear(yr) ? 366 : 365;
yr++;
}
/* Skip the 29th of February in non-leap years */
if (!IsLeapYear(yr) && rem >= ACCUM_MAR - 1) rem++;
ymd->year = yr;
x = _month_date_from_year_day[rem];
ymd->month = x >> 5;
ymd->day = x & 0x1F;
}
/**
* Converts a tupe of Year, Month and Day to a Date.
* @param year is a number between 0..MAX_YEAR
* @param month is a number between 0..11
* @param day is a number between 1..31
*/
Date ConvertYMDToDate(Year year, Month month, Day day)
{
/*
* Each passed leap year adds one day to the 'day count'.
*
* A special case for the year 0 as no year has been passed,
* but '(year - 1) / 4' does not yield '-1' to counteract the
* '+1' at the end of the formula as divisions round to zero.
*/
int nr_of_leap_years = (year == 0) ? 0 : ((year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + 1);
/* Day-offset in a leap year */
int days = _accum_days_for_month[month] + day - 1;
/* Account for the missing of the 29th of February in non-leap years */
if (!IsLeapYear(year) && days >= ACCUM_MAR) days--;
return year * 365 + nr_of_leap_years + days;
}
/** Functions used by the IncreaseDate function */
extern void OnNewDay_Train(Vehicle *v);
extern void OnNewDay_RoadVeh(Vehicle *v);
extern void OnNewDay_Aircraft(Vehicle *v);
extern void OnNewDay_Ship(Vehicle *v);
static void OnNewDay_EffectVehicle(Vehicle *v) { /* empty */ }
extern void OnNewDay_DisasterVehicle(Vehicle *v);
typedef void OnNewVehicleDayProc(Vehicle *v);
static OnNewVehicleDayProc * _on_new_vehicle_day_proc[] = {
OnNewDay_Train,
OnNewDay_RoadVeh,
OnNewDay_Ship,
OnNewDay_Aircraft,
OnNewDay_EffectVehicle,
OnNewDay_DisasterVehicle,
};
extern void WaypointsDailyLoop(void);
extern void TextMessageDailyLoop(void);
extern void EnginesDailyLoop(void);
extern void DisasterDailyLoop(void);
extern void PlayersMonthlyLoop(void);
extern void EnginesMonthlyLoop(void);
extern void TownsMonthlyLoop(void);
extern void IndustryMonthlyLoop(void);
extern void StationMonthlyLoop(void);
extern void PlayersYearlyLoop(void);
extern void TrainsYearlyLoop(void);
extern void RoadVehiclesYearlyLoop(void);
extern void AircraftYearlyLoop(void);
extern void ShipsYearlyLoop(void);
extern void ShowEndGameChart(void);
static const Month _autosave_months[] = {
0, // never
1, // every month
3, // every 3 months
6, // every 6 months
12, // every 12 months
};
/**
* Runs the day_proc for every DAY_TICKS vehicle starting at daytick.
*/
static void RunVehicleDayProc(uint daytick)
{
uint total = GetMaxVehicleIndex() + 1;
uint i;
for (i = daytick; i < total; i += DAY_TICKS) {
Vehicle *v = GetVehicle(i);
if (IsValidVehicle(v)) _on_new_vehicle_day_proc[v->type - 0x10](v);
}
}
void IncreaseDate(void)
{
YearMonthDay ymd;
if (_game_mode == GM_MENU) {
_tick_counter++;
return;
}
RunVehicleDayProc(_date_fract);
/* increase day, and check if a new day is there? */
_tick_counter++;
_date_fract++;
if (_date_fract < DAY_TICKS) return;
_date_fract = 0;
/* yeah, increase day counter and call various daily loops */
_date++;
TextMessageDailyLoop();
DisasterDailyLoop();
WaypointsDailyLoop();
if (_game_mode != GM_MENU) {
InvalidateWindowWidget(WC_STATUS_BAR, 0, 0);
EnginesDailyLoop();
}
/* check if we entered a new month? */
ConvertDateToYMD(_date, &ymd);
if (ymd.month == _cur_month) return;
_cur_month = ymd.month;
/* yes, call various monthly loops */
if (_game_mode != GM_MENU) {
if (_opt.autosave != 0 && (_cur_month % _autosave_months[_opt.autosave]) == 0) {
_do_autosave = true;
RedrawAutosave();
}
PlayersMonthlyLoop();
EnginesMonthlyLoop();
TownsMonthlyLoop();
IndustryMonthlyLoop();
StationMonthlyLoop();
if (_network_server) NetworkServerMonthlyLoop();
}
/* check if we entered a new year? */
if (ymd.year == _cur_year) return;
_cur_year = ymd.year;
/* yes, call various yearly loops */
PlayersYearlyLoop();
TrainsYearlyLoop();
RoadVehiclesYearlyLoop();
AircraftYearlyLoop();
ShipsYearlyLoop();
if (_network_server) NetworkServerYearlyLoop();
/* check if we reached end of the game */
if (_cur_year == _patches.ending_year) {
ShowEndGameChart();
/* check if we reached the maximum year, decrement dates by a year */
} else if (_cur_year == MAX_YEAR + 1) {
Vehicle *v;
uint days_this_year;
_cur_year--;
days_this_year = IsLeapYear(_cur_year) ? 366 : 365;
_date -= days_this_year;
FOR_ALL_VEHICLES(v) v->date_of_last_service -= days_this_year;
/* Because the _date wraps here, and text-messages expire by game-days, we have to clean out
* all of them if the date is set back, else those messages will hang for ever */
InitTextMessage();
}
if (_patches.auto_euro) CheckSwitchToEuro();
}

59
date.h
View File

@@ -1,59 +0,0 @@
/* $Id$ */
#ifndef DATE_H
#define DATE_H
/**
* 1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885. On
* an overflow the new day begun and 65535 / 885 = 74.
* 1 tick is approximately 30 ms.
* 1 day is thus about 2 seconds (74 * 30 = 2220) on a machine that can run OpenTTD normally
*/
#define DAY_TICKS 74
/*
* ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR and DAYS_TILL_ORIGINAL_BASE_YEAR are
* primarily used for loading newgrf and savegame data and returning some
* newgrf (callback) functions that were in the original (TTD) inherited
* format, where '_date == 0' meant that it was 1920-01-01.
*/
/** The minimum starting year/base year of the original TTD */
#define ORIGINAL_BASE_YEAR 1920
/** The maximum year of the original TTD */
#define ORIGINAL_MAX_YEAR 2090
/**
* The offset in days from the '_date == 0' till
* 'ConvertYMDToDate(ORIGINAL_BASE_YEAR, 0, 1)'
*/
#define DAYS_TILL_ORIGINAL_BASE_YEAR (365 * ORIGINAL_BASE_YEAR + ORIGINAL_BASE_YEAR / 4 - ORIGINAL_BASE_YEAR / 100 + ORIGINAL_BASE_YEAR / 400)
/* The absolute minimum & maximum years in OTTD */
#define MIN_YEAR 0
/* MAX_YEAR, nicely rounded value of the number of years that can
* be encoded in a single 32 bits date, about 2^31 / 366 years. */
#define MAX_YEAR 5000000
/* Year and Date are defined elsewhere */
typedef uint8 Month;
typedef uint8 Day;
typedef uint16 DateFract;
typedef struct YearMonthDay {
Year year;
Month month;
Day day;
} YearMonthDay;
extern Year _cur_year;
extern Month _cur_month;
extern Date _date;
extern DateFract _date_fract;
void SetDate(Date date);
void ConvertDateToYMD(Date date, YearMonthDay *ymd);
Date ConvertYMDToDate(Year year, Month month, Day day);
#endif /* DATE_H */

24
debug.c
View File

@@ -1,16 +1,12 @@
/* $Id$ */
#include "stdafx.h"
#include <stdio.h>
#include <stdarg.h>
#include "openttd.h"
#include "ttd.h"
#include "console.h"
#include "debug.h"
#include "functions.h"
#include "string.h"
int _debug_ai_level;
int _debug_driver_level;
int _debug_grf_level;
int _debug_map_level;
int _debug_misc_level;
@@ -18,10 +14,7 @@ int _debug_ms_level;
int _debug_net_level;
int _debug_spritecache_level;
int _debug_oldloader_level;
int _debug_ntp_level;
int _debug_npf_level;
int _debug_yapf_level;
int _debug_freetype_level;
void CDECL debug(const char *s, ...)
@@ -44,7 +37,6 @@ typedef struct DebugLevel {
#define DEBUG_LEVEL(x) { #x, &_debug_##x##_level }
static const DebugLevel debug_level[] = {
DEBUG_LEVEL(ai),
DEBUG_LEVEL(driver),
DEBUG_LEVEL(grf),
DEBUG_LEVEL(map),
DEBUG_LEVEL(misc),
@@ -52,10 +44,7 @@ typedef struct DebugLevel {
DEBUG_LEVEL(net),
DEBUG_LEVEL(spritecache),
DEBUG_LEVEL(oldloader),
DEBUG_LEVEL(ntp),
DEBUG_LEVEL(npf),
DEBUG_LEVEL(yapf),
DEBUG_LEVEL(freetype)
DEBUG_LEVEL(npf)
};
#undef DEBUG_LEVEL
@@ -72,11 +61,12 @@ void SetDebugString(const char *s)
v = strtoul(s, &end, 0);
s = end;
for (i = debug_level; i != endof(debug_level); ++i) *i->level = v;
for (i = debug_level; i != endof(debug_level); ++i)
*i->level = v;
}
// individual levels
for (;;) {
for(;;) {
const DebugLevel *i;
int *p;
@@ -98,9 +88,9 @@ void SetDebugString(const char *s)
if (*s == '=') s++;
v = strtoul(s, &end, 0);
s = end;
if (p != NULL) {
if (p != NULL)
*p = v;
} else {
else {
ShowInfoF("Unknown debug level '%.*s'", s - t, t);
return;
}

29
debug.h
View File

@@ -1,5 +1,3 @@
/* $Id$ */
#ifndef DEBUG_H
#define DEBUG_H
@@ -9,7 +7,6 @@
#define DEBUG(name, level) if (level == 0 || _debug_ ## name ## _level >= level) debug
extern int _debug_ai_level;
extern int _debug_driver_level;
extern int _debug_grf_level;
extern int _debug_map_level;
extern int _debug_misc_level;
@@ -17,10 +14,7 @@
extern int _debug_net_level;
extern int _debug_spritecache_level;
extern int _debug_oldloader_level;
extern int _debug_ntp_level;
extern int _debug_npf_level;
extern int _debug_yapf_level;
extern int _debug_freetype_level;
#endif
void CDECL debug(const char *s, ...);
@@ -28,27 +22,4 @@ void CDECL debug(const char *s, ...);
void SetDebugString(const char *s);
const char *GetDebugString(void);
/* MSVCRT of course has to have a different syntax for long long *sigh* */
#if defined(_MSC_VER) || defined(__MINGW32__)
# define OTTD_PRINTF64 "I64"
#else
# define OTTD_PRINTF64 "ll"
#endif
// Used for profiling
#define TIC() {\
extern uint64 _rdtsc(void);\
uint64 _xxx_ = _rdtsc();\
static uint64 __sum__ = 0;\
static uint32 __i__ = 0;
#define TOC(str, count)\
__sum__ += _rdtsc() - _xxx_;\
if (++__i__ == count) {\
printf("[%s]: %" OTTD_PRINTF64 "u [avg: %.1f]\n", str, __sum__, __sum__/(double)__i__);\
__i__ = 0;\
__sum__ = 0;\
}\
}
#endif /* DEBUG_H */

View File

@@ -1,17 +1,54 @@
/* $Id$ */
#include "stdafx.h"
#include "ttd.h"
#include "debug.h"
#include "network.h"
#include "hal.h"
#ifdef ENABLE_NETWORK
#if defined(UNIX) && !defined(__MORPHOS__)
#include "gfx.h"
#include "window.h"
#include "command.h"
#include "console.h"
#ifdef WIN32
# include <windows.h> /* GetTickCount */
# include <conio.h>
#endif
#include "openttd.h"
#include "variables.h"
#ifdef __OS2__
# include <sys/time.h> /* gettimeofday */
# include <sys/types.h>
# include <unistd.h>
# include <conio.h>
# define STDIN 0 /* file descriptor for standard input */
#include <sys/types.h>
#include <unistd.h>
extern void OS2_SwitchToConsoleMode();
#endif
#ifdef UNIX
# include <sys/time.h> /* gettimeofday */
# include <sys/types.h>
# include <unistd.h>
# include <signal.h>
# define STDIN 0 /* file descriptor for standard input */
#endif
#ifdef __MORPHOS__
/* Voids the fork, option will be disabled for MorphOS build anyway, because
* MorphOS doesn't support forking (could only implemented with lots of code
* changes here). */
int fork(void) { return -1; }
int dup2(int oldd, int newd) { return -1; }
#endif
// This file handles all dedicated-server in- and outputs
static void *_dedicated_video_mem;
extern bool SafeSaveOrLoad(const char *filename, int mode, int newgm);
extern void SwitchMode(int new_mode);
#ifdef UNIX
/* We want to fork our dedicated server */
void DedicatedFork(void)
{
/* Fork the program */
@@ -20,28 +57,25 @@ void DedicatedFork(void)
case -1:
perror("Unable to fork");
exit(1);
case 0: { // We're the child
FILE* f;
case 0:
// We're the child
/* Open the log-file to log all stuff too */
f = fopen(_log_file, "a");
if (f == NULL) {
_log_file_fd = fopen(_log_file, "a");
if (!_log_file_fd) {
perror("Unable to open logfile");
exit(1);
}
/* Redirect stdout and stderr to log-file */
if (dup2(fileno(f), fileno(stdout)) == -1) {
if (dup2(fileno(_log_file_fd), fileno(stdout)) == -1) {
perror("Rerouting stdout");
exit(1);
}
if (dup2(fileno(f), fileno(stderr)) == -1) {
if (dup2(fileno(_log_file_fd), fileno(stderr)) == -1) {
perror("Rerouting stderr");
exit(1);
}
break;
}
default:
// We're the parent
printf("Loading dedicated server...\n");
@@ -49,10 +83,274 @@ void DedicatedFork(void)
exit(0);
}
}
/* Signal handlers */
static void DedicatedSignalHandler(int sig)
{
_exit_game = true;
signal(sig, DedicatedSignalHandler);
}
#endif
#ifdef WIN32
#include <time.h>
HANDLE hEvent;
static HANDLE hThread; // Thread to close
static char _win_console_thread_buffer[200];
/* Windows Console thread. Just loop and signal when input has been received */
void WINAPI CheckForConsoleInput(void)
{
while (true) {
fgets(_win_console_thread_buffer, lengthof(_win_console_thread_buffer), stdin);
SetEvent(hEvent); // signal input waiting that the line is ready
}
}
void CreateWindowsConsoleThread(void)
{
static char tbuffer[9];
DWORD dwThreadId;
/* Create event to signal when console input is ready */
hEvent = CreateEvent(NULL, false, false, _strtime(tbuffer));
if (hEvent == NULL)
error("Cannot create console event!");
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, NULL, 0, &dwThreadId);
if (hThread == NULL)
error("Cannot create console thread!");
DEBUG(misc, 0) ("Windows console thread started...");
}
void CloseWindowsConsoleThread(void)
{
CloseHandle(hThread);
CloseHandle(hEvent);
DEBUG(misc, 0) ("Windows console thread shut down...");
}
#endif
static const char *DedicatedVideoStart(const char * const *parm)
{
_screen.width = _screen.pitch = _cur_resolution[0];
_screen.height = _cur_resolution[1];
_dedicated_video_mem = malloc(_cur_resolution[0]*_cur_resolution[1]);
_debug_net_level = 6;
_debug_misc_level = 0;
#ifdef WIN32
// For win32 we need to allocate an console (debug mode does the same)
CreateConsole();
CreateWindowsConsoleThread();
SetConsoleTitle("OpenTTD Dedicated Server");
#endif
#ifdef __OS2__
// For OS/2 we also need to switch to console mode instead of PM mode
OS2_SwitchToConsoleMode();
#endif
DEBUG(misc,0)("Loading dedicated server...");
return NULL;
}
static void DedicatedVideoStop(void)
{
#ifdef WIN32
CloseWindowsConsoleThread();
#endif
free(_dedicated_video_mem);
}
static void DedicatedVideoMakeDirty(int left, int top, int width, int height) {}
static bool DedicatedVideoChangeRes(int w, int h) { return false; }
static void DedicatedVideoFullScreen(bool fs) {}
#if defined(UNIX) || defined(__OS2__)
static bool InputWaiting(void)
{
struct timeval tv;
fd_set readfds;
byte ret;
tv.tv_sec = 0;
tv.tv_usec = 1;
FD_ZERO(&readfds);
FD_SET(STDIN, &readfds);
/* don't care about writefds and exceptfds: */
ret = select(STDIN + 1, &readfds, NULL, NULL, &tv);
if (ret > 0)
return true;
return false;
}
#else
static bool InputWaiting(void)
{
if (WaitForSingleObject(hEvent, 1) == WAIT_OBJECT_0)
return true;
return false;
}
#endif
static void DedicatedHandleKeyInput(void)
{
static char input_line[200] = "";
if (!InputWaiting())
return;
if (_exit_game)
return;
#if defined(UNIX) || defined(__OS2__)
fgets(input_line, lengthof(input_line), stdin);
#else
strncpy(input_line, _win_console_thread_buffer, lengthof(input_line));
#endif
/* XXX - strtok() does not 'forget' \n\r if it is the first character! */
strtok(input_line, "\r\n"); // Forget about the final \n (or \r)
{ /* Remove any special control characters */
uint i;
for (i = 0; i < lengthof(input_line); i++) {
if (input_line[i] == '\n' || input_line[i] == '\r') // cut missed beginning '\0'
input_line[i] = '\0';
if (input_line[i] == '\0')
break;
if (!IS_INT_INSIDE(input_line[i], ' ', 256))
input_line[i] = ' ';
}
}
IConsoleCmdExec(input_line); // execute command
}
static int DedicatedVideoMainLoop(void)
{
#ifndef WIN32
struct timeval tim;
#endif
uint32 next_tick;
uint32 cur_ticks;
#ifdef WIN32
next_tick = GetTickCount() + 30;
#else
gettimeofday(&tim, NULL);
next_tick = (tim.tv_usec / 1000) + 30 + (tim.tv_sec * 1000);
#endif
/* Signal handlers */
#ifdef UNIX
signal(SIGTERM, DedicatedSignalHandler);
signal(SIGINT, DedicatedSignalHandler);
signal(SIGQUIT, DedicatedSignalHandler);
#endif
// Load the dedicated server stuff
_is_network_server = true;
_network_dedicated = true;
_network_playas = OWNER_SPECTATOR;
_local_player = OWNER_SPECTATOR;
/* If SwitchMode is SM_LOAD, it means that the user used the '-g' options */
if (_switch_mode != SM_LOAD) {
_switch_mode = SM_NONE;
GenRandomNewGame(Random(), InteractiveRandom());
} else {
_switch_mode = SM_NONE;
/* First we need to test if the savegame can be loaded, else we will end up playing the
* intro game... */
if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL)) {
/* Loading failed, pop out.. */
DEBUG(net, 0)("Loading requested map failed. Aborting.");
_networking = false;
} else {
/* We can load this game, so go ahead */
SwitchMode(SM_LOAD);
}
}
// Done loading, start game!
if (!_networking) {
DEBUG(net, 1)("Dedicated server could not be launched. Aborting.");
return ML_QUIT;
}
while (true) {
InteractiveRandom(); // randomness
if (_exit_game) return ML_QUIT;
if (!_dedicated_forks)
DedicatedHandleKeyInput();
#ifdef WIN32
cur_ticks = GetTickCount();
#else
gettimeofday(&tim, NULL);
cur_ticks = (tim.tv_usec / 1000) + (tim.tv_sec * 1000);
#endif
if (cur_ticks >= next_tick) {
next_tick += 30;
GameLoop();
_screen.dst_ptr = _dedicated_video_mem;
UpdateWindows();
}
CSleep(1);
}
return ML_QUIT;
}
const HalVideoDriver _dedicated_video_driver = {
DedicatedVideoStart,
DedicatedVideoStop,
DedicatedVideoMakeDirty,
DedicatedVideoMainLoop,
DedicatedVideoChangeRes,
DedicatedVideoFullScreen,
};
#else
static void *_dedicated_video_mem;
static const char *DedicatedVideoStart(const char * const *parm)
{
DEBUG(misc, 0) ("OpenTTD compiled without network support, exiting.");
return NULL;
}
void DedicatedFork(void) {}
static void DedicatedVideoStop(void) { free(_dedicated_video_mem); }
static void DedicatedVideoMakeDirty(int left, int top, int width, int height) {}
static bool DedicatedVideoChangeRes(int w, int h) { return false; }
static void DedicatedVideoFullScreen(bool fs) {}
static int DedicatedVideoMainLoop(void) { return ML_QUIT; }
const HalVideoDriver _dedicated_video_driver = {
DedicatedVideoStart,
DedicatedVideoStop,
DedicatedVideoMakeDirty,
DedicatedVideoMainLoop,
DedicatedVideoChangeRes,
DedicatedVideoFullScreen,
};
#endif /* ENABLE_NETWORK */

87
depot.c
View File

@@ -1,29 +1,31 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "depot.h"
#include "functions.h"
#include "tile.h"
#include "map.h"
#include "table/strings.h"
#include "saveload.h"
#include "order.h"
enum {
/* Max depots: 64000 (8 * 8000) */
DEPOT_POOL_BLOCK_SIZE_BITS = 3, /* In bits, so (1 << 3) == 8 */
DEPOT_POOL_MAX_BLOCKS = 8000,
};
/**
* Called if a new block is added to the depot-pool
*/
static void DepotPoolNewBlock(uint start_item)
{
Depot *d;
Depot *depot;
/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
* TODO - This is just a temporary stage, this will be removed. */
for (d = GetDepot(start_item); d != NULL; d = (d->index + 1U < GetDepotPoolSize()) ? GetDepot(d->index + 1U) : NULL) d->index = start_item++;
FOR_ALL_DEPOTS_FROM(depot, start_item)
depot->index = start_item++;
}
DEFINE_OLD_POOL(Depot, Depot, DepotPoolNewBlock, NULL)
/* Initialize the town-pool */
MemoryPool _depot_pool = { "Depots", DEPOT_POOL_MAX_BLOCKS, DEPOT_POOL_BLOCK_SIZE_BITS, sizeof(Depot), &DepotPoolNewBlock, 0, 0, NULL };
/**
@@ -31,12 +33,13 @@ DEFINE_OLD_POOL(Depot, Depot, DepotPoolNewBlock, NULL)
*
* @return Returns the depot if the tile had a depot, else it returns NULL
*/
Depot *GetDepotByTile(TileIndex tile)
Depot *GetDepotByTile(uint tile)
{
Depot *depot;
FOR_ALL_DEPOTS(depot) {
if (depot->xy == tile) return depot;
if (depot->xy == tile)
return depot;
}
return NULL;
@@ -47,53 +50,63 @@ Depot *GetDepotByTile(TileIndex tile)
*/
Depot *AllocateDepot(void)
{
Depot *d;
Depot *depot;
/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
* TODO - This is just a temporary stage, this will be removed. */
for (d = GetDepot(0); d != NULL; d = (d->index + 1U < GetDepotPoolSize()) ? GetDepot(d->index + 1U) : NULL) {
if (!IsValidDepot(d)) {
DepotID index = d->index;
FOR_ALL_DEPOTS(depot) {
if (!IsValidDepot(depot)) {
uint index = depot->index;
memset(d, 0, sizeof(Depot));
d->index = index;
memset(depot, 0, sizeof(Depot));
depot->index = index;
return d;
return depot;
}
}
/* Check if we can add a block to the pool */
if (AddBlockToPool(&_Depot_pool)) return AllocateDepot();
if (AddBlockToPool(&_depot_pool))
return AllocateDepot();
return NULL;
}
/**
* Clean up a depot
* Delete a depot
*/
void DestroyDepot(Depot *depot)
void DoDeleteDepot(uint tile)
{
Order order;
Depot *depot;
/* Get the depot */
depot = GetDepotByTile(tile);
/* Clear the tile */
DoClearSquare(depot->xy);
DoClearSquare(tile);
/* Clear the depot */
depot->xy = 0;
/* Clear the depot from all order-lists */
RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, depot->index);
order.type = OT_GOTO_DEPOT;
order.station = depot->index;
DeleteDestinationFromVehicleOrder(order);
/* Delete the depot-window */
DeleteWindowById(WC_VEHICLE_DEPOT, depot->xy);
DeleteWindowById(WC_VEHICLE_DEPOT, tile);
}
void InitializeDepots(void)
void InitializeDepot(void)
{
CleanPool(&_Depot_pool);
AddBlockToPool(&_Depot_pool);
CleanPool(&_depot_pool);
AddBlockToPool(&_depot_pool);
}
static const SaveLoad _depot_desc[] = {
SLE_CONDVAR(Depot, xy, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Depot, xy, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_VAR(Depot, town_index, SLE_UINT16),
static const byte _depot_desc[] = {
SLE_CONDVAR(Depot, xy, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Depot, xy, SLE_UINT32, 6, 255),
SLE_VAR(Depot,town_index, SLE_UINT16),
SLE_END()
};
@@ -102,8 +115,10 @@ static void Save_DEPT(void)
Depot *depot;
FOR_ALL_DEPOTS(depot) {
SlSetArrayIndex(depot->index);
SlObject(depot, _depot_desc);
if (IsValidDepot(depot)) {
SlSetArrayIndex(depot->index);
SlObject(depot, _depot_desc);
}
}
}
@@ -114,7 +129,7 @@ static void Load_DEPT(void)
while ((index = SlIterateArray()) != -1) {
Depot *depot;
if (!AddBlockIfNeeded(&_Depot_pool, index))
if (!AddBlockIfNeeded(&_depot_pool, index))
error("Depots: failed loading savegame: too many depots");
depot = GetDepot(index);

116
depot.h
View File

@@ -1,48 +1,39 @@
/* $Id$ */
#ifndef DEPOT_H
#define DEPOT_H
/** @file depot.h Header files for depots (not hangars)
* @see depot.c */
#include "direction.h"
#include "oldpool.h"
#include "pool.h"
#include "tile.h"
#include "variables.h"
struct Depot {
TileIndex xy;
TownID town_index;
DepotID index;
uint16 town_index;
uint16 index;
};
DECLARE_OLD_POOL(Depot, Depot, 3, 8000)
extern MemoryPool _depot_pool;
/**
* Check if a depot really exists.
* Get the pointer to the depot with index 'index'
*/
static inline bool IsValidDepot(const Depot *depot)
static inline Depot *GetDepot(uint index)
{
return depot != NULL && depot->xy != 0;
return (Depot*)GetItemFromPool(&_depot_pool, index);
}
static inline bool IsValidDepotID(uint index)
/**
* Get the current size of the DepotPool
*/
static inline uint16 GetDepotPoolSize(void)
{
return index < GetDepotPoolSize() && IsValidDepot(GetDepot(index));
return _depot_pool.total_items;
}
void DestroyDepot(Depot *depot);
static inline void DeleteDepot(Depot *depot)
static inline bool IsDepotIndex(uint index)
{
DestroyDepot(depot);
depot->xy = 0;
return index < GetDepotPoolSize();
}
void ShowDepotWindow(TileIndex tile, byte type);
#define FOR_ALL_DEPOTS_FROM(d, start) for (d = GetDepot(start); d != NULL; d = (d->index + 1U < GetDepotPoolSize()) ? GetDepot(d->index + 1U) : NULL) if (IsValidDepot(d))
#define FOR_ALL_DEPOTS_FROM(d, start) for (d = GetDepot(start); d != NULL; d = (d->index + 1 < GetDepotPoolSize()) ? GetDepot(d->index + 1) : NULL)
#define FOR_ALL_DEPOTS(d) FOR_ALL_DEPOTS_FROM(d, 0)
#define MIN_SERVINT_PERCENT 5
@@ -50,63 +41,80 @@ void ShowDepotWindow(TileIndex tile, byte type);
#define MIN_SERVINT_DAYS 30
#define MAX_SERVINT_DAYS 800
/**
* Get the service interval domain.
/** Get the service interval domain.
* Get the new proposed service interval for the vehicle is indeed, clamped
* within the given bounds. @see MIN_SERVINT_PERCENT ,etc.
* @param index proposed service interval
*/
static inline Date GetServiceIntervalClamped(uint index)
static inline uint16 GetServiceIntervalClamped(uint index)
{
return (_patches.servint_ispercent) ? clamp(index, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : clamp(index, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
}
VARDEF TileIndex _last_built_train_depot_tile;
VARDEF TileIndex _last_built_road_depot_tile;
VARDEF TileIndex _last_built_aircraft_depot_tile;
VARDEF TileIndex _last_built_ship_depot_tile;
/**
* Check if a depot really exists.
*/
static inline bool IsValidDepot(const Depot* depot)
{
return depot->xy != 0; /* XXX: Replace by INVALID_TILE someday */
}
/**
* Check if a tile is a depot of the given type.
*/
static inline bool IsTileDepotType(TileIndex tile, TransportType type)
{
switch (type) {
switch(type)
{
case TRANSPORT_RAIL:
return IsTileType(tile, MP_RAILWAY) && (_m[tile].m5 & 0xFC) == 0xC0;
return IsTileType(tile, MP_RAILWAY) && (_map5[tile] & 0xFC) == 0xC0;
break;
case TRANSPORT_ROAD:
return IsTileType(tile, MP_STREET) && (_m[tile].m5 & 0xF0) == 0x20;
return IsTileType(tile, MP_STREET) && (_map5[tile] & 0xF0) == 0x20;
break;
case TRANSPORT_WATER:
return IsTileType(tile, MP_WATER) && (_m[tile].m5 & ~3) == 0x80;
return IsTileType(tile, MP_WATER) && (_map5[tile] & ~3) == 0x80;
break;
default:
assert(0);
return false;
}
}
/**
* Find out if the slope of the tile is suitable to build a depot of given direction
* @param direction The direction in which the depot's exit points. Starts with 0 as NE and goes Clockwise
* @param tileh The slope of the tile in question
* @return true if the construction is possible
* This is checked by the ugly 0x4C >> direction magic, which does the following:
* 0x4C is 0100 1100 and tileh has only bits 0..3 set (steep tiles are ruled out)
* So: for direction (only the significant bits are shown)<p>
* 00 (exit towards NE) we need either bit 2 or 3 set in tileh: 0x4C >> 0 = 1100<p>
* 01 (exit towards SE) we need either bit 1 or 2 set in tileh: 0x4C >> 1 = 0110<p>
* 02 (exit towards SW) we need either bit 0 or 1 set in tileh: 0x4C >> 2 = 0011<p>
* 03 (exit towards NW) we need either bit 0 or 4 set in tileh: 0x4C >> 3 = 1001<p>
* So ((0x4C >> direction) & tileh) determines whether the depot can be built on the current tileh
* Returns the direction the exit of the depot on the given tile is facing.
*/
static inline bool CanBuildDepotByTileh(uint32 direction, Slope tileh)
static inline uint GetDepotDirection(TileIndex tile, TransportType type)
{
return ((0x4C >> direction) & tileh) != 0;
assert(IsTileDepotType(tile, type));
switch (type)
{
case TRANSPORT_RAIL:
case TRANSPORT_ROAD:
/* Rail and road store a diagonal direction in bits 0 and 1 */
return _map5[tile] & 3;
case TRANSPORT_WATER:
/* Water is stubborn, it stores the directions in a different order. */
switch (_map5[tile] & 3) {
case 0: return 0;
case 1: return 2;
case 2: return 3;
case 3: return 1;
}
default:
return 0; /* Not reached */
}
}
Depot *GetDepotByTile(TileIndex tile);
void InitializeDepots(void);
Depot *GetDepotByTile(uint tile);
void InitializeDepot(void);
Depot *AllocateDepot(void);
void DeleteDepotHighlightOfVehicle(const Vehicle *v);
void DoDeleteDepot(uint tile);
#endif /* DEPOT_H */

File diff suppressed because it is too large Load Diff

View File

@@ -1,147 +0,0 @@
/* $Id$ */
#ifndef DIRECTION_H
#define DIRECTION_H
/* Direction as commonly used in v->direction, 8 way. */
typedef enum Direction {
DIR_N = 0,
DIR_NE = 1, /* Northeast, upper right on your monitor */
DIR_E = 2,
DIR_SE = 3,
DIR_S = 4,
DIR_SW = 5,
DIR_W = 6,
DIR_NW = 7,
DIR_END,
INVALID_DIR = 0xFF,
} Direction;
static inline Direction ReverseDir(Direction d)
{
return (Direction)(4 ^ d);
}
typedef enum DirDiff {
DIRDIFF_SAME = 0,
DIRDIFF_45RIGHT = 1,
DIRDIFF_90RIGHT = 2,
DIRDIFF_REVERSE = 4,
DIRDIFF_90LEFT = 6,
DIRDIFF_45LEFT = 7
} DirDiff;
static inline DirDiff DirDifference(Direction d0, Direction d1)
{
return (DirDiff)((d0 + 8 - d1) % 8);
}
static inline DirDiff ChangeDirDiff(DirDiff d, DirDiff delta)
{
return (DirDiff)((d + delta) % 8);
}
static inline Direction ChangeDir(Direction d, DirDiff delta)
{
return (Direction)((d + delta) % 8);
}
/* Direction commonly used as the direction of entering and leaving tiles, 4-way */
typedef enum DiagDirection {
DIAGDIR_NE = 0, /* Northeast, upper right on your monitor */
DIAGDIR_SE = 1,
DIAGDIR_SW = 2,
DIAGDIR_NW = 3,
DIAGDIR_END,
INVALID_DIAGDIR = 0xFF,
} DiagDirection;
static inline DiagDirection ReverseDiagDir(DiagDirection d)
{
return (DiagDirection)(2 ^ d);
}
typedef enum DiagDirDiff {
DIAGDIRDIFF_SAME = 0,
DIAGDIRDIFF_90RIGHT = 1,
DIAGDIRDIFF_REVERSE = 2,
DIAGDIRDIFF_90LEFT = 3
} DiagDirDiff;
static inline DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
{
return (DiagDirection)((d + delta) % 4);
}
static inline DiagDirection DirToDiagDir(Direction dir)
{
return (DiagDirection)(dir >> 1);
}
static inline Direction DiagDirToDir(DiagDirection dir)
{
return (Direction)(dir * 2 + 1);
}
/* the 2 axis */
typedef enum Axis {
AXIS_X = 0,
AXIS_Y = 1,
AXIS_END
} Axis;
static inline Axis OtherAxis(Axis a)
{
return (Axis)(a ^ 1);
}
static inline Axis DiagDirToAxis(DiagDirection d)
{
return (Axis)(d & 1);
}
/*
* Converts an Axis to a DiagDirection
* Points always in the positive direction, i.e. S[EW]
*/
static inline DiagDirection AxisToDiagDir(Axis a)
{
return (DiagDirection)(2 - a);
}
/**
* Convert an axis and a flag for north/south into a DiagDirection
* @param ns north -> 0, south -> 1
*/
static inline DiagDirection XYNSToDiagDir(Axis xy, uint ns)
{
return (DiagDirection)(xy * 3 ^ ns * 2);
}
static inline bool IsValidDiagDirection(DiagDirection d)
{
return d < DIAGDIR_END;
}
static inline bool IsValidDirection(Direction d)
{
return d < DIR_END;
}
static inline bool IsValidAxis(Axis d)
{
return d < AXIS_END;
}
#endif /* DIRECTION_H */

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,7 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "functions.h"
#include "map.h"
#include "window.h"
#include "station.h"
@@ -13,14 +10,13 @@
#include "gfx.h"
#include "sound.h"
#include "command.h"
#include "variables.h"
static void ShowBuildDockStationPicker(void);
static void ShowBuildDocksDepotPicker(void);
static Axis _ship_depot_direction;
static byte _ship_depot_direction;
void CcBuildDocks(bool success, TileIndex tile, uint32 p1, uint32 p2)
void CcBuildDocks(bool success, uint tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_02_SPLAT, tile);
@@ -28,81 +24,72 @@ void CcBuildDocks(bool success, TileIndex tile, uint32 p1, uint32 p2)
}
}
void CcBuildCanal(bool success, TileIndex tile, uint32 p1, uint32 p2)
void CcBuildCanal(bool success, uint tile, uint32 p1, uint32 p2)
{
if (success) SndPlayTileFx(SND_02_SPLAT, tile);
}
static void PlaceDocks_Dock(TileIndex tile)
static void PlaceDocks_Dock(uint tile)
{
DoCommandP(tile, 0, 0, CcBuildDocks, CMD_BUILD_DOCK | CMD_AUTO | CMD_MSG(STR_9802_CAN_T_BUILD_DOCK_HERE));
}
static void PlaceDocks_Depot(TileIndex tile)
static void PlaceDocks_Depot(uint tile)
{
DoCommandP(tile, _ship_depot_direction, 0, CcBuildDocks, CMD_BUILD_SHIP_DEPOT | CMD_AUTO | CMD_MSG(STR_3802_CAN_T_BUILD_SHIP_DEPOT));
}
static void PlaceDocks_Buoy(TileIndex tile)
static void PlaceDocks_Buoy(uint tile)
{
DoCommandP(tile, 0, 0, CcBuildDocks, CMD_BUILD_BUOY | CMD_AUTO | CMD_MSG(STR_9835_CAN_T_POSITION_BUOY_HERE));
}
static void PlaceDocks_DemolishArea(TileIndex tile)
static void PlaceDocks_DemolishArea(uint tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y | GUI_PlaceProc_DemolishArea);
}
static void PlaceDocks_BuildCanal(TileIndex tile)
static void PlaceDocks_BuildCanal(uint tile)
{
VpStartPlaceSizing(tile, VPM_X_OR_Y);
}
static void PlaceDocks_BuildLock(TileIndex tile)
static void PlaceDocks_BuildLock(uint tile)
{
DoCommandP(tile, 0, 0, CcBuildDocks, CMD_BUILD_LOCK | CMD_AUTO | CMD_MSG(STR_CANT_BUILD_LOCKS));
}
enum {
DTW_CANAL = 3,
DTW_LOCK = 4,
DTW_DEMOLISH = 6,
DTW_DEPOT = 7,
DTW_STATION = 8,
DTW_BUOY = 9
};
static void BuildDocksClick_Canal(Window *w)
{
HandlePlacePushButton(w, DTW_CANAL, SPR_CURSOR_CANAL, 1, PlaceDocks_BuildCanal);
HandlePlacePushButton(w, 3, SPR_OPENTTD_BASE + 11, 1, PlaceDocks_BuildCanal);
}
static void BuildDocksClick_Lock(Window *w)
{
HandlePlacePushButton(w, DTW_LOCK, SPR_CURSOR_LOCK, 1, PlaceDocks_BuildLock);
HandlePlacePushButton(w, 4, SPR_OPENTTD_BASE + 64, 1, PlaceDocks_BuildLock);
}
static void BuildDocksClick_Demolish(Window *w)
{
HandlePlacePushButton(w, DTW_DEMOLISH, ANIMCURSOR_DEMOLISH, 1, PlaceDocks_DemolishArea);
HandlePlacePushButton(w, 6, ANIMCURSOR_DEMOLISH, 1, PlaceDocks_DemolishArea);
}
static void BuildDocksClick_Depot(Window *w)
{
if (HandlePlacePushButton(w, DTW_DEPOT, SPR_CURSOR_SHIP_DEPOT, 1, PlaceDocks_Depot)) ShowBuildDocksDepotPicker();
if (HandlePlacePushButton(w, 7, 0x2D1, 1, PlaceDocks_Depot)) ShowBuildDocksDepotPicker();
}
static void BuildDocksClick_Dock(Window *w)
{
if (HandlePlacePushButton(w, DTW_STATION, SPR_CURSOR_DOCK, 3, PlaceDocks_Dock)) ShowBuildDockStationPicker();
if (HandlePlacePushButton(w, 8, 0xE54, 3, PlaceDocks_Dock)) ShowBuildDockStationPicker();
}
static void BuildDocksClick_Buoy(Window *w)
{
HandlePlacePushButton(w, DTW_BUOY, SPR_CURSOR_BOUY, 1, PlaceDocks_Buoy);
HandlePlacePushButton(w, 9, 0x2BE, 1, PlaceDocks_Buoy);
}
static void BuildDocksClick_Landscaping(Window *w)
@@ -114,7 +101,7 @@ typedef void OnButtonClick(Window *w);
static OnButtonClick * const _build_docks_button_proc[] = {
BuildDocksClick_Canal,
BuildDocksClick_Lock,
NULL,
0,
BuildDocksClick_Demolish,
BuildDocksClick_Depot,
BuildDocksClick_Dock,
@@ -124,17 +111,17 @@ static OnButtonClick * const _build_docks_button_proc[] = {
static void BuildDocksToolbWndProc(Window *w, WindowEvent *e)
{
switch (e->event) {
switch(e->event) {
case WE_PAINT:
DrawWindowWidgets(w);
break;
case WE_CLICK:
if (e->we.click.widget - 3 >= 0 && e->we.click.widget != 5) _build_docks_button_proc[e->we.click.widget - 3](w);
break;
case WE_CLICK: {
if (e->click.widget - 3 >= 0 && e->click.widget != 5) _build_docks_button_proc[e->click.widget - 3](w);
} break;
case WE_KEYPRESS:
switch (e->we.keypress.keycode) {
case WE_KEYPRESS: {
switch(e->keypress.keycode) {
case '1': BuildDocksClick_Canal(w); break;
case '2': BuildDocksClick_Lock(w); break;
case '3': BuildDocksClick_Demolish(w); break;
@@ -142,80 +129,75 @@ static void BuildDocksToolbWndProc(Window *w, WindowEvent *e)
case '5': BuildDocksClick_Dock(w); break;
case '6': BuildDocksClick_Buoy(w); break;
case 'l': BuildDocksClick_Landscaping(w); break;
default: return;
default:
return;
}
break;
} break;
case WE_PLACE_OBJ:
_place_proc(e->we.place.tile);
_place_proc(e->place.tile);
break;
case WE_PLACE_DRAG: {
VpSelectTilesWithMethod(e->we.place.pt.x, e->we.place.pt.y, e->we.place.userdata);
VpSelectTilesWithMethod(e->place.pt.x, e->place.pt.y, e->place.userdata);
return;
}
case WE_PLACE_MOUSEUP:
if (e->we.place.pt.x != -1) {
if ((e->we.place.userdata & 0xF) == VPM_X_AND_Y) { // dragged actions
if (e->click.pt.x != -1) {
if ((e->place.userdata & 0xF) == VPM_X_AND_Y) { // dragged actions
GUIPlaceProcDragXY(e);
} else if (e->we.place.userdata == VPM_X_OR_Y) {
DoCommandP(e->we.place.tile, e->we.place.starttile, 0, CcBuildCanal, CMD_BUILD_CANAL | CMD_AUTO | CMD_MSG(STR_CANT_BUILD_CANALS));
}
} else if(e->place.userdata == VPM_X_OR_Y)
DoCommandP(e->place.tile, e->place.starttile, 0, CcBuildCanal, CMD_BUILD_CANAL | CMD_AUTO | CMD_MSG(STR_CANT_BUILD_CANALS));
}
break;
case WE_ABORT_PLACE_OBJ:
RaiseWindowButtons(w);
UnclickWindowButtons(w);
SetWindowDirty(w);
w = FindWindowById(WC_BUILD_STATION, 0);
if (w != NULL) WP(w,def_d).close = true;
if (w != NULL) WP(w,def_d).close=true;
w = FindWindowById(WC_BUILD_DEPOT, 0);
if (w != NULL) WP(w,def_d).close = true;
if (w != NULL) WP(w,def_d).close=true;
break;
case WE_PLACE_PRESIZE: {
TileIndex tile_from;
TileIndex tile_to;
uint tile_from, tile_to;
tile_from = tile_to = e->we.place.tile;
switch (GetTileSlope(tile_from, NULL)) {
case SLOPE_SW: tile_to += TileDiffXY(-1, 0); break;
case SLOPE_SE: tile_to += TileDiffXY( 0, -1); break;
case SLOPE_NW: tile_to += TileDiffXY( 0, 1); break;
case SLOPE_NE: tile_to += TileDiffXY( 1, 0); break;
default: break;
tile_from = tile_to = e->place.tile;
switch(GetTileSlope(tile_from, NULL)) {
case 3: tile_to += TILE_XY(-1,0); break;
case 6: tile_to += TILE_XY(0,-1); break;
case 9: tile_to += TILE_XY(0,1); break;
case 12:tile_to += TILE_XY(1,0); break;
}
VpSetPresizeRange(tile_from, tile_to);
} break;
case WE_DESTROY:
if (_patches.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0);
break;
}
}
static const Widget _build_docks_toolb_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 145, 0, 13, STR_9801_DOCK_CONSTRUCTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_NONE, 7, 146, 157, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_IMGBTN, RESIZE_NONE, 7, 0, 21, 14, 35, SPR_IMG_BUILD_CANAL, STR_BUILD_CANALS_TIP},
{ WWT_IMGBTN, RESIZE_NONE, 7, 22, 43, 14, 35, SPR_IMG_BUILD_LOCK, STR_BUILD_LOCKS_TIP},
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 145, 0, 13, STR_9801_DOCK_CONSTRUCTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_NONE, 7, 146, 157, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 21, 14, 35, SPR_IMG_BUILD_CANAL, STR_BUILD_CANALS_TIP},
{ WWT_PANEL, RESIZE_NONE, 7, 22, 43, 14, 35, SPR_IMG_BUILD_LOCK, STR_BUILD_LOCKS_TIP},
{ WWT_PANEL, RESIZE_NONE, 7, 44, 47, 14, 35, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, 7, 44, 47, 14, 35, 0x0, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, 7, 48, 69, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC},
{ WWT_IMGBTN, RESIZE_NONE, 7, 70, 91, 14, 35, SPR_IMG_SHIP_DEPOT, STR_981E_BUILD_SHIP_DEPOT_FOR_BUILDING},
{ WWT_IMGBTN, RESIZE_NONE, 7, 92, 113, 14, 35, SPR_IMG_SHIP_DOCK, STR_981D_BUILD_SHIP_DOCK},
{ WWT_IMGBTN, RESIZE_NONE, 7, 114, 135, 14, 35, SPR_IMG_BOUY, STR_9834_POSITION_BUOY_WHICH_CAN},
{ WWT_IMGBTN, RESIZE_NONE, 7, 136, 157, 14, 35, SPR_IMG_LANDSCAPING, STR_LANDSCAPING_TOOLBAR_TIP},
{ WWT_PANEL, RESIZE_NONE, 7, 48, 69, 14, 35, 703, STR_018D_DEMOLISH_BUILDINGS_ETC},
{ WWT_PANEL, RESIZE_NONE, 7, 70, 91, 14, 35, 748, STR_981E_BUILD_SHIP_DEPOT_FOR_BUILDING},
{ WWT_PANEL, RESIZE_NONE, 7, 92, 113, 14, 35, 746, STR_981D_BUILD_SHIP_DOCK},
{ WWT_PANEL, RESIZE_NONE, 7, 114, 135, 14, 35, 693, STR_9834_POSITION_BUOY_WHICH_CAN},
{ WWT_PANEL, RESIZE_NONE, 7, 136, 157, 14, 35, SPR_IMG_LANDSCAPING, STR_LANDSCAPING_TOOLBAR_TIP},
{ WIDGETS_END},
};
static const WindowDesc _build_docks_toolbar_desc = {
WDP_ALIGN_TBR, 22, 158, 36,
WC_BUILD_TOOLBAR, 0,
640-158, 22, 158, 36,
WC_BUILD_TOOLBAR,0,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
_build_docks_toolb_widgets,
BuildDocksToolbWndProc
@@ -223,48 +205,45 @@ static const WindowDesc _build_docks_toolbar_desc = {
void ShowBuildDocksToolbar(void)
{
if (!IsValidPlayer(_current_player)) return;
if (_current_player == OWNER_SPECTATOR) return;
DeleteWindowById(WC_BUILD_TOOLBAR, 0);
AllocateWindowDesc(&_build_docks_toolbar_desc);
if (_patches.link_terraform_toolbar) ShowTerraformToolbar();
}
static void BuildDockStationWndProc(Window *w, WindowEvent *e)
{
switch (e->event) {
case WE_CREATE: LowerWindowWidget(w, _station_show_coverage + 3); break;
int rad;
switch(e->event) {
case WE_PAINT: {
int rad = (_patches.modified_catchment) ? CA_DOCK : 4;
if (WP(w,def_d).close) return;
if (WP(w,def_d).close)
return;
w->click_state = (1<<3) << _station_show_coverage;
DrawWindowWidgets(w);
if (_station_show_coverage) {
SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
if (_patches.modified_catchment) {
rad = CA_DOCK;
} else {
SetTileSelectSize(1, 1);
rad = 4;
}
if (_station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
else SetTileSelectBigSize(0, 0, 0, 0);
DrawStringCentered(74, 17, STR_3066_COVERAGE_AREA_HIGHLIGHT, 0);
DrawStationCoverageAreaText(4, 50, (uint)-1, rad);
break;
}
} break;
case WE_CLICK:
switch (e->we.click.widget) {
case 3:
case 4:
RaiseWindowWidget(w, _station_show_coverage + 3);
_station_show_coverage = e->we.click.widget - 3;
LowerWindowWidget(w, _station_show_coverage + 3);
SndPlayFx(SND_15_BEEP);
SetWindowDirty(w);
break;
case WE_CLICK: {
switch(e->click.widget) {
case 3: case 4:
_station_show_coverage = e->click.widget - 3;
SndPlayFx(SND_15_BEEP);
SetWindowDirty(w);
break;
}
break;
} break;
case WE_MOUSELOOP:
case WE_MOUSELOOP: {
if (WP(w,def_d).close) {
DeleteWindow(w);
return;
@@ -272,26 +251,27 @@ static void BuildDockStationWndProc(Window *w, WindowEvent *e)
CheckRedrawStationCoverage(w);
break;
}
case WE_DESTROY:
if (!WP(w,def_d).close) ResetObjectToPlace();
if (!WP(w,def_d).close)
ResetObjectToPlace();
break;
}
}
static const Widget _build_dock_station_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 147, 0, 13, STR_3068_DOCK, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 147, 14, 74, 0x0, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 14, 73, 30, 40, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE},
{ WWT_TEXTBTN, RESIZE_NONE, 14, 74, 133, 30, 40, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA},
{ WWT_LABEL, RESIZE_NONE, 7, 0, 147, 17, 30, STR_3066_COVERAGE_AREA_HIGHLIGHT, STR_NULL},
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 147, 0, 13, STR_3068_DOCK, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 147, 14, 74, 0x0, STR_NULL},
{ WWT_CLOSEBOX, RESIZE_NONE, 14, 14, 73, 30, 40, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE},
{ WWT_CLOSEBOX, RESIZE_NONE, 14, 74, 133, 30, 40, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA},
{ WIDGETS_END},
};
static const WindowDesc _build_dock_station_desc = {
WDP_AUTO, WDP_AUTO, 148, 75,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
-1, -1, 148, 75,
WC_BUILD_STATION,WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_build_dock_station_widgets,
BuildDockStationWndProc
@@ -304,7 +284,7 @@ static void ShowBuildDockStationPicker(void)
static void UpdateDocksDirection(void)
{
if (_ship_depot_direction != AXIS_X) {
if (_ship_depot_direction != 0) {
SetTileSelectSize(1, 2);
} else {
SetTileSelectSize(2, 1);
@@ -313,10 +293,9 @@ static void UpdateDocksDirection(void)
static void BuildDocksDepotWndProc(Window *w, WindowEvent *e)
{
switch (e->event) {
case WE_CREATE: LowerWindowWidget(w, _ship_depot_direction + 3); break;
switch(e->event) {
case WE_PAINT:
w->click_state = (1<<3) << _ship_depot_direction;
DrawWindowWidgets(w);
DrawShipDepotSprite(67, 35, 0);
@@ -326,12 +305,10 @@ static void BuildDocksDepotWndProc(Window *w, WindowEvent *e)
return;
case WE_CLICK: {
switch (e->we.click.widget) {
switch(e->click.widget) {
case 3:
case 4:
RaiseWindowWidget(w, _ship_depot_direction + 3);
_ship_depot_direction = e->we.click.widget - 3;
LowerWindowWidget(w, _ship_depot_direction + 3);
_ship_depot_direction = e->click.widget - 3;
SndPlayFx(SND_15_BEEP);
UpdateDocksDirection();
SetWindowDirty(w);
@@ -340,27 +317,29 @@ static void BuildDocksDepotWndProc(Window *w, WindowEvent *e)
} break;
case WE_MOUSELOOP:
if (WP(w,def_d).close) DeleteWindow(w);
if (WP(w,def_d).close)
DeleteWindow(w);
break;
case WE_DESTROY:
if (!WP(w,def_d).close) ResetObjectToPlace();
if (!WP(w,def_d).close)
ResetObjectToPlace();
break;
}
}
static const Widget _build_docks_depot_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 203, 0, 13, STR_3800_SHIP_DEPOT_ORIENTATION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 203, 14, 85, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, 14, 3, 100, 17, 82, 0x0, STR_3803_SELECT_SHIP_DEPOT_ORIENTATION},
{ WWT_PANEL, RESIZE_NONE, 14, 103, 200, 17, 82, 0x0, STR_3803_SELECT_SHIP_DEPOT_ORIENTATION},
{ WWT_CLOSEBOX, RESIZE_NONE, 7, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 7, 11, 203, 0, 13, STR_3800_SHIP_DEPOT_ORIENTATION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, 7, 0, 203, 14, 85, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, 14, 3, 100, 17, 82, 0x0, STR_3803_SELECT_SHIP_DEPOT_ORIENTATION},
{ WWT_PANEL, RESIZE_NONE, 14, 103, 200, 17, 82, 0x0, STR_3803_SELECT_SHIP_DEPOT_ORIENTATION},
{ WIDGETS_END},
};
static const WindowDesc _build_docks_depot_desc = {
WDP_AUTO, WDP_AUTO, 204, 86,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
-1, -1, 204, 86,
WC_BUILD_DEPOT,WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_build_docks_depot_widgets,
BuildDocksDepotWndProc
@@ -376,5 +355,5 @@ static void ShowBuildDocksDepotPicker(void)
void InitializeDockGui(void)
{
_ship_depot_direction = AXIS_X;
_ship_depot_direction = 0;
}

View File

@@ -1,59 +0,0 @@
STRGEN USAGE
------------
This guide is only interesting for people who want to alter something
themselves without access to WT2 (translator2.openttd.org). Please note that
your compiled language file will only be compatible with the OpenTTD version
you have downloaded english.txt, the master language file, for. While this is
not always true, namely when changes in the code have not touched language
files, your safest bet is to assume this 'limitation'.
As a first step you need to compile strgen. This is as easy as typing
'make strgen'. You can also download a precompiled binary from a release,
nightly, etc.
strgen takes as argument a txt file and translates it to a lng file, allowing
it to be used inside OpenTTD. strgen needs the master language file
english.txt to work. Below are some examples of strgen usage.
EXAMPLES
--------
Example 1:
if you are in the root of your working copy (svn code), you should type
strgen/strgen -s lang lang/english.txt
to compile englist.txt into english.lng. It will be placed in the lang dir
Example 2:
you only have the strgen executable (no working copy) and you want to compile
a txt file in the same directory. You should type
./strgen english.txt
and you will get and english.lng in the same dir
Example 3:
you have strgen somewhere, english.txt in /usr/openttd/lang and you want the
resulting language file to go to /tmp. Use
./strgen -s /usr/openttd/lang -d /tmp english.txt
You can interchange english.txt to whichever language you want to generate a
.lng file for.
STRGEN COMMAND SWITCHES
-----------------------
-v | --version
strgen will tell what svn revision it was last modified
-t | --todo
strgen will add <TODO> to any untranslated/missing strings and use the english
strings while compiling the language file
-w | --warning
strgen will print any missing strings or wrongly translated (bad format)
to standard error output(stderr)
-h | --help | -?
Print out a summarized help message explaining these switches
-s | --source_dir
strgen will search for the master file english.txt in the directory specified
by this switch instead of the current directory
-d | --dest_dir
strgen will put <language>.lng in the directory specified by this switch; if
no dest_dir is given, output is the same as source_dir

View File

@@ -32,3 +32,18 @@ this will need english.txt to be present
-w
strgen will print any missing strings to standard error output(stderr)
this will need english.txt to be present
here are a very useful tool for translators:
http://openttd.rulez.org/
HOWTO compile strgen:
(this should be useless as you can just type make)
Goto the main dir
Compile by typing
gcc strgen/strgen.c -o strgen/strgen -DUNIX
or if you want it to tell the revision too
gcc strgen/strgen.c rev.o -o strgen/strgen -DUNIX -DWITH_REV (this is the one the makefile uses)
you now have a program called strgen in the strgen directory

View File

@@ -2,9 +2,9 @@ Welcome to the manual for OpenTTD. The latest release version at the time of wr
1 Obtaining OpenTTD.
You can obtain built binaries of OpenTTD for the 4 supported platforms - Win32, Linux,-x86, BeOS 5 and MacOS-X from the projects Sourceforge page, at http://sourceforge.net/projects/openttd . For the non-Win32 builds you will need libSDL.so, libpng.so and zlib.so compiled for your platform. Some builds will include these.
You can obtain built binaries of OpenTTD for the 4 supported platforms - Win32, Linux,-x86, BeOS 5 and MacOS-X from the projects Sourceforge page, at http://sourceforge.net/projects/openttd . For the non-Win32 builds you will need libSDL.so, libpng.so and zlib.so compiled for your platform. Some builds will include these.
If you use another platform, such as FreeBSD, which has POSIX file i/o and an SDL port, you should be able to build OpenTTD from its source. This is available in the proejcts Subversion repository at svn://svn.openttd.com . The module name is "trunk".
If you use another platform, such as FreeBSD, which has POSIX file i/o and an SDL port, you should be able to build OpenTTD from its source. This is available in the proejcts Subversion repository at svn://svn.openttd.com . The module name is "trunk".
1.1 Building OpenTTD.
@@ -18,11 +18,12 @@ Use make or gmake to compile OpenTTD. You can adjust Makefile.config to compile
BeOS:
On BeOS, run ./configure and then use jam. There are a variaty of options you can pass to your build tool, these are reported by ./configure.
1.2 Installing OpenTTD.
On Windows, insert your "Transport Tycoon Deluxe for Windows 95" disk. You can use a DOS version, but your graphics will be purple. NB: Even if your version of Transport Tycoon Deluxe ran on Windows 95, it may still be the DOS version. Then run the OpenTTD installer.
On Windows, insert your "Transport Tycoon Deluxe for Windows 95" disk. You can use a DOS version, but your graphics will be purple. NB: Even if your version of Transport Tycoon Deluxe ran on Windows 95, it may still be the DOS version. Then run the OpenTTD installer.
On UNIX platforms; decompress your OpenTTD archive, or otherwise run the installer. You should be left with an OpenTTD directory on your system. In this directory, make a subdirectory called 'data', and into this place the sample.cat file and all the .grf files from the install CD of 'Transport Tycoon Deluxe for Windows 95".
On UNIX platforms; decompress your OpenTTD archive, or otherwise run the installer. You should be left with an OpenTTD directory on your system. In this directory, make a subdirectory called 'data', and into this place the sample.cat file and all the .grf files from the install CD of 'Transport Tycoon Deluxe for Windows 95".
(Alternatively you can use the TTD GRF files from the DOS version: TRG1.GRF, TRGC.GRF, TRGH.GRF, TRGI.GRF, TRGT.GRF. A few minor graphical glitches with the DOS graphics remain. E.g. the autorail button in the rail toolbar doesn't look as nice as with the Windows graphics.)
If you want MIDI music, copy the 'gm' folder from the original game directory/CD to the OpenTTD folder.
@@ -37,7 +38,7 @@ On BeOS and Mac OS-X, just double click the ttd binary in the Tracker/Finder. Yo
1.4 Configuring OpenTTD
OpenTTD's launch menu contains three configuration menus - Difficulty Settings, Configure Patches and Game Settings. Most of these menus can be configured from within a running game as well.
OpenTTD's launch menu contains three configuration menus - Difficulty Settings, Configure Patches and Game Settings. Most of these menus can be configured from within a running game as well.
Difficulty Settings lets you configure settings that affect the difficulty of playing the game. These include when your (computer-controlled) competitors can start building, how many of them there are, and how intelligent they are. You can also control how much the subsidy mutliplier is for subsidised routes, and how stable/volitile the in-game economy is. You can also set how you want the terrain to be configured in a random game.
@@ -51,13 +52,14 @@ This section of the manual is written with the assumption that you already know
2.2 Station Construction
In OpenTTD, you can build rail stations up to seven squares long and with up to seven platforms. You can also have stations spreading across far larger distances, allowing a large rail station to be connected to a large airport, for instance.
In OpenTTD, you can build rail stations up to seven squares long and with up to seven platforms. You can also have stations spreading across far larger distances, allowing a large rail station to be connected to a large airport, for instance.
However, there is an even more noticable difference in rail station construction. You may now add platforms and lenght to a station after it has been built, and you may also add platforms of a different type. Users of TTDPatch will be used to this behaviour. But beyond what TTDPatch has, you can make stations of uneven lenght/width, and even ones with perpendicular tracks. You can also delete single tiles or tracks from a station, by holding down Shift before pressing the station construction button.
2.3 Checkpoint Stations
Checkpoint stations (the small blue item in the rail construction window) are small 1x1 stations. They must be built on top of pre-existing track. They do not accept or produce carge of any kind. They exist solely for use as route points. They become useful when dealing with large networks where trains may attempt to route themselves along undesirable or impossible routes. As an alternative to checkpoint stations, you can also direct trains to visit depots along the way. This has the advantage of also servicing the train and hence the train will rarely to never need to depart from its route to be serviced.
Checkpoint stations (the small blue item in the rail construction window) are small 1x1 stations. They must be built on top of pre-existing track. They do not accept or produce carge of any kind. They exist solely for use as route points. They become useful when dealing with large networks where trains may attempt to route themselves along undesirable or impossible routes. As an alternative to checkpoint stations, you can also direct trains to visit depots along the way. This has the advantage of also servicing the train and hence the train will rarely to never need to depart from its route to be serviced.
2.4 Freeform Rail Laying.
@@ -73,7 +75,7 @@ This allows you to build roads, rails, stations and depots on slopes. It also al
2.7 Long Bridges
OpenTTD allows you to constuct bridges up to 127 squares - half the size of the current map. This means that the crossing of large estuaries, such at the Bristol Channel in the original "West Country 90210" scenario can be acheived with one bridge instead of many bridges with staging points.
OpenTTD allows you to constuct bridges up to 127 squares - half the size of the current map. This means that the crossing of large estuaries, such at the Bristol Channel in the original "West Country 90210" scenario can be acheived with one bridge instead of many bridges with staging points.
2.8 Long trains
@@ -87,7 +89,7 @@ This addition to OpenTTD allows you to see the current speed of any vehicle in t
Virtually any settings - train numbers, start date, what vehicles your competitors can use, etc - can be set in OpenTTD. Just use the Configure Patches menu on the main screen.
2.11 Network Play
2.11 Network Play
See multiplayer.txt for more info.
@@ -97,4 +99,4 @@ This button, at the end of the train construction window, lets you 'recycle' tra
2.13 Canal Building
This button, at the end of the water construction window, lets you build canals and shiplifts across the landscape. These act just like normal water.
This button, at the end of the water construction window, lets you build canals and shiplifts across the landscape. These act just like normal water.

View File

@@ -1,23 +0,0 @@
To install OpenTTD, you should drag the game to any location you want and in that folder, you should create a folder called "data". It should contain:
sample.cat
trg1r.grf
trgcr.grf
trghr.grf
trgir.grf
trgtr.grf
(Alternatively you can use the TTD GRF files from the DOS version: TRG1.GRF, TRGC.GRF, TRGH.GRF, TRGI.GRF, TRGT.GRF. A few minor graphical glitches with the DOS graphics remain. E.g. the autorail button in the rail toolbar doesn't look as nice as with the Windows graphics.)
You should also use the data folder to add any custom grf files if you like
if you want music, you can add a GM folder and add all .gm files from TTD inside it
If you want to use the scenarios, you can copy the scenario folder as well. If you already have one, just copy the content so you don't overwrite old ones that have been removed.
In the end, you should have a folder containing:
OpenTTD (the actual game)
data (containing the grf files)
GM (optional for music)
scenario (optional pregenerated maps)
The game adds some items by itself when it runs, like a save folder and a setting file

View File

@@ -0,0 +1,24 @@
It's gone
The main goal with the package system was to make it as simple as possible to update. The problem was that some files inside the data folder should be updated and not others. Now the data files have been moved inside OpenTTD itself and to make it even easier, the same goes for the lang dir. There will no longer be an issue where people have different versions of grf files, language files and OpenTTD.
To install simply copy OpenTTD into the folder you want
If it is your current folder with outdated grf files, you should remove
canalsw.grf
openttd.grf
opntitle.dat
signalsw.grf
trkfoundw.grf
THE TTD GRF FILES ARE STILL NEEDED!
They need to be inside a folder called "data" in the same folder as OpenTTD. Create it if you have none. It should contain:
sample.cat
trg1r.grf
trgcr.grf
trghr.grf
trgir.grf
trgtr.grf
(Alternatively you can use the TTD GRF files from the DOS version: TRG1.GRF, TRGC.GRF, TRGH.GRF, TRGI.GRF, TRGT.GRF. A few minor graphical glitches with the DOS graphics remain. E.g. the autorail button in the rail toolbar doesn't look as nice as with the Windows graphics.)
You should also use the data folder to add any custom grf files if you like

View File

@@ -0,0 +1,36 @@
Since you are reading this, OpenTTD have crashed. This file tells you how
to fix the most common problems or make to make a bug report, that the
developers can use to track down the problem
If it is an assert, OpenTTD will open the console for you, if it is truly a crash, you have to do it yourself. The Console is located at /Applications/Utilities/Console.
The problem is near the button of the page
The problems are as follows:
NOTE: build from source means to download the source and compile
yourself. If you get one of the build from source error with the version
that is downloaded on a dmg file, you should make a bug report
--Didn't find a needed file:
you just give it the file it asks for. It even tells you what
folder it wants it in
most common version of this problem is "Error: Cannot open file
'data/sample.cat'"
if you get that one, that means that you haven't got all the
needed files from the WINDOWS version of TTD
or if you build from source,
--Error: No available language packs
you need at least one .lng file in your lang folder. This applies
only to people who build from source
--spritecache.c:237: failed assertion `b'
you got an outdated grf file. Update from the data folder in the
source. This applies only to people, who build from source
--assertion error that are not triggered by one of the errors listed in
this file:
you most likely found a bug. Write down the assertion and try to
see if you can reproduce it. If you can, make a
savegame from just before it happens (autosaves are useful here)
and post a bugreport with it on sourceforge
Write what you did to trigger the bug and what assertion it made

View File

@@ -0,0 +1,62 @@
Compiling and developing OpenTTD on MandrakeLinux 10.0 Official
A quick guide to get started with OpenTTD development on Linux.
---------------------------------------------------------------
1.) RPMs:
Most packages that are required for development (like gcc) should already be installed on your box. You will require those RPMs additionally:
- libsdl1.2-devel-1.2.7-2mdk
- subversion-1.0.1-1mdk (+ dependencies)
- libsvn_ra_svn1_0-1.0.1-1mdk
2.) Subversion:
To obtain the source code from the subversion server type
$ svn co svn://svn.openttd.com/openttd/trunk openttd
from command line to dump the code into the directory 'openttd'.
To update your working copy to the latest revision use
$ svn update
Don't worry, your version will be merged with the latest version.
The command
$ svn diff > mypatch.diff
creates a patch file (aka diff file) which you can submit to the developers to share your improvements.
You can undo changes to a file with
$svn revert filename
3.) Required data files:
Copy the following files from Transport Tycoon Deluxe to openttd/data/
sample.cat
trg1r.grf
trgcr.grf
trghr.grf
trgir.grf
trgtr.grf
(Alternatively you can use the TTD GRF files from the DOS version: TRG1.GRF, TRGC.GRF, TRGH.GRF, TRGI.GRF, TRGT.GRF. A few minor graphical glitches with the DOS graphics remain. E.g. the autorail button in the rail toolbar doesn't look as nice as with the Windows graphics.)
4.) Compiling and running:
Compile OpenTTD with
$ make
and run it with
$ ./ttd
5.) Playing the soundtrack:
If you want the original TTD music you need to copy the whole /gm/ directory from Windows. Additionally the TiMidity driver is required:
TiMidity++-2.12.0-0.pre1.4mdk (+ dependencies)
To run OpenTTD with music support type
$ ./ttd -m extmidi
X.) Last Update: $Date: 2004-06-01 19:08:09 +0200 (Tue, 01 Jun 2004) $
Written for revision $Rev: 710 $

View File

@@ -15,13 +15,15 @@ LIBRARIES REQUIRED FOR END USERS
SDL.DLL (SDL 1.2.7) and FSLib.dll are required to use this program:
these can be downloaded from the Files section at
http://sourceforge.net/projects/openttd/ - see "os2-useful-v1.1.zip".
Version 20051222 of SDL or later is required. This can be found at
http://sdl.netlabs.org/.
http://sourceforge.net/projects/openttd/ - see "os2-useful.zip".
(Note that a newer version of SDL is now available at
ftp://ftp.netlabs.org/pub/sdl/sdl-dev-os2-2004-12-22.zip which may
help solve some problems).
Please note that earlier SDL releases will probably NOT work with
OpenTTD. If you experience problems with OpenTTD, please check
your SDL and FSLib.dll versions (both must match).
Please note that SDL release 2005-03-30 does NOT work with OpenTTD,
at least in my experience and the experience of a couple of other
users. If you experience problems with OpenTTD, please try downgrading
to SDL 2004-12-22.
Note that to actually play the game, I have found in my own
experience that a version of the Scitech Display Drivers or its later
@@ -50,9 +52,6 @@ To enable music, start OpenTTD with the command line:
If I hear enough responses that both music and sound work together (it might
just be my system), I'll have the defaults changed.
Please note also that the GCC version does not currently support the MCI MIDI
system.
A NOTE ABOUT DEDICATED MULTIPLAYER SERVERS
------------------------------------------
@@ -70,33 +69,16 @@ BUILDING THE OS/2 VERSION
Compiler
--------
Innotek GCC, an OS/2 port of the popular GCC compiler, was used to build OpenTTD.
See www.innotek.de for more information. You WILL need a reasonably UNIX-like
build environment in order to build OpenTTD successfully - the following link
may help to set one up (although some of the links from that page are broken):
Open Watcom 1.3 was used to build OpenTTD (earlier versions will
NOT work). See http://www.openwatcom.org/ to download it. It may
also be possible to build OpenTTD with GCC: I attempted this
before using Open Watcom, but found the tools available for OS/2
at the time to be a bit more tricky to get working.
http://www.mozilla.org/ports/os2/gccsetup.html
Alternatively, Paul Smedley's ready-to-go GCC build environment has been known to
successfully build the game:
http://www.smedley.info/os2ports/index.php?page=build-environment
To build, you should, if your environment is set up well enough, be able to just
type `./configure' (or `sh configure' if you're using the OS/2 shell) and `make'.
You may have to manually specify `--os OS2' on the configure command line, as
configure cannot currently detect OS/2 manually.
A note on Open Watcom
---------------------
Open Watcom C/C++ was previously used to build OpenTTD (version 0.4.x and earlier).
However, due to advanced C++ features used in the YAPF portion of OpenTTD 0.5
in particular, the compiler is no longer able to build the game at the moment.
Hopefully one day Open Watcom will be able to catch up and we will be able to build
the game once again (it's easier than getting an OS/2 UNIX-like environment set up
in my opinion!), but until then, OpenTTD 0.5 and later can only be built with GCC.
Due to complexities in my set-up, I actually used the Win32 version
of Open Watcom to initially compile OpenTTD for OS/2. There should
be no reason of course why the OS/2 version cannot be used, and I
have subsequently built OpenTTD successfully this way.
Libraries Required
------------------
@@ -107,22 +89,42 @@ to an IDE project file and built a library. Do not use the makefiles
provided, they are not designed for Watcom (apart from SDL):
- zlib
http://www.zlib.org/
http://www.zlib.org/ - contains a makefile for OS/2, but is out
of date and uses EMX, ignore this
- libpng
http://www.libpng.org/
http://www.libpng.org/ - contains an EMX/gcc makefile, ignore this
- SDL for OS/2
ftp://ftp.netlabs.org/pub/sdl/sdl-1.2.7-src-20051222.zip used for
0.4.7
For 0.3.5, I used ftp://ftp.netlabs.org/pub/sdl/SDL-1.2.7-src-20040908a.zip -
take SDL.dll and SDL.lib from the src/ directory. Note that 20041222 is
out now, which is recommended for stability updates.
- Freetype
http://freetype.sourceforge.net/
If you do not wish to build the libraries yourself, pre-built versions
can be downloaded from the Files section at
http://sourceforge.net/projects/openttd/ - see "os2-useful.zip".
Currently, there are no pre-built libraries available for GCC. If you manage to get
OpenTTD working on Watcom though (do let us know if this is the case!), pre-built
versions can be downloaded from the Files section at
http://sourceforge.net/projects/openttd/ - see "os2-useful-v1.1.zip".
A Note About Subversion Revision Numbers
----------------------------------------
The project file uses a bit of a hack to find out the SVN revision number and
create an appropriate rev.c file. You'll need the SVN tools in your path
(specifically, "svnversion"). If "svnversion" can't be found, a generic rev.c
with the revision set to "norev000" will be created. To specifically force a
version number, set the environment variable "RELEASE" to the number (eg, "0.3.6")
-before- starting the Open Watcom IDE (which must be launched from the same shell
session). Also, beware, as you WILL cause incompatibilities if you try to
play a multiplayer game with a different version.
Compiling
---------
To compile, open the os/os2/openttd.wpj file in the IDE and first build
the strgen.exe target. This will build the .lng file generator, and will
also attempt to build all the language files (plus the table\strings.h
file which is required for openttd.exe to be built). Once strgen.exe and
the language files are built successfully, you can build the openttd.exe
target.
Contact Information
-------------------
@@ -131,6 +133,4 @@ If you have any questions regarding OS/2 issues, please contact me
(owen@owenrudge.net) and I'll try to help you out. For general OpenTTD
issues, see the Contacting section of readme.txt.
Thanks to Paul Smedley for his help with getting OpenTTD to compile under GCC on OS/2.
- Owen Rudge, 24th June 2007
- Owen Rudge

View File

@@ -1,108 +0,0 @@
Compiling OpenTTD using Microsoft Visual C++
December 28, 2006
--------------------------------------------
PLEASE READ THE ENTIRE DOCUMENT BEFORE DOING ANY ACTUAL CHANGES!!
SUPPORTED MSVC COMPILERS
------------------------
OpenTTD includes projects for MSVC 2003.NET and MSVC 2005.NET. Both will
compile out of the box, providing you have the required libraries/headers;
which ones, see below. There is no support for VS6, you are therefore
strongly encouraged to either upgrade to MSVC 2005 Express (free) or use GCC.
MSVC 2002 probably works as well, but it has not been tested.
1) REQUIRED FILES
-----------------
You might already have some of the files already installed, so check before
downloading; mostly because the DirectX SDK and Platform SDK are about
500MB each.
Download the following files:
* openttd-useful.zip (http://sf.net/project/showfiles.php?group_id=103924&package_id=114307)
* DirectX 8.1 SDK (http://neuron.tuke.sk/~mizanin/eng/Dx81sdk-include-lib.rar) (or alternatively the latest DirectX SDK from Microsoft)
* MS Windows Platform SDK (http://www.microsoft.com/downloads/details.aspx?FamilyId=A55B6B43-E24F-4EA3-A93E-40C0EC4F68E5&displaylang=en)
* afxres.h (http://www-d0.fnal.gov/d0dist/dist/packages/d0ve/devel/windows/AFXRES.H)
...and of course the newest source from svn://svn.openttd.org/trunk
You need an SVN-client to download the source from subversion:
* CLI Subversion (http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91)
* GUI TortoiseSVN (http://tortoisesvn.tigris.org/download.html)
2) INCLUDES AND LIBRARIES
-------------------------
Put the newly downloaded files in the VC lib\ and include\ directories; where
"C:\Program Files\Microsoft Visual Studio 8\VC" is your location of Visual C.
If you are compiling for an x64 system, use the include\ and lib\ directories
from the win64/ folder.
* openttd-useful.zip\include\*
* afxresh.h
to > C:\Program Files\Microsoft Visual Studio 8\VC\Include
* openttd-useful.zip\lib\*
to > C:\Program Files\Microsoft Visual Studio 8\VC\Lib
Custom directories might be recommended, check 2.2)
2.1) INCLUDES AND LIBRARIES - DIRECTX/PLATFORM SDK
--------------------------------------------------
Basically the same procedure as with the useful zip file, providing
you are not using the Microsoft installer. Put the include files in the
include\ directory and the library files to the Lib\ directory.
It is recommended to use custom directories so you don't overwrite any
default header or library files.
2.2) CUSTOM DIRECTORIES
-----------------------
If you have put the above include and/or library files into custom folders,
MSVC will not find them by default. You need to add these paths to VC through:
Tools > Options > Projects and Solutions > VC++ Directories > show directories for
* Include files: Add the DirectX/Platform SDK include dir you've created
* Library files: Add the path to the SDK custom lib dir
NOTE: make sure that the directory for the DirectX SDK is the first one in the
list, above all others, otherwise compilation will most likely fail!!
3) TTD GRAPHICS FILES
---------------------
Copy the following files from Transport Tycoon Deluxe to the data folder
* sample.cat
* trg1r.grf
* trgcr.grf
* trghr.grf
* trgir.grf
* trgtr.grf
4) COMPILING
------------
Open trunk/openttd[_vs80].sln
Set the build mode to 'Release' in
Build > Configuration manager > Active solution configuration > select "Release"
Compile...
If everything works well the binary should be in trunk/Release/openttd.exe
5) EDITING, CHANGING SOURCE CODE
--------------------------------
Set the build mode (back to) 'Debug'
Change the startup project to openttd by right-clicking the 'openttd' project
in the Solution Explorer and selecting 'Set as Startup Project'. The 'openttd'
project should now show up bold instead of 'strgen'.
6) PROBLEMS?
------------
If compilation fails, double-check that you are using the latest SVN (!)
source. If it still doesn't work, check in on IRC (irc://irc.oftc.net/openttd),
to ask about reasons; or just wait. The problem will most likely solve itself
within a few days as the problem is noticed and fixed.
An up-to-date version of this README can be found on the wiki:
http://wiki.openttd.org/index.php/MicrosoftVisualCExpress

View File

@@ -0,0 +1,105 @@
Compiling OpenTTD using Microsoft Visual C++ 6.0
---Step 1
Download the following files:
* Useful.zip (http://sourceforge.net/project/showfiles.php?group_id=103924&package_id=114307&release_id=228633)
* SDL-1.2.8-VC6.zip (http://www.libsdl.org/release/SDL-devel-1.2.8-VC6.zip)
* DirectX7.0 SDK (http://www.tt-forums.net/download.php?id=15989) (or alternatively the latest DirectX SDK from Microsoft)
* afxres.h (http://www-d0.fnal.gov/d0dist/dist/packages/d0ve/devel/windows/AFXRES.H)
...and of course the newest source from svn://svn.openttd.com/trunk
(The alpha version of the new map array can be found at svn://svn.openttd.com/branch/map)
You have to have and SVN-client to download the source:
* Command line version (http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91)
* TortoiseSVN (http://tortoisesvn.tigris.org/download.html)
---Step 2
Put the newly downloaded files in the VC lib and include directories (Where C:\program files\ is your local location of VC)
* zconf.h [useful.zip]
* zlib.h [useful.zip]
* png.h [useful.zip]
* pngconf.h [useful.zip]
* afxres.h
in
C:\Program Files\Microsoft Visual Studio\VC98\Include
and
* zlibstat.lib [useful.zip]
* SDL.lib [SDL.zip]
* libpng.lib [useful.zip]
in
C:\Program Files\Microsoft Visual Studio\VC98\Lib
---Step 3: DirectX SDK
(This should work with the latest DirectX SDK as well.) The installation with DirectX 7 was odd, so you'd better use the version available via the forum, see also the download link on top.
There are 2 folder in the compressed file: Include and Lib
Copy all files from Include folder to
C:\Program Files\Microsoft Visual Studio\VC98\Include
and all files from Lib folder to
C:\Program Files\Microsoft Visual Studio\VC98\Lib
You can also make custom directories, for libraries (.lib) and includes/header files (.h) and add it to the VC paths via:
Tools -> Options -> Directories -> show directories for:
a) include files (the include dir: C:\Program Files\Microsoft Visual Studio\VC98\DirectX 7 SDK\include )
b) library files (the lib dir, C:\Program Files\Microsoft Visual Studio\VC98\DirectX 7 SDK\lib )
---Step 4
Copy the following files from Transport Tycoon Deluxe to the data folder
* sample.cat
* trg1r.grf
* trgcr.grf
* trghr.grf
* trgir.grf
* trgtr.grf
---Step 5
Open trunk/ttd.dsw
Build menu > Set active configuration > Select: "ttd - Win32 Release with PNG"
Compile...
Now it should work, it worked for me :)
From r1319 you can compile branch/map in Debug mode (by Bociusz)
If it's not working, and you checked that you using the newest SVN (!) report to Bociusz on IRC (irc://irc.freenode.net/#openttd)
Go ahead and make that patch! Happy Hacking! :)
Originally written by Dribbel
Project file updating by Bociusz

58
docs/console.txt Normal file
View File

@@ -0,0 +1,58 @@
OPENTTD INGAME CONSOLE DOCUMENTATION
====================================
http://wiki.openttd.org/index.php/OpenTTDDevBlackBook
for detailed information
*** WARNING **
This document is out of date
*** WARNING **
HOTKEY: BACKQUOTE (aka tilde, the key left to "1")
COMMANDS:
---------
echo [string]
echoc [color-code] [string]
exit
debug_level [0-9]
dump_vars [filter]
help
list_cmds [filter]
list_vars [filter]
printf [formatstring] [var] [var] [var]....
printfc [color-code] [formatstring] [var] [var] [var]....
quit
random
screenshot ["big"/"no_con"]
VARIABLES:
----------
*con_developer
-> true = console debugging info
-> false = no output
*developer
-> 0 = no output
-> 1 = console error output [like command not found]
-> 2 = console error and debug output
*cursor_rate
-> 1-12 = defines the cursor blink interval
VARIABLE HANDLING:
------------------
developer = 0
developer ++
temp_string = test
temp_string = "my little"
printf "%s world" temp_string
---------------------------------------------------
feel free to add more commands and use this in-game
console for your debugging / enhancements

20
docs/directmusic.txt Normal file
View File

@@ -0,0 +1,20 @@
Notes about DirectMusic driver for Win32
----------------------------------------
If compiling under MinGW32, you require the DirectX 7.0 files for MinGW32, available from
http://alleg.sourceforge.net/files/dx70_mgw.zip.
If compiling under MSVC 6.0, you require the equivalent for MSVC, available from
http://alleg.sourceforge.net/files/dx70_min.zip. MSVC 7.0/7.1 include header files that
are recent enough.
If you do not want to compile the DirectMusic driver, undefine WIN32_ENABLE_DIRECTMUSIC_SUPPORT
in stdafx.h.
Bugs, etc
---------
- The volume control doesn't work properly. I'll fix this soon.
Owen Rudge
14th March 2004

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

View File

@@ -11,17 +11,7 @@
<h3><a name="Landscape">Landscape</a></h3>
<p>
Five attributes hold the information about a tile.
These attributes are referred to as
"<span style="font-weight: bold;">type_height</span>",
"<span style="font-weight: bold;">m1</span>",
"<span style="font-weight: bold;">m2</span>",
"<span style="font-weight: bold;">m3</span>",
"<span style="font-weight: bold;">m4</span>" and
"<span style="font-weight: bold;">m5</span>".
The most important value is the class of a tile, stored in the upper 4 bits of the type_height array.
The lower 4 bits are used to encode the height and slope data.
For a graphical represenation of the tile-layout have a look at <a href="landscape_grid.html">Landscape grid</a> page.
Five arrays are used to encode the information of the contents of each tile. These arrays are referred to as "<span style="font-weight: bold;">map_owner</span>", "<span style="font-weight: bold;">map2</span>", "<span style="font-weight: bold;">map3_lo|_hi</span>", "<span style="font-weight: bold;">map_type_and_height</span>" and "<span style="font-weight: bold;">map5</span>". The known encodings are listed in the table below. The most important value is the class of a tile, stored in the upper 4 bits of the type_and_height array. The lower 4 bits are used to encode the height and slope data. For a graphical represenation of the tile-layout have a look at <a href="landscape_grid.html">Landscape grid</a> page.
</p>
<p>
OTTD's class-specific periodic tile processing routine is called once every +256 ticks for each tile.
@@ -32,7 +22,7 @@ OTTD's class-specific periodic tile processing routine is called once every +256
<tr><td valign=top nowrap><a name="Class0"><tt> 0 </tt></a></td><td>
<ul>
<li>m5 bits 4..0: tile type:
<li>map5 bits 4..0: tile type:
<table>
<tr><td nowrap valign=top><tt>00</tt>&nbsp; </td><td align=left>bare land</td></tr>
<tr><td nowrap valign=top><tt>01</tt>&nbsp; </td><td align=left>1/3 grass</td></tr>
@@ -40,9 +30,7 @@ OTTD's class-specific periodic tile processing routine is called once every +256
<tr><td nowrap valign=top><tt>03</tt>&nbsp; </td><td align=left>full grass</td></tr>
<tr><td nowrap valign=top><tt>07</tt>&nbsp; </td><td align=left>rough land</td></tr>
<tr><td nowrap valign=top><tt>0B</tt>&nbsp; </td><td align=left>rocks</td></tr>
<tr><td nowrap valign=top><tt>0F</tt>&nbsp; </td><td align=left>fields; type of fields in m3 bits 3..0 (legal values: 0 through 9)<br>
m2: Index into the array of industries (farms), INVALID_INDUSTRY (0xFFFF) if farm has been removed </td>
</tr>
<tr><td nowrap valign=top><tt>0F</tt>&nbsp; </td><td align=left>fields; type of fields in map3_lo bits 3..0 (legal values: 0 through 9)</td></tr>
<tr><td nowrap valign=top><tt>10</tt>&nbsp; </td><td align=left>1/4 snow</td></tr>
<tr><td nowrap valign=top><tt>11</tt>&nbsp; </td><td align=left>2/4 snow</td></tr>
<tr><td nowrap valign=top><tt>12</tt>&nbsp; </td><td align=left>3/4 snow</td></tr>
@@ -51,20 +39,20 @@ OTTD's class-specific periodic tile processing routine is called once every +256
<tr><td nowrap valign=top><tt>17</tt>&nbsp; </td><td align=left>full desert</td></tr>
</table>
</li>
<li>m5 bits 7..5: update counter, incremented on every periodic processing for tile types other than <tt>03</tt>, <tt>07</tt>, <tt>0B</tt> and <tt>10</tt> and above, on wraparound the tile is updated (for fields, the type of fields in m3 is increased, for other types the tile type in m5 is increased)
<li>map5 bits 7..6: update counter, incremented on every periodic processing for tile types other than <tt>03</tt>, <tt>07</tt>, <tt>0B</tt> and <tt>10</tt> and above, on wraparound the tile is updated (for fields, the type of fields in map3_lo is increased, for other types the tile type in map5 is increased)
<br>(for snow and desert, these bits are not used, tile is updated on every periodic processing)
</li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the tile (normally <tt>10</tt>)
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the tile (normally <tt>10</tt>)
</li>
<li>m4 bits 7..5: type of hedge on the SW border of the tile (1 through 6, or 0=none); bits 4..2: same for the SE border
<li>map3_hi bits 7..5: type of hedge on the SW border of the tile (1 through 6, or 0=none); bits 4..2: same for the SE border
</li>
</ul>
</td></tr>
<tr><td valign=top nowrap><a name="Class1"><tt> 1 </tt></a></td><td>
m5 bit 7 clear: railway track
map5 bit 7 clear: railway track
<ul>
<li>m5 bits 0..5: track layout: bit set = track present:
<li>map5 bits 0..5: track layout: bit set = track present:
<table>
<tr><td nowrap valign=top>bit 0: </td><td align=left>in the X direction</td></tr>
<tr><td nowrap valign=top>bit 1: </td><td align=left>in the Y direction</td></tr>
@@ -73,9 +61,9 @@ m5 bit 7 clear: railway track
<tr><td nowrap valign=top>bit 4: </td><td align=left>in the west corner (direction N-S)</td></tr>
<tr><td nowrap valign=top>bit 5: </td><td align=left>in the east corner (direction N-S)</td></tr>
</table></li>
<li>m5 bit 6 set = with signals:
<li>map5 bit 6 set = with signals:
<ul>
<li>m3 bits 7..4: bit set = signal present:
<li>map3_lo bits 7..4: bit set = signal present:
<ul>
<li>For track in the X direction:
<table>
@@ -102,8 +90,8 @@ m5 bit 7 clear: railway track
<tr><td nowrap valign=top>bit 7: </td><td align=left>signal in the N direction on the track in the W corner</td></tr>
</table></li>
</ul></li>
<li>m2 bits 7..4: bit clear = signal shows red; same bits as in m3</li>
<li>OpenTTD bits in m4:
<li>map2 bits 7..4: bit clear = signal shows red; same bits as in map3_lo</li>
<li>OpenTTD bits in map3_hi:
<table>
<tr><td nowrap valign=top>bits 1..0: </td><td align=left>type of signal:</td></tr>
<tr><td nowrap valign=top><tt>00</tt>: </td><td align=left>normal signals</td></tr>
@@ -113,9 +101,9 @@ m5 bit 7 clear: railway track
<tr><td nowrap valign=top>bit 2: </td><td align=left>set = semaphore signals, clear = light signals</td></tr>
</table></li>
</ul></li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the track
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the track
</li>
<li>m2 bits 0..3:
<li>map2 bits 0..3:
<table>
<tr><td nowrap valign=top><tt>0</tt>&nbsp; </td><td align=left>on bare land</td></tr>
<tr><td nowrap valign=top><tt>1</tt>&nbsp; </td><td align=left>on grass, no fences</td></tr>
@@ -131,63 +119,64 @@ m5 bit 7 clear: railway track
<tr><td nowrap valign=top><tt>B</tt>&nbsp; </td><td align=left>fence on the N side (track in the S corner)</td></tr>
<tr><td nowrap valign=top><tt>C</tt>&nbsp; </td><td align=left>on snow or desert</td></tr>
</table></li>
<li>m3 bits 0..3 = <a name="TrackType">track type</a>: <tt>0</tt> - conventional railway, <tt>1</tt> - electrified railway, <tt>2</tt> - monorail, <tt>3</tt> - maglev
<li>map3_lo bits 0..3 = <a name="TrackType">track type</a>: <tt>0</tt> - conventional railway, <tt>1</tt> - monorail, <tt>2</tt> - maglev
</li>
</ul>
m5 bits 7 and 6 set: railway depot / checkpoints
map5 bits 7 and 6 set: railway depot / checkpoints
<ul>
<li>m5 value C0..C3: railway depot
<br>m5 bits 1..0 - direction: exit towards: <tt>00</tt> = NE, <tt>01</tt> = SE, <tt>02</tt> = SW, <tt>03</tt> = NW</li>
<li>m5 value C4..C5: checkpoint
<li>map5 value C0..C3: railway depot
<br>map5 bits 1..0 - direction: exit towards: <tt>00</tt> = NE, <tt>01</tt> = SE, <tt>02</tt> = SW, <tt>03</tt> = NW</li>
<li>map5 value C4..C5: checkpoint
<br>bit 0: clear = in X direction, set = in Y direction
<br>
<br>
<li>m1: <a href="#OwnershipInfo">owner</a> of the depot / checkpoint</li>
<li>m2: For waypoints, index into the array of waypoints.</li>
<li>m3 bits 0..3 = <a href="#TrackType">track type</a></li>
<li>m4 bits 0..3 = ground type, as per m2 bits 0..3 for railway tiles.</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the depot / checkpoint</li>
<li>map3_lo bits 0..3 = <a href="#TrackType">track type</a></li>
<li>map3_lo bit 4 = use custom sprite (valid only for the checkpoint)</li>
<li>map3_hi = custom station id</li>
</ul>
</td></tr>
<tr><td valign=top nowrap><a name="Class2"><tt> 2 </tt></a></td><td>
m5 bits 7..4 clear: road
map5 bits 7..4 clear: road
<ul>
<li>m5 bits 3..0: road layout: bit set = road piece present:
<li>map5 bits 3..0: road layout: bit set = road piece present:
<table>
<tr><td nowrap valign=top>bit 0: </td><td align=left>NW piece</td></tr>
<tr><td nowrap valign=top>bit 1: </td><td align=left>SW piece</td></tr>
<tr><td nowrap valign=top>bit 2: </td><td align=left>SE piece</td></tr>
<tr><td nowrap valign=top>bit 3: </td><td align=left>NE piece</td></tr>
</table></li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the road</li>
<li>m2: Index into the array of towns, 0 for non-town roads</li>
<li>m4 bits 0..3: counter for the roadworks</li>
<li>m4 bits 4..6: <tt>0</tt> - on bare land, <tt>1</tt> - on grass, <tt>2</tt> - paved, <tt>3</tt> - with streetlights, <tt>5</tt> - tree-lined, <tt>6</tt> - on grass with road works, <tt>7</tt> - paved with road works</li>
<li>m4 bit 7 set = on snow or desert</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the road</li>
<li>map2: Index into the array of towns, 0 for non-town roads</li>
<li>map3_hi bits 0..3: counter for the roadworks</li>
<li>map3_hi bits 4..6: <tt>0</tt> - on bare land, <tt>1</tt> - on grass, <tt>2</tt> - paved, <tt>3</tt> - with streetlights, <tt>5</tt> - tree-lined, <tt>6</tt> - on grass with road works, <tt>7</tt> - paved with road works</li>
<li>map3_hi bit 7 set = on snow or desert</li>
</ul>
m5 bit 4 set, bits 7..5 clear: level crossing
map5 bit 4 set, bits 7..5 clear: level crossing
<ul>
<li>m5 bit 3: clear - road in the X direction, set - road in the Y direction (railway track always perpendicular)</li>
<li>m5 bit 2: set if crossing lights are on</li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the railway track</li>
<li>m2: Index into the array of towns, 0 for non-town roads</li>
<li>m3 bits 0..7: <a href="#OwnershipInfo">owner</a> of the road</li>
<li>m4 bits 3..0: <a href="#TrackType">track type</a></li>
<li>m4 bits 4..6: <tt>0</tt> - on bare land, <tt>1</tt> - on grass, <tt>2</tt> or higher - paved</li>
<li>m4 bit 7 set = on snow or desert</li>
<li>map5 bit 3: clear - road in the X direction, set - road in the Y direction (railway track always perpendicular)</li>
<li>map5 bit 2: set if crossing lights are on</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the railway track</li>
<li>map2: Index into the array of towns, 0 for non-town roads</li>
<li>map3_lo bits 0..7: <a href="#OwnershipInfo">owner</a> of the road</li>
<li>map3_hi bits 3..0: <a href="#TrackType">track type</a></li>
<li>map3_hi bits 4..6: <tt>0</tt> - on bare land, <tt>1</tt> - on grass, <tt>2</tt> or higher - paved</li>
<li>map3_hi bit 7 set = on snow or desert</li>
</ul>
m5 bit 5 set: road depot
map5 bit 5 set: road depot
<ul>
<li>m5 bits 3..0 - direction: exit towards: <tt>0</tt> = NE, <tt>1</tt> = SE, <tt>2</tt> = SW, <tt>3</tt> = NW</li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the depot</li>
<li>m4 bit 7 set = on snow or desert (not displayed, but set internally)</li>
<li>map5 bits 3..0 - direction: exit towards: <tt>0</tt> = NE, <tt>1</tt> = SE, <tt>2</tt> = SW, <tt>3</tt> = NW</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the depot</li>
<li>map3_hi bit 7 set = on snow or desert (not displayed, but set internally)</li>
</ul>
</td></tr>
<tr><td valign=top nowrap><a name="Class3"><tt> 3 </tt></a></td><td>
Town building
<ul>
<li>m2: Index into the array of towns</li>
<li>m4: <a name="HouseTypes">town building type</a>:
<li>map2: Index into the array of towns</li>
<li>map3_hi: <a name="HouseTypes">town building type</a>:
<p><small>Note: In the climate list, 'sub-arctic' means below the <a href="#_snowline">snow line</a>, and 'snow' means above the snow line in the sub-arctic climate.</small></p>
<table>
<tr><th align=left>Type&nbsp;</th><th align=left>Size&nbsp;</th><th align=left>Climates&nbsp;</th><th align=left>Description</th></tr>
@@ -277,13 +266,13 @@ Town building
<tr><td nowrap valign=top><tt>6D</tt>&nbsp; </td><td>1&times;1</td><td>toyland</td><td align=left>piggy-bank</td></tr>
<tr><td colspan=2></td></tr> <!-- spacer -- -- (and I don't mean a walk) -->
</table></li>
<li>m3 bits 7..6: stage of construction (<tt>3</tt> = completed)</li>
<li>m5 bits 2..0: construction counter, for buildings under construction incremented on every periodic tile processing, on wraparound the stage of construction in m3 is increased</li>
<li>map3_lo bits 7..6: stage of construction (<tt>3</tt> = completed)</li>
<li>map5 bits 2..0: construction counter, for buildings under construction incremented on every periodic tile processing, on wraparound the stage of construction in map3_lo is increased</li>
<li>for large office blocks (types <tt>04</tt> and <tt>05</tt>):
<ul>
<li>m1 bits 6..0: position of the lift</li>
<li>m1 bit 7: if set the lift is moving</li>
<li>m5 bit 7: if set then m5 bits 5..0 hold the destination floor of the lift, which could be 0..6, except 1, so the building has 6 effective floors. This due to the fact that the first floor is 2 'normal' floors high. One 'normal' floor has a height of 6 lift positions.</li>
<li>map_owner bits 6..0: position of the lift</li>
<li>map_owner bit 7: if set the lift is moving</li>
<li>map5 bit 7: if set then map5 bits 5..0 hold the final position of the lift divided by 6 (valid values 0..6 except 1)</li>
</ul></li>
</ul>
</td></tr>
@@ -291,9 +280,9 @@ Town building
<tr><td valign=top nowrap><a name="Class4"><tt> 4 </tt></a></td><td>
Trees
<ul>
<li>m5 bits 7..6: number of trees minus one</li>
<li>m5 bits 2..0: growth status: <tt>0</tt>..<tt>2</tt> - one of trees is growing, <tt>3</tt> - all trees are fully grown, <tt>4</tt>..<tt>6</tt> - one of trees is withering</li>
<li>m3 bits 7..0: type of trees:
<li>map5 bits 7..6: number of trees minus one</li>
<li>map5 bits 2..0: growth status: <tt>0</tt>..<tt>2</tt> - one of trees is growing, <tt>3</tt> - all trees are fully grown, <tt>4</tt>..<tt>6</tt> - one of trees is withering</li>
<li>map3_lo bits 7..0: type of trees:
<table>
<tr><td nowrap valign=top><tt>00</tt>..<tt>0B</tt>&nbsp; </td><td align=left>temperate climate trees</td></tr>
<tr><td nowrap valign=top><tt>0C</tt>..<tt>13</tt>&nbsp; </td><td align=left>sub-arctic climate trees</td></tr>
@@ -304,24 +293,24 @@ Trees
</table>
(note: the actually displayed set of trees depends on both type and number of trees)
</li>
<li>m4 bits 7..5: type of hedge on the SW border of the tile (1 through 6, or 0=none)</li>
<li>m4 bits 4..2: type of hedge on the SE border of the tile (1 through 6, or 0=none)</li>
<li>m2 bits 5..4:
<li>map3_hi bits 7..5: type of hedge on the SW border of the tile (1 through 6, or 0=none)</li>
<li>map3_hi bits 4..2: type of hedge on the SE border of the tile (1 through 6, or 0=none)</li>
<li>map2 bits 5..4:
<table>
<tr><td nowrap valign=top><tt>0</tt>&nbsp; </td><td align=left>on grass</td></tr>
<tr><td nowrap valign=top><tt>1</tt>&nbsp; </td><td align=left>on rough land</td></tr>
<tr><td nowrap valign=top><tt>2</tt>&nbsp; </td><td align=left>on snow or desert; m2 bits 7..6 - amount of snow or desert (for desert always set to 3 in TTD)
<tr><td nowrap valign=top><tt>2</tt>&nbsp; </td><td align=left>on snow or desert; map2 bits 7..6 - amount of snow or desert (for desert always set to 3 in TTD)
</td></tr>
</table></li>
<li>m2 bits 3..0: update counter, incremented on every periodic processing, on wraparound the growth status is updated (or, if it's <tt>3</tt>, a random action is taken)</li>
<li>m1: <a href="#OwnershipInfo">owner</a> (normally <tt>10</tt>)</li>
<li>map2 bits 3..0: update counter, incremented on every periodic processing, on wraparound the growth status is updated (or, if it's <tt>3</tt>, a random action is taken)</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> (normally <tt>10</tt>)</li>
</ul>
</td></tr>
<tr><td valign=top nowrap><a name="Class5"><tt> 5 </tt></a></td><td>
Station tile
<ul>
<li>m5: tile type:
<li>map5: tile type:
<table>
<tr><td nowrap valign=top><tt>00</tt>..<tt>07</tt>&nbsp; </td><td align=left>railway station
<br><tt>00</tt>..<tt>01</tt> - open platform, <tt>02</tt>..<tt>03</tt> - open platform with station building, <tt>04</tt>....<tt>07</tt> - roofed platform
@@ -379,17 +368,17 @@ exit towards: <tt>47</tt> - NE, <tt>48</tt> - SE, <tt>49</tt> - SW, <tt>4A</tt>
<tr><td colspan=2></td></tr> <!-- spacer -->
</table>
</li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the station</li>
<li>m2: index into the <a href="#_StationArray">array of stations</a></li>
<li>m3 bits 0..3: <a href="#TrackType">track type</a> for railway stations, must be 0 for all the other stations</li>
<li>m3 bits 4..7: persistent random data for newstations</li>
<li>m4 = custom station id; 0 means standard graphics</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the station</li>
<li>map2: index into the <a href="#_StationArray">array of stations</a></li>
<li>map3_lo bits 0..3: <a href="#TrackType">track type</a> for railway stations, must be 0 for all the other stations</li>
<li>map3_lo bit 4 = use custom sprite (valid only railway stations FOR NOW)</li>
<li>map3_hi = custom station id</li>
</ul>
</td></tr>
<tr><td valign=top nowrap><a name="Class6"><tt> 6 </tt></a></td><td>
<ul>
<li>m5: tile type:
<li>map5: tile type:
<table>
<tr><td nowrap valign=top><tt>00</tt>&nbsp; </td><td align=left>water</td></tr>
<tr><td nowrap valign=top><tt>01</tt>&nbsp; </td><td align=left>coast or riverbank</td></tr>
@@ -420,7 +409,7 @@ exit towards: <tt>47</tt> - NE, <tt>48</tt> - SE, <tt>49</tt> - SW, <tt>4A</tt>
</table>
</td></tr>
</table></li>
<li>m1: <a href="#OwnershipInfo">owner</a> (for water and coasts normally <tt>11</tt>)</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> (for water and coasts normally <tt>11</tt>)</li>
</ul>
</td></tr>
@@ -434,19 +423,19 @@ Tiles of this class form an invisible, one tile wide border at the south (bottom
<tr><td valign=top nowrap><a name="Class8"><tt> 8 </tt></a></td><td>
Industry tile
<ul>
<li>m5: type:
<li>map5: type:
<br><small>(note: this is not the same as the <a href="#industry.type">industry type</a> stored in the <a href="#_IndustryArray">array of industries</a>)</small>
<table>
<tr><td nowrap valign=top><tt>00</tt>..<tt>06</tt>&nbsp; </td><td align=left>coal mine
<table>
<tr><td nowrap valign=top><tt>00</tt>&nbsp; </td><td align=left>wheel tower when not animated</td></tr>
<tr><td nowrap valign=top><tt>01</tt>&nbsp; </td><td align=left>wheel tower when animated; animation state in m1 bits 5..0; m1 bit 6 set = sound already generated</td></tr>
<tr><td nowrap valign=top><tt>01</tt>&nbsp; </td><td align=left>wheel tower when animated; animation state in map_owner bits 5..0; map_owner bit 6 set = sound already generated</td></tr>
</table>
</td></tr>
<tr><td nowrap valign=top><tt>07</tt>..<tt>0A</tt>&nbsp; </td><td align=left>power station
<table>
<tr><td nowrap valign=top><tt>08</tt>&nbsp; </td><td align=left>chimney</td></tr>
<tr><td nowrap valign=top><tt>0A</tt>&nbsp; </td><td align=left>transformer; animation progress in m1 bits 5..2 (valid range <tt>0</tt>..<tt>7</tt>)</td></tr>
<tr><td nowrap valign=top><tt>0A</tt>&nbsp; </td><td align=left>transformer; animation progress in map_owner bits 5..2 (valid range <tt>0</tt>..<tt>7</tt>)</td></tr>
</table>
</td></tr>
<tr><td nowrap valign=top><tt>0B</tt>..<tt>0F</tt>&nbsp; </td><td align=left>sawmill</td></tr>
@@ -460,7 +449,7 @@ Industry tile
<tr><td nowrap valign=top><tt>1D</tt>..<tt>20</tt>&nbsp; </td><td align=left>oil wells
<table>
<tr><td nowrap valign=top><tt>1D</tt>&nbsp; </td><td align=left>not animated</td></tr>
<tr><td nowrap valign=top><tt>1E</tt>..<tt>20</tt>&nbsp; </td><td align=left>various stages of animation; progress of animation in m1 bits 1..0</td></tr>
<tr><td nowrap valign=top><tt>1E</tt>..<tt>20</tt>&nbsp; </td><td align=left>various stages of animation; progress of animation in map_owner bits 1..0</td></tr>
</table>
</td></tr>
<tr><td nowrap valign=top><tt>21</tt>..<tt>26</tt>&nbsp; </td><td align=left>farm</td></tr>
@@ -469,7 +458,7 @@ Industry tile
<tr><td nowrap valign=top><tt>2F</tt>..<tt>33</tt>&nbsp; </td><td align=left>copper ore mine
<table>
<tr><td nowrap valign=top><tt>2F</tt>&nbsp; </td><td align=left>wheel tower when not animated</td></tr>
<tr><td nowrap valign=top><tt>30</tt>&nbsp; </td><td align=left>wheel tower when animated; animation state in m1 bits 5..0; m1 bit 6 set = sound already generated</td></tr>
<tr><td nowrap valign=top><tt>30</tt>&nbsp; </td><td align=left>wheel tower when animated; animation state in map_owner bits 5..0; map_owner bit 6 set = sound already generated</td></tr>
<tr><td nowrap valign=top><tt>31</tt>&nbsp; </td><td align=left>chimney</td></tr>
</table>
</td></tr>
@@ -480,7 +469,7 @@ Industry tile
<tr><td nowrap valign=top><tt>48</tt>..<tt>58</tt>&nbsp; </td><td align=left>gold mine
<table>
<tr><td nowrap valign=top><tt>4F</tt>&nbsp; </td><td align=left>wheel tower when not animated</td></tr>
<tr><td nowrap valign=top><tt>58</tt>&nbsp; </td><td align=left>wheel tower when animated; animation state in m1 bits 5..0; m1 bit 6 set = sound already generated</td></tr>
<tr><td nowrap valign=top><tt>58</tt>&nbsp; </td><td align=left>wheel tower when animated; animation state in map_owner bits 5..0; map_owner bit 6 set = sound already generated</td></tr>
</table>
</td></tr>
<tr><td nowrap valign=top><tt>59</tt>..<tt>5A</tt>&nbsp; </td><td align=left>bank (sub-arctic or sub-tropical climate)</td></tr>
@@ -507,9 +496,9 @@ Industry tile
<tr><td nowrap valign=top><tt>8A</tt>..<tt>8D</tt>&nbsp; </td><td align=left>toy shop</td></tr>
<tr><td nowrap valign=top><tt>8E</tt>..<tt>93</tt>&nbsp; </td><td align=left>toy factory
<table>
<tr><td nowrap valign=top><tt>8F</tt>&nbsp; </td><td align=left>animated part; animation state in m3 (valid range <tt>00</tt>..<tt>31</tt>)<br>
tile animation is started (m4 zeroed) on the periodic processing if <a href="#industry.didtransform">field <tt>2C</tt></a> in the corresponding industry array entry is nonzero<br>
while the animation is in progress (see the <a href="#_AnimatedTilesList">array at <tt>04328</tt></a>) m4 holds the number of animation cycles that have already taken place; when this number reaches 8 the animation is stopped</td></tr>
<tr><td nowrap valign=top><tt>8F</tt>&nbsp; </td><td align=left>animated part; animation state in map3_lo (valid range <tt>00</tt>..<tt>31</tt>)<br>
tile animation is started (map3_hi zeroed) on the periodic processing if <a href="#industry.didtransform">field <tt>2C</tt></a> in the corresponding industry array entry is nonzero<br>
while the animation is in progress (see the <a href="#_AnimatedTilesList">array at <tt>04328</tt></a>) map3_hi holds the number of animation cycles that have already taken place; when this number reaches 8 the animation is stopped</td></tr>
</table>
</td></tr>
<tr><td nowrap valign=top><tt>94</tt>..<tt>9B</tt>&nbsp; </td><td align=left>plastic fountains (various stages of cyclic animation)</td></tr>
@@ -517,69 +506,69 @@ while the animation is in progress (see the <a href="#_AnimatedTilesList">array
<tr><td nowrap valign=top><tt>A0</tt>..<tt>A3</tt>&nbsp; </td><td align=left>bubble generator
<table>
<tr><td nowrap valign=top><tt>A1</tt>&nbsp; </td><td align=left>generators</td></tr>
<tr><td nowrap valign=top><tt>A2</tt>&nbsp; </td><td align=left>bubble capture facility; animation state in m3 (valid range <tt>00</tt>..<tt>27</tt>)</td></tr>
<tr><td nowrap valign=top><tt>A2</tt>&nbsp; </td><td align=left>bubble capture facility; animation state in map3_lo (valid range <tt>00</tt>..<tt>27</tt>)</td></tr>
</table>
</td></tr>
<tr><td nowrap valign=top><tt>A4</tt>..<tt>A6</tt>&nbsp; </td><td align=left>toffee quarry
<table>
<tr><td nowrap valign=top><tt>A5</tt>&nbsp; </td><td align=left>animated part; animation state in m3 (valid range <tt>00</tt>..<tt>45</tt>)</td></tr>
<tr><td nowrap valign=top><tt>A5</tt>&nbsp; </td><td align=left>animated part; animation state in map3_lo (valid range <tt>00</tt>..<tt>45</tt>)</td></tr>
</table>
</td></tr>
<tr><td nowrap valign=top><tt>A7</tt>..<tt>AE</tt>&nbsp; </td><td align=left>sugar mine
<table>
<tr><td nowrap valign=top><tt>AE</tt>&nbsp; </td><td align=left>animated part; animation state in m3 (valid range <tt>00</tt>..<tt>5F</tt>)</td></tr>
<tr><td nowrap valign=top><tt>AE</tt>&nbsp; </td><td align=left>animated part; animation state in map3_lo (valid range <tt>00</tt>..<tt>5F</tt>)</td></tr>
</table>
</td></tr>
<tr><td colspan=2></td></tr> <!-- spacer -->
</table></li>
<li>m2: index into the <a href="#_IndustryArray">array of industries</a>
<li>map2: index into the <a href="#_IndustryArray">array of industries</a>
</li>
<li>m1 bit 7: clear = under construction
<li>map_owner bit 7: clear = under construction
<ul>
<li>m1 bits 4..2: construction counter, for buildings under construction incremented on every periodic tile processing
<li>map_owner bits 4..2: construction counter, for buildings under construction incremented on every periodic tile processing
</li>
</ul></li>
<li>m1 bits 1..0: stage of construction (<tt>3</tt> = completed), incremented when the construction counter wraps around
<li>map_owner bits 1..0: stage of construction (<tt>3</tt> = completed), incremented when the construction counter wraps around
<br>the meaning is different for some animated tiles which are never under construction (types <tt>01</tt>, <tt>1E</tt>..<tt>20</tt>, <tt>30</tt>, <tt>58</tt>; see above)
</li>
</ul>
</td></tr>
<tr><td valign=top nowrap><a name="Class9"><tt> 9 </tt></a></td><td>
m5 bits 7..4 clear: tunnel entrance/exit
map5 bits 7..4 clear: tunnel entrance/exit
<ul>
<li>m5 bits 3..2: <tt>0</tt> - railway tunnel, <tt>1</tt> - road tunnel</li>
<li>m5 bits 1..0 - direction: entrance towards: <tt>0</tt> = NE, <tt>1</tt> = SE, <tt>2</tt> = SW, <tt>3</tt> = NW</li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the tunnel</li>
<li>m3 bits 3..0 = <a href="#TrackType">track type</a> for railway tunnel, must be 0 for road tunnel</li>
<li>m4 bit 7 set = on snow or desert</li>
<li>map5 bits 3..2: <tt>0</tt> - railway tunnel, <tt>1</tt> - road tunnel</li>
<li>map5 bits 1..0 - direction: entrance towards: <tt>0</tt> = NE, <tt>1</tt> = SE, <tt>2</tt> = SW, <tt>3</tt> = NW</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the tunnel</li>
<li>map3_lo bits 3..0 = <a href="#TrackType">track type</a> for railway tunnel, must be 0 for road tunnel</li>
<li>map3_hi bit 7 set = on snow or desert</li>
</ul>
m5 bit 7 set: bridge
map5 bit 7 set: bridge
<ul><li>
m5 bit 6 clear: bridge ending
map5 bit 6 clear: bridge ending
<ul>
<li>m5 bit 5: clear - northern, set - southern ending</li>
<li>m3 bits 3..0 = <a href="#TrackType">type of track</a> on the bridge, must be 0 for road bridge</li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the bridge</li>
<li>map5 bit 5: clear - northern, set - southern ending</li>
<li>map3_lo bits 3..0 = <a href="#TrackType">type of track</a> on the bridge, must be 0 for road bridge</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the bridge</li>
</ul>
m5 bit 6 set: bridge middle part
map5 bit 6 set: bridge middle part
<ul>
<li>m5 bit 5 clear:
<li>map5 bit 5 clear:
<ul>
<li>m5 bits 4..3: land under bridge: <tt>0</tt> - grass, snow or desert, <tt>1</tt> - water</li>
<li>map5 bits 4..3: land under bridge: <tt>0</tt> - grass, snow or desert, <tt>1</tt> - water</li>
</ul>
m5 bit 5 set:
map5 bit 5 set:
<ul>
<li>m5 bits 4..3: transport route under bridge: <tt>0</tt> - railway, <tt>1</tt> - road</li>
<li>map5 bits 4..3: transport route under bridge: <tt>0</tt> - railway, <tt>1</tt> - road</li>
</ul>
<li>m3 bits 7..4 = <a href="#TrackType">type of track</a> on the bridge, must be 0 for road bridge</li>
<li>m3 bits 3..0 = <a href="#TrackType">type of track</a> under the bridge, if any</li>
<li>m2 bits 3..0: bridge piece (<tt>0</tt>..<tt>5</tt>)
<li>m1: <a href="#OwnershipInfo">owner</a> of the land under bridge</li>
<li>map3_lo bits 7..4 = <a href="#TrackType">type of track</a> on the bridge, must be 0 for road bridge</li>
<li>map3_lo bits 3..0 = <a href="#TrackType">type of track</a> under the bridge, if any</li>
<li>map2 bits 3..0: bridge piece (<tt>0</tt>..<tt>5</tt>)
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the land under bridge</li>
</ul></li>
<li>m5 bits 2..1: <tt>0</tt> - railway bridge, <tt>1</tt> - road bridge</li>
<li>m5 bit 0: clear - bridge in the X direction, set - bridge in the Y direction</li>
<li>m2 bits 7..4: <a name="BridgeType">bridge type</a>:
<li>map5 bits 2..1: <tt>0</tt> - railway bridge, <tt>1</tt> - road bridge</li>
<li>map5 bit 0: clear - bridge in the X direction, set - bridge in the Y direction</li>
<li>map2 bits 7..4: <a name="BridgeType">bridge type</a>:
<table>
<tr><th align=left>Type&nbsp;</th><th align=left>Max. speed (mph)&nbsp;</th><th align=left>Description</th></tr>
<tr><td nowrap valign=top><tt>0</tt>&nbsp; </td><td align=center>20</td><td align=left>wooden</td></tr>
@@ -594,13 +583,13 @@ m5 bit 5 set:
<tr><td nowrap valign=top><tt>9</tt>&nbsp; </td><td align=center>160</td><td align=left>girder, steel</td></tr>
<tr><td nowrap valign=top><tt>A</tt>&nbsp; </td><td align=center>200</td><td align=left>tubular, steel</td></tr>
</table></li>
<li>m4 bit 7 set = on snow or desert</li>
<li>map3_hi bit 7 set = on snow or desert</li>
</ul>
</td></tr>
<tr><td valign=top nowrap><a name="ClassA"><tt> A </tt></a></td><td>
<ul>
<li>m5: tile type:
<li>map5: tile type:
<table>
<tr><td nowrap valign=top><tt>00</tt>&nbsp; </td><td align=left>transmitter</td></tr>
<tr><td nowrap valign=top><tt>01</tt>&nbsp; </td><td align=left>lighthouse</td></tr>
@@ -609,7 +598,7 @@ m5 bit 5 set:
<tr><td nowrap valign=top><tt>80</tt>..<tt>93</tt>&nbsp; </td><td align=left>company headquarters (5 sets of 4 tiles each, updated quarterly depending on the company performance)</td></tr>
</table>
</li>
<li>m1: <a href="#OwnershipInfo">owner</a> of the object (for lighthouses and transmitters normally <tt>10</tt>)</li>
<li>map_owner: <a href="#OwnershipInfo">owner</a> of the object (for lighthouses and transmitters normally <tt>10</tt>)</li>
</ul>
</td></tr>

View File

@@ -5,262 +5,232 @@
<meta name="Description" content="Structure of OpenTTD (OTTD) landscape arrays #2">
<title>OpenTTD Landscape Internals - #2</title>
<style type="text/css">
span.abuse { font-family: "Courier New", Courier, mono; background-color: rgb(255, 58, 31); }
span.free { font-family: "Courier New", Courier, mono; background-color: rgb(30, 178, 54); }
span.used { font-family: "Courier New", Courier, mono; }
td.bits { white-space: nowrap; text-align: center; font-family: "Courier New", Courier, mono; }
td.caption { white-space: nowrap; text-align: left; }
td li { white-space: nowrap; text-align: left; }
th { white-space: nowrap; text-align: center; }
.freebits { background-color: rgb(30, 178, 54);}
.abuse { background-color: rgb(255, 58, 31);}
</style>
</head>
<body style="direction: ltr;">
<h3 style="font-weight: bold;">Landscape</h3>
<span style="font-weight: bold;"></span>Five attributes hold the information about a tile.
<span style="font-weight: bold;"></span>Five arrays are used to encode the information of the contents of the tile.
This can be seen in the <a href="landscape.html">Landscape</a> document. This page tries to give an overview of used and free bits of
the array so you can quickly see what is used and what is not.
<ul>
<li><span style="font-weight: bold;"><span class="free">O</span></span> - bit is free</li>
<li><span style="font-weight: bold;"><span class="used">X</span></span> - bit is used</li>
<li><span style="font-weight: bold;"><span class="abuse">&nbsp;</span></span> - bit of attribute is abused for different purposes</li>
<li><span style="font-weight: bold;"><span class="freebits">O</span></span> - bit is free</li>
<li><span style="font-weight: bold;">X</span> - bit is used</li>
<li><span style="font-weight: bold;"><span class="abuse">&nbsp;&nbsp;&nbsp;</span></span> - bit of _map_* is abused for different purposes</li>
</ul>
<p>
<ul>
<li><span style="font-weight: bold;">type_height</span> - 8 bits in size, stores tile height (lower 4 bits) and tile class (upper 4 bits)</li>
<li><span style="font-weight: bold;">m1</span> - 8 bits in size, used to identify the owner of that tile (eg piece of rail, bridge, etc.)</li>
<li><span style="font-weight: bold;">m2</span> - 16 bits in size, used to identify the index of the given tile (object) in the (object-)array</li>
<li><span style="font-weight: bold;">m3</span> - 8 bits in size, is used for general storage</li>
<li><span style="font-weight: bold;">m4</span> - 8 bits in size, is used for general storage</li>
<li><span style="font-weight: bold;">m5</span> - 8 bits in size, is used for general storage</li>
<li><span style="font-weight: bold;">_map_owner[]</span> - 8 bits in size, used to identify the owner of that tile (eg piece of rail, bridge, etc.).</li>
<li><span style="font-weight: bold;">_map2[]</span> - 16 bits in size, used to identify the index of the given tile (object) in the (object-)array.</li>
<li><span style="font-weight: bold;">_map3[]</span> - 16 bits in size, which is split up into _map3lo[] and _map3hi[] is used for general storage.</li>
<li><span style="font-weight: bold;">_map_type_and_height[]</span> - 8 bits in size, stores tile height (lower 4 bits) and tile class (upper 4 bits).</li>
<li><span style="font-weight: bold;">_map5[]</span> - 8 bits in size, is used for general storage.</li>
</ul>
<table align=center border="1" cellpadding="2" cellspacing="2">
<table style="text-align: left;" border="1" cellpadding="2"
cellspacing="2" width="100%">
<tbody>
<tr>
<th colspan=2>class</th>
<th>m1 (8)</th>
<th>m2 (16)</th>
<th>m3 (8)</th>
<th>m4 (8)</th>
<th>type_height (8)</th>
<th>m5 (8)</th>
<th style="white-space: nowrap; text-align: left;">class</th>
<th style="white-space: nowrap; text-align: center;">_map_owner[L1] (8)</th>
<th style="white-space: nowrap; text-align: center;">_map2[L2] (16)</th>
<th style="white-space: nowrap; text-align: center;">_map3[lo&amp; hi,L3] (16)</th>
<th style="white-space: nowrap; text-align: center;">_map_type_and_height[L4] (8)</th>
<th style="white-space: nowrap; text-align: center;">_map5[L5] (8)</th>
</tr>
<tr>
<td colspan=2 class="caption">bits</td>
<td class="bits">7654 3210</td>
<td class="bits">FEDC BA98 7654 3210</td>
<td class="bits">7654 3210</td>
<td class="bits">7654 3210</td>
<td class="bits">7654 3210</td>
<td class="bits">7654 3210</td>
<td style="white-space: nowrap; text-align: left;">(0) ground</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX <span class="freebits">OOOO OO</span>XX XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX X<span class="freebits">O</span>XX</td>
</tr>
<tr>
<td rowspan="2">0</td>
<td class="caption">ground</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits">XXXX XX<span class="free">OO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: left;">(1) rail</td>
<td style="white-space: nowrap; text-align: center;"><span class="abuse">XXXX XXXX</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX <span class="freebits">OOOO OOOO</span><br>
</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX XXX<span class="freebits">O OOOO</span><br>
</td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX<br>
</td>
</tr>
<tr>
<td class="caption">farmland</td>
<td class="bits">-inherit-</td>
<td class="bits">XXXX XXXX XXXX XXXX</td>
<td class="bits"><span class="free">OOOO</span> XXXX</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits"><span class="free">OOO</span>X XXXX</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">depot/checkpoint</li>
</ul>
</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="text-align: center;">XXXX X<span class="freebits">OOO</span> XXXX XXXX</td>
<td style="text-align: center;">-inherit-</td>
<td style="white-space: nowrap; text-align: center;">XXX<span class="freebits">O OO</span>XX</td>
</tr>
<tr>
<td rowspan=3>1</td>
<td class="caption">rail</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO</span> XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO O</span>XXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: left;">(2) road</td>
<td style="text-align: center;">XXXX XXXX</td>
<td style="text-align: center;"><span class="abuse">XXXX XXXX XXXX XXXX</span></td>
<td style="text-align: center;"><span class="freebits">OOOO OOOO</span> XXXX XXXX</td>
<td style="text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="text-align: center;">XXXX XXXX</td>
</tr>
<tr>
<td class="caption">depot</td>
<td class="bits">-inherit-</td>
<td class="bits"><span class="free">OOOO OOOO OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO</span> XXXX</td>
<td class="bits"><span class="free">OOOO</span> XXXX</td>
<td class="bits">-inherit-</td>
<td class="bits">XX<span class="free">OO O</span>XXX</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">level crossing</li>
</ul>
</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;"><span class="abuse">XXXX XXXX XXXX XXXX</span></td>
<td style="text-align: center;">XXXX XXXX XXXX XXXX</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;"><span class="freebits">OO</span>XX XXXX</td>
</tr>
<tr>
<td class="caption">waypoint</td>
<td class="bits">-inherit-</td>
<td class="bits">XXXX XXXX XXXX XXXX</td>
<td class="bits"><span class="free">OOOO</span> XXXX</td>
<td class="bits"><span class="free">OOOO</span> XXXX</td>
<td class="bits">-inherit-</td>
<td class="bits">XX<span class="free">OO O</span>XXX</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">road depot</li>
</ul>
</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="text-align: center;"><span class="freebits">OOOO OOOO OOOO OOO</span>X</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">XXXX XXXX</td>
</tr>
<tr>
<td rowspan=3>2</td>
<td class="caption">road</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: left;">(3) town</td>
<td style="white-space: nowrap; text-align: center;"><span class="abuse">XXXX XXXX</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX XXXX XXXX<br>
</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX XXXX XXXX<br>
</td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX XX<span class="freebits">O</span>X</td>
</tr>
<tr>
<td class="caption">level crossing</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">-inherit-</td>
<td class="bits">XXXX XX<span class="free">OO</span></td>
<td style="white-space: nowrap; text-align: left;">(4) trees</td>
<td style="white-space: nowrap; text-align: center;"><span class="abuse">XXXX XXXX</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX XX<span class="freebits">OO OOOO OOOO</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX <span class="freebits">OO</span>XX XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXX<span class="freebits">O OO</span>XX</td>
</tr>
<tr>
<td class="caption">road depot</td>
<td class="bits">-inherit-</td>
<td class="bits"><span class="free">OOOO OOOO OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits">X<span class="free">OOO OOOO</span></td>
<td class="bits">-inherit-</td>
<td class="bits">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: left;">(5) station</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX XXXX XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX X<span class="freebits">OOO</span> XXXX XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
</tr>
<tr>
<td>3</td>
<td class="caption">town</td>
<td class="bits"><span class="abuse">XXXX XXXX</span></td>
<td class="bits">XXXX XXXX XXXX XXXX</td>
<td class="bits">XX<span class="free">OO OOOO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">X<span class="free">O</span>XX XXXX</td>
<td style="white-space: nowrap; text-align: left;">(6) water</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="white-space: nowrap; text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
</tr>
<tr>
<td>4</td>
<td class="caption">trees</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO</span> XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XX<span class="free">OO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XX<span class="free">OO O</span>XXX</td>
<td style="white-space: nowrap; text-align: left;">(8) industry</td>
<td style="white-space: nowrap; text-align: center;"><span class="abuse">XXXX X</span><span class="freebits">OO</span><span class="abuse">X</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX XXXX XXXX</td>
<td style="white-space: nowrap; text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
</tr>
<tr>
<td>5</td>
<td class="caption">station</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">bubble/sugar/toffee</li>
</ul>
</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">XXXX XXXX <span class="freebits">OOOO OOOO</span></td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
</tr>
<tr>
<td>6</td>
<td class="caption">water</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">toy factory</li>
</ul>
</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">XXXX XXXX XXXX XXXX</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
</tr>
<tr>
<td rowspan=6>8</td>
<td class="caption">industry</td>
<td class="bits"><span class="abuse">X</span><span class="free">OO</span><span class="abuse">X XXXX</span></td>
<td class="bits">XXXX XXXX XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">gold/copper/coal</li>
</ul>
</td>
<td style="text-align: center;">XXXX XXXX</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
</tr>
<tr>
<td>bubble/sugar/toffee</td>
<td class="bits"><span class="abuse">X</span><span class="free">OOO OOOO</span></td>
<td class="bits">-inherit-</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">oil wells</li>
</ul>
</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
</tr>
<tr>
<td>toy factory</td>
<td class="bits"><span class="abuse">X</span><span class="free">OOO OOOO</span></td>
<td class="bits">-inherit-</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">power station</li>
</ul>
</td>
<td style="text-align: center;">XXXX XX<span class="freebits">O</span>X</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
<td style="text-align: center;">-inherit-</td>
</tr>
<tr>
<td>gold/copper/coal</td>
<td class="bits"><span class="abuse">XX</span><span class="free">OO OO</span><span class="abuse">XX</span></td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td style="white-space: nowrap; text-align: left;">(9) tunnel</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX <span class="freebits">OOOO OOOO OOO</span>X</td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
</tr>
<tr>
<td>oil wells</td>
<td class="bits"><span class="abuse">X</span><span class="free">OOO OO</span><span class="abuse">XX</span></td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td>
<ul>
<li style="white-space: nowrap; text-align: left;">bridge</li>
</ul>
</td>
<td style="text-align: center;">XXXX XXXX</td>
<td style="text-align: center;"><span class="abuse">XXXX XXXX</span> <span class="freebits">OOOO OOOO</span></td>
<td style="text-align: center;">XXXX XXXX <span class="freebits">OOOO OOO</span>X</td>
<td style="text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="text-align: center;">XXXX XXXX</td>
</tr>
<tr>
<td>power station</td>
<td class="bits"><span class="abuse">X</span><span class="free">O</span><span class="abuse">XX XX</span><span class="free">OO</span></td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
<td class="bits">-inherit-</td>
</tr>
<tr>
<td rowspan=3>9</td>
<td class="caption">tunnel</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO</span> XXXX</td>
<td class="bits">X<span class="free">OOO OOOO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">X<span class="free">OOO</span> XXXX</td>
</tr>
<tr>
<td>bridge ramp</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO</span> <span class="abuse">XXXX</span> <span class="free">OOOO</span></td>
<td class="bits"><span class="free">OOOO</span> XXXX</td>
<td class="bits">X<span class="free">OOO OOOO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXX<span class="free">O O</span>XXX</td>
</tr>
<tr>
<td>bridge middle part</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO</span> <span class="abuse">XXXX XXXX</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">X<span class="free">OOO OOOO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
</tr>
<tr>
<td>A</td>
<td class="caption">various (HQ)</td>
<td class="bits">XXXX XXXX</td>
<td class="bits"><span class="free">OOOO OOOO OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits"><span class="free">OOOO OOOO</span></td>
<td class="bits">XXXX XXXX</td>
<td class="bits">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: left;">(10) various (HQ)</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
<td style="white-space: nowrap; text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="white-space: nowrap; text-align: center;"><span class="freebits">OOOO OOOO OOOO OOOO</span></td>
<td style="white-space: nowrap; text-align: center;">XXXX&nbsp;&nbsp;&nbsp;&nbsp;XXXX</td>
<td style="white-space: nowrap; text-align: center;">XXXX XXXX</td>
</tr>
</tbody>
</table>

View File

@@ -9,7 +9,7 @@ Multiplayer Manual for OpenTTD (0.3.5)
- Type in a game name
- Select the type of game ('LAN/Internet' or 'Internet (advertise)'. With the last one
other people are able to see you online. Else they need your IP and port to join)
- Click "start game", "load game" or "load scenario"
- Click "start game" ,"load game" or "load scenario"
- Start playing
@@ -46,7 +46,7 @@ Multiplayer Manual for OpenTTD (0.3.5)
- Open the console and type in the following command:
connect <ip/host>:<port>#<player-no>
]connect <ip/host>:<port>#<player-no>
4. Playing Internet-Games
@@ -54,9 +54,7 @@ Multiplayer Manual for OpenTTD (0.3.5)
- Since OpenTTD 0.3.5 the network protocol has been rewritten and is very stable, even over slow connections.
- Servers with a red dot behind it have a different version then you have. You will not be able to join those servers.
- Servers with a yellow dot behind it have NewGRFs that you do not have. You will not be able to join those servers.
- Server with a red dot behind it have a different version then you have. You will not be able to join those servers.
- It can happen that a connection is that slow, or you have that many clients connected to your server, that your clients start to loose their connection. Some things you can do about it:
@@ -112,10 +110,3 @@ Multiplayer Manual for OpenTTD (0.3.5)
- From 0.3.5, desyncs should not happen anymore
- From 0.3.5, patch-settings are also synced. You can now play without deleting openttd.cfg, and with, for example, extra large trains enabled.
7. Troubleshooting
------------------
- My advertised server does not show up in the 'advertised server list' (servers.openttd.org)
Run openttd with the '-d net=2' parameter, as this will show whether it receives replies from the master server.
If it does not receive replies it is most likely that you need to configure your router to forward the OpenTTD ports 3979 (both TCP and UDP) to the computer that is hosting the game.

View File

@@ -1,66 +1,50 @@
.\" Hey, EMACS: -*- nroff -*-
.\" First parameter, NAME, should be all caps
.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
.\" other parameters are allowed: see man(7), man(1)
.TH OPENTTD 6 "September 16, 2004"
.\" Please adjust this date whenever revising the manpage.
.Dd Jul 07, 2007
.Dt OPENTTD 6
.Sh NAME
.Nm openttd
.Nd An open source clone of the Microprose game "Transport Tycoon Deluxe"
.Sh SYNOPSIS
.Nm
.Op Fl Defhi
.Op Fl G Ar seed
.Op Fl d Ar [level | cat=lvl[, ...]]
.Op Fl g Ar [savegame]
.Op Fl n Ar host[:port][#player]
.Op Fl r Ar widthxheight
.Op Fl t Ar date
.Op Fl m Ar driver
.Op Fl s Ar driver
.Op Fl v Ar driver
.Sh OPTIONS
.Bl -tag -width ".Fl n Ar host[:port][#player]"
.It Fl D
Start a dedicated server
.It Fl G Ar seed
Seed the pseudo random number generator
.It Fl d Ar [level]
Set debug verbosity for all categories to
.Ar level
or 1 if omitted
.It Fl d Ar cat=level[, ...]
Set debug verbosity for a specific category
.It Fl e
Start in world editor mode
.It Fl f
Fork into background (dedicated only, see
.Fl D )
.It Fl g Ar [savegame]
Load
.Ar savegame
at start or start a new game if omitted
.It Fl h
Display a summary of all options and available drivers
.It Fl i
Force to use the DOS palette (use this if you see a lot of magenta)
.It Fl m Ar driver
Set the music driver, see
.Fl h
.It Fl n Ar host[:port][#player]
Join a network game, optionally specify player to play as and port to connect to
.It Fl r Ar widthxheight
Set the resolution
.It Fl s Ar driver
Set the sound driver, see
.Fl h
.It Fl t Ar date
Set the starting date
.It Fl v Ar driver
Set the video driver, see
.Fl h
.El
.Sh SEE ALSO
http://wiki.openttd.org/, http://www.openttd.org
.Sh HISTORY
Transport Tycoon Deluxe was written by Chris Sawyer and published by Microprose.
.Nm
is a free reimplementation.
.\"
.\" Some roff macros, for reference:
.\" .nh disable hyphenation
.\" .hy enable hyphenation
.\" .ad l left justify
.\" .ad b justify to both left and right margins
.\" .nf disable filling
.\" .fi enable filling
.\" .br insert line break
.\" .sp <n> insert n+1 empty lines
.\" for manpage-specific macros, see man(7)
.SH NAME
openttd \- An open source clone of the Microprose game "Transport Tycoon Deluxe"
.SH SYNOPSIS
.B openttd
.RI [ options ]
.br
.SH DESCRIPTION
Unfortunately, there is no real manpage for openttd yet. Hopefully someone
will write one soon. For now you should use
.B openttd -h
for more information, or check our Wiki manual: http://wiki.openttd.org/
.PP
.\" TeX users may be more comfortable with the \fB<whatever>\fP and
.\" \fI<whatever>\fP escape sequences to invoke bold face and italics,
.\" respectively.
.\" \fBopenttd\fP is a program that...
.SH OPTIONS
Wouldn't we like to have something here?
.\" below are commented out, to serve as layout examples for when somebody
.\" does actually fill this page
.\" .TP
.\" .B \-h, \-\-help
.\" Show summary of options.
.\" .TP
.\" .B \-v, \-\-version
.\" Show version of program.
.\" .SH SEE ALSO
.\" .BR bar (1),
.\" .BR baz (1).
.br
.SH AUTHOR
This manual page was written by Matthijs Kooijman <matthijs@katherina.student.utwente.nl>,
for the Debian project (but may be used by others).

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

38
docs/textcolor.txt Normal file
View File

@@ -0,0 +1,38 @@
0,9,10,2,3,13,9,9,0,10,4,15,6,11,14,1
dark blue=0 =0
pale_green=1 =9
pink=2 =10
yellow=3 =2
red=4 =3
light blue=5 =13
green=6 =9
dark green=7 =9
blue=8 =0
cream=9 =10
mauve=10 =4
purple=11 =15
orange=12 =6
brown=13 =11
grey=14 =14
white=15 =1
=blue=0
=white=1
=yellow=2
=red=3
=blue=4
=grey=5
=orange=6
=green=7
=light yellow=8
=light green=9
=cream=10
=brown=11
=white=12
=light blue=13
=dark grey=14
=purple=15
=black=16
=dark green=17=not good
=dark grey=21

224
driver.c
View File

@@ -1,224 +0,0 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "driver.h"
#include "functions.h"
#include "hal.h"
#include "string.h"
#include "music/bemidi.h"
#include "music/dmusic.h"
#include "music/extmidi.h"
#include "music/null_m.h"
#include "music/os2_m.h"
#include "music/win32_m.h"
#include "music/qtmidi.h"
#include "sound/null_s.h"
#include "sound/sdl_s.h"
#include "sound/cocoa_s.h"
#include "sound/win32_s.h"
#include "video/dedicated_v.h"
#include "video/null_v.h"
#include "video/sdl_v.h"
#include "video/cocoa_v.h"
#include "video/win32_v.h"
typedef struct DriverDesc {
const char* name;
const char* longname;
const HalCommonDriver* drv;
} DriverDesc;
typedef struct DriverClass {
const DriverDesc *descs;
const char *name;
const HalCommonDriver** drv;
} DriverClass;
#define M(x, y, z) { x, y, (const HalCommonDriver *)(void *)z }
static const DriverDesc _music_driver_descs[] = {
#ifdef __BEOS__
M("bemidi", "BeOS MIDI Driver", &_bemidi_music_driver),
#endif
#if defined(__OS2__) && !defined(__INNOTEK_LIBC__)
M("os2", "OS/2 Music Driver", &_os2_music_driver),
#endif
#ifdef WIN32_ENABLE_DIRECTMUSIC_SUPPORT
M("dmusic", "DirectMusic MIDI Driver", &_dmusic_midi_driver),
#endif
#ifdef WIN32
M("win32", "Win32 MIDI Driver", &_win32_music_driver),
#endif
#if defined(__APPLE__) && !defined(DEDICATED)
M("qt", "QuickTime MIDI Driver", &_qtime_music_driver),
#endif
#ifdef UNIX
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(__OS2__)
M("extmidi", "External MIDI Driver", &_extmidi_music_driver),
#endif
#endif
M("null", "Null Music Driver", &_null_music_driver),
M(NULL, NULL, NULL)
};
static const DriverDesc _sound_driver_descs[] = {
#ifdef WIN32
M("win32", "Win32 WaveOut Driver", &_win32_sound_driver),
#endif
#ifdef WITH_SDL
M("sdl", "SDL Sound Driver", &_sdl_sound_driver),
#endif
#ifdef WITH_COCOA
M("cocoa", "Cocoa Sound Driver", &_cocoa_sound_driver),
#endif
M("null", "Null Sound Driver", &_null_sound_driver),
M(NULL, NULL, NULL)
};
static const DriverDesc _video_driver_descs[] = {
#ifdef WIN32
M("win32", "Win32 GDI Video Driver", &_win32_video_driver),
#endif
#ifdef WITH_SDL
M("sdl", "SDL Video Driver", &_sdl_video_driver),
#endif
#ifdef WITH_COCOA
M("cocoa", "Cocoa Video Driver", &_cocoa_video_driver),
#endif
M("null", "Null Video Driver", &_null_video_driver),
#ifdef ENABLE_NETWORK
M("dedicated", "Dedicated Video Driver", &_dedicated_video_driver),
#endif
M(NULL, NULL, NULL)
};
#undef M
#define M(x, y, z) { x, y, (const HalCommonDriver **)(void *)z }
static const DriverClass _driver_classes[] = {
M(_video_driver_descs, "video", &_video_driver),
M(_sound_driver_descs, "sound", &_sound_driver),
M(_music_driver_descs, "music", &_music_driver)
};
#undef M
static const DriverDesc* GetDriverByName(const DriverDesc* dd, const char* name)
{
for (; dd->name != NULL; dd++) {
if (strcmp(dd->name, name) == 0) return dd;
}
return NULL;
}
void LoadDriver(int driver, const char *name)
{
const DriverClass *dc = &_driver_classes[driver];
const DriverDesc *dd;
const char *err;
if (*name == '\0') {
for (dd = dc->descs; dd->name != NULL; dd++) {
err = dd->drv->start(NULL);
if (err == NULL) break;
DEBUG(driver, 1) ("Probing %s driver \"%s\" failed with error: %s",
dc->name, dd->name, err
);
}
if (dd->name == NULL) {
error("Couldn't find any suitable %s driver", dc->name);
}
DEBUG(driver, 1)
("Successfully probed %s driver \"%s\"", dc->name, dd->name);
*dc->drv = dd->drv;
} else {
char* parm;
char buffer[256];
const char* parms[32];
// Extract the driver name and put parameter list in parm
ttd_strlcpy(buffer, name, sizeof(buffer));
parm = strchr(buffer, ':');
parms[0] = NULL;
if (parm != NULL) {
uint np = 0;
// Tokenize the parm.
do {
*parm++ = '\0';
if (np < lengthof(parms) - 1)
parms[np++] = parm;
while (*parm != '\0' && *parm != ',')
parm++;
} while (*parm == ',');
parms[np] = NULL;
}
dd = GetDriverByName(dc->descs, buffer);
if (dd == NULL)
error("No such %s driver: %s\n", dc->name, buffer);
if (*dc->drv != NULL) (*dc->drv)->stop();
*dc->drv = NULL;
err = dd->drv->start(parms);
if (err != NULL) {
error("Unable to load driver %s(%s). The error was: %s\n",
dd->name, dd->longname, err
);
}
*dc->drv = dd->drv;
}
}
static const char* GetDriverParam(const char* const* parm, const char* name)
{
size_t len;
if (parm == NULL) return NULL;
len = strlen(name);
for (; *parm != NULL; parm++) {
const char* p = *parm;
if (strncmp(p, name, len) == 0) {
if (p[len] == '=') return p + len + 1;
if (p[len] == '\0') return p + len;
}
}
return NULL;
}
bool GetDriverParamBool(const char* const* parm, const char* name)
{
return GetDriverParam(parm, name) != NULL;
}
int GetDriverParamInt(const char* const* parm, const char* name, int def)
{
const char* p = GetDriverParam(parm, name);
return p != NULL ? atoi(p) : def;
}
char *GetDriverList(char* p, const char *last)
{
const DriverClass* dc;
for (dc = _driver_classes; dc != endof(_driver_classes); dc++) {
const DriverDesc* dd;
p += snprintf(p, last - p, "List of %s drivers:\n", dc->name);
for (dd = dc->descs; dd->name != NULL; dd++) {
p += snprintf(p, last - p, "%10s: %s\n", dd->name, dd->longname);
}
p = strecpy(p, "\n", last);
}
return p;
}

View File

@@ -1,13 +0,0 @@
/* $Id$ */
#ifndef DRIVER_H
#define DRIVER_H
void LoadDriver(int driver, const char *name);
bool GetDriverParamBool(const char* const* parm, const char* name);
int GetDriverParamInt(const char* const* parm, const char* name, int def);
char *GetDriverList(char *p, const char *last);
#endif /* DRIVER_H */

View File

@@ -1,83 +1,78 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "table/strings.h"
#include "functions.h"
#include "viewport.h"
#include "command.h"
#include "table/sprites.h"
static void DrawTile_Dummy(TileInfo *ti)
{
DrawGroundSpriteAt(SPR_SHADOW_CELL, ti->x, ti->y, ti->z);
DrawGroundSpriteAt(0x3EC, ti->x, ti->y, ti->z);
}
static uint GetSlopeZ_Dummy(TileIndex tile, uint x, uint y)
{
return 0;
static uint GetSlopeZ_Dummy(TileInfo *ti) {
return GetPartialZ(ti->x&0xF, ti->y&0xF, ti->tileh) + ti->z;
}
static Slope GetSlopeTileh_Dummy(TileIndex tile, Slope tileh)
{
return SLOPE_FLAT;
static uint GetSlopeTileh_Dummy(TileInfo *ti) {
return ti->tileh;
}
static int32 ClearTile_Dummy(TileIndex tile, byte flags)
{
static int32 ClearTile_Dummy(uint tile, byte flags) {
return_cmd_error(STR_0001_OFF_EDGE_OF_MAP);
}
static void GetAcceptedCargo_Dummy(TileIndex tile, AcceptedCargo ac)
static void GetAcceptedCargo_Dummy(uint tile, AcceptedCargo ac)
{
/* not used */
}
static void GetTileDesc_Dummy(TileIndex tile, TileDesc *td)
static void GetTileDesc_Dummy(uint tile, TileDesc *td)
{
td->str = STR_EMPTY;
td->owner = OWNER_NONE;
}
static void AnimateTile_Dummy(TileIndex tile)
static void AnimateTile_Dummy(uint tile)
{
/* not used */
}
static void TileLoop_Dummy(TileIndex tile)
static void TileLoop_Dummy(uint tile)
{
/* not used */
}
static void ClickTile_Dummy(TileIndex tile)
static void ClickTile_Dummy(uint tile)
{
/* not used */
}
static void ChangeTileOwner_Dummy(TileIndex tile, PlayerID old_player, PlayerID new_player)
static void ChangeTileOwner_Dummy(uint tile, byte old_player, byte new_player)
{
/* not used */
}
static uint32 GetTileTrackStatus_Dummy(TileIndex tile, TransportType mode)
static uint32 GetTileTrackStatus_Dummy(uint tile, TransportType mode)
{
return 0;
}
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 */
GetSlopeTileh_Dummy, /* get_slope_tileh_proc */
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 */
NULL, /* vehicle_leave_tile_proc */
GetSlopeTileh_Dummy, /* get_slope_tileh_proc */
};

1130
economy.c

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,6 @@
/* $Id$ */
#ifndef ECONOMY_H
#define ECONOMY_H
void ResetPriceBaseMultipliers(void);
void SetPriceBaseMultiplier(uint price, byte factor);
typedef struct {
// Maximum possible loan
int32 max_loan;
@@ -21,50 +16,63 @@ typedef struct {
VARDEF Economy _economy;
typedef struct Subsidy {
CargoID cargo_type;
byte cargo_type;
byte age;
/* from and to can either be TownID, StationID or IndustryID */
uint16 from;
uint16 to;
} Subsidy;
enum {
SCORE_VEHICLES = 0,
SCORE_STATIONS = 1,
SCORE_MIN_PROFIT = 2,
SCORE_MIN_INCOME = 3,
SCORE_MAX_INCOME = 4,
SCORE_DELIVERED = 5,
SCORE_CARGO = 6,
SCORE_MONEY = 7,
SCORE_LOAN = 8,
SCORE_TOTAL = 9, // This must always be the last entry
SCORE_VEHICLES = 0,
SCORE_STATIONS = 1,
SCORE_MIN_PROFIT = 2,
SCORE_MIN_INCOME = 3,
SCORE_MAX_INCOME = 4,
SCORE_DELIVERED = 5,
SCORE_CARGO = 6,
SCORE_MONEY = 7,
SCORE_LOAN = 8,
SCORE_TOTAL = 9, // This must always be the last entry
NUM_SCORE = 10, // How many scores are there..
NUM_SCORE = 10, // How many scores are there..
SCORE_MAX = 1000 // The max score that can be in the performance history
// the scores together of score_info is allowed to be more!
SCORE_MAX = 1000, // The max score that can be in the performance history
// the scores together of score_info is allowed to be more!
};
typedef struct ScoreInfo {
byte id; // Unique ID of the score
int needed; // How much you need to get the perfect score
int score; // How much score it will give
byte id; // Unique ID of the score
int needed; // How much you need to get the perfect score
int score; // How much score it will give
} ScoreInfo;
extern const ScoreInfo _score_info[];
extern int _score_part[MAX_PLAYERS][NUM_SCORE];
static const ScoreInfo score_info[] = {
{SCORE_VEHICLES, 120, 100},
{SCORE_STATIONS, 80, 100},
{SCORE_MIN_PROFIT, 10000, 100},
{SCORE_MIN_INCOME, 50000, 50},
{SCORE_MAX_INCOME, 100000, 100},
{SCORE_DELIVERED, 40000, 400},
{SCORE_CARGO, 8, 50},
{SCORE_MONEY, 10000000, 50},
{SCORE_LOAN, 250000, 50},
{SCORE_TOTAL, 0, 0}
};
int _score_part[MAX_PLAYERS][NUM_SCORE];
int UpdateCompanyRatingAndValue(Player *p, bool update);
void UpdatePlayerHouse(Player *p, uint score);
VARDEF Subsidy _subsidies[MAX_PLAYERS];
Pair SetupSubsidyDecodeParam(const Subsidy* s, bool mode);
void DeleteSubsidyWithTown(TownID index);
void DeleteSubsidyWithIndustry(IndustryID index);
void DeleteSubsidyWithStation(StationID index);
Pair SetupSubsidyDecodeParam(Subsidy *s, bool mode);
void DeleteSubsidyWithIndustry(uint16 index);
void DeleteSubsidyWithStation(uint16 index);
void RemoteSubsidyAdd(Subsidy *s_new);
int32 GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type);
uint MoveGoodsToStation(TileIndex tile, int w, int h, int type, uint amount);
int32 GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, byte cargo_type);
uint MoveGoodsToStation(uint tile, int w, int h, int type, uint amount);
#endif /* ECONOMY_H */

456
elrail.c
View File

@@ -1,456 +0,0 @@
/* $Id$ */
/** @file elrail.c
* This file deals with displaying wires and pylons for electric railways.
* <h2>Basics</h2>
*
* <h3>Tile Types</h3>
*
* We have two different types of tiles in the drawing code:
* Normal Railway Tiles (NRTs) which can have more than one track on it, and
* Special Railways tiles (SRTs) which have only one track (like crossings, depots
* stations, etc).
*
* <h3>Location Categories</h3>
*
* All tiles are categorized into three location groups (TLG):
* Group 0: Tiles with both an even X coordinate and an even Y coordinate
* Group 1: Tiles with an even X and an odd Y coordinate
* Group 2: Tiles with an odd X and an even Y coordinate
* Group 3: Tiles with both an odd X and Y coordnate.
*
* <h3>Pylon Points</h3>
* <h4>Control Points</h4>
* A Pylon Control Point (PCP) is a position where a wire (or rather two)
* is mounted onto a pylon.
* Each NRT does contain 4 PCPs which are bitmapped to a byte
* variable and are represented by the DiagDirection enum
*
* Each track ends on two PCPs and thus requires one pylon on each end. However,
* there is one exception: Straight-and-level tracks only have one pylon every
* other tile.
*
* Now on each edge there are two PCPs: One from each adjacent tile. Both PCPs
* are merged using an OR operation (i. e. if one tile needs a PCP at the postion
* in question, both tiles get it).
*
* <h4>Position Points</h4>
* A Pylon Position Point (PPP) is a position where a pylon is located on the
* ground. Each PCP owns 8 in (45 degree steps) PPPs that are located around
* it. PPPs are represented using the Direction enum. Each track bit has PPPs
* that are impossible (because the pylon would be situated on the track) and
* some that are preferred (because the pylon would be rectangular to the track).
*
* <img src="../../elrail_tile.png">
* <img src="../../elrail_track.png">
*
*/
#include "stdafx.h"
#include "openttd.h"
#include "station_map.h"
#include "tile.h"
#include "viewport.h"
#include "functions.h" /* We should REALLY get rid of this goddamn file, as it is butt-ugly */
#include "variables.h" /* ... same here */
#include "rail.h"
#include "debug.h"
#include "tunnel_map.h"
#include "road_map.h"
#include "bridge_map.h"
#include "bridge.h"
#include "rail_map.h"
#include "table/sprites.h"
#include "table/elrail_data.h"
#include "vehicle.h"
#include "train.h"
#include "gui.h"
static inline TLG GetTLG(TileIndex t)
{
return (HASBIT(TileX(t), 0) << 1) + HASBIT(TileY(t), 0);
}
/** Finds which Rail Bits are present on a given tile. For bridge tiles,
* returns track bits under the bridge
*/
static TrackBits GetRailTrackBitsUniversal(TileIndex t, byte *override)
{
switch (GetTileType(t)) {
case MP_RAILWAY:
if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0;
switch (GetRailTileType(t)) {
case RAIL_TILE_NORMAL: case RAIL_TILE_SIGNALS:
return GetTrackBits(t);
case RAIL_TILE_DEPOT_WAYPOINT:
if (GetRailTileSubtype(t) == RAIL_SUBTYPE_WAYPOINT) return GetRailWaypointBits(t);
default:
return 0;
}
break;
case MP_TUNNELBRIDGE:
if (IsTunnel(t)) {
if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0;
if (override != NULL) *override = 1 << GetTunnelDirection(t);
return AxisToTrackBits(DiagDirToAxis(GetTunnelDirection(t)));
} else {
if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0;
if (IsBridgeMiddle(t)) {
if (IsTransportUnderBridge(t) &&
GetTransportTypeUnderBridge(t) == TRANSPORT_RAIL) {
return GetRailBitsUnderBridge(t);
} else {
return 0;
}
} else {
if (override != NULL && DistanceMax(t, GetOtherBridgeEnd(t)) > 1) *override = 1 << GetBridgeRampDirection(t);
return AxisToTrackBits(DiagDirToAxis(GetBridgeRampDirection(t)));
}
}
case MP_STREET:
if (GetRoadTileType(t) != ROAD_TILE_CROSSING) return 0;
if (GetRailTypeCrossing(t) != RAILTYPE_ELECTRIC) return 0;
return GetCrossingRailBits(t);
case MP_STATION:
if (!IsRailwayStation(t)) return 0;
if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0;
if (!IsStationTileElectrifiable(t)) return 0;
return TrackToTrackBits(GetRailStationTrack(t));
default:
return 0;
}
}
/** Corrects the tileh for certain tile types. Returns an effective tileh for the track on the tile.
* @param tile The tile to analyse
* @param *tileh the tileh
*/
static void AdjustTileh(TileIndex tile, Slope *tileh)
{
if (IsTileType(tile, MP_TUNNELBRIDGE)) {
if (IsTunnel(tile)) {
*tileh = SLOPE_STEEP; /* XXX - Hack to make tunnel entrances to always have a pylon */
} else {
if (IsBridgeRamp(tile)) {
if (*tileh != SLOPE_FLAT) {
*tileh = SLOPE_FLAT;
} else {
switch (GetBridgeRampDirection(tile)) {
case DIAGDIR_NE: *tileh = SLOPE_NE; break;
case DIAGDIR_SE: *tileh = SLOPE_SE; break;
case DIAGDIR_SW: *tileh = SLOPE_SW; break;
case DIAGDIR_NW: *tileh = SLOPE_NW; break;
default: break;
}
}
}
}
}
}
/** Draws wires and, if required, pylons on a given tile
* @param ti The Tileinfo to draw the tile for
*/
static void DrawCatenaryRailway(const TileInfo *ti)
{
/* Pylons are placed on a tile edge, so we need to take into account
* the track configuration of 2 adjacent tiles. trackconfig[0] stores the
* current tile (home tile) while [1] holds the neighbour */
TrackBits trackconfig[TS_END];
bool isflat[TS_END];
/* Note that ti->tileh has already been adjusted for Foundations */
Slope tileh[TS_END] = { ti->tileh, SLOPE_FLAT };
TLG tlg = GetTLG(ti->tile);
byte PCPstatus = 0;
byte OverridePCP = 0;
byte PPPpreferred[DIAGDIR_END];
byte PPPallowed[DIAGDIR_END];
DiagDirection i;
Track t;
/* Find which rail bits are present, and select the override points.
* We don't draw a pylon:
* 1) INSIDE a tunnel (we wouldn't see it anyway)
* 2) on the "far" end of a bridge head (the one that connects to bridge middle),
* because that one is drawn on the bridge. Exception is for length 0 bridges
* which have no middle tiles */
trackconfig[TS_HOME] = GetRailTrackBitsUniversal(ti->tile, &OverridePCP);
/* If a track bit is present that is not in the main direction, the track is level */
isflat[TS_HOME] = trackconfig[TS_HOME] & (TRACK_BIT_HORZ | TRACK_BIT_VERT);
AdjustTileh(ti->tile, &tileh[TS_HOME]);
for (i = DIAGDIR_NE; i < DIAGDIR_END; i++) {
TileIndex neighbour = ti->tile + TileOffsByDiagDir(i);
uint foundation = 0;
int k;
/* Here's one of the main headaches. GetTileSlope does not correct for possibly
* existing foundataions, so we do have to do that manually later on.*/
tileh[TS_NEIGHBOUR] = GetTileSlope(neighbour, NULL);
trackconfig[TS_NEIGHBOUR] = GetRailTrackBitsUniversal(neighbour, NULL);
if (IsTunnelTile(neighbour) && i != GetTunnelDirection(neighbour)) trackconfig[TS_NEIGHBOUR] = 0;
isflat[TS_NEIGHBOUR] = trackconfig[TS_NEIGHBOUR] & (TRACK_BIT_HORZ | TRACK_BIT_VERT);
PPPpreferred[i] = 0xFF; /* We start with preferring everything (end-of-line in any direction) */
PPPallowed[i] = AllowedPPPonPCP[i];
/* We cycle through all the existing tracks at a PCP and see what
* PPPs we want to have, or may not have at all */
for (k = 0; k < NUM_TRACKS_AT_PCP; k++) {
/* Next to us, we have a bridge head, don't worry about that one, if it shows away from us */
if (TrackSourceTile[i][k] == TS_NEIGHBOUR &&
IsBridgeTile(neighbour) && IsBridgeRamp(neighbour) &&
GetBridgeRampDirection(neighbour) == ReverseDiagDir(i)) {
continue;
}
/* We check whether the track in question (k) is present in the tile
* (TrackSourceTile) */
if (HASBIT(trackconfig[TrackSourceTile[i][k]], TracksAtPCP[i][k])) {
/* track found, if track is in the neighbour tile, adjust the number
* of the PCP for preferred/allowed determination*/
DiagDirection PCPpos = (TrackSourceTile[i][k] == TS_HOME) ? i : ReverseDiagDir(i);
SETBIT(PCPstatus, i); /* This PCP is in use */
PPPpreferred[i] &= PreferredPPPofTrackAtPCP[TracksAtPCP[i][k]][PCPpos];
PPPallowed[i] &= ~DisallowedPPPofTrackAtPCP[TracksAtPCP[i][k]][PCPpos];
}
}
/* Deactivate all PPPs if PCP is not used */
PPPpreferred[i] *= HASBIT(PCPstatus, i);
PPPallowed[i] *= HASBIT(PCPstatus, i);
/* A station is always "flat", so adjust the tileh accordingly */
if (IsTileType(neighbour, MP_STATION)) tileh[TS_NEIGHBOUR] = SLOPE_FLAT;
/* Read the foundataions if they are present, and adjust the tileh */
if (IsTileType(neighbour, MP_RAILWAY) && GetRailType(neighbour) == RAILTYPE_ELECTRIC) foundation = GetRailFoundation(tileh[TS_NEIGHBOUR], trackconfig[TS_NEIGHBOUR]);
if (IsBridgeTile(neighbour) && IsBridgeRamp(neighbour)) {
foundation = GetBridgeFoundation(tileh[TS_NEIGHBOUR], DiagDirToAxis(GetBridgeRampDirection(neighbour)));
}
if (foundation != 0) {
if (foundation < 15) {
tileh[TS_NEIGHBOUR] = SLOPE_FLAT;
} else {
tileh[TS_NEIGHBOUR] = _inclined_tileh[foundation - 15];
}
}
AdjustTileh(neighbour, &tileh[TS_NEIGHBOUR]);
/* If we have a straight (and level) track, we want a pylon only every 2 tiles
* Delete the PCP if this is the case. */
/* Level means that the slope is the same, or the track is flat */
if (tileh[TS_HOME] == tileh[TS_NEIGHBOUR] || (isflat[TS_HOME] && isflat[TS_NEIGHBOUR])) {
for (k = 0; k < NUM_IGNORE_GROUPS; k++)
if (PPPpreferred[i] == IgnoredPCP[k][tlg][i]) CLRBIT(PCPstatus, i);
}
/* Now decide where we draw our pylons. First try the preferred PPPs, but they may not exist.
* In that case, we try the any of the allowed ones. if they don't exist either, don't draw
* anything. Note that the preferred PPPs still contain the end-of-line markers.
* Remove those (simply by ANDing with allowed, since these markers are never allowed) */
if ((PPPallowed[i] & PPPpreferred[i]) != 0) PPPallowed[i] &= PPPpreferred[i];
if (PPPallowed[i] != 0 && HASBIT(PCPstatus, i) && !HASBIT(OverridePCP, i)) {
for (k = 0; k < DIR_END; k++) {
byte temp = PPPorder[i][GetTLG(ti->tile)][k];
if (HASBIT(PPPallowed[i], temp)) {
uint x = ti->x + x_pcp_offsets[i] + x_ppp_offsets[temp];
uint y = ti->y + y_pcp_offsets[i] + y_ppp_offsets[temp];
/* Don't build the pylon if it would be outside the tile */
if (!HASBIT(OwnedPPPonPCP[i], temp)) {
/* We have a neighour that will draw it, bail out */
if (trackconfig[TS_NEIGHBOUR] != 0) break;
continue; /* No neighbour, go looking for a better position */
}
AddSortableSpriteToDraw(pylons_normal[temp], x, y, 1, 1, 10,
GetSlopeZ(ti->x + x_pcp_offsets[i], ti->y + y_pcp_offsets[i]));
break; /* We already have drawn a pylon, bail out */
}
}
}
}
/* Don't draw a wire under a low bridge */
if (IsBridgeTile(ti->tile) &&
IsBridgeMiddle(ti->tile) &&
!(_display_opt & DO_TRANS_BUILDINGS) &&
GetBridgeHeight(ti->tile) <= TilePixelHeight(ti->tile) + TILE_HEIGHT) {
return;
}
/* Drawing of pylons is finished, now draw the wires */
for (t = 0; t < TRACK_END; t++) {
if (HASBIT(trackconfig[TS_HOME], t)) {
byte PCPconfig;
const SortableSpriteStruct *sss;
int tileh_selector;
if (IsTunnelTile(ti->tile)) {
const SortableSpriteStruct* sss = &CatenarySpriteData_Tunnel[GetTunnelDirection(ti->tile)];
AddSortableSpriteToDraw(
sss->image, ti->x + sss->x_offset, ti->y + sss->y_offset,
sss->x_size, sss->y_size, sss->z_size,
GetTileZ(ti->tile) + sss->z_offset
);
break;
}
PCPconfig = HASBIT(PCPstatus, PCPpositions[t][0]) +
(HASBIT(PCPstatus, PCPpositions[t][1]) << 1);
tileh_selector = !(tileh[TS_HOME] % 3) * tileh[TS_HOME] / 3; /* tileh for the slopes, 0 otherwise */
assert(PCPconfig != 0); /* We have a pylon on neither end of the wire, that doesn't work (since we have no sprites for that) */
assert(!IsSteepSlope(tileh[TS_HOME]));
sss = &CatenarySpriteData[Wires[tileh_selector][t][PCPconfig]];
AddSortableSpriteToDraw( sss->image, ti->x + sss->x_offset, ti->y + sss->y_offset,
sss->x_size, sss->y_size, sss->z_size, GetSlopeZ(ti->x + min(sss->x_offset, TILE_SIZE - 1), ti->y + min(sss->y_offset, TILE_SIZE - 1)) + sss->z_offset);
}
}
}
static void DrawCatenaryOnBridge(const TileInfo *ti)
{
TileIndex end = GetSouthernBridgeEnd(ti->tile);
TileIndex start = GetOtherBridgeEnd(end);
uint length = GetBridgeLength(start, end);
uint num = DistanceMax(ti->tile, start);
uint height;
const SortableSpriteStruct *sss;
Axis axis = GetBridgeAxis(ti->tile);
TLG tlg = GetTLG(ti->tile);
CatenarySprite offset = axis == AXIS_X ? 0 : WIRE_Y_FLAT_BOTH - WIRE_X_FLAT_BOTH;
if ((length % 2) && num == length) {
/* Draw the "short" wire on the southern end of the bridge
* only needed if the length of the bridge is odd */
sss = &CatenarySpriteData[WIRE_X_FLAT_BOTH + offset];
} else {
/* Draw "long" wires on all other tiles of the bridge (one pylon every two tiles) */
sss = &CatenarySpriteData[WIRE_X_FLAT_SW + (num % 2) + offset];
}
height = GetBridgeHeight(ti->tile);
AddSortableSpriteToDraw( sss->image, ti->x + sss->x_offset, ti->y + sss->y_offset,
sss->x_size, sss->y_size, sss->z_size, height + sss->z_offset
);
/* Finished with wires, draw pylons */
/* every other tile needs a pylon on the northern end */
if (num % 2) {
if (axis == AXIS_X) {
AddSortableSpriteToDraw(pylons_bridge[0 + HASBIT(tlg, 0)], ti->x, ti->y + 4 + 8 * HASBIT(tlg, 0), 1, 1, 10, height);
} else {
AddSortableSpriteToDraw(pylons_bridge[2 + HASBIT(tlg, 1)], ti->x + 4 + 8 * HASBIT(tlg, 1), ti->y, 1, 1, 10, height);
}
}
/* need a pylon on the southern end of the bridge */
if (DistanceMax(ti->tile, start) == length) {
if (axis == AXIS_X) {
AddSortableSpriteToDraw(pylons_bridge[0 + HASBIT(tlg, 0)], ti->x + 16, ti->y + 4 + 8 * HASBIT(tlg, 0), 1, 1, 10, height);
} else {
AddSortableSpriteToDraw(pylons_bridge[2 + HASBIT(tlg, 1)], ti->x + 4 + 8 * HASBIT(tlg, 1), ti->y + 16, 1, 1, 10, height);
}
}
}
void DrawCatenary(const TileInfo *ti)
{
if (_patches.disable_elrails) return;
switch (GetTileType(ti->tile)) {
case MP_RAILWAY:
if ( IsRailDepot(ti->tile)) {
const SortableSpriteStruct* sss = &CatenarySpriteData_Depot[GetRailDepotDirection(ti->tile)];
AddSortableSpriteToDraw(
sss->image, ti->x + sss->x_offset, ti->y + sss->y_offset,
sss->x_size, sss->y_size, sss->z_size,
GetTileMaxZ(ti->tile) + sss->z_offset
);
return;
}
break;
case MP_TUNNELBRIDGE:
if (IsBridge(ti->tile) && IsBridgeMiddle(ti->tile) && GetRailTypeOnBridge(ti->tile) == RAILTYPE_ELECTRIC) DrawCatenaryOnBridge(ti);
break;
case MP_STREET: break;
case MP_STATION: break;
default: return;
}
DrawCatenaryRailway(ti);
}
int32 SettingsDisableElrail(int32 p1)
{
EngineID e_id;
Vehicle* v;
Player *p;
bool disable = (p1 != 0);
/* we will now walk through all electric train engines and change their railtypes if it is the wrong one*/
const RailType old_railtype = disable ? RAILTYPE_ELECTRIC : RAILTYPE_RAIL;
const RailType new_railtype = disable ? RAILTYPE_RAIL : RAILTYPE_ELECTRIC;
/* walk through all train engines */
for (e_id = 0; e_id < NUM_TRAIN_ENGINES; e_id++) {
const RailVehicleInfo *rv_info = RailVehInfo(e_id);
Engine *e = GetEngine(e_id);
/* if it is an electric rail engine and its railtype is the wrong one */
if (rv_info->engclass == 2 && e->railtype == old_railtype) {
/* change it to the proper one */
e->railtype = new_railtype;
_engine_info[e_id].railtype = new_railtype;
}
}
/* when disabling elrails, make sure that all existing trains can run on
* normal rail too */
if (disable) {
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_Train && v->u.rail.railtype == RAILTYPE_ELECTRIC) {
/* this railroad vehicle is now compatible only with elrail,
* so add there also normal rail compatibility */
v->u.rail.compatible_railtypes |= (1 << RAILTYPE_RAIL);
v->u.rail.railtype = RAILTYPE_RAIL;
SETBIT(v->u.rail.flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL);
}
}
}
/* setup total power for trains */
FOR_ALL_VEHICLES(v) {
/* power is cached only for front engines */
if (v->type == VEH_Train && IsFrontEngine(v)) TrainPowerChanged(v);
}
FOR_ALL_PLAYERS(p) p->avail_railtypes = GetPlayerRailtypes(p->index);
/* This resets the _last_built_railtype, which will be invalid for electric
* rails. It may have unintended consequences if that function is ever
* extended, though. */
ReinitGuiAfterToggleElrail(disable);
return 0;
}

View File

@@ -1,5 +1,3 @@
/* $Id$ */
#include <stdio.h>
// This pretty simple file checks if the system is LITTLE_ENDIAN or BIG_ENDIAN
@@ -11,42 +9,22 @@
// care of the real writing to the file.
int main (int argc, char *argv[]) {
unsigned char EndianTest[2] = { 1, 0 };
int force_BE = 0, force_LE = 0, force_PREPROCESSOR = 0;
unsigned char EndianTest[2] = { 1, 0 };
int force_BE = 0, force_LE = 0;
if (argc > 1 && strcmp(argv[1], "BE") == 0)
force_BE = 1;
if (argc > 1 && strcmp(argv[1], "LE") == 0)
force_LE = 1;
if (argc > 1 && strcmp(argv[1], "PREPROCESSOR") == 0)
force_PREPROCESSOR = 1;
if (argc > 1 && strcmp(argv[1], "BE") == 0)
force_BE = 1;
if (argc > 1 && strcmp(argv[1], "LE") == 0)
force_LE = 1;
printf("#ifndef ENDIAN_H\n#define ENDIAN_H\n");
printf("#ifndef ENDIAN_H\n#define ENDIAN_H\n");
if (force_LE == 1) {
printf("#define TTD_LITTLE_ENDIAN\n");
} else {
if (force_BE == 1) {
printf("#define TTD_BIG_ENDIAN\n");
} else {
if (force_PREPROCESSOR == 1) {
// adding support for universal binaries on OSX
// Universal binaries supports both PPC and x86
// If a compiler for OSX gets this setting, it will always pick the correct endian and no test is needed
printf("#ifdef __BIG_ENDIAN__\n");
printf("#define TTD_BIG_ENDIAN\n");
printf("#else\n");
printf("#define TTD_LITTLE_ENDIAN\n");
printf("#endif\n");
} else {
if ( *(short *) EndianTest == 1 )
printf("#define TTD_LITTLE_ENDIAN\n");
else
printf("#define TTD_BIG_ENDIAN\n");
}
}
}
printf("#endif\n");
if ( (*(short *) EndianTest == 1 && force_BE != 1) || force_LE == 1)
printf("#define TTD_LITTLE_ENDIAN\n");
else
printf("#define TTD_BIG_ENDIAN\n");
return 0;
printf("#endif\n");
return 0;
}

992
engine.c

File diff suppressed because it is too large Load Diff

303
engine.h
View File

@@ -1,11 +1,7 @@
/* $Id$ */
#ifndef ENGINE_H
#define ENGINE_H
/** @file engine.h */
#include "oldpool.h"
#include "sprite.h"
typedef struct RailVehicleInfo {
byte image_index;
@@ -13,40 +9,24 @@ typedef struct RailVehicleInfo {
byte base_cost;
uint16 max_speed;
uint16 power;
uint16 weight;
byte weight;
byte running_cost_base;
byte running_cost_class;
byte engclass; // 0: steam, 1: diesel, 2: electric
byte capacity;
CargoID cargo_type;
byte ai_rank;
uint16 pow_wag_power;
byte pow_wag_weight;
byte visual_effect; // NOTE: this is not 100% implemented yet, at the moment it is only used as a 'fallback' value
// for when the 'powered wagon' callback fails. But it should really also determine what
// kind of visual effect to generate for a vehicle (default, steam, diesel, electric).
// Same goes for the callback result, which atm is only used to check if a wagon is powered.
byte shorten_factor; // length on main map for this type is 8 - shorten_factor
byte user_def_data; ///! Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles
byte cargo_type;
} RailVehicleInfo;
typedef struct ShipVehicleInfo {
byte image_index;
byte base_cost;
uint16 max_speed;
CargoID cargo_type;
byte cargo_type;
uint16 capacity;
byte running_cost;
byte sfx;
byte refittable;
} ShipVehicleInfo;
// Aircraft subtypes
enum {
AIR_CTOL = 1, // Conventional Take Off and Landing, i.e. planes
AIR_FAST = 2
};
typedef struct AircraftVehicleInfo {
byte image_index;
byte base_cost;
@@ -66,51 +46,33 @@ typedef struct RoadVehicleInfo {
byte sfx;
byte max_speed;
byte capacity;
CargoID cargo_type;
byte cargo_type;
} RoadVehicleInfo;
/** Information about a vehicle
* @see table/engines.h
*/
typedef struct EngineInfo {
Date base_intro;
byte unk2; ///< Carriages have the highest bit set in this one
Year lifelength;
Year base_life;
byte load_amount;
byte railtype:4;
byte climates:4;
uint32 refit_mask;
byte refit_cost;
byte misc_flags;
byte callbackmask;
uint16 base_intro;
byte unk2;
byte lifelength;
byte base_life;
byte railtype_climates;
} EngineInfo;
typedef struct Engine {
Date intro_date;
Date age;
uint16 intro_date;
uint16 age;
uint16 reliability;
uint16 reliability_spd_dec;
uint16 reliability_start, reliability_max, reliability_final;
uint16 duration_phase_1, duration_phase_2, duration_phase_3;
byte lifelength;
byte flags;
byte preview_player;
PlayerID preview_player;
byte preview_wait;
byte railtype;
byte player_avail;
byte type; // type, ie VEH_Road, VEH_Train, etc. Same as in vehicle.h
PlayerID player_avail;
byte type; // type, ie VEH_Road, VEH_Train, etc. Same as in vehicle.h
} Engine;
/**
* EngineInfo.misc_flags is a bitmask, with the following values
*/
enum {
EF_RAIL_TILTS = 0, ///< Rail vehicle tilts in curves (unsupported)
EF_ROAD_TRAM = 0, ///< Road vehicle is a tram/light rail vehicle (unsup)
EF_USES_2CC = 1, ///< Vehicle uses two company colours
EF_RAIL_IS_MU = 2, ///< Rail vehicle is a multiple-unit (DMU/EMU)
};
enum {
RVI_MULTIHEAD = 1,
@@ -121,44 +83,112 @@ enum {
NUM_VEHICLE_TYPES = 6
};
enum {
INVALID_ENGINE = 0xFFFF,
};
void AddTypeToEngines(void);
void StartupEngines(void);
enum GlobalCargo {
GC_PASSENGERS = 0,
GC_COAL = 1,
GC_MAIL = 2,
GC_OIL = 3,
GC_LIVESTOCK = 4,
GC_GOODS = 5,
GC_GRAIN = 6, // GC_WHEAT / GC_MAIZE
GC_WOOD = 7,
GC_IRON_ORE = 8,
GC_STEEL = 9,
GC_VALUABLES = 10, // GC_GOLD / GC_DIAMONDS
GC_PAPER = 11,
GC_FOOD = 12,
GC_FRUIT = 13,
GC_COPPER_ORE = 14,
GC_WATER = 15,
GC_RUBBER = 16,
GC_SUGAR = 17,
GC_TOYS = 18,
GC_BATTERIES = 19,
GC_CANDY = 20,
GC_TOFFEE = 21,
GC_COLA = 22,
GC_COTTON_CANDY = 23,
GC_BUBBLES = 24,
GC_PLASTIC = 25,
GC_FIZZY_DRINKS = 26,
GC_PAPER_TEMP = 27,
GC_UNDEFINED = 28, // undefined; unused slot in arctic climate
GC_DEFAULT = 29,
GC_PURCHASE = 30,
GC_INVALID = 255,
NUM_GLOBAL_CID = 31
};
void DrawTrainEngine(int x, int y, EngineID engine, uint32 image_ormod);
void DrawRoadVehEngine(int x, int y, EngineID engine, uint32 image_ormod);
void DrawShipEngine(int x, int y, EngineID engine, uint32 image_ormod);
void DrawAircraftEngine(int x, int y, EngineID engine, uint32 image_ormod);
VARDEF const uint32 _default_refitmasks[NUM_VEHICLE_TYPES];
VARDEF const CargoID _global_cargo_id[NUM_LANDSCAPE][NUM_CARGO];
VARDEF const uint32 _landscape_global_cargo_mask[NUM_LANDSCAPE];
VARDEF const CargoID _local_cargo_id_ctype[NUM_GLOBAL_CID];
VARDEF uint32 _engine_refit_masks[256];
VARDEF byte _engine_original_sprites[256];
void SetWagonOverrideSprites(byte engine, struct SpriteGroup *group, byte *train_id, int trains);
void SetCustomEngineSprites(byte engine, byte cargo, struct SpriteGroup *group);
// loaded is in percents, overriding_engine 0xffff is none
int GetCustomEngineSprite(byte engine, const Vehicle *v, byte direction);
#define GetCustomVehicleSprite(v, direction) GetCustomEngineSprite(v->engine_type, v, direction)
#define GetCustomVehicleIcon(et, direction) GetCustomEngineSprite(et, NULL, direction)
typedef enum VehicleTrigger {
VEHICLE_TRIGGER_NEW_CARGO = 1,
// Externally triggered only for the first vehicle in chain
VEHICLE_TRIGGER_DEPOT = 2,
// Externally triggered only for the first vehicle in chain, only if whole chain is empty
VEHICLE_TRIGGER_EMPTY = 4,
// Not triggered externally (called for the whole chain if we got NEW_CARGO)
VEHICLE_TRIGGER_ANY_NEW_CARGO = 8,
} VehicleTrigger;
void TriggerVehicle(Vehicle *veh, VehicleTrigger trigger);
void SetCustomEngineName(int engine, const char *name);
StringID GetCustomEngineName(int engine);
void DrawTrainEngine(int x, int y, int engine, uint32 image_ormod);
void DrawRoadVehEngine(int x, int y, int engine, uint32 image_ormod);
void DrawShipEngine(int x, int y, int engine, uint32 image_ormod);
void DrawAircraftEngine(int x, int y, int engine, uint32 image_ormod);
void DrawTrainEngineInfo(int engine, int x, int y, int maxw);
void DrawRoadVehEngineInfo(int engine, int x, int y, int maxw);
void DrawShipEngineInfo(int engine, int x, int y, int maxw);
void DrawAircraftEngineInfo(int engine, int x, int y, int maxw);
void AcceptEnginePreview(Engine *e, PlayerID player);
void LoadCustomEngineNames(void);
void DeleteCustomEngineNames(void);
bool IsEngineBuildable(EngineID engine, byte type, PlayerID player);
bool IsEngineBuildable(uint engine, byte type);
void UnInitNewgrEngines(void);
enum {
NUM_NORMAL_RAIL_ENGINES = 54,
NUM_MONORAIL_ENGINES = 30,
NUM_MAGLEV_ENGINES = 32,
NUM_TRAIN_ENGINES = NUM_NORMAL_RAIL_ENGINES + NUM_MONORAIL_ENGINES + NUM_MAGLEV_ENGINES,
NUM_ROAD_ENGINES = 88,
NUM_SHIP_ENGINES = 11,
NUM_AIRCRAFT_ENGINES = 41,
TOTAL_NUM_ENGINES = NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES + NUM_SHIP_ENGINES + NUM_AIRCRAFT_ENGINES,
AIRCRAFT_ENGINES_INDEX = NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES + NUM_SHIP_ENGINES,
SHIP_ENGINES_INDEX = NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES,
ROAD_ENGINES_INDEX = NUM_TRAIN_ENGINES,
NUM_MONORAIL_ENGINES = 30,
NUM_MAGLEV_ENGINES = 32,
NUM_TRAIN_ENGINES = NUM_NORMAL_RAIL_ENGINES + NUM_MONORAIL_ENGINES + NUM_MAGLEV_ENGINES,
NUM_ROAD_ENGINES = 88,
NUM_SHIP_ENGINES = 11,
NUM_AIRCRAFT_ENGINES = 41,
TOTAL_NUM_ENGINES = NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES + NUM_SHIP_ENGINES + NUM_AIRCRAFT_ENGINES,
AIRCRAFT_ENGINES_INDEX = NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES + NUM_SHIP_ENGINES,
SHIP_ENGINES_INDEX = NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES,
ROAD_ENGINES_INDEX = NUM_TRAIN_ENGINES,
};
VARDEF Engine _engines[TOTAL_NUM_ENGINES];
#define FOR_ALL_ENGINES(e) for (e = _engines; e != endof(_engines); e++)
static inline Engine* GetEngine(EngineID i)
#define DEREF_ENGINE(i) (GetEngine(i))
static inline Engine* GetEngine(uint i)
{
assert(i < lengthof(_engines));
return &_engines[i];
assert(i < lengthof(_engines));
return &_engines[i];
}
VARDEF StringID _engine_name_strings[TOTAL_NUM_ENGINES];
@@ -170,139 +200,34 @@ static inline bool IsEngineIndex(uint index)
/* Access Vehicle Data */
//#include "table/engines.h"
extern const EngineInfo orig_engine_info[TOTAL_NUM_ENGINES];
extern const RailVehicleInfo orig_rail_vehicle_info[NUM_TRAIN_ENGINES];
extern const ShipVehicleInfo orig_ship_vehicle_info[NUM_SHIP_ENGINES];
extern const AircraftVehicleInfo orig_aircraft_vehicle_info[NUM_AIRCRAFT_ENGINES];
extern const RoadVehicleInfo orig_road_vehicle_info[NUM_ROAD_ENGINES];
extern EngineInfo _engine_info[TOTAL_NUM_ENGINES];
extern RailVehicleInfo _rail_vehicle_info[NUM_TRAIN_ENGINES];
extern ShipVehicleInfo _ship_vehicle_info[NUM_SHIP_ENGINES];
extern AircraftVehicleInfo _aircraft_vehicle_info[NUM_AIRCRAFT_ENGINES];
extern RoadVehicleInfo _road_vehicle_info[NUM_ROAD_ENGINES];
static inline const EngineInfo *EngInfo(EngineID e)
{
assert(e < lengthof(_engine_info));
return &_engine_info[e];
}
static inline const RailVehicleInfo* RailVehInfo(EngineID e)
static inline RailVehicleInfo *RailVehInfo(uint e)
{
assert(e < lengthof(_rail_vehicle_info));
return &_rail_vehicle_info[e];
}
static inline const ShipVehicleInfo* ShipVehInfo(EngineID e)
static inline ShipVehicleInfo *ShipVehInfo(uint e)
{
assert(e >= SHIP_ENGINES_INDEX && e < SHIP_ENGINES_INDEX + lengthof(_ship_vehicle_info));
assert(e - SHIP_ENGINES_INDEX < lengthof(_ship_vehicle_info));
return &_ship_vehicle_info[e - SHIP_ENGINES_INDEX];
}
static inline const AircraftVehicleInfo* AircraftVehInfo(EngineID e)
static inline AircraftVehicleInfo *AircraftVehInfo(uint e)
{
assert(e >= AIRCRAFT_ENGINES_INDEX && e < AIRCRAFT_ENGINES_INDEX + lengthof(_aircraft_vehicle_info));
assert(e - AIRCRAFT_ENGINES_INDEX < lengthof(_aircraft_vehicle_info));
return &_aircraft_vehicle_info[e - AIRCRAFT_ENGINES_INDEX];
}
static inline const RoadVehicleInfo* RoadVehInfo(EngineID e)
static inline RoadVehicleInfo *RoadVehInfo(uint e)
{
assert(e >= ROAD_ENGINES_INDEX && e < ROAD_ENGINES_INDEX + lengthof(_road_vehicle_info));
assert(e - ROAD_ENGINES_INDEX < lengthof(_road_vehicle_info));
return &_road_vehicle_info[e - ROAD_ENGINES_INDEX];
}
/************************************************************************
* Engine Replacement stuff
************************************************************************/
/**
* Struct to store engine replacements. DO NOT USE outside of engine.c. Is
* placed here so the only exception to this rule, the saveload code, can use
* it.
*/
struct EngineRenew {
EngineRenewID index;
EngineID from;
EngineID to;
struct EngineRenew *next;
};
typedef struct EngineRenew EngineRenew;
/**
* Memory pool for engine renew elements. DO NOT USE outside of engine.c. Is
* placed here so the only exception to this rule, the saveload code, can use
* it.
*/
DECLARE_OLD_POOL(EngineRenew, EngineRenew, 3, 8000)
/**
* Check if a EngineRenew really exists.
*/
static inline bool IsValidEngineRenew(const EngineRenew *er)
{
return er->from != INVALID_ENGINE;
}
static inline void DeleteEngineRenew(EngineRenew *er)
{
er->from = INVALID_ENGINE;
}
#define FOR_ALL_ENGINE_RENEWS_FROM(er, start) for (er = GetEngineRenew(start); er != NULL; er = (er->index + 1U < GetEngineRenewPoolSize()) ? GetEngineRenew(er->index + 1U) : NULL) if (er->from != INVALID_ENGINE) if (IsValidEngineRenew(er))
#define FOR_ALL_ENGINE_RENEWS(er) FOR_ALL_ENGINE_RENEWS_FROM(er, 0)
/**
* A list to group EngineRenew directives together (such as per-player).
*/
typedef EngineRenew* EngineRenewList;
/**
* Remove all engine replacement settings for the player.
* @param er The renewlist for a given player.
* @return The new renewlist for the player.
*/
void RemoveAllEngineReplacement(EngineRenewList* erl);
/**
* Retrieve the engine replacement in a given renewlist for an original engine type.
* @param erl The renewlist to search in.
* @param engine Engine type to be replaced.
* @return The engine type to replace with, or INVALID_ENGINE if no
* replacement is in the list.
*/
EngineID EngineReplacement(EngineRenewList erl, EngineID engine);
/**
* Add an engine replacement to the given renewlist.
* @param erl The renewlist to add to.
* @param old_engine The original engine type.
* @param new_engine The replacement engine type.
* @param flags The calling command flags.
* @return 0 on success, CMD_ERROR on failure.
*/
int32 AddEngineReplacement(EngineRenewList* erl, EngineID old_engine, EngineID new_engine, uint32 flags);
/**
* Remove an engine replacement from a given renewlist.
* @param erl The renewlist from which to remove the replacement
* @param engine The original engine type.
* @param flags The calling command flags.
* @return 0 on success, CMD_ERROR on failure.
*/
int32 RemoveEngineReplacement(EngineRenewList* erl, EngineID engine, uint32 flags);
/* Engine list manipulators - current implementation is only C wrapper of CBlobT<EngineID> class (helpers.cpp) */
void EngList_Create(EngineList *el); ///< Creates engine list
void EngList_Destroy(EngineList *el); ///< Deallocate and destroy engine list
uint EngList_Count(const EngineList *el); ///< Returns number of items in the engine list
void EngList_Add(EngineList *el, EngineID eid); ///< Append one item at the end of engine list
EngineID* EngList_Items(EngineList *el); ///< Returns engine list items as C array
void EngList_RemoveAll(EngineList *el); ///< Removes all items from engine list
typedef int CDECL EngList_SortTypeFunction(const void*, const void*); ///< argument type for EngList_Sort()
void EngList_Sort(EngineList *el, EngList_SortTypeFunction compare); ///< qsort of the engine list
void EngList_SortPartial(EngineList *el, EngList_SortTypeFunction compare, uint begin, uint num_items); ///< qsort of specified portion of the engine list
#endif /* ENGINE_H */
#endif

View File

@@ -1,10 +1,6 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "table/strings.h"
#include "table/sprites.h"
#include "functions.h"
#include "window.h"
#include "gui.h"
#include "viewport.h"
@@ -12,89 +8,89 @@
#include "engine.h"
#include "command.h"
#include "news.h"
#include "variables.h"
#include "newgrf_engine.h"
#include "vehicle.h"
static StringID GetEngineCategoryName(EngineID engine)
static StringID GetEngineCategoryName(byte 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:
switch (GetEngine(engine)->railtype) {
default: NOT_REACHED();
case RAILTYPE_RAIL: return STR_8102_RAILROAD_LOCOMOTIVE;
case RAILTYPE_ELECTRIC: return STR_8102_RAILROAD_LOCOMOTIVE;
case RAILTYPE_MONO: return STR_8106_MONORAIL_LOCOMOTIVE;
case RAILTYPE_MAGLEV: return STR_8107_MAGLEV_LOCOMOTIVE;
}
if (engine < NUM_TRAIN_ENGINES) {
switch (_engines[engine].railtype) {
case 0:
return STR_8102_RAILROAD_LOCOMOTIVE;
case 1:
return STR_8106_MONORAIL_LOCOMOTIVE;
case 2:
return STR_8107_MAGLEV_LOCOMOTIVE;
}
}
if (engine < NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES)
return STR_8103_ROAD_VEHICLE;
if (engine < NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES + NUM_SHIP_ENGINES)
return STR_8105_SHIP;
return STR_8104_AIRCRAFT;
}
static const Widget _engine_preview_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, 5, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_TEXTBTN, RESIZE_NONE, 5, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, 5, 11, 299, 0, 13, STR_8100_MESSAGE_FROM_VEHICLE_MANUFACTURE, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, 5, 0, 299, 14, 191, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, 5, 85, 144, 172, 183, STR_00C9_NO, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, 5, 155, 214, 172, 183, STR_00C8_YES, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, 5, 0, 299, 14, 191, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, 5, 85, 144, 172, 183, STR_00C9_NO, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, 5, 155, 214, 172, 183, STR_00C8_YES, STR_NULL},
{ WIDGETS_END},
};
typedef void DrawEngineProc(int x, int y, EngineID engine, uint32 image_ormod);
typedef void DrawEngineInfoProc(EngineID, int x, int y, int maxw);
typedef void DrawEngineProc(int x, int y, int engine, uint32 image_ormod);
typedef void DrawEngineInfoProc(int x, int y, int engine, int maxw);
typedef struct DrawEngineInfo {
DrawEngineProc *engine_proc;
DrawEngineInfoProc *info_proc;
} DrawEngineInfo;
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 },
{DrawTrainEngine,DrawTrainEngineInfo},
{DrawRoadVehEngine,DrawRoadVehEngineInfo},
{DrawShipEngine,DrawShipEngineInfo},
{DrawAircraftEngine,DrawAircraftEngineInfo},
};
static void EnginePreviewWndProc(Window *w, WindowEvent *e)
{
switch (e->event) {
case WE_PAINT: {
EngineID engine = w->window_number;
const DrawEngineInfo* dei;
int width;
byte eng;
int engine;
const DrawEngineInfo *dei;
int width;
switch(e->event) {
case WE_PAINT:
DrawWindowWidgets(w);
engine = w->window_number;
SetDParam(0, GetEngineCategoryName(engine));
DrawStringMultiCenter(150, 44, STR_8101_WE_HAVE_JUST_DESIGNED_A, 296);
DrawStringCentered(w->width >> 1, 80, GetCustomEngineName(engine), 0x10);
dei = &_draw_engine_list[GetEngine(engine)->type - VEH_Train];
eng = (byte)engine;
(dei = _draw_engine_list,eng < NUM_TRAIN_ENGINES) ||
(dei++,eng < NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES) ||
(dei++,eng < NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES + NUM_SHIP_ENGINES) ||
(dei++, true);
width = w->width;
dei->engine_proc(width >> 1, 100, engine, 0);
dei->info_proc(engine, width >> 1, 130, width - 52);
break;
}
case WE_CLICK:
switch (e->we.click.widget) {
case 4:
DoCommandP(0, w->window_number, 0, NULL, CMD_WANT_ENGINE_PREVIEW);
/* Fallthrough */
case 3:
DeleteWindow(w);
break;
switch(e->click.widget) {
case 3: DeleteWindow(w); break;
case 4:
DoCommandP(0, w->window_number, 0, NULL, CMD_WANT_ENGINE_PREVIEW);
DeleteWindow(w);
break;
}
break;
}
@@ -109,92 +105,119 @@ static const WindowDesc _engine_preview_desc = {
};
void ShowEnginePreviewWindow(EngineID engine)
void ShowEnginePreviewWindow(int engine)
{
AllocateWindowDescFront(&_engine_preview_desc, engine);
Window *w;
w = AllocateWindowDesc(&_engine_preview_desc);
w->window_number = engine;
}
static void DrawTrainEngineInfo(EngineID engine, int x, int y, int maxw)
void DrawNewsNewTrainAvail(Window *w)
{
const RailVehicleInfo *rvi = RailVehInfo(engine);
uint multihead = (rvi->flags & RVI_MULTIHEAD) ? 1 : 0;
SetDParam(0, (_price.build_railvehicle >> 3) * rvi->base_cost >> 5);
SetDParam(2, rvi->max_speed);
SetDParam(3, rvi->power << multihead);
SetDParam(1, rvi->weight << multihead);
SetDParam(4, rvi->running_cost_base * _price.running_rail[rvi->running_cost_class] >> 8 << multihead);
if (rvi->capacity != 0) {
SetDParam(5, rvi->cargo_type);
SetDParam(6, rvi->capacity << multihead);
} 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 AircraftVehicleInfo *avi = AircraftVehInfo(engine);
SetDParam(0, (_price.aircraft_base >> 3) * avi->base_cost >> 5);
SetDParam(1, avi->max_speed * 128 / 10);
SetDParam(2, avi->passenger_capacity);
SetDParam(3, avi->mail_capacity);
SetDParam(4, avi->running_cost * _price.aircraft_running >> 8);
DrawStringMultiCenter(x, y, STR_A02E_COST_MAX_SPEED_CAPACITY, maxw);
}
static void DrawRoadVehEngineInfo(EngineID engine, int x, int y, int maxw)
{
const RoadVehicleInfo *rvi = RoadVehInfo(engine);
SetDParam(0, (_price.roadveh_base >> 3) * rvi->base_cost >> 5);
SetDParam(1, rvi->max_speed / 2);
SetDParam(2, rvi->running_cost * _price.roadveh_running >> 8);
SetDParam(3, rvi->cargo_type);
SetDParam(4, rvi->capacity);
DrawStringMultiCenter(x, y, STR_902A_COST_SPEED_RUNNING_COST, maxw);
}
static void DrawShipEngineInfo(EngineID engine, int x, int y, int maxw)
{
const ShipVehicleInfo *svi = ShipVehInfo(engine);
SetDParam(0, svi->base_cost * (_price.ship_base >> 3) >> 5);
SetDParam(1, svi->max_speed / 2);
SetDParam(2, svi->cargo_type);
SetDParam(3, svi->capacity);
SetDParam(4, svi->running_cost * _price.ship_running >> 8);
DrawStringMultiCenter(x, y, STR_982E_COST_MAX_SPEED_CAPACITY, maxw);
}
StringID GetNewsStringNewVehicleAvail(const NewsItem *ni)
{
EngineID engine = ni->string_id;
SetDParam(0, GetEngineCategoryName(engine));
SetDParam(1, GetCustomEngineName(engine));
return STR_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE;
}
void DrawNewsNewVehicleAvail(Window *w)
{
EngineID engine = WP(w, news_d).ni->string_id;
const DrawEngineInfo *dei = &_draw_engine_list[GetEngine(engine)->type - VEH_Train];
int engine;
DrawNewsBorder(w);
engine = WP(w,news_d).ni->string_id;
SetDParam(0, GetEngineCategoryName(engine));
DrawStringMultiCenter(w->width >> 1, 20, STR_NEW_VEHICLE_NOW_AVAILABLE, w->width - 2);
DrawStringMultiCenter(w->width >> 1, 20, STR_8859_NEW_NOW_AVAILABLE, w->width - 2);
GfxFillRect(25, 56, w->width - 25, w->height - 2, 10);
SetDParam(0, GetCustomEngineName(engine));
DrawStringMultiCenter(w->width >> 1, 57, STR_NEW_VEHICLE_TYPE, w->width - 2);
DrawStringMultiCenter(w->width >> 1, 57, STR_885A, w->width - 2);
dei->engine_proc(w->width >> 1, 88, engine, 0);
GfxFillRect(25, 56, w->width - 56, 112, 0x323 | USE_COLORTABLE);
dei->info_proc(engine, w->width >> 1, 129, w->width - 52);
DrawTrainEngine(w->width >> 1, 88, engine, 0);
GfxFillRect(25, 56, w->width - 56, 112, 0x4323);
DrawTrainEngineInfo(engine, w->width >> 1, 129, w->width - 52);
}
StringID GetNewsStringNewTrainAvail(NewsItem *ni)
{
int engine = ni->string_id;
SetDParam(0, STR_8859_NEW_NOW_AVAILABLE);
SetDParam(1, GetEngineCategoryName(engine));
SetDParam(2, GetCustomEngineName(engine));
return STR_02B6;
}
void DrawNewsNewAircraftAvail(Window *w)
{
int engine;
DrawNewsBorder(w);
engine = WP(w,news_d).ni->string_id;
DrawStringMultiCenter(w->width >> 1, 20, STR_A02C_NEW_AIRCRAFT_NOW_AVAILABLE, w->width - 2);
GfxFillRect(25, 56, w->width - 25, w->height - 2, 10);
SetDParam(0, GetCustomEngineName(engine));
DrawStringMultiCenter(w->width >> 1, 57, STR_A02D, w->width - 2);
DrawAircraftEngine(w->width >> 1, 93, engine, 0);
GfxFillRect(25, 56, w->width - 56, 110, 0x4323);
DrawAircraftEngineInfo(engine, w->width >> 1, 131, w->width - 52);
}
StringID GetNewsStringNewAircraftAvail(NewsItem *ni)
{
int engine = ni->string_id;
SetDParam(0, STR_A02C_NEW_AIRCRAFT_NOW_AVAILABLE);
SetDParam(1, GetCustomEngineName(engine));
return STR_02B6;
}
void DrawNewsNewRoadVehAvail(Window *w)
{
int engine;
DrawNewsBorder(w);
engine = WP(w,news_d).ni->string_id;
DrawStringMultiCenter(w->width >> 1, 20, STR_9028_NEW_ROAD_VEHICLE_NOW_AVAILABLE, w->width - 2);
GfxFillRect(25, 56, w->width - 25, w->height - 2, 10);
SetDParam(0, GetCustomEngineName(engine));
DrawStringMultiCenter(w->width >> 1, 57, STR_9029, w->width - 2);
DrawRoadVehEngine(w->width >> 1, 88, engine, 0);
GfxFillRect(25, 56, w->width - 56, 112, 0x4323);
DrawRoadVehEngineInfo(engine, w->width >> 1, 129, w->width - 52);
}
StringID GetNewsStringNewRoadVehAvail(NewsItem *ni)
{
int engine = ni->string_id;
SetDParam(0, STR_9028_NEW_ROAD_VEHICLE_NOW_AVAILABLE);
SetDParam(1, GetCustomEngineName(engine));
return STR_02B6;
}
void DrawNewsNewShipAvail(Window *w)
{
int engine;
DrawNewsBorder(w);
engine = WP(w,news_d).ni->string_id;
DrawStringMultiCenter(w->width >> 1, 20, STR_982C_NEW_SHIP_NOW_AVAILABLE, w->width - 2);
GfxFillRect(25, 56, w->width - 25, w->height - 2, 10);
SetDParam(0, GetCustomEngineName(engine));
DrawStringMultiCenter(w->width >> 1, 57, STR_982D, w->width - 2);
DrawShipEngine(w->width >> 1, 93, engine, 0);
GfxFillRect(25, 56, w->width - 56, 110, 0x4323);
DrawShipEngineInfo(engine, w->width >> 1, 131, w->width - 52);
}
StringID GetNewsStringNewShipAvail(NewsItem *ni)
{
int engine = ni->string_id;
SetDParam(0, STR_982C_NEW_SHIP_NOW_AVAILABLE);
SetDParam(1, GetCustomEngineName(engine));
return STR_02B6;
}

View File

@@ -1,13 +1,11 @@
/* $Id$ */
#ifndef __BEOS__
#ifndef __MORPHOS__
#include "../stdafx.h"
#include "../openttd.h"
#include "../sound.h"
#include "../string.h"
#include "../variables.h"
#include "../debug.h"
#include "extmidi.h"
#include "stdafx.h"
#include "ttd.h"
#include "hal.h"
#include "sound.h"
#include "string.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
@@ -18,7 +16,7 @@
static struct {
char song[MAX_PATH];
pid_t pid;
int pid;
} _midi;
static void DoPlay(void);
@@ -59,7 +57,7 @@ static bool ExtMidiIsPlaying(void)
static void ExtMidiSetVolume(byte vol)
{
DEBUG(driver, 1) ("extmidi: set volume not implemented");
fprintf(stderr, "extmidi: set volume not implemented\n");
}
static void DoPlay(void)
@@ -70,19 +68,23 @@ static void DoPlay(void)
int d;
close(0);
close(1);
close(2);
d = open("/dev/null", O_RDONLY);
if (d != -1 && dup2(d, 1) != -1 && dup2(d, 2) != -1) {
#if defined(MIDI_ARG)
execlp(msf.extmidi, "extmidi", MIDI_ARG, _midi.song, (char*)0);
#else
execlp(msf.extmidi, "extmidi", _midi.song, (char*)0);
#endif
if (d != -1) {
if (dup2(d, 1) != -1 && dup2(d, 2) != -1) {
#if defined(MIDI_ARG)
execlp(msf.extmidi, "extmidi", MIDI_ARG, _midi.song, NULL);
#else
execlp(msf.extmidi, "extmidi", _midi.song, NULL);
#endif
}
}
_exit(1);
exit(1);
}
case -1:
DEBUG(driver, 0) ("extmidi: couldn't fork: %s", strerror(errno));
fprintf(stderr, "extmidi: couldn't fork: %s\n", strerror(errno));
/* FALLTHROUGH */
default:
@@ -106,3 +108,4 @@ const HalMusicDriver _extmidi_music_driver = {
};
#endif /* __MORPHOS__ */
#endif /* __BEOS__ */

109
fileio.c
View File

@@ -1,12 +1,9 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "ttd.h"
#include "fileio.h"
#include "functions.h"
#include "string.h"
#include "macros.h"
#include "variables.h"
#if defined(UNIX) || defined(__OS2__)
#include <ctype.h> // required for tolower()
#endif
/*************************************************/
/* FILE IO ROUTINES ******************************/
@@ -15,11 +12,11 @@
#define FIO_BUFFER_SIZE 512
typedef struct {
byte *buffer, *buffer_end; ///< position pointer in local buffer and last valid byte of buffer
uint32 pos; ///< current (system) position in file
FILE *cur_fh; ///< current file handle
FILE *handles[64]; ///< array of file handles we can have open
byte buffer_start[FIO_BUFFER_SIZE]; ///< local buffer when read from file
byte *buffer, *buffer_end;
uint32 pos;
FILE *cur_fh;
FILE *handles[32];
byte buffer_start[512];
} Fio;
static Fio _fio;
@@ -34,8 +31,7 @@ void FioSeekTo(uint32 pos, int mode)
{
if (mode == SEEK_CUR) pos += FioGetPos();
_fio.buffer = _fio.buffer_end = _fio.buffer_start + FIO_BUFFER_SIZE;
_fio.pos = pos;
fseek(_fio.cur_fh, _fio.pos, SEEK_SET);
fseek(_fio.cur_fh, (_fio.pos=pos), SEEK_SET);
}
// Seek to a file and a position
@@ -44,7 +40,7 @@ void FioSeekToFile(uint32 pos)
FILE *f = _fio.handles[pos >> 24];
assert(f != NULL);
_fio.cur_fh = f;
FioSeekTo(GB(pos, 0, 24), SEEK_SET);
FioSeekTo(pos & 0xFFFFFF, SEEK_SET);
}
byte FioReadByte(void)
@@ -58,7 +54,7 @@ byte FioReadByte(void)
void FioSkipBytes(int n)
{
for (;;) {
for(;;) {
int m = min(_fio.buffer_end - _fio.buffer, n);
_fio.buffer += m;
n -= m;
@@ -68,6 +64,7 @@ void FioSkipBytes(int n)
}
}
uint16 FioReadWord(void)
{
byte b = FioReadByte();
@@ -103,66 +100,76 @@ void FioCloseAll(void)
FioCloseFile(i);
}
bool FioCheckFileExists(const char *filename)
{
FILE *f = FioFOpenFile(filename);
if (f == NULL) return false;
fclose(f);
return true;
}
FILE *FioFOpenFile(const char *filename)
bool FiosCheckFileExists(const char *filename)
{
FILE *f;
char buf[MAX_PATH];
snprintf(buf, lengthof(buf), "%s%s", _paths.data_dir, filename);
sprintf(buf, "%s%s", _path.data_dir, filename);
f = fopen(buf, "rb");
#if !defined(WIN32)
if (f == NULL) {
strtolower(buf + strlen(_paths.data_dir) - 1);
char *s;
// Make lower case and try again
for(s=buf + strlen(_path.data_dir) - 1; *s != 0; s++)
*s = tolower(*s);
f = fopen(buf, "rb");
#if defined SECOND_DATA_DIR
// tries in the 2nd data directory
// tries in the 2nd data directory
if (f == NULL) {
snprintf(buf, lengthof(buf), "%s%s", _paths.second_data_dir, filename);
strtolower(buf + strlen(_paths.second_data_dir) - 1);
f = fopen(buf, "rb");
sprintf(buf, "%s%s", _path.second_data_dir, filename);
for(s=buf + strlen(_path.second_data_dir) - 1; *s != 0; s++)
*s = tolower(*s);
f = fopen(buf, "rb");
}
#endif
}
#endif
return f;
if (f == NULL)
return false;
else {
fclose(f);
return true;
}
}
void FioOpenFile(int slot, const char *filename)
{
FILE *f = FioFOpenFile(filename);
FILE *f;
char buf[MAX_PATH];
if (f == NULL) error("Cannot open file '%s%s'", _paths.data_dir, filename);
sprintf(buf, "%s%s", _path.data_dir, filename);
f = fopen(buf, "rb");
#if !defined(WIN32)
if (f == NULL) {
char *s;
// Make lower case and try again
for(s=buf + strlen(_path.data_dir) - 1; *s != 0; s++)
*s = tolower(*s);
f = fopen(buf, "rb");
#if defined SECOND_DATA_DIR
// tries in the 2nd data directory
if (f == NULL) {
sprintf(buf, "%s%s", _path.second_data_dir, filename);
for(s=buf + strlen(_path.second_data_dir) - 1; *s != 0; s++)
*s = tolower(*s);
f = fopen(buf, "rb");
}
#endif
}
#endif
if (f == NULL)
error("Cannot open file '%s'", buf);
FioCloseFile(slot); // if file was opened before, close it
_fio.handles[slot] = f;
FioSeekToFile(slot << 24);
}
/**
* Sanitizes a filename, i.e. removes all illegal characters from it.
* @param filename the "\0" terminated filename
*/
void SanitizeFilename(char *filename)
{
for (; *filename != '\0'; filename++) {
switch (*filename) {
/* The following characters are not allowed in filenames
* on at least one of the supported operating systems: */
case ':': case '\\': case '*': case '?': case '/': case '<': case '>': case '|': case '"':
*filename = '_';
break;
}
}
}

View File

@@ -1,5 +1,3 @@
/* $Id$ */
#ifndef FILEIO_H
#define FILEIO_H
@@ -10,11 +8,9 @@ byte FioReadByte(void);
uint16 FioReadWord(void);
uint32 FioReadDword(void);
void FioCloseAll(void);
FILE *FioFOpenFile(const char *filename);
void FioOpenFile(int slot, const char *filename);
void FioReadBlock(void *ptr, uint size);
void FioSkipBytes(int n);
bool FioCheckFileExists(const char *filename);
void SanitizeFilename(char *filename);
bool FiosCheckFileExists(const char *filename);
#endif /* FILEIO_H */

415
fios.c
View File

@@ -1,415 +0,0 @@
/* $Id$ */
/** @file fios.c
* This file contains functions for building file lists for the save/load dialogs.
*/
#include "stdafx.h"
#include "openttd.h"
#include "hal.h"
#include "string.h"
#include "variables.h"
#include "functions.h"
#include "heightmap.h"
#include "table/strings.h"
#include "fios.h"
#include <sys/types.h>
#include <sys/stat.h>
#ifdef WIN32
# include <tchar.h>
# include <io.h>
#else
# include <unistd.h>
#endif /* WIN32 */
/* Variables to display file lists */
int _fios_num;
static char *_fios_path;
static FiosItem *_fios_items;
static int _fios_count, _fios_alloc;
/* OS-specific functions are taken from their respective files (win32/unix/os2 .c) */
extern bool FiosIsRoot(const char *path);
extern bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb);
extern bool FiosIsHiddenFile(const struct dirent *ent);
extern void FiosGetDrives(void);
extern bool FiosGetDiskFreeSpace(const char *path, uint32 *tot);
/* get the name of an oldstyle savegame */
extern void GetOldSaveGameName(char *title, const char *path, const char *file);
/**
* Allocate a new FiosItem.
* @return A pointer to the newly allocated FiosItem.
*/
FiosItem *FiosAlloc(void)
{
if (_fios_count == _fios_alloc) {
_fios_alloc += 256;
_fios_items = realloc(_fios_items, _fios_alloc * sizeof(FiosItem));
}
return &_fios_items[_fios_count++];
}
/**
* Compare two FiosItem's. Used with qsort when sorting the file list.
* @param a A pointer to the first FiosItem to compare.
* @param a A pointer to the second FiosItem to compare.
* @return -1, 0 or 1, depending on how the two items should be sorted.
*/
int CDECL compare_FiosItems(const void *a, const void *b)
{
const FiosItem *da = (const FiosItem *)a;
const FiosItem *db = (const FiosItem *)b;
int r;
if (_savegame_sort_order & SORT_BY_NAME) {
r = strcasecmp(da->title, db->title);
} else {
r = da->mtime < db->mtime ? -1 : 1;
}
if (_savegame_sort_order & SORT_DESCENDING) r = -r;
return r;
}
/**
* Free the list of savegames
*/
void FiosFreeSavegameList(void)
{
free(_fios_items);
_fios_items = NULL;
_fios_alloc = _fios_count = 0;
}
/**
* Get descriptive texts. Returns the path and free space
* left on the device
* @param path string describing the path
* @param total_free total free space in megabytes, optional (can be NULL)
* @return StringID describing the path (free space or failure)
*/
StringID FiosGetDescText(const char **path, uint32 *total_free)
{
*path = _fios_path;
return FiosGetDiskFreeSpace(*path, total_free) ? STR_4005_BYTES_FREE : STR_4006_UNABLE_TO_READ_DRIVE;
}
/* Browse to a new path based on the passed FiosItem struct
* @param *item FiosItem object telling us what to do
* @return a string if we have given a file as a target, otherwise NULL */
char *FiosBrowseTo(const FiosItem *item)
{
char *s;
char *path = _fios_path;
switch (item->type) {
#if defined(WIN32) || defined(__OS2__)
case FIOS_TYPE_DRIVE: sprintf(path, "%c:" PATHSEP, item->title[0]); break;
#endif
case FIOS_TYPE_PARENT:
/* Check for possible NULL ptr (not required for UNIXes, but AmigaOS-alikes) */
if ((s = strrchr(path, PATHSEPCHAR)) != NULL) {
s[1] = '\0'; // go up a directory
if (!FiosIsRoot(path)) s[0] = '\0';
}
#if defined(__MORPHOS__) || defined(__AMIGAOS__)
/* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
else if ((s = strrchr(path, ':')) != NULL) s[1] = '\0';
#endif
break;
case FIOS_TYPE_DIR:
if (!FiosIsRoot(path)) strcat(path, PATHSEP);
strcat(path, item->name);
break;
case FIOS_TYPE_DIRECT:
sprintf(path, "%s" PATHSEP, item->name);
s = strrchr(path, PATHSEPCHAR);
if (s != NULL && s[1] == '\0') s[0] = '\0'; // strip trailing slash
break;
case FIOS_TYPE_FILE:
case FIOS_TYPE_OLDFILE:
case FIOS_TYPE_SCENARIO:
case FIOS_TYPE_OLD_SCENARIO:
case FIOS_TYPE_PNG:
case FIOS_TYPE_BMP:
{
static char str_buffr[512];
#if defined(__MORPHOS__) || defined(__AMIGAOS__)
/* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
if (FiosIsRoot(path)) {
snprintf(str_buffr, lengthof(str_buffr), "%s:%s", path, item->name);
} else // XXX - only next line!
#endif
snprintf(str_buffr, lengthof(str_buffr), "%s" PATHSEP "%s", path, item->name);
return str_buffr;
}
}
return NULL;
}
void FiosMakeSavegameName(char *buf, const char *name, size_t size)
{
const char *extension, *period;
extension = (_game_mode == GM_EDITOR) ? ".scn" : ".sav";
/* Don't append the extension if it is already there */
period = strrchr(name, '.');
if (period != NULL && strcasecmp(period, extension) == 0) extension = "";
snprintf(buf, size, "%s" PATHSEP "%s%s", _fios_path, name, extension);
}
#if defined(WIN32)
# define unlink _tunlink
#endif
bool FiosDelete(const char *name)
{
char filename[512];
FiosMakeSavegameName(filename, name, lengthof(filename));
return unlink(OTTD2FS(filename)) == 0;
}
bool FileExists(const char *filename)
{
return access(filename, 0) == 0;
}
typedef byte fios_getlist_callback_proc(int mode, const char *filename, const char *ext, char *title);
/** Create a list of the files in a directory, according to some arbitrary rule.
* @param num Will be filled with the amount of items.
* @param mode The mode we are in. Some modes don't allow 'parent'.
* @param callback The function that is called where you need to do the filtering.
* @return Return the list of files. */
static FiosItem *FiosGetFileList(int mode, fios_getlist_callback_proc *callback_proc)
{
struct stat sb;
struct dirent *dirent;
DIR *dir;
FiosItem *fios;
int sort_start;
char d_name[sizeof(fios->name)];
/* A parent directory link exists if we are not in the root directory */
if (!FiosIsRoot(_fios_path) && mode != SLD_NEW_GAME) {
fios = FiosAlloc();
fios->type = FIOS_TYPE_PARENT;
fios->mtime = 0;
ttd_strlcpy(fios->name, "..", lengthof(fios->name));
ttd_strlcpy(fios->title, ".. (Parent directory)", lengthof(fios->title));
}
/* Show subdirectories */
if (mode != SLD_NEW_GAME && (dir = ttd_opendir(_fios_path)) != NULL) {
while ((dirent = readdir(dir)) != NULL) {
ttd_strlcpy(d_name, FS2OTTD(dirent->d_name), sizeof(d_name));
/* found file must be directory, but not '.' or '..' */
if (FiosIsValidFile(_fios_path, dirent, &sb) && (sb.st_mode & S_IFDIR) &&
(!FiosIsHiddenFile(dirent) || strncasecmp(d_name, PERSONAL_DIR, strlen(d_name)) == 0) &&
strcmp(d_name, ".") != 0 && strcmp(d_name, "..") != 0) {
fios = FiosAlloc();
fios->type = FIOS_TYPE_DIR;
fios->mtime = 0;
ttd_strlcpy(fios->name, d_name, lengthof(fios->name));
snprintf(fios->title, lengthof(fios->title), "%s" PATHSEP " (Directory)", d_name);
str_validate(fios->title);
}
}
closedir(dir);
}
/* Sort the subdirs always by name, ascending, remember user-sorting order */
{
byte order = _savegame_sort_order;
_savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING;
qsort(_fios_items, _fios_count, sizeof(FiosItem), compare_FiosItems);
_savegame_sort_order = order;
}
/* This is where to start sorting for the filenames */
sort_start = _fios_count;
/* Show files */
dir = ttd_opendir(_fios_path);
if (dir != NULL) {
while ((dirent = readdir(dir)) != NULL) {
char fios_title[64];
char *t;
byte type;
ttd_strlcpy(d_name, FS2OTTD(dirent->d_name), sizeof(d_name));
if (!FiosIsValidFile(_fios_path, dirent, &sb) || !(sb.st_mode & S_IFREG) || FiosIsHiddenFile(dirent)) continue;
/* File has no extension, skip it */
if ((t = strrchr(d_name, '.')) == NULL) continue;
fios_title[0] = '\0'; // reset the title;
type = callback_proc(mode, d_name, t, fios_title);
if (type != FIOS_TYPE_INVALID) {
fios = FiosAlloc();
fios->mtime = sb.st_mtime;
fios->type = type;
ttd_strlcpy(fios->name, d_name, lengthof(fios->name));
/* Some callbacks want to lookup the title of the file. Allow that.
* If we just copy the title from the filename, strip the extension */
t = (fios_title[0] == '\0') ? *t = '\0', d_name : fios_title;
ttd_strlcpy(fios->title, t, lengthof(fios->title));
str_validate(fios->title);
}
}
closedir(dir);
}
qsort(_fios_items + sort_start, _fios_count - sort_start, sizeof(FiosItem), compare_FiosItems);
/* Show drives */
if (mode != SLD_NEW_GAME) FiosGetDrives();
_fios_num = _fios_count;
return _fios_items;
}
/**
* Callback for FiosGetFileList. It tells if a file is a savegame or not.
* @param mode Save/load mode.
* @param file Name of the file to check.
* @param ext A pointer to the extension identifier inside file
* @param title Buffer if a callback wants to lookup the title of the file
* @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame
* @see FiosGetFileList
* @see FiosGetSavegameList
*/
static byte FiosGetSavegameListCallback(int mode, const char *file, const char *ext, char *title)
{
/* Show savegame files
* .SAV OpenTTD saved game
* .SS1 Transport Tycoon Deluxe preset game
* .SV1 Transport Tycoon Deluxe (Patch) saved game
* .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
if (strcasecmp(ext, ".sav") == 0) return FIOS_TYPE_FILE;
if (mode == SLD_LOAD_GAME || mode == SLD_LOAD_SCENARIO) {
if (strcasecmp(ext, ".ss1") == 0 || strcasecmp(ext, ".sv1") == 0 ||
strcasecmp(ext, ".sv2") == 0) {
GetOldSaveGameName(title, _fios_path, file);
return FIOS_TYPE_OLDFILE;
}
}
return FIOS_TYPE_INVALID;
}
/**
* Get a list of savegames.
* @param mode Save/load mode.
* @return A pointer to an array of FiosItem representing all the files to be shown in the save/load dialog.
* @see FiosGetFileList
*/
FiosItem *FiosGetSavegameList(int mode)
{
static char *_fios_save_path = NULL;
if (_fios_save_path == NULL) {
_fios_save_path = malloc(MAX_PATH);
ttd_strlcpy(_fios_save_path, _paths.save_dir, MAX_PATH);
}
_fios_path = _fios_save_path;
return FiosGetFileList(mode, &FiosGetSavegameListCallback);
}
/**
* Callback for FiosGetFileList. It tells if a file is a scenario or not.
* @param mode Save/load mode.
* @param file Name of the file to check.
* @param ext A pointer to the extension identifier inside file
* @param title Buffer if a callback wants to lookup the title of the file
* @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario
* @see FiosGetFileList
* @see FiosGetScenarioList
*/
static byte FiosGetScenarioListCallback(int mode, const char *file, const char *ext, char *title)
{
/* Show scenario files
* .SCN OpenTTD style scenario file
* .SV0 Transport Tycoon Deluxe (Patch) scenario
* .SS0 Transport Tycoon Deluxe preset scenario */
if (strcasecmp(ext, ".scn") == 0) return FIOS_TYPE_SCENARIO;
if (mode == SLD_LOAD_GAME || mode == SLD_LOAD_SCENARIO || mode == SLD_NEW_GAME) {
if (strcasecmp(ext, ".sv0") == 0 || strcasecmp(ext, ".ss0") == 0 ) {
GetOldSaveGameName(title, _fios_path, file);
return FIOS_TYPE_OLD_SCENARIO;
}
}
return FIOS_TYPE_INVALID;
}
/**
* Get a list of scenarios.
* @param mode Save/load mode.
* @return A pointer to an array of FiosItem representing all the files to be shown in the save/load dialog.
* @see FiosGetFileList
*/
FiosItem *FiosGetScenarioList(int mode)
{
static char *_fios_scn_path = NULL;
if (_fios_scn_path == NULL) {
_fios_scn_path = malloc(MAX_PATH);
ttd_strlcpy(_fios_scn_path, _paths.scenario_dir, MAX_PATH);
}
_fios_path = _fios_scn_path;
return FiosGetFileList(mode, &FiosGetScenarioListCallback);
}
static byte FiosGetHeightmapListCallback(int mode, const char *file, const char *ext, char *title)
{
/* Show heightmap files
* .PNG PNG Based heightmap files
* .BMP BMP Based heightmap files
*/
#ifdef WITH_PNG
if (strcasecmp(ext, ".png") == 0) return FIOS_TYPE_PNG;
#endif /* WITH_PNG */
if (strcasecmp(ext, ".bmp") == 0) return FIOS_TYPE_BMP;
return FIOS_TYPE_INVALID;
}
// Get a list of Heightmaps
FiosItem *FiosGetHeightmapList(int mode)
{
static char *_fios_hmap_path = NULL;
if (_fios_hmap_path == NULL) {
_fios_hmap_path = malloc(MAX_PATH);
strcpy(_fios_hmap_path, _paths.heightmap_dir);
}
_fios_path = _fios_hmap_path;
return FiosGetFileList(mode, &FiosGetHeightmapListCallback);
}

101
fios.h
View File

@@ -1,101 +0,0 @@
/* $Id$ */
#ifndef FIOS_H
#define FIOS_H
/* Deals with finding savegames */
typedef struct {
byte type;
uint64 mtime;
char title[64];
char name[256 - 12 - 64];
} FiosItem;
enum {
FIOS_TYPE_DRIVE = 0,
FIOS_TYPE_PARENT = 1,
FIOS_TYPE_DIR = 2,
FIOS_TYPE_FILE = 3,
FIOS_TYPE_OLDFILE = 4,
FIOS_TYPE_SCENARIO = 5,
FIOS_TYPE_OLD_SCENARIO = 6,
FIOS_TYPE_DIRECT = 7,
FIOS_TYPE_PNG = 8,
FIOS_TYPE_BMP = 9,
FIOS_TYPE_INVALID = 255,
};
/* Variables to display file lists */
extern FiosItem *_fios_list; // defined in misc_gui.c
extern int _fios_num; // defined in fios.c, read_only version of _fios_count
extern int _saveload_mode; // defined in misc_gui.c
// Get a list of savegames
FiosItem *FiosGetSavegameList(int mode);
// Get a list of scenarios
FiosItem *FiosGetScenarioList(int mode);
// Get a list of Heightmaps
FiosItem *FiosGetHeightmapList(int mode);
// Free the list of savegames
void FiosFreeSavegameList(void);
// Browse to. Returns a filename w/path if we reached a file.
char *FiosBrowseTo(const FiosItem *item);
// Return path, free space and stringID
StringID FiosGetDescText(const char **path, uint32 *total_free);
// Delete a name
bool FiosDelete(const char *name);
// Make a filename from a name
void FiosMakeSavegameName(char *buf, const char *name, size_t size);
// Allocate a new FiosItem
FiosItem *FiosAlloc(void);
int CDECL compare_FiosItems(const void *a, const void *b);
/* Implementation of opendir/readdir/closedir for Windows */
#if defined(WIN32)
#include <windows.h>
typedef struct DIR DIR;
typedef struct dirent { // XXX - only d_name implemented
TCHAR *d_name; /* name of found file */
/* little hack which will point to parent DIR struct which will
* save us a call to GetFileAttributes if we want information
* about the file (for example in function fio_bla */
DIR *dir;
} dirent;
struct DIR {
HANDLE hFind;
/* the dirent returned by readdir.
* note: having only one global instance is not possible because
* multiple independent opendir/readdir sequences must be supported. */
dirent ent;
WIN32_FIND_DATA fd;
/* since opendir calls FindFirstFile, we need a means of telling the
* first call to readdir that we already have a file.
* that's the case iff this is true */
bool at_first_entry;
};
DIR *opendir(const TCHAR *path);
struct dirent *readdir(DIR *d);
int closedir(DIR *d);
#else
/* Use system-supplied opendir/readdir/closedir functions */
# include <sys/types.h>
# include <dirent.h>
#endif /* defined(WIN32) */
/**
* A wrapper around opendir() which will convert the string from
* OPENTTD encoding to that of the filesystem. For all purposes this
* function behaves the same as the original opendir function
* @param path string to open directory of
* @return DIR pointer
*/
static inline DIR *ttd_opendir(const char *path)
{
return opendir(OTTD2FS(path));
}
#endif /* FIOS_H */

View File

@@ -1,522 +0,0 @@
/* $Id$ */
#include "stdafx.h"
#include "openttd.h"
#include "functions.h"
#include "macros.h"
#include "debug.h"
#include "table/sprites.h"
#include "table/control_codes.h"
#include "spritecache.h"
#include "gfx.h"
#include "string.h"
#include "fontcache.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 <tchar.h>
#include <shlobj.h> // SHGetFolderPath
#include "win32.h"
/* 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 = malloc(MAX_PATH * sizeof(TCHAR));
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));
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;
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;
}
#else
# ifdef 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;
}
# else
FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) {return FT_Err_Cannot_Open_Resource;}
# endif /* WITH_FONTCONFIG */
#endif
/**
* 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 (strlen(font_name) == 0) 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) ("[FreeType] 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(void)
{
if (strlen(_freetype.small_font) == 0 && strlen(_freetype.medium_font) == 0 && strlen(_freetype.large_font) == 0) {
DEBUG(freetype, 1) ("[FreeType] 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) ("[FreeType] 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 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;
}
}
typedef struct GlyphEntry {
Sprite *sprite;
byte width;
} GlyphEntry;
/* 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];
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) ("[FreeType] Allocating root glyph cache for size %u", size);
_glyph_ptr[size] = calloc(256, sizeof(**_glyph_ptr));
}
if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) {
DEBUG(freetype, 3) ("[FreeType] Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), size);
_glyph_ptr[size][GB(key, 8, 8)] = calloc(256, sizeof(***_glyph_ptr));
}
DEBUG(freetype, 4) ("[FreeType] 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;
}
const Sprite *GetGlyph(FontSize size, WChar key)
{
FT_Face face = GetFontFace(size);
FT_GlyphSlot slot;
GlyphEntry new_glyph;
GlyphEntry *glyph;
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);
}
/* Check for the glyph in our cache */
glyph = GetGlyphPtr(size, key);
if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;
slot = face->glyph;
FT_Load_Char(face, key, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_MONO);
/* 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 = calloc(width * height + 8, 1);
sprite->info = 1;
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 (HASBIT(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
sprite->data[1 + x + (1 + y) * sprite->width] = SHADOW_COLOUR;
}
}
}
}
for (y = 0; y < slot->bitmap.rows; y++) {
for (x = 0; x < slot->bitmap.width; x++) {
if (HASBIT(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
sprite->data[x + y * sprite->width] = FACE_COLOUR;
}
}
}
new_glyph.sprite = sprite;
new_glyph.width = (slot->advance.x >> 6) + (size != FS_NORMAL);
SetGlyphPtr(size, key, &new_glyph);
return 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)->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] = calloc(256, sizeof(*_unicode_glyph_map[size]));
if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) _unicode_glyph_map[size][GB(key, 8, 8)] = calloc(256, sizeof(**_unicode_glyph_map[size]));
_unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)] = sprite;
}
void InitializeUnicodeGlyphMap(void)
{
FontSize size;
SpriteID base;
SpriteID sprite;
uint i;
for (size = FS_NORMAL; size != FS_END; size++) {
/* Clear out existing glyph map if it exists */
if (_unicode_glyph_map[size] != NULL) {
for (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;
}
base = GetFontBase(size);
for (i = ASCII_LETTERSTART; i < 256; i++) {
sprite = base + i - ASCII_LETTERSTART;
if (!SpriteExists(sprite)) continue;
SetUnicodeGlyph(size, i, sprite);
SetUnicodeGlyph(size, i + SCC_SPRITE_START, sprite);
}
for (i = 0; i < lengthof(_default_unicode_map); i++) {
sprite = base + _default_unicode_map[i].key - ASCII_LETTERSTART;
SetUnicodeGlyph(size, _default_unicode_map[i].code, sprite);
}
}
}

Some files were not shown because too many files have changed in this diff Show More