2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * 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.
5 * 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/>.
10 * All actions handling saving and loading of the settings/configuration goes on in this file.
11 * The file consists of three parts:
13 * <li>Parsing the configuration file (openttd.cfg). This is achieved with the ini_ functions which
14 * handle various types, such as normal 'key = value' pairs, lists and value combinations of
15 * lists, strings, integers, 'bit'-masks and element selections.
16 * <li>Handle reading and writing to the setting-structures from inside the game either from
17 * the console for example or through the gui with CMD_ functions.
18 * <li>Handle saving/loading of the PATS chunk inside the savegame.
27 #include "screenshot.h"
28 #include "network/network.h"
29 #include "network/network_func.h"
30 #include "settings_internal.h"
31 #include "command_func.h"
32 #include "console_func.h"
33 #include "pathfinder/pathfinder_type.h"
36 #include "news_func.h"
37 #include "window_func.h"
38 #include "sound_func.h"
39 #include "company_func.h"
41 #if defined(WITH_FREETYPE) || defined(_WIN32) || defined(WITH_COCOA)
42 #include "fontcache.h"
44 #include "textbuf_gui.h"
46 #include "elrail_func.h"
49 #include "video/video_driver.hpp"
50 #include "sound/sound_driver.hpp"
51 #include "music/music_driver.hpp"
52 #include "blitter/factory.hpp"
53 #include "base_media_base.h"
55 #include "settings_func.h"
57 #include "ai/ai_config.hpp"
59 #include "game/game_config.hpp"
60 #include "game/game.hpp"
62 #include "smallmap_gui.h"
65 #include "strings_func.h"
68 #include "station_base.h"
70 #if defined(WITH_FREETYPE) || defined(_WIN32) || defined(WITH_COCOA)
71 #define HAS_TRUETYPE_FONT
74 #include "table/strings.h"
75 #include "table/settings.h"
77 #include "safeguards.h"
79 ClientSettings _settings_client
;
80 GameSettings _settings_game
; ///< Game settings of a running game or the scenario editor.
81 GameSettings _settings_newgame
; ///< Game settings for new games (updated from the intro screen).
82 VehicleDefaultSettings _old_vds
; ///< Used for loading default vehicles settings from old savegames
83 std::string _config_file
; ///< Configuration file of OpenTTD
85 typedef std::list
<ErrorMessageData
> ErrorList
;
86 static ErrorList _settings_error_list
; ///< Errors while loading minimal settings.
89 typedef void SettingDescProc(IniFile
*ini
, const SettingDesc
*desc
, const char *grpname
, void *object
);
90 typedef void SettingDescProcList(IniFile
*ini
, const char *grpname
, StringList
&list
);
92 static bool IsSignedVarMemType(VarType vt
);
95 * Groups in openttd.cfg that are actually lists.
97 static const char * const _list_group_names
[] = {
101 "server_bind_addresses",
106 * Find the index value of a ONEofMANY type in a string separated by |
107 * @param many full domain of values the ONEofMANY setting can have
108 * @param one the current value of the setting for which a value needs found
109 * @param onelen force calculation of the *one parameter
110 * @return the integer index of the full-list, or -1 if not found
112 static size_t LookupOneOfMany(const char *many
, const char *one
, size_t onelen
= 0)
117 if (onelen
== 0) onelen
= strlen(one
);
119 /* check if it's an integer */
120 if (*one
>= '0' && *one
<= '9') return strtoul(one
, nullptr, 0);
124 /* find end of item */
126 while (*s
!= '|' && *s
!= 0) s
++;
127 if ((size_t)(s
- many
) == onelen
&& !memcmp(one
, many
, onelen
)) return idx
;
128 if (*s
== 0) return (size_t)-1;
135 * Find the set-integer value MANYofMANY type in a string
136 * @param many full domain of values the MANYofMANY setting can have
137 * @param str the current string value of the setting, each individual
138 * of separated by a whitespace,tab or | character
139 * @return the 'fully' set integer, or -1 if a set is not found
141 static size_t LookupManyOfMany(const char *many
, const char *str
)
148 /* skip "whitespace" */
149 while (*str
== ' ' || *str
== '\t' || *str
== '|') str
++;
150 if (*str
== 0) break;
153 while (*s
!= 0 && *s
!= ' ' && *s
!= '\t' && *s
!= '|') s
++;
155 r
= LookupOneOfMany(many
, str
, s
- str
);
156 if (r
== (size_t)-1) return r
;
158 SetBit(res
, (uint8
)r
); // value found, set it
166 * Parse an integerlist string and set each found value
167 * @param p the string to be parsed. Each element in the list is separated by a
168 * comma or a space character
169 * @param items pointer to the integerlist-array that will be filled with values
170 * @param maxitems the maximum number of elements the integerlist-array has
171 * @return returns the number of items found, or -1 on an error
174 static int ParseIntList(const char *p
, T
*items
, int maxitems
)
176 int n
= 0; // number of items read so far
177 bool comma
= false; // do we accept comma?
182 /* Do not accept multiple commas between numbers */
183 if (!comma
) return -1;
192 if (n
== maxitems
) return -1; // we don't accept that many numbers
194 unsigned long v
= strtoul(p
, &end
, 0);
195 if (p
== end
) return -1; // invalid character (not a number)
196 if (sizeof(T
) < sizeof(v
)) v
= Clamp
<unsigned long>(v
, std::numeric_limits
<T
>::min(), std::numeric_limits
<T
>::max());
198 p
= end
; // first non-number
199 comma
= true; // we accept comma now
205 /* If we have read comma but no number after it, fail.
206 * We have read comma when (n != 0) and comma is not allowed */
207 if (n
!= 0 && !comma
) return -1;
213 * Load parsed string-values into an integer-array (intlist)
214 * @param str the string that contains the values (and will be parsed)
215 * @param array pointer to the integer-arrays that will be filled
216 * @param nelems the number of elements the array holds. Maximum is 64 elements
217 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
218 * @return return true on success and false on error
220 static bool LoadIntList(const char *str
, void *array
, int nelems
, VarType type
)
222 unsigned long items
[64];
225 if (str
== nullptr) {
226 memset(items
, 0, sizeof(items
));
229 nitems
= ParseIntList(str
, items
, lengthof(items
));
230 if (nitems
!= nelems
) return false;
237 for (i
= 0; i
!= nitems
; i
++) ((byte
*)array
)[i
] = items
[i
];
242 for (i
= 0; i
!= nitems
; i
++) ((uint16
*)array
)[i
] = items
[i
];
247 for (i
= 0; i
!= nitems
; i
++) ((uint32
*)array
)[i
] = items
[i
];
250 default: NOT_REACHED();
257 * Convert an integer-array (intlist) to a string representation. Each value
258 * is separated by a comma or a space character
259 * @param buf output buffer where the string-representation will be stored
260 * @param last last item to write to in the output buffer
261 * @param array pointer to the integer-arrays that is read from
262 * @param nelems the number of elements the array holds.
263 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
265 static void MakeIntList(char *buf
, const char *last
, const void *array
, int nelems
, VarType type
)
268 const byte
*p
= (const byte
*)array
;
270 for (i
= 0; i
!= nelems
; i
++) {
271 switch (GetVarMemType(type
)) {
273 case SLE_VAR_I8
: v
= *(const int8
*)p
; p
+= 1; break;
274 case SLE_VAR_U8
: v
= *(const uint8
*)p
; p
+= 1; break;
275 case SLE_VAR_I16
: v
= *(const int16
*)p
; p
+= 2; break;
276 case SLE_VAR_U16
: v
= *(const uint16
*)p
; p
+= 2; break;
277 case SLE_VAR_I32
: v
= *(const int32
*)p
; p
+= 4; break;
278 case SLE_VAR_U32
: v
= *(const uint32
*)p
; p
+= 4; break;
279 default: NOT_REACHED();
281 if (IsSignedVarMemType(type
)) {
282 buf
+= seprintf(buf
, last
, (i
== 0) ? "%d" : ",%d", v
);
283 } else if (type
& SLF_HEX
) {
284 buf
+= seprintf(buf
, last
, (i
== 0) ? "0x%X" : ",0x%X", v
);
286 buf
+= seprintf(buf
, last
, (i
== 0) ? "%u" : ",%u", v
);
292 * Convert a ONEofMANY structure to a string representation.
293 * @param buf output buffer where the string-representation will be stored
294 * @param last last item to write to in the output buffer
295 * @param many the full-domain string of possible values
296 * @param id the value of the variable and whose string-representation must be found
298 static void MakeOneOfMany(char *buf
, const char *last
, const char *many
, int id
)
302 /* Look for the id'th element */
304 for (; *many
!= '|'; many
++) {
305 if (*many
== '\0') { // not found
306 seprintf(buf
, last
, "%d", orig_id
);
310 many
++; // pass the |-character
313 /* copy string until next item (|) or the end of the list if this is the last one */
314 while (*many
!= '\0' && *many
!= '|' && buf
< last
) *buf
++ = *many
++;
319 * Convert a MANYofMANY structure to a string representation.
320 * @param buf output buffer where the string-representation will be stored
321 * @param last last item to write to in the output buffer
322 * @param many the full-domain string of possible values
323 * @param x the value of the variable and whose string-representation must
324 * be found in the bitmasked many string
326 static void MakeManyOfMany(char *buf
, const char *last
, const char *many
, uint32 x
)
332 for (; x
!= 0; x
>>= 1, i
++) {
334 while (*many
!= 0 && *many
!= '|') many
++; // advance to the next element
336 if (HasBit(x
, 0)) { // item found, copy it
337 if (!init
) buf
+= seprintf(buf
, last
, "|");
340 buf
+= seprintf(buf
, last
, "%d", i
);
342 memcpy(buf
, start
, many
- start
);
347 if (*many
== '|') many
++;
354 * Convert a string representation (external) of a setting to the internal rep.
355 * @param desc SettingDesc struct that holds all information about the variable
356 * @param orig_str input string that will be parsed based on the type of desc
357 * @return return the parsed value of the setting
359 static const void *StringToVal(const SettingDescBase
*desc
, const char *orig_str
)
361 const char *str
= orig_str
== nullptr ? "" : orig_str
;
366 size_t val
= strtoul(str
, &end
, 0);
368 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
369 msg
.SetDParamStr(0, str
);
370 msg
.SetDParamStr(1, desc
->name
);
371 _settings_error_list
.push_back(msg
);
375 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_TRAILING_CHARACTERS
);
376 msg
.SetDParamStr(0, desc
->name
);
377 _settings_error_list
.push_back(msg
);
382 case SDT_ONEOFMANY
: {
383 size_t r
= LookupOneOfMany(desc
->many
, str
);
384 /* if the first attempt of conversion from string to the appropriate value fails,
385 * look if we have defined a converter from old value to new value. */
386 if (r
== (size_t)-1 && desc
->proc_cnvt
!= nullptr) r
= desc
->proc_cnvt(str
);
387 if (r
!= (size_t)-1) return (void*)r
; // and here goes converted value
389 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
390 msg
.SetDParamStr(0, str
);
391 msg
.SetDParamStr(1, desc
->name
);
392 _settings_error_list
.push_back(msg
);
396 case SDT_MANYOFMANY
: {
397 size_t r
= LookupManyOfMany(desc
->many
, str
);
398 if (r
!= (size_t)-1) return (void*)r
;
399 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
400 msg
.SetDParamStr(0, str
);
401 msg
.SetDParamStr(1, desc
->name
);
402 _settings_error_list
.push_back(msg
);
407 if (strcmp(str
, "true") == 0 || strcmp(str
, "on") == 0 || strcmp(str
, "1") == 0) return (void*)true;
408 if (strcmp(str
, "false") == 0 || strcmp(str
, "off") == 0 || strcmp(str
, "0") == 0) return (void*)false;
410 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
411 msg
.SetDParamStr(0, str
);
412 msg
.SetDParamStr(1, desc
->name
);
413 _settings_error_list
.push_back(msg
);
418 case SDT_STRING
: return orig_str
;
419 case SDT_INTLIST
: return str
;
427 * Set the value of a setting and if needed clamp the value to
428 * the preset minimum and maximum.
429 * @param ptr the variable itself
430 * @param sd pointer to the 'information'-database of the variable
431 * @param val signed long version of the new value
432 * @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
433 * SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now
435 static void Write_ValidateSetting(void *ptr
, const SettingDesc
*sd
, int32 val
)
437 const SettingDescBase
*sdb
= &sd
->desc
;
439 if (sdb
->cmd
!= SDT_BOOLX
&&
440 sdb
->cmd
!= SDT_NUMX
&&
441 sdb
->cmd
!= SDT_ONEOFMANY
&&
442 sdb
->cmd
!= SDT_MANYOFMANY
) {
446 /* We cannot know the maximum value of a bitset variable, so just have faith */
447 if (sdb
->cmd
!= SDT_MANYOFMANY
) {
448 /* We need to take special care of the uint32 type as we receive from the function
449 * a signed integer. While here also bail out on 64-bit settings as those are not
450 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
452 * TODO: Support 64-bit settings/variables */
453 switch (GetVarMemType(sd
->save
.conv
)) {
454 case SLE_VAR_NULL
: return;
461 /* Override the minimum value. No value below sdb->min, except special value 0 */
462 if (!(sdb
->flags
& SGF_0ISDISABLED
) || val
!= 0) {
463 if (!(sdb
->flags
& SGF_MULTISTRING
)) {
464 /* Clamp value-type setting to its valid range */
465 val
= Clamp(val
, sdb
->min
, sdb
->max
);
466 } else if (val
< sdb
->min
|| val
> (int32
)sdb
->max
) {
467 /* Reset invalid discrete setting (where different values change gameplay) to its default value */
468 val
= (int32
)(size_t)sdb
->def
;
474 /* Override the minimum value. No value below sdb->min, except special value 0 */
475 uint32 uval
= (uint32
)val
;
476 if (!(sdb
->flags
& SGF_0ISDISABLED
) || uval
!= 0) {
477 if (!(sdb
->flags
& SGF_MULTISTRING
)) {
478 /* Clamp value-type setting to its valid range */
479 uval
= ClampU(uval
, sdb
->min
, sdb
->max
);
480 } else if (uval
< (uint
)sdb
->min
|| uval
> sdb
->max
) {
481 /* Reset invalid discrete setting to its default value */
482 uval
= (uint32
)(size_t)sdb
->def
;
485 WriteValue(ptr
, SLE_VAR_U32
, (int64
)uval
);
490 default: NOT_REACHED();
494 WriteValue(ptr
, sd
->save
.conv
, (int64
)val
);
498 * Load values from a group of an IniFile structure into the internal representation
499 * @param ini pointer to IniFile structure that holds administrative information
500 * @param sd pointer to SettingDesc structure whose internally pointed variables will
502 * @param grpname the group of the IniFile to search in for the new values
503 * @param object pointer to the object been loaded
505 static void IniLoadSettings(IniFile
*ini
, const SettingDesc
*sd
, const char *grpname
, void *object
)
508 IniGroup
*group_def
= ini
->GetGroup(grpname
);
510 for (; sd
->save
.cmd
!= SL_END
; sd
++) {
511 const SettingDescBase
*sdb
= &sd
->desc
;
512 const SaveLoad
*sld
= &sd
->save
;
514 if (!SlIsObjectCurrentlyValid(sld
->version_from
, sld
->version_to
)) continue;
516 /* For settings.xx.yy load the settings from [xx] yy = ? */
517 std::string s
{ sdb
->name
};
518 auto sc
= s
.find('.');
519 if (sc
!= std::string::npos
) {
520 group
= ini
->GetGroup(s
.substr(0, sc
));
521 s
= s
.substr(sc
+ 1);
526 IniItem
*item
= group
->GetItem(s
, false);
527 if (item
== nullptr && group
!= group_def
) {
528 /* For settings.xx.yy load the settings from [settings] yy = ? in case the previous
529 * did not exist (e.g. loading old config files with a [settings] section */
530 item
= group_def
->GetItem(s
, false);
532 if (item
== nullptr) {
533 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
534 * did not exist (e.g. loading old config files with a [yapf] section */
536 if (sc
!= std::string::npos
) item
= ini
->GetGroup(s
.substr(0, sc
))->GetItem(s
.substr(sc
+ 1), false);
539 const void *p
= (item
== nullptr) ? sdb
->def
: StringToVal(sdb
, item
->value
.has_value() ? item
->value
->c_str() : nullptr);
540 void *ptr
= GetVariableAddress(object
, sld
);
543 case SDT_BOOLX
: // All four are various types of (integer) numbers
547 Write_ValidateSetting(ptr
, sd
, (int32
)(size_t)p
);
551 switch (GetVarMemType(sld
->conv
)) {
554 if (p
!= nullptr) strecpy((char*)ptr
, (const char*)p
, (char*)ptr
+ sld
->length
- 1);
560 *(char**)ptr
= p
== nullptr ? nullptr : stredup((const char*)p
);
563 case SLE_VAR_CHAR
: if (p
!= nullptr) *(char *)ptr
= *(const char *)p
; break;
565 default: NOT_REACHED();
570 switch (GetVarMemType(sld
->conv
)) {
574 reinterpret_cast<std::string
*>(ptr
)->assign((const char *)p
);
576 reinterpret_cast<std::string
*>(ptr
)->clear();
580 default: NOT_REACHED();
586 if (!LoadIntList((const char*)p
, ptr
, sld
->length
, GetVarMemType(sld
->conv
))) {
587 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_ARRAY
);
588 msg
.SetDParamStr(0, sdb
->name
);
589 _settings_error_list
.push_back(msg
);
592 LoadIntList((const char*)sdb
->def
, ptr
, sld
->length
, GetVarMemType(sld
->conv
));
593 } else if (sd
->desc
.proc_cnvt
!= nullptr) {
594 sd
->desc
.proc_cnvt((const char*)p
);
598 default: NOT_REACHED();
604 * Save the values of settings to the inifile.
605 * @param ini pointer to IniFile structure
606 * @param sd read-only SettingDesc structure which contains the unmodified,
607 * loaded values of the configuration file and various information about it
608 * @param grpname holds the name of the group (eg. [network]) where these will be saved
609 * @param object pointer to the object been saved
610 * The function works as follows: for each item in the SettingDesc structure we
611 * have a look if the value has changed since we started the game (the original
612 * values are reloaded when saving). If settings indeed have changed, we get
613 * these and save them.
615 static void IniSaveSettings(IniFile
*ini
, const SettingDesc
*sd
, const char *grpname
, void *object
)
617 IniGroup
*group_def
= nullptr, *group
;
622 for (; sd
->save
.cmd
!= SL_END
; sd
++) {
623 const SettingDescBase
*sdb
= &sd
->desc
;
624 const SaveLoad
*sld
= &sd
->save
;
626 /* If the setting is not saved to the configuration
627 * file, just continue with the next setting */
628 if (!SlIsObjectCurrentlyValid(sld
->version_from
, sld
->version_to
)) continue;
629 if (sld
->conv
& SLF_NOT_IN_CONFIG
) continue;
631 /* XXX - wtf is this?? (group override?) */
632 std::string s
{ sdb
->name
};
633 auto sc
= s
.find('.');
634 if (sc
!= std::string::npos
) {
635 group
= ini
->GetGroup(s
.substr(0, sc
));
636 s
= s
.substr(sc
+ 1);
638 if (group_def
== nullptr) group_def
= ini
->GetGroup(grpname
);
642 item
= group
->GetItem(s
, true);
643 ptr
= GetVariableAddress(object
, sld
);
645 if (item
->value
.has_value()) {
646 /* check if the value is the same as the old value */
647 const void *p
= StringToVal(sdb
, item
->value
->c_str());
649 /* The main type of a variable/setting is in bytes 8-15
650 * The subtype (what kind of numbers do we have there) is in 0-7 */
656 switch (GetVarMemType(sld
->conv
)) {
658 if (*(bool*)ptr
== (p
!= nullptr)) continue;
663 if (*(byte
*)ptr
== (byte
)(size_t)p
) continue;
668 if (*(uint16
*)ptr
== (uint16
)(size_t)p
) continue;
673 if (*(uint32
*)ptr
== (uint32
)(size_t)p
) continue;
676 default: NOT_REACHED();
680 default: break; // Assume the other types are always changed
684 /* Value has changed, get the new value and put it into a buffer */
689 case SDT_MANYOFMANY
: {
690 uint32 i
= (uint32
)ReadValue(ptr
, sld
->conv
);
693 case SDT_BOOLX
: strecpy(buf
, (i
!= 0) ? "true" : "false", lastof(buf
)); break;
694 case SDT_NUMX
: seprintf(buf
, lastof(buf
), IsSignedVarMemType(sld
->conv
) ? "%d" : (sld
->conv
& SLF_HEX
) ? "%X" : "%u", i
); break;
695 case SDT_ONEOFMANY
: MakeOneOfMany(buf
, lastof(buf
), sdb
->many
, i
); break;
696 case SDT_MANYOFMANY
: MakeManyOfMany(buf
, lastof(buf
), sdb
->many
, i
); break;
697 default: NOT_REACHED();
703 switch (GetVarMemType(sld
->conv
)) {
704 case SLE_VAR_STRB
: strecpy(buf
, (char*)ptr
, lastof(buf
)); break;
705 case SLE_VAR_STRBQ
:seprintf(buf
, lastof(buf
), "\"%s\"", (char*)ptr
); break;
706 case SLE_VAR_STR
: strecpy(buf
, *(char**)ptr
, lastof(buf
)); break;
709 if (*(char**)ptr
== nullptr) {
712 seprintf(buf
, lastof(buf
), "\"%s\"", *(char**)ptr
);
716 case SLE_VAR_CHAR
: buf
[0] = *(char*)ptr
; buf
[1] = '\0'; break;
717 default: NOT_REACHED();
722 switch (GetVarMemType(sld
->conv
)) {
723 case SLE_VAR_STR
: strecpy(buf
, reinterpret_cast<std::string
*>(ptr
)->c_str(), lastof(buf
)); break;
726 if (reinterpret_cast<std::string
*>(ptr
)->empty()) {
729 seprintf(buf
, lastof(buf
), "\"%s\"", reinterpret_cast<std::string
*>(ptr
)->c_str());
733 default: NOT_REACHED();
738 MakeIntList(buf
, lastof(buf
), ptr
, sld
->length
, sld
->conv
);
741 default: NOT_REACHED();
744 /* The value is different, that means we have to write it to the ini */
745 item
->value
.emplace(buf
);
750 * Loads all items from a 'grpname' section into a list
751 * The list parameter can be a nullptr pointer, in this case nothing will be
752 * saved and a callback function should be defined that will take over the
753 * list-handling and store the data itself somewhere.
754 * @param ini IniFile handle to the ini file with the source data
755 * @param grpname character string identifying the section-header of the ini file that will be parsed
756 * @param list new list with entries of the given section
758 static void IniLoadSettingList(IniFile
*ini
, const char *grpname
, StringList
&list
)
760 IniGroup
*group
= ini
->GetGroup(grpname
);
762 if (group
== nullptr) return;
766 for (const IniItem
*item
= group
->item
; item
!= nullptr; item
= item
->next
) {
767 if (!item
->name
.empty()) list
.push_back(item
->name
);
772 * Saves all items from a list into the 'grpname' section
773 * The list parameter can be a nullptr pointer, in this case a callback function
774 * should be defined that will provide the source data to be saved.
775 * @param ini IniFile handle to the ini file where the destination data is saved
776 * @param grpname character string identifying the section-header of the ini file
777 * @param list pointer to an string(pointer) array that will be used as the
778 * source to be saved into the relevant ini section
780 static void IniSaveSettingList(IniFile
*ini
, const char *grpname
, StringList
&list
)
782 IniGroup
*group
= ini
->GetGroup(grpname
);
784 if (group
== nullptr) return;
787 for (const auto &iter
: list
) {
788 group
->GetItem(iter
.c_str(), true)->SetValue("");
793 * Load a WindowDesc from config.
794 * @param ini IniFile handle to the ini file with the source data
795 * @param grpname character string identifying the section-header of the ini file that will be parsed
796 * @param desc Destination WindowDesc
798 void IniLoadWindowSettings(IniFile
*ini
, const char *grpname
, void *desc
)
800 IniLoadSettings(ini
, _window_settings
, grpname
, desc
);
804 * Save a WindowDesc to config.
805 * @param ini IniFile handle to the ini file where the destination data is saved
806 * @param grpname character string identifying the section-header of the ini file
807 * @param desc Source WindowDesc
809 void IniSaveWindowSettings(IniFile
*ini
, const char *grpname
, void *desc
)
811 IniSaveSettings(ini
, _window_settings
, grpname
, desc
);
815 * Check whether the setting is editable in the current gamemode.
816 * @param do_command true if this is about checking a command from the server.
817 * @return true if editable.
819 bool SettingDesc::IsEditable(bool do_command
) const
821 if (!do_command
&& !(this->save
.conv
& SLF_NO_NETWORK_SYNC
) && _networking
&& !_network_server
&& !(this->desc
.flags
& SGF_PER_COMPANY
)) return false;
822 if ((this->desc
.flags
& SGF_NETWORK_ONLY
) && !_networking
&& _game_mode
!= GM_MENU
) return false;
823 if ((this->desc
.flags
& SGF_NO_NETWORK
) && _networking
) return false;
824 if ((this->desc
.flags
& SGF_NEWGAME_ONLY
) &&
825 (_game_mode
== GM_NORMAL
||
826 (_game_mode
== GM_EDITOR
&& !(this->desc
.flags
& SGF_SCENEDIT_TOO
)))) return false;
831 * Return the type of the setting.
832 * @return type of setting
834 SettingType
SettingDesc::GetType() const
836 if (this->desc
.flags
& SGF_PER_COMPANY
) return ST_COMPANY
;
837 return (this->save
.conv
& SLF_NOT_IN_SAVE
) ? ST_CLIENT
: ST_GAME
;
840 /* Begin - Callback Functions for the various settings. */
842 /** Reposition the main toolbar as the setting changed. */
843 static bool v_PositionMainToolbar(int32 p1
)
845 if (_game_mode
!= GM_MENU
) PositionMainToolbar(nullptr);
849 /** Reposition the statusbar as the setting changed. */
850 static bool v_PositionStatusbar(int32 p1
)
852 if (_game_mode
!= GM_MENU
) {
853 PositionStatusbar(nullptr);
854 PositionNewsMessage(nullptr);
855 PositionNetworkChatWindow(nullptr);
860 static bool PopulationInLabelActive(int32 p1
)
862 UpdateAllTownVirtCoords();
866 static bool RedrawScreen(int32 p1
)
868 MarkWholeScreenDirty();
873 * Redraw the smallmap after a colour scheme change.
874 * @param p1 Callback parameter.
875 * @return Always true.
877 static bool RedrawSmallmap(int32 p1
)
881 SetWindowClassesDirty(WC_SMALLMAP
);
885 static bool InvalidateDetailsWindow(int32 p1
)
887 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
891 static bool StationSpreadChanged(int32 p1
)
893 InvalidateWindowData(WC_SELECT_STATION
, 0);
894 InvalidateWindowData(WC_BUILD_STATION
, 0);
898 static bool InvalidateBuildIndustryWindow(int32 p1
)
900 InvalidateWindowData(WC_BUILD_INDUSTRY
, 0);
904 static bool CloseSignalGUI(int32 p1
)
907 DeleteWindowByClass(WC_BUILD_SIGNAL
);
912 static bool InvalidateTownViewWindow(int32 p1
)
914 InvalidateWindowClassesData(WC_TOWN_VIEW
, p1
);
918 static bool DeleteSelectStationWindow(int32 p1
)
920 DeleteWindowById(WC_SELECT_STATION
, 0);
924 static bool UpdateConsists(int32 p1
)
926 for (Train
*t
: Train::Iterate()) {
927 /* Update the consist of all trains so the maximum speed is set correctly. */
928 if (t
->IsFrontEngine() || t
->IsFreeWagon()) t
->ConsistChanged(CCF_TRACK
);
930 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
934 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
935 static bool CheckInterval(int32 p1
)
937 bool update_vehicles
;
938 VehicleDefaultSettings
*vds
;
939 if (_game_mode
== GM_MENU
|| !Company::IsValidID(_current_company
)) {
940 vds
= &_settings_client
.company
.vehicle
;
941 update_vehicles
= false;
943 vds
= &Company::Get(_current_company
)->settings
.vehicle
;
944 update_vehicles
= true;
948 vds
->servint_trains
= 50;
949 vds
->servint_roadveh
= 50;
950 vds
->servint_aircraft
= 50;
951 vds
->servint_ships
= 50;
953 vds
->servint_trains
= 150;
954 vds
->servint_roadveh
= 150;
955 vds
->servint_aircraft
= 100;
956 vds
->servint_ships
= 360;
959 if (update_vehicles
) {
960 const Company
*c
= Company::Get(_current_company
);
961 for (Vehicle
*v
: Vehicle::Iterate()) {
962 if (v
->owner
== _current_company
&& v
->IsPrimaryVehicle() && !v
->ServiceIntervalIsCustom()) {
963 v
->SetServiceInterval(CompanyServiceInterval(c
, v
->type
));
964 v
->SetServiceIntervalIsPercent(p1
!= 0);
969 InvalidateDetailsWindow(0);
974 static bool UpdateInterval(VehicleType type
, int32 p1
)
976 bool update_vehicles
;
977 VehicleDefaultSettings
*vds
;
978 if (_game_mode
== GM_MENU
|| !Company::IsValidID(_current_company
)) {
979 vds
= &_settings_client
.company
.vehicle
;
980 update_vehicles
= false;
982 vds
= &Company::Get(_current_company
)->settings
.vehicle
;
983 update_vehicles
= true;
986 /* Test if the interval is valid */
987 uint16 interval
= GetServiceIntervalClamped(p1
, vds
->servint_ispercent
);
988 if (interval
!= p1
) return false;
990 if (update_vehicles
) {
991 for (Vehicle
*v
: Vehicle::Iterate()) {
992 if (v
->owner
== _current_company
&& v
->type
== type
&& v
->IsPrimaryVehicle() && !v
->ServiceIntervalIsCustom()) {
993 v
->SetServiceInterval(p1
);
998 InvalidateDetailsWindow(0);
1003 static bool UpdateIntervalTrains(int32 p1
)
1005 return UpdateInterval(VEH_TRAIN
, p1
);
1008 static bool UpdateIntervalRoadVeh(int32 p1
)
1010 return UpdateInterval(VEH_ROAD
, p1
);
1013 static bool UpdateIntervalShips(int32 p1
)
1015 return UpdateInterval(VEH_SHIP
, p1
);
1018 static bool UpdateIntervalAircraft(int32 p1
)
1020 return UpdateInterval(VEH_AIRCRAFT
, p1
);
1023 static bool TrainAccelerationModelChanged(int32 p1
)
1025 for (Train
*t
: Train::Iterate()) {
1026 if (t
->IsFrontEngine()) {
1027 t
->tcache
.cached_max_curve_speed
= t
->GetCurveSpeedLimit();
1028 t
->UpdateAcceleration();
1032 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1033 SetWindowClassesDirty(WC_ENGINE_PREVIEW
);
1034 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
1035 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
1041 * This function updates the train acceleration cache after a steepness change.
1042 * @param p1 Callback parameter.
1043 * @return Always true.
1045 static bool TrainSlopeSteepnessChanged(int32 p1
)
1047 for (Train
*t
: Train::Iterate()) {
1048 if (t
->IsFrontEngine()) t
->CargoChanged();
1055 * This function updates realistic acceleration caches when the setting "Road vehicle acceleration model" is set.
1056 * @param p1 Callback parameter
1057 * @return Always true
1059 static bool RoadVehAccelerationModelChanged(int32 p1
)
1061 if (_settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) {
1062 for (RoadVehicle
*rv
: RoadVehicle::Iterate()) {
1063 if (rv
->IsFrontEngine()) {
1069 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1070 SetWindowClassesDirty(WC_ENGINE_PREVIEW
);
1071 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
1072 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
1078 * This function updates the road vehicle acceleration cache after a steepness change.
1079 * @param p1 Callback parameter.
1080 * @return Always true.
1082 static bool RoadVehSlopeSteepnessChanged(int32 p1
)
1084 for (RoadVehicle
*rv
: RoadVehicle::Iterate()) {
1085 if (rv
->IsFrontEngine()) rv
->CargoChanged();
1091 static bool DragSignalsDensityChanged(int32
)
1093 InvalidateWindowData(WC_BUILD_SIGNAL
, 0);
1098 static bool TownFoundingChanged(int32 p1
)
1100 if (_game_mode
!= GM_EDITOR
&& _settings_game
.economy
.found_town
== TF_FORBIDDEN
) {
1101 DeleteWindowById(WC_FOUND_TOWN
, 0);
1104 InvalidateWindowData(WC_FOUND_TOWN
, 0);
1108 static bool InvalidateVehTimetableWindow(int32 p1
)
1110 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE
, VIWD_MODIFY_ORDERS
);
1114 static bool ZoomMinMaxChanged(int32 p1
)
1116 extern void ConstrainAllViewportsZoom();
1117 ConstrainAllViewportsZoom();
1118 GfxClearSpriteCache();
1119 if (_settings_client
.gui
.zoom_min
> _gui_zoom
) {
1120 /* Restrict GUI zoom if it is no longer available. */
1121 _gui_zoom
= _settings_client
.gui
.zoom_min
;
1123 LoadStringWidthTable();
1129 * Update any possible saveload window and delete any newgrf dialogue as
1130 * its widget parts might change. Reinit all windows as it allows access to the
1131 * newgrf debug button.
1133 * @return Always true.
1135 static bool InvalidateNewGRFChangeWindows(int32 p1
)
1137 InvalidateWindowClassesData(WC_SAVELOAD
);
1138 DeleteWindowByClass(WC_GAME_OPTIONS
);
1143 static bool InvalidateCompanyLiveryWindow(int32 p1
)
1145 InvalidateWindowClassesData(WC_COMPANY_COLOUR
, -1);
1146 return RedrawScreen(p1
);
1149 static bool InvalidateIndustryViewWindow(int32 p1
)
1151 InvalidateWindowClassesData(WC_INDUSTRY_VIEW
);
1155 static bool InvalidateAISettingsWindow(int32 p1
)
1157 InvalidateWindowClassesData(WC_AI_SETTINGS
);
1162 * Update the town authority window after a town authority setting change.
1164 * @return Always true.
1166 static bool RedrawTownAuthority(int32 p1
)
1168 SetWindowClassesDirty(WC_TOWN_AUTHORITY
);
1173 * Invalidate the company infrastructure details window after a infrastructure maintenance setting change.
1175 * @return Always true.
1177 static bool InvalidateCompanyInfrastructureWindow(int32 p1
)
1179 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE
);
1184 * Invalidate the company details window after the shares setting changed.
1186 * @return Always true.
1188 static bool InvalidateCompanyWindow(int32 p1
)
1190 InvalidateWindowClassesData(WC_COMPANY
);
1194 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
1195 static void ValidateSettings()
1197 /* Do not allow a custom sea level with the original land generator. */
1198 if (_settings_newgame
.game_creation
.land_generator
== LG_ORIGINAL
&&
1199 _settings_newgame
.difficulty
.quantity_sea_lakes
== CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
) {
1200 _settings_newgame
.difficulty
.quantity_sea_lakes
= CUSTOM_SEA_LEVEL_MIN_PERCENTAGE
;
1204 static bool DifficultyNoiseChange(int32 i
)
1206 if (_game_mode
== GM_NORMAL
) {
1207 UpdateAirportsNoise();
1208 if (_settings_game
.economy
.station_noise_level
) {
1209 InvalidateWindowClassesData(WC_TOWN_VIEW
, 0);
1216 static bool MaxNoAIsChange(int32 i
)
1218 if (GetGameSettings().difficulty
.max_no_competitors
!= 0 &&
1219 AI::GetInfoList()->size() == 0 &&
1220 (!_networking
|| _network_server
)) {
1221 ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI
, INVALID_STRING_ID
, WL_CRITICAL
);
1224 InvalidateWindowClassesData(WC_GAME_OPTIONS
, 0);
1229 * Check whether the road side may be changed.
1231 * @return true if the road side may be changed.
1233 static bool CheckRoadSide(int p1
)
1235 extern bool RoadVehiclesAreBuilt();
1236 return _game_mode
== GM_MENU
|| !RoadVehiclesAreBuilt();
1240 * Conversion callback for _gameopt_settings_game.landscape
1241 * It converts (or try) between old values and the new ones,
1242 * without losing initial setting of the user
1243 * @param value that was read from config file
1244 * @return the "hopefully" converted value
1246 static size_t ConvertLandscape(const char *value
)
1248 /* try with the old values */
1249 return LookupOneOfMany("normal|hilly|desert|candy", value
);
1252 static bool CheckFreeformEdges(int32 p1
)
1254 if (_game_mode
== GM_MENU
) return true;
1256 for (Ship
*s
: Ship::Iterate()) {
1257 /* Check if there is a ship on the northern border. */
1258 if (TileX(s
->tile
) == 0 || TileY(s
->tile
) == 0) {
1259 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY
, INVALID_STRING_ID
, WL_ERROR
);
1263 for (const BaseStation
*st
: BaseStation::Iterate()) {
1264 /* Check if there is a non-deleted buoy on the northern border. */
1265 if (st
->IsInUse() && (TileX(st
->xy
) == 0 || TileY(st
->xy
) == 0)) {
1266 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY
, INVALID_STRING_ID
, WL_ERROR
);
1270 for (uint x
= 0; x
< MapSizeX(); x
++) MakeVoid(TileXY(x
, 0));
1271 for (uint y
= 0; y
< MapSizeY(); y
++) MakeVoid(TileXY(0, y
));
1273 for (uint i
= 0; i
< MapMaxX(); i
++) {
1274 if (TileHeight(TileXY(i
, 1)) != 0) {
1275 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1279 for (uint i
= 1; i
< MapMaxX(); i
++) {
1280 if (!IsTileType(TileXY(i
, MapMaxY() - 1), MP_WATER
) || TileHeight(TileXY(1, MapMaxY())) != 0) {
1281 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1285 for (uint i
= 0; i
< MapMaxY(); i
++) {
1286 if (TileHeight(TileXY(1, i
)) != 0) {
1287 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1291 for (uint i
= 1; i
< MapMaxY(); i
++) {
1292 if (!IsTileType(TileXY(MapMaxX() - 1, i
), MP_WATER
) || TileHeight(TileXY(MapMaxX(), i
)) != 0) {
1293 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1297 /* Make tiles at the border water again. */
1298 for (uint i
= 0; i
< MapMaxX(); i
++) {
1299 SetTileHeight(TileXY(i
, 0), 0);
1300 SetTileType(TileXY(i
, 0), MP_WATER
);
1302 for (uint i
= 0; i
< MapMaxY(); i
++) {
1303 SetTileHeight(TileXY(0, i
), 0);
1304 SetTileType(TileXY(0, i
), MP_WATER
);
1307 MarkWholeScreenDirty();
1312 * Changing the setting "allow multiple NewGRF sets" is not allowed
1313 * if there are vehicles.
1315 static bool ChangeDynamicEngines(int32 p1
)
1317 if (_game_mode
== GM_MENU
) return true;
1319 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
1320 ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES
, INVALID_STRING_ID
, WL_ERROR
);
1327 static bool ChangeMaxHeightLevel(int32 p1
)
1329 if (_game_mode
== GM_NORMAL
) return false;
1330 if (_game_mode
!= GM_EDITOR
) return true;
1332 /* Check if at least one mountain on the map is higher than the new value.
1333 * If yes, disallow the change. */
1334 for (TileIndex t
= 0; t
< MapSize(); t
++) {
1335 if ((int32
)TileHeight(t
) > p1
) {
1336 ShowErrorMessage(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN
, INVALID_STRING_ID
, WL_ERROR
);
1337 /* Return old, unchanged value */
1342 /* The smallmap uses an index from heightlevels to colours. Trigger rebuilding it. */
1343 InvalidateWindowClassesData(WC_SMALLMAP
, 2);
1348 static bool StationCatchmentChanged(int32 p1
)
1350 Station::RecomputeCatchmentForAll();
1351 MarkWholeScreenDirty();
1355 static bool MaxVehiclesChanged(int32 p1
)
1357 InvalidateWindowClassesData(WC_BUILD_TOOLBAR
);
1358 MarkWholeScreenDirty();
1362 static bool InvalidateShipPathCache(int32 p1
)
1364 for (Ship
*s
: Ship::Iterate()) {
1370 static bool UpdateClientName(int32 p1
)
1372 NetworkUpdateClientName();
1376 static bool UpdateServerPassword(int32 p1
)
1378 if (strcmp(_settings_client
.network
.server_password
, "*") == 0) {
1379 _settings_client
.network
.server_password
[0] = '\0';
1385 static bool UpdateRconPassword(int32 p1
)
1387 if (strcmp(_settings_client
.network
.rcon_password
, "*") == 0) {
1388 _settings_client
.network
.rcon_password
[0] = '\0';
1394 static bool UpdateClientConfigValues(int32 p1
)
1396 if (_network_server
) NetworkServerSendConfigUpdate();
1401 /* End - Callback Functions */
1404 * Prepare for reading and old diff_custom by zero-ing the memory.
1406 static void PrepareOldDiffCustom()
1408 memset(_old_diff_custom
, 0, sizeof(_old_diff_custom
));
1412 * Reading of the old diff_custom array and transforming it to the new format.
1413 * @param savegame is it read from the config or savegame. In the latter case
1414 * we are sure there is an array; in the former case we have
1417 static void HandleOldDiffCustom(bool savegame
)
1419 uint options_to_load
= GAME_DIFFICULTY_NUM
- ((savegame
&& IsSavegameVersionBefore(SLV_4
)) ? 1 : 0);
1422 /* If we did read to old_diff_custom, then at least one value must be non 0. */
1423 bool old_diff_custom_used
= false;
1424 for (uint i
= 0; i
< options_to_load
&& !old_diff_custom_used
; i
++) {
1425 old_diff_custom_used
= (_old_diff_custom
[i
] != 0);
1428 if (!old_diff_custom_used
) return;
1431 for (uint i
= 0; i
< options_to_load
; i
++) {
1432 const SettingDesc
*sd
= &_settings
[i
];
1433 /* Skip deprecated options */
1434 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
1435 void *var
= GetVariableAddress(savegame
? &_settings_game
: &_settings_newgame
, &sd
->save
);
1436 Write_ValidateSetting(var
, sd
, (int32
)((i
== 4 ? 1000 : 1) * _old_diff_custom
[i
]));
1440 static void AILoadConfig(IniFile
*ini
, const char *grpname
)
1442 IniGroup
*group
= ini
->GetGroup(grpname
);
1445 /* Clean any configured AI */
1446 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1447 AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
)->Change(nullptr);
1450 /* If no group exists, return */
1451 if (group
== nullptr) return;
1453 CompanyID c
= COMPANY_FIRST
;
1454 for (item
= group
->item
; c
< MAX_COMPANIES
&& item
!= nullptr; c
++, item
= item
->next
) {
1455 AIConfig
*config
= AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
);
1457 config
->Change(item
->name
.c_str());
1458 if (!config
->HasScript()) {
1459 if (item
->name
!= "none") {
1460 DEBUG(script
, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item
->name
.c_str());
1464 if (item
->value
.has_value()) config
->StringToSettings(item
->value
->c_str());
1468 static void GameLoadConfig(IniFile
*ini
, const char *grpname
)
1470 IniGroup
*group
= ini
->GetGroup(grpname
);
1473 /* Clean any configured GameScript */
1474 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME
)->Change(nullptr);
1476 /* If no group exists, return */
1477 if (group
== nullptr) return;
1480 if (item
== nullptr) return;
1482 GameConfig
*config
= GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME
);
1484 config
->Change(item
->name
.c_str());
1485 if (!config
->HasScript()) {
1486 if (item
->name
!= "none") {
1487 DEBUG(script
, 0, "The GameScript by the name '%s' was no longer found, and removed from the list.", item
->name
.c_str());
1491 if (item
->value
.has_value()) config
->StringToSettings(item
->value
->c_str());
1495 * Convert a character to a hex nibble value, or \c -1 otherwise.
1496 * @param c Character to convert.
1497 * @return Hex value of the character, or \c -1 if not a hex digit.
1499 static int DecodeHexNibble(char c
)
1501 if (c
>= '0' && c
<= '9') return c
- '0';
1502 if (c
>= 'A' && c
<= 'F') return c
+ 10 - 'A';
1503 if (c
>= 'a' && c
<= 'f') return c
+ 10 - 'a';
1508 * Parse a sequence of characters (supposedly hex digits) into a sequence of bytes.
1509 * After the hex number should be a \c '|' character.
1510 * @param pos First character to convert.
1511 * @param[out] dest Output byte array to write the bytes.
1512 * @param dest_size Number of bytes in \a dest.
1513 * @return Whether reading was successful.
1515 static bool DecodeHexText(const char *pos
, uint8
*dest
, size_t dest_size
)
1517 while (dest_size
> 0) {
1518 int hi
= DecodeHexNibble(pos
[0]);
1519 int lo
= (hi
>= 0) ? DecodeHexNibble(pos
[1]) : -1;
1520 if (lo
< 0) return false;
1521 *dest
++ = (hi
<< 4) | lo
;
1529 * Load a GRF configuration
1530 * @param ini The configuration to read from.
1531 * @param grpname Group name containing the configuration of the GRF.
1532 * @param is_static GRF is static.
1534 static GRFConfig
*GRFLoadConfig(IniFile
*ini
, const char *grpname
, bool is_static
)
1536 IniGroup
*group
= ini
->GetGroup(grpname
);
1538 GRFConfig
*first
= nullptr;
1539 GRFConfig
**curr
= &first
;
1541 if (group
== nullptr) return nullptr;
1543 for (item
= group
->item
; item
!= nullptr; item
= item
->next
) {
1544 GRFConfig
*c
= nullptr;
1546 uint8 grfid_buf
[4], md5sum
[16];
1547 const char *filename
= item
->name
.c_str();
1548 bool has_grfid
= false;
1549 bool has_md5sum
= false;
1551 /* Try reading "<grfid>|" and on success, "<md5sum>|". */
1552 has_grfid
= DecodeHexText(filename
, grfid_buf
, lengthof(grfid_buf
));
1554 filename
+= 1 + 2 * lengthof(grfid_buf
);
1555 has_md5sum
= DecodeHexText(filename
, md5sum
, lengthof(md5sum
));
1556 if (has_md5sum
) filename
+= 1 + 2 * lengthof(md5sum
);
1558 uint32 grfid
= grfid_buf
[0] | (grfid_buf
[1] << 8) | (grfid_buf
[2] << 16) | (grfid_buf
[3] << 24);
1560 const GRFConfig
*s
= FindGRFConfig(grfid
, FGCM_EXACT
, md5sum
);
1561 if (s
!= nullptr) c
= new GRFConfig(*s
);
1563 if (c
== nullptr && !FioCheckFileExists(filename
, NEWGRF_DIR
)) {
1564 const GRFConfig
*s
= FindGRFConfig(grfid
, FGCM_NEWEST_VALID
);
1565 if (s
!= nullptr) c
= new GRFConfig(*s
);
1568 if (c
== nullptr) c
= new GRFConfig(filename
);
1570 /* Parse parameters */
1571 if (item
->value
.has_value() && !item
->value
->empty()) {
1572 int count
= ParseIntList(item
->value
->c_str(), c
->param
, lengthof(c
->param
));
1574 SetDParamStr(0, filename
);
1575 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_ARRAY
, WL_CRITICAL
);
1578 c
->num_params
= count
;
1581 /* Check if item is valid */
1582 if (!FillGRFDetails(c
, is_static
) || HasBit(c
->flags
, GCF_INVALID
)) {
1583 if (c
->status
== GCS_NOT_FOUND
) {
1584 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND
);
1585 } else if (HasBit(c
->flags
, GCF_UNSAFE
)) {
1586 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE
);
1587 } else if (HasBit(c
->flags
, GCF_SYSTEM
)) {
1588 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM
);
1589 } else if (HasBit(c
->flags
, GCF_INVALID
)) {
1590 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE
);
1592 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN
);
1595 SetDParamStr(0, StrEmpty(filename
) ? item
->name
.c_str() : filename
);
1596 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_GRF
, WL_CRITICAL
);
1601 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1602 bool duplicate
= false;
1603 for (const GRFConfig
*gc
= first
; gc
!= nullptr; gc
= gc
->next
) {
1604 if (gc
->ident
.grfid
== c
->ident
.grfid
) {
1605 SetDParamStr(0, c
->filename
);
1606 SetDParamStr(1, gc
->filename
);
1607 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_DUPLICATE_GRFID
, WL_CRITICAL
);
1617 /* Mark file as static to avoid saving in savegame. */
1618 if (is_static
) SetBit(c
->flags
, GCF_STATIC
);
1620 /* Add item to list */
1628 static void AISaveConfig(IniFile
*ini
, const char *grpname
)
1630 IniGroup
*group
= ini
->GetGroup(grpname
);
1632 if (group
== nullptr) return;
1635 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1636 AIConfig
*config
= AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
);
1639 config
->SettingsToString(value
, lastof(value
));
1641 if (config
->HasScript()) {
1642 name
= config
->GetName();
1647 IniItem
*item
= new IniItem(group
, name
);
1648 item
->SetValue(value
);
1652 static void GameSaveConfig(IniFile
*ini
, const char *grpname
)
1654 IniGroup
*group
= ini
->GetGroup(grpname
);
1656 if (group
== nullptr) return;
1659 GameConfig
*config
= GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME
);
1662 config
->SettingsToString(value
, lastof(value
));
1664 if (config
->HasScript()) {
1665 name
= config
->GetName();
1670 IniItem
*item
= new IniItem(group
, name
);
1671 item
->SetValue(value
);
1675 * Save the version of OpenTTD to the ini file.
1676 * @param ini the ini to write to
1678 static void SaveVersionInConfig(IniFile
*ini
)
1680 IniGroup
*group
= ini
->GetGroup("version");
1683 seprintf(version
, lastof(version
), "%08X", _openttd_newgrf_version
);
1685 const char * const versions
[][2] = {
1686 { "version_string", _openttd_revision
},
1687 { "version_number", version
}
1690 for (uint i
= 0; i
< lengthof(versions
); i
++) {
1691 group
->GetItem(versions
[i
][0], true)->SetValue(versions
[i
][1]);
1695 /* Save a GRF configuration to the given group name */
1696 static void GRFSaveConfig(IniFile
*ini
, const char *grpname
, const GRFConfig
*list
)
1698 ini
->RemoveGroup(grpname
);
1699 IniGroup
*group
= ini
->GetGroup(grpname
);
1702 for (c
= list
; c
!= nullptr; c
= c
->next
) {
1703 /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1704 char key
[4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH
];
1706 GRFBuildParamList(params
, c
, lastof(params
));
1708 char *pos
= key
+ seprintf(key
, lastof(key
), "%08X|", BSWAP32(c
->ident
.grfid
));
1709 pos
= md5sumToString(pos
, lastof(key
), c
->ident
.md5sum
);
1710 seprintf(pos
, lastof(key
), "|%s", c
->filename
);
1711 group
->GetItem(key
, true)->SetValue(params
);
1715 /* Common handler for saving/loading variables to the configuration file */
1716 static void HandleSettingDescs(IniFile
*ini
, SettingDescProc
*proc
, SettingDescProcList
*proc_list
, bool basic_settings
= true, bool other_settings
= true)
1718 if (basic_settings
) {
1719 proc(ini
, (const SettingDesc
*)_misc_settings
, "misc", nullptr);
1720 #if defined(_WIN32) && !defined(DEDICATED)
1721 proc(ini
, (const SettingDesc
*)_win32_settings
, "win32", nullptr);
1725 if (other_settings
) {
1726 proc(ini
, _settings
, "patches", &_settings_newgame
);
1727 proc(ini
, _currency_settings
,"currency", &_custom_currency
);
1728 proc(ini
, _company_settings
, "company", &_settings_client
.company
);
1730 proc_list(ini
, "server_bind_addresses", _network_bind_list
);
1731 proc_list(ini
, "servers", _network_host_list
);
1732 proc_list(ini
, "bans", _network_ban_list
);
1736 static IniFile
*IniLoadConfig()
1738 IniFile
*ini
= new IniFile(_list_group_names
);
1739 ini
->LoadFromDisk(_config_file
, NO_DIRECTORY
);
1744 * Load the values from the configuration files
1745 * @param minimal Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1747 void LoadFromConfig(bool minimal
)
1749 IniFile
*ini
= IniLoadConfig();
1750 if (!minimal
) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1752 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1753 HandleSettingDescs(ini
, IniLoadSettings
, IniLoadSettingList
, minimal
, !minimal
);
1756 _grfconfig_newgame
= GRFLoadConfig(ini
, "newgrf", false);
1757 _grfconfig_static
= GRFLoadConfig(ini
, "newgrf-static", true);
1758 AILoadConfig(ini
, "ai_players");
1759 GameLoadConfig(ini
, "game_scripts");
1761 PrepareOldDiffCustom();
1762 IniLoadSettings(ini
, _gameopt_settings
, "gameopt", &_settings_newgame
);
1763 HandleOldDiffCustom(false);
1767 /* Display scheduled errors */
1768 extern void ScheduleErrorMessage(ErrorList
&datas
);
1769 ScheduleErrorMessage(_settings_error_list
);
1770 if (FindWindowById(WC_ERRMSG
, 0) == nullptr) ShowFirstError();
1776 /** Save the values to the configuration file */
1779 IniFile
*ini
= IniLoadConfig();
1781 /* Remove some obsolete groups. These have all been loaded into other groups. */
1782 ini
->RemoveGroup("patches");
1783 ini
->RemoveGroup("yapf");
1784 ini
->RemoveGroup("gameopt");
1786 HandleSettingDescs(ini
, IniSaveSettings
, IniSaveSettingList
);
1787 GRFSaveConfig(ini
, "newgrf", _grfconfig_newgame
);
1788 GRFSaveConfig(ini
, "newgrf-static", _grfconfig_static
);
1789 AISaveConfig(ini
, "ai_players");
1790 GameSaveConfig(ini
, "game_scripts");
1791 SaveVersionInConfig(ini
);
1792 ini
->SaveToDisk(_config_file
);
1797 * Get the list of known NewGrf presets.
1798 * @returns List of preset names.
1800 StringList
GetGRFPresetList()
1804 std::unique_ptr
<IniFile
> ini(IniLoadConfig());
1805 for (IniGroup
*group
= ini
->group
; group
!= nullptr; group
= group
->next
) {
1806 if (group
->name
.compare(0, 7, "preset-") == 0) {
1807 list
.push_back(group
->name
.substr(7));
1815 * Load a NewGRF configuration by preset-name.
1816 * @param config_name Name of the preset.
1817 * @return NewGRF configuration.
1818 * @see GetGRFPresetList
1820 GRFConfig
*LoadGRFPresetFromConfig(const char *config_name
)
1822 size_t len
= strlen(config_name
) + 8;
1823 char *section
= (char*)alloca(len
);
1824 seprintf(section
, section
+ len
- 1, "preset-%s", config_name
);
1826 IniFile
*ini
= IniLoadConfig();
1827 GRFConfig
*config
= GRFLoadConfig(ini
, section
, false);
1834 * Save a NewGRF configuration with a preset name.
1835 * @param config_name Name of the preset.
1836 * @param config NewGRF configuration to save.
1837 * @see GetGRFPresetList
1839 void SaveGRFPresetToConfig(const char *config_name
, GRFConfig
*config
)
1841 size_t len
= strlen(config_name
) + 8;
1842 char *section
= (char*)alloca(len
);
1843 seprintf(section
, section
+ len
- 1, "preset-%s", config_name
);
1845 IniFile
*ini
= IniLoadConfig();
1846 GRFSaveConfig(ini
, section
, config
);
1847 ini
->SaveToDisk(_config_file
);
1852 * Delete a NewGRF configuration by preset name.
1853 * @param config_name Name of the preset.
1855 void DeleteGRFPresetFromConfig(const char *config_name
)
1857 size_t len
= strlen(config_name
) + 8;
1858 char *section
= (char*)alloca(len
);
1859 seprintf(section
, section
+ len
- 1, "preset-%s", config_name
);
1861 IniFile
*ini
= IniLoadConfig();
1862 ini
->RemoveGroup(section
);
1863 ini
->SaveToDisk(_config_file
);
1867 const SettingDesc
*GetSettingDescription(uint index
)
1869 if (index
>= lengthof(_settings
)) return nullptr;
1870 return &_settings
[index
];
1874 * Network-safe changing of settings (server-only).
1875 * @param tile unused
1876 * @param flags operation to perform
1877 * @param p1 the index of the setting in the SettingDesc array which identifies it
1878 * @param p2 the new value for the setting
1879 * The new value is properly clamped to its minimum/maximum when setting
1880 * @param text unused
1881 * @return the cost of this operation or an error
1884 CommandCost
CmdChangeSetting(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1886 const SettingDesc
*sd
= GetSettingDescription(p1
);
1888 if (sd
== nullptr) return CMD_ERROR
;
1889 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) return CMD_ERROR
;
1891 if (!sd
->IsEditable(true)) return CMD_ERROR
;
1893 if (flags
& DC_EXEC
) {
1894 void *var
= GetVariableAddress(&GetGameSettings(), &sd
->save
);
1896 int32 oldval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1897 int32 newval
= (int32
)p2
;
1899 Write_ValidateSetting(var
, sd
, newval
);
1900 newval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1902 if (oldval
== newval
) return CommandCost();
1904 if (sd
->desc
.proc
!= nullptr && !sd
->desc
.proc(newval
)) {
1905 WriteValue(var
, sd
->save
.conv
, (int64
)oldval
);
1906 return CommandCost();
1909 if (sd
->desc
.flags
& SGF_NO_NETWORK
) {
1910 GamelogStartAction(GLAT_SETTING
);
1911 GamelogSetting(sd
->desc
.name
, oldval
, newval
);
1912 GamelogStopAction();
1915 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1917 if (_save_config
) SaveToConfig();
1920 return CommandCost();
1924 * Change one of the per-company settings.
1925 * @param tile unused
1926 * @param flags operation to perform
1927 * @param p1 the index of the setting in the _company_settings array which identifies it
1928 * @param p2 the new value for the setting
1929 * The new value is properly clamped to its minimum/maximum when setting
1930 * @param text unused
1931 * @return the cost of this operation or an error
1933 CommandCost
CmdChangeCompanySetting(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1935 if (p1
>= lengthof(_company_settings
)) return CMD_ERROR
;
1936 const SettingDesc
*sd
= &_company_settings
[p1
];
1938 if (flags
& DC_EXEC
) {
1939 void *var
= GetVariableAddress(&Company::Get(_current_company
)->settings
, &sd
->save
);
1941 int32 oldval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1942 int32 newval
= (int32
)p2
;
1944 Write_ValidateSetting(var
, sd
, newval
);
1945 newval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1947 if (oldval
== newval
) return CommandCost();
1949 if (sd
->desc
.proc
!= nullptr && !sd
->desc
.proc(newval
)) {
1950 WriteValue(var
, sd
->save
.conv
, (int64
)oldval
);
1951 return CommandCost();
1954 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1957 return CommandCost();
1961 * Top function to save the new value of an element of the Settings struct
1962 * @param index offset in the SettingDesc array of the Settings struct which
1963 * identifies the setting member we want to change
1964 * @param value new value of the setting
1965 * @param force_newgame force the newgame settings
1967 bool SetSettingValue(uint index
, int32 value
, bool force_newgame
)
1969 const SettingDesc
*sd
= &_settings
[index
];
1970 /* If an item is company-based, we do not send it over the network
1971 * (if any) to change. Also *hack*hack* we update the _newgame version
1972 * of settings because changing a company-based setting in a game also
1973 * changes its defaults. At least that is the convention we have chosen */
1974 if (sd
->save
.conv
& SLF_NO_NETWORK_SYNC
) {
1975 void *var
= GetVariableAddress(&GetGameSettings(), &sd
->save
);
1976 Write_ValidateSetting(var
, sd
, value
);
1978 if (_game_mode
!= GM_MENU
) {
1979 void *var2
= GetVariableAddress(&_settings_newgame
, &sd
->save
);
1980 Write_ValidateSetting(var2
, sd
, value
);
1982 if (sd
->desc
.proc
!= nullptr) sd
->desc
.proc((int32
)ReadValue(var
, sd
->save
.conv
));
1984 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1986 if (_save_config
) SaveToConfig();
1990 if (force_newgame
) {
1991 void *var2
= GetVariableAddress(&_settings_newgame
, &sd
->save
);
1992 Write_ValidateSetting(var2
, sd
, value
);
1994 if (_save_config
) SaveToConfig();
1998 /* send non-company-based settings over the network */
1999 if (!_networking
|| (_networking
&& _network_server
)) {
2000 return DoCommandP(0, index
, value
, CMD_CHANGE_SETTING
);
2006 * Top function to save the new value of an element of the Settings struct
2007 * @param index offset in the SettingDesc array of the CompanySettings struct
2008 * which identifies the setting member we want to change
2009 * @param value new value of the setting
2011 void SetCompanySetting(uint index
, int32 value
)
2013 const SettingDesc
*sd
= &_company_settings
[index
];
2014 if (Company::IsValidID(_local_company
) && _game_mode
!= GM_MENU
) {
2015 DoCommandP(0, index
, value
, CMD_CHANGE_COMPANY_SETTING
);
2017 void *var
= GetVariableAddress(&_settings_client
.company
, &sd
->save
);
2018 Write_ValidateSetting(var
, sd
, value
);
2019 if (sd
->desc
.proc
!= nullptr) sd
->desc
.proc((int32
)ReadValue(var
, sd
->save
.conv
));
2024 * Set the company settings for a new company to their default values.
2026 void SetDefaultCompanySettings(CompanyID cid
)
2028 Company
*c
= Company::Get(cid
);
2029 const SettingDesc
*sd
;
2030 for (sd
= _company_settings
; sd
->save
.cmd
!= SL_END
; sd
++) {
2031 void *var
= GetVariableAddress(&c
->settings
, &sd
->save
);
2032 Write_ValidateSetting(var
, sd
, (int32
)(size_t)sd
->desc
.def
);
2037 * Sync all company settings in a multiplayer game.
2039 void SyncCompanySettings()
2041 const SettingDesc
*sd
;
2043 for (sd
= _company_settings
; sd
->save
.cmd
!= SL_END
; sd
++, i
++) {
2044 const void *old_var
= GetVariableAddress(&Company::Get(_current_company
)->settings
, &sd
->save
);
2045 const void *new_var
= GetVariableAddress(&_settings_client
.company
, &sd
->save
);
2046 uint32 old_value
= (uint32
)ReadValue(old_var
, sd
->save
.conv
);
2047 uint32 new_value
= (uint32
)ReadValue(new_var
, sd
->save
.conv
);
2048 if (old_value
!= new_value
) NetworkSendCommand(0, i
, new_value
, CMD_CHANGE_COMPANY_SETTING
, nullptr, nullptr, _local_company
);
2053 * Get the index in the _company_settings array of a setting
2054 * @param name The name of the setting
2055 * @return The index in the _company_settings array
2057 uint
GetCompanySettingIndex(const char *name
)
2060 const SettingDesc
*sd
= GetSettingFromName(name
, &i
);
2061 (void)sd
; // Unused without asserts
2062 assert(sd
!= nullptr && (sd
->desc
.flags
& SGF_PER_COMPANY
) != 0);
2067 * Set a setting value with a string.
2068 * @param index the settings index.
2069 * @param value the value to write
2070 * @param force_newgame force the newgame settings
2071 * @note Strings WILL NOT be synced over the network
2073 bool SetSettingValue(uint index
, const char *value
, bool force_newgame
)
2075 const SettingDesc
*sd
= &_settings
[index
];
2076 assert(sd
->save
.conv
& SLF_NO_NETWORK_SYNC
);
2078 if (GetVarMemType(sd
->save
.conv
) == SLE_VAR_STRQ
) {
2079 char **var
= (char**)GetVariableAddress((_game_mode
== GM_MENU
|| force_newgame
) ? &_settings_newgame
: &_settings_game
, &sd
->save
);
2081 *var
= strcmp(value
, "(null)") == 0 ? nullptr : stredup(value
);
2083 char *var
= (char*)GetVariableAddress(nullptr, &sd
->save
);
2084 strecpy(var
, value
, &var
[sd
->save
.length
- 1]);
2086 if (sd
->desc
.proc
!= nullptr) sd
->desc
.proc(0);
2088 if (_save_config
) SaveToConfig();
2093 * Given a name of setting, return a setting description of it.
2094 * @param name Name of the setting to return a setting description of
2095 * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
2096 * @return Pointer to the setting description of setting \a name if it can be found,
2097 * \c nullptr indicates failure to obtain the description
2099 const SettingDesc
*GetSettingFromName(const char *name
, uint
*i
)
2101 const SettingDesc
*sd
;
2103 /* First check all full names */
2104 for (*i
= 0, sd
= _settings
; sd
->save
.cmd
!= SL_END
; sd
++, (*i
)++) {
2105 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
2106 if (strcmp(sd
->desc
.name
, name
) == 0) return sd
;
2109 /* Then check the shortcut variant of the name. */
2110 for (*i
= 0, sd
= _settings
; sd
->save
.cmd
!= SL_END
; sd
++, (*i
)++) {
2111 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
2112 const char *short_name
= strchr(sd
->desc
.name
, '.');
2113 if (short_name
!= nullptr) {
2115 if (strcmp(short_name
, name
) == 0) return sd
;
2119 if (strncmp(name
, "company.", 8) == 0) name
+= 8;
2120 /* And finally the company-based settings */
2121 for (*i
= 0, sd
= _company_settings
; sd
->save
.cmd
!= SL_END
; sd
++, (*i
)++) {
2122 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
2123 if (strcmp(sd
->desc
.name
, name
) == 0) return sd
;
2129 /* Those 2 functions need to be here, else we have to make some stuff non-static
2130 * and besides, it is also better to keep stuff like this at the same place */
2131 void IConsoleSetSetting(const char *name
, const char *value
, bool force_newgame
)
2134 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2136 if (sd
== nullptr) {
2137 IConsolePrintF(CC_WARNING
, "'%s' is an unknown setting.", name
);
2142 if (sd
->desc
.cmd
== SDT_STRING
) {
2143 success
= SetSettingValue(index
, value
, force_newgame
);
2146 extern bool GetArgumentInteger(uint32
*value
, const char *arg
);
2147 success
= GetArgumentInteger(&val
, value
);
2149 IConsolePrintF(CC_ERROR
, "'%s' is not an integer.", value
);
2153 success
= SetSettingValue(index
, val
, force_newgame
);
2157 if (_network_server
) {
2158 IConsoleError("This command/variable is not available during network games.");
2160 IConsoleError("This command/variable is only available to a network server.");
2165 void IConsoleSetSetting(const char *name
, int value
)
2168 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2169 (void)sd
; // Unused without asserts
2170 assert(sd
!= nullptr);
2171 SetSettingValue(index
, value
);
2175 * Output value of a specific setting to the console
2176 * @param name Name of the setting to output its value
2177 * @param force_newgame force the newgame settings
2179 void IConsoleGetSetting(const char *name
, bool force_newgame
)
2183 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2186 if (sd
== nullptr) {
2187 IConsolePrintF(CC_WARNING
, "'%s' is an unknown setting.", name
);
2191 ptr
= GetVariableAddress((_game_mode
== GM_MENU
|| force_newgame
) ? &_settings_newgame
: &_settings_game
, &sd
->save
);
2193 if (sd
->desc
.cmd
== SDT_STRING
) {
2194 IConsolePrintF(CC_WARNING
, "Current value for '%s' is: '%s'", name
, (GetVarMemType(sd
->save
.conv
) == SLE_VAR_STRQ
) ? *(const char * const *)ptr
: (const char *)ptr
);
2196 if (sd
->desc
.cmd
== SDT_BOOLX
) {
2197 seprintf(value
, lastof(value
), (*(const bool*)ptr
!= 0) ? "on" : "off");
2199 seprintf(value
, lastof(value
), sd
->desc
.min
< 0 ? "%d" : "%u", (int32
)ReadValue(ptr
, sd
->save
.conv
));
2202 IConsolePrintF(CC_WARNING
, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
2203 name
, value
, (sd
->desc
.flags
& SGF_0ISDISABLED
) ? "(0) " : "", sd
->desc
.min
, sd
->desc
.max
);
2208 * List all settings and their value to the console
2210 * @param prefilter If not \c nullptr, only list settings with names that begin with \a prefilter prefix
2212 void IConsoleListSettings(const char *prefilter
)
2214 IConsolePrintF(CC_WARNING
, "All settings with their current value:");
2216 for (const SettingDesc
*sd
= _settings
; sd
->save
.cmd
!= SL_END
; sd
++) {
2217 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
2218 if (prefilter
!= nullptr && strstr(sd
->desc
.name
, prefilter
) == nullptr) continue;
2220 const void *ptr
= GetVariableAddress(&GetGameSettings(), &sd
->save
);
2222 if (sd
->desc
.cmd
== SDT_BOOLX
) {
2223 seprintf(value
, lastof(value
), (*(const bool *)ptr
!= 0) ? "on" : "off");
2224 } else if (sd
->desc
.cmd
== SDT_STRING
) {
2225 seprintf(value
, lastof(value
), "%s", (GetVarMemType(sd
->save
.conv
) == SLE_VAR_STRQ
) ? *(const char * const *)ptr
: (const char *)ptr
);
2227 seprintf(value
, lastof(value
), sd
->desc
.min
< 0 ? "%d" : "%u", (int32
)ReadValue(ptr
, sd
->save
.conv
));
2229 IConsolePrintF(CC_DEFAULT
, "%s = %s", sd
->desc
.name
, value
);
2232 IConsolePrintF(CC_WARNING
, "Use 'setting' command to change a value");
2236 * Save and load handler for settings
2237 * @param osd SettingDesc struct containing all information
2238 * @param object can be either nullptr in which case we load global variables or
2239 * a pointer to a struct which is getting saved
2241 static void LoadSettings(const SettingDesc
*osd
, void *object
)
2243 for (; osd
->save
.cmd
!= SL_END
; osd
++) {
2244 const SaveLoad
*sld
= &osd
->save
;
2245 void *ptr
= GetVariableAddress(object
, sld
);
2247 if (!SlObjectMember(ptr
, sld
)) continue;
2248 if (IsNumericType(sld
->conv
)) Write_ValidateSetting(ptr
, osd
, ReadValue(ptr
, sld
->conv
));
2253 * Save and load handler for settings
2254 * @param sd SettingDesc struct containing all information
2255 * @param object can be either nullptr in which case we load global variables or
2256 * a pointer to a struct which is getting saved
2258 static void SaveSettings(const SettingDesc
*sd
, void *object
)
2260 /* We need to write the CH_RIFF header, but unfortunately can't call
2261 * SlCalcLength() because we have a different format. So do this manually */
2262 const SettingDesc
*i
;
2264 for (i
= sd
; i
->save
.cmd
!= SL_END
; i
++) {
2265 length
+= SlCalcObjMemberLength(object
, &i
->save
);
2267 SlSetLength(length
);
2269 for (i
= sd
; i
->save
.cmd
!= SL_END
; i
++) {
2270 void *ptr
= GetVariableAddress(object
, &i
->save
);
2271 SlObjectMember(ptr
, &i
->save
);
2275 static void Load_OPTS()
2277 /* Copy over default setting since some might not get loaded in
2278 * a networking environment. This ensures for example that the local
2279 * autosave-frequency stays when joining a network-server */
2280 PrepareOldDiffCustom();
2281 LoadSettings(_gameopt_settings
, &_settings_game
);
2282 HandleOldDiffCustom(true);
2285 static void Load_PATS()
2287 /* Copy over default setting since some might not get loaded in
2288 * a networking environment. This ensures for example that the local
2289 * currency setting stays when joining a network-server */
2290 LoadSettings(_settings
, &_settings_game
);
2293 static void Check_PATS()
2295 LoadSettings(_settings
, &_load_check_data
.settings
);
2298 static void Save_PATS()
2300 SaveSettings(_settings
, &_settings_game
);
2303 extern const ChunkHandler _setting_chunk_handlers
[] = {
2304 { 'OPTS', nullptr, Load_OPTS
, nullptr, nullptr, CH_RIFF
},
2305 { 'PATS', Save_PATS
, Load_PATS
, nullptr, Check_PATS
, CH_RIFF
| CH_LAST
},
2308 static bool IsSignedVarMemType(VarType vt
)
2310 switch (GetVarMemType(vt
)) {