Merge remote-tracking branch 'upstream/master'

This commit is contained in:
dP
2025-05-14 18:41:13 +05:00
994 changed files with 38759 additions and 34518 deletions

View File

@@ -3,7 +3,7 @@
# OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
# Doxyfile 1.5.4
# Doxyfile 1.9.4
#---------------------------------------------------------------------------
# Project related configuration options
@@ -11,14 +11,18 @@
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = "OpenTTD AI API"
PROJECT_NUMBER = ${REV_VERSION}
PROJECT_BRIEF =
PROJECT_LOGO =
OUTPUT_DIRECTORY = ${CPACK_BINARY_DIR}/docs/ai-api/
CREATE_SUBDIRS = NO
CREATE_SUBDIRS_LEVEL = 8
ALLOW_UNICODE_NAMES = NO
OUTPUT_LANGUAGE = English
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
ABBREVIATE_BRIEF = "The $name class " \
"The $name widget " \
"The $name file " \
ABBREVIATE_BRIEF = "The $name class" \
"The $name widget" \
"The $name file" \
is \
provides \
specifies \
@@ -34,29 +38,47 @@ STRIP_FROM_PATH = ./
STRIP_FROM_INC_PATH =
SHORT_NAMES = NO
JAVADOC_AUTOBRIEF = YES
JAVADOC_BANNER = NO
QT_AUTOBRIEF = NO
MULTILINE_CPP_IS_BRIEF = NO
PYTHON_DOCSTRING = YES
INHERIT_DOCS = YES
SEPARATE_MEMBER_PAGES = NO
TAB_SIZE = 2
ALIASES =
OPTIMIZE_OUTPUT_FOR_C = YES
OPTIMIZE_OUTPUT_JAVA = NO
OPTIMIZE_FOR_FORTRAN = NO
OPTIMIZE_OUTPUT_VHDL = NO
OPTIMIZE_OUTPUT_SLICE = NO
EXTENSION_MAPPING =
MARKDOWN_SUPPORT = YES
TOC_INCLUDE_HEADINGS = 5
AUTOLINK_SUPPORT = YES
BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO
SIP_SUPPORT = NO
IDL_PROPERTY_SUPPORT = YES
DISTRIBUTE_GROUP_DOC = NO
GROUP_NESTED_COMPOUNDS = NO
SUBGROUPING = YES
INLINE_GROUPED_CLASSES = NO
INLINE_SIMPLE_STRUCTS = NO
TYPEDEF_HIDES_STRUCT = NO
LOOKUP_CACHE_SIZE = 0
NUM_PROC_THREADS = 1
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL = NO
EXTRACT_PRIVATE = NO
EXTRACT_PRIV_VIRTUAL = NO
EXTRACT_PACKAGE = NO
EXTRACT_STATIC = YES
EXTRACT_LOCAL_CLASSES = YES
EXTRACT_LOCAL_METHODS = YES
EXTRACT_ANON_NSPACES = NO
RESOLVE_UNNAMED_PARAMS = YES
HIDE_UNDOC_MEMBERS = NO
HIDE_UNDOC_CLASSES = NO
HIDE_FRIEND_COMPOUNDS = NO
@@ -64,11 +86,18 @@ HIDE_IN_BODY_DOCS = YES
INTERNAL_DOCS = YES
CASE_SENSE_NAMES = YES
HIDE_SCOPE_NAMES = NO
HIDE_COMPOUND_REFERENCE= NO
SHOW_HEADERFILE = YES
SHOW_INCLUDE_FILES = NO
SHOW_GROUPED_MEMB_INC = NO
FORCE_LOCAL_INCLUDES = NO
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
SORT_BRIEF_DOCS = NO
SORT_MEMBERS_CTORS_1ST = NO
SORT_GROUP_NAMES = YES
SORT_BY_SCOPE_NAME = NO
STRICT_PROTO_MATCHING = NO
GENERATE_TODOLIST = NO
GENERATE_TESTLIST = NO
GENERATE_BUGLIST = NO
@@ -76,21 +105,29 @@ GENERATE_DEPRECATEDLIST= NO
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = NO
SHOW_FILES = YES
SHOW_NAMESPACES = YES
FILE_VERSION_FILTER =
LAYOUT_FILE =
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
WARN_IF_DOC_ERROR = YES
WARN_IF_INCOMPLETE_DOC = YES
WARN_NO_PARAMDOC = YES
WARN_FORMAT = "$file:$line: $text "
WARN_AS_ERROR = NO
WARN_FORMAT = "$file:$line: $text"
WARN_LINE_FORMAT = "at line $line of file $file"
WARN_LOGFILE =
#---------------------------------------------------------------------------
# configuration options related to the input files
# Configuration options related to the input files
#---------------------------------------------------------------------------
INPUT = . ${FIND_VERSION_BINARY_DIR}/script/api
INPUT = . \
${FIND_VERSION_BINARY_DIR}/script/api
INPUT_ENCODING = UTF-8
FILE_PATTERNS = script_*.hpp \
ai_*.hpp
@@ -98,7 +135,9 @@ RECURSIVE = YES
EXCLUDE =
EXCLUDE_SYMLINKS = NO
EXCLUDE_PATTERNS = ai_includes.hpp
EXCLUDE_SYMBOLS = GetClassName DECLARE_ENUM_AS_BIT_SET DECLARE_POSTFIX_INCREMENT
EXCLUDE_SYMBOLS = GetClassName \
DECLARE_ENUM_AS_BIT_SET \
DECLARE_POSTFIX_INCREMENT
EXAMPLE_PATH =
EXAMPLE_PATTERNS = *
EXAMPLE_RECURSIVE = NO
@@ -106,8 +145,10 @@ IMAGE_PATH =
INPUT_FILTER = "./doxygen_filter.sh AI"
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
FILTER_SOURCE_PATTERNS =
USE_MDFILE_AS_MAINPAGE =
#---------------------------------------------------------------------------
# configuration options related to source browsing
# Configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER = NO
INLINE_SOURCES = NO
@@ -115,15 +156,20 @@ STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = NO
REFERENCES_RELATION = NO
REFERENCES_LINK_SOURCE = YES
SOURCE_TOOLTIPS = YES
USE_HTAGS = NO
VERBATIM_HEADERS = NO
CLANG_ASSISTED_PARSING = NO
CLANG_ADD_INC_PATHS = YES
CLANG_OPTIONS =
CLANG_DATABASE_PATH =
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX = NO
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# configuration options related to the HTML output
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML = YES
HTML_OUTPUT = html
@@ -131,34 +177,86 @@ HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
GENERATE_HTMLHELP = NO
HTML_EXTRA_STYLESHEET =
HTML_EXTRA_FILES =
HTML_COLORSTYLE_HUE = 220
HTML_COLORSTYLE_SAT = 100
HTML_COLORSTYLE_GAMMA = 80
HTML_TIMESTAMP = NO
HTML_DYNAMIC_MENUS = YES
HTML_DYNAMIC_SECTIONS = NO
HTML_INDEX_NUM_ENTRIES = 100
GENERATE_DOCSET = NO
DOCSET_FEEDNAME = "Doxygen generated docs"
DOCSET_FEEDURL =
DOCSET_BUNDLE_ID = org.doxygen.Project
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
DOCSET_PUBLISHER_NAME = Publisher
GENERATE_HTMLHELP = NO
CHM_FILE =
HHC_LOCATION =
GENERATE_CHI = NO
CHM_INDEX_ENCODING =
BINARY_TOC = NO
TOC_EXPAND = NO
GENERATE_QHP = NO
QCH_FILE =
QHP_NAMESPACE = org.doxygen.Project
QHP_VIRTUAL_FOLDER = doc
QHP_CUST_FILTER_NAME =
QHP_CUST_FILTER_ATTRS =
QHP_SECT_FILTER_ATTRS =
QHG_LOCATION =
GENERATE_ECLIPSEHELP = NO
ECLIPSE_DOC_ID = org.doxygen.Project
DISABLE_INDEX = NO
ENUM_VALUES_PER_LINE = 1
GENERATE_TREEVIEW = NO
FULL_SIDEBAR = NO
ENUM_VALUES_PER_LINE = 1
TREEVIEW_WIDTH = 250
EXT_LINKS_IN_WINDOW = NO
OBFUSCATE_EMAILS = YES
HTML_FORMULA_FORMAT = png
FORMULA_FONTSIZE = 10
FORMULA_TRANSPARENT = YES
FORMULA_MACROFILE =
USE_MATHJAX = NO
MATHJAX_VERSION = MathJax_2
MATHJAX_FORMAT = HTML-CSS
MATHJAX_RELPATH =
MATHJAX_EXTENSIONS =
MATHJAX_CODEFILE =
SEARCHENGINE = NO
SERVER_BASED_SEARCH = NO
EXTERNAL_SEARCH = NO
SEARCHENGINE_URL =
SEARCHDATA_FILE = searchdata.xml
EXTERNAL_SEARCH_ID =
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX = NO
LATEX_OUTPUT = latex
LATEX_CMD_NAME = latex
MAKEINDEX_CMD_NAME = makeindex
LATEX_MAKEINDEX_CMD = makeindex
COMPACT_LATEX = NO
PAPER_TYPE = a4
EXTRA_PACKAGES =
LATEX_HEADER =
LATEX_FOOTER =
LATEX_EXTRA_STYLESHEET =
LATEX_EXTRA_FILES =
PDF_HYPERLINKS = NO
USE_PDFLATEX = NO
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
LATEX_BIB_STYLE = plain
LATEX_TIMESTAMP = NO
LATEX_EMOJI_DIRECTORY =
#---------------------------------------------------------------------------
# configuration options related to the RTF output
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF = NO
RTF_OUTPUT = rtf
@@ -167,24 +265,31 @@ RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# configuration options related to the man page output
# Configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN = NO
MAN_OUTPUT = man
MAN_EXTENSION = .3
MAN_SUBDIR =
MAN_LINKS = NO
#---------------------------------------------------------------------------
# configuration options related to the XML output
# Configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML = NO
XML_OUTPUT = xml
XML_PROGRAMLISTING = YES
XML_NS_MEMB_FILE_SCOPE = NO
#---------------------------------------------------------------------------
# configuration options for the AutoGen Definitions output
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
GENERATE_DOCBOOK = NO
DOCBOOK_OUTPUT = docbook
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# configuration options related to the Perl module output
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
@@ -203,22 +308,30 @@ PREDEFINED = DOXYGEN_API
EXPAND_AS_DEFINED = DEF_COMMAND
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration::additions related to external references
# Configuration options related to external references
#---------------------------------------------------------------------------
TAGFILES =
GENERATE_TAGFILE = ${CPACK_BINARY_DIR}/docs/openttd_ai_api.tag
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
EXTERNAL_PAGES = YES
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS = YES
DIA_PATH =
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = NO
DOT_NUM_THREADS = 0
DOT_FONTNAME = Helvetica
DOT_FONTSIZE = 10
DOT_FONTPATH =
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
GROUP_GRAPHS = YES
UML_LOOK = NO
UML_LIMIT_NUM_FIELDS = 10
DOT_UML_DETAILS = NO
DOT_WRAP_THRESHOLD = 17
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
@@ -226,16 +339,19 @@ CALL_GRAPH = NO
CALLER_GRAPH = NO
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DIR_GRAPH_MAX_DEPTH = 1
DOT_IMAGE_FORMAT = png
INTERACTIVE_SVG = NO
DOT_PATH =
DOTFILE_DIRS =
MSCFILE_DIRS =
DIAFILE_DIRS =
PLANTUML_JAR_PATH =
PLANTUML_CFG_FILE =
PLANTUML_INCLUDE_PATH =
DOT_GRAPH_MAX_NODES = 50
MAX_DOT_GRAPH_DEPTH = 1000
DOT_TRANSPARENT = NO
DOT_MULTI_TARGETS = NO
GENERATE_LEGEND = NO
DOT_CLEANUP = YES
#---------------------------------------------------------------------------
# Configuration::additions related to the search engine
#---------------------------------------------------------------------------
SEARCHENGINE = NO

View File

@@ -3,7 +3,7 @@
# OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
# Doxyfile 1.5.4
# Doxyfile 1.9.4
#---------------------------------------------------------------------------
# Project related configuration options
@@ -11,14 +11,18 @@
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = "OpenTTD GameScript API"
PROJECT_NUMBER = ${REV_VERSION}
PROJECT_BRIEF =
PROJECT_LOGO =
OUTPUT_DIRECTORY = ${CPACK_BINARY_DIR}/docs/gs-api/
CREATE_SUBDIRS = NO
CREATE_SUBDIRS_LEVEL = 8
ALLOW_UNICODE_NAMES = NO
OUTPUT_LANGUAGE = English
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
ABBREVIATE_BRIEF = "The $name class " \
"The $name widget " \
"The $name file " \
ABBREVIATE_BRIEF = "The $name class" \
"The $name widget" \
"The $name file" \
is \
provides \
specifies \
@@ -34,29 +38,47 @@ STRIP_FROM_PATH = ./
STRIP_FROM_INC_PATH =
SHORT_NAMES = NO
JAVADOC_AUTOBRIEF = YES
JAVADOC_BANNER = NO
QT_AUTOBRIEF = NO
MULTILINE_CPP_IS_BRIEF = NO
PYTHON_DOCSTRING = YES
INHERIT_DOCS = YES
SEPARATE_MEMBER_PAGES = NO
TAB_SIZE = 2
ALIASES =
OPTIMIZE_OUTPUT_FOR_C = YES
OPTIMIZE_OUTPUT_JAVA = NO
OPTIMIZE_FOR_FORTRAN = NO
OPTIMIZE_OUTPUT_VHDL = NO
OPTIMIZE_OUTPUT_SLICE = NO
EXTENSION_MAPPING =
MARKDOWN_SUPPORT = YES
TOC_INCLUDE_HEADINGS = 5
AUTOLINK_SUPPORT = YES
BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO
SIP_SUPPORT = NO
IDL_PROPERTY_SUPPORT = YES
DISTRIBUTE_GROUP_DOC = NO
GROUP_NESTED_COMPOUNDS = NO
SUBGROUPING = YES
INLINE_GROUPED_CLASSES = NO
INLINE_SIMPLE_STRUCTS = NO
TYPEDEF_HIDES_STRUCT = NO
LOOKUP_CACHE_SIZE = 0
NUM_PROC_THREADS = 1
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL = NO
EXTRACT_PRIVATE = NO
EXTRACT_PRIV_VIRTUAL = NO
EXTRACT_PACKAGE = NO
EXTRACT_STATIC = YES
EXTRACT_LOCAL_CLASSES = YES
EXTRACT_LOCAL_METHODS = YES
EXTRACT_ANON_NSPACES = NO
RESOLVE_UNNAMED_PARAMS = YES
HIDE_UNDOC_MEMBERS = NO
HIDE_UNDOC_CLASSES = NO
HIDE_FRIEND_COMPOUNDS = NO
@@ -64,11 +86,18 @@ HIDE_IN_BODY_DOCS = YES
INTERNAL_DOCS = YES
CASE_SENSE_NAMES = YES
HIDE_SCOPE_NAMES = NO
HIDE_COMPOUND_REFERENCE= NO
SHOW_HEADERFILE = YES
SHOW_INCLUDE_FILES = NO
SHOW_GROUPED_MEMB_INC = NO
FORCE_LOCAL_INCLUDES = NO
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
SORT_BRIEF_DOCS = NO
SORT_MEMBERS_CTORS_1ST = NO
SORT_GROUP_NAMES = NO
SORT_BY_SCOPE_NAME = NO
STRICT_PROTO_MATCHING = NO
GENERATE_TODOLIST = NO
GENERATE_TESTLIST = NO
GENERATE_BUGLIST = NO
@@ -76,21 +105,29 @@ GENERATE_DEPRECATEDLIST= NO
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = NO
SHOW_FILES = YES
SHOW_NAMESPACES = YES
FILE_VERSION_FILTER =
LAYOUT_FILE =
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
WARN_IF_DOC_ERROR = YES
WARN_IF_INCOMPLETE_DOC = YES
WARN_NO_PARAMDOC = YES
WARN_FORMAT = "$file:$line: $text "
WARN_AS_ERROR = NO
WARN_FORMAT = "$file:$line: $text"
WARN_LINE_FORMAT = "at line $line of file $file"
WARN_LOGFILE =
#---------------------------------------------------------------------------
# configuration options related to the input files
# Configuration options related to the input files
#---------------------------------------------------------------------------
INPUT = . ${FIND_VERSION_BINARY_DIR}/script/api
INPUT = . \
${FIND_VERSION_BINARY_DIR}/script/api
INPUT_ENCODING = UTF-8
FILE_PATTERNS = script_*.hpp \
game_*.hpp
@@ -98,7 +135,9 @@ RECURSIVE = YES
EXCLUDE =
EXCLUDE_SYMLINKS = NO
EXCLUDE_PATTERNS = game_includes.hpp
EXCLUDE_SYMBOLS = GetClassName DECLARE_ENUM_AS_BIT_SET DECLARE_POSTFIX_INCREMENT
EXCLUDE_SYMBOLS = GetClassName \
DECLARE_ENUM_AS_BIT_SET \
DECLARE_POSTFIX_INCREMENT
EXAMPLE_PATH =
EXAMPLE_PATTERNS = *
EXAMPLE_RECURSIVE = NO
@@ -106,8 +145,10 @@ IMAGE_PATH =
INPUT_FILTER = "./doxygen_filter.sh GS"
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
FILTER_SOURCE_PATTERNS =
USE_MDFILE_AS_MAINPAGE =
#---------------------------------------------------------------------------
# configuration options related to source browsing
# Configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER = NO
INLINE_SOURCES = NO
@@ -115,15 +156,20 @@ STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = NO
REFERENCES_RELATION = NO
REFERENCES_LINK_SOURCE = YES
SOURCE_TOOLTIPS = YES
USE_HTAGS = NO
VERBATIM_HEADERS = NO
CLANG_ASSISTED_PARSING = NO
CLANG_ADD_INC_PATHS = YES
CLANG_OPTIONS =
CLANG_DATABASE_PATH =
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX = NO
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# configuration options related to the HTML output
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML = YES
HTML_OUTPUT = html
@@ -131,34 +177,86 @@ HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
GENERATE_HTMLHELP = NO
HTML_EXTRA_STYLESHEET =
HTML_EXTRA_FILES =
HTML_COLORSTYLE_HUE = 220
HTML_COLORSTYLE_SAT = 100
HTML_COLORSTYLE_GAMMA = 80
HTML_TIMESTAMP = NO
HTML_DYNAMIC_MENUS = YES
HTML_DYNAMIC_SECTIONS = NO
HTML_INDEX_NUM_ENTRIES = 100
GENERATE_DOCSET = NO
DOCSET_FEEDNAME = "Doxygen generated docs"
DOCSET_FEEDURL =
DOCSET_BUNDLE_ID = org.doxygen.Project
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
DOCSET_PUBLISHER_NAME = Publisher
GENERATE_HTMLHELP = NO
CHM_FILE =
HHC_LOCATION =
GENERATE_CHI = NO
CHM_INDEX_ENCODING =
BINARY_TOC = NO
TOC_EXPAND = NO
GENERATE_QHP = NO
QCH_FILE =
QHP_NAMESPACE = org.doxygen.Project
QHP_VIRTUAL_FOLDER = doc
QHP_CUST_FILTER_NAME =
QHP_CUST_FILTER_ATTRS =
QHP_SECT_FILTER_ATTRS =
QHG_LOCATION =
GENERATE_ECLIPSEHELP = NO
ECLIPSE_DOC_ID = org.doxygen.Project
DISABLE_INDEX = NO
ENUM_VALUES_PER_LINE = 1
GENERATE_TREEVIEW = NO
FULL_SIDEBAR = NO
ENUM_VALUES_PER_LINE = 1
TREEVIEW_WIDTH = 250
EXT_LINKS_IN_WINDOW = NO
OBFUSCATE_EMAILS = YES
HTML_FORMULA_FORMAT = png
FORMULA_FONTSIZE = 10
FORMULA_TRANSPARENT = YES
FORMULA_MACROFILE =
USE_MATHJAX = NO
MATHJAX_VERSION = MathJax_2
MATHJAX_FORMAT = HTML-CSS
MATHJAX_RELPATH =
MATHJAX_EXTENSIONS =
MATHJAX_CODEFILE =
SEARCHENGINE = NO
SERVER_BASED_SEARCH = NO
EXTERNAL_SEARCH = NO
SEARCHENGINE_URL =
SEARCHDATA_FILE = searchdata.xml
EXTERNAL_SEARCH_ID =
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX = NO
LATEX_OUTPUT = latex
LATEX_CMD_NAME = latex
MAKEINDEX_CMD_NAME = makeindex
LATEX_MAKEINDEX_CMD = makeindex
COMPACT_LATEX = NO
PAPER_TYPE = a4
EXTRA_PACKAGES =
LATEX_HEADER =
LATEX_FOOTER =
LATEX_EXTRA_STYLESHEET =
LATEX_EXTRA_FILES =
PDF_HYPERLINKS = NO
USE_PDFLATEX = NO
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
LATEX_BIB_STYLE = plain
LATEX_TIMESTAMP = NO
LATEX_EMOJI_DIRECTORY =
#---------------------------------------------------------------------------
# configuration options related to the RTF output
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF = NO
RTF_OUTPUT = rtf
@@ -167,24 +265,31 @@ RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# configuration options related to the man page output
# Configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN = NO
MAN_OUTPUT = man
MAN_EXTENSION = .3
MAN_SUBDIR =
MAN_LINKS = NO
#---------------------------------------------------------------------------
# configuration options related to the XML output
# Configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML = NO
XML_OUTPUT = xml
XML_PROGRAMLISTING = YES
XML_NS_MEMB_FILE_SCOPE = NO
#---------------------------------------------------------------------------
# configuration options for the AutoGen Definitions output
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
GENERATE_DOCBOOK = NO
DOCBOOK_OUTPUT = docbook
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# configuration options related to the Perl module output
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
@@ -203,22 +308,30 @@ PREDEFINED = DOXYGEN_API
EXPAND_AS_DEFINED = DEF_COMMAND
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration::additions related to external references
# Configuration options related to external references
#---------------------------------------------------------------------------
TAGFILES =
GENERATE_TAGFILE = ${CPACK_BINARY_DIR}/docs/openttd_gs_api.tag
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
EXTERNAL_PAGES = YES
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS = YES
DIA_PATH =
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = NO
DOT_NUM_THREADS = 0
DOT_FONTNAME = Helvetica
DOT_FONTSIZE = 10
DOT_FONTPATH =
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
GROUP_GRAPHS = YES
UML_LOOK = NO
UML_LIMIT_NUM_FIELDS = 10
DOT_UML_DETAILS = NO
DOT_WRAP_THRESHOLD = 17
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
@@ -226,16 +339,19 @@ CALL_GRAPH = NO
CALLER_GRAPH = NO
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DIR_GRAPH_MAX_DEPTH = 1
DOT_IMAGE_FORMAT = png
INTERACTIVE_SVG = NO
DOT_PATH =
DOTFILE_DIRS =
MSCFILE_DIRS =
DIAFILE_DIRS =
PLANTUML_JAR_PATH =
PLANTUML_CFG_FILE =
PLANTUML_INCLUDE_PATH =
DOT_GRAPH_MAX_NODES = 50
MAX_DOT_GRAPH_DEPTH = 1000
DOT_TRANSPARENT = NO
DOT_MULTI_TARGETS = NO
GENERATE_LEGEND = NO
DOT_CLEANUP = YES
#---------------------------------------------------------------------------
# Configuration::additions related to the search engine
#---------------------------------------------------------------------------
SEARCHENGINE = NO

View File

@@ -6,18 +6,23 @@
*/
/**
* @file ai_changelog.hpp Lists all changes / additions to the API.
* @page ai_changelog Lists all changes / additions to the API.
*
* Only new / renamed / deleted api functions will be listed here. A list of
* bug fixes can be found in the normal changelog. Note that removed API
* functions may still be available if you return an older API version
* in GetAPIVersion() in info.nut.
*
* \b 14.0
* \b 15.0
*
* This version is not yet released. The following changes are not set in stone yet.
*
* API additions:
* \li AIEventVehicleCrashed::GetVictims
*
* \b 14.0
*
* API additions:
* \li AITown::ROAD_LAYOUT_RANDOM
* \li AIVehicle::IsPrimaryVehicle
* \li AITileList_StationCoverage
@@ -455,3 +460,17 @@
* \b 0.7.0
* \li First stable release with the NoAI framework.
*/
/**
* @mainpage
*
* What's new?
* \li \ref ai_changelog
*
* Main classes:
* \li \ref AIInfo
* \li \ref AIController
*
* Detail topics:
* \li \ref script_ids
*/

View File

@@ -24,7 +24,10 @@ BEGIN {
}
{
# replace Script with AI/GS, except for ScriptErrorType
gsub(/Script/, api)
gsub(/AIErrorType/, "ScriptErrorType")
gsub(/GSErrorType/, "ScriptErrorType")
}
{
@@ -133,6 +136,16 @@ BEGIN {
next
}
# Convert/unify type names
{
gsub(/\<SQInteger\>/, "int")
gsub(/\<SquirrelTable\>/, "table")
gsub(/\<u?int[0-9]*(_t)?\>/, "int")
gsub(/\<HSQOBJECT\>/, "object")
gsub(/std::optional<std::string>/, "string")
gsub(/(const )?std::string *[*&]?/, "string ")
}
# Store comments
/\/\*\*.*\*\// { comment_buffer = $0; comment = "false"; next; }
/\/\*.*\*\// { comment_buffer = ""; comment = "false"; next; }
@@ -245,7 +258,7 @@ BEGIN {
}
# Add a const (non-enum) value
/^[ ]*static const \w+ \w+ = -?\(?\w*\)?\w+;/ {
/^[ ]*static const \w+ \w+ = [^;]+;/ {
if (api_selected == "") api_selected = cls_in_api
if (api_selected == "false") {
api_selected = ""

View File

@@ -21,6 +21,7 @@ fi
case $2 in
*ai_changelog.hpp) cat $2; exit 0;;
*game_changelog.hpp) cat $2; exit 0;;
*script_types.hpp) cat $2; exit 0;;
esac
${AWK} -v api=$1 -f doxygen_filter.awk $2

View File

@@ -6,18 +6,23 @@
*/
/**
* @file game_changelog.hpp Lists all changes / additions to the API.
* @page game_changelog Lists all changes / additions to the API.
*
* Only new / renamed / deleted api functions will be listed here. A list of
* bug fixes can be found in the normal changelog. Note that removed API
* functions may still be available if you return an older API version
* in GetAPIVersion() in info.nut.
*
* \b 14.0
* \b 15.0
*
* This version is not yet released. The following changes are not set in stone yet.
*
* API additions:
* \li GSEventVehicleCrashed::GetVictims
*
* \b 14.0
*
* API additions:
* \li GSIndustry::GetConstructionDate
* \li GSAsyncMode
* \li GSCompanyMode::IsValid
@@ -299,3 +304,17 @@
* \b 1.2.0
* \li First stable release with the NoGo framework.
*/
/**
* @mainpage
*
* What's new?
* \li \ref game_changelog
*
* Main classes:
* \li \ref GSInfo
* \li \ref GSController
*
* Detail topics:
* \li \ref script_ids
*/

View File

@@ -77,11 +77,11 @@ bool ScriptAdminMakeJSON(nlohmann::json &json, HSQUIRRELVM vm, SQInteger index,
sq_pushnull(vm);
while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
/* Squirrel ensure the key is a string. */
assert(sq_gettype(vm, -2) == OT_STRING);
sq_tostring(vm, -2);
const SQChar *buf;
sq_getstring(vm, -2, &buf);
sq_getstring(vm, -1, &buf);
std::string key = std::string(buf);
sq_pop(vm, 1);
nlohmann::json value;
bool res = ScriptAdminMakeJSON(value, vm, -1, depth + 1);

View File

@@ -27,13 +27,13 @@ public:
/**
* Send information to the AdminPort. The information can be anything
* as long as it isn't a class or instance thereof.
* @param table The information to send, in a table. For example: { param = "param" }.
* @param data The information to send, in a table. For example: { param = "param" }.
* @return True if and only if the data was successfully converted to JSON
* and send to the AdminPort.
* @note If the resulting JSON of your table is larger than 1450 bytes,
* nothing will be sent (and false will be returned).
*/
static bool Send(void *table);
static bool Send(table data);
#endif /* DOXYGEN_API */
};

View File

@@ -138,7 +138,8 @@
if (_settings_game.economy.station_noise_level) {
uint dist;
AirportGetNearestTown(as, as->rotation[0], tile, AirportTileTableIterator(as->table[0], tile), dist);
const auto &layout = as->layouts[0];
AirportGetNearestTown(as, layout.rotation, tile, AirportTileTableIterator(layout.tiles.data(), tile), dist);
return GetAirportNoiseLevelForDistance(as, dist);
}
@@ -154,7 +155,8 @@
if (!as->IsWithinMapBounds(0, tile)) return INVALID_TOWN;
uint dist;
return AirportGetNearestTown(as, as->rotation[0], tile, AirportTileTableIterator(as->table[0], tile), dist)->index;
const auto &layout = as->layouts[0];
return AirportGetNearestTown(as, layout.rotation, tile, AirportTileTableIterator(layout.tiles.data(), tile), dist)->index;
}
/* static */ SQInteger ScriptAirport::GetMaintenanceCostFactor(AirportType type)

View File

@@ -204,7 +204,8 @@ public:
* Get the monthly maintenance cost of an airport type.
* @param type The airport type to get the monthly maintenance cost of.
* @pre IsAirportInformationAvailable(type)
* @return Monthly maintenance cost of the airport type.
* @return Maintenance cost of the airport type per economy-month.
* @see \ref ScriptEconomyTime
*/
static Money GetMonthlyMaintenanceCost(AirportType type);

View File

@@ -37,7 +37,7 @@
/* static */ bool ScriptBaseStation::SetName(StationID station_id, Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceCompanyModeValid(false);
EnforcePrecondition(false, IsValidBaseStation(station_id));

View File

@@ -68,9 +68,10 @@ public:
static TileIndex GetLocation(StationID station_id);
/**
* Get the last date a station part was added to this station.
* Get the last calendar-date a station part was added to this station.
* @param station_id The station to look at.
* @return The last date some part of this station was build.
* @return The last calendar-date some part of this station was build.
* @see \ref ScriptCalendarTime
*/
static ScriptDate::Date GetConstructionDate(StationID station_id);
};

View File

@@ -20,6 +20,8 @@ class ScriptBridge : public ScriptObject {
public:
/**
* All bridge related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Base for bridge related errors */

View File

@@ -16,14 +16,14 @@
ScriptBridgeList::ScriptBridgeList()
{
for (byte j = 0; j < MAX_BRIDGES; j++) {
for (uint8_t j = 0; j < MAX_BRIDGES; j++) {
if (ScriptBridge::IsValidBridge(j)) this->AddItem(j);
}
}
ScriptBridgeList_Length::ScriptBridgeList_Length(SQInteger length)
{
for (byte j = 0; j < MAX_BRIDGES; j++) {
for (uint8_t j = 0; j < MAX_BRIDGES; j++) {
if (ScriptBridge::IsValidBridge(j)) {
if (length >= ScriptBridge::GetMinLength(j) && length <= ScriptBridge::GetMaxLength(j)) this->AddItem(j);
}

View File

@@ -28,7 +28,7 @@ ScriptCargoList_IndustryAccepting::ScriptCargoList_IndustryAccepting(IndustryID
{
if (!ScriptIndustry::IsValidIndustry(industry_id)) return;
Industry *ind = ::Industry::Get(industry_id);
const Industry *ind = ::Industry::Get(industry_id);
for (const auto &a : ind->accepted) {
if (::IsValidCargoID(a.cargo)) {
this->AddItem(a.cargo);
@@ -40,7 +40,7 @@ ScriptCargoList_IndustryProducing::ScriptCargoList_IndustryProducing(IndustryID
{
if (!ScriptIndustry::IsValidIndustry(industry_id)) return;
Industry *ind = ::Industry::Get(industry_id);
const Industry *ind = ::Industry::Get(industry_id);
for (const auto &p : ind->produced) {
if (::IsValidCargoID(p.cargo)) {
this->AddItem(p.cargo);
@@ -52,7 +52,7 @@ ScriptCargoList_StationAccepting::ScriptCargoList_StationAccepting(StationID sta
{
if (!ScriptStation::IsValidStation(station_id)) return;
Station *st = ::Station::Get(station_id);
const Station *st = ::Station::Get(station_id);
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) this->AddItem(i);
}

View File

@@ -56,10 +56,11 @@ public:
static ScriptCompany::CompanyID GetCompany(ClientID client);
/**
* Get the game date when the given client has joined.
* Get the economy-date when the given client has joined.
* @param client The client to get joining date for.
* @pre ResolveClientID(client) != CLIENT_INVALID.
* @return The date when client has joined.
* @return The economy-date when client has joined.
* @see \ref ScriptEconomyTime
*/
static ScriptDate::Date GetJoinDate(ClientID client);
};

View File

@@ -32,7 +32,7 @@
{
if (company == COMPANY_SELF) {
if (!::Company::IsValidID(_current_company)) return COMPANY_INVALID;
return (CompanyID)((byte)_current_company);
return (CompanyID)((uint8_t)_current_company);
}
return ::Company::IsValidID(company) ? company : COMPANY_INVALID;
@@ -46,7 +46,7 @@
/* static */ bool ScriptCompany::SetName(Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceCompanyModeValid(false);
EnforcePrecondition(false, name != nullptr);
@@ -68,7 +68,7 @@
/* static */ bool ScriptCompany::SetPresidentName(Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceCompanyModeValid(false);
EnforcePrecondition(false, name != nullptr);

View File

@@ -99,7 +99,7 @@ public:
* Types of expenses.
* @api -ai
*/
enum ExpensesType : byte {
enum ExpensesType : uint8_t {
EXPENSES_CONSTRUCTION = ::EXPENSES_CONSTRUCTION, ///< Construction costs.
EXPENSES_NEW_VEHICLES = ::EXPENSES_NEW_VEHICLES, ///< New vehicles.
EXPENSES_TRAIN_RUN = ::EXPENSES_TRAIN_RUN, ///< Running costs trains.
@@ -281,59 +281,64 @@ public:
static bool ChangeBankBalance(CompanyID company, Money delta, ExpensesType expenses_type, TileIndex tile);
/**
* Get the income of the company in the given quarter.
* Get the income of the company in the given economy-quarter.
* Note that this function only considers recurring income from vehicles;
* it does not include one-time income from selling stuff.
* @param company The company to get the quarterly income of.
* @param quarter The quarter to get the income of.
* @param quarter The economy-quarter to get the income of.
* @pre ResolveCompanyID(company) != COMPANY_INVALID.
* @pre quarter <= EARLIEST_QUARTER.
* @return The gross income of the company in the given quarter.
* @return The gross income of the company in the given economy-quarter.
* @see \ref ScriptEconomyTime
*/
static Money GetQuarterlyIncome(CompanyID company, SQInteger quarter);
/**
* Get the expenses of the company in the given quarter.
* Get the expenses of the company in the given economy-quarter.
* Note that this function only considers recurring expenses from vehicle
* running cost, maintenance and interests; it does not include one-time
* expenses from construction and buying stuff.
* @param company The company to get the quarterly expenses of.
* @param quarter The quarter to get the expenses of.
* @param quarter The economy-quarter to get the expenses of.
* @pre ResolveCompanyID(company) != COMPANY_INVALID.
* @pre quarter <= EARLIEST_QUARTER.
* @return The expenses of the company in the given quarter.
* @return The expenses of the company in the given economy-quarter.
* @see \ref ScriptEconomyTime
*/
static Money GetQuarterlyExpenses(CompanyID company, SQInteger quarter);
/**
* Get the amount of cargo delivered by the given company in the given quarter.
* Get the amount of cargo delivered by the given company in the given economy-quarter.
* @param company The company to get the amount of delivered cargo of.
* @param quarter The quarter to get the amount of delivered cargo of.
* @param quarter The economy-quarter to get the amount of delivered cargo of.
* @pre ResolveCompanyID(company) != COMPANY_INVALID.
* @pre quarter <= EARLIEST_QUARTER.
* @return The amount of cargo delivered by the given company in the given quarter.
* @return The amount of cargo delivered by the given company in the given economy-quarter.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetQuarterlyCargoDelivered(CompanyID company, SQInteger quarter);
/**
* Get the performance rating of the given company in the given quarter.
* Get the performance rating of the given company in the given economy-quarter.
* @param company The company to get the performance rating of.
* @param quarter The quarter to get the performance rating of.
* @param quarter The economy-quarter to get the performance rating of.
* @pre ResolveCompanyID(company) != COMPANY_INVALID.
* @pre quarter <= EARLIEST_QUARTER.
* @pre quarter != CURRENT_QUARTER.
* @note The performance rating is calculated after every quarter, so the value for CURRENT_QUARTER is undefined.
* @return The performance rating of the given company in the given quarter.
* @note The performance rating is calculated after every economy-quarter, so the value for CURRENT_QUARTER is undefined.
* @return The performance rating of the given company in the given economy-quarter.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetQuarterlyPerformanceRating(CompanyID company, SQInteger quarter);
/**
* Get the value of the company in the given quarter.
* Get the value of the company in the given economy-quarter.
* @param company The company to get the value of.
* @param quarter The quarter to get the value of.
* @param quarter The economy-quarter to get the value of.
* @pre ResolveCompanyID(company) != COMPANY_INVALID.
* @pre quarter <= EARLIEST_QUARTER.
* @return The value of the company in the given quarter.
* @return The value of the company in the given economy-quarter.
* @see \ref ScriptEconomyTime
*/
static Money GetQuarterlyCompanyValue(CompanyID company, SQInteger quarter);
@@ -377,10 +382,11 @@ public:
/**
* Set the number of months before/after max age to autorenew an engine for your company.
* @param months The new months between autorenew.
* @param months The number of calendar-months before/after max age of engine.
* The value will be clamped to MIN(int16_t) .. MAX(int16_t).
* @game @pre ScriptCompanyMode::IsValid().
* @return True if autorenew months has been modified.
* @see \ref ScriptCalendarTime
*/
static bool SetAutoRenewMonths(SQInteger months);
@@ -388,7 +394,8 @@ public:
* Return the number of months before/after max age to autorenew an engine for a company.
* @param company The company to get the autorenew months of.
* @pre ResolveCompanyID(company) != COMPANY_INVALID.
* @return The months before/after max age of engine.
* @return The number of calendar-months before/after max age of engine.
* @see \ref ScriptCalendarTime
*/
static SQInteger GetAutoRenewMonths(CompanyID company);

View File

@@ -52,7 +52,7 @@ public:
* Check whether a company mode is valid. In other words, are commands
* being executed under some company and does the company still exist?
* @return true When a company mode is valid.
* @post !ScriptCompanyMode::IsDeity().
* @post If IsValid() is true, then IsDeity() is false.
*/
static bool IsValid();
@@ -60,7 +60,7 @@ public:
* Check whether the company mode is not active, i.e. whether we are a deity.
* In other words, are commands are not being executed under some company.
* @return true When we are a deity, i.e. company mode is not active.
* @post !ScriptCompanyMode::IsValid().
* @post if IsDeity() is true, then IsValid() is false.
*/
static bool IsDeity();
};

View File

@@ -92,7 +92,7 @@ public:
*
* @return Data of the script that should be stored in the save game.
*/
SquirrelTable Save();
table Save();
/**
* Load saved data just before calling #Start.
@@ -100,7 +100,7 @@ public:
* @param version Version number of the script that created the \a data.
* @param data Data that was saved (return value of #Save).
*/
void Load(int version, SquirrelTable data);
void Load(int version, table data);
#endif /* DOXYGEN_API */
/**

View File

@@ -23,6 +23,30 @@
* @note Dates can be used to determine the number of days between
* two different moments in time because they count the number
* of days since the year 0.
*
* \anchor ScriptCalendarTime
* \b Calendar-Time
*
* Calendar time measures the technological progression in the game.
* \li The calendar date is shown in the status bar.
* \li The calendar date affects engine model introduction and expiration.
* \li Progression of calendar time can be slowed or even halted via game settings.
*
* Calendar time uses the Gregorian calendar with 365 or 366 days per year.
*
* \anchor ScriptEconomyTime
* \b Economy-Time
*
* Economy time measures the in-game time progression, while the game is not paused.
* \li Cargo production and consumption follows economy time.
* \li Recurring income and expenses follow economy time.
* \li Production and income statistics and balances are created per economy month/quarter/year.
*
* Depending on game settings economy time is represented differently:
* \li Calendar-based timekeeping: Economy- and calendar-time use the identical Gregorian calendar.
* \li Wallclock-based timekeeping: Economy- and calendar-time are separate.
* Economy-time will use a 360 day calendar (12 months with 30 days each), which runs at a constant speed of one economy-month per realtime-minute.
* Calendar-time will use a Gregorian calendar, which can be slowed to stopped via game settings.
*/
class ScriptDate : public ScriptObject {
public:

View File

@@ -125,8 +125,8 @@ public:
* Get the maximum age of a brand new engine.
* @param engine_id The engine to get the maximum age of.
* @pre IsValidEngine(engine_id).
* @returns The maximum age of a new engine in days.
* @note Age is in days; divide by 366 to get per year.
* @returns The maximum age of a new engine in calendar-days.
* @see \ref ScriptCalendarTime
*/
static SQInteger GetMaxAge(EngineID engine_id);
@@ -134,8 +134,8 @@ public:
* Get the running cost of an engine.
* @param engine_id The engine to get the running cost of.
* @pre IsValidEngine(engine_id).
* @return The running cost of a vehicle per year.
* @note Cost is per year; divide by 365 to get per day.
* @return The running cost of a vehicle per economy-year.
* @see \ref ScriptEconomyTime
*/
static Money GetRunningCost(EngineID engine_id);
@@ -167,10 +167,11 @@ public:
static SQInteger GetMaxTractiveEffort(EngineID engine_id);
/**
* Get the date this engine was designed.
* Get the calendar-date this engine was designed.
* @param engine_id The engine to get the design date of.
* @pre IsValidEngine(engine_id).
* @return The date this engine was designed.
* @return The calendar-date this engine was designed.
* @see \ref ScriptCalendarTime
*/
static ScriptDate::Date GetDesignDate(EngineID engine_id);

View File

@@ -120,6 +120,8 @@ public:
/**
* All general related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Initial error value */

View File

@@ -38,12 +38,14 @@ public:
* @param vehicle The vehicle that crashed.
* @param crash_site Where the vehicle crashed.
* @param crash_reason The reason why the vehicle crashed.
* @param victims The number of victims caused by the crash.
*/
ScriptEventVehicleCrashed(VehicleID vehicle, TileIndex crash_site, CrashReason crash_reason) :
ScriptEventVehicleCrashed(VehicleID vehicle, TileIndex crash_site, CrashReason crash_reason, uint victims) :
ScriptEvent(ET_VEHICLE_CRASHED),
crash_site(crash_site),
vehicle(vehicle),
crash_reason(crash_reason)
crash_reason(crash_reason),
victims(victims)
{}
#endif /* DOXYGEN_API */
@@ -72,10 +74,17 @@ public:
*/
CrashReason GetCrashReason() { return this->crash_reason; }
/**
* Get the number of victims
* @return The number of victims
*/
SQInteger GetVictims() { return this->victims; }
private:
TileIndex crash_site; ///< The location of the crash.
VehicleID vehicle; ///< The crashed vehicle.
CrashReason crash_reason; ///< The reason for crashing.
uint victims; ///< The number of victims.
};
/**
@@ -272,8 +281,8 @@ public:
/**
* Get the running cost of the offered engine.
* @return The running cost of the vehicle per year.
* @note Cost is per year; divide by 365 to get per day.
* @return The running cost of the vehicle per economy-year.
* @see \ref ScriptEconomyTime
*/
Money GetRunningCost();

View File

@@ -44,7 +44,7 @@
/* static */ ScriptGoal::GoalID ScriptGoal::New(ScriptCompany::CompanyID company, Text *goal, GoalType type, SQInteger destination)
{
CCountedPtr<Text> counter(goal);
ScriptObjectRef counter(goal);
EnforceDeityMode(GOAL_INVALID);
EnforcePrecondition(GOAL_INVALID, goal != nullptr);
@@ -71,7 +71,7 @@
{
EnforceDeityMode(false);
EnforcePrecondition(false, IsValidGoal(goal_id));
Goal *g = Goal::Get(goal_id);
const Goal *g = Goal::Get(goal_id);
EnforcePrecondition(false, IsValidGoalDestination((ScriptCompany::CompanyID)g->company, type, destination));
return ScriptObject::Command<CMD_SET_GOAL_DESTINATION>::Do(goal_id, (::GoalType)type, destination);
@@ -79,7 +79,7 @@
/* static */ bool ScriptGoal::SetText(GoalID goal_id, Text *goal)
{
CCountedPtr<Text> counter(goal);
ScriptObjectRef counter(goal);
EnforcePrecondition(false, IsValidGoal(goal_id));
EnforceDeityMode(false);
@@ -92,7 +92,7 @@
/* static */ bool ScriptGoal::SetProgress(GoalID goal_id, Text *progress)
{
CCountedPtr<Text> counter(progress);
ScriptObjectRef counter(progress);
EnforcePrecondition(false, IsValidGoal(goal_id));
EnforceDeityMode(false);
@@ -113,13 +113,13 @@
EnforcePrecondition(false, IsValidGoal(goal_id));
EnforceDeityMode(false);
Goal *g = Goal::Get(goal_id);
const Goal *g = Goal::Get(goal_id);
return g != nullptr && g->completed;
}
/* static */ bool ScriptGoal::DoQuestion(SQInteger uniqueid, uint32_t target, bool is_client, Text *question, QuestionType type, SQInteger buttons)
{
CCountedPtr<Text> counter(question);
ScriptObjectRef counter(question);
EnforceDeityMode(false);
EnforcePrecondition(false, question != nullptr);

View File

@@ -36,7 +36,7 @@ public:
/**
* Goal types that can be given to a goal.
*/
enum GoalType : byte {
enum GoalType : uint8_t {
/* Note: these values represent part of the in-game GoalType enum */
GT_NONE = ::GT_NONE, ///< Destination is not linked.
GT_TILE = ::GT_TILE, ///< Destination is a tile.

View File

@@ -56,7 +56,7 @@
/* static */ bool ScriptGroup::SetName(GroupID group_id, Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceCompanyModeValid(false);
EnforcePrecondition(false, IsValidGroup(group_id));

View File

@@ -222,7 +222,8 @@ public:
* Get the current profit of a group.
* @param group_id The group to get the profit of.
* @pre IsValidGroup(group_id).
* @return The current profit the group has.
* @return The profit the vehicles in this group have made this economy-year so far.
* @see \ref ScriptEconomyTime
*/
static Money GetProfitThisYear(GroupID group_id);
@@ -230,7 +231,8 @@ public:
* Get the profit of last year of a group.
* @param group_id The group to get the profit of.
* @pre IsValidGroup(group_id).
* @return The current profit the group had last year.
* @return The profit the vehicles in this group made in the previous economy-year.
* @see \ref ScriptEconomyTime
*/
static Money GetProfitLastYear(GroupID group_id);

View File

@@ -29,20 +29,22 @@ public:
/**
* Apply a filter when building the list.
* @param filter_function The function which will be doing the filtering.
* @param params The params to give to the filters (minus the first param,
* @param ... The params to give to the filters (minus the first param,
* which is always the index-value).
* @game @pre ScriptCompanyMode::IsValid().
* @note You can write your own filters and use them. Just remember that
* the first parameter should be the index-value, and it should return
* a bool.
* @note Example:
* @code
* function IsType(group_id, type)
* {
* return ScriptGroup.GetVehicleType(group_id) == type;
* }
* ScriptGroupList(IsType, ScriptVehicle.VT_ROAD);
* local rv_groups = ScriptGroupList(IsType, ScriptVehicle.VT_ROAD);
* @endcode
*/
ScriptGroupList(void *filter_function, int params, ...);
ScriptGroupList(function filter_function, ...);
#else
/**
* The constructor wrapper from Squirrel.

View File

@@ -51,14 +51,14 @@
/* static */ ScriptDate::Date ScriptIndustry::GetConstructionDate(IndustryID industry_id)
{
Industry *i = Industry::GetIfValid(industry_id);
const Industry *i = Industry::GetIfValid(industry_id);
if (i == nullptr) return ScriptDate::DATE_INVALID;
return (ScriptDate::Date)i->construction_date.base();
}
/* static */ bool ScriptIndustry::SetText(IndustryID industry_id, Text *text)
{
CCountedPtr<Text> counter(text);
ScriptObjectRef counter(text);
EnforceDeityMode(false);
EnforcePrecondition(false, IsValidIndustry(industry_id));
@@ -71,6 +71,7 @@
if (!IsValidIndustry(industry_id)) return CAS_NOT_ACCEPTED;
if (!ScriptCargo::IsValidCargo(cargo_id)) return CAS_NOT_ACCEPTED;
/* Not const because IndustryTemporarilyRefusesCargo tests a callback which needs a non-const object. */
Industry *i = ::Industry::Get(industry_id);
if (!i->IsCargoAccepted(cargo_id)) return CAS_NOT_ACCEPTED;
@@ -84,7 +85,7 @@
if (!IsValidIndustry(industry_id)) return -1;
if (!ScriptCargo::IsValidCargo(cargo_id)) return -1;
Industry *i = ::Industry::Get(industry_id);
const Industry *i = ::Industry::Get(industry_id);
auto it = i->GetCargoAccepted(cargo_id);
if (it == std::end(i->accepted)) return -1;
@@ -97,7 +98,7 @@
if (!IsValidIndustry(industry_id)) return -1;
if (!ScriptCargo::IsValidCargo(cargo_id)) return -1;
Industry *i = ::Industry::Get(industry_id);
const Industry *i = ::Industry::Get(industry_id);
auto it = i->GetCargoProduced(cargo_id);
if (it == std::end(i->produced)) return -1;
@@ -110,7 +111,7 @@
if (!IsValidIndustry(industry_id)) return -1;
if (!ScriptCargo::IsValidCargo(cargo_id)) return -1;
Industry *i = ::Industry::Get(industry_id);
const Industry *i = ::Industry::Get(industry_id);
auto it = i->GetCargoProduced(cargo_id);
if (it == std::end(i->produced)) return -1;
@@ -123,7 +124,7 @@
if (!IsValidIndustry(industry_id)) return -1;
if (!ScriptCargo::IsValidCargo(cargo_id)) return -1;
Industry *i = ::Industry::Get(industry_id);
const Industry *i = ::Industry::Get(industry_id);
auto it = i->GetCargoProduced(cargo_id);
if (it == std::end(i->produced)) return -1;
@@ -142,7 +143,7 @@
{
if (!IsValidIndustry(industry_id)) return -1;
Industry *ind = ::Industry::Get(industry_id);
const Industry *ind = ::Industry::Get(industry_id);
return ind->stations_near.size();
}
@@ -220,14 +221,14 @@
/* static */ SQInteger ScriptIndustry::GetLastProductionYear(IndustryID industry_id)
{
Industry *i = Industry::GetIfValid(industry_id);
const Industry *i = Industry::GetIfValid(industry_id);
if (i == nullptr) return 0;
return i->last_prod_year.base();
}
/* static */ ScriptDate::Date ScriptIndustry::GetCargoLastAcceptedDate(IndustryID industry_id, CargoID cargo_type)
{
Industry *i = Industry::GetIfValid(industry_id);
const Industry *i = Industry::GetIfValid(industry_id);
if (i == nullptr) return ScriptDate::DATE_INVALID;
if (!::IsValidCargoID(cargo_type)) {
@@ -242,7 +243,7 @@
/* static */ SQInteger ScriptIndustry::GetControlFlags(IndustryID industry_id)
{
Industry *i = Industry::GetIfValid(industry_id);
const Industry *i = Industry::GetIfValid(industry_id);
if (i == nullptr) return 0;
return i->ctlflags;
}
@@ -262,7 +263,7 @@
auto company_id = ::Industry::Get(industry_id)->exclusive_supplier;
if (!::Company::IsValidID(company_id)) return ScriptCompany::COMPANY_INVALID;
return (ScriptCompany::CompanyID)((byte)company_id);
return (ScriptCompany::CompanyID)((uint8_t)company_id);
}
/* static */ bool ScriptIndustry::SetExclusiveSupplier(IndustryID industry_id, ScriptCompany::CompanyID company_id)
@@ -282,7 +283,7 @@
auto company_id = ::Industry::Get(industry_id)->exclusive_consumer;
if (!::Company::IsValidID(company_id)) return ScriptCompany::COMPANY_INVALID;
return (ScriptCompany::CompanyID)((byte)company_id);
return (ScriptCompany::CompanyID)((uint8_t)company_id);
}
/* static */ bool ScriptIndustry::SetExclusiveConsumer(IndustryID industry_id, ScriptCompany::CompanyID company_id)
@@ -297,14 +298,14 @@
/* static */ SQInteger ScriptIndustry::GetProductionLevel(IndustryID industry_id)
{
Industry *i = Industry::GetIfValid(industry_id);
const Industry *i = Industry::GetIfValid(industry_id);
if (i == nullptr) return 0;
return i->prod_level;
}
/* static */ bool ScriptIndustry::SetProductionLevel(IndustryID industry_id, SQInteger prod_level, bool show_news, Text *custom_news)
{
CCountedPtr<Text> counter(custom_news);
ScriptObjectRef counter(custom_news);
EnforceDeityMode(false);
EnforcePrecondition(false, IsValidIndustry(industry_id));

View File

@@ -86,10 +86,11 @@ public:
static std::optional<std::string> GetName(IndustryID industry_id);
/**
* Get the construction date of an industry.
* Get the construction calendar-date of an industry.
* @param industry_id The index of the industry.
* @pre IsValidIndustry(industry_id).
* @return Date the industry was constructed.
* @return Calendar-date the industry was constructed.
* @see \ref ScriptCalendarTime
* @api -ai
*/
static ScriptDate::Date GetConstructionDate(IndustryID industry_id);
@@ -126,32 +127,35 @@ public:
static SQInteger GetStockpiledCargo(IndustryID industry_id, CargoID cargo_id);
/**
* Get the total last month's production of the given cargo at an industry.
* Get the total last economy-month's production of the given cargo at an industry.
* @param industry_id The index of the industry.
* @param cargo_id The index of the cargo.
* @pre IsValidIndustry(industry_id).
* @pre ScriptCargo::IsValidCargo(cargo_id).
* @return The last month's production of the given cargo for this industry.
* @return The last economy-month's production of the given cargo for this industry.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetLastMonthProduction(IndustryID industry_id, CargoID cargo_id);
/**
* Get the total amount of cargo transported from an industry last month.
* Get the total amount of cargo transported from an industry last economy-month.
* @param industry_id The index of the industry.
* @param cargo_id The index of the cargo.
* @pre IsValidIndustry(industry_id).
* @pre ScriptCargo::IsValidCargo(cargo_id).
* @return The amount of given cargo transported from this industry last month.
* @return The amount of given cargo transported from this industry last economy-month.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetLastMonthTransported(IndustryID industry_id, CargoID cargo_id);
/**
* Get the percentage of cargo transported from an industry last month.
* Get the percentage of cargo transported from an industry last economy-month.
* @param industry_id The index of the industry.
* @param cargo_id The index of the cargo.
* @pre IsValidIndustry(industry_id).
* @pre ScriptCargo::IsValidCargo(cargo_id).
* @return The percentage of given cargo transported from this industry last month.
* @return The percentage of given cargo transported from this industry last economy-month.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetLastMonthTransportedPercentage(IndustryID industry_id, CargoID cargo_id);
@@ -246,21 +250,23 @@ public:
static IndustryType GetIndustryType(IndustryID industry_id);
/**
* Get the last year this industry had any production output.
* Get the last economy-year this industry had any production output.
* @param industry_id The index of the industry.
* @pre IsValidIndustry(industry_id).
* @return Year the industry last had production, 0 if error.
* @return Economy-year the industry last had production, 0 if error.
* @see \ref ScriptEconomyTime
* @api -ai
*/
static SQInteger GetLastProductionYear(IndustryID industry_id);
/**
* Get the last date this industry accepted any cargo delivery.
* Get the last economy-date this industry accepted any cargo delivery.
* @param industry_id The index of the industry.
* @param cargo_type The cargo to query, or INVALID_CARGO to query latest of all accepted cargoes.
* @pre IsValidIndustry(industry_id).
* @pre IsValidCargo(cargo_type) || cargo_type == INVALID_CARGO.
* @return Date the industry last received cargo from a delivery, or ScriptDate::DATE_INVALID on error.
* @return Economy-date the industry last received cargo from a delivery, or ScriptDate::DATE_INVALID on error.
* @see \ref ScriptEconomyTime
* @api -ai
*/
static ScriptDate::Date GetCargoLastAcceptedDate(IndustryID industry_id, CargoID cargo_type);

View File

@@ -25,20 +25,23 @@ public:
/**
* Apply a filter when building the list.
* @param filter_function The function which will be doing the filtering.
* @param params The params to give to the filters (minus the first param,
* @param ... The params to give to the filters (minus the first param,
* which is always the index-value).
* @note You can write your own filters and use them. Just remember that
* the first parameter should be the index-value, and it should return
* a bool.
* @note Example:
* ScriptIndustryList(ScriptIndustry.HasDock);
* @code
* local water_industries = ScriptIndustryList(ScriptIndustry.HasDock);
*
* function IsType(industry_id, type)
* {
* return ScriptIndustry.GetIndustryType(industry_id) == type;
* }
* ScriptIndustryList(IsType, 0);
* local industries = ScriptIndustryList(IsType, 0);
* @endcode
*/
ScriptIndustryList(void *filter_function, int params, ...);
ScriptIndustryList(function filter_function, ...);
#else
/**
* The constructor wrapper from Squirrel.

View File

@@ -252,5 +252,5 @@ public:
* @note This is a function provided by OpenTTD, you don't have to
* include it in your Script but should just call it from GetSettings.
*/
void AddLabels(const char *setting_name, table value_names);
void AddLabels(string setting_name, table value_names);
};

View File

@@ -39,7 +39,7 @@
company = ScriptCompany::ResolveCompanyID(company);
if (company == ScriptCompany::COMPANY_INVALID) return 0;
::Company *c = ::Company::Get((::CompanyID)company);
const ::Company *c = ::Company::Get((::CompanyID)company);
switch (infra_type) {
case INFRASTRUCTURE_RAIL:
return c->infrastructure.GetRailTotal();
@@ -87,7 +87,7 @@
company = ScriptCompany::ResolveCompanyID(company);
if (company == ScriptCompany::COMPANY_INVALID || !_settings_game.economy.infrastructure_maintenance) return 0;
::Company *c = ::Company::Get((::CompanyID)company);
const ::Company *c = ::Company::Get((::CompanyID)company);
switch (infra_type) {
case INFRASTRUCTURE_RAIL: {
Money cost;

View File

@@ -58,7 +58,8 @@ public:
* Return the monthly maintenance costs of a specific rail type for a company.
* @param company The company to get the monthly cost for.
* @param railtype Rail type to get the cost of.
* @return Monthly maintenance cost for the rail type.
* @return Maintenance cost for the rail type per economy-month.
* @see \ref ScriptEconomyTime
*/
static Money GetMonthlyRailCosts(ScriptCompany::CompanyID company, ScriptRail::RailType railtype);
@@ -66,7 +67,8 @@ public:
* Return the monthly maintenance costs of a specific road type for a company.
* @param company The company to get the monthly cost for.
* @param roadtype Road type to get the cost of.
* @return Monthly maintenance cost for the road type.
* @return Maintenance cost for the road type per economy-month.
* @see \ref ScriptEconomyTime
*/
static Money GetMonthlyRoadCosts(ScriptCompany::CompanyID company, ScriptRoad::RoadType roadtype);
@@ -74,8 +76,9 @@ public:
* Return the monthly maintenance costs of an infrastructure category for a company.
* @param company The company to get the monthly cost for.
* @param infra_type Infrastructure category to get the cost of.
* @return Monthly maintenance cost for the wanted category.
* @return Maintenance cost for the wanted category per economy-month.
* @note #INFRASTRUCTURE_RAIL and #INFRASTRUCTURE_ROAD return the total cost for all rail/road types.
* @see \ref ScriptEconomyTime
*/
static Money GetMonthlyInfrastructureCosts(ScriptCompany::CompanyID company, Infrastructure infra_type);
};

View File

@@ -26,9 +26,9 @@
/* static */ ScriptLeagueTable::LeagueTableID ScriptLeagueTable::New(Text *title, Text *header, Text *footer)
{
CCountedPtr<Text> title_counter(title);
CCountedPtr<Text> header_counter(header);
CCountedPtr<Text> footer_counter(footer);
ScriptObjectRef title_counter(title);
ScriptObjectRef header_counter(header);
ScriptObjectRef footer_counter(footer);
EnforceDeityMode(LEAGUE_TABLE_INVALID);
EnforcePrecondition(LEAGUE_TABLE_INVALID, title != nullptr);
@@ -49,10 +49,10 @@
return ::LeagueTableElement::IsValidID(element_id);
}
/* static */ ScriptLeagueTable::LeagueTableElementID ScriptLeagueTable::NewElement(ScriptLeagueTable::LeagueTableID table, SQInteger rating, ScriptCompany::CompanyID company, Text *text, Text *score, LinkType link_type, LinkTargetID link_target)
/* static */ ScriptLeagueTable::LeagueTableElementID ScriptLeagueTable::NewElement(ScriptLeagueTable::LeagueTableID table, SQInteger rating, ScriptCompany::CompanyID company, Text *text, Text *score, LinkType link_type, SQInteger link_target)
{
CCountedPtr<Text> text_counter(text);
CCountedPtr<Text> score_counter(score);
ScriptObjectRef text_counter(text);
ScriptObjectRef score_counter(score);
EnforceDeityMode(LEAGUE_TABLE_ELEMENT_INVALID);
@@ -78,9 +78,9 @@
return (ScriptLeagueTable::LeagueTableElementID)0;
}
/* static */ bool ScriptLeagueTable::UpdateElementData(LeagueTableElementID element, ScriptCompany::CompanyID company, Text *text, LinkType link_type, LinkTargetID link_target)
/* static */ bool ScriptLeagueTable::UpdateElementData(LeagueTableElementID element, ScriptCompany::CompanyID company, Text *text, LinkType link_type, SQInteger link_target)
{
CCountedPtr<Text> text_counter(text);
ScriptObjectRef text_counter(text);
EnforceDeityMode(false);
EnforcePrecondition(false, IsValidLeagueTableElement(element));
@@ -100,7 +100,7 @@
/* static */ bool ScriptLeagueTable::UpdateElementScore(LeagueTableElementID element, SQInteger rating, Text *score)
{
CCountedPtr<Text> score_counter(score);
ScriptObjectRef score_counter(score);
EnforceDeityMode(false);
EnforcePrecondition(false, IsValidLeagueTableElement(element));

View File

@@ -42,7 +42,7 @@ public:
/**
* The type of a link.
*/
enum LinkType : byte {
enum LinkType : uint8_t {
LINK_NONE = ::LT_NONE, ///< No link
LINK_TILE = ::LT_TILE, ///< Link a tile
LINK_INDUSTRY = ::LT_INDUSTRY, ///< Link an industry
@@ -92,7 +92,7 @@ public:
* @pre score != null && len(score) != 0.
* @pre IsValidLink(Link(link_type, link_target)).
*/
static LeagueTableElementID NewElement(LeagueTableID table, SQInteger rating, ScriptCompany::CompanyID company, Text *text, Text *score, LinkType link_type, LinkTargetID link_target);
static LeagueTableElementID NewElement(LeagueTableID table, SQInteger rating, ScriptCompany::CompanyID company, Text *text, Text *score, LinkType link_type, SQInteger link_target);
/**
* Update the attributes of a league table element.
@@ -107,7 +107,7 @@ public:
* @pre text != null && len(text) != 0.
* @pre IsValidLink(Link(link_type, link_target)).
*/
static bool UpdateElementData(LeagueTableElementID element, ScriptCompany::CompanyID company, Text *text, LinkType link_type, LinkTargetID link_target);
static bool UpdateElementData(LeagueTableElementID element, ScriptCompany::CompanyID company, Text *text, LinkType link_type, SQInteger link_target);
/**
* Create a new league table element.

View File

@@ -370,7 +370,7 @@ public:
/**
* Give all items a value defined by the valuator you give.
* @param valuator_function The function which will be doing the valuation.
* @param params The params to give to the valuators (minus the first param,
* @param ... The params to give to the valuators (minus the first param,
* which is always the index-value we are valuating).
* @note You may not add, remove or change (setting the value of) items while
* valuating. You may also not (re)sort while valuating.
@@ -378,6 +378,7 @@ public:
* the first parameter should be the index-value, and it should return
* an integer.
* @note Example:
* @code
* list.Valuate(ScriptBridge.GetPrice, 5);
* list.Valuate(ScriptBridge.GetMaxLength);
* function MyVal(bridge_id, myparam)
@@ -385,8 +386,9 @@ public:
* return myparam * bridge_id; // This is silly
* }
* list.Valuate(MyVal, 12);
* @endcode
*/
void Valuate(void *valuator_function, int params, ...);
void Valuate(function valuator_function, ...);
#endif /* DOXYGEN_API */
};

View File

@@ -20,6 +20,8 @@ class ScriptMarine : public ScriptObject {
public:
/**
* All marine related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Base for marine related errors */

View File

@@ -22,7 +22,7 @@
/* static */ bool ScriptNews::Create(NewsType type, Text *text, ScriptCompany::CompanyID company, NewsReferenceType ref_type, SQInteger reference)
{
CCountedPtr<Text> counter(text);
ScriptObjectRef counter(text);
EnforceDeityMode(false);
EnforcePrecondition(false, text != nullptr);

View File

@@ -25,6 +25,21 @@
#include "../../safeguards.h"
void SimpleCountedObject::Release()
{
int32_t res = --this->ref_count;
assert(res >= 0);
if (res == 0) {
try {
this->FinalRelease(); // may throw, for example ScriptTest/ExecMode
} catch (...) {
delete this;
throw;
}
delete this;
}
}
/**
* Get the storage associated with the current ScriptInstance.
* @return The storage.
@@ -241,7 +256,7 @@ ScriptObject::ActiveInstance::~ActiveInstance()
/* static */ void ScriptObject::SetCallbackVariable(int index, int value)
{
if ((size_t)index >= GetStorage()->callback_value.size()) GetStorage()->callback_value.resize(index + 1);
if (static_cast<size_t>(index) >= GetStorage()->callback_value.size()) GetStorage()->callback_value.resize(index + 1);
GetStorage()->callback_value[index] = value;
}

View File

@@ -10,7 +10,6 @@
#ifndef SCRIPT_OBJECT_HPP
#define SCRIPT_OBJECT_HPP
#include "../../misc/countedptr.hpp"
#include "../../road_type.h"
#include "../../rail_type.h"
#include "../../string_func.h"
@@ -34,6 +33,27 @@ typedef bool (ScriptModeProc)();
*/
typedef bool (ScriptAsyncModeProc)();
/**
* Simple counted object. Use it as base of your struct/class if you want to use
* basic reference counting. Your struct/class will destroy and free itself when
* last reference to it is released (using Release() method). The initial reference
* count (when it is created) is zero (don't forget AddRef() at least one time if
* not using ScriptObjectRef.
* @api -all
*/
class SimpleCountedObject {
public:
SimpleCountedObject() : ref_count(0) {}
virtual ~SimpleCountedObject() = default;
inline void AddRef() { ++this->ref_count; }
void Release();
virtual void FinalRelease() {};
private:
int32_t ref_count;
};
/**
* Uper-parent object of all API classes. You should never use this class in
* your script, as it doesn't publish any public functions. It is used
@@ -406,7 +426,7 @@ public:
*/
ScriptObjectRef(T *data) : data(data)
{
this->data->AddRef();
if (this->data != nullptr) this->data->AddRef();
}
/* No copy constructor. */
@@ -453,6 +473,15 @@ public:
{
return this->data;
}
/**
* The arrow operator on this reference returns the reference counted object.
* @return Pointer to the underlying object.
*/
const T *operator->() const
{
return this->data;
}
};
#endif /* SCRIPT_OBJECT_HPP */

View File

@@ -687,11 +687,11 @@ static void _DoCommandReturnSetOrderFlags(class ScriptInstance *instance)
{
if (vehicle_type == ScriptVehicle::VT_AIR) {
if (ScriptTile::IsStationTile(origin_tile)) {
Station *orig_station = ::Station::GetByTile(origin_tile);
const Station *orig_station = ::Station::GetByTile(origin_tile);
if (orig_station != nullptr && orig_station->airport.tile != INVALID_TILE) origin_tile = orig_station->airport.tile;
}
if (ScriptTile::IsStationTile(dest_tile)) {
Station *dest_station = ::Station::GetByTile(dest_tile);
const Station *dest_station = ::Station::GetByTile(dest_tile);
if (dest_station != nullptr && dest_station->airport.tile != INVALID_TILE) dest_tile = dest_station->airport.tile;
}

View File

@@ -21,6 +21,8 @@ class ScriptOrder : public ScriptObject {
public:
/**
* All order related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Base for all order related errors */
@@ -91,10 +93,10 @@ public:
OC_RELIABILITY = ::OCV_RELIABILITY, ///< Skip based on the reliability, value is percent (0..100).
OC_MAX_RELIABILITY = ::OCV_MAX_RELIABILITY, ///< Skip based on the maximum reliability. Value in percent
OC_MAX_SPEED = ::OCV_MAX_SPEED, ///< Skip based on the maximum speed, value is in OpenTTD's internal speed unit, see ScriptEngine::GetMaxSpeed.
OC_AGE = ::OCV_AGE, ///< Skip based on the age, value is in years.
OC_AGE = ::OCV_AGE, ///< Skip based on the age, value is in calender-years. @see \ref ScriptCalendarTime
OC_REQUIRES_SERVICE = ::OCV_REQUIRES_SERVICE, ///< Skip when the vehicle requires service, no value.
OC_UNCONDITIONALLY = ::OCV_UNCONDITIONALLY, ///< Always skip, no compare function, no value.
OC_REMAINING_LIFETIME = ::OCV_REMAINING_LIFETIME, ///< Skip based on the remaining lifetime
OC_REMAINING_LIFETIME = ::OCV_REMAINING_LIFETIME, ///< Skip based on the remaining lifetime in calendar-years. @see \ref ScriptCalendarTime
/* Custom added value, only valid for this API */
OC_INVALID = -1, ///< An invalid condition, do not use.

View File

@@ -42,21 +42,21 @@ public:
* @param priority The priority to assign the item.
* @return True if the item was inserted, false if it was already in the queue.
*/
bool Insert(void *item, SQInteger priority);
bool Insert(object item, SQInteger priority);
/**
* Remove and return the item with the lowest priority.
* @return The item with the lowest priority, removed from the queue. Returns null on an empty queue.
* @pre !IsEmpty()
*/
void *Pop();
object Pop();
/**
* Get the item with the lowest priority, keeping it in the queue.
* @return The item with the lowest priority. Returns null on an empty queue.
* @pre !IsEmpty()
*/
void *Peek();
object Peek();
/**
* Check if an items is already included in the queue.
@@ -64,7 +64,7 @@ public:
* @return true if the items is already in the queue.
* @note Performance is O(n), use only when absolutely required.
*/
bool Exists(void *item);
bool Exists(object item);
/**
* Clear the queue, making Count() returning 0 and IsEmpty() returning true.

View File

@@ -193,13 +193,12 @@
bool adjacent = station_id != ScriptStation::STATION_JOIN_ADJACENT;
StationID to_join = ScriptStation::IsValidStation(station_id) ? station_id : INVALID_STATION;
if (res != CALLBACK_FAILED) {
int index = 0;
const StationSpec *spec = StationClass::GetByGrf(file->grfid, res, &index);
const StationSpec *spec = StationClass::GetByGrf(file->grfid, res);
if (spec == nullptr) {
Debug(grf, 1, "{} returned an invalid station ID for 'AI construction/purchase selection (18)' callback", file->filename);
} else {
/* We might have gotten an usable station spec. Try to build it, but if it fails we'll fall back to the original station. */
if (ScriptObject::Command<CMD_BUILD_RAIL_STATION>::Do(tile, (::RailType)GetCurrentRailType(), axis, num_platforms, platform_length, spec->cls_id, index, to_join, adjacent)) return true;
if (ScriptObject::Command<CMD_BUILD_RAIL_STATION>::Do(tile, (::RailType)GetCurrentRailType(), axis, num_platforms, platform_length, spec->class_index, spec->index, to_join, adjacent)) return true;
}
}

View File

@@ -22,6 +22,8 @@ class ScriptRail : public ScriptObject {
public:
/**
* All rail related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Base for rail building / maintaining errors */
@@ -40,7 +42,7 @@ public:
/**
* Types of rail known to the game.
*/
enum RailType : byte {
enum RailType : uint8_t {
/* Note: these values represent part of the in-game static values */
RAILTYPE_INVALID = ::INVALID_RAILTYPE, ///< Invalid RailType.
};

View File

@@ -54,7 +54,7 @@
if (!::IsValidTile(tile)) return false;
if (!IsRoadTypeAvailable(GetCurrentRoadType())) return false;
return ::IsRoadStopTile(tile) && HasBit(::GetPresentRoadTypes(tile), (::RoadType)GetCurrentRoadType());
return ::IsStationRoadStopTile(tile) && HasBit(::GetPresentRoadTypes(tile), (::RoadType)GetCurrentRoadType());
}
/* static */ bool ScriptRoad::IsDriveThroughRoadStationTile(TileIndex tile)
@@ -136,6 +136,32 @@
/* Helper functions for ScriptRoad::CanBuildConnectedRoadParts(). */
/**
* Enumeration or the orientations of road parts.
*
* Technically DiagDirection could be used, but that allows simple conversions to/from integer. In this case that is not wanted.
*/
enum class RoadPartOrientation {
NW, NE, SW, SE
};
/**
* Check whether the two given orientations combined are a straight road.
* @param start The part that should be build first.
* @param end The part that will be build second.
* @return True iff start and end combined describe a straight road (ROAD_X or ROAD_Y).
*/
static bool IsStraight(RoadPartOrientation start, RoadPartOrientation end)
{
switch (start) {
case RoadPartOrientation::NW: return end == RoadPartOrientation::SE;
case RoadPartOrientation::NE: return end == RoadPartOrientation::SW;
case RoadPartOrientation::SW: return end == RoadPartOrientation::NE;
case RoadPartOrientation::SE: return end == RoadPartOrientation::NW;
default: NOT_REACHED();
}
}
/**
* Check whether the given existing bits the start and end part can be build.
* As the function assumes the bits being build on a slope that does not
@@ -150,9 +176,9 @@
* @param end The part that will be build second.
* @return True if and only if the road bits can be build.
*/
static bool CheckAutoExpandedRoadBits(const Array<> &existing, int32_t start, int32_t end)
static bool CheckAutoExpandedRoadBits(const Array<RoadPartOrientation> &existing, RoadPartOrientation start, RoadPartOrientation end)
{
return (start + end == 0) && (existing.empty() || existing[0] == start || existing[0] == end);
return IsStraight(start, end) && (existing.empty() || existing[0] == start || existing[0] == end);
}
/**
@@ -165,7 +191,7 @@ static bool CheckAutoExpandedRoadBits(const Array<> &existing, int32_t start, in
* they are build or 2 when building the first part automatically
* builds the second part.
*/
static int32_t LookupWithoutBuildOnSlopes(::Slope slope, const Array<> &existing, int32_t start, int32_t end)
static int32_t LookupWithoutBuildOnSlopes(::Slope slope, const Array<RoadPartOrientation> &existing, RoadPartOrientation start, RoadPartOrientation end)
{
switch (slope) {
/* Flat slopes can always be build. */
@@ -177,9 +203,9 @@ static int32_t LookupWithoutBuildOnSlopes(::Slope slope, const Array<> &existing
* in the game have been changed.
*/
case SLOPE_NE: case SLOPE_SW:
return (CheckAutoExpandedRoadBits(existing, start, end) && (start == 1 || end == 1)) ? (existing.empty() ? 2 : 1) : 0;
return (CheckAutoExpandedRoadBits(existing, start, end) && (start == RoadPartOrientation::SW || end == RoadPartOrientation::SW)) ? (existing.empty() ? 2 : 1) : 0;
case SLOPE_SE: case SLOPE_NW:
return (CheckAutoExpandedRoadBits(existing, start, end) && (start != 1 && end != 1)) ? (existing.empty() ? 2 : 1) : 0;
return (CheckAutoExpandedRoadBits(existing, start, end) && (start != RoadPartOrientation::SW && end != RoadPartOrientation::SW)) ? (existing.empty() ? 2 : 1) : 0;
/* Any other tile cannot be built on. */
default:
@@ -192,13 +218,13 @@ static int32_t LookupWithoutBuildOnSlopes(::Slope slope, const Array<> &existing
* @param neighbour The neighbour.
* @return The rotate neighbour data.
*/
static int32_t RotateNeighbour(int32_t neighbour)
static RoadPartOrientation RotateNeighbour(RoadPartOrientation neighbour)
{
switch (neighbour) {
case -2: return -1;
case -1: return 2;
case 1: return -2;
case 2: return 1;
case RoadPartOrientation::NW: return RoadPartOrientation::NE;
case RoadPartOrientation::NE: return RoadPartOrientation::SE;
case RoadPartOrientation::SE: return RoadPartOrientation::SW;
case RoadPartOrientation::SW: return RoadPartOrientation::NW;
default: NOT_REACHED();
}
}
@@ -208,13 +234,13 @@ static int32_t RotateNeighbour(int32_t neighbour)
* @param neighbour The neighbour.
* @return The bits representing the direction.
*/
static RoadBits NeighbourToRoadBits(int32_t neighbour)
static RoadBits NeighbourToRoadBits(RoadPartOrientation neighbour)
{
switch (neighbour) {
case -2: return ROAD_NW;
case -1: return ROAD_NE;
case 2: return ROAD_SE;
case 1: return ROAD_SW;
case RoadPartOrientation::NW: return ROAD_NW;
case RoadPartOrientation::NE: return ROAD_NE;
case RoadPartOrientation::SE: return ROAD_SE;
case RoadPartOrientation::SW: return ROAD_SW;
default: NOT_REACHED();
}
}
@@ -229,7 +255,7 @@ static RoadBits NeighbourToRoadBits(int32_t neighbour)
* they are build or 2 when building the first part automatically
* builds the second part.
*/
static int32_t LookupWithBuildOnSlopes(::Slope slope, const Array<> &existing, int32_t start, int32_t end)
static int32_t LookupWithBuildOnSlopes(::Slope slope, const Array<RoadPartOrientation> &existing, RoadPartOrientation start, RoadPartOrientation end)
{
/* Steep slopes behave the same as slopes with one corner raised. */
if (IsSteepSlope(slope)) {
@@ -245,13 +271,13 @@ static int32_t LookupWithBuildOnSlopes(::Slope slope, const Array<> &existing, i
SLOPE_W, SLOPE_EW, SLOPE_SW, SLOPE_WSE,
SLOPE_W, SLOPE_SW, SLOPE_EW, SLOPE_WSE,
SLOPE_SW, SLOPE_WSE, SLOPE_WSE};
static const byte base_rotates[] = {0, 0, 1, 0, 2, 0, 1, 0, 3, 3, 2, 3, 2, 2, 1};
static const uint8_t base_rotates[] = {0, 0, 1, 0, 2, 0, 1, 0, 3, 3, 2, 3, 2, 2, 1};
if (slope >= (::Slope)lengthof(base_slopes)) {
/* This slope is an invalid slope, so ignore it. */
return -1;
}
byte base_rotate = base_rotates[slope];
uint8_t base_rotate = base_rotates[slope];
slope = base_slopes[slope];
/* Some slopes don't need rotating, so return early when we know we do
@@ -287,7 +313,7 @@ static int32_t LookupWithBuildOnSlopes(::Slope slope, const Array<> &existing, i
RoadBits start_roadbits = NeighbourToRoadBits(start);
RoadBits new_roadbits = start_roadbits | NeighbourToRoadBits(end);
RoadBits existing_roadbits = ROAD_NONE;
for (int32_t neighbour : existing) {
for (RoadPartOrientation neighbour : existing) {
for (int j = 0; j < base_rotate; j++) {
neighbour = RotateNeighbour(neighbour);
}
@@ -356,48 +382,44 @@ static int32_t LookupWithBuildOnSlopes(::Slope slope, const Array<> &existing, i
}
/**
* Normalise all input data so we can easily handle it without needing
* to call the API lots of times or create large if-elseif-elseif-else
* constructs.
* In this case it means that a TileXY(0, -1) becomes -2 and TileXY(0, 1)
* becomes 2. TileXY(-1, 0) and TileXY(1, 0) stay respectively -1 and 1.
* Any other value means that it is an invalid tile offset.
* @param tile The tile to normalise.
* @return True if and only if the tile offset is valid.
* Normalise all input data (tile indices) so we can easily handle it without needing
* to call the API lots of times or create large if-elseif-elseif-else constructs.
* @param tile The tile to get the orientation from.
* @return The orientation or an empty optional when the input is invalid..
*/
static bool NormaliseTileOffset(int32_t *tile)
static std::optional<RoadPartOrientation> ToRoadPartOrientation(const TileIndex &tile)
{
if (*tile == 1 || *tile == -1) return true;
if (*tile == ::TileDiffXY(0, -1)) {
*tile = -2;
return true;
}
if (*tile == ::TileDiffXY(0, 1)) {
*tile = 2;
return true;
}
return false;
if (tile == ScriptMap::GetTileIndex(0, -1)) return RoadPartOrientation::NW;
if (tile == ScriptMap::GetTileIndex(1, 0)) return RoadPartOrientation::SW;
if (tile == ScriptMap::GetTileIndex(0, 1)) return RoadPartOrientation::SE;
if (tile == ScriptMap::GetTileIndex(-1, 0)) return RoadPartOrientation::NE;
return std::nullopt;
}
/* static */ SQInteger ScriptRoad::CanBuildConnectedRoadParts(ScriptTile::Slope slope_, Array<> &&existing, TileIndex start_, TileIndex end_)
/* static */ SQInteger ScriptRoad::CanBuildConnectedRoadParts(ScriptTile::Slope slope_, Array<TileIndex> &&existing, TileIndex start, TileIndex end)
{
::Slope slope = (::Slope)slope_;
int32_t start = start_.base();
int32_t end = end_.base();
/* The start tile and end tile cannot be the same tile either. */
if (start == end) return -1;
for (size_t i = 0; i < existing.size(); i++) {
if (!NormaliseTileOffset(&existing[i])) return -1;
std::vector<RoadPartOrientation> existing_orientations;
existing_orientations.reserve(existing.size());
for (const auto &t : existing) {
auto orientation = ToRoadPartOrientation(t);
if (!orientation) return -1;
existing_orientations.push_back(*orientation);
}
if (!NormaliseTileOffset(&start)) return -1;
if (!NormaliseTileOffset(&end)) return -1;
auto start_orientation = ToRoadPartOrientation(start);
auto end_orientation = ToRoadPartOrientation(end);
if (!start_orientation || !end_orientation) return -1;
/* Without build on slopes the characteristics are vastly different, so use
* a different helper function (one that is much simpler). */
return _settings_game.construction.build_on_slopes ? LookupWithBuildOnSlopes(slope, existing, start, end) : LookupWithoutBuildOnSlopes(slope, existing, start, end);
return _settings_game.construction.build_on_slopes ?
LookupWithBuildOnSlopes(slope, existing_orientations, *start_orientation, *end_orientation) :
LookupWithoutBuildOnSlopes(slope, existing_orientations, *start_orientation, *end_orientation);
}
/* static */ SQInteger ScriptRoad::CanBuildConnectedRoadPartsHere(TileIndex tile, TileIndex start, TileIndex end)
@@ -405,8 +427,12 @@ static bool NormaliseTileOffset(int32_t *tile)
if (!::IsValidTile(tile) || !::IsValidTile(start) || !::IsValidTile(end)) return -1;
if (::DistanceManhattan(tile, start) != 1 || ::DistanceManhattan(tile, end) != 1) return -1;
/* ROAD_NW ROAD_SW ROAD_SE ROAD_NE */
const TileIndexDiff neighbours[] = {::TileDiffXY(0, -1), ::TileDiffXY(1, 0), ::TileDiffXY(0, 1), ::TileDiffXY(-1, 0)};
const TileIndex neighbours[] = {
ScriptMap::GetTileIndex(0, -1), // ROAD_NW
ScriptMap::GetTileIndex(1, 0), // ROAD_SW
ScriptMap::GetTileIndex(0, 1), // ROAD_SE
ScriptMap::GetTileIndex(-1, 0), // ROAD_NE
};
::RoadBits rb = ::ROAD_NONE;
if (::IsNormalRoadTile(tile)) {
@@ -415,7 +441,7 @@ static bool NormaliseTileOffset(int32_t *tile)
rb = ::GetAnyRoadBits(tile, RTT_ROAD) | ::GetAnyRoadBits(tile, RTT_TRAM);
}
Array<> existing;
Array<TileIndex> existing;
for (uint i = 0; i < lengthof(neighbours); i++) {
if (HasBit(rb, i)) existing.emplace_back(neighbours[i]);
}
@@ -442,7 +468,7 @@ static bool NeighbourHasReachableRoad(::RoadType rt, TileIndex start_tile, DiagD
case MP_STATION:
if (::IsDriveThroughStopTile(neighbour_tile)) {
return (::DiagDirToAxis(neighbour) == ::DiagDirToAxis(::GetRoadStopDir(neighbour_tile)));
return ::DiagDirToAxis(neighbour) == ::GetDriveThroughStopAxis(neighbour_tile);
}
return false;
@@ -478,14 +504,16 @@ static bool NeighbourHasReachableRoad(::RoadType rt, TileIndex start_tile, DiagD
{
if (!IsRoadStationTile(station)) return INVALID_TILE;
return station + ::TileOffsByDiagDir(::GetRoadStopDir(station));
if (::IsBayRoadStopTile(station)) return station + ::TileOffsByDiagDir(::GetBayRoadStopDir(station));
return station - ::TileOffsByAxis(::GetDriveThroughStopAxis(station));
}
/* static */ TileIndex ScriptRoad::GetDriveThroughBackTile(TileIndex station)
{
if (!IsDriveThroughRoadStationTile(station)) return INVALID_TILE;
return station + ::TileOffsByDiagDir(::ReverseDiagDir(::GetRoadStopDir(station)));
return station + ::TileOffsByAxis(::GetDriveThroughStopAxis(station));
}
/* static */ bool ScriptRoad::_BuildRoadInternal(TileIndex start, TileIndex end, bool one_way, bool full)
@@ -604,7 +632,7 @@ static bool NeighbourHasReachableRoad(::RoadType rt, TileIndex start_tile, DiagD
EnforceCompanyModeValid(false);
EnforcePrecondition(false, ::IsValidTile(tile));
EnforcePrecondition(false, IsTileType(tile, MP_STATION));
EnforcePrecondition(false, IsRoadStop(tile));
EnforcePrecondition(false, IsStationRoadStop(tile));
return ScriptObject::Command<CMD_REMOVE_ROAD_STOP>::Do(tile, 1, 1, GetRoadStopType(tile), false);
}

View File

@@ -22,6 +22,8 @@ class ScriptRoad : public ScriptObject {
public:
/**
* All road related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Base for road building / maintaining errors */
@@ -246,7 +248,7 @@ public:
* they are build or 2 when building the first part automatically
* builds the second part. -1 means the preconditions are not met.
*/
static SQInteger CanBuildConnectedRoadParts(ScriptTile::Slope slope, Array<> &&existing, TileIndex start, TileIndex end);
static SQInteger CanBuildConnectedRoadParts(ScriptTile::Slope slope, Array<TileIndex> &&existing, TileIndex start, TileIndex end);
/**
* Lookup function for building road parts independent of whether the

View File

@@ -35,7 +35,7 @@
/* static */ bool ScriptSign::SetName(SignID sign_id, Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceDeityOrCompanyModeValid(false);
EnforcePrecondition(false, IsValidSign(sign_id));
@@ -72,7 +72,7 @@
/* static */ SignID ScriptSign::BuildSign(TileIndex location, Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceDeityOrCompanyModeValid(INVALID_SIGN);
EnforcePrecondition(INVALID_SIGN, ::IsValidTile(location));

View File

@@ -21,6 +21,8 @@ class ScriptSign : public ScriptObject {
public:
/**
* All sign related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {

View File

@@ -25,20 +25,22 @@ public:
/**
* Apply a filter when building the list.
* @param filter_function The function which will be doing the filtering.
* @param params The params to give to the filters (minus the first param,
* @param ... The params to give to the filters (minus the first param,
* which is always the index-value).
* @note You can write your own filters and use them. Just remember that
* the first parameter should be the index-value, and it should return
* a bool.
* @note Example:
* @code
* function Contains(sign_id, str)
* {
* local name = ScriptSign.GetName(sign_id);
* return name != null && name.find(str) != null;
* }
* ScriptSignList(Contains, "something");
* local signs = ScriptSignList(Contains, "something");
* @endcode
*/
ScriptSignList(void *filter_function, int params, ...);
ScriptSignList(function filter_function, ...);
#else
ScriptSignList(HSQUIRRELVM);
#endif /* DOXYGEN_API */

View File

@@ -22,6 +22,8 @@ class ScriptStation : public ScriptBaseStation {
public:
/**
* All station related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Base for station related errors */

View File

@@ -32,7 +32,7 @@ ScriptStationList_Vehicle::ScriptStationList_Vehicle(VehicleID vehicle_id)
{
if (!ScriptVehicle::IsPrimaryVehicle(vehicle_id)) return;
Vehicle *v = ::Vehicle::Get(vehicle_id);
const Vehicle *v = ::Vehicle::Get(vehicle_id);
for (Order *o = v->GetFirstOrder(); o != nullptr; o = o->next) {
if (o->IsType(OT_GOTO_STATION)) this->AddItem(o->GetDestination());

View File

@@ -45,7 +45,7 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type)
/* static */ ScriptStoryPage::StoryPageID ScriptStoryPage::New(ScriptCompany::CompanyID company, Text *title)
{
CCountedPtr<Text> counter(title);
ScriptObjectRef counter(title);
EnforceDeityMode(STORY_PAGE_INVALID);
EnforcePrecondition(STORY_PAGE_INVALID, company == ScriptCompany::COMPANY_INVALID || ScriptCompany::ResolveCompanyID(company) != ScriptCompany::COMPANY_INVALID);
@@ -62,7 +62,7 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type)
/* static */ ScriptStoryPage::StoryPageElementID ScriptStoryPage::NewElement(StoryPageID story_page_id, StoryPageElementType type, SQInteger reference, Text *text)
{
CCountedPtr<Text> counter(text);
ScriptObjectRef counter(text);
::StoryPageElementType btype = static_cast<::StoryPageElementType>(type);
@@ -109,13 +109,13 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type)
/* static */ bool ScriptStoryPage::UpdateElement(StoryPageElementID story_page_element_id, SQInteger reference, Text *text)
{
CCountedPtr<Text> counter(text);
ScriptObjectRef counter(text);
EnforceDeityMode(false);
EnforcePrecondition(false, IsValidStoryPageElement(story_page_element_id));
StoryPageElement *pe = StoryPageElement::Get(story_page_element_id);
StoryPage *p = StoryPage::Get(pe->page);
const StoryPageElement *pe = StoryPageElement::Get(story_page_element_id);
const StoryPage *p = StoryPage::Get(pe->page);
::StoryPageElementType type = pe->type;
std::string encoded_text;
@@ -165,7 +165,7 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type)
/* static */ bool ScriptStoryPage::SetTitle(StoryPageID story_page_id, Text *title)
{
CCountedPtr<Text> counter(title);
ScriptObjectRef counter(title);
EnforcePrecondition(false, IsValidStoryPage(story_page_id));
EnforceDeityMode(false);

View File

@@ -57,7 +57,7 @@ public:
/**
* Story page element types.
*/
enum StoryPageElementType : byte {
enum StoryPageElementType : uint8_t {
SPET_TEXT = ::SPET_TEXT, ///< An element that displays a block of text.
SPET_LOCATION = ::SPET_LOCATION, ///< An element that displays a single line of text along with a button to view the referenced location.
SPET_GOAL = ::SPET_GOAL, ///< An element that displays a goal.
@@ -75,7 +75,7 @@ public:
* Formatting and layout flags for story page buttons.
* The SPBF_FLOAT_LEFT and SPBF_FLOAT_RIGHT flags can not be combined.
*/
enum StoryPageButtonFlags : byte {
enum StoryPageButtonFlags : uint8_t {
SPBF_NONE = ::SPBF_NONE, ///< No special formatting for button.
SPBF_FLOAT_LEFT = ::SPBF_FLOAT_LEFT, ///< Button is placed to the left of the following paragraph.
SPBF_FLOAT_RIGHT = ::SPBF_FLOAT_RIGHT, ///< Button is placed to the right of the following paragraph.
@@ -84,7 +84,7 @@ public:
/**
* Mouse cursors usable by story page buttons.
*/
enum StoryPageButtonCursor : byte {
enum StoryPageButtonCursor : uint8_t {
SPBC_MOUSE = ::SPBC_MOUSE,
SPBC_ZZZ = ::SPBC_ZZZ,
SPBC_BUOY = ::SPBC_BUOY,
@@ -146,7 +146,7 @@ public:
* Colour codes usable for story page button elements.
* Place a colour value in the lowest 8 bits of the \c reference parameter to the button.
*/
enum StoryPageButtonColour : byte {
enum StoryPageButtonColour : uint8_t {
SPBC_DARK_BLUE = ::COLOUR_DARK_BLUE,
SPBC_PALE_GREEN = ::COLOUR_PALE_GREEN,
SPBC_PINK = ::COLOUR_PINK,
@@ -203,8 +203,8 @@ public:
* @param reference A reference value to the object that is referred to by some page element types.
* When type is SPET_GOAL, this is the goal ID.
* When type is SPET_LOCATION, this is the TileIndex.
* When type is a button, this is additional parameters for the button,
* use the #BuildPushButtonReference, #BuildTileButtonReference, or #BuildVehicleButtonReference functions to make the values.
* When type is a button, this is the ID returned by
* #MakePushButtonReference, #MakeTileButtonReference, or #MakeVehicleButtonReference.
* @param text The body text of page elements that allow custom text. (SPET_TEXT and SPET_LOCATION)
* @return The new StoryPageElementID, or STORY_PAGE_ELEMENT_INVALID if it failed.
* @pre ScriptCompanyMode::IsDeity().
@@ -265,18 +265,20 @@ public:
/**
* Get the page date which is displayed at the top of each page.
* @param story_page_id The story page to get the date of.
* @return The date
* @return The calendar-date
* @pre IsValidStoryPage(story_page_id).
* @see \ref ScriptCalendarTime
*/
static ScriptDate::Date GetDate(StoryPageID story_page_id);
/**
* Update date of a story page. The date is shown in the top left of the page
* @param story_page_id The story page to set the date for.
* @param date Date to display at the top of story page or ScriptDate::DATE_INVALID to disable showing date on this page. (also, @see ScriptDate)
* @param date Calendar-date to display at the top of story page or ScriptDate::DATE_INVALID to disable showing date on this page. (also, @see ScriptDate)
* @return True if the action succeeded.
* @pre ScriptCompanyMode::IsDeity().
* @pre IsValidStoryPage(story_page_id).
* @see \ref ScriptCalendarTime
*/
static bool SetDate(StoryPageID story_page_id, ScriptDate::Date date);
@@ -329,14 +331,14 @@ public:
/**
* Check whether this is a valid story page button flag.
* @param colour The StoryPageButtonFlags to check.
* @param flags The StoryPageButtonFlags to check.
* @return True if and only if this story page button flag is valid.
*/
static bool IsValidStoryPageButtonFlags(StoryPageButtonFlags flags);
/**
* Check whether this is a valid story page button cursor.
* @param colour The StoryPageButtonCursor to check.
* @param cursor The StoryPageButtonCursor to check.
* @return True if and only if this story page button cursor is valid.
*/
static bool IsValidStoryPageButtonCursor(StoryPageButtonCursor cursor);

View File

@@ -47,7 +47,7 @@
{
if (!IsAwarded(subsidy_id)) return ScriptCompany::COMPANY_INVALID;
return (ScriptCompany::CompanyID)((byte)::Subsidy::Get(subsidy_id)->awarded);
return (ScriptCompany::CompanyID)((uint8_t)::Subsidy::Get(subsidy_id)->awarded);
}
/* static */ ScriptDate::Date ScriptSubsidy::GetExpireDate(SubsidyID subsidy_id)

View File

@@ -74,14 +74,15 @@ public:
static ScriptCompany::CompanyID GetAwardedTo(SubsidyID subsidy_id);
/**
* Get the date this subsidy expires. In case the subsidy is already
* awarded, return the date the subsidy expires, else, return the date the
* Get the economy-date this subsidy expires. In case the subsidy is already
* awarded, return the economy-date the subsidy expires, else, return the economy-date the
* offer expires.
* @param subsidy_id The SubsidyID to check.
* @pre IsValidSubsidy(subsidy_id).
* @return The last valid date of this subsidy.
* @return The last valid economy-date of this subsidy.
* @note The return value of this function will change if the subsidy is
* awarded.
* @see \ref ScriptEconomyTime
*/
static ScriptDate::Date GetExpireDate(SubsidyID subsidy_id);

View File

@@ -25,19 +25,21 @@ public:
/**
* Apply a filter when building the list.
* @param filter_function The function which will be doing the filtering.
* @param params The params to give to the filters (minus the first param,
* @param ... The params to give to the filters (minus the first param,
* which is always the index-value).
* @note You can write your own filters and use them. Just remember that
* the first parameter should be the index-value, and it should return
* a bool.
* @note Example:
* @code
* function IsType(subsidy_id, type)
* {
* return ScriptSubsidy.GetSourceType(subsidy_id) == type;
* }
* ScriptSubsidyList(IsType, ScriptSubsidy.SPT_TOWN);
* local town_subs = ScriptSubsidyList(IsType, ScriptSubsidy.SPT_TOWN);
* @endcode
*/
ScriptSubsidyList(void *filter_function, int params, ...);
ScriptSubsidyList(function filter_function, ...);
#else
ScriptSubsidyList(HSQUIRRELVM vm);
#endif /* DOXYGEN_API */

View File

@@ -20,13 +20,8 @@
#include "../../safeguards.h"
RawText::RawText(const std::string &text) : text(text)
{
}
ScriptText::ScriptText(HSQUIRRELVM vm) :
ZeroedMemoryAllocator()
ScriptText::ScriptText(HSQUIRRELVM vm)
{
int nparam = sq_gettop(vm) - 1;
if (nparam < 1) {
@@ -173,7 +168,7 @@ std::string ScriptText::GetEncodedText()
void ScriptText::_FillParamList(ParamList &params, ScriptTextList &seen_texts)
{
if (std::find(seen_texts.begin(), seen_texts.end(), this) != seen_texts.end()) throw Script_FatalError(fmt::format("{}: Circular reference detected", GetGameStringName(this->string)));
if (std::ranges::find(seen_texts, this) != seen_texts.end()) throw Script_FatalError(fmt::format("{}: Circular reference detected", GetGameStringName(this->string)));
seen_texts.push_back(this);
for (int i = 0; i < this->paramc; i++) {
@@ -198,13 +193,21 @@ void ScriptText::ParamCheck::Encode(std::back_insert_iterator<std::string> &outp
{
if (this->cmd == nullptr) this->cmd = cmd;
if (this->used) return;
if (std::holds_alternative<std::string>(*this->param)) fmt::format_to(output, ":\"{}\"", std::get<std::string>(*this->param));
if (std::holds_alternative<SQInteger>(*this->param)) fmt::format_to(output, ":{:X}", std::get<SQInteger>(*this->param));
if (std::holds_alternative<ScriptTextRef>(*this->param)) {
fmt::format_to(output, ":");
Utf8Encode(output, SCC_ENCODED);
fmt::format_to(output, "{:X}", std::get<ScriptTextRef>(*this->param)->string);
}
struct visitor {
std::back_insert_iterator<std::string> &output;
void operator()(const std::string &value) { fmt::format_to(this->output, ":\"{}\"", value); }
void operator()(const SQInteger &value) { fmt::format_to(this->output, ":{:X}", value); }
void operator()(const ScriptTextRef &value)
{
fmt::format_to(this->output, ":");
Utf8Encode(this->output, SCC_ENCODED);
fmt::format_to(this->output, "{:X}", value->string);
}
};
std::visit(visitor{output}, *this->param);
this->used = true;
}

View File

@@ -11,7 +11,6 @@
#define SCRIPT_TEXT_HPP
#include "script_object.hpp"
#include "../../core/alloc_type.hpp"
#include <variant>
@@ -42,7 +41,7 @@ public:
*/
class RawText : public Text {
public:
RawText(const std::string &text);
RawText(const std::string &text) : text(text) {}
std::string GetEncodedText() override { return this->text; }
private:
@@ -72,7 +71,7 @@ private:
*
* @api game
*/
class ScriptText : public Text , public ZeroedMemoryAllocator {
class ScriptText : public Text {
public:
static const int SCRIPT_TEXT_MAX_PARAMETERS = 20; ///< The maximum amount of parameters you can give to one object.
@@ -112,14 +111,14 @@ public:
* @param parameter Which parameter to set.
* @param value The value of the parameter. Has to be string, integer or an instance of the class ScriptText.
*/
void SetParam(int parameter, Object value);
void SetParam(int parameter, object value);
/**
* Add a value as parameter (appending it).
* @param value The value of the parameter. Has to be string, integer or an instance of the class ScriptText.
* @return The same object as on which this is called, so you can chain.
*/
ScriptText *AddParam(Object value);
ScriptText *AddParam(object value);
#endif /* DOXYGEN_API */
/**
@@ -136,10 +135,10 @@ private:
StringID owner;
int idx;
Param *param;
bool used;
const char *cmd;
bool used = false;
const char *cmd = nullptr;
ParamCheck(StringID owner, int idx, Param *param) : owner(owner), idx(idx), param(param), used(false), cmd(nullptr) {}
ParamCheck(StringID owner, int idx, Param *param) : owner(owner), idx(idx), param(param) {}
void Encode(std::back_insert_iterator<std::string> &output, const char *cmd);
};
@@ -148,8 +147,8 @@ private:
using ParamSpan = std::span<ParamCheck>;
StringID string;
Param param[SCRIPT_TEXT_MAX_PARAMETERS];
int paramc;
std::array<Param, SCRIPT_TEXT_MAX_PARAMETERS> param = {};
int paramc = 0;
/**
* Internal function to recursively fill a list of parameters.

View File

@@ -199,8 +199,7 @@
{
if (!::IsValidTile(tile) || !::IsValidCorner((::Corner)corner)) return -1;
int z;
::Slope slope = ::GetTileSlope(tile, &z);
auto [slope, z] = ::GetTileSlopeZ(tile);
return (z + ::GetSlopeZInCorner(slope, (::Corner)corner));
}
@@ -210,7 +209,7 @@
if (::IsTileType(tile, MP_HOUSE)) return ScriptCompany::COMPANY_INVALID;
if (::IsTileType(tile, MP_INDUSTRY)) return ScriptCompany::COMPANY_INVALID;
return ScriptCompany::ResolveCompanyID((ScriptCompany::CompanyID)(byte)::GetTileOwner(tile));
return ScriptCompany::ResolveCompanyID((ScriptCompany::CompanyID)(uint8_t)::GetTileOwner(tile));
}
/* static */ bool ScriptTile::HasTransportType(TileIndex tile, TransportType transport_type)
@@ -298,7 +297,8 @@
EnforcePrecondition(false, ::IsValidTile(tile));
EnforcePrecondition(false, width >= 1 && width <= 20);
EnforcePrecondition(false, height >= 1 && height <= 20);
TileIndex end_tile = tile + ::TileDiffXY(width - 1, height - 1);
TileIndex end_tile = TileAddWrap(tile, width - 1, height - 1);
EnforcePrecondition(false, ::IsValidTile(end_tile));
return ScriptObject::Command<CMD_PLANT_TREE>::Do(tile, end_tile, TREE_INVALID, false);
}

View File

@@ -23,6 +23,8 @@ class ScriptTile : public ScriptObject {
public:
/**
* Error messages related to modifying tiles.
*
* @see ScriptErrorType
*/
enum ErrorMessages {

View File

@@ -42,7 +42,7 @@
/* static */ bool ScriptTown::SetName(TownID town_id, Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceDeityMode(false);
EnforcePrecondition(false, IsValidTown(town_id));
@@ -57,7 +57,7 @@
/* static */ bool ScriptTown::SetText(TownID town_id, Text *text)
{
CCountedPtr<Text> counter(text);
ScriptObjectRef counter(text);
EnforceDeityMode(false);
EnforcePrecondition(false, IsValidTown(town_id));
@@ -283,7 +283,7 @@
/* static */ bool ScriptTown::FoundTown(TileIndex tile, TownSize size, bool city, RoadLayout layout, Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceDeityOrCompanyModeValid(false);
EnforcePrecondition(false, ScriptCompanyMode::IsDeity() || _settings_game.economy.found_town != TF_FORBIDDEN);
@@ -294,7 +294,7 @@
EnforcePrecondition(false, layout >= ROAD_LAYOUT_ORIGINAL && layout <= ROAD_LAYOUT_RANDOM);
} else {
/* The layout parameter is ignored for AIs when custom layouts is disabled. */
layout = (RoadLayout) (byte)_settings_game.economy.town_layout;
layout = (RoadLayout) (uint8_t)_settings_game.economy.town_layout;
}
std::string text;

View File

@@ -48,7 +48,8 @@ public:
TOWN_ACTION_ADVERTISE_LARGE = 2,
/**
* Rebuild the roads of this town for 6 months.
* Rebuild the roads of this town for 6 economy-months.
* @see \ref ScriptEconomyTime
*/
TOWN_ACTION_ROAD_REBUILD = 3,
@@ -58,12 +59,14 @@ public:
TOWN_ACTION_BUILD_STATUE = 4,
/**
* Fund the creation of extra buildings for 3 months.
* Fund the creation of extra buildings for 3 economy-months.
* @see \ref ScriptEconomyTime
*/
TOWN_ACTION_FUND_BUILDINGS = 5,
/**
* Buy exclusive rights for this town for 12 months.
* Buy exclusive rights for this town for 12 economy-months.
* @see \ref ScriptEconomyTime
*/
TOWN_ACTION_BUY_RIGHTS = 6,
@@ -191,92 +194,100 @@ public:
static TileIndex GetLocation(TownID town_id);
/**
* Get the total last month's production of the given cargo at a town.
* Get the total last economy-month's production of the given cargo at a town.
* @param town_id The index of the town.
* @param cargo_id The index of the cargo.
* @pre IsValidTown(town_id).
* @pre ScriptCargo::IsValidCargo(cargo_id).
* @return The last month's production of the given cargo for this town.
* @return The last economy-month's production of the given cargo for this town.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetLastMonthProduction(TownID town_id, CargoID cargo_id);
/**
* Get the total amount of cargo supplied from a town last month.
* Get the total amount of cargo supplied from a town last economy-month.
* @param town_id The index of the town.
* @param cargo_id The index of the cargo.
* @pre IsValidTown(town_id).
* @pre ScriptCargo::IsValidCargo(cargo_id).
* @return The amount of cargo supplied for transport from this town last month.
* @return The amount of cargo supplied for transport from this town last economy-month.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetLastMonthSupplied(TownID town_id, CargoID cargo_id);
/**
* Get the percentage of transported production of the given cargo at a town.
* Get the percentage of transported production of the given cargo at a town last economy-month.
* @param town_id The index of the town.
* @param cargo_id The index of the cargo.
* @pre IsValidTown(town_id).
* @pre ScriptCargo::IsValidCargo(cargo_id).
* @return The percentage of given cargo transported from this town last month.
* @return The percentage of given cargo transported from this town last economy-month.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetLastMonthTransportedPercentage(TownID town_id, CargoID cargo_id);
/**
* Get the total amount of cargo effects received by a town last month.
* Get the total amount of cargo effects received by a town last economy-month.
* @param town_id The index of the town.
* @param towneffect_id The index of the cargo.
* @pre IsValidTown(town_id).
* @pre ScriptCargo::IsValidTownEffect(cargo_id).
* @return The amount of cargo received by this town last month for this cargo effect.
* @return The amount of cargo received by this town last economy-month for this cargo effect.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetLastMonthReceived(TownID town_id, ScriptCargo::TownEffect towneffect_id);
/**
* Set the goal of a cargo for this town.
* Set the goal of a cargo per economy-month for this town.
* @param town_id The index of the town.
* @param towneffect_id The index of the towneffect.
* @param goal The new goal.
* @param goal The new goal amount for cargo delivered per economy-month.
* The value will be clamped to 0 .. MAX(uint32_t).
* @pre IsValidTown(town_id).
* @pre ScriptCargo::IsValidTownEffect(towneffect_id).
* @pre ScriptCompanyMode::IsDeity().
* @return True if the action succeeded.
* @see \ref ScriptEconomyTime
* @api -ai
*/
static bool SetCargoGoal(TownID town_id, ScriptCargo::TownEffect towneffect_id, SQInteger goal);
/**
* Get the amount of cargo that needs to be delivered (per TownEffect) for a
* Get the amount of cargo per economy-month that needs to be delivered (per TownEffect) for a
* town to grow. All goals need to be reached before a town will grow.
* @param town_id The index of the town.
* @param towneffect_id The index of the towneffect.
* @pre IsValidTown(town_id).
* @pre ScriptCargo::IsValidTownEffect(towneffect_id).
* @return The goal of the cargo.
* @return The goal of the cargo (amount per economy-month).
* @note Goals can change over time. For example with a changing snowline, or
* with a growing town.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetCargoGoal(TownID town_id, ScriptCargo::TownEffect towneffect_id);
/**
* Set the amount of days between town growth.
* Set the amount of economy-days between town growth.
* @param town_id The index of the town.
* @param days_between_town_growth The amount of days between town growth, TOWN_GROWTH_NONE or TOWN_GROWTH_NORMAL.
* @param days_between_town_growth The amount of economy-days between town growth, TOWN_GROWTH_NONE or TOWN_GROWTH_NORMAL.
* @pre IsValidTown(town_id).
* @pre days_between_town_growth <= 880 || days_between_town_growth == TOWN_GROWTH_NONE || days_between_town_growth == TOWN_GROWTH_NORMAL.
* @return True if the action succeeded.
* @note Even when setting a growth rate, towns only grow when the conditions for growth (SetCargoCoal) are met,
* and the game settings (economy.town_growth_rate) allow town growth at all.
* @note When changing the growth rate, the relative progress is preserved and scaled to the new rate.
* @see \ref ScriptEconomyTime
* @api -ai
*/
static bool SetGrowthRate(TownID town_id, SQInteger days_between_town_growth);
/**
* Get the amount of days between town growth.
* Get the amount of economy-days between town growth.
* @param town_id The index of the town.
* @pre IsValidTown(town_id).
* @return Amount of days between town growth, or TOWN_GROWTH_NONE.
* @return Amount of economy-days between town growth, or TOWN_GROWTH_NONE.
* @note This function does not indicate when it will grow next. It only tells you the time between growths.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetGrowthRate(TownID town_id);
@@ -332,8 +343,9 @@ public:
* Find out how long the town is undergoing road reconstructions.
* @param town_id The town to check.
* @pre IsValidTown(town_id).
* @return The number of months the road reworks are still going to take.
* @return The number of economy-months the road reworks are still going to take.
* The value 0 means that there are currently no road reworks.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetRoadReworkDuration(TownID town_id);
@@ -341,8 +353,9 @@ public:
* Find out how long new buildings are still being funded in a town.
* @param town_id The town to check.
* @pre IsValidTown(town_id).
* @return The number of months building construction is still funded.
* @return The number of economy-months building construction is still funded.
* The value 0 means that there is currently no funding.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetFundBuildingsDuration(TownID town_id);
@@ -361,9 +374,10 @@ public:
* Find out how long the town is under influence of the exclusive rights.
* @param town_id The town to check.
* @pre IsValidTown(town_id).
* @return The number of months the exclusive rights hold.
* @return The number of economy-months the exclusive rights hold.
* The value 0 means that there are currently no exclusive rights
* given out to anyone.
* @see \ref ScriptEconomyTime
*/
static SQInteger GetExclusiveRightsDuration(TownID town_id);

View File

@@ -25,20 +25,23 @@ public:
/**
* Apply a filter when building the list.
* @param filter_function The function which will be doing the filtering.
* @param params The params to give to the filters (minus the first param,
* @param ... The params to give to the filters (minus the first param,
* which is always the index-value).
* @note You can write your own filters and use them. Just remember that
* the first parameter should be the index-value, and it should return
* a bool.
* @note Example:
* ScriptTownList(ScriptTown.IsActionAvailable, ScriptTown.TOWN_ACTION_BRIBE);
* @code
* local bribeable_towns = ScriptTownList(ScriptTown.IsActionAvailable, ScriptTown.TOWN_ACTION_BRIBE);
*
* function MinPopulation(town_id, pop)
* {
* return ScriptTown.GetPopulation(town_id) >= pop;
* }
* ScriptTownList(MinPopulation, 1000);
* local proper_towns = ScriptTownList(MinPopulation, 1000);
* @endcode
*/
ScriptTownList(void *filter_function, int params, ...);
ScriptTownList(function filter_function, ...);
#else
ScriptTownList(HSQUIRRELVM vm);
#endif /* DOXYGEN_API */

View File

@@ -31,8 +31,7 @@
/* If it's a tunnel already, take the easy way out! */
if (IsTunnelTile(tile)) return ::GetOtherTunnelEnd(tile);
int start_z;
Slope start_tileh = ::GetTileSlope(tile, &start_z);
auto [start_tileh, start_z] = ::GetTileSlopeZ(tile);
DiagDirection direction = ::GetInclinedSlopeDirection(start_tileh);
if (direction == INVALID_DIAGDIR) return INVALID_TILE;
@@ -42,7 +41,7 @@
tile += delta;
if (!::IsValidTile(tile)) return INVALID_TILE;
::GetTileSlope(tile, &end_z);
std::tie(std::ignore, end_z) = ::GetTileSlopeZ(tile);
} while (start_z != end_z);
return tile;

View File

@@ -20,6 +20,8 @@ class ScriptTunnel : public ScriptObject {
public:
/**
* All tunnel related errors.
*
* @see ScriptErrorType
*/
enum ErrorMessages {

View File

@@ -7,7 +7,10 @@
/**
* @file script_types.hpp Defines all the types of the game, like IDs of various objects.
*
*/
/**
* @page script_ids Identifying game object
* IDs are used to identify certain objects. They are only unique within the object type, so for example a vehicle may have VehicleID 2009,
* while a station has StationID 2009 at the same time. Also IDs are assigned arbitrary, you cannot assume them to be consecutive.
* Also note that some IDs are static and never change, while others are allocated dynamically and might be
@@ -46,6 +49,14 @@
* <td> game start \ref newgrf_changes "(1)" </td>
* <td> never \ref newgrf_changes "(1)" </td>
* <td> no </td></tr>
* <tr><td>#ObjectType </td><td> NewGRF object type </td>
* <td> game start \ref newgrf_changes "(1)" </td>
* <td> never \ref newgrf_changes "(1)" </td>
* <td> no </td></tr>
* <tr><td>#ScriptErrorType</td><td> error message </td>
* <td> OpenTTD start \ref transient_id "(3)" </td>
* <td> OpenTTD exit </td>
* <td> no </td></tr>
* <tr><td>#SignID </td><td> sign </td>
* <td> construction </td>
* <td> deletion </td>
@@ -54,10 +65,22 @@
* <td> construction </td>
* <td> expiration of 'grey' station sign after deletion </td>
* <td> yes </td></tr>
* <tr><td>#StringID </td><td> translatable text </td>
* <td> OpenTTD start \ref transient_id "(3)" </td>
* <td> OpenTTD exit </td>
* <td> no </td></tr>
* <tr><td>#SubsidyID </td><td> subsidy </td>
* <td> offer announcement </td>
* <td> (offer) expiration </td>
* <td> yes </td></tr>
* <tr><td>#StoryPageID </td><td> story page </td>
* <td> creation </td>
* <td> deletion </td>
* <td> yes </td></tr>
* <tr><td>#StoryPageElementID</td><td> story page element </td>
* <td> creation </td>
* <td> deletion </td>
* <td> yes </td></tr>
* <tr><td>#TileIndex </td><td> tile on map </td>
* <td> game start </td>
* <td> never </td>
@@ -75,6 +98,7 @@
* @remarks
* \li \anchor newgrf_changes (1) in-game changes of newgrfs may reassign/invalidate IDs (will also cause other trouble though).
* \li \anchor dynamic_engines (2) engine IDs are reassigned/invalidated on changing 'allow multiple newgrf engine sets' (only allowed as long as no vehicles are built).
* \li \anchor transient_id (3) string/error IDs are only valid during a session, and may be reassigned/invalidated when loading savegames (so you cannot store them).
*/
#ifndef SCRIPT_TYPES_HPP
@@ -85,27 +109,37 @@
#include "../../tile_type.h"
#include <squirrel.h>
/* Define all types here, so we don't have to include the whole _type.h maze */
typedef uint BridgeType; ///< Internal name, not of any use for you.
typedef byte CargoID; ///< The ID of a cargo.
class CommandCost; ///< The cost of a command.
/* Define all types here, so they are added to the API docs. */
typedef uint BridgeID; ///< The ID of a bridge type.
typedef uint8_t CargoID; ///< The ID of a cargo.
typedef uint16_t EngineID; ///< The ID of an engine.
typedef uint16_t GoalID; ///< The ID of a goal.
typedef uint16_t GroupID; ///< The ID of a group.
typedef uint16_t IndustryID; ///< The ID of an industry.
typedef uint8_t IndustryType; ///< The ID of an industry-type.
typedef OverflowSafeInt64 Money; ///< Money, stored in a 32bit/64bit safe way. For scripts money is always in pounds.
#ifdef DOXYGEN_API
typedef int64_t Money; ///< Money, stored in a 32bit/64bit safe way. For scripts money is always in pounds.
#else
typedef OverflowSafeInt64 Money;
#endif /* DOXYGEN_API */
typedef uint16_t ObjectType; ///< The ID of an object-type.
typedef uint16_t SignID; ///< The ID of a sign.
typedef uint16_t StationID; ///< The ID of a station.
typedef uint32_t StringID; ///< The ID of a string.
typedef uint16_t SubsidyID; ///< The ID of a subsidy.
typedef uint16_t StoryPageID; ///< The ID of a story page.
typedef uint16_t StoryPageElementID; ///< The ID of a story page element.
#ifdef DOXYGEN_API
typedef uint32_t TileIndex; ///< The ID of a map location.
#endif /* DOXYGEN_API */
typedef uint16_t TownID; ///< The ID of a town.
typedef uint32_t VehicleID; ///< The ID of a vehicle.
/* Types we defined ourself, as the OpenTTD core doesn't have them (yet) */
typedef uint ScriptErrorType;///< The types of errors inside the script framework.
typedef BridgeType BridgeID; ///< The ID of a bridge.
/**
* The types of errors inside the script framework.
*
* Possible value are defined inside each API class in an ErrorMessages enum.
*/
typedef uint ScriptErrorType;
#endif /* SCRIPT_TYPES_HPP */

View File

@@ -247,7 +247,7 @@
/* static */ bool ScriptVehicle::SetName(VehicleID vehicle_id, Text *name)
{
CCountedPtr<Text> counter(name);
ScriptObjectRef counter(name);
EnforceCompanyModeValid(false);
EnforcePrecondition(false, IsPrimaryVehicle(vehicle_id));
@@ -353,7 +353,7 @@
if (!IsValidVehicle(vehicle_id)) return ScriptVehicle::VS_INVALID;
const Vehicle *v = ::Vehicle::Get(vehicle_id);
byte vehstatus = v->vehstatus;
uint8_t vehstatus = v->vehstatus;
if (vehstatus & ::VS_CRASHED) return ScriptVehicle::VS_CRASHED;
if (v->breakdown_ctr != 0) return ScriptVehicle::VS_BROKEN;
@@ -462,7 +462,7 @@
{
if (!IsPrimaryVehicle(vehicle_id)) return false;
Vehicle *v = ::Vehicle::Get(vehicle_id);
const Vehicle *v = ::Vehicle::Get(vehicle_id);
return v->orders != nullptr && v->orders->GetNumVehicles() > 1;
}

View File

@@ -20,6 +20,8 @@ class ScriptVehicle : public ScriptObject {
public:
/**
* All vehicle related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Base for vehicle related errors */
@@ -31,7 +33,7 @@ public:
/** Vehicle is not available */
ERR_VEHICLE_NOT_AVAILABLE, // [STR_ERROR_AIRCRAFT_NOT_AVAILABLE, STR_ERROR_ROAD_VEHICLE_NOT_AVAILABLE, STR_ERROR_SHIP_NOT_AVAILABLE, STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE]
/** Vehicle can't be build due to game settigns */
/** Vehicle can't be built due to game settings */
ERR_VEHICLE_BUILD_DISABLED, // [STR_ERROR_CAN_T_BUY_TRAIN, STR_ERROR_CAN_T_BUY_ROAD_VEHICLE, STR_ERROR_CAN_T_BUY_SHIP, STR_ERROR_CAN_T_BUY_AIRCRAFT]
/** Vehicle can't be build in the selected depot */
@@ -186,8 +188,8 @@ public:
* Get the current age of a vehicle.
* @param vehicle_id The vehicle to get the age of.
* @pre IsValidVehicle(vehicle_id).
* @return The current age the vehicle has.
* @note The age is in days.
* @return The current age of the vehicle in calendar-days.
* @see \ref ScriptCalendarTime
*/
static SQInteger GetAge(VehicleID vehicle_id);
@@ -197,8 +199,8 @@ public:
* @param wagon The wagon in the vehicle to get the age of.
* @pre IsValidVehicle(vehicle_id).
* @pre wagon < GetNumWagons(vehicle_id).
* @return The current age the vehicle has.
* @note The age is in days.
* @return The current age of the vehicle in calendar-days.
* @see \ref ScriptCalendarTime
*/
static SQInteger GetWagonAge(VehicleID vehicle_id, SQInteger wagon);
@@ -206,8 +208,8 @@ public:
* Get the maximum age of a vehicle.
* @param vehicle_id The vehicle to get the age of.
* @pre IsPrimaryVehicle(vehicle_id).
* @return The maximum age the vehicle has.
* @note The age is in days.
* @return The maximum age for the vehicle in calendar-days.
* @see \ref ScriptCalendarTime
*/
static SQInteger GetMaxAge(VehicleID vehicle_id);
@@ -215,8 +217,8 @@ public:
* Get the age a vehicle has left (maximum - current).
* @param vehicle_id The vehicle to get the age of.
* @pre IsPrimaryVehicle(vehicle_id).
* @return The age the vehicle has left.
* @note The age is in days.
* @return The remaining age of the vehicle in calendar-days.
* @see \ref ScriptCalendarTime
*/
static SQInteger GetAgeLeft(VehicleID vehicle_id);
@@ -243,10 +245,10 @@ public:
* Get the running cost of this vehicle.
* @param vehicle_id The vehicle to get the running cost of.
* @pre IsPrimaryVehicle(vehicle_id).
* @return The running cost of the vehicle per year.
* @note Cost is per year; divide by 365 to get per day.
* @return The running cost of the vehicle per economy-year.
* @note This is not equal to ScriptEngine::GetRunningCost for Trains, because
* wagons and second engines can add up in the calculation too.
* @see \ref ScriptEconomyTime
*/
static Money GetRunningCost(VehicleID vehicle_id);
@@ -254,7 +256,8 @@ public:
* Get the current profit of a vehicle.
* @param vehicle_id The vehicle to get the profit of.
* @pre IsPrimaryVehicle(vehicle_id).
* @return The current profit the vehicle has.
* @return The profit the vehicle has made this economy-year so far.
* @see \ref ScriptEconomyTime
*/
static Money GetProfitThisYear(VehicleID vehicle_id);
@@ -262,7 +265,8 @@ public:
* Get the profit of last year of a vehicle.
* @param vehicle_id The vehicle to get the profit of.
* @pre IsPrimaryVehicle(vehicle_id).
* @return The profit the vehicle had last year.
* @return The profit the vehicle made in the previous economy-year.
* @see \ref ScriptEconomyTime
*/
static Money GetProfitLastYear(VehicleID vehicle_id);

View File

@@ -26,20 +26,23 @@ public:
/**
* Apply a filter when building the list.
* @param filter_function The function which will be doing the filtering.
* @param params The params to give to the filters (minus the first param,
* @param ... The params to give to the filters (minus the first param,
* which is always the index-value).
* @note You can write your own filters and use them. Just remember that
* the first parameter should be the index-value, and it should return
* a bool.
* @note Example:
* ScriptVehicleList(ScriptVehicle.IsInDepot);
* @code
* local vehs_in_depot = ScriptVehicleList(ScriptVehicle.IsInDepot);
*
* function IsType(vehicle_id, type)
* {
* return ScriptVehicle.GetVehicleType(vehicle_id) == type;
* }
* ScriptVehicleList(IsType, ScriptVehicle.VT_ROAD);
* local road_vehs = ScriptVehicleList(IsType, ScriptVehicle.VT_ROAD);
* @endcode
*/
ScriptVehicleList(void *filter_function, int params, ...);
ScriptVehicleList(function filter_function, ...);
#else
/**
* The constructor wrapper from Squirrel.

View File

@@ -22,6 +22,8 @@ class ScriptWaypoint : public ScriptBaseStation {
public:
/**
* All waypoint related error messages.
*
* @see ScriptErrorType
*/
enum ErrorMessages {
/** Base for waypoint related errors */

View File

@@ -73,7 +73,6 @@ public:
* @param version The version of the Script to load, or -1 of latest.
* @param force_exact_match If true try to find the exact same version
* as specified. If false any compatible version is ok.
* @param is_random Is the Script chosen randomly?
*/
void Change(std::optional<const std::string> name, int version = -1, bool force_exact_match = false);

View File

@@ -15,9 +15,10 @@
#include "../stringfilter_type.h"
#include "../company_base.h"
#include "../company_gui.h"
#include "../dropdown_type.h"
#include "../dropdown_func.h"
#include "../window_func.h"
#include "../network/network.h"
#include "../widgets/dropdown_func.h"
#include "../hotkeys.h"
#include "../company_cmd.h"
#include "../misc_cmd.h"
@@ -66,7 +67,7 @@ struct ScriptListWindow : public Window {
* @param slot The company we're changing the Script for.
* @param show_all Whether to show all available versions.
*/
ScriptListWindow(WindowDesc *desc, CompanyID slot, bool show_all) : Window(desc),
ScriptListWindow(WindowDesc &desc, CompanyID slot, bool show_all) : Window(desc),
slot(slot), show_all(show_all)
{
if (slot == OWNER_DEITY) {
@@ -104,15 +105,15 @@ struct ScriptListWindow : public Window {
SetDParam(0, (this->slot == OWNER_DEITY) ? STR_AI_LIST_CAPTION_GAMESCRIPT : STR_AI_LIST_CAPTION_AI);
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
if (widget != WID_SCRL_LIST) return;
this->line_height = GetCharacterHeight(FS_NORMAL) + padding.height;
resize->width = 1;
resize->height = this->line_height;
size->height = 5 * this->line_height;
resize.width = 1;
resize.height = this->line_height;
size.height = 5 * this->line_height;
}
void DrawWidget(const Rect &r, WidgetID widget) const override
@@ -263,11 +264,11 @@ static constexpr NWidgetPart _nested_script_list_widgets[] = {
};
/** Window definition for the ai list window. */
static WindowDesc _script_list_desc(__FILE__, __LINE__,
static WindowDesc _script_list_desc(
WDP_CENTER, "settings_script_list", 200, 234,
WC_SCRIPT_LIST, WC_NONE,
0,
std::begin(_nested_script_list_widgets), std::end(_nested_script_list_widgets)
_nested_script_list_widgets
);
/**
@@ -278,7 +279,7 @@ static WindowDesc _script_list_desc(__FILE__, __LINE__,
void ShowScriptListWindow(CompanyID slot, bool show_all)
{
CloseWindowByClass(WC_SCRIPT_LIST);
new ScriptListWindow(&_script_list_desc, slot, show_all);
new ScriptListWindow(_script_list_desc, slot, show_all);
}
@@ -303,7 +304,7 @@ struct ScriptSettingsWindow : public Window {
* @param desc The description of the window.
* @param slot The company we're changing the settings for.
*/
ScriptSettingsWindow(WindowDesc *desc, CompanyID slot) : Window(desc),
ScriptSettingsWindow(WindowDesc &desc, CompanyID slot) : Window(desc),
slot(slot),
clicked_button(-1),
clicked_dropdown(false),
@@ -342,26 +343,21 @@ struct ScriptSettingsWindow : public Window {
SetDParam(0, (this->slot == OWNER_DEITY) ? STR_AI_SETTINGS_CAPTION_GAMESCRIPT : STR_AI_SETTINGS_CAPTION_AI);
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
if (widget != WID_SCRS_BACKGROUND) return;
this->line_height = std::max(SETTING_BUTTON_HEIGHT, GetCharacterHeight(FS_NORMAL)) + padding.height;
resize->width = 1;
resize->height = this->line_height;
size->height = 5 * this->line_height;
resize.width = 1;
resize.height = this->line_height;
size.height = 5 * this->line_height;
}
void DrawWidget(const Rect &r, WidgetID widget) const override
{
if (widget != WID_SCRS_BACKGROUND) return;
ScriptConfig *config = this->script_config;
VisibleSettingsList::const_iterator it = this->visible_settings.begin();
int i = 0;
for (; !this->vscroll->IsVisible(i); i++) it++;
Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
bool rtl = _current_text_dir == TD_RTL;
Rect br = ir.WithWidth(SETTING_BUTTON_WIDTH, rtl);
@@ -370,9 +366,11 @@ struct ScriptSettingsWindow : public Window {
int y = r.top;
int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
int text_y_offset = (this->line_height - GetCharacterHeight(FS_NORMAL)) / 2;
for (; this->vscroll->IsVisible(i) && it != visible_settings.end(); i++, it++) {
const auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->visible_settings);
for (auto it = first; it != last; ++it) {
const ScriptConfigItem &config_item = **it;
int current_value = config->GetSetting((config_item).name);
int current_value = this->script_config->GetSetting(config_item.name);
bool editable = this->IsEditableItem(config_item);
StringID str;
@@ -391,6 +389,7 @@ struct ScriptSettingsWindow : public Window {
DrawBoolButton(br.left, y + button_y_offset, current_value != 0, editable);
SetDParam(idx++, current_value == 0 ? STR_CONFIG_SETTING_OFF : STR_CONFIG_SETTING_ON);
} else {
int i = static_cast<int>(std::distance(std::begin(this->visible_settings), it));
if (config_item.complete_labels) {
DrawDropDownButton(br.left, y + button_y_offset, COLOUR_YELLOW, this->clicked_row == i && clicked_dropdown, editable);
} else {
@@ -469,7 +468,7 @@ struct ScriptSettingsWindow : public Window {
DropDownList list;
for (int i = config_item.min_value; i <= config_item.max_value; i++) {
list.push_back(std::make_unique<DropDownListStringItem>(config_item.labels.find(i)->second, i, false));
list.push_back(MakeDropDownListStringItem(config_item.labels.find(i)->second, i));
}
ShowDropDownListAt(this, std::move(list), old_val, WID_SCRS_SETTING_DROPDOWN, wi_rect, COLOUR_ORANGE);
@@ -516,10 +515,10 @@ struct ScriptSettingsWindow : public Window {
}
}
void OnQueryTextFinished(char *str) override
void OnQueryTextFinished(std::optional<std::string> str) override
{
if (StrEmpty(str)) return;
int32_t value = atoi(str);
if (!str.has_value() || str->empty()) return;
int32_t value = atoi(str->c_str());
SetValue(value);
}
@@ -608,11 +607,11 @@ static constexpr NWidgetPart _nested_script_settings_widgets[] = {
};
/** Window definition for the Script settings window. */
static WindowDesc _script_settings_desc(__FILE__, __LINE__,
static WindowDesc _script_settings_desc(
WDP_CENTER, "settings_script", 500, 208,
WC_SCRIPT_SETTINGS, WC_NONE,
0,
std::begin(_nested_script_settings_widgets), std::end(_nested_script_settings_widgets)
_nested_script_settings_widgets
);
/**
@@ -623,7 +622,7 @@ void ShowScriptSettingsWindow(CompanyID slot)
{
CloseWindowByClass(WC_SCRIPT_LIST);
CloseWindowByClass(WC_SCRIPT_SETTINGS);
new ScriptSettingsWindow(&_script_settings_desc, slot);
new ScriptSettingsWindow(_script_settings_desc, slot);
}
@@ -780,7 +779,7 @@ struct ScriptDebugWindow : public Window {
* @param desc The description of the window.
* @param number The window number (actually unused).
*/
ScriptDebugWindow(WindowDesc *desc, WindowNumber number, Owner show_company) : Window(desc), break_editbox(MAX_BREAK_STR_STRING_LENGTH)
ScriptDebugWindow(WindowDesc &desc, WindowNumber number, Owner show_company) : Window(desc), break_editbox(MAX_BREAK_STR_STRING_LENGTH)
{
this->filter = ScriptDebugWindow::initial_state;
this->break_string_filter = {&this->filter.case_sensitive_break_check, false};
@@ -824,11 +823,11 @@ struct ScriptDebugWindow : public Window {
ScriptDebugWindow::initial_state = this->filter;
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
if (widget == WID_SCRD_LOG_PANEL) {
resize->height = GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal;
size->height = 14 * resize->height + WidgetDimensions::scaled.framerect.Vertical();
resize.height = GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal;
size.height = 14 * resize.height + WidgetDimensions::scaled.framerect.Vertical();
}
}
@@ -899,7 +898,7 @@ struct ScriptDebugWindow : public Window {
{
if (this->filter.script_debug_company == INVALID_COMPANY) return;
ScriptLogTypes::LogData &log = this->GetLogData();
const ScriptLogTypes::LogData &log = this->GetLogData();
if (log.empty()) return;
Rect fr = r.Shrink(WidgetDimensions::scaled.framerect);
@@ -913,10 +912,11 @@ struct ScriptDebugWindow : public Window {
AutoRestoreBackup dpi_backup(_cur_dpi, &tmp_dpi);
fr.left -= this->hscroll->GetPosition();
fr = ScrollRect(fr, *this->hscroll, 1);
for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && (size_t)i < log.size(); i++) {
const ScriptLogTypes::LogLine &line = log[i];
auto [first, last] = this->vscroll->GetVisibleRangeIterators(log);
for (auto it = first; it != last; ++it) {
const ScriptLogTypes::LogLine &line = *it;
TextColour colour;
switch (line.type) {
@@ -929,7 +929,7 @@ struct ScriptDebugWindow : public Window {
}
/* Check if the current line should be highlighted */
if (i == this->highlight_row) {
if (std::distance(std::begin(log), it) == this->highlight_row) {
fr.bottom = fr.top + this->resize.step_height - 1;
GfxFillRect(fr, PC_BLACK);
if (colour == TC_BLACK) colour = TC_WHITE; // Make black text readable by inverting it to white.
@@ -1192,7 +1192,7 @@ struct ScriptDebugWindow : public Window {
void OnResize() override
{
this->vscroll->SetCapacityFromWidget(this, WID_SCRD_LOG_PANEL, WidgetDimensions::scaled.framerect.Vertical());
this->hscroll->SetCapacityFromWidget(this, WID_SCRD_LOG_PANEL);
this->hscroll->SetCapacityFromWidget(this, WID_SCRD_LOG_PANEL, WidgetDimensions::scaled.framerect.Horizontal());
}
/**
@@ -1268,7 +1268,7 @@ static constexpr NWidgetPart _nested_script_debug_widgets[] = {
/* Break string widgets */
NWidget(NWID_SELECTION, INVALID_COLOUR, WID_SCRD_BREAK_STRING_WIDGETS),
NWidget(NWID_HORIZONTAL),
NWidget(WWT_IMGBTN_2, COLOUR_GREY, WID_SCRD_BREAK_STR_ON_OFF_BTN), SetFill(0, 1), SetDataTip(SPR_FLAG_VEH_STOPPED, STR_AI_DEBUG_BREAK_STR_ON_OFF_TOOLTIP),
NWidget(WWT_IMGBTN_2, COLOUR_GREY, WID_SCRD_BREAK_STR_ON_OFF_BTN), SetAspect(WidgetDimensions::ASPECT_VEHICLE_FLAG), SetFill(0, 1), SetDataTip(SPR_FLAG_VEH_STOPPED, STR_AI_DEBUG_BREAK_STR_ON_OFF_TOOLTIP),
NWidget(WWT_PANEL, COLOUR_GREY),
NWidget(NWID_HORIZONTAL),
NWidget(WWT_LABEL, COLOUR_GREY), SetPadding(2, 2, 2, 4), SetDataTip(STR_AI_DEBUG_BREAK_ON_LABEL, 0x0),
@@ -1289,11 +1289,11 @@ EndContainer(),
};
/** Window definition for the Script debug window. */
static WindowDesc _script_debug_desc(__FILE__, __LINE__,
static WindowDesc _script_debug_desc(
WDP_AUTO, "script_debug", 600, 450,
WC_SCRIPT_DEBUG, WC_NONE,
0,
std::begin(_nested_script_debug_widgets), std::end(_nested_script_debug_widgets),
_nested_script_debug_widgets,
&ScriptDebugWindow::hotkeys
);
@@ -1325,7 +1325,7 @@ Window *ShowScriptDebugWindow(CompanyID show_company, bool new_window)
return w;
}
}
return new ScriptDebugWindow(&_script_debug_desc, i, show_company);
return new ScriptDebugWindow(_script_debug_desc, i, show_company);
} else {
ShowErrorMessage(STR_ERROR_AI_DEBUG_SERVER_ONLY, INVALID_STRING_ID, WL_INFO);
}

View File

@@ -47,8 +47,8 @@ bool ScriptInfo::CheckMethod(const char *name) const
"GetDate",
"CreateInstance",
};
for (size_t i = 0; i < lengthof(required_functions); i++) {
if (!info->CheckMethod(required_functions[i])) return SQ_ERROR;
for (const auto &required_function : required_functions) {
if (!info->CheckMethod(required_function)) return SQ_ERROR;
}
/* Get location information of the scanner */

View File

@@ -11,8 +11,8 @@
#define SCRIPT_INFO_HPP
#include <squirrel.h>
#include "../misc/countedptr.hpp"
#include "script_object.hpp"
#include "script_config.hpp"
/** The maximum number of operations for saving or loading the data of a script. */

View File

@@ -344,7 +344,7 @@ ScriptLogTypes::LogData &ScriptInstance::GetLogData()
* - null: No data.
*/
static byte _script_sl_byte; ///< Used as source/target by the script saveload code to store/load a single byte.
static uint8_t _script_sl_byte; ///< Used as source/target by the script saveload code to store/load a single byte.
/** SaveLoad array that saves/loads exactly one byte. */
static const SaveLoad _script_byte[] = {
@@ -386,7 +386,7 @@ static const SaveLoad _script_byte[] = {
return false;
}
if (!test) {
_script_sl_byte = (byte)len;
_script_sl_byte = (uint8_t)len;
SlObject(nullptr, _script_byte);
SlCopy(const_cast<char *>(buf), len, SLE_CHAR);
}
@@ -613,52 +613,46 @@ bool ScriptInstance::IsPaused()
ScriptDataVariant value = data->front();
data->pop_front();
if (std::holds_alternative<SQInteger>(value)) {
sq_pushinteger(vm, std::get<SQInteger>(value));
return true;
}
struct visitor {
HSQUIRRELVM vm;
ScriptData *data;
if (std::holds_alternative<std::string>(value)) {
sq_pushstring(vm, std::get<std::string>(value), -1);
return true;
}
bool operator()(const SQInteger &value) { sq_pushinteger(this->vm, value); return true; }
bool operator()(const std::string &value) { sq_pushstring(this->vm, value, -1); return true; }
bool operator()(const SQBool &value) { sq_pushbool(this->vm, value); return true; }
bool operator()(const SQSaveLoadType &type)
{
switch (type) {
case SQSL_ARRAY:
sq_newarray(this->vm, 0);
while (LoadObjects(this->vm, this->data)) {
sq_arrayappend(this->vm, -2);
/* The value is popped from the stack by squirrel. */
}
return true;
if (std::holds_alternative<SQBool>(value)) {
sq_pushbool(vm, std::get<SQBool>(value));
return true;
}
case SQSL_TABLE:
sq_newtable(this->vm);
while (LoadObjects(this->vm, this->data)) {
LoadObjects(this->vm, this->data);
sq_rawset(this->vm, -3);
/* The key (-2) and value (-1) are popped from the stack by squirrel. */
}
return true;
switch (std::get<SQSaveLoadType>(value)) {
case SQSL_ARRAY: {
sq_newarray(vm, 0);
while (LoadObjects(vm, data)) {
sq_arrayappend(vm, -2);
/* The value is popped from the stack by squirrel. */
case SQSL_NULL:
sq_pushnull(this->vm);
return true;
case SQSL_ARRAY_TABLE_END:
return false;
default: NOT_REACHED();
}
return true;
}
};
case SQSL_TABLE: {
sq_newtable(vm);
while (LoadObjects(vm, data)) {
LoadObjects(vm, data);
sq_rawset(vm, -3);
/* The key (-2) and value (-1) are popped from the stack by squirrel. */
}
return true;
}
case SQSL_NULL: {
sq_pushnull(vm);
return true;
}
case SQSL_ARRAY_TABLE_END: {
return false;
}
default: NOT_REACHED();
}
return std::visit(visitor{vm, data}, value);
}
/* static */ void ScriptInstance::LoadEmpty()

View File

@@ -168,11 +168,11 @@ struct ScriptFileChecksumCreator : FileScanner {
size_t len, size;
/* Open the file ... */
FILE *f = FioFOpenFile(filename, "rb", this->dir, &size);
if (f == nullptr) return false;
auto f = FioFOpenFile(filename, "rb", this->dir, &size);
if (!f.has_value()) return false;
/* ... calculate md5sum... */
while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, *f)) != 0 && size != 0) {
size -= len;
checksum.Append(buffer, len);
}
@@ -180,8 +180,6 @@ struct ScriptFileChecksumCreator : FileScanner {
MD5Hash tmp_md5sum;
checksum.Finish(tmp_md5sum);
FioFCloseFile(f);
/* ... and xor it to the overall md5sum. */
this->md5sum ^= tmp_md5sum;

View File

@@ -548,12 +548,12 @@ void Squirrel::Initialize()
class SQFile {
private:
FILE *file;
FileHandle file;
size_t size;
size_t pos;
public:
SQFile(FILE *file, size_t size) : file(file), size(size), pos(0) {}
SQFile(FileHandle file, size_t size) : file(std::move(file)), size(size), pos(0) {}
size_t Read(void *buf, size_t elemsize, size_t count)
{
@@ -622,40 +622,37 @@ SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool
{
ScriptAllocatorScope alloc_scope(this);
FILE *file;
std::optional<FileHandle> file = std::nullopt;
size_t size;
if (strncmp(this->GetAPIName(), "AI", 2) == 0) {
file = FioFOpenFile(filename, "rb", AI_DIR, &size);
if (file == nullptr) file = FioFOpenFile(filename, "rb", AI_LIBRARY_DIR, &size);
if (!file.has_value()) file = FioFOpenFile(filename, "rb", AI_LIBRARY_DIR, &size);
} else if (strncmp(this->GetAPIName(), "GS", 2) == 0) {
file = FioFOpenFile(filename, "rb", GAME_DIR, &size);
if (file == nullptr) file = FioFOpenFile(filename, "rb", GAME_LIBRARY_DIR, &size);
if (!file.has_value()) file = FioFOpenFile(filename, "rb", GAME_LIBRARY_DIR, &size);
} else {
NOT_REACHED();
}
if (file == nullptr) {
if (!file.has_value()) {
return sq_throwerror(vm, "cannot open the file");
}
unsigned short bom = 0;
if (size >= 2) {
[[maybe_unused]] size_t sr = fread(&bom, 1, sizeof(bom), file);
if (fread(&bom, 1, sizeof(bom), *file) != sizeof(bom)) return sq_throwerror(vm, "cannot read the file");;
}
SQLEXREADFUNC func;
switch (bom) {
case SQ_BYTECODE_STREAM_TAG: { // BYTECODE
if (fseek(file, -2, SEEK_CUR) < 0) {
FioFCloseFile(file);
if (fseek(*file, -2, SEEK_CUR) < 0) {
return sq_throwerror(vm, "cannot seek the file");
}
SQFile f(file, size);
SQFile f(std::move(*file), size);
if (SQ_SUCCEEDED(sq_readclosure(vm, _io_file_read, &f))) {
FioFCloseFile(file);
return SQ_OK;
}
FioFCloseFile(file);
return sq_throwerror(vm, "Couldn't read bytecode");
}
case 0xFFFE:
@@ -673,12 +670,10 @@ SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool
case 0xEFBB: { // UTF-8 on big-endian machine
/* Similarly, check the file is actually big enough to finish checking BOM */
if (size < 3) {
FioFCloseFile(file);
return sq_throwerror(vm, "I/O error");
}
unsigned char uc;
if (fread(&uc, 1, sizeof(uc), file) != sizeof(uc) || uc != 0xBF) {
FioFCloseFile(file);
if (fread(&uc, 1, sizeof(uc), *file) != sizeof(uc) || uc != 0xBF) {
return sq_throwerror(vm, "Unrecognized encoding");
}
func = _io_file_lexfeed_UTF8;
@@ -688,19 +683,16 @@ SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool
default: // ASCII
func = _io_file_lexfeed_ASCII;
/* Account for when we might not have fread'd earlier */
if (size >= 2 && fseek(file, -2, SEEK_CUR) < 0) {
FioFCloseFile(file);
if (size >= 2 && fseek(*file, -2, SEEK_CUR) < 0) {
return sq_throwerror(vm, "cannot seek the file");
}
break;
}
SQFile f(file, size);
SQFile f(std::move(*file), size);
if (SQ_SUCCEEDED(sq_compile(vm, func, &f, filename.c_str(), printerror))) {
FioFCloseFile(file);
return SQ_OK;
}
FioFCloseFile(file);
return SQ_ERROR;
}