4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
12 * All actions handling saving and loading of the settings/configuration goes on in this file.
13 * The file consists of three parts:
15 * <li>Parsing the configuration file (openttd.cfg). This is achieved with the ini_ functions which
16 * handle various types, such as normal 'key = value' pairs, lists and value combinations of
17 * lists, strings, integers, 'bit'-masks and element selections.
18 * <li>Handle reading and writing to the setting-structures from inside the game either from
19 * the console for example or through the gui with CMD_ functions.
20 * <li>Handle saving/loading of the PATS chunk inside the savegame.
28 #include "screenshot.h"
29 #include "network/network.h"
30 #include "network/network_func.h"
31 #include "settings_internal.h"
32 #include "command_func.h"
33 #include "console_func.h"
34 #include "pathfinder/pathfinder_type.h"
37 #include "news_func.h"
38 #include "window_func.h"
39 #include "sound_func.h"
40 #include "company_func.h"
43 #include "fontcache.h"
45 #include "textbuf_gui.h"
47 #include "elrail_func.h"
50 #include "video/video_driver.hpp"
51 #include "sound/sound_driver.hpp"
52 #include "music/music_driver.hpp"
53 #include "blitter/factory.hpp"
54 #include "base_media_base.h"
56 #include "settings_func.h"
58 #include "ai/ai_config.hpp"
60 #include "game/game_config.hpp"
61 #include "game/game.hpp"
63 #include "smallmap_gui.h"
66 #include "strings_func.h"
68 #include "map/ground.h"
69 #include "station_base.h"
70 #include "station_func.h"
72 #include "table/strings.h"
73 #include "table/settings.h"
75 ClientSettings _settings_client
;
76 GameSettings _settings_game
; ///< Game settings of a running game or the scenario editor.
77 GameSettings _settings_newgame
; ///< Game settings for new games (updated from the intro screen).
78 VehicleDefaultSettings _old_vds
; ///< Used for loading default vehicles settings from old savegames
79 char *_config_file
; ///< Configuration file of OpenTTD
81 typedef std::list
<ErrorMessageData
> ErrorList
;
82 static ErrorList _settings_error_list
; ///< Errors while loading minimal settings.
85 typedef void SettingDescProc(IniFile
*ini
, const SettingDesc
*desc
, const char *grpname
, void *object
);
86 typedef void SettingDescProcList(IniFile
*ini
, const char *grpname
, StringList
*list
);
88 static bool IsSignedVarMemType(VarType vt
);
91 * Groups in openttd.cfg that are actually lists.
93 static const char * const _list_group_names
[] = {
97 "server_bind_addresses",
102 * Find the index value of a ONEofMANY type in a string separated by |
103 * @param many full domain of values the ONEofMANY setting can have
104 * @param one the current value of the setting for which a value needs found
105 * @param onelen force calculation of the *one parameter
106 * @return the integer index of the full-list, or -1 if not found
108 static size_t LookupOneOfMany(const char *many
, const char *one
, size_t onelen
= 0)
113 if (onelen
== 0) onelen
= strlen(one
);
115 /* check if it's an integer */
116 if (*one
>= '0' && *one
<= '9') return strtoul(one
, NULL
, 0);
120 /* find end of item */
122 while (*s
!= '|' && *s
!= 0) s
++;
123 if ((size_t)(s
- many
) == onelen
&& !memcmp(one
, many
, onelen
)) return idx
;
124 if (*s
== 0) return (size_t)-1;
131 * Find the set-integer value MANYofMANY type in a string
132 * @param many full domain of values the MANYofMANY setting can have
133 * @param str the current string value of the setting, each individual
134 * of separated by a whitespace,tab or | character
135 * @return the 'fully' set integer, or -1 if a set is not found
137 static size_t LookupManyOfMany(const char *many
, const char *str
)
144 /* skip "whitespace" */
145 while (*str
== ' ' || *str
== '\t' || *str
== '|') str
++;
146 if (*str
== 0) break;
149 while (*s
!= 0 && *s
!= ' ' && *s
!= '\t' && *s
!= '|') s
++;
151 r
= LookupOneOfMany(many
, str
, s
- str
);
152 if (r
== (size_t)-1) return r
;
154 SetBit(res
, (uint8
)r
); // value found, set it
162 * Parse an integerlist string and set each found value
163 * @param p the string to be parsed. Each element in the list is separated by a
164 * comma or a space character
165 * @param items pointer to the integerlist-array that will be filled with values
166 * @param maxitems the maximum number of elements the integerlist-array has
167 * @return returns the number of items found, or -1 on an error
169 static int ParseIntList(const char *p
, int *items
, int maxitems
)
171 int n
= 0; // number of items read so far
172 bool comma
= false; // do we accept comma?
177 /* Do not accept multiple commas between numbers */
178 if (!comma
) return -1;
186 if (n
== maxitems
) return -1; // we don't accept that many numbers
188 long v
= strtol(p
, &end
, 0);
189 if (p
== end
) return -1; // invalid character (not a number)
190 if (sizeof(int) < sizeof(long)) v
= ClampToI32(v
);
192 p
= end
; // first non-number
193 comma
= true; // we accept comma now
199 /* If we have read comma but no number after it, fail.
200 * We have read comma when (n != 0) and comma is not allowed */
201 if (n
!= 0 && !comma
) return -1;
207 * Load parsed string-values into an integer-array (intlist)
208 * @param str the string that contains the values (and will be parsed)
209 * @param array pointer to the integer-arrays that will be filled
210 * @param nelems the number of elements the array holds. Maximum is 64 elements
211 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
212 * @return return true on success and false on error
214 static bool LoadIntList(const char *str
, void *array
, int nelems
, VarType type
)
220 memset(items
, 0, sizeof(items
));
223 nitems
= ParseIntList(str
, items
, lengthof(items
));
224 if (nitems
!= nelems
) return false;
231 for (i
= 0; i
!= nitems
; i
++) ((byte
*)array
)[i
] = items
[i
];
236 for (i
= 0; i
!= nitems
; i
++) ((uint16
*)array
)[i
] = items
[i
];
241 for (i
= 0; i
!= nitems
; i
++) ((uint32
*)array
)[i
] = items
[i
];
244 default: NOT_REACHED();
251 * Convert an integer-array (intlist) to a string representation. Each value
252 * is separated by a comma or a space character
253 * @param buf output buffer where the string-representation will be stored
254 * @param last last item to write to in the output buffer
255 * @param array pointer to the integer-arrays that is read from
256 * @param nelems the number of elements the array holds.
257 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
259 static void MakeIntList(char *buf
, const char *last
, const void *array
, int nelems
, VarType type
)
262 const byte
*p
= (const byte
*)array
;
264 for (i
= 0; i
!= nelems
; i
++) {
267 case SLE_VAR_I8
: v
= *(const int8
*)p
; p
+= 1; break;
268 case SLE_VAR_U8
: v
= *(const uint8
*)p
; p
+= 1; break;
269 case SLE_VAR_I16
: v
= *(const int16
*)p
; p
+= 2; break;
270 case SLE_VAR_U16
: v
= *(const uint16
*)p
; p
+= 2; break;
271 case SLE_VAR_I32
: v
= *(const int32
*)p
; p
+= 4; break;
272 case SLE_VAR_U32
: v
= *(const uint32
*)p
; p
+= 4; break;
273 default: NOT_REACHED();
275 buf
+= seprintf(buf
, last
, (i
== 0) ? "%d" : ",%d", v
);
280 * Convert a ONEofMANY structure to a string representation.
281 * @param buf output buffer where the string-representation will be stored
282 * @param last last item to write to in the output buffer
283 * @param many the full-domain string of possible values
284 * @param id the value of the variable and whose string-representation must be found
286 static void MakeOneOfMany(char *buf
, const char *last
, const char *many
, int id
)
290 /* Look for the id'th element */
292 for (; *many
!= '|'; many
++) {
293 if (*many
== '\0') { // not found
294 seprintf(buf
, last
, "%d", orig_id
);
298 many
++; // pass the |-character
301 /* copy string until next item (|) or the end of the list if this is the last one */
302 while (*many
!= '\0' && *many
!= '|' && buf
< last
) *buf
++ = *many
++;
307 * Convert a MANYofMANY structure to a string representation.
308 * @param buf output buffer where the string-representation will be stored
309 * @param last last item to write to in the output buffer
310 * @param many the full-domain string of possible values
311 * @param x the value of the variable and whose string-representation must
312 * be found in the bitmasked many string
314 static void MakeManyOfMany(char *buf
, const char *last
, const char *many
, uint32 x
)
320 for (; x
!= 0; x
>>= 1, i
++) {
322 while (*many
!= 0 && *many
!= '|') many
++; // advance to the next element
324 if (HasBit(x
, 0)) { // item found, copy it
325 if (!init
) buf
+= seprintf(buf
, last
, "|");
328 buf
+= seprintf(buf
, last
, "%d", i
);
330 memcpy(buf
, start
, many
- start
);
335 if (*many
== '|') many
++;
342 * Convert a string representation (external) of a setting to the internal rep.
343 * @param desc SettingDesc struct that holds all information about the variable
344 * @param orig_str input string that will be parsed based on the type of desc
345 * @return return the parsed value of the setting
347 static const void *StringToVal(const SettingDescBase
*desc
, const char *orig_str
)
349 const char *str
= orig_str
== NULL
? "" : orig_str
;
354 size_t val
= strtoul(str
, &end
, 0);
356 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
357 msg
.SetDParamStr(0, str
);
358 msg
.SetDParamStr(1, desc
->name
);
359 _settings_error_list
.push_back(msg
);
363 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_TRAILING_CHARACTERS
);
364 msg
.SetDParamStr(0, desc
->name
);
365 _settings_error_list
.push_back(msg
);
370 case SDT_ONEOFMANY
: {
371 size_t r
= LookupOneOfMany(desc
->many
, str
);
372 /* if the first attempt of conversion from string to the appropriate value fails,
373 * look if we have defined a converter from old value to new value. */
374 if (r
== (size_t)-1 && desc
->proc_cnvt
!= NULL
) r
= desc
->proc_cnvt(str
);
375 if (r
!= (size_t)-1) return (void*)r
; // and here goes converted value
377 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
378 msg
.SetDParamStr(0, str
);
379 msg
.SetDParamStr(1, desc
->name
);
380 _settings_error_list
.push_back(msg
);
384 case SDT_MANYOFMANY
: {
385 size_t r
= LookupManyOfMany(desc
->many
, str
);
386 if (r
!= (size_t)-1) return (void*)r
;
387 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
388 msg
.SetDParamStr(0, str
);
389 msg
.SetDParamStr(1, desc
->name
);
390 _settings_error_list
.push_back(msg
);
395 if (strcmp(str
, "true") == 0 || strcmp(str
, "on") == 0 || strcmp(str
, "1") == 0) return (void*)true;
396 if (strcmp(str
, "false") == 0 || strcmp(str
, "off") == 0 || strcmp(str
, "0") == 0) return (void*)false;
398 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
399 msg
.SetDParamStr(0, str
);
400 msg
.SetDParamStr(1, desc
->name
);
401 _settings_error_list
.push_back(msg
);
405 case SDT_STRING
: return orig_str
;
406 case SDT_INTLIST
: return str
;
414 * Set the value of a setting and if needed clamp the value to
415 * the preset minimum and maximum.
416 * @param ptr the variable itself
417 * @param sd pointer to the 'information'-database of the variable
418 * @param val signed long version of the new value
419 * @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
420 * SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now
422 static void Write_ValidateSetting(void *ptr
, const SettingDesc
*sd
, int32 val
)
424 const SettingDescBase
*sdb
= &sd
->desc
;
426 if (sdb
->cmd
!= SDT_BOOLX
&&
427 sdb
->cmd
!= SDT_NUMX
&&
428 sdb
->cmd
!= SDT_ONEOFMANY
&&
429 sdb
->cmd
!= SDT_MANYOFMANY
) {
433 /* We cannot know the maximum value of a bitset variable, so just have faith */
434 if (sdb
->cmd
!= SDT_MANYOFMANY
) {
435 assert(sd
->save
.type
== SL_VAR
);
437 /* We need to take special care of the uint32 type as we receive from the function
438 * a signed integer. While here also bail out on 64-bit settings as those are not
439 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
441 * TODO: Support 64-bit settings/variables */
442 switch (GetVarMemType(sd
->save
.conv
)) {
443 case SLE_VAR_NULL
: return;
450 /* Override the minimum value. No value below sdb->min, except special value 0 */
451 if (!(sdb
->flags
& SGF_0ISDISABLED
) || val
!= 0) val
= Clamp(val
, sdb
->min
, sdb
->max
);
455 /* Override the minimum value. No value below sdb->min, except special value 0 */
456 uint min
= ((sdb
->flags
& SGF_0ISDISABLED
) && (uint
)val
<= (uint
)sdb
->min
) ? 0 : sdb
->min
;
457 WriteValue(ptr
, SLE_VAR_U32
, (int64
)ClampU(val
, min
, sdb
->max
));
462 default: NOT_REACHED();
466 WriteValue(ptr
, sd
->save
.conv
, (int64
)val
);
470 * Load values from a group of an IniFile structure into the internal representation
471 * @param ini pointer to IniFile structure that holds administrative information
472 * @param sd pointer to SettingDesc structure whose internally pointed variables will
474 * @param grpname the group of the IniFile to search in for the new values
475 * @param object pointer to the object been loaded
477 static void IniLoadSettings(IniFile
*ini
, const SettingDesc
*sd
, const char *grpname
, void *object
)
480 IniGroup
*group_def
= ini
->GetGroup(grpname
);
486 for (; sd
->save
.type
!= SL_END
; sd
++) {
487 const SettingDescBase
*sdb
= &sd
->desc
;
488 const SaveLoad
*sld
= &sd
->save
;
490 if (!SlIsObjectCurrentlyValid(sld
)) continue;
492 /* For settings.xx.yy load the settings from [xx] yy = ? */
493 s
= strchr(sdb
->name
, '.');
495 group
= ini
->GetGroup(sdb
->name
, s
- sdb
->name
);
502 item
= group
->GetItem(s
, false);
503 if (item
== NULL
&& group
!= group_def
) {
504 /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
505 * did not exist (e.g. loading old config files with a [settings] section */
506 item
= group_def
->GetItem(s
, false);
509 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
510 * did not exist (e.g. loading old config files with a [yapf] section */
511 const char *sc
= strchr(s
, '.');
512 if (sc
!= NULL
) item
= ini
->GetGroup(s
, sc
- s
)->GetItem(sc
+ 1, false);
515 p
= (item
== NULL
) ? sdb
->def
: StringToVal(sdb
, item
->value
);
516 ptr
= GetVariableAddress(sld
, object
);
519 case SDT_BOOLX
: // All four are various types of (integer) numbers
523 Write_ValidateSetting(ptr
, sd
, (int32
)(size_t)p
);
527 if (sld
->type
!= SL_STR
) {
528 assert(sld
->type
== SL_VAR
);
529 assert(GetVarMemType(sld
->conv
) == SLE_VAR_CHAR
);
530 if (p
!= NULL
) *(char *)ptr
= *(const char *)p
;
531 } else if (sld
->conv
& SLS_POINTER
) {
533 *(char**)ptr
= p
== NULL
? NULL
: strdup((const char*)p
);
535 if (p
!= NULL
) ttd_strlcpy((char*)ptr
, (const char*)p
, sld
->length
);
540 if (!LoadIntList((const char*)p
, ptr
, sld
->length
, GetVarMemType(sld
->conv
))) {
541 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_ARRAY
);
542 msg
.SetDParamStr(0, sdb
->name
);
543 _settings_error_list
.push_back(msg
);
546 LoadIntList((const char*)sdb
->def
, ptr
, sld
->length
, GetVarMemType(sld
->conv
));
547 } else if (sd
->desc
.proc_cnvt
!= NULL
) {
548 sd
->desc
.proc_cnvt((const char*)p
);
552 default: NOT_REACHED();
558 * Save the values of settings to the inifile.
559 * @param ini pointer to IniFile structure
560 * @param sd read-only SettingDesc structure which contains the unmodified,
561 * loaded values of the configuration file and various information about it
562 * @param grpname holds the name of the group (eg. [network]) where these will be saved
563 * @param object pointer to the object been saved
564 * The function works as follows: for each item in the SettingDesc structure we
565 * have a look if the value has changed since we started the game (the original
566 * values are reloaded when saving). If settings indeed have changed, we get
567 * these and save them.
569 static void IniSaveSettings(IniFile
*ini
, const SettingDesc
*sd
, const char *grpname
, void *object
)
571 IniGroup
*group_def
= NULL
, *group
;
577 for (; sd
->save
.type
!= SL_END
; sd
++) {
578 const SettingDescBase
*sdb
= &sd
->desc
;
579 const SaveLoad
*sld
= &sd
->save
;
581 /* If the setting is not saved to the configuration
582 * file, just continue with the next setting */
583 if (!SlIsObjectCurrentlyValid(sld
)) continue;
584 if (sld
->flags
& SLF_NOT_IN_CONFIG
) continue;
586 /* XXX - wtf is this?? (group override?) */
587 s
= strchr(sdb
->name
, '.');
589 group
= ini
->GetGroup(sdb
->name
, s
- sdb
->name
);
592 if (group_def
== NULL
) group_def
= ini
->GetGroup(grpname
);
597 item
= group
->GetItem(s
, true);
598 ptr
= GetVariableAddress(sld
, object
);
600 if (item
->value
!= NULL
) {
601 /* check if the value is the same as the old value */
602 const void *p
= StringToVal(sdb
, item
->value
);
604 /* The main type of a variable/setting is in bytes 8-15
605 * The subtype (what kind of numbers do we have there) is in 0-7 */
611 assert(sld
->type
== SL_VAR
);
612 switch (GetVarMemType(sld
->conv
)) {
614 if (*(bool*)ptr
== (p
!= NULL
)) continue;
619 if (*(byte
*)ptr
== (byte
)(size_t)p
) continue;
624 if (*(uint16
*)ptr
== (uint16
)(size_t)p
) continue;
629 if (*(uint32
*)ptr
== (uint32
)(size_t)p
) continue;
632 default: NOT_REACHED();
636 default: break; // Assume the other types are always changed
640 /* Value has changed, get the new value and put it into a buffer */
645 case SDT_MANYOFMANY
: {
646 uint32 i
= (uint32
)ReadValue(ptr
, sld
->conv
);
649 case SDT_BOOLX
: strecpy(buf
, (i
!= 0) ? "true" : "false", lastof(buf
)); break;
650 case SDT_NUMX
: seprintf(buf
, lastof(buf
), IsSignedVarMemType(sld
->conv
) ? "%d" : "%u", i
); break;
651 case SDT_ONEOFMANY
: MakeOneOfMany(buf
, lastof(buf
), sdb
->many
, i
); break;
652 case SDT_MANYOFMANY
: MakeManyOfMany(buf
, lastof(buf
), sdb
->many
, i
); break;
653 default: NOT_REACHED();
659 if (sld
->type
!= SL_STR
) {
660 assert(sld
->type
== SL_VAR
);
661 assert(GetVarMemType(sld
->conv
) == SLE_VAR_CHAR
);
662 buf
[0] = *(char*)ptr
;
667 if (sld
->conv
& SLS_POINTER
) {
668 s
= *(const char *const *)ptr
;
670 s
= (const char *)ptr
;
673 if (sld
->conv
& SLS_QUOTED
) {
677 seprintf(buf
, lastof(buf
), "\"%s\"", s
);
680 strecpy(buf
, s
, lastof(buf
));
686 MakeIntList(buf
, lastof(buf
), ptr
, sld
->length
, GetVarMemType(sld
->conv
));
689 default: NOT_REACHED();
692 /* The value is different, that means we have to write it to the ini */
694 item
->value
= strdup(buf
);
699 * Loads all items from a 'grpname' section into a list
700 * The list parameter can be a NULL pointer, in this case nothing will be
701 * saved and a callback function should be defined that will take over the
702 * list-handling and store the data itself somewhere.
703 * @param ini IniFile handle to the ini file with the source data
704 * @param grpname character string identifying the section-header of the ini file that will be parsed
705 * @param list new list with entries of the given section
707 static void IniLoadSettingList(IniFile
*ini
, const char *grpname
, StringList
*list
)
709 IniGroup
*group
= ini
->GetGroup(grpname
);
711 if (group
== NULL
|| list
== NULL
) return;
715 for (const IniItem
*item
= group
->item
; item
!= NULL
; item
= item
->next
) {
716 if (item
->name
!= NULL
) *list
->Append() = strdup(item
->name
);
721 * Saves all items from a list into the 'grpname' section
722 * The list parameter can be a NULL pointer, in this case a callback function
723 * should be defined that will provide the source data to be saved.
724 * @param ini IniFile handle to the ini file where the destination data is saved
725 * @param grpname character string identifying the section-header of the ini file
726 * @param list pointer to an string(pointer) array that will be used as the
727 * source to be saved into the relevant ini section
729 static void IniSaveSettingList(IniFile
*ini
, const char *grpname
, StringList
*list
)
731 IniGroup
*group
= ini
->GetGroup(grpname
);
733 if (group
== NULL
|| list
== NULL
) return;
736 for (char **iter
= list
->Begin(); iter
!= list
->End(); iter
++) {
737 group
->GetItem(*iter
, true)->SetValue("");
742 * Load a WindowDesc from config.
743 * @param ini IniFile handle to the ini file with the source data
744 * @param grpname character string identifying the section-header of the ini file that will be parsed
745 * @param desc Destination WindowDesc
747 void IniLoadWindowSettings(IniFile
*ini
, const char *grpname
, void *desc
)
749 IniLoadSettings(ini
, _window_settings
, grpname
, desc
);
753 * Save a WindowDesc to config.
754 * @param ini IniFile handle to the ini file where the destination data is saved
755 * @param grpname character string identifying the section-header of the ini file
756 * @param desc Source WindowDesc
758 void IniSaveWindowSettings(IniFile
*ini
, const char *grpname
, void *desc
)
760 IniSaveSettings(ini
, _window_settings
, grpname
, desc
);
764 * Check whether the setting is editable in the current gamemode.
765 * @param do_command true if this is about checking a command from the server.
766 * @return true if editable.
768 bool SettingDesc::IsEditable(bool do_command
) const
770 if (!do_command
&& !(this->save
.flags
& SLF_NO_NETWORK_SYNC
) && _networking
&& !_network_server
&& !(this->desc
.flags
& SGF_PER_COMPANY
)) return false;
771 if ((this->desc
.flags
& SGF_NETWORK_ONLY
) && !_networking
&& _game_mode
!= GM_MENU
) return false;
772 if ((this->desc
.flags
& SGF_NO_NETWORK
) && _networking
) return false;
773 if ((this->desc
.flags
& SGF_NEWGAME_ONLY
) &&
774 (_game_mode
== GM_NORMAL
||
775 (_game_mode
== GM_EDITOR
&& !(this->desc
.flags
& SGF_SCENEDIT_TOO
)))) return false;
780 * Return the type of the setting.
781 * @return type of setting
783 SettingType
SettingDesc::GetType() const
785 if (this->desc
.flags
& SGF_PER_COMPANY
) return ST_COMPANY
;
786 return (this->save
.flags
& SLF_NOT_IN_SAVE
) ? ST_CLIENT
: ST_GAME
;
789 /* Begin - Callback Functions for the various settings. */
791 /** Reposition the main toolbar as the setting changed. */
792 static bool v_PositionMainToolbar(int32 p1
)
794 if (_game_mode
!= GM_MENU
) PositionMainToolbar(NULL
);
798 /** Reposition the statusbar as the setting changed. */
799 static bool v_PositionStatusbar(int32 p1
)
801 if (_game_mode
!= GM_MENU
) {
802 PositionStatusbar(NULL
);
803 PositionNewsMessage(NULL
);
804 PositionNetworkChatWindow(NULL
);
809 static bool PopulationInLabelActive(int32 p1
)
811 UpdateAllTownVirtCoords();
815 static bool RedrawScreen(int32 p1
)
817 MarkWholeScreenDirty();
822 * Redraw the smallmap after a colour scheme change.
823 * @param p1 Callback parameter.
824 * @return Always true.
826 static bool RedrawSmallmap(int32 p1
)
830 SetWindowClassesDirty(WC_SMALLMAP
);
834 static bool InvalidateDetailsWindow(int32 p1
)
836 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
840 static bool StationSpreadChanged(int32 p1
)
842 InvalidateWindowData(WC_SELECT_STATION
, 0);
843 InvalidateWindowData(WC_BUILD_STATION
, 0);
847 static bool InvalidateBuildIndustryWindow(int32 p1
)
849 InvalidateWindowData(WC_BUILD_INDUSTRY
, 0);
853 static bool CloseSignalGUI(int32 p1
)
856 DeleteWindowByClass(WC_BUILD_SIGNAL
);
861 static bool InvalidateTownViewWindow(int32 p1
)
863 InvalidateWindowClassesData(WC_TOWN_VIEW
, p1
);
867 static bool DeleteSelectStationWindow(int32 p1
)
869 DeleteWindowById(WC_SELECT_STATION
, 0);
873 static bool UpdateConsists(int32 p1
)
877 /* Update the consist of all trains so the maximum speed is set correctly. */
878 if (t
->IsFrontEngine() || t
->IsFreeWagon()) t
->ConsistChanged(true);
880 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
884 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
885 static bool CheckInterval(int32 p1
)
887 bool update_vehicles
;
888 VehicleDefaultSettings
*vds
;
889 if (_game_mode
== GM_MENU
|| !Company::IsValidID(_current_company
)) {
890 vds
= &_settings_client
.company
.vehicle
;
891 update_vehicles
= false;
893 vds
= &Company::Get(_current_company
)->settings
.vehicle
;
894 update_vehicles
= true;
898 vds
->servint_trains
= 50;
899 vds
->servint_roadveh
= 50;
900 vds
->servint_aircraft
= 50;
901 vds
->servint_ships
= 50;
903 vds
->servint_trains
= 150;
904 vds
->servint_roadveh
= 150;
905 vds
->servint_aircraft
= 100;
906 vds
->servint_ships
= 360;
909 if (update_vehicles
) {
910 const Company
*c
= Company::Get(_current_company
);
912 FOR_ALL_VEHICLES(v
) {
913 if (v
->owner
== _current_company
&& v
->IsPrimaryVehicle() && !v
->ServiceIntervalIsCustom()) {
914 v
->SetServiceInterval(CompanyServiceInterval(c
, v
->type
));
915 v
->SetServiceIntervalIsPercent(p1
!= 0);
920 InvalidateDetailsWindow(0);
925 static bool UpdateInterval(VehicleType type
, int32 p1
)
927 bool update_vehicles
;
928 VehicleDefaultSettings
*vds
;
929 if (_game_mode
== GM_MENU
|| !Company::IsValidID(_current_company
)) {
930 vds
= &_settings_client
.company
.vehicle
;
931 update_vehicles
= false;
933 vds
= &Company::Get(_current_company
)->settings
.vehicle
;
934 update_vehicles
= true;
937 /* Test if the interval is valid */
938 uint16 interval
= GetServiceIntervalClamped(p1
, vds
->servint_ispercent
);
939 if (interval
!= p1
) return false;
941 if (update_vehicles
) {
943 FOR_ALL_VEHICLES(v
) {
944 if (v
->owner
== _current_company
&& v
->type
== type
&& v
->IsPrimaryVehicle() && !v
->ServiceIntervalIsCustom()) {
945 v
->SetServiceInterval(p1
);
950 InvalidateDetailsWindow(0);
955 static bool UpdateIntervalTrains(int32 p1
)
957 return UpdateInterval(VEH_TRAIN
, p1
);
960 static bool UpdateIntervalRoadVeh(int32 p1
)
962 return UpdateInterval(VEH_ROAD
, p1
);
965 static bool UpdateIntervalShips(int32 p1
)
967 return UpdateInterval(VEH_SHIP
, p1
);
970 static bool UpdateIntervalAircraft(int32 p1
)
972 return UpdateInterval(VEH_AIRCRAFT
, p1
);
975 static bool TrainAccelerationModelChanged(int32 p1
)
979 if (t
->IsFrontEngine()) {
980 t
->tcache
.cached_max_curve_speed
= t
->GetCurveSpeedLimit();
981 t
->UpdateAcceleration();
985 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
986 SetWindowClassesDirty(WC_ENGINE_PREVIEW
);
987 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
988 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
994 * This function updates the train acceleration cache after a steepness change.
995 * @param p1 Callback parameter.
996 * @return Always true.
998 static bool TrainSlopeSteepnessChanged(int32 p1
)
1002 if (t
->IsFrontEngine()) t
->CargoChanged();
1009 * This function updates realistic acceleration caches when the setting "Road vehicle acceleration model" is set.
1010 * @param p1 Callback parameter
1011 * @return Always true
1013 static bool RoadVehAccelerationModelChanged(int32 p1
)
1015 if (_settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) {
1017 FOR_ALL_ROADVEHICLES(rv
) {
1018 if (rv
->IsFrontEngine()) {
1024 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1025 SetWindowClassesDirty(WC_ENGINE_PREVIEW
);
1026 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
1027 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
1033 * This function updates the road vehicle acceleration cache after a steepness change.
1034 * @param p1 Callback parameter.
1035 * @return Always true.
1037 static bool RoadVehSlopeSteepnessChanged(int32 p1
)
1040 FOR_ALL_ROADVEHICLES(rv
) {
1041 if (rv
->IsFrontEngine()) rv
->CargoChanged();
1047 static bool DragSignalsDensityChanged(int32
)
1049 InvalidateWindowData(WC_BUILD_SIGNAL
, 0);
1054 static bool TownFoundingChanged(int32 p1
)
1056 if (_game_mode
!= GM_EDITOR
&& _settings_game
.economy
.found_town
== TF_FORBIDDEN
) {
1057 DeleteWindowById(WC_FOUND_TOWN
, 0);
1060 InvalidateWindowData(WC_FOUND_TOWN
, 0);
1064 static bool InvalidateVehTimetableWindow(int32 p1
)
1066 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE
, VIWD_MODIFY_ORDERS
);
1070 static bool ZoomMinMaxChanged(int32 p1
)
1072 extern void ConstrainAllViewportsZoom();
1073 ConstrainAllViewportsZoom();
1074 GfxClearSpriteCache();
1079 * Update any possible saveload window and delete any newgrf dialogue as
1080 * its widget parts might change. Reinit all windows as it allows access to the
1081 * newgrf debug button.
1083 * @return Always true.
1085 static bool InvalidateNewGRFChangeWindows(int32 p1
)
1087 InvalidateWindowClassesData(WC_SAVELOAD
);
1088 DeleteWindowByClass(WC_GAME_OPTIONS
);
1093 static bool InvalidateCompanyLiveryWindow(int32 p1
)
1095 InvalidateWindowClassesData(WC_COMPANY_COLOUR
);
1096 return RedrawScreen(p1
);
1099 static bool InvalidateIndustryViewWindow(int32 p1
)
1101 InvalidateWindowClassesData(WC_INDUSTRY_VIEW
);
1105 static bool InvalidateAISettingsWindow(int32 p1
)
1107 InvalidateWindowClassesData(WC_AI_SETTINGS
);
1112 * Update the town authority window after a town authority setting change.
1114 * @return Always true.
1116 static bool RedrawTownAuthority(int32 p1
)
1118 SetWindowClassesDirty(WC_TOWN_AUTHORITY
);
1123 * Invalidate the company infrastructure details window after a infrastructure maintenance setting change.
1125 * @return Always true.
1127 static bool InvalidateCompanyInfrastructureWindow(int32 p1
)
1129 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE
);
1134 * Invalidate the company details window after the shares setting changed.
1136 * @return Always true.
1138 static bool InvalidateCompanyWindow(int32 p1
)
1140 InvalidateWindowClassesData(WC_COMPANY
);
1144 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
1145 static void ValidateSettings()
1147 /* Do not allow a custom sea level with the original land generator. */
1148 if (_settings_newgame
.game_creation
.land_generator
== 0 &&
1149 _settings_newgame
.difficulty
.quantity_sea_lakes
== CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
) {
1150 _settings_newgame
.difficulty
.quantity_sea_lakes
= CUSTOM_SEA_LEVEL_MIN_PERCENTAGE
;
1154 static bool DifficultyNoiseChange(int32 i
)
1156 if (_game_mode
== GM_NORMAL
) {
1157 UpdateAirportsNoise();
1158 if (_settings_game
.economy
.station_noise_level
) {
1159 InvalidateWindowClassesData(WC_TOWN_VIEW
, 0);
1166 static bool MaxNoAIsChange(int32 i
)
1168 if (GetGameSettings().difficulty
.max_no_competitors
!= 0 &&
1169 AI::GetInfoList()->size() == 0 &&
1170 (!_networking
|| _network_server
)) {
1171 ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI
, INVALID_STRING_ID
, WL_CRITICAL
);
1178 * Check whether the road side may be changed.
1180 * @return true if the road side may be changed.
1182 static bool CheckRoadSide(int p1
)
1184 extern bool RoadVehiclesAreBuilt();
1185 return _game_mode
== GM_MENU
|| !RoadVehiclesAreBuilt();
1189 * Conversion callback for _gameopt_settings_game.landscape
1190 * It converts (or try) between old values and the new ones,
1191 * without losing initial setting of the user
1192 * @param value that was read from config file
1193 * @return the "hopefully" converted value
1195 static size_t ConvertLandscape(const char *value
)
1197 /* try with the old values */
1198 return LookupOneOfMany("normal|hilly|desert|candy", value
);
1201 static bool CheckFreeformEdges(int32 p1
)
1203 if (_game_mode
== GM_MENU
) return true;
1207 /* Check if there is a ship on the northern border. */
1208 if (TileX(s
->tile
) == 0 || TileY(s
->tile
) == 0) {
1209 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY
, INVALID_STRING_ID
, WL_ERROR
);
1214 FOR_ALL_BASE_STATIONS(st
) {
1215 /* Check if there is a non-deleted buoy on the northern border. */
1216 if (st
->IsInUse() && (TileX(st
->xy
) == 0 || TileY(st
->xy
) == 0)) {
1217 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY
, INVALID_STRING_ID
, WL_ERROR
);
1221 for (uint i
= 0; i
< MapSizeX(); i
++) MakeVoid(TileXY(i
, 0));
1222 for (uint i
= 0; i
< MapSizeY(); i
++) MakeVoid(TileXY(0, i
));
1224 for (uint i
= 0; i
< MapMaxX(); i
++) {
1225 if (TileHeight(TileXY(i
, 1)) != 0) {
1226 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1230 for (uint i
= 1; i
< MapMaxX(); i
++) {
1231 if (!IsWaterTile(TileXY(i
, MapMaxY() - 1)) || TileHeight(TileXY(1, MapMaxY())) != 0) {
1232 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1236 for (uint i
= 0; i
< MapMaxY(); i
++) {
1237 if (TileHeight(TileXY(1, i
)) != 0) {
1238 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1242 for (uint i
= 1; i
< MapMaxY(); i
++) {
1243 if (!IsWaterTile(TileXY(MapMaxX() - 1, i
)) || TileHeight(TileXY(MapMaxX(), i
)) != 0) {
1244 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1248 /* Make tiles at the border water again. */
1249 for (uint i
= 0; i
< MapMaxX(); i
++) {
1250 SetTileHeight(TileXY(i
, 0), 0);
1251 MakeSea(TileXY(i
, 0));
1253 for (uint i
= 0; i
< MapMaxY(); i
++) {
1254 SetTileHeight(TileXY(0, i
), 0);
1255 MakeSea(TileXY(0, i
));
1258 MarkWholeScreenDirty();
1263 * Changing the setting "allow multiple NewGRF sets" is not allowed
1264 * if there are vehicles.
1266 static bool ChangeDynamicEngines(int32 p1
)
1268 if (_game_mode
== GM_MENU
) return true;
1270 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
1271 ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES
, INVALID_STRING_ID
, WL_ERROR
);
1278 static bool StationCatchmentChanged(int32 p1
)
1280 Station::RecomputeIndustriesNearForAll();
1285 #ifdef ENABLE_NETWORK
1287 static bool UpdateClientName(int32 p1
)
1289 NetworkUpdateClientName();
1293 static bool UpdateServerPassword(int32 p1
)
1295 if (strcmp(_settings_client
.network
.server_password
, "*") == 0) {
1296 _settings_client
.network
.server_password
[0] = '\0';
1302 static bool UpdateRconPassword(int32 p1
)
1304 if (strcmp(_settings_client
.network
.rcon_password
, "*") == 0) {
1305 _settings_client
.network
.rcon_password
[0] = '\0';
1311 static bool UpdateClientConfigValues(int32 p1
)
1313 if (_network_server
) NetworkServerSendConfigUpdate();
1318 #endif /* ENABLE_NETWORK */
1321 /* End - Callback Functions */
1324 * Prepare for reading and old diff_custom by zero-ing the memory.
1326 static void PrepareOldDiffCustom()
1328 memset(_old_diff_custom
, 0, sizeof(_old_diff_custom
));
1332 * Reading of the old diff_custom array and transforming it to the new format.
1333 * @param stv Savegame type and version; or NULL if reading from config.
1334 * In the former case we are sure there is an array;
1335 * in the latter case we have to check that.
1337 static void HandleOldDiffCustom(const SavegameTypeVersion
*stv
)
1339 uint options_to_load
= GAME_DIFFICULTY_NUM
- ((stv
!= NULL
&& IsOTTDSavegameVersionBefore(stv
, 4)) ? 1 : 0);
1342 /* If we did read to old_diff_custom, then at least one value must be non 0. */
1343 bool old_diff_custom_used
= false;
1344 for (uint i
= 0; i
< options_to_load
&& !old_diff_custom_used
; i
++) {
1345 old_diff_custom_used
= (_old_diff_custom
[i
] != 0);
1348 if (!old_diff_custom_used
) return;
1351 for (uint i
= 0; i
< options_to_load
; i
++) {
1352 const SettingDesc
*sd
= &_settings
[i
];
1353 /* Skip deprecated options */
1354 if (!SlIsObjectCurrentlyValid(&sd
->save
)) continue;
1355 void *var
= GetVariableAddress(&sd
->save
, stv
!= NULL
? &_settings_game
: &_settings_newgame
);
1356 Write_ValidateSetting(var
, sd
, (int32
)((i
== 4 ? 1000 : 1) * _old_diff_custom
[i
]));
1360 static void AILoadConfig(IniFile
*ini
, const char *grpname
)
1362 IniGroup
*group
= ini
->GetGroup(grpname
);
1365 /* Clean any configured AI */
1366 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1367 AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
)->Change(NULL
);
1370 /* If no group exists, return */
1371 if (group
== NULL
) return;
1373 CompanyID c
= COMPANY_FIRST
;
1374 for (item
= group
->item
; c
< MAX_COMPANIES
&& item
!= NULL
; c
++, item
= item
->next
) {
1375 AIConfig
*config
= AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
);
1377 config
->Change(item
->name
);
1378 if (!config
->HasScript()) {
1379 if (strcmp(item
->name
, "none") != 0) {
1380 DEBUG(script
, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item
->name
);
1384 if (item
->value
!= NULL
) config
->StringToSettings(item
->value
);
1388 static void GameLoadConfig(IniFile
*ini
, const char *grpname
)
1390 IniGroup
*group
= ini
->GetGroup(grpname
);
1393 /* Clean any configured GameScript */
1394 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME
)->Change(NULL
);
1396 /* If no group exists, return */
1397 if (group
== NULL
) return;
1400 if (item
== NULL
) return;
1402 GameConfig
*config
= GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME
);
1404 config
->Change(item
->name
);
1405 if (!config
->HasScript()) {
1406 if (strcmp(item
->name
, "none") != 0) {
1407 DEBUG(script
, 0, "The GameScript by the name '%s' was no longer found, and removed from the list.", item
->name
);
1411 if (item
->value
!= NULL
) config
->StringToSettings(item
->value
);
1415 * Load a GRF configuration
1416 * @param ini The configuration to read from.
1417 * @param grpname Group name containing the configuration of the GRF.
1418 * @param is_static GRF is static.
1420 static GRFConfig
*GRFLoadConfig(IniFile
*ini
, const char *grpname
, bool is_static
)
1422 IniGroup
*group
= ini
->GetGroup(grpname
);
1424 GRFConfig
*first
= NULL
;
1425 GRFConfig
**curr
= &first
;
1427 if (group
== NULL
) return NULL
;
1429 for (item
= group
->item
; item
!= NULL
; item
= item
->next
) {
1430 GRFConfig
*c
= new GRFConfig(item
->name
);
1432 /* Parse parameters */
1433 if (!StrEmpty(item
->value
)) {
1434 c
->num_params
= ParseIntList(item
->value
, (int*)c
->param
, lengthof(c
->param
));
1435 if (c
->num_params
== (byte
)-1) {
1436 SetDParamStr(0, item
->name
);
1437 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_ARRAY
, WL_CRITICAL
);
1442 /* Check if item is valid */
1443 if (!FillGRFDetails(c
, is_static
) || HasBit(c
->flags
, GCF_INVALID
)) {
1444 if (c
->status
== GCS_NOT_FOUND
) {
1445 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND
);
1446 } else if (HasBit(c
->flags
, GCF_UNSAFE
)) {
1447 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE
);
1448 } else if (HasBit(c
->flags
, GCF_SYSTEM
)) {
1449 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM
);
1450 } else if (HasBit(c
->flags
, GCF_INVALID
)) {
1451 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE
);
1453 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN
);
1456 SetDParamStr(0, item
->name
);
1457 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_GRF
, WL_CRITICAL
);
1462 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1463 bool duplicate
= false;
1464 for (const GRFConfig
*gc
= first
; gc
!= NULL
; gc
= gc
->next
) {
1465 if (gc
->ident
.grfid
== c
->ident
.grfid
) {
1466 SetDParamStr(0, item
->name
);
1467 SetDParamStr(1, gc
->filename
);
1468 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_DUPLICATE_GRFID
, WL_CRITICAL
);
1478 /* Mark file as static to avoid saving in savegame. */
1479 if (is_static
) SetBit(c
->flags
, GCF_STATIC
);
1481 /* Add item to list */
1489 static void AISaveConfig(IniFile
*ini
, const char *grpname
)
1491 IniGroup
*group
= ini
->GetGroup(grpname
);
1493 if (group
== NULL
) return;
1496 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1497 AIConfig
*config
= AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
);
1500 config
->SettingsToString(value
, lengthof(value
));
1502 if (config
->HasScript()) {
1503 name
= config
->GetName();
1508 IniItem
*item
= new IniItem(group
, name
, strlen(name
));
1509 item
->SetValue(value
);
1513 static void GameSaveConfig(IniFile
*ini
, const char *grpname
)
1515 IniGroup
*group
= ini
->GetGroup(grpname
);
1517 if (group
== NULL
) return;
1520 GameConfig
*config
= GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME
);
1523 config
->SettingsToString(value
, lengthof(value
));
1525 if (config
->HasScript()) {
1526 name
= config
->GetName();
1531 IniItem
*item
= new IniItem(group
, name
, strlen(name
));
1532 item
->SetValue(value
);
1536 * Save the version of OpenTTD to the ini file.
1537 * @param ini the ini to write to
1539 static void SaveVersionInConfig(IniFile
*ini
)
1541 IniGroup
*group
= ini
->GetGroup("version");
1544 snprintf(version
, lengthof(version
), "%08X", _openttd_newgrf_version
);
1546 const char * const versions
[][2] = {
1547 { "version_string", _openttd_revision
},
1548 { "version_number", version
}
1551 for (uint i
= 0; i
< lengthof(versions
); i
++) {
1552 group
->GetItem(versions
[i
][0], true)->SetValue(versions
[i
][1]);
1556 /* Save a GRF configuration to the given group name */
1557 static void GRFSaveConfig(IniFile
*ini
, const char *grpname
, const GRFConfig
*list
)
1559 ini
->RemoveGroup(grpname
);
1560 IniGroup
*group
= ini
->GetGroup(grpname
);
1563 for (c
= list
; c
!= NULL
; c
= c
->next
) {
1565 GRFBuildParamList(params
, c
, lastof(params
));
1567 group
->GetItem(c
->filename
, true)->SetValue(params
);
1571 /* Common handler for saving/loading variables to the configuration file */
1572 static void HandleSettingDescs(IniFile
*ini
, SettingDescProc
*proc
, SettingDescProcList
*proc_list
, bool basic_settings
= true, bool other_settings
= true)
1574 if (basic_settings
) {
1575 proc(ini
, (const SettingDesc
*)_misc_settings
, "misc", NULL
);
1576 #if defined(WIN32) && !defined(DEDICATED)
1577 proc(ini
, (const SettingDesc
*)_win32_settings
, "win32", NULL
);
1581 if (other_settings
) {
1582 proc(ini
, _settings
, "patches", &_settings_newgame
);
1583 proc(ini
, _currency_settings
,"currency", &_custom_currency
);
1584 proc(ini
, _company_settings
, "company", &_settings_client
.company
);
1586 #ifdef ENABLE_NETWORK
1587 proc_list(ini
, "server_bind_addresses", &_network_bind_list
);
1588 proc_list(ini
, "servers", &_network_host_list
);
1589 proc_list(ini
, "bans", &_network_ban_list
);
1590 #endif /* ENABLE_NETWORK */
1594 static IniFile
*IniLoadConfig()
1596 IniFile
*ini
= new IniFile(_list_group_names
);
1597 ini
->LoadFromDisk(_config_file
, BASE_DIR
);
1602 * Load the values from the configuration files
1603 * @param minimal Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1605 void LoadFromConfig(bool minimal
)
1607 IniFile
*ini
= IniLoadConfig();
1608 if (!minimal
) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1610 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1611 HandleSettingDescs(ini
, IniLoadSettings
, IniLoadSettingList
, minimal
, !minimal
);
1614 _grfconfig_newgame
= GRFLoadConfig(ini
, "newgrf", false);
1615 _grfconfig_static
= GRFLoadConfig(ini
, "newgrf-static", true);
1616 AILoadConfig(ini
, "ai_players");
1617 GameLoadConfig(ini
, "game_scripts");
1619 PrepareOldDiffCustom();
1620 IniLoadSettings(ini
, _gameopt_settings
, "gameopt", &_settings_newgame
);
1621 HandleOldDiffCustom(NULL
);
1625 /* Display sheduled errors */
1626 extern void ScheduleErrorMessage(ErrorList
&datas
);
1627 ScheduleErrorMessage(_settings_error_list
);
1628 if (FindWindowById(WC_ERRMSG
, 0) == NULL
) ShowFirstError();
1634 /** Save the values to the configuration file */
1637 IniFile
*ini
= IniLoadConfig();
1639 /* Remove some obsolete groups. These have all been loaded into other groups. */
1640 ini
->RemoveGroup("patches");
1641 ini
->RemoveGroup("yapf");
1642 ini
->RemoveGroup("gameopt");
1644 HandleSettingDescs(ini
, IniSaveSettings
, IniSaveSettingList
);
1645 GRFSaveConfig(ini
, "newgrf", _grfconfig_newgame
);
1646 GRFSaveConfig(ini
, "newgrf-static", _grfconfig_static
);
1647 AISaveConfig(ini
, "ai_players");
1648 GameSaveConfig(ini
, "game_scripts");
1649 SaveVersionInConfig(ini
);
1650 ini
->SaveToDisk(_config_file
);
1655 * Get the list of known NewGrf presets.
1656 * @param list[inout] Pointer to list for storing the preset names.
1658 void GetGRFPresetList(GRFPresetList
*list
)
1662 IniFile
*ini
= IniLoadConfig();
1664 for (group
= ini
->group
; group
!= NULL
; group
= group
->next
) {
1665 if (strncmp(group
->name
, "preset-", 7) == 0) {
1666 *list
->Append() = strdup(group
->name
+ 7);
1674 * Load a NewGRF configuration by preset-name.
1675 * @param config_name Name of the preset.
1676 * @return NewGRF configuration.
1677 * @see GetGRFPresetList
1679 GRFConfig
*LoadGRFPresetFromConfig(const char *config_name
)
1681 char *section
= (char*)alloca(strlen(config_name
) + 8);
1682 sprintf(section
, "preset-%s", config_name
);
1684 IniFile
*ini
= IniLoadConfig();
1685 GRFConfig
*config
= GRFLoadConfig(ini
, section
, false);
1692 * Save a NewGRF configuration with a preset name.
1693 * @param config_name Name of the preset.
1694 * @param config NewGRF configuration to save.
1695 * @see GetGRFPresetList
1697 void SaveGRFPresetToConfig(const char *config_name
, GRFConfig
*config
)
1699 char *section
= (char*)alloca(strlen(config_name
) + 8);
1700 sprintf(section
, "preset-%s", config_name
);
1702 IniFile
*ini
= IniLoadConfig();
1703 GRFSaveConfig(ini
, section
, config
);
1704 ini
->SaveToDisk(_config_file
);
1709 * Delete a NewGRF configuration by preset name.
1710 * @param config_name Name of the preset.
1712 void DeleteGRFPresetFromConfig(const char *config_name
)
1714 char *section
= (char*)alloca(strlen(config_name
) + 8);
1715 sprintf(section
, "preset-%s", config_name
);
1717 IniFile
*ini
= IniLoadConfig();
1718 ini
->RemoveGroup(section
);
1719 ini
->SaveToDisk(_config_file
);
1723 const SettingDesc
*GetSettingDescription(uint index
)
1725 if (index
>= lengthof(_settings
)) return NULL
;
1726 return &_settings
[index
];
1730 * Network-safe changing of settings (server-only).
1731 * @param tile unused
1732 * @param flags operation to perform
1733 * @param p1 the index of the setting in the SettingDesc array which identifies it
1734 * @param p2 the new value for the setting
1735 * The new value is properly clamped to its minimum/maximum when setting
1736 * @param text unused
1737 * @return the cost of this operation or an error
1740 CommandCost
CmdChangeSetting(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1742 const SettingDesc
*sd
= GetSettingDescription(p1
);
1744 if (sd
== NULL
) return CMD_ERROR
;
1745 if (!SlIsObjectCurrentlyValid(&sd
->save
)) return CMD_ERROR
;
1747 if (!sd
->IsEditable(true)) return CMD_ERROR
;
1749 if (flags
& DC_EXEC
) {
1750 void *var
= GetVariableAddress(&sd
->save
, &GetGameSettings());
1752 int32 oldval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1753 int32 newval
= (int32
)p2
;
1755 Write_ValidateSetting(var
, sd
, newval
);
1756 newval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1758 if (oldval
== newval
) return CommandCost();
1760 if (sd
->desc
.proc
!= NULL
&& !sd
->desc
.proc(newval
)) {
1761 WriteValue(var
, sd
->save
.conv
, (int64
)oldval
);
1762 return CommandCost();
1765 if (sd
->desc
.flags
& SGF_NO_NETWORK
) {
1766 GamelogSetting(sd
->desc
.name
, oldval
, newval
);
1769 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1772 return CommandCost();
1776 * Change one of the per-company settings.
1777 * @param tile unused
1778 * @param flags operation to perform
1779 * @param p1 the index of the setting in the _company_settings array which identifies it
1780 * @param p2 the new value for the setting
1781 * The new value is properly clamped to its minimum/maximum when setting
1782 * @param text unused
1783 * @return the cost of this operation or an error
1785 CommandCost
CmdChangeCompanySetting(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1787 if (p1
>= lengthof(_company_settings
)) return CMD_ERROR
;
1788 const SettingDesc
*sd
= &_company_settings
[p1
];
1790 if (flags
& DC_EXEC
) {
1791 void *var
= GetVariableAddress(&sd
->save
, &Company::Get(_current_company
)->settings
);
1793 int32 oldval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1794 int32 newval
= (int32
)p2
;
1796 Write_ValidateSetting(var
, sd
, newval
);
1797 newval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1799 if (oldval
== newval
) return CommandCost();
1801 if (sd
->desc
.proc
!= NULL
&& !sd
->desc
.proc(newval
)) {
1802 WriteValue(var
, sd
->save
.conv
, (int64
)oldval
);
1803 return CommandCost();
1806 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1809 return CommandCost();
1813 * Top function to save the new value of an element of the Settings struct
1814 * @param index offset in the SettingDesc array of the Settings struct which
1815 * identifies the setting member we want to change
1816 * @param value new value of the setting
1817 * @param force_newgame force the newgame settings
1819 bool SetSettingValue(uint index
, int32 value
, bool force_newgame
)
1821 const SettingDesc
*sd
= &_settings
[index
];
1822 /* If an item is company-based, we do not send it over the network
1823 * (if any) to change. Also *hack*hack* we update the _newgame version
1824 * of settings because changing a company-based setting in a game also
1825 * changes its defaults. At least that is the convention we have chosen */
1826 if (sd
->save
.flags
& SLF_NO_NETWORK_SYNC
) {
1827 void *var
= GetVariableAddress(&sd
->save
, &GetGameSettings());
1828 Write_ValidateSetting(var
, sd
, value
);
1830 if (_game_mode
!= GM_MENU
) {
1831 void *var2
= GetVariableAddress(&sd
->save
, &_settings_newgame
);
1832 Write_ValidateSetting(var2
, sd
, value
);
1834 if (sd
->desc
.proc
!= NULL
) sd
->desc
.proc((int32
)ReadValue(var
, sd
->save
.conv
));
1836 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1841 if (force_newgame
) {
1842 void *var2
= GetVariableAddress(&sd
->save
, &_settings_newgame
);
1843 Write_ValidateSetting(var2
, sd
, value
);
1847 /* send non-company-based settings over the network */
1848 if (!_networking
|| (_networking
&& _network_server
)) {
1849 return DoCommandP(0, index
, value
, CMD_CHANGE_SETTING
);
1855 * Top function to save the new value of an element of the Settings struct
1856 * @param index offset in the SettingDesc array of the CompanySettings struct
1857 * which identifies the setting member we want to change
1858 * @param value new value of the setting
1860 void SetCompanySetting(uint index
, int32 value
)
1862 const SettingDesc
*sd
= &_company_settings
[index
];
1863 if (Company::IsValidID(_local_company
) && _game_mode
!= GM_MENU
) {
1864 DoCommandP(0, index
, value
, CMD_CHANGE_COMPANY_SETTING
);
1866 void *var
= GetVariableAddress(&sd
->save
, &_settings_client
.company
);
1867 Write_ValidateSetting(var
, sd
, value
);
1868 if (sd
->desc
.proc
!= NULL
) sd
->desc
.proc((int32
)ReadValue(var
, sd
->save
.conv
));
1873 * Set the company settings for a new company to their default values.
1875 void SetDefaultCompanySettings(CompanyID cid
)
1877 Company
*c
= Company::Get(cid
);
1878 const SettingDesc
*sd
;
1879 for (sd
= _company_settings
; sd
->save
.type
!= SL_END
; sd
++) {
1880 void *var
= GetVariableAddress(&sd
->save
, &c
->settings
);
1881 Write_ValidateSetting(var
, sd
, (int32
)(size_t)sd
->desc
.def
);
1885 #if defined(ENABLE_NETWORK)
1887 * Sync all company settings in a multiplayer game.
1889 void SyncCompanySettings()
1891 const SettingDesc
*sd
;
1893 for (sd
= _company_settings
; sd
->save
.type
!= SL_END
; sd
++, i
++) {
1894 const void *old_var
= GetVariableAddress(&sd
->save
, &Company::Get(_current_company
)->settings
);
1895 const void *new_var
= GetVariableAddress(&sd
->save
, &_settings_client
.company
);
1896 uint32 old_value
= (uint32
)ReadValue(old_var
, sd
->save
.conv
);
1897 uint32 new_value
= (uint32
)ReadValue(new_var
, sd
->save
.conv
);
1898 if (old_value
!= new_value
) NetworkSendCommand(0, i
, new_value
, CMD_CHANGE_COMPANY_SETTING
, NULL
, NULL
, _local_company
);
1901 #endif /* ENABLE_NETWORK */
1904 * Get the index in the _company_settings array of a setting
1905 * @param name The name of the setting
1906 * @return The index in the _company_settings array
1908 uint
GetCompanySettingIndex(const char *name
)
1911 const SettingDesc
*sd
= GetSettingFromName(name
, &i
);
1912 assert(sd
!= NULL
&& (sd
->desc
.flags
& SGF_PER_COMPANY
) != 0);
1917 * Set a setting value with a string.
1918 * @param index the settings index.
1919 * @param value the value to write
1920 * @param force_newgame force the newgame settings
1921 * @note Strings WILL NOT be synced over the network
1923 bool SetSettingValue(uint index
, const char *value
, bool force_newgame
)
1925 const SettingDesc
*sd
= &_settings
[index
];
1926 assert(sd
->save
.flags
& SLF_NO_NETWORK_SYNC
);
1928 if ((sd
->save
.type
== SL_STR
) && (sd
->save
.conv
& SLS_POINTER
)) {
1929 char **var
= (char**)GetVariableAddress(&sd
->save
, (_game_mode
== GM_MENU
|| force_newgame
) ? &_settings_newgame
: &_settings_game
);
1931 *var
= strcmp(value
, "(null)") == 0 ? NULL
: strdup(value
);
1933 char *var
= (char*)GetVariableAddress(&sd
->save
);
1934 ttd_strlcpy(var
, value
, sd
->save
.length
);
1936 if (sd
->desc
.proc
!= NULL
) sd
->desc
.proc(0);
1942 * Given a name of setting, return a setting description of it.
1943 * @param name Name of the setting to return a setting description of
1944 * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
1945 * @return Pointer to the setting description of setting \a name if it can be found,
1946 * \c NULL indicates failure to obtain the description
1948 const SettingDesc
*GetSettingFromName(const char *name
, uint
*i
)
1950 const SettingDesc
*sd
;
1952 /* First check all full names */
1953 for (*i
= 0, sd
= _settings
; sd
->save
.type
!= SL_END
; sd
++, (*i
)++) {
1954 if (!SlIsObjectCurrentlyValid(&sd
->save
)) continue;
1955 if (strcmp(sd
->desc
.name
, name
) == 0) return sd
;
1958 /* Then check the shortcut variant of the name. */
1959 for (*i
= 0, sd
= _settings
; sd
->save
.type
!= SL_END
; sd
++, (*i
)++) {
1960 if (!SlIsObjectCurrentlyValid(&sd
->save
)) continue;
1961 const char *short_name
= strchr(sd
->desc
.name
, '.');
1962 if (short_name
!= NULL
) {
1964 if (strcmp(short_name
, name
) == 0) return sd
;
1968 if (strncmp(name
, "company.", 8) == 0) name
+= 8;
1969 /* And finally the company-based settings */
1970 for (*i
= 0, sd
= _company_settings
; sd
->save
.type
!= SL_END
; sd
++, (*i
)++) {
1971 if (!SlIsObjectCurrentlyValid(&sd
->save
)) continue;
1972 if (strcmp(sd
->desc
.name
, name
) == 0) return sd
;
1978 /* Those 2 functions need to be here, else we have to make some stuff non-static
1979 * and besides, it is also better to keep stuff like this at the same place */
1980 void IConsoleSetSetting(const char *name
, const char *value
, bool force_newgame
)
1983 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
1986 IConsolePrintF(CC_WARNING
, "'%s' is an unknown setting.", name
);
1991 if (sd
->desc
.cmd
== SDT_STRING
) {
1992 success
= SetSettingValue(index
, value
, force_newgame
);
1995 extern bool GetArgumentInteger(uint32
*value
, const char *arg
);
1996 success
= GetArgumentInteger(&val
, value
);
1998 IConsolePrintF(CC_ERROR
, "'%s' is not an integer.", value
);
2002 success
= SetSettingValue(index
, val
, force_newgame
);
2006 if (_network_server
) {
2007 IConsoleError("This command/variable is not available during network games.");
2009 IConsoleError("This command/variable is only available to a network server.");
2014 void IConsoleSetSetting(const char *name
, int value
)
2017 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2019 SetSettingValue(index
, value
);
2023 * Output value of a specific setting to the console
2024 * @param name Name of the setting to output its value
2025 * @param force_newgame force the newgame settings
2027 void IConsoleGetSetting(const char *name
, bool force_newgame
)
2031 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2035 IConsolePrintF(CC_WARNING
, "'%s' is an unknown setting.", name
);
2039 ptr
= GetVariableAddress(&sd
->save
, (_game_mode
== GM_MENU
|| force_newgame
) ? &_settings_newgame
: &_settings_game
);
2041 if (sd
->desc
.cmd
== SDT_STRING
) {
2042 IConsolePrintF(CC_WARNING
, "Current value for '%s' is: '%s'", name
, (sd
->save
.conv
& SLS_POINTER
) ? *(const char * const *)ptr
: (const char *)ptr
);
2044 if (sd
->desc
.cmd
== SDT_BOOLX
) {
2045 snprintf(value
, sizeof(value
), (*(const bool*)ptr
!= 0) ? "on" : "off");
2047 snprintf(value
, sizeof(value
), sd
->desc
.min
< 0 ? "%d" : "%u", (int32
)ReadValue(ptr
, sd
->save
.conv
));
2050 IConsolePrintF(CC_WARNING
, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
2051 name
, value
, (sd
->desc
.flags
& SGF_0ISDISABLED
) ? "(0) " : "", sd
->desc
.min
, sd
->desc
.max
);
2056 * List all settings and their value to the console
2058 * @param prefilter If not \c NULL, only list settings with names that begin with \a prefilter prefix
2060 void IConsoleListSettings(const char *prefilter
)
2062 IConsolePrintF(CC_WARNING
, "All settings with their current value:");
2064 for (const SettingDesc
*sd
= _settings
; sd
->save
.type
!= SL_END
; sd
++) {
2065 if (!SlIsObjectCurrentlyValid(&sd
->save
)) continue;
2066 if (prefilter
!= NULL
&& strstr(sd
->desc
.name
, prefilter
) == NULL
) continue;
2068 const void *ptr
= GetVariableAddress(&sd
->save
, &GetGameSettings());
2070 if (sd
->desc
.cmd
== SDT_BOOLX
) {
2071 snprintf(value
, lengthof(value
), (*(const bool *)ptr
!= 0) ? "on" : "off");
2072 } else if (sd
->desc
.cmd
== SDT_STRING
) {
2073 snprintf(value
, sizeof(value
), "%s", (sd
->save
.conv
& SLS_POINTER
) ? *(const char * const *)ptr
: (const char *)ptr
);
2075 snprintf(value
, lengthof(value
), sd
->desc
.min
< 0 ? "%d" : "%u", (int32
)ReadValue(ptr
, sd
->save
.conv
));
2077 IConsolePrintF(CC_DEFAULT
, "%s = %s", sd
->desc
.name
, value
);
2080 IConsolePrintF(CC_WARNING
, "Use 'setting' command to change a value");
2084 * Save and load handler for settings
2085 * @param osd SettingDesc struct containing all information
2086 * @param object can be either NULL in which case we load global variables or
2087 * a pointer to a struct which is getting saved
2089 static void LoadSettings(LoadBuffer
*reader
, const SettingDesc
*osd
, void *object
)
2091 for (; osd
->save
.type
!= SL_END
; osd
++) {
2092 const SaveLoad
*sld
= &osd
->save
;
2093 if (!reader
->ReadObjectMember(object
, sld
)) continue;
2095 void *ptr
= GetVariableAddress(sld
, object
);
2096 if ((sld
->type
== SL_VAR
) && IsNumericType(sld
->conv
)) Write_ValidateSetting(ptr
, osd
, ReadValue(ptr
, sld
->conv
));
2101 * Save and load handler for settings
2102 * @param sd SettingDesc struct containing all information
2103 * @param object can be either NULL in which case we load global variables or
2104 * a pointer to a struct which is getting saved
2106 static void SaveSettings(SaveDumper
*dumper
, const SettingDesc
*sd
, void *object
)
2108 SaveDumper
temp(1024);
2110 for (const SettingDesc
*i
= sd
; i
->save
.type
!= SL_END
; i
++) {
2111 temp
.WriteObjectMember(object
, &i
->save
);
2114 dumper
->WriteRIFFSize(temp
.GetSize());
2118 static void Load_OPTS(LoadBuffer
*reader
)
2120 /* Copy over default setting since some might not get loaded in
2121 * a networking environment. This ensures for example that the local
2122 * autosave-frequency stays when joining a network-server */
2123 PrepareOldDiffCustom();
2124 LoadSettings(reader
, _gameopt_settings
, &_settings_game
);
2125 HandleOldDiffCustom(reader
->stv
);
2128 static void Load_PATS(LoadBuffer
*reader
)
2130 /* Copy over default setting since some might not get loaded in
2131 * a networking environment. This ensures for example that the local
2132 * currency setting stays when joining a network-server */
2133 LoadSettings(reader
, _settings
, &_settings_game
);
2136 static void Check_PATS(LoadBuffer
*reader
)
2138 LoadSettings(reader
, _settings
, &_load_check_data
.settings
);
2141 static void Save_PATS(SaveDumper
*dumper
)
2143 SaveSettings(dumper
, _settings
, &_settings_game
);
2149 * Increase old default values for pf_maxdepth and pf_maxlength
2150 * to support big networks.
2152 if (_settings_newgame
.pf
.opf
.pf_maxdepth
== 16 && _settings_newgame
.pf
.opf
.pf_maxlength
== 512) {
2153 _settings_newgame
.pf
.opf
.pf_maxdepth
= 48;
2154 _settings_newgame
.pf
.opf
.pf_maxlength
= 4096;
2158 extern const ChunkHandler _setting_chunk_handlers
[] = {
2159 { 'OPTS', NULL
, Load_OPTS
, NULL
, NULL
, CH_RIFF
},
2160 { 'PATS', Save_PATS
, Load_PATS
, NULL
, Check_PATS
, CH_RIFF
| CH_LAST
},
2163 static bool IsSignedVarMemType(VarType vt
)
2165 switch (GetVarMemType(vt
)) {