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.
29 #include "screenshot.h"
30 #include "network/network.h"
31 #include "network/network_func.h"
32 #include "settings_internal.h"
33 #include "command_func.h"
34 #include "console_func.h"
35 #include "pathfinder/yapf/yapf.h"
38 #include "news_func.h"
39 #include "window_func.h"
40 #include "sound_func.h"
41 #include "company_func.h"
46 #include "textbuf_gui.h"
48 #include "elrail_func.h"
51 #include "video/video_driver.hpp"
52 #include "sound/sound_driver.hpp"
53 #include "music/music_driver.hpp"
54 #include "blitter/blitter.h"
55 #include "spritecache.h"
56 #include "base_media_base.h"
58 #include "settings_func.h"
60 #include "ai/ai_config.hpp"
62 #include "game/game_config.hpp"
63 #include "game/game.hpp"
65 #include "smallmap_gui.h"
68 #include "strings_func.h"
70 #include "map/ground.h"
71 #include "station_base.h"
72 #include "station_func.h"
74 #include "table/strings.h"
75 #include "table/settings.h"
77 ClientSettings _settings_client
;
78 GameSettings _settings_game
; ///< Game settings of a running game or the scenario editor.
79 GameSettings _settings_newgame
; ///< Game settings for new games (updated from the intro screen).
80 VehicleDefaultSettings _old_vds
; ///< Used for loading default vehicles settings from old savegames
81 bool _old_no_servicing_if_no_breakdowns
; ///< Used for loading servicing behaviour from old savegames
82 char *_config_file
; ///< Configuration file of OpenTTD
84 typedef std::list
<ErrorMessageData
> ErrorList
;
85 static ErrorList _settings_error_list
; ///< Errors while loading minimal settings.
88 typedef void SettingDescProc(IniFile
*ini
, const SettingDesc
*desc
, const char *grpname
, void *object
);
89 typedef void SettingDescProcList(IniFile
*ini
, const char *grpname
, StringList
*list
);
91 static bool IsSignedVarMemType(VarType vt
);
94 * Groups in openttd.cfg that are actually lists.
96 static const char * const _list_group_names
[] = {
100 "server_bind_addresses",
105 * Find the index value of a ONEofMANY type in a string separated by |
106 * @param many full domain of values the ONEofMANY setting can have
107 * @param one the current value of the setting for which a value needs found
108 * @param onelen force calculation of the *one parameter
109 * @return the integer index of the full-list, or -1 if not found
111 static size_t LookupOneOfMany(const char *many
, const char *one
, size_t onelen
= 0)
116 if (onelen
== 0) onelen
= strlen(one
);
118 /* check if it's an integer */
119 if (*one
>= '0' && *one
<= '9') return strtoul(one
, NULL
, 0);
123 /* find end of item */
125 while (*s
!= '|' && *s
!= 0) s
++;
126 if ((size_t)(s
- many
) == onelen
&& !memcmp(one
, many
, onelen
)) return idx
;
127 if (*s
== 0) return (size_t)-1;
134 * Find the set-integer value MANYofMANY type in a string
135 * @param many full domain of values the MANYofMANY setting can have
136 * @param str the current string value of the setting, each individual
137 * of separated by a whitespace,tab or | character
138 * @return the 'fully' set integer, or -1 if a set is not found
140 static size_t LookupManyOfMany(const char *many
, const char *str
)
147 /* skip "whitespace" */
148 while (*str
== ' ' || *str
== '\t' || *str
== '|') str
++;
149 if (*str
== 0) break;
152 while (*s
!= 0 && *s
!= ' ' && *s
!= '\t' && *s
!= '|') s
++;
154 r
= LookupOneOfMany(many
, str
, s
- str
);
155 if (r
== (size_t)-1) return r
;
157 SetBit(res
, (uint8
)r
); // value found, set it
165 * Parse an integerlist string and set each found value
166 * @param p the string to be parsed. Each element in the list is separated by a
167 * comma or a space character
168 * @param items pointer to the integerlist-array that will be filled with values
169 * @param maxitems the maximum number of elements the integerlist-array has
170 * @return returns the number of items found, or -1 on an error
172 static int ParseIntList(const char *p
, int *items
, int maxitems
)
174 int n
= 0; // number of items read so far
175 bool comma
= false; // do we accept comma?
180 /* Do not accept multiple commas between numbers */
181 if (!comma
) return -1;
189 if (n
== maxitems
) return -1; // we don't accept that many numbers
191 long v
= strtol(p
, &end
, 0);
192 if (p
== end
) return -1; // invalid character (not a number)
193 if (sizeof(int) < sizeof(long)) v
= ClampToI32(v
);
195 p
= end
; // first non-number
196 comma
= true; // we accept comma now
202 /* If we have read comma but no number after it, fail.
203 * We have read comma when (n != 0) and comma is not allowed */
204 if (n
!= 0 && !comma
) return -1;
210 * Load parsed string-values into an integer-array (intlist)
211 * @param str the string that contains the values (and will be parsed)
212 * @param array pointer to the integer-arrays that will be filled
213 * @param nelems the number of elements the array holds. Maximum is 64 elements
214 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
215 * @return return true on success and false on error
217 static bool LoadIntList(const char *str
, void *array
, int nelems
, VarType type
)
223 memset(items
, 0, sizeof(items
));
226 nitems
= ParseIntList(str
, items
, lengthof(items
));
227 if (nitems
!= nelems
) return false;
234 for (i
= 0; i
!= nitems
; i
++) ((byte
*)array
)[i
] = items
[i
];
239 for (i
= 0; i
!= nitems
; i
++) ((uint16
*)array
)[i
] = items
[i
];
244 for (i
= 0; i
!= nitems
; i
++) ((uint32
*)array
)[i
] = items
[i
];
247 default: NOT_REACHED();
254 * Convert an integer-array (intlist) to a string representation. Each value
255 * is separated by a comma or a space character
256 * @param array pointer to the integer-arrays that is read from
257 * @param nelems the number of elements the array holds.
258 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
259 * @return the string representation in newly-allocated storage
261 static char *MakeIntList (const void *array
, int nelems
, VarType type
)
266 const byte
*p
= (const byte
*)array
;
268 for (i
= 0; i
!= nelems
; i
++) {
271 case SLE_VAR_I8
: v
= *(const int8
*)p
; p
+= 1; break;
272 case SLE_VAR_U8
: v
= *(const uint8
*)p
; p
+= 1; break;
273 case SLE_VAR_I16
: v
= *(const int16
*)p
; p
+= 2; break;
274 case SLE_VAR_U16
: v
= *(const uint16
*)p
; p
+= 2; break;
275 case SLE_VAR_I32
: v
= *(const int32
*)p
; p
+= 4; break;
276 case SLE_VAR_U32
: v
= *(const uint32
*)p
; p
+= 4; break;
277 default: NOT_REACHED();
279 buffer
.append_fmt ((i
== 0) ? "%d" : ",%d", v
);
282 return xstrdup (buffer
.c_str());
286 * Convert a ONEofMANY structure to a string representation.
287 * @param many the full-domain string of possible values
288 * @param id the value of the variable and whose string-representation must be found
289 * @return the string representation in newly-allocated storage
291 static char *MakeOneOfMany (const char *many
, int id
)
295 /* Look for the id'th element */
297 many
= strchr (many
, '|');
298 if (many
== NULL
) { // not found
299 return str_fmt ("%d", orig_id
);
301 many
++; // pass the |-character
304 /* copy string until next item (|) or the end of the list if this is the last one */
305 const char *end
= strchr (many
, '|');
307 return xstrdup (many
);
309 return xstrmemdup (many
, end
- many
);
314 * Convert a MANYofMANY structure to a string representation.
315 * @param many the full-domain string of possible values
316 * @param x the value of the variable and whose string-representation must
317 * be found in the bitmasked many string
318 * @return the string representation in newly-allocated storage
320 static char *MakeManyOfMany (const char *many
, uint32 x
)
325 for (; x
!= 0; x
>>= 1, i
++) {
326 const char *start
= many
;
327 while (*many
!= 0 && *many
!= '|') many
++; // advance to the next element
329 if (HasBit(x
, 0)) { // item found, copy it
330 if (!buffer
.empty()) buffer
.append ('|');
332 buffer
.append_fmt ("%d", i
);
334 buffer
.append_fmt ("%.*s", (int)(many
- start
), start
);
338 if (*many
== '|') many
++;
341 return xstrdup (buffer
.c_str());
345 * Convert a string representation (external) of a setting to the internal rep.
346 * @param desc SettingDesc struct that holds all information about the variable
347 * @param orig_str input string that will be parsed based on the type of desc
348 * @return return the parsed value of the setting
350 static size_t StringToVal (const SettingDescBase
*desc
, const char *orig_str
)
352 const char *str
= orig_str
== NULL
? "" : orig_str
;
357 size_t val
= strtoul(str
, &end
, 0);
358 if (end
== str
) break;
360 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_TRAILING_CHARACTERS
);
361 msg
.SetDParamStr(0, desc
->name
);
362 _settings_error_list
.push_back(msg
);
367 case SDT_ONEOFMANY
: {
368 size_t r
= LookupOneOfMany(desc
->many
, str
);
369 /* if the first attempt of conversion from string to the appropriate value fails,
370 * look if we have defined a converter from old value to new value. */
371 if (r
== (size_t)-1 && desc
->proc_cnvt
!= NULL
) r
= desc
->proc_cnvt(str
);
372 if (r
!= (size_t)-1) return r
; // and here goes converted value
376 case SDT_MANYOFMANY
: {
377 size_t r
= LookupManyOfMany(desc
->many
, str
);
378 if (r
!= (size_t)-1) return r
;
383 if (strcmp(str
, "true") == 0 || strcmp(str
, "on") == 0 || strcmp(str
, "1") == 0) return 1;
384 if (strcmp(str
, "false") == 0 || strcmp(str
, "off") == 0 || strcmp(str
, "0") == 0) return 0;
387 default: NOT_REACHED();
390 ErrorMessageData
msg (STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
391 msg
.SetDParamStr (0, str
);
392 msg
.SetDParamStr (1, desc
->name
);
393 _settings_error_list
.push_back (msg
);
394 return (size_t)desc
->def
;
398 * Set the value of a setting and if needed clamp the value to
399 * the preset minimum and maximum.
400 * @param ptr the variable itself
401 * @param sd pointer to the 'information'-database of the variable
402 * @param val signed long version of the new value
403 * @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
404 * SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now
406 static void Write_ValidateSetting(void *ptr
, const SettingDesc
*sd
, int32 val
)
408 const SettingDescBase
*sdb
= &sd
->desc
;
410 if (sdb
->cmd
!= SDT_BOOLX
&&
411 sdb
->cmd
!= SDT_NUMX
&&
412 sdb
->cmd
!= SDT_ONEOFMANY
&&
413 sdb
->cmd
!= SDT_MANYOFMANY
) {
417 /* We cannot know the maximum value of a bitset variable, so just have faith */
418 if (sdb
->cmd
!= SDT_MANYOFMANY
) {
419 assert(sd
->save
.type
== SL_VAR
);
421 /* We need to take special care of the uint32 type as we receive from the function
422 * a signed integer. While here also bail out on 64-bit settings as those are not
423 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
425 * TODO: Support 64-bit settings/variables */
426 switch (GetVarMemType(sd
->save
.conv
)) {
433 /* Override the minimum value. No value below sdb->min, except special value 0 */
434 if (!(sdb
->flags
& SGF_0ISDISABLED
) || val
!= 0) val
= Clamp(val
, sdb
->min
, sdb
->max
);
438 /* Override the minimum value. No value below sdb->min, except special value 0 */
439 uint min
= ((sdb
->flags
& SGF_0ISDISABLED
) && (uint
)val
<= (uint
)sdb
->min
) ? 0 : sdb
->min
;
440 WriteValue(ptr
, SLE_VAR_U32
, (int64
)ClampU(val
, min
, sdb
->max
));
445 default: NOT_REACHED();
449 WriteValue(ptr
, sd
->save
.conv
, (int64
)val
);
453 * Load values from a group of an IniFile structure into the internal representation
454 * @param ini pointer to IniFile structure that holds administrative information
455 * @param sd pointer to SettingDesc structure whose internally pointed variables will
457 * @param grpname the group of the IniFile to search in for the new values
458 * @param object pointer to the object been loaded
460 static void IniLoadSettings(IniFile
*ini
, const SettingDesc
*sd
, const char *grpname
, void *object
)
462 const IniGroup
*group_def
= ini
->get_group (grpname
);
464 for (; sd
->save
.type
!= SL_END
; sd
++) {
465 const SettingDescBase
*sdb
= &sd
->desc
;
466 const SaveLoad
*sld
= &sd
->save
;
468 if (!sld
->is_currently_valid()) continue;
470 /* For settings.xx.yy load the settings from [xx] yy = ? */
471 const char *s
= strchr(sdb
->name
, '.');
472 const IniGroup
*group
;
474 group
= ini
->get_group (sdb
->name
, s
- sdb
->name
);
481 const IniItem
*item
= group
->find (s
);
482 if (item
== NULL
&& group
!= group_def
) {
483 /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
484 * did not exist (e.g. loading old config files with a [settings] section */
485 item
= group_def
->find (s
);
488 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
489 * did not exist (e.g. loading old config files with a [yapf] section */
490 const char *sc
= strchr(s
, '.');
491 if (sc
!= NULL
) item
= ini
->get_group (s
, sc
- s
)->find (sc
+ 1);
494 void *ptr
= sld
->get_variable_address (object
);
497 case SDT_BOOLX
: // All four are various types of (integer) numbers
500 case SDT_MANYOFMANY
: {
501 size_t p
= (item
== NULL
) ? (size_t)sdb
->def
: StringToVal (sdb
, item
->value
);
502 Write_ValidateSetting (ptr
, sd
, (int32
)p
);
507 assert (sld
->type
== SL_STR
);
508 const char *str
= (item
== NULL
) ? (const char*)sdb
->def
: item
->value
;
509 if (sld
->length
== 0) {
511 *(char**)ptr
= str
== NULL
? NULL
: xstrdup (str
);
513 if (str
!= NULL
) ttd_strlcpy ((char*)ptr
, str
, sld
->length
);
519 const char *str
= (item
== NULL
) ? (const char*)sdb
->def
:
520 (item
->value
== NULL
) ? "" : item
->value
;
521 if (!LoadIntList (str
, ptr
, sld
->length
, GetVarMemType (sld
->conv
))) {
522 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_ARRAY
);
523 msg
.SetDParamStr(0, sdb
->name
);
524 _settings_error_list
.push_back(msg
);
527 LoadIntList((const char*)sdb
->def
, ptr
, sld
->length
, GetVarMemType(sld
->conv
));
528 } else if (sd
->desc
.proc_cnvt
!= NULL
) {
529 sd
->desc
.proc_cnvt (str
);
533 default: NOT_REACHED();
539 * Save the values of settings to the inifile.
540 * @param ini pointer to IniFile structure
541 * @param sd read-only SettingDesc structure which contains the unmodified,
542 * loaded values of the configuration file and various information about it
543 * @param grpname holds the name of the group (eg. [network]) where these will be saved
544 * @param object pointer to the object been saved
545 * The function works as follows: for each item in the SettingDesc structure we
546 * have a look if the value has changed since we started the game (the original
547 * values are reloaded when saving). If settings indeed have changed, we get
548 * these and save them.
550 static void IniSaveSettings(IniFile
*ini
, const SettingDesc
*sd
, const char *grpname
, void *object
)
552 IniGroup
*group_def
= NULL
;
554 for (; sd
->save
.type
!= SL_END
; sd
++) {
555 const SettingDescBase
*sdb
= &sd
->desc
;
556 const SaveLoad
*sld
= &sd
->save
;
558 /* If the setting is not saved to the configuration
559 * file, just continue with the next setting */
560 if (!sld
->is_currently_valid()) continue;
561 if (sld
->flags
& SLF_NOT_IN_CONFIG
) continue;
563 /* XXX - wtf is this?? (group override?) */
564 const char *s
= strchr(sdb
->name
, '.');
567 group
= ini
->get_group (sdb
->name
, s
- sdb
->name
);
570 if (group_def
== NULL
) group_def
= ini
->get_group (grpname
);
575 IniItem
*item
= group
->get_item (s
);
576 void *ptr
= sld
->get_variable_address (object
);
578 /* Get the new value and put it into a buffer. */
584 case SDT_MANYOFMANY
: {
585 if (item
->value
!= NULL
) {
586 /* check if the value is the same as the old value */
587 size_t p
= StringToVal (sdb
, item
->value
);
589 /* The main type of a variable/setting is in bytes 8-15
590 * The subtype (what kind of numbers do we have there) is in 0-7 */
591 assert(sld
->type
== SL_VAR
);
592 switch (GetVarMemType(sld
->conv
)) {
594 if (*(bool*)ptr
== (p
!= 0)) continue;
599 if (*(byte
*)ptr
== (byte
)p
) continue;
604 if (*(uint16
*)ptr
== (uint16
)p
) continue;
609 if (*(uint32
*)ptr
== (uint32
)p
) continue;
612 default: NOT_REACHED();
616 uint32 i
= (uint32
)ReadValue(ptr
, sld
->conv
);
619 case SDT_BOOLX
: new_value
= xstrdup ((i
!= 0) ? "true" : "false"); break;
620 case SDT_NUMX
: new_value
= str_fmt (IsSignedVarMemType(sld
->conv
) ? "%d" : "%u", i
); break;
621 case SDT_ONEOFMANY
: new_value
= MakeOneOfMany (sdb
->many
, i
); break;
622 case SDT_MANYOFMANY
: new_value
= MakeManyOfMany (sdb
->many
, i
); break;
623 default: NOT_REACHED();
629 assert (sld
->type
== SL_STR
);
633 if (sld
->length
== 0) {
634 s
= *(const char *const *)ptr
;
636 s
= (const char *)ptr
;
639 if (sld
->conv
& SLS_QUOTED
) {
641 new_value
= xstrdup ("");
643 new_value
= str_fmt ("\"%s\"", s
);
646 new_value
= xstrdup (s
);
652 new_value
= MakeIntList (ptr
, sld
->length
, GetVarMemType(sld
->conv
));
655 default: NOT_REACHED();
658 /* The value is different, that means we have to write it to the ini */
660 item
->value
= new_value
;
665 * Loads all items from a 'grpname' section into a list
666 * The list parameter can be a NULL pointer, in this case nothing will be
667 * saved and a callback function should be defined that will take over the
668 * list-handling and store the data itself somewhere.
669 * @param ini IniFile handle to the ini file with the source data
670 * @param grpname character string identifying the section-header of the ini file that will be parsed
671 * @param list new list with entries of the given section
673 static void IniLoadSettingList(IniFile
*ini
, const char *grpname
, StringList
*list
)
675 const IniGroup
*group
= ini
->get_group (grpname
);
677 if (group
== NULL
|| list
== NULL
) return;
681 for (IniItem::const_iterator item
= group
->cbegin(); item
!= group
->cend(); item
++) {
682 *list
->Append() = xstrdup(item
->get_name());
687 * Saves all items from a list into the 'grpname' section
688 * The list parameter can be a NULL pointer, in this case a callback function
689 * should be defined that will provide the source data to be saved.
690 * @param ini IniFile handle to the ini file where the destination data is saved
691 * @param grpname character string identifying the section-header of the ini file
692 * @param list pointer to an string(pointer) array that will be used as the
693 * source to be saved into the relevant ini section
695 static void IniSaveSettingList(IniFile
*ini
, const char *grpname
, StringList
*list
)
697 IniGroup
*group
= ini
->get_group (grpname
);
699 if (group
== NULL
|| list
== NULL
) return;
702 for (char **iter
= list
->Begin(); iter
!= list
->End(); iter
++) {
703 group
->get_item(*iter
)->SetValue("");
708 * Load a WindowDesc from config.
709 * @param ini IniFile handle to the ini file with the source data
710 * @param grpname character string identifying the section-header of the ini file that will be parsed
711 * @param desc Destination WindowDesc
713 void IniLoadWindowSettings(IniFile
*ini
, const char *grpname
, void *desc
)
715 IniLoadSettings(ini
, _window_settings
, grpname
, desc
);
719 * Save a WindowDesc to config.
720 * @param ini IniFile handle to the ini file where the destination data is saved
721 * @param grpname character string identifying the section-header of the ini file
722 * @param desc Source WindowDesc
724 void IniSaveWindowSettings(IniFile
*ini
, const char *grpname
, void *desc
)
726 IniSaveSettings(ini
, _window_settings
, grpname
, desc
);
730 * Check whether the setting is editable in the current gamemode.
731 * @param do_command true if this is about checking a command from the server.
732 * @return true if editable.
734 bool SettingDesc::IsEditable(bool do_command
) const
736 if (!do_command
&& !(this->save
.flags
& SLF_NO_NETWORK_SYNC
) && _networking
&& !_network_server
&& !(this->desc
.flags
& SGF_PER_COMPANY
)) return false;
737 if ((this->desc
.flags
& SGF_NETWORK_ONLY
) && !_networking
&& _game_mode
!= GM_MENU
) return false;
738 if ((this->desc
.flags
& SGF_NO_NETWORK
) && _networking
) return false;
739 if ((this->desc
.flags
& SGF_NEWGAME_ONLY
) &&
740 (_game_mode
== GM_NORMAL
||
741 (_game_mode
== GM_EDITOR
&& !(this->desc
.flags
& SGF_SCENEDIT_TOO
)))) return false;
746 * Return the type of the setting.
747 * @return type of setting
749 SettingType
SettingDesc::GetType() const
751 if (this->desc
.flags
& SGF_PER_COMPANY
) return ST_COMPANY
;
752 return (this->save
.flags
& SLF_NOT_IN_SAVE
) ? ST_CLIENT
: ST_GAME
;
755 /* Begin - Callback Functions for the various settings. */
757 /** Reposition the main toolbar as the setting changed. */
758 static bool v_PositionMainToolbar(int32 p1
)
760 if (_game_mode
!= GM_MENU
) PositionMainToolbar(NULL
);
764 /** Reposition the statusbar as the setting changed. */
765 static bool v_PositionStatusbar(int32 p1
)
767 if (_game_mode
!= GM_MENU
) {
768 PositionStatusbar(NULL
);
769 PositionNewsMessage(NULL
);
770 PositionNetworkChatWindow(NULL
);
775 static bool PopulationInLabelActive(int32 p1
)
777 UpdateAllTownVirtCoords();
781 static bool RedrawScreen(int32 p1
)
783 MarkWholeScreenDirty();
788 * Redraw the smallmap after a colour scheme change.
789 * @param p1 Callback parameter.
790 * @return Always true.
792 static bool RedrawSmallmap(int32 p1
)
796 SetWindowClassesDirty(WC_SMALLMAP
);
800 static bool InvalidateDetailsWindow(int32 p1
)
802 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
806 static bool StationSpreadChanged(int32 p1
)
808 InvalidateWindowData(WC_SELECT_STATION
, 0);
809 InvalidateWindowData(WC_BUILD_STATION
, 0);
813 static bool InvalidateBuildIndustryWindow(int32 p1
)
815 InvalidateWindowData(WC_BUILD_INDUSTRY
, 0);
819 static bool CloseSignalGUI(int32 p1
)
822 DeleteWindowByClass(WC_BUILD_SIGNAL
);
827 static bool InvalidateTownViewWindow(int32 p1
)
829 InvalidateWindowClassesData(WC_TOWN_VIEW
, p1
);
833 static bool DeleteSelectStationWindow(int32 p1
)
835 DeleteWindowById(WC_SELECT_STATION
, 0);
839 static bool UpdateConsists(int32 p1
)
843 /* Update the consist of all trains so the maximum speed is set correctly. */
844 if (t
->IsFrontEngine() || t
->IsFreeWagon()) t
->ConsistChanged(CCF_TRACK
);
846 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
850 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
851 static bool CheckInterval(int32 p1
)
853 bool update_vehicles
;
854 VehicleDefaultSettings
*vds
;
855 if (_game_mode
== GM_MENU
|| !Company::IsValidID(_current_company
)) {
856 vds
= &_settings_client
.company
.vehicle
;
857 update_vehicles
= false;
859 vds
= &Company::Get(_current_company
)->settings
.vehicle
;
860 update_vehicles
= true;
864 vds
->servint_trains
= 50;
865 vds
->servint_roadveh
= 50;
866 vds
->servint_aircraft
= 50;
867 vds
->servint_ships
= 50;
869 vds
->servint_trains
= 150;
870 vds
->servint_roadveh
= 150;
871 vds
->servint_aircraft
= 100;
872 vds
->servint_ships
= 360;
875 if (update_vehicles
) {
876 const Company
*c
= Company::Get(_current_company
);
878 FOR_ALL_VEHICLES(v
) {
879 if (v
->owner
== _current_company
&& v
->IsPrimaryVehicle() && !v
->ServiceIntervalIsCustom()) {
880 v
->SetServiceInterval(CompanyServiceInterval(c
, v
->type
));
881 v
->SetServiceIntervalIsPercent(p1
!= 0);
886 InvalidateDetailsWindow(0);
891 static bool UpdateInterval(VehicleType type
, int32 p1
)
893 bool update_vehicles
;
894 VehicleDefaultSettings
*vds
;
895 if (_game_mode
== GM_MENU
|| !Company::IsValidID(_current_company
)) {
896 vds
= &_settings_client
.company
.vehicle
;
897 update_vehicles
= false;
899 vds
= &Company::Get(_current_company
)->settings
.vehicle
;
900 update_vehicles
= true;
903 /* Test if the interval is valid */
904 uint16 interval
= GetServiceIntervalClamped(p1
, vds
->servint_ispercent
);
905 if (interval
!= p1
) return false;
907 if (update_vehicles
) {
909 FOR_ALL_VEHICLES(v
) {
910 if (v
->owner
== _current_company
&& v
->type
== type
&& v
->IsPrimaryVehicle() && !v
->ServiceIntervalIsCustom()) {
911 v
->SetServiceInterval(p1
);
916 InvalidateDetailsWindow(0);
921 static bool UpdateIntervalTrains(int32 p1
)
923 return UpdateInterval(VEH_TRAIN
, p1
);
926 static bool UpdateIntervalRoadVeh(int32 p1
)
928 return UpdateInterval(VEH_ROAD
, p1
);
931 static bool UpdateIntervalShips(int32 p1
)
933 return UpdateInterval(VEH_SHIP
, p1
);
936 static bool UpdateIntervalAircraft(int32 p1
)
938 return UpdateInterval(VEH_AIRCRAFT
, p1
);
941 static bool TrainAccelerationModelChanged(int32 p1
)
945 if (t
->IsFrontEngine()) {
946 t
->tcache
.cached_max_curve_speed
= t
->GetCurveSpeedLimit();
947 t
->UpdateAcceleration();
951 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
952 SetWindowClassesDirty(WC_ENGINE_PREVIEW
);
953 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
954 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
960 * This function updates the train acceleration cache after a steepness change.
961 * @param p1 Callback parameter.
962 * @return Always true.
964 static bool TrainSlopeSteepnessChanged(int32 p1
)
968 if (t
->IsFrontEngine()) t
->CargoChanged();
975 * This function updates realistic acceleration caches when the setting "Road vehicle acceleration model" is set.
976 * @param p1 Callback parameter
977 * @return Always true
979 static bool RoadVehAccelerationModelChanged(int32 p1
)
981 if (_settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) {
983 FOR_ALL_ROADVEHICLES(rv
) {
984 if (rv
->IsFrontEngine()) {
990 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
991 SetWindowClassesDirty(WC_ENGINE_PREVIEW
);
992 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
993 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
999 * This function updates the road vehicle acceleration cache after a steepness change.
1000 * @param p1 Callback parameter.
1001 * @return Always true.
1003 static bool RoadVehSlopeSteepnessChanged(int32 p1
)
1006 FOR_ALL_ROADVEHICLES(rv
) {
1007 if (rv
->IsFrontEngine()) rv
->CargoChanged();
1013 static bool DragSignalsDensityChanged(int32
)
1015 InvalidateWindowData(WC_BUILD_SIGNAL
, 0);
1020 static bool TownFoundingChanged(int32 p1
)
1022 if (_game_mode
!= GM_EDITOR
&& _settings_game
.economy
.found_town
== TF_FORBIDDEN
) {
1023 DeleteWindowById(WC_FOUND_TOWN
, 0);
1026 InvalidateWindowData(WC_FOUND_TOWN
, 0);
1030 static bool InvalidateVehTimetableWindow(int32 p1
)
1032 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE
, VIWD_MODIFY_ORDERS
);
1036 static bool ZoomMinMaxChanged(int32 p1
)
1038 extern void ConstrainAllViewportsZoom();
1039 ConstrainAllViewportsZoom();
1040 GfxClearSpriteCache();
1041 if (_settings_client
.gui
.zoom_min
> _gui_zoom
) {
1042 /* Restrict GUI zoom if it is no longer available. */
1043 _gui_zoom
= _settings_client
.gui
.zoom_min
;
1045 LoadStringWidthTable();
1051 * Update any possible saveload window and delete any newgrf dialogue as
1052 * its widget parts might change. Reinit all windows as it allows access to the
1053 * newgrf debug button.
1055 * @return Always true.
1057 static bool InvalidateNewGRFChangeWindows(int32 p1
)
1059 InvalidateWindowClassesData(WC_SAVELOAD
);
1060 DeleteWindowByClass(WC_GAME_OPTIONS
);
1065 static bool InvalidateCompanyLiveryWindow(int32 p1
)
1067 InvalidateWindowClassesData(WC_COMPANY_COLOUR
);
1068 return RedrawScreen(p1
);
1071 static bool InvalidateIndustryViewWindow(int32 p1
)
1073 InvalidateWindowClassesData(WC_INDUSTRY_VIEW
);
1077 static bool InvalidateAISettingsWindow(int32 p1
)
1079 InvalidateWindowClassesData(WC_AI_SETTINGS
);
1084 * Update the town authority window after a town authority setting change.
1086 * @return Always true.
1088 static bool RedrawTownAuthority(int32 p1
)
1090 SetWindowClassesDirty(WC_TOWN_AUTHORITY
);
1095 * Invalidate the company infrastructure details window after a infrastructure maintenance setting change.
1097 * @return Always true.
1099 static bool InvalidateCompanyInfrastructureWindow(int32 p1
)
1101 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE
);
1106 * Invalidate the company details window after the shares setting changed.
1108 * @return Always true.
1110 static bool InvalidateCompanyWindow(int32 p1
)
1112 InvalidateWindowClassesData(WC_COMPANY
);
1116 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
1117 static void ValidateSettings()
1119 /* Do not allow a custom sea level with the original land generator. */
1120 if (_settings_newgame
.game_creation
.land_generator
== LG_ORIGINAL
&&
1121 _settings_newgame
.difficulty
.quantity_sea_lakes
== CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
) {
1122 _settings_newgame
.difficulty
.quantity_sea_lakes
= CUSTOM_SEA_LEVEL_MIN_PERCENTAGE
;
1126 static bool DifficultyNoiseChange(int32 i
)
1128 if (_game_mode
== GM_NORMAL
) {
1129 UpdateAirportsNoise();
1130 if (_settings_game
.economy
.station_noise_level
) {
1131 InvalidateWindowClassesData(WC_TOWN_VIEW
, 0);
1138 static bool MaxNoAIsChange(int32 i
)
1140 if (GetGameSettings().difficulty
.max_no_competitors
!= 0 &&
1142 (!_networking
|| _network_server
)) {
1143 ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI
, INVALID_STRING_ID
, WL_CRITICAL
);
1150 * Check whether the road side may be changed.
1152 * @return true if the road side may be changed.
1154 static bool CheckRoadSide(int p1
)
1156 extern bool RoadVehiclesAreBuilt();
1157 return _game_mode
== GM_MENU
|| !RoadVehiclesAreBuilt();
1161 * Conversion callback for _gameopt_settings_game.landscape
1162 * It converts (or try) between old values and the new ones,
1163 * without losing initial setting of the user
1164 * @param value that was read from config file
1165 * @return the "hopefully" converted value
1167 static size_t ConvertLandscape(const char *value
)
1169 /* try with the old values */
1170 return LookupOneOfMany("normal|hilly|desert|candy", value
);
1173 static bool CheckFreeformEdges(int32 p1
)
1175 if (_game_mode
== GM_MENU
) return true;
1179 /* Check if there is a ship on the northern border. */
1180 if (TileX(s
->tile
) == 0 || TileY(s
->tile
) == 0) {
1181 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY
, INVALID_STRING_ID
, WL_ERROR
);
1186 FOR_ALL_BASE_STATIONS(st
) {
1187 /* Check if there is a non-deleted buoy on the northern border. */
1188 if (st
->IsInUse() && (TileX(st
->xy
) == 0 || TileY(st
->xy
) == 0)) {
1189 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY
, INVALID_STRING_ID
, WL_ERROR
);
1193 for (uint i
= 0; i
< MapSizeX(); i
++) MakeVoid(TileXY(i
, 0));
1194 for (uint i
= 0; i
< MapSizeY(); i
++) MakeVoid(TileXY(0, i
));
1196 for (uint i
= 1; i
< MapMaxX(); i
++) {
1197 if (TileHeight(TileXY(i
, 1)) != 0) {
1198 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1202 for (uint i
= 1; i
< MapMaxX(); i
++) {
1203 if (!IsWaterTile(TileXY(i
, MapMaxY() - 1)) || TileHeight(TileXY(i
, MapMaxY())) != 0) {
1204 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1208 for (uint i
= 1; i
< MapMaxY(); i
++) {
1209 if (TileHeight(TileXY(1, i
)) != 0) {
1210 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1214 for (uint i
= 1; i
< MapMaxY(); i
++) {
1215 if (!IsWaterTile(TileXY(MapMaxX() - 1, i
)) || TileHeight(TileXY(MapMaxX(), i
)) != 0) {
1216 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1220 /* Make tiles at the border water again. */
1221 for (uint i
= 0; i
< MapMaxX(); i
++) {
1222 SetTileHeight(TileXY(i
, 0), 0);
1223 MakeSea(TileXY(i
, 0));
1225 for (uint i
= 0; i
< MapMaxY(); i
++) {
1226 SetTileHeight(TileXY(0, i
), 0);
1227 MakeSea(TileXY(0, i
));
1230 MarkWholeScreenDirty();
1235 * Changing the setting "allow multiple NewGRF sets" is not allowed
1236 * if there are vehicles.
1238 static bool ChangeDynamicEngines(int32 p1
)
1240 if (_game_mode
== GM_MENU
) return true;
1242 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
1243 ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES
, INVALID_STRING_ID
, WL_ERROR
);
1250 static bool ChangeMaxHeightLevel(int32 p1
)
1252 if (_game_mode
== GM_NORMAL
) return false;
1253 if (_game_mode
!= GM_EDITOR
) return true;
1255 /* Check if at least one mountain on the map is higher than the new value.
1256 * If yes, disallow the change. */
1257 for (TileIndex t
= 0; t
< MapSize(); t
++) {
1258 if ((int32
)TileHeight(t
) > p1
) {
1259 ShowErrorMessage(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN
, INVALID_STRING_ID
, WL_ERROR
);
1260 /* Return old, unchanged value */
1265 /* The smallmap uses an index from heightlevels to colours. Trigger rebuilding it. */
1266 InvalidateWindowClassesData(WC_SMALLMAP
, 2);
1271 static bool StationCatchmentChanged(int32 p1
)
1273 Station::RecomputeIndustriesNearForAll();
1277 static bool MaxVehiclesChanged(int32 p1
)
1279 InvalidateWindowClassesData(WC_BUILD_TOOLBAR
);
1280 MarkWholeScreenDirty();
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
&& stv
->is_ottd_before (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 (!sd
->save
.is_currently_valid()) continue;
1355 void *var
= sd
->save
.get_variable_address (stv
!= NULL
? &_settings_game
: &_settings_newgame
);
1356 Write_ValidateSetting(var
, sd
, (int32
)((i
== 4 ? 1000 : 1) * _old_diff_custom
[i
]));
1360 static bool ScriptLoadConfig (ScriptConfig
*config
, const IniItem
*item
)
1362 config
->Change (item
->get_name());
1364 if (!config
->HasScript() && !item
->is_name("none")) return false;
1366 if (item
->value
!= NULL
) config
->StringToSettings (item
->value
);
1371 static void AILoadConfig(IniFile
*ini
, const char *grpname
)
1373 const IniGroup
*group
= ini
->get_group (grpname
);
1375 /* Clean any configured AI */
1376 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1377 AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
)->Change(NULL
);
1380 /* If no group exists, return */
1381 if (group
== NULL
) return;
1383 CompanyID c
= COMPANY_FIRST
;
1384 for (IniItem::const_iterator item
= group
->cbegin(); c
< MAX_COMPANIES
&& item
!= group
->cend(); c
++, item
++) {
1385 AIConfig
*config
= AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
);
1386 if (!ScriptLoadConfig (config
, &*item
)) {
1387 DEBUG(script
, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item
->get_name());
1392 static void GameLoadConfig(IniFile
*ini
, const char *grpname
)
1394 const IniGroup
*group
= ini
->get_group (grpname
);
1396 /* Clean any configured GameScript */
1397 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME
)->Change(NULL
);
1399 /* If no group exists, return */
1400 if (group
== NULL
) return;
1402 IniItem::const_iterator item
= group
->cbegin();
1403 if (item
== group
->cend()) return;
1405 GameConfig
*config
= GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME
);
1406 if (!ScriptLoadConfig (config
, &*item
)) {
1407 DEBUG(script
, 0, "The GameScript by the name '%s' was no longer found, and removed from the list.", item
->get_name());
1412 * Convert a character to a hex nibble value, or \c -1 otherwise.
1413 * @param c Character to convert.
1414 * @return Hex value of the character, or \c -1 if not a hex digit.
1416 static int DecodeHexNibble(char c
)
1418 if (c
>= '0' && c
<= '9') return c
- '0';
1419 if (c
>= 'A' && c
<= 'F') return c
+ 10 - 'A';
1420 if (c
>= 'a' && c
<= 'f') return c
+ 10 - 'a';
1425 * Parse a sequence of characters (supposedly hex digits) into a sequence of bytes.
1426 * After the hex number should be a \c '|' character.
1427 * @param pos First character to convert.
1428 * @param dest [out] Output byte array to write the bytes.
1429 * @param dest_size Number of bytes in \a dest.
1430 * @return Whether reading was successful.
1432 static bool DecodeHexText(const char *pos
, uint8
*dest
, size_t dest_size
)
1434 while (dest_size
> 0) {
1435 int hi
= DecodeHexNibble(pos
[0]);
1436 if (hi
< 0) return false;
1437 int lo
= DecodeHexNibble(pos
[1]);
1438 if (lo
< 0) return false;
1439 *dest
++ = (hi
<< 4) | lo
;
1447 * Load a GRF configuration
1448 * @param ini The configuration to read from.
1449 * @param grpname Group name containing the configuration of the GRF.
1450 * @param is_static GRF is static.
1452 static GRFConfig
*GRFLoadConfig(IniFile
*ini
, const char *grpname
, bool is_static
)
1454 const IniGroup
*group
= ini
->get_group (grpname
);
1455 GRFConfig
*first
= NULL
;
1456 GRFConfig
**curr
= &first
;
1458 if (group
== NULL
) return NULL
;
1460 for (IniItem::const_iterator item
= group
->cbegin(); item
!= group
->cend(); item
++) {
1461 GRFConfig
*c
= NULL
;
1463 uint8 grfid_buf
[4], md5sum
[16];
1464 const char *filename
= item
->get_name();
1466 /* Try reading "<grfid>|" and on success, "<md5sum>|". */
1467 if (DecodeHexText(filename
, grfid_buf
, lengthof(grfid_buf
))) {
1468 filename
+= 1 + 2 * lengthof(grfid_buf
);
1469 uint32 grfid
= grfid_buf
[0] | (grfid_buf
[1] << 8) | (grfid_buf
[2] << 16) | (grfid_buf
[3] << 24);
1471 if (DecodeHexText(filename
, md5sum
, lengthof(md5sum
))) {
1472 filename
+= 1 + 2 * lengthof(md5sum
);
1473 const GRFConfig
*s
= FindGRFConfig(grfid
, FGCM_EXACT
, md5sum
);
1474 if (s
!= NULL
) c
= new GRFConfig(*s
);
1476 if (c
== NULL
&& !FioCheckFileExists(filename
, NEWGRF_DIR
)) {
1477 const GRFConfig
*s
= FindGRFConfig(grfid
, FGCM_NEWEST_VALID
);
1478 if (s
!= NULL
) c
= new GRFConfig(*s
);
1481 if (c
== NULL
) c
= new GRFConfig(filename
);
1483 /* Parse parameters */
1484 if (!StrEmpty(item
->value
)) {
1485 int count
= ParseIntList(item
->value
, (int*)c
->param
, lengthof(c
->param
));
1487 SetDParamStr(0, filename
);
1488 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_ARRAY
, WL_CRITICAL
);
1491 c
->num_params
= count
;
1494 /* Check if item is valid */
1495 if (!FillGRFDetails(c
, is_static
) || HasBit(c
->flags
, GCF_INVALID
)) {
1496 if (c
->status
== GCS_NOT_FOUND
) {
1497 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND
);
1498 } else if (HasBit(c
->flags
, GCF_UNSAFE
)) {
1499 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE
);
1500 } else if (HasBit(c
->flags
, GCF_SYSTEM
)) {
1501 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM
);
1502 } else if (HasBit(c
->flags
, GCF_INVALID
)) {
1503 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE
);
1505 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN
);
1508 SetDParamStr(0, StrEmpty(filename
) ? item
->get_name() : filename
);
1509 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_GRF
, WL_CRITICAL
);
1514 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1515 bool duplicate
= false;
1516 for (const GRFConfig
*gc
= first
; gc
!= NULL
; gc
= gc
->next
) {
1517 if (gc
->ident
.grfid
== c
->ident
.grfid
) {
1518 SetDParamStr(0, c
->filename
);
1519 SetDParamStr(1, gc
->filename
);
1520 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_DUPLICATE_GRFID
, WL_CRITICAL
);
1530 /* Mark file as static to avoid saving in savegame. */
1531 if (is_static
) SetBit(c
->flags
, GCF_STATIC
);
1533 /* Add item to list */
1541 static void ScriptSaveConfig (const ScriptConfig
*config
, IniGroup
*group
)
1544 config
->SettingsToString (value
);
1546 const char *name
= config
->HasScript() ? config
->GetName() : "none";
1547 group
->append(name
)->SetValue (value
);
1550 static void AISaveConfig(IniFile
*ini
, const char *grpname
)
1552 IniGroup
*group
= ini
->get_group (grpname
);
1554 if (group
== NULL
) return;
1557 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1558 AIConfig
*config
= AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
);
1559 ScriptSaveConfig (config
, group
);
1563 static void GameSaveConfig(IniFile
*ini
, const char *grpname
)
1565 IniGroup
*group
= ini
->get_group (grpname
);
1567 if (group
== NULL
) return;
1570 GameConfig
*config
= GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME
);
1571 ScriptSaveConfig (config
, group
);
1575 * Save the version of OpenTTD to the ini file.
1576 * @param ini the ini to write to
1578 static void SaveVersionInConfig(IniFile
*ini
)
1580 IniGroup
*group
= ini
->get_group ("version");
1583 bstrfmt (version
, "%08X", _openttd_newgrf_version
);
1585 const char * const versions
[][2] = {
1586 { "version_string", _openttd_revision
},
1587 { "version_number", version
}
1590 for (uint i
= 0; i
< lengthof(versions
); i
++) {
1591 group
->get_item(versions
[i
][0])->SetValue(versions
[i
][1]);
1595 /* Save a GRF configuration to the given group name */
1596 static void GRFSaveConfig(IniFile
*ini
, const char *grpname
, const GRFConfig
*list
)
1598 ini
->remove (grpname
);
1599 IniGroup
*group
= ini
->get_group (grpname
);
1602 for (c
= list
; c
!= NULL
; c
= c
->next
) {
1603 /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1604 sstring
<4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH
> key
;
1605 key
.fmt ("%08X|", BSWAP32(c
->ident
.grfid
));
1606 key
.append_md5sum (c
->ident
.md5sum
);
1607 key
.append_fmt ("|%s", c
->filename
);
1609 sstring
<512> params
;
1610 GRFBuildParamList (¶ms
, c
);
1611 group
->get_item(key
.c_str())->SetValue(params
.c_str());
1615 /* Common handler for saving/loading variables to the configuration file */
1616 static void HandleSettingDescs(IniFile
*ini
, SettingDescProc
*proc
, SettingDescProcList
*proc_list
, bool basic_settings
= true, bool other_settings
= true)
1618 if (basic_settings
) {
1619 proc(ini
, (const SettingDesc
*)_misc_settings
, "misc", NULL
);
1620 #if defined(WIN32) && !defined(DEDICATED)
1621 proc(ini
, (const SettingDesc
*)_win32_settings
, "win32", NULL
);
1625 if (other_settings
) {
1626 proc(ini
, _settings
, "patches", &_settings_newgame
);
1627 proc(ini
, _currency_settings
,"currency", &_custom_currency
);
1628 proc(ini
, _company_settings
, "company", &_settings_client
.company
);
1630 #ifdef ENABLE_NETWORK
1631 proc_list(ini
, "server_bind_addresses", &_network_bind_list
);
1632 proc_list(ini
, "servers", &_network_host_list
);
1633 proc_list(ini
, "bans", &_network_ban_list
);
1634 #endif /* ENABLE_NETWORK */
1638 struct ConfigIniFile
: IniFile
{
1643 this->SaveToDisk (_config_file
);
1647 ConfigIniFile::ConfigIniFile()
1648 : IniFile (_config_file
, NO_DIRECTORY
, _list_group_names
)
1653 * Load the values from the configuration files
1654 * @param minimal Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1656 void LoadFromConfig(bool minimal
)
1660 if (!minimal
) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1662 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1663 HandleSettingDescs (&ini
, IniLoadSettings
, IniLoadSettingList
, minimal
, !minimal
);
1666 _grfconfig_newgame
= GRFLoadConfig (&ini
, "newgrf", false);
1667 _grfconfig_static
= GRFLoadConfig (&ini
, "newgrf-static", true);
1668 AILoadConfig (&ini
, "ai_players");
1669 GameLoadConfig (&ini
, "game_scripts");
1671 PrepareOldDiffCustom();
1672 IniLoadSettings (&ini
, _gameopt_settings
, "gameopt", &_settings_newgame
);
1673 HandleOldDiffCustom(NULL
);
1677 /* Display sheduled errors */
1678 extern void ScheduleErrorMessage(ErrorList
&datas
);
1679 ScheduleErrorMessage(_settings_error_list
);
1680 if (FindWindowById(WC_ERRMSG
, 0) == NULL
) ShowFirstError();
1684 /** Save the values to the configuration file */
1689 /* Remove some obsolete groups. These have all been loaded into other groups. */
1690 ini
.remove ("patches");
1691 ini
.remove ("yapf");
1692 ini
.remove ("gameopt");
1694 HandleSettingDescs (&ini
, IniSaveSettings
, IniSaveSettingList
);
1695 GRFSaveConfig (&ini
, "newgrf", _grfconfig_newgame
);
1696 GRFSaveConfig (&ini
, "newgrf-static", _grfconfig_static
);
1697 AISaveConfig (&ini
, "ai_players");
1698 GameSaveConfig (&ini
, "game_scripts");
1699 SaveVersionInConfig (&ini
);
1704 * Get the list of known NewGrf presets.
1705 * @param list[inout] Pointer to list for storing the preset names.
1707 void GetGRFPresetList(GRFPresetList
*list
)
1712 for (IniGroup::const_iterator group
= ini
.cbegin(); group
!= ini
.cend(); group
++) {
1713 if (strncmp(group
->get_name(), "preset-", 7) == 0) {
1714 *list
->Append() = xstrdup(group
->get_name() + 7);
1720 * Load a NewGRF configuration by preset-name.
1721 * @param config_name Name of the preset.
1722 * @return NewGRF configuration.
1723 * @see GetGRFPresetList
1725 GRFConfig
*LoadGRFPresetFromConfig(const char *config_name
)
1727 char *section
= (char*)alloca(strlen(config_name
) + 8);
1728 sprintf(section
, "preset-%s", config_name
);
1731 return GRFLoadConfig (&ini
, section
, false);
1735 * Save a NewGRF configuration with a preset name.
1736 * @param config_name Name of the preset.
1737 * @param config NewGRF configuration to save.
1738 * @see GetGRFPresetList
1740 void SaveGRFPresetToConfig(const char *config_name
, GRFConfig
*config
)
1742 char *section
= (char*)alloca(strlen(config_name
) + 8);
1743 sprintf(section
, "preset-%s", config_name
);
1746 GRFSaveConfig (&ini
, section
, config
);
1751 * Delete a NewGRF configuration by preset name.
1752 * @param config_name Name of the preset.
1754 void DeleteGRFPresetFromConfig(const char *config_name
)
1756 char *section
= (char*)alloca(strlen(config_name
) + 8);
1757 sprintf(section
, "preset-%s", config_name
);
1760 ini
.remove (section
);
1764 const SettingDesc
*GetSettingDescription(uint index
)
1766 if (index
>= lengthof(_settings
)) return NULL
;
1767 return &_settings
[index
];
1771 * Actually change a setting.
1772 * @param sd Description of the setting to change.
1773 * @param settings Settings structure where to look for the setting.
1774 * @param newval New value to set.
1775 * @param log Whether to log the change.
1777 static void ChangeSetting (const SettingDesc
*sd
, void *settings
, int32 newval
, bool log
)
1779 void *var
= sd
->save
.get_variable_address (settings
);
1781 int32 oldval
= (int32
)ReadValue (var
, sd
->save
.conv
);
1783 Write_ValidateSetting (var
, sd
, newval
);
1784 newval
= (int32
)ReadValue (var
, sd
->save
.conv
);
1786 if (oldval
== newval
) return;
1788 if (sd
->desc
.proc
!= NULL
&& !sd
->desc
.proc (newval
)) {
1789 WriteValue (var
, sd
->save
.conv
, (int64
)oldval
);
1793 if (log
&& (sd
->desc
.flags
& SGF_NO_NETWORK
)) {
1794 GamelogSetting (sd
->desc
.name
, oldval
, newval
);
1797 SetWindowClassesDirty (WC_GAME_OPTIONS
);
1801 * Network-safe changing of settings (server-only).
1802 * @param tile unused
1803 * @param flags operation to perform
1804 * @param p1 the index of the setting in the SettingDesc array which identifies it
1805 * @param p2 the new value for the setting
1806 * The new value is properly clamped to its minimum/maximum when setting
1807 * @param text unused
1808 * @return the cost of this operation or an error
1811 CommandCost
CmdChangeSetting(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1813 const SettingDesc
*sd
= GetSettingDescription(p1
);
1815 if (sd
== NULL
) return CMD_ERROR
;
1816 if (!sd
->save
.is_currently_valid()) return CMD_ERROR
;
1818 if (!sd
->IsEditable(true)) return CMD_ERROR
;
1820 if (flags
& DC_EXEC
) {
1821 ChangeSetting (sd
, &GetGameSettings(), p2
, true);
1824 return CommandCost();
1828 * Change one of the per-company settings.
1829 * @param tile unused
1830 * @param flags operation to perform
1831 * @param p1 the index of the setting in the _company_settings array which identifies it
1832 * @param p2 the new value for the setting
1833 * The new value is properly clamped to its minimum/maximum when setting
1834 * @param text unused
1835 * @return the cost of this operation or an error
1837 CommandCost
CmdChangeCompanySetting(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1839 if (p1
>= lengthof(_company_settings
)) return CMD_ERROR
;
1841 if (flags
& DC_EXEC
) {
1842 ChangeSetting (&_company_settings
[p1
],
1843 &Company::Get(_current_company
)->settings
,
1847 return CommandCost();
1851 * Top function to save the new value of an element of the Settings struct
1852 * @param index offset in the SettingDesc array of the Settings struct which
1853 * identifies the setting member we want to change
1854 * @param value new value of the setting
1855 * @param force_newgame force the newgame settings
1857 bool SetSettingValue(uint index
, int32 value
, bool force_newgame
)
1859 const SettingDesc
*sd
= &_settings
[index
];
1860 /* If an item is company-based, we do not send it over the network
1861 * (if any) to change. Also *hack*hack* we update the _newgame version
1862 * of settings because changing a company-based setting in a game also
1863 * changes its defaults. At least that is the convention we have chosen */
1864 if (sd
->save
.flags
& SLF_NO_NETWORK_SYNC
) {
1865 void *var
= sd
->save
.get_variable_address (&GetGameSettings());
1866 Write_ValidateSetting(var
, sd
, value
);
1868 if (_game_mode
!= GM_MENU
) {
1869 void *var2
= sd
->save
.get_variable_address (&_settings_newgame
);
1870 Write_ValidateSetting(var2
, sd
, value
);
1872 if (sd
->desc
.proc
!= NULL
) sd
->desc
.proc((int32
)ReadValue(var
, sd
->save
.conv
));
1874 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1879 if (force_newgame
) {
1880 void *var2
= sd
->save
.get_variable_address (&_settings_newgame
);
1881 Write_ValidateSetting(var2
, sd
, value
);
1885 /* send non-company-based settings over the network */
1886 if (!_networking
|| (_networking
&& _network_server
)) {
1887 return DoCommandP(0, index
, value
, CMD_CHANGE_SETTING
);
1893 * Top function to save the new value of an element of the Settings struct
1894 * @param index offset in the SettingDesc array of the CompanySettings struct
1895 * which identifies the setting member we want to change
1896 * @param value new value of the setting
1898 void SetCompanySetting(uint index
, int32 value
)
1900 const SettingDesc
*sd
= &_company_settings
[index
];
1901 if (Company::IsValidID(_local_company
) && _game_mode
!= GM_MENU
) {
1902 DoCommandP(0, index
, value
, CMD_CHANGE_COMPANY_SETTING
);
1904 void *var
= sd
->save
.get_variable_address (&_settings_client
.company
);
1905 Write_ValidateSetting(var
, sd
, value
);
1906 if (sd
->desc
.proc
!= NULL
) sd
->desc
.proc((int32
)ReadValue(var
, sd
->save
.conv
));
1911 * Set the company settings for a new company to their default values.
1913 void SetDefaultCompanySettings(CompanyID cid
)
1915 Company
*c
= Company::Get(cid
);
1916 const SettingDesc
*sd
;
1917 for (sd
= _company_settings
; sd
->save
.type
!= SL_END
; sd
++) {
1918 void *var
= sd
->save
.get_variable_address (&c
->settings
);
1919 Write_ValidateSetting(var
, sd
, (int32
)(size_t)sd
->desc
.def
);
1923 #if defined(ENABLE_NETWORK)
1925 * Sync all company settings in a multiplayer game.
1927 void SyncCompanySettings()
1929 const SettingDesc
*sd
;
1931 for (sd
= _company_settings
; sd
->save
.type
!= SL_END
; sd
++, i
++) {
1932 const void *old_var
= sd
->save
.get_variable_address (&Company::Get(_current_company
)->settings
);
1933 const void *new_var
= sd
->save
.get_variable_address (&_settings_client
.company
);
1934 uint32 old_value
= (uint32
)ReadValue(old_var
, sd
->save
.conv
);
1935 uint32 new_value
= (uint32
)ReadValue(new_var
, sd
->save
.conv
);
1936 if (old_value
!= new_value
) NetworkSendCommand(0, i
, new_value
, CMD_CHANGE_COMPANY_SETTING
, NULL
, _local_company
);
1939 #endif /* ENABLE_NETWORK */
1942 * Get the index in the _company_settings array of a setting
1943 * @param name The name of the setting
1944 * @return The index in the _company_settings array
1946 uint
GetCompanySettingIndex(const char *name
)
1949 const SettingDesc
*sd
= GetSettingFromName(name
, &i
);
1950 assert(sd
!= NULL
&& (sd
->desc
.flags
& SGF_PER_COMPANY
) != 0);
1955 * Set a setting value with a string.
1956 * @param index the settings index.
1957 * @param value the value to write
1958 * @param force_newgame force the newgame settings
1959 * @note Strings WILL NOT be synced over the network
1961 bool SetSettingValue(uint index
, const char *value
, bool force_newgame
)
1963 const SettingDesc
*sd
= &_settings
[index
];
1964 assert(sd
->save
.flags
& SLF_NO_NETWORK_SYNC
);
1965 assert(sd
->save
.type
== SL_STR
);
1967 if (sd
->save
.length
== 0) {
1968 char **var
= (char**) sd
->save
.get_variable_address ((_game_mode
== GM_MENU
|| force_newgame
) ? &_settings_newgame
: &_settings_game
);
1970 *var
= strcmp(value
, "(null)") == 0 ? NULL
: xstrdup(value
);
1972 char *var
= (char*) sd
->save
.get_variable_address();
1973 ttd_strlcpy(var
, value
, sd
->save
.length
);
1975 if (sd
->desc
.proc
!= NULL
) sd
->desc
.proc(0);
1981 * Given a name of setting, return a setting description of it.
1982 * @param name Name of the setting to return a setting description of
1983 * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
1984 * @return Pointer to the setting description of setting \a name if it can be found,
1985 * \c NULL indicates failure to obtain the description
1987 const SettingDesc
*GetSettingFromName(const char *name
, uint
*i
)
1989 const SettingDesc
*sd
;
1991 /* First check all full names */
1992 for (*i
= 0, sd
= _settings
; sd
->save
.type
!= SL_END
; sd
++, (*i
)++) {
1993 if (!sd
->save
.is_currently_valid()) continue;
1994 if (strcmp(sd
->desc
.name
, name
) == 0) return sd
;
1997 /* Then check the shortcut variant of the name. */
1998 for (*i
= 0, sd
= _settings
; sd
->save
.type
!= SL_END
; sd
++, (*i
)++) {
1999 if (!sd
->save
.is_currently_valid()) continue;
2000 const char *short_name
= strchr(sd
->desc
.name
, '.');
2001 if (short_name
!= NULL
) {
2003 if (strcmp(short_name
, name
) == 0) return sd
;
2007 if (strncmp(name
, "company.", 8) == 0) name
+= 8;
2008 /* And finally the company-based settings */
2009 for (*i
= 0, sd
= _company_settings
; sd
->save
.type
!= SL_END
; sd
++, (*i
)++) {
2010 if (!sd
->save
.is_currently_valid()) continue;
2011 if (strcmp(sd
->desc
.name
, name
) == 0) return sd
;
2017 /* Those 2 functions need to be here, else we have to make some stuff non-static
2018 * and besides, it is also better to keep stuff like this at the same place */
2019 void IConsoleSetSetting(const char *name
, const char *value
, bool force_newgame
)
2022 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2025 IConsolePrintF(CC_WARNING
, "'%s' is an unknown setting.", name
);
2030 if (sd
->desc
.cmd
== SDT_STRING
) {
2031 success
= SetSettingValue(index
, value
, force_newgame
);
2034 extern bool GetArgumentInteger(uint32
*value
, const char *arg
);
2035 success
= GetArgumentInteger(&val
, value
);
2037 IConsolePrintF(CC_ERROR
, "'%s' is not an integer.", value
);
2041 success
= SetSettingValue(index
, val
, force_newgame
);
2045 if (_network_server
) {
2046 IConsoleError("This command/variable is not available during network games.");
2048 IConsoleError("This command/variable is only available to a network server.");
2053 void IConsoleSetSetting(const char *name
, int value
)
2056 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2058 SetSettingValue(index
, value
);
2062 * Output value of a specific setting to the console
2063 * @param name Name of the setting to output its value
2064 * @param force_newgame force the newgame settings
2066 void IConsoleGetSetting(const char *name
, bool force_newgame
)
2070 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2074 IConsolePrintF(CC_WARNING
, "'%s' is an unknown setting.", name
);
2078 ptr
= sd
->save
.get_variable_address ((_game_mode
== GM_MENU
|| force_newgame
) ? &_settings_newgame
: &_settings_game
);
2080 if (sd
->desc
.cmd
== SDT_STRING
) {
2081 IConsolePrintF(CC_WARNING
, "Current value for '%s' is: '%s'", name
, (sd
->save
.length
== 0) ? *(const char * const *)ptr
: (const char *)ptr
);
2083 if (sd
->desc
.cmd
== SDT_BOOLX
) {
2084 bstrfmt (value
, (*(const bool*)ptr
!= 0) ? "on" : "off");
2086 bstrfmt (value
, sd
->desc
.min
< 0 ? "%d" : "%u", (int32
)ReadValue(ptr
, sd
->save
.conv
));
2089 IConsolePrintF(CC_WARNING
, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
2090 name
, value
, (sd
->desc
.flags
& SGF_0ISDISABLED
) ? "(0) " : "", sd
->desc
.min
, sd
->desc
.max
);
2095 * List all settings and their value to the console
2097 * @param prefilter If not \c NULL, only list settings with names that begin with \a prefilter prefix
2099 void IConsoleListSettings(const char *prefilter
)
2101 IConsolePrintF(CC_WARNING
, "All settings with their current value:");
2103 for (const SettingDesc
*sd
= _settings
; sd
->save
.type
!= SL_END
; sd
++) {
2104 if (!sd
->save
.is_currently_valid()) continue;
2105 if (prefilter
!= NULL
&& strstr(sd
->desc
.name
, prefilter
) == NULL
) continue;
2107 const void *ptr
= sd
->save
.get_variable_address (&GetGameSettings());
2109 if (sd
->desc
.cmd
== SDT_BOOLX
) {
2110 bstrfmt (value
, (*(const bool *)ptr
!= 0) ? "on" : "off");
2111 } else if (sd
->desc
.cmd
== SDT_STRING
) {
2112 bstrfmt (value
, "%s", (sd
->save
.length
== 0) ? *(const char * const *)ptr
: (const char *)ptr
);
2114 bstrfmt (value
, sd
->desc
.min
< 0 ? "%d" : "%u", (int32
)ReadValue(ptr
, sd
->save
.conv
));
2116 IConsolePrintF(CC_DEFAULT
, "%s = %s", sd
->desc
.name
, value
);
2119 IConsolePrintF(CC_WARNING
, "Use 'setting' command to change a value");
2123 * Save and load handler for settings
2124 * @param osd SettingDesc struct containing all information
2125 * @param object can be either NULL in which case we load global variables or
2126 * a pointer to a struct which is getting saved
2128 static void LoadSettings(LoadBuffer
*reader
, const SettingDesc
*osd
, void *object
)
2130 for (; osd
->save
.type
!= SL_END
; osd
++) {
2131 const SaveLoad
*sld
= &osd
->save
;
2132 if (!reader
->ReadObjectMember(object
, sld
)) continue;
2134 void *ptr
= sld
->get_variable_address (object
);
2135 if ((sld
->type
== SL_VAR
) && IsNumericType(sld
->conv
)) Write_ValidateSetting(ptr
, osd
, ReadValue(ptr
, sld
->conv
));
2140 * Save and load handler for settings
2141 * @param sd SettingDesc struct containing all information
2142 * @param object can be either NULL in which case we load global variables or
2143 * a pointer to a struct which is getting saved
2145 static void SaveSettings(SaveDumper
*dumper
, const SettingDesc
*sd
, void *object
)
2147 SaveDumper
temp(1024);
2149 for (const SettingDesc
*i
= sd
; i
->save
.type
!= SL_END
; i
++) {
2150 temp
.WriteObjectMember(object
, &i
->save
);
2153 dumper
->WriteRIFFSize(temp
.GetSize());
2157 static void Load_OPTS(LoadBuffer
*reader
)
2159 /* Copy over default setting since some might not get loaded in
2160 * a networking environment. This ensures for example that the local
2161 * autosave-frequency stays when joining a network-server */
2162 PrepareOldDiffCustom();
2163 LoadSettings(reader
, _gameopt_settings
, &_settings_game
);
2164 HandleOldDiffCustom(reader
->stv
);
2167 static void Load_PATS(LoadBuffer
*reader
)
2169 /* Copy over default setting since some might not get loaded in
2170 * a networking environment. This ensures for example that the local
2171 * currency setting stays when joining a network-server */
2172 LoadSettings(reader
, _settings
, &_settings_game
);
2175 static void Check_PATS(LoadBuffer
*reader
)
2177 LoadSettings(reader
, _settings
, &_load_check_data
.settings
);
2180 static void Save_PATS(SaveDumper
*dumper
)
2182 SaveSettings(dumper
, _settings
, &_settings_game
);
2188 * Increase old default values for pf_maxdepth and pf_maxlength
2189 * to support big networks.
2191 if (_settings_newgame
.pf
.opf
.pf_maxdepth
== 16 && _settings_newgame
.pf
.opf
.pf_maxlength
== 512) {
2192 _settings_newgame
.pf
.opf
.pf_maxdepth
= 48;
2193 _settings_newgame
.pf
.opf
.pf_maxlength
= 4096;
2197 extern const ChunkHandler _setting_chunk_handlers
[] = {
2198 { 'OPTS', NULL
, Load_OPTS
, NULL
, NULL
, CH_RIFF
},
2199 { 'PATS', Save_PATS
, Load_PATS
, NULL
, Check_PATS
, CH_RIFF
| CH_LAST
},
2202 static bool IsSignedVarMemType(VarType vt
)
2204 switch (GetVarMemType(vt
)) {