Hotfix: Conditional order comparator dropdown list was broken.
[openttd-joker.git] / src / settings.cpp
blobc2cc9efdafdaad601b07fcb98d7156427199d44a
1 /* $Id$ */
3 /*
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/>.
8 */
10 /**
11 * @file settings.cpp
12 * All actions handling saving and loading of the settings/configuration goes on in this file.
13 * The file consists of three parts:
14 * <ol>
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.
21 * </ol>
22 * @see SettingDesc
23 * @see SaveLoad
26 #include "stdafx.h"
27 #include "currency.h"
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"
35 #include "genworld.h"
36 #include "train.h"
37 #include "news_func.h"
38 #include "window_func.h"
39 #include "sound_func.h"
40 #include "company_func.h"
41 #include "rev.h"
42 #ifdef WITH_FREETYPE
43 #include "fontcache.h"
44 #endif
45 #include "textbuf_gui.h"
46 #include "rail_gui.h"
47 #include "elrail_func.h"
48 #include "error.h"
49 #include "town.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"
55 #include "gamelog.h"
56 #include "settings_func.h"
57 #include "ini_type.h"
58 #include "ai/ai_config.hpp"
59 #include "ai/ai.hpp"
60 #include "game/game_config.hpp"
61 #include "game/game.hpp"
62 #include "ship.h"
63 #include "smallmap_gui.h"
64 #include "roadveh.h"
65 #include "fios.h"
66 #include "strings_func.h"
67 #include "statusbar_gui.h"
69 #include "void_map.h"
70 #include "station_base.h"
72 #include "table/strings.h"
73 #include "table/settings.h"
75 #include "safeguards.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 char *_config_file; ///< Configuration file of OpenTTD
83 typedef std::list<ErrorMessageData> ErrorList;
84 static ErrorList _settings_error_list; ///< Errors while loading minimal settings.
87 typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
88 typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList *list);
90 static bool IsSignedVarMemType(VarType vt);
92 /**
93 * Groups in openttd.cfg that are actually lists.
95 static const char * const _list_group_names[] = {
96 "bans",
97 "newgrf",
98 "servers",
99 "server_bind_addresses",
100 NULL
104 * Find the index value of a ONEofMANY type in a string separated by |
105 * @param many full domain of values the ONEofMANY setting can have
106 * @param one the current value of the setting for which a value needs found
107 * @param onelen force calculation of the *one parameter
108 * @return the integer index of the full-list, or -1 if not found
110 static size_t LookupOneOfMany(const char *many, const char *one, size_t onelen = 0)
112 const char *s;
113 size_t idx;
115 if (onelen == 0) onelen = strlen(one);
117 /* check if it's an integer */
118 if (*one >= '0' && *one <= '9') return strtoul(one, NULL, 0);
120 idx = 0;
121 for (;;) {
122 /* find end of item */
123 s = many;
124 while (*s != '|' && *s != 0) s++;
125 if ((size_t)(s - many) == onelen && !memcmp(one, many, onelen)) return idx;
126 if (*s == 0) return (size_t)-1;
127 many = s + 1;
128 idx++;
133 * Find the set-integer value MANYofMANY type in a string
134 * @param many full domain of values the MANYofMANY setting can have
135 * @param str the current string value of the setting, each individual
136 * of separated by a whitespace,tab or | character
137 * @return the 'fully' set integer, or -1 if a set is not found
139 static size_t LookupManyOfMany(const char *many, const char *str)
141 const char *s;
142 size_t r;
143 size_t res = 0;
145 for (;;) {
146 /* skip "whitespace" */
147 while (*str == ' ' || *str == '\t' || *str == '|') str++;
148 if (*str == 0) break;
150 s = str;
151 while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
153 r = LookupOneOfMany(many, str, s - str);
154 if (r == (size_t)-1) return r;
156 SetBit(res, (uint8)r); // value found, set it
157 if (*s == 0) break;
158 str = s + 1;
160 return res;
164 * Parse an integerlist string and set each found value
165 * @param p the string to be parsed. Each element in the list is separated by a
166 * comma or a space character
167 * @param items pointer to the integerlist-array that will be filled with values
168 * @param maxitems the maximum number of elements the integerlist-array has
169 * @return returns the number of items found, or -1 on an error
171 static int ParseIntList(const char *p, int *items, int maxitems)
173 int n = 0; // number of items read so far
174 bool comma = false; // do we accept comma?
176 while (*p != '\0') {
177 switch (*p) {
178 case ',':
179 /* Do not accept multiple commas between numbers */
180 if (!comma) return -1;
181 comma = false;
182 FALLTHROUGH;
184 case ' ':
185 p++;
186 break;
188 default: {
189 if (n == maxitems) return -1; // we don't accept that many numbers
190 char *end;
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);
194 items[n++] = v;
195 p = end; // first non-number
196 comma = true; // we accept comma now
197 break;
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;
206 return n;
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)
219 int items[64];
220 int i, nitems;
222 if (str == NULL) {
223 memset(items, 0, sizeof(items));
224 nitems = nelems;
225 } else {
226 nitems = ParseIntList(str, items, lengthof(items));
227 if (nitems != nelems) return false;
230 switch (type) {
231 case SLE_VAR_BL:
232 case SLE_VAR_I8:
233 case SLE_VAR_U8:
234 for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
235 break;
237 case SLE_VAR_I16:
238 case SLE_VAR_U16:
239 for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
240 break;
242 case SLE_VAR_I32:
243 case SLE_VAR_U32:
244 for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
245 break;
247 default: NOT_REACHED();
250 return true;
254 * Convert an integer-array (intlist) to a string representation. Each value
255 * is separated by a comma or a space character
256 * @param buf output buffer where the string-representation will be stored
257 * @param last last item to write to in the output buffer
258 * @param array pointer to the integer-arrays that is read from
259 * @param nelems the number of elements the array holds.
260 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
262 static void MakeIntList(char *buf, const char *last, const void *array, int nelems, VarType type)
264 int i, v = 0;
265 const byte *p = (const byte *)array;
267 for (i = 0; i != nelems; i++) {
268 switch (type) {
269 case SLE_VAR_BL:
270 case SLE_VAR_I8: v = *(const int8 *)p; p += 1; break;
271 case SLE_VAR_U8: v = *(const uint8 *)p; p += 1; break;
272 case SLE_VAR_I16: v = *(const int16 *)p; p += 2; break;
273 case SLE_VAR_U16: v = *(const uint16 *)p; p += 2; break;
274 case SLE_VAR_I32: v = *(const int32 *)p; p += 4; break;
275 case SLE_VAR_U32: v = *(const uint32 *)p; p += 4; break;
276 default: NOT_REACHED();
278 buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
283 * Convert a ONEofMANY structure to a string representation.
284 * @param buf output buffer where the string-representation will be stored
285 * @param last last item to write to in the output buffer
286 * @param many the full-domain string of possible values
287 * @param id the value of the variable and whose string-representation must be found
289 static void MakeOneOfMany(char *buf, const char *last, const char *many, int id)
291 int orig_id = id;
293 /* Look for the id'th element */
294 while (--id >= 0) {
295 for (; *many != '|'; many++) {
296 if (*many == '\0') { // not found
297 seprintf(buf, last, "%d", orig_id);
298 return;
301 many++; // pass the |-character
304 /* copy string until next item (|) or the end of the list if this is the last one */
305 while (*many != '\0' && *many != '|' && buf < last) *buf++ = *many++;
306 *buf = '\0';
310 * Convert a MANYofMANY structure to a string representation.
311 * @param buf output buffer where the string-representation will be stored
312 * @param last last item to write to in the output buffer
313 * @param many the full-domain string of possible values
314 * @param x the value of the variable and whose string-representation must
315 * be found in the bitmasked many string
317 static void MakeManyOfMany(char *buf, const char *last, const char *many, uint32 x)
319 const char *start;
320 int i = 0;
321 bool init = true;
323 for (; x != 0; x >>= 1, i++) {
324 start = many;
325 while (*many != 0 && *many != '|') many++; // advance to the next element
327 if (HasBit(x, 0)) { // item found, copy it
328 if (!init) buf += seprintf(buf, last, "|");
329 init = false;
330 if (start == many) {
331 buf += seprintf(buf, last, "%d", i);
332 } else {
333 memcpy(buf, start, many - start);
334 buf += many - start;
338 if (*many == '|') many++;
341 *buf = '\0';
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 const void *StringToVal(const SettingDescBase *desc, const char *orig_str)
352 const char *str = orig_str == NULL ? "" : orig_str;
354 switch (desc->cmd) {
355 case SDT_NUMX: {
356 char *end;
357 size_t val = strtoul(str, &end, 0);
358 if (end == str) {
359 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
360 msg.SetDParamStr(0, str);
361 msg.SetDParamStr(1, desc->name);
362 _settings_error_list.push_back(msg);
363 return desc->def;
365 if (*end != '\0') {
366 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_TRAILING_CHARACTERS);
367 msg.SetDParamStr(0, desc->name);
368 _settings_error_list.push_back(msg);
370 return (void*)val;
373 case SDT_ONEOFMANY: {
374 size_t r = LookupOneOfMany(desc->many, str);
375 /* if the first attempt of conversion from string to the appropriate value fails,
376 * look if we have defined a converter from old value to new value. */
377 if (r == (size_t)-1 && desc->proc_cnvt != NULL) r = desc->proc_cnvt(str);
378 if (r != (size_t)-1) return (void*)r; // and here goes converted value
380 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
381 msg.SetDParamStr(0, str);
382 msg.SetDParamStr(1, desc->name);
383 _settings_error_list.push_back(msg);
384 return desc->def;
387 case SDT_MANYOFMANY: {
388 size_t r = LookupManyOfMany(desc->many, str);
389 if (r != (size_t)-1) return (void*)r;
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 desc->def;
397 case SDT_BOOLX: {
398 if (strcmp(str, "true") == 0 || strcmp(str, "on") == 0 || strcmp(str, "1") == 0) return (void*)true;
399 if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return (void*)false;
401 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
402 msg.SetDParamStr(0, str);
403 msg.SetDParamStr(1, desc->name);
404 _settings_error_list.push_back(msg);
405 return desc->def;
408 case SDT_STRING: return orig_str;
409 case SDT_INTLIST: return str;
410 default: break;
413 return NULL;
417 * Set the value of a setting and if needed clamp the value to
418 * the preset minimum and maximum.
419 * @param ptr the variable itself
420 * @param sd pointer to the 'information'-database of the variable
421 * @param val signed long version of the new value
422 * @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
423 * SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now
425 static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
427 const SettingDescBase *sdb = &sd->desc;
429 if (sdb->cmd != SDT_BOOLX &&
430 sdb->cmd != SDT_NUMX &&
431 sdb->cmd != SDT_ONEOFMANY &&
432 sdb->cmd != SDT_MANYOFMANY) {
433 return;
436 /* We cannot know the maximum value of a bitset variable, so just have faith */
437 if (sdb->cmd != SDT_MANYOFMANY) {
438 /* We need to take special care of the uint32 type as we receive from the function
439 * a signed integer. While here also bail out on 64-bit settings as those are not
440 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
441 * 32-bit variable
442 * TODO: Support 64-bit settings/variables */
443 switch (GetVarMemType(sd->save.conv)) {
444 case SLE_VAR_NULL: return;
445 case SLE_VAR_BL:
446 case SLE_VAR_I8:
447 case SLE_VAR_U8:
448 case SLE_VAR_I16:
449 case SLE_VAR_U16:
450 case SLE_VAR_I32: {
451 /* Override the minimum value. No value below sdb->min, except special value 0 */
452 if (!(sdb->flags & SGF_0ISDISABLED) || val != 0) val = Clamp(val, sdb->min, sdb->max);
453 break;
455 case SLE_VAR_U32: {
456 /* Override the minimum value. No value below sdb->min, except special value 0 */
457 uint min = ((sdb->flags & SGF_0ISDISABLED) && (uint)val <= (uint)sdb->min) ? 0 : sdb->min;
458 WriteValue(ptr, SLE_VAR_U32, (int64)ClampU(val, min, sdb->max));
459 return;
461 case SLE_VAR_I64:
462 case SLE_VAR_U64:
463 default: NOT_REACHED();
467 WriteValue(ptr, sd->save.conv, (int64)val);
471 * Load values from a group of an IniFile structure into the internal representation
472 * @param ini pointer to IniFile structure that holds administrative information
473 * @param sd pointer to SettingDesc structure whose internally pointed variables will
474 * be given values
475 * @param grpname the group of the IniFile to search in for the new values
476 * @param object pointer to the object been loaded
478 static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
480 IniGroup *group;
481 IniGroup *group_def = ini->GetGroup(grpname);
482 IniItem *item;
483 const void *p;
484 void *ptr;
485 const char *s;
487 for (; sd->save.cmd != SL_END; sd++) {
488 const SettingDescBase *sdb = &sd->desc;
489 const SaveLoad *sld = &sd->save;
491 if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
493 /* For settings.xx.yy load the settings from [xx] yy = ? */
494 s = strchr(sdb->name, '.');
495 if (s != NULL) {
496 group = ini->GetGroup(sdb->name, s - sdb->name);
497 s++;
498 } else {
499 s = sdb->name;
500 group = group_def;
503 item = group->GetItem(s, false);
504 if (item == NULL && group != group_def) {
505 /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
506 * did not exist (e.g. loading old config files with a [settings] section */
507 item = group_def->GetItem(s, false);
509 if (item == NULL) {
510 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
511 * did not exist (e.g. loading old config files with a [yapf] section */
512 const char *sc = strchr(s, '.');
513 if (sc != NULL) item = ini->GetGroup(s, sc - s)->GetItem(sc + 1, false);
516 p = (item == NULL) ? sdb->def : StringToVal(sdb, item->value);
517 ptr = GetVariableAddress(object, sld);
519 switch (sdb->cmd) {
520 case SDT_BOOLX: // All four are various types of (integer) numbers
521 case SDT_NUMX:
522 case SDT_ONEOFMANY:
523 case SDT_MANYOFMANY:
524 Write_ValidateSetting(ptr, sd, (int32)(size_t)p);
525 break;
527 case SDT_STRING:
528 switch (GetVarMemType(sld->conv)) {
529 case SLE_VAR_STRB:
530 case SLE_VAR_STRBQ:
531 if (p != NULL) strecpy((char*)ptr, (const char*)p, (char*)ptr + sld->length - 1);
532 break;
534 case SLE_VAR_STR:
535 case SLE_VAR_STRQ:
536 free(*(char**)ptr);
537 *(char**)ptr = p == NULL ? NULL : stredup((const char*)p);
538 break;
540 case SLE_VAR_CHAR: if (p != NULL) *(char *)ptr = *(const char *)p; break;
542 default: NOT_REACHED();
544 break;
546 case SDT_INTLIST: {
547 if (!LoadIntList((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) {
548 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY);
549 msg.SetDParamStr(0, sdb->name);
550 _settings_error_list.push_back(msg);
552 /* Use default */
553 LoadIntList((const char*)sdb->def, ptr, sld->length, GetVarMemType(sld->conv));
554 } else if (sd->desc.proc_cnvt != NULL) {
555 sd->desc.proc_cnvt((const char*)p);
557 break;
559 default: NOT_REACHED();
565 * Save the values of settings to the inifile.
566 * @param ini pointer to IniFile structure
567 * @param sd read-only SettingDesc structure which contains the unmodified,
568 * loaded values of the configuration file and various information about it
569 * @param grpname holds the name of the group (eg. [network]) where these will be saved
570 * @param object pointer to the object been saved
571 * The function works as follows: for each item in the SettingDesc structure we
572 * have a look if the value has changed since we started the game (the original
573 * values are reloaded when saving). If settings indeed have changed, we get
574 * these and save them.
576 static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
578 IniGroup *group_def = NULL, *group;
579 IniItem *item;
580 char buf[512];
581 const char *s;
582 void *ptr;
584 for (; sd->save.cmd != SL_END; sd++) {
585 const SettingDescBase *sdb = &sd->desc;
586 const SaveLoad *sld = &sd->save;
588 /* If the setting is not saved to the configuration
589 * file, just continue with the next setting */
590 if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
591 if (sld->conv & SLF_NOT_IN_CONFIG) continue;
593 /* XXX - wtf is this?? (group override?) */
594 s = strchr(sdb->name, '.');
595 if (s != NULL) {
596 group = ini->GetGroup(sdb->name, s - sdb->name);
597 s++;
598 } else {
599 if (group_def == NULL) group_def = ini->GetGroup(grpname);
600 s = sdb->name;
601 group = group_def;
604 item = group->GetItem(s, true);
605 ptr = GetVariableAddress(object, sld);
607 if (item->value != NULL) {
608 /* check if the value is the same as the old value */
609 const void *p = StringToVal(sdb, item->value);
611 /* The main type of a variable/setting is in bytes 8-15
612 * The subtype (what kind of numbers do we have there) is in 0-7 */
613 switch (sdb->cmd) {
614 case SDT_BOOLX:
615 case SDT_NUMX:
616 case SDT_ONEOFMANY:
617 case SDT_MANYOFMANY:
618 switch (GetVarMemType(sld->conv)) {
619 case SLE_VAR_BL:
620 if (*(bool*)ptr == (p != NULL)) continue;
621 break;
623 case SLE_VAR_I8:
624 case SLE_VAR_U8:
625 if (*(byte*)ptr == (byte)(size_t)p) continue;
626 break;
628 case SLE_VAR_I16:
629 case SLE_VAR_U16:
630 if (*(uint16*)ptr == (uint16)(size_t)p) continue;
631 break;
633 case SLE_VAR_I32:
634 case SLE_VAR_U32:
635 if (*(uint32*)ptr == (uint32)(size_t)p) continue;
636 break;
638 default: NOT_REACHED();
640 break;
642 default: break; // Assume the other types are always changed
646 /* Value has changed, get the new value and put it into a buffer */
647 switch (sdb->cmd) {
648 case SDT_BOOLX:
649 case SDT_NUMX:
650 case SDT_ONEOFMANY:
651 case SDT_MANYOFMANY: {
652 uint32 i = (uint32)ReadValue(ptr, sld->conv);
654 switch (sdb->cmd) {
655 case SDT_BOOLX: strecpy(buf, (i != 0) ? "true" : "false", lastof(buf)); break;
656 case SDT_NUMX: seprintf(buf, lastof(buf), IsSignedVarMemType(sld->conv) ? "%d" : "%u", i); break;
657 case SDT_ONEOFMANY: MakeOneOfMany(buf, lastof(buf), sdb->many, i); break;
658 case SDT_MANYOFMANY: MakeManyOfMany(buf, lastof(buf), sdb->many, i); break;
659 default: NOT_REACHED();
661 break;
664 case SDT_STRING:
665 switch (GetVarMemType(sld->conv)) {
666 case SLE_VAR_STRB: strecpy(buf, (char*)ptr, lastof(buf)); break;
667 case SLE_VAR_STRBQ:seprintf(buf, lastof(buf), "\"%s\"", (char*)ptr); break;
668 case SLE_VAR_STR: strecpy(buf, *(char**)ptr, lastof(buf)); break;
670 case SLE_VAR_STRQ:
671 if (*(char**)ptr == NULL) {
672 buf[0] = '\0';
673 } else {
674 seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
676 break;
678 case SLE_VAR_CHAR: buf[0] = *(char*)ptr; buf[1] = '\0'; break;
679 default: NOT_REACHED();
681 break;
683 case SDT_INTLIST:
684 MakeIntList(buf, lastof(buf), ptr, sld->length, GetVarMemType(sld->conv));
685 break;
687 default: NOT_REACHED();
690 /* The value is different, that means we have to write it to the ini */
691 free(item->value);
692 item->value = stredup(buf);
697 * Loads all items from a 'grpname' section into a list
698 * The list parameter can be a NULL pointer, in this case nothing will be
699 * saved and a callback function should be defined that will take over the
700 * list-handling and store the data itself somewhere.
701 * @param ini IniFile handle to the ini file with the source data
702 * @param grpname character string identifying the section-header of the ini file that will be parsed
703 * @param list new list with entries of the given section
705 static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *list)
707 IniGroup *group = ini->GetGroup(grpname);
709 if (group == NULL || list == NULL) return;
711 list->Clear();
713 for (const IniItem *item = group->item; item != NULL; item = item->next) {
714 if (item->name != NULL) *list->Append() = stredup(item->name);
719 * Saves all items from a list into the 'grpname' section
720 * The list parameter can be a NULL pointer, in this case a callback function
721 * should be defined that will provide the source data to be saved.
722 * @param ini IniFile handle to the ini file where the destination data is saved
723 * @param grpname character string identifying the section-header of the ini file
724 * @param list pointer to an string(pointer) array that will be used as the
725 * source to be saved into the relevant ini section
727 static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *list)
729 IniGroup *group = ini->GetGroup(grpname);
731 if (group == NULL || list == NULL) return;
732 group->Clear();
734 for (char **iter = list->Begin(); iter != list->End(); iter++) {
735 group->GetItem(*iter, true)->SetValue("");
740 * Load a WindowDesc from config.
741 * @param ini IniFile handle to the ini file with the source data
742 * @param grpname character string identifying the section-header of the ini file that will be parsed
743 * @param desc Destination WindowDesc
745 void IniLoadWindowSettings(IniFile *ini, const char *grpname, void *desc)
747 IniLoadSettings(ini, _window_settings, grpname, desc);
751 * Save a WindowDesc to config.
752 * @param ini IniFile handle to the ini file where the destination data is saved
753 * @param grpname character string identifying the section-header of the ini file
754 * @param desc Source WindowDesc
756 void IniSaveWindowSettings(IniFile *ini, const char *grpname, void *desc)
758 IniSaveSettings(ini, _window_settings, grpname, desc);
762 * Check whether the setting is editable in the current gamemode.
763 * @param do_command true if this is about checking a command from the server.
764 * @return true if editable.
766 bool SettingDesc::IsEditable(bool do_command) const
768 if (!do_command && !(this->save.conv & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(this->desc.flags & SGF_PER_COMPANY)) return false;
769 if ((this->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return false;
770 if ((this->desc.flags & SGF_NO_NETWORK) && _networking) return false;
771 if ((this->desc.flags & SGF_NEWGAME_ONLY) &&
772 (_game_mode == GM_NORMAL ||
773 (_game_mode == GM_EDITOR && !(this->desc.flags & SGF_SCENEDIT_TOO)))) return false;
774 return true;
778 * Return the type of the setting.
779 * @return type of setting
781 SettingType SettingDesc::GetType() const
783 if (this->desc.flags & SGF_PER_COMPANY) return ST_COMPANY;
784 return (this->save.conv & SLF_NOT_IN_SAVE) ? ST_CLIENT : ST_GAME;
787 /* Begin - Callback Functions for the various settings. */
789 /** Reposition the main toolbar as the setting changed. */
790 static bool v_PositionMainToolbar(int32 p1)
792 if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
793 return true;
796 /** Reposition the statusbar as the setting changed. */
797 static bool v_PositionStatusbar(int32 p1)
799 if (_game_mode != GM_MENU) {
800 PositionStatusbar(NULL);
801 PositionNewsMessage(NULL);
802 PositionNetworkChatWindow(NULL);
804 return true;
807 static bool PopulationInLabelActive(int32 p1)
809 UpdateAllTownVirtCoords();
810 return true;
813 static bool RedrawScreen(int32 p1)
815 MarkWholeScreenDirty();
816 return true;
820 * Redraw the smallmap after a colour scheme change.
821 * @param p1 Callback parameter.
822 * @return Always true.
824 static bool RedrawSmallmap(int32 p1)
826 BuildLandLegend();
827 BuildOwnerLegend();
828 SetWindowClassesDirty(WC_SMALLMAP);
829 return true;
832 static bool InvalidateDetailsWindow(int32 p1)
834 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
835 return true;
838 static bool StationSpreadChanged(int32 p1)
840 InvalidateWindowData(WC_SELECT_STATION, 0);
841 InvalidateWindowData(WC_BUILD_STATION, 0);
842 return true;
845 static bool InvalidateBuildIndustryWindow(int32 p1)
847 InvalidateWindowData(WC_BUILD_INDUSTRY, 0);
848 return true;
851 static bool CloseSignalGUI(int32 p1)
853 if (p1 == 0) {
854 DeleteWindowByClass(WC_BUILD_SIGNAL);
856 return true;
859 static bool InvalidateTownViewWindow(int32 p1)
861 InvalidateWindowClassesData(WC_TOWN_VIEW, p1);
862 return true;
865 static bool DeleteSelectStationWindow(int32 p1)
867 DeleteWindowById(WC_SELECT_STATION, 0);
868 return true;
871 static bool UpdateConsists(int32 p1)
873 Train *t;
874 FOR_ALL_TRAINS(t) {
875 /* Update the consist of all trains so the maximum speed is set correctly. */
876 if (t->IsFrontEngine() || t->IsFreeWagon()) t->ConsistChanged(CCF_TRACK);
878 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
879 return true;
882 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
883 static bool CheckInterval(int32 p1)
885 bool update_vehicles;
886 VehicleDefaultSettings *vds;
887 if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
888 vds = &_settings_client.company.vehicle;
889 update_vehicles = false;
890 } else {
891 vds = &Company::Get(_current_company)->settings.vehicle;
892 update_vehicles = true;
895 if (p1 != 0) {
896 vds->servint_trains = 50;
897 vds->servint_roadveh = 50;
898 vds->servint_aircraft = 50;
899 vds->servint_ships = 50;
900 } else {
901 vds->servint_trains = 150;
902 vds->servint_roadveh = 150;
903 vds->servint_aircraft = 100;
904 vds->servint_ships = 360;
907 if (update_vehicles) {
908 const Company *c = Company::Get(_current_company);
909 Vehicle *v;
910 FOR_ALL_VEHICLES(v) {
911 if (v->owner == _current_company && v->IsPrimaryVehicle() && !v->ServiceIntervalIsCustom()) {
912 v->SetServiceInterval(CompanyServiceInterval(c, v->type));
913 v->SetServiceIntervalIsPercent(p1 != 0);
918 InvalidateDetailsWindow(0);
920 return true;
923 static bool UpdateInterval(VehicleType type, int32 p1)
925 bool update_vehicles;
926 VehicleDefaultSettings *vds;
927 if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
928 vds = &_settings_client.company.vehicle;
929 update_vehicles = false;
930 } else {
931 vds = &Company::Get(_current_company)->settings.vehicle;
932 update_vehicles = true;
935 /* Test if the interval is valid */
936 uint16 interval = GetServiceIntervalClamped(p1, vds->servint_ispercent);
937 if (interval != p1) return false;
939 if (update_vehicles) {
940 Vehicle *v;
941 FOR_ALL_VEHICLES(v) {
942 if (v->owner == _current_company && v->type == type && v->IsPrimaryVehicle() && !v->ServiceIntervalIsCustom()) {
943 v->SetServiceInterval(p1);
948 InvalidateDetailsWindow(0);
950 return true;
953 static bool UpdateIntervalTrains(int32 p1)
955 return UpdateInterval(VEH_TRAIN, p1);
958 static bool UpdateIntervalRoadVeh(int32 p1)
960 return UpdateInterval(VEH_ROAD, p1);
963 static bool UpdateIntervalShips(int32 p1)
965 return UpdateInterval(VEH_SHIP, p1);
968 static bool UpdateIntervalAircraft(int32 p1)
970 return UpdateInterval(VEH_AIRCRAFT, p1);
973 static bool TrainAccelerationModelChanged(int32 p1)
975 Train *t;
976 FOR_ALL_TRAINS(t) {
977 if (t->IsFrontEngine()) {
978 t->tcache.cached_max_curve_speed = t->GetCurveSpeedLimit();
979 t->UpdateAcceleration();
983 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
984 SetWindowClassesDirty(WC_ENGINE_PREVIEW);
985 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
986 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
988 return true;
992 * This function updates the train acceleration cache after a steepness change.
993 * @param p1 Callback parameter.
994 * @return Always true.
996 static bool TrainSlopeSteepnessChanged(int32 p1)
998 Train *t;
999 FOR_ALL_TRAINS(t) {
1000 if (t->IsFrontEngine()) t->CargoChanged();
1003 return true;
1007 * This function updates realistic acceleration caches when the setting "Road vehicle acceleration model" is set.
1008 * @param p1 Callback parameter
1009 * @return Always true
1011 static bool RoadVehAccelerationModelChanged(int32 p1)
1013 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
1014 RoadVehicle *rv;
1015 FOR_ALL_ROADVEHICLES(rv) {
1016 if (rv->IsFrontEngine()) {
1017 rv->CargoChanged();
1022 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1023 SetWindowClassesDirty(WC_ENGINE_PREVIEW);
1024 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
1025 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
1027 return true;
1031 * This function updates the road vehicle acceleration cache after a steepness change.
1032 * @param p1 Callback parameter.
1033 * @return Always true.
1035 static bool RoadVehSlopeSteepnessChanged(int32 p1)
1037 RoadVehicle *rv;
1038 FOR_ALL_ROADVEHICLES(rv) {
1039 if (rv->IsFrontEngine()) rv->CargoChanged();
1042 return true;
1045 static bool DragSignalsDensityChanged(int32)
1047 InvalidateWindowData(WC_BUILD_SIGNAL, 0);
1049 return true;
1052 static bool TownFoundingChanged(int32 p1)
1054 if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
1055 DeleteWindowById(WC_FOUND_TOWN, 0);
1056 return true;
1058 InvalidateWindowData(WC_FOUND_TOWN, 0);
1059 return true;
1062 static bool InvalidateVehTimetableWindow(int32 p1)
1064 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE, VIWD_MODIFY_ORDERS);
1065 return true;
1068 static bool InvalidateTicksPerMinute(int32 p1)
1070 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE, VIWD_MODIFY_ORDERS);
1071 InvalidateWindowClassesData(WC_TRAINS_LIST);
1072 InvalidateWindowClassesData(WC_ROADVEH_LIST);
1073 InvalidateWindowClassesData(WC_SHIPS_LIST);
1074 InvalidateWindowClassesData(WC_AIRCRAFT_LIST);
1075 InvalidateWindowClassesData(WC_DEPARTURES_BOARD);
1076 InvalidateWindowClassesData(WC_STATUS_BAR, SBI_TICKS_PER_MINUTE);
1077 InvalidateWindowClassesData(WC_VEHICLE_TRIP_HISTORY);
1079 return true;
1082 static bool ZoomMinMaxChanged(int32 p1)
1084 extern void ConstrainAllViewportsZoom();
1085 extern void UpdateFontHeightCache();
1086 ConstrainAllViewportsZoom();
1087 GfxClearSpriteCache();
1088 if (_settings_client.gui.zoom_min > _gui_zoom) {
1089 /* Restrict GUI zoom if it is no longer available. */
1090 _gui_zoom = _settings_client.gui.zoom_min;
1091 UpdateCursorSize();
1092 UpdateFontHeightCache();
1093 LoadStringWidthTable();
1095 return true;
1099 * Update any possible saveload window and delete any newgrf dialogue as
1100 * its widget parts might change. Reinit all windows as it allows access to the
1101 * newgrf debug button.
1102 * @param p1 unused.
1103 * @return Always true.
1105 static bool InvalidateNewGRFChangeWindows(int32 p1)
1107 InvalidateWindowClassesData(WC_SAVELOAD);
1108 DeleteWindowByClass(WC_GAME_OPTIONS);
1109 ReInitAllWindows();
1110 return true;
1113 static bool InvalidateCompanyLiveryWindow(int32 p1)
1115 InvalidateWindowClassesData(WC_COMPANY_COLOUR);
1116 return RedrawScreen(p1);
1119 static bool InvalidateIndustryViewWindow(int32 p1)
1121 InvalidateWindowClassesData(WC_INDUSTRY_VIEW);
1122 return true;
1125 static bool InvalidateAISettingsWindow(int32 p1)
1127 InvalidateWindowClassesData(WC_AI_SETTINGS);
1128 return true;
1132 * Update the town authority window after a town authority setting change.
1133 * @param p1 Unused.
1134 * @return Always true.
1136 static bool RedrawTownAuthority(int32 p1)
1138 SetWindowClassesDirty(WC_TOWN_AUTHORITY);
1139 return true;
1143 * Invalidate the company infrastructure details window after a infrastructure maintenance setting change.
1144 * @param p1 Unused.
1145 * @return Always true.
1147 static bool InvalidateCompanyInfrastructureWindow(int32 p1)
1149 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
1150 return true;
1154 * Invalidate the company details window after the shares setting changed.
1155 * @param p1 Unused.
1156 * @return Always true.
1158 static bool InvalidateCompanyWindow(int32 p1)
1160 InvalidateWindowClassesData(WC_COMPANY);
1161 return true;
1164 static bool SimulatedWormholeSignalsChanged(int32 p1)
1166 extern void AfterLoadCompanyStats();
1167 AfterLoadCompanyStats();
1168 MarkWholeScreenDirty();
1169 return true;
1172 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
1173 static void ValidateSettings()
1175 /* Do not allow a custom sea level with the original land generator. */
1176 if (_settings_newgame.game_creation.land_generator == LG_ORIGINAL &&
1177 _settings_newgame.difficulty.quantity_sea_lakes == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) {
1178 _settings_newgame.difficulty.quantity_sea_lakes = CUSTOM_SEA_LEVEL_MIN_PERCENTAGE;
1182 static bool DifficultyNoiseChange(int32 i)
1184 if (_game_mode == GM_NORMAL) {
1185 UpdateAirportsNoise();
1186 if (_settings_game.economy.station_noise_level) {
1187 InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
1191 return true;
1194 static bool MaxNoAIsChange(int32 i)
1196 if (GetGameSettings().difficulty.max_no_competitors != 0 &&
1197 AI::GetInfoList()->size() == 0 &&
1198 (!_networking || _network_server)) {
1199 ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, WL_CRITICAL);
1202 return true;
1206 * Check whether the road side may be changed.
1207 * @param p1 unused
1208 * @return true if the road side may be changed.
1210 static bool CheckRoadSide(int p1)
1212 extern bool RoadVehiclesAreBuilt();
1213 return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
1217 * Conversion callback for _gameopt_settings_game.landscape
1218 * It converts (or try) between old values and the new ones,
1219 * without losing initial setting of the user
1220 * @param value that was read from config file
1221 * @return the "hopefully" converted value
1223 static size_t ConvertLandscape(const char *value)
1225 /* try with the old values */
1226 return LookupOneOfMany("normal|hilly|desert|candy", value);
1229 static bool CheckFreeformEdges(int32 p1)
1231 if (_game_mode == GM_MENU) return true;
1232 if (p1 != 0) {
1233 Ship *s;
1234 FOR_ALL_SHIPS(s) {
1235 /* Check if there is a ship on the northern border. */
1236 if (TileX(s->tile) == 0 || TileY(s->tile) == 0) {
1237 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
1238 return false;
1241 BaseStation *st;
1242 FOR_ALL_BASE_STATIONS(st) {
1243 /* Check if there is a non-deleted buoy on the northern border. */
1244 if (st->IsInUse() && (TileX(st->xy) == 0 || TileY(st->xy) == 0)) {
1245 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
1246 return false;
1249 for (uint i = 0; i < MapSizeX(); i++) MakeVoid(TileXY(i, 0));
1250 for (uint i = 0; i < MapSizeY(); i++) MakeVoid(TileXY(0, i));
1251 } else {
1252 for (uint i = 0; i < MapMaxX(); i++) {
1253 if (TileHeight(TileXY(i, 1)) != 0) {
1254 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1255 return false;
1258 for (uint i = 1; i < MapMaxX(); i++) {
1259 if (!IsTileType(TileXY(i, MapMaxY() - 1), MP_WATER) || TileHeight(TileXY(1, MapMaxY())) != 0) {
1260 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1261 return false;
1264 for (uint i = 0; i < MapMaxY(); i++) {
1265 if (TileHeight(TileXY(1, i)) != 0) {
1266 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1267 return false;
1270 for (uint i = 1; i < MapMaxY(); i++) {
1271 if (!IsTileType(TileXY(MapMaxX() - 1, i), MP_WATER) || TileHeight(TileXY(MapMaxX(), i)) != 0) {
1272 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1273 return false;
1276 /* Make tiles at the border water again. */
1277 for (uint i = 0; i < MapMaxX(); i++) {
1278 SetTileHeight(TileXY(i, 0), 0);
1279 MakeSea(TileXY(i, 0));
1281 for (uint i = 0; i < MapMaxY(); i++) {
1282 SetTileHeight(TileXY(0, i), 0);
1283 MakeSea(TileXY(0, i));
1286 MarkWholeScreenDirty();
1287 return true;
1291 * Changing the setting "allow multiple NewGRF sets" is not allowed
1292 * if there are vehicles.
1294 static bool ChangeDynamicEngines(int32 p1)
1296 if (_game_mode == GM_MENU) return true;
1298 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
1299 ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, WL_ERROR);
1300 return false;
1303 return true;
1306 static bool ChangeMaxHeightLevel(int32 p1)
1308 if (_game_mode == GM_NORMAL) return false;
1309 if (_game_mode != GM_EDITOR) return true;
1311 /* Check if at least one mountain on the map is higher than the new value.
1312 * If yes, disallow the change. */
1313 for (TileIndex t = 0; t < MapSize(); t++) {
1314 if ((int32)TileHeight(t) > p1) {
1315 ShowErrorMessage(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN, INVALID_STRING_ID, WL_ERROR);
1316 /* Return old, unchanged value */
1317 return false;
1321 /* The smallmap uses an index from heightlevels to colours. Trigger rebuilding it. */
1322 InvalidateWindowClassesData(WC_SMALLMAP, 2);
1324 return true;
1327 static bool StationCatchmentChanged(int32 p1)
1329 Station::RecomputeIndustriesNearForAll();
1330 return true;
1333 static bool MaxVehiclesChanged(int32 p1)
1335 InvalidateWindowClassesData(WC_BUILD_TOOLBAR);
1336 MarkWholeScreenDirty();
1337 return true;
1341 #ifdef ENABLE_NETWORK
1343 static bool UpdateClientName(int32 p1)
1345 NetworkUpdateClientName();
1346 return true;
1349 static bool UpdateServerPassword(int32 p1)
1351 if (strcmp(_settings_client.network.server_password, "*") == 0) {
1352 _settings_client.network.server_password[0] = '\0';
1355 return true;
1358 static bool UpdateRconPassword(int32 p1)
1360 if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
1361 _settings_client.network.rcon_password[0] = '\0';
1364 return true;
1367 static bool UpdateClientConfigValues(int32 p1)
1369 if (_network_server) NetworkServerSendConfigUpdate();
1371 return true;
1374 #endif /* ENABLE_NETWORK */
1377 /* End - Callback Functions */
1380 * Prepare for reading and old diff_custom by zero-ing the memory.
1382 static void PrepareOldDiffCustom()
1384 memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
1388 * Reading of the old diff_custom array and transforming it to the new format.
1389 * @param savegame is it read from the config or savegame. In the latter case
1390 * we are sure there is an array; in the former case we have
1391 * to check that.
1393 static void HandleOldDiffCustom(bool savegame)
1395 uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && IsSavegameVersionBefore(4)) ? 1 : 0);
1397 if (!savegame) {
1398 /* If we did read to old_diff_custom, then at least one value must be non 0. */
1399 bool old_diff_custom_used = false;
1400 for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
1401 old_diff_custom_used = (_old_diff_custom[i] != 0);
1404 if (!old_diff_custom_used) return;
1407 for (uint i = 0; i < options_to_load; i++) {
1408 const SettingDesc *sd = &_settings[i];
1409 /* Skip deprecated options */
1410 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1411 void *var = GetVariableAddress(savegame ? &_settings_game : &_settings_newgame, &sd->save);
1412 Write_ValidateSetting(var, sd, (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]));
1416 static void AILoadConfig(IniFile *ini, const char *grpname)
1418 IniGroup *group = ini->GetGroup(grpname);
1419 IniItem *item;
1421 /* Clean any configured AI */
1422 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1423 AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME)->Change(NULL);
1426 /* If no group exists, return */
1427 if (group == NULL) return;
1429 CompanyID c = COMPANY_FIRST;
1430 for (item = group->item; c < MAX_COMPANIES && item != NULL; c++, item = item->next) {
1431 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1433 config->Change(item->name);
1434 if (!config->HasScript()) {
1435 if (strcmp(item->name, "none") != 0) {
1436 DEBUG(script, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item->name);
1437 continue;
1440 if (item->value != NULL) config->StringToSettings(item->value);
1444 static void GameLoadConfig(IniFile *ini, const char *grpname)
1446 IniGroup *group = ini->GetGroup(grpname);
1447 IniItem *item;
1449 /* Clean any configured GameScript */
1450 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME)->Change(NULL);
1452 /* If no group exists, return */
1453 if (group == NULL) return;
1455 item = group->item;
1456 if (item == NULL) return;
1458 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1460 config->Change(item->name);
1461 if (!config->HasScript()) {
1462 if (strcmp(item->name, "none") != 0) {
1463 DEBUG(script, 0, "The GameScript by the name '%s' was no longer found, and removed from the list.", item->name);
1464 return;
1467 if (item->value != NULL) config->StringToSettings(item->value);
1471 * Convert a character to a hex nibble value, or \c -1 otherwise.
1472 * @param c Character to convert.
1473 * @return Hex value of the character, or \c -1 if not a hex digit.
1475 static int DecodeHexNibble(char c)
1477 if (c >= '0' && c <= '9') return c - '0';
1478 if (c >= 'A' && c <= 'F') return c + 10 - 'A';
1479 if (c >= 'a' && c <= 'f') return c + 10 - 'a';
1480 return -1;
1484 * Parse a sequence of characters (supposedly hex digits) into a sequence of bytes.
1485 * After the hex number should be a \c '|' character.
1486 * @param pos First character to convert.
1487 * @param dest [out] Output byte array to write the bytes.
1488 * @param dest_size Number of bytes in \a dest.
1489 * @return Whether reading was successful.
1491 static bool DecodeHexText(char *pos, uint8 *dest, size_t dest_size)
1493 while (dest_size > 0) {
1494 int hi = DecodeHexNibble(pos[0]);
1495 int lo = (hi >= 0) ? DecodeHexNibble(pos[1]) : -1;
1496 if (lo < 0) return false;
1497 *dest++ = (hi << 4) | lo;
1498 pos += 2;
1499 dest_size--;
1501 return *pos == '|';
1505 * Load a GRF configuration
1506 * @param ini The configuration to read from.
1507 * @param grpname Group name containing the configuration of the GRF.
1508 * @param is_static GRF is static.
1510 static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
1512 IniGroup *group = ini->GetGroup(grpname);
1513 IniItem *item;
1514 GRFConfig *first = NULL;
1515 GRFConfig **curr = &first;
1517 if (group == NULL) return NULL;
1519 for (item = group->item; item != NULL; item = item->next) {
1520 GRFConfig *c = NULL;
1522 uint8 grfid_buf[4], md5sum[16];
1523 char *filename = item->name;
1524 bool has_grfid = false;
1525 bool has_md5sum = false;
1527 /* Try reading "<grfid>|" and on success, "<md5sum>|". */
1528 has_grfid = DecodeHexText(filename, grfid_buf, lengthof(grfid_buf));
1529 if (has_grfid) {
1530 filename += 1 + 2 * lengthof(grfid_buf);
1531 has_md5sum = DecodeHexText(filename, md5sum, lengthof(md5sum));
1532 if (has_md5sum) filename += 1 + 2 * lengthof(md5sum);
1534 uint32 grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
1535 if (has_md5sum) {
1536 const GRFConfig *s = FindGRFConfig(grfid, FGCM_EXACT, md5sum);
1537 if (s != NULL) c = new GRFConfig(*s);
1539 if (c == NULL && !FioCheckFileExists(filename, NEWGRF_DIR)) {
1540 const GRFConfig *s = FindGRFConfig(grfid, FGCM_NEWEST_VALID);
1541 if (s != NULL) c = new GRFConfig(*s);
1544 if (c == NULL) c = new GRFConfig(filename);
1546 /* Parse parameters */
1547 if (!StrEmpty(item->value)) {
1548 int count = ParseIntList(item->value, (int*)c->param, lengthof(c->param));
1549 if (count < 0) {
1550 SetDParamStr(0, filename);
1551 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY, WL_CRITICAL);
1552 count = 0;
1554 c->num_params = count;
1557 /* Check if item is valid */
1558 if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
1559 if (c->status == GCS_NOT_FOUND) {
1560 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND);
1561 } else if (HasBit(c->flags, GCF_UNSAFE)) {
1562 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE);
1563 } else if (HasBit(c->flags, GCF_SYSTEM)) {
1564 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM);
1565 } else if (HasBit(c->flags, GCF_INVALID)) {
1566 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE);
1567 } else {
1568 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN);
1571 SetDParamStr(0, StrEmpty(filename) ? item->name : filename);
1572 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_GRF, WL_CRITICAL);
1573 delete c;
1574 continue;
1577 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1578 bool duplicate = false;
1579 for (const GRFConfig *gc = first; gc != NULL; gc = gc->next) {
1580 if (gc->ident.grfid == c->ident.grfid) {
1581 SetDParamStr(0, c->filename);
1582 SetDParamStr(1, gc->filename);
1583 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_DUPLICATE_GRFID, WL_CRITICAL);
1584 duplicate = true;
1585 break;
1588 if (duplicate) {
1589 delete c;
1590 continue;
1593 /* Mark file as static to avoid saving in savegame. */
1594 if (is_static) SetBit(c->flags, GCF_STATIC);
1596 /* Add item to list */
1597 *curr = c;
1598 curr = &c->next;
1601 return first;
1604 static void AISaveConfig(IniFile *ini, const char *grpname)
1606 IniGroup *group = ini->GetGroup(grpname);
1608 if (group == NULL) return;
1609 group->Clear();
1611 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1612 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1613 const char *name;
1614 char value[1024];
1615 config->SettingsToString(value, lastof(value));
1617 if (config->HasScript()) {
1618 name = config->GetName();
1619 } else {
1620 name = "none";
1623 IniItem *item = new IniItem(group, name);
1624 item->SetValue(value);
1628 static void GameSaveConfig(IniFile *ini, const char *grpname)
1630 IniGroup *group = ini->GetGroup(grpname);
1632 if (group == NULL) return;
1633 group->Clear();
1635 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1636 const char *name;
1637 char value[1024];
1638 config->SettingsToString(value, lastof(value));
1640 if (config->HasScript()) {
1641 name = config->GetName();
1642 } else {
1643 name = "none";
1646 IniItem *item = new IniItem(group, name);
1647 item->SetValue(value);
1651 * Save the version of OpenTTD to the ini file.
1652 * @param ini the ini to write to
1654 static void SaveVersionInConfig(IniFile *ini)
1656 IniGroup *group = ini->GetGroup("version");
1658 char version[9];
1659 seprintf(version, lastof(version), "%08X", _openttd_newgrf_version);
1661 const char * const versions[][2] = {
1662 { "version_string", _openttd_revision },
1663 { "version_number", version }
1666 for (uint i = 0; i < lengthof(versions); i++) {
1667 group->GetItem(versions[i][0], true)->SetValue(versions[i][1]);
1671 /* Save a GRF configuration to the given group name */
1672 static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
1674 ini->RemoveGroup(grpname);
1675 IniGroup *group = ini->GetGroup(grpname);
1676 const GRFConfig *c;
1678 for (c = list; c != NULL; c = c->next) {
1679 /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1680 char key[4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH];
1681 char params[512];
1682 GRFBuildParamList(params, c, lastof(params));
1684 char *pos = key + seprintf(key, lastof(key), "%08X|", BSWAP32(c->ident.grfid));
1685 pos = md5sumToString(pos, lastof(key), c->ident.md5sum);
1686 seprintf(pos, lastof(key), "|%s", c->filename);
1687 group->GetItem(key, true)->SetValue(params);
1691 /* Common handler for saving/loading variables to the configuration file */
1692 static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list, bool basic_settings = true, bool other_settings = true)
1694 if (basic_settings) {
1695 proc(ini, (const SettingDesc*)_misc_settings, "misc", NULL);
1696 #if defined(WIN32) && !defined(DEDICATED)
1697 proc(ini, (const SettingDesc*)_win32_settings, "win32", NULL);
1698 #endif /* WIN32 */
1701 if (other_settings) {
1702 proc(ini, _settings, "patches", &_settings_newgame);
1703 proc(ini, _currency_settings,"currency", &_custom_currency);
1704 proc(ini, _company_settings, "company", &_settings_client.company);
1706 #ifdef ENABLE_NETWORK
1707 proc_list(ini, "server_bind_addresses", &_network_bind_list);
1708 proc_list(ini, "servers", &_network_host_list);
1709 proc_list(ini, "bans", &_network_ban_list);
1710 #endif /* ENABLE_NETWORK */
1714 static IniFile *IniLoadConfig()
1716 IniFile *ini = new IniFile(_list_group_names);
1717 ini->LoadFromDisk(_config_file, NO_DIRECTORY);
1718 return ini;
1722 * Load the values from the configuration files
1723 * @param minimal Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1725 void LoadFromConfig(bool minimal)
1727 IniFile *ini = IniLoadConfig();
1728 if (!minimal) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1730 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1731 HandleSettingDescs(ini, IniLoadSettings, IniLoadSettingList, minimal, !minimal);
1733 if (!minimal) {
1734 _grfconfig_newgame = GRFLoadConfig(ini, "newgrf", false);
1735 _grfconfig_static = GRFLoadConfig(ini, "newgrf-static", true);
1736 AILoadConfig(ini, "ai_players");
1737 GameLoadConfig(ini, "game_scripts");
1739 PrepareOldDiffCustom();
1740 IniLoadSettings(ini, _gameopt_settings, "gameopt", &_settings_newgame);
1741 HandleOldDiffCustom(false);
1743 ValidateSettings();
1745 /* Display sheduled errors */
1746 extern void ScheduleErrorMessage(ErrorList &datas);
1747 ScheduleErrorMessage(_settings_error_list);
1748 if (FindWindowById(WC_ERRMSG, 0) == NULL) ShowFirstError();
1751 delete ini;
1754 /** Save the values to the configuration file */
1755 void SaveToConfig()
1757 IniFile *ini = IniLoadConfig();
1759 /* Remove some obsolete groups. These have all been loaded into other groups. */
1760 ini->RemoveGroup("patches");
1761 ini->RemoveGroup("yapf");
1762 ini->RemoveGroup("gameopt");
1764 HandleSettingDescs(ini, IniSaveSettings, IniSaveSettingList);
1765 GRFSaveConfig(ini, "newgrf", _grfconfig_newgame);
1766 GRFSaveConfig(ini, "newgrf-static", _grfconfig_static);
1767 AISaveConfig(ini, "ai_players");
1768 GameSaveConfig(ini, "game_scripts");
1769 SaveVersionInConfig(ini);
1770 ini->SaveToDisk(_config_file);
1771 delete ini;
1775 * Get the list of known NewGrf presets.
1776 * @param list[inout] Pointer to list for storing the preset names.
1778 void GetGRFPresetList(GRFPresetList *list)
1780 list->Clear();
1782 IniFile *ini = IniLoadConfig();
1783 IniGroup *group;
1784 for (group = ini->group; group != NULL; group = group->next) {
1785 if (strncmp(group->name, "preset-", 7) == 0) {
1786 *list->Append() = stredup(group->name + 7);
1790 delete ini;
1794 * Load a NewGRF configuration by preset-name.
1795 * @param config_name Name of the preset.
1796 * @return NewGRF configuration.
1797 * @see GetGRFPresetList
1799 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
1801 size_t len = strlen(config_name) + 8;
1802 char *section = (char*)alloca(len);
1803 seprintf(section, section + len - 1, "preset-%s", config_name);
1805 IniFile *ini = IniLoadConfig();
1806 GRFConfig *config = GRFLoadConfig(ini, section, false);
1807 delete ini;
1809 return config;
1813 * Save a NewGRF configuration with a preset name.
1814 * @param config_name Name of the preset.
1815 * @param config NewGRF configuration to save.
1816 * @see GetGRFPresetList
1818 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
1820 size_t len = strlen(config_name) + 8;
1821 char *section = (char*)alloca(len);
1822 seprintf(section, section + len - 1, "preset-%s", config_name);
1824 IniFile *ini = IniLoadConfig();
1825 GRFSaveConfig(ini, section, config);
1826 ini->SaveToDisk(_config_file);
1827 delete ini;
1831 * Delete a NewGRF configuration by preset name.
1832 * @param config_name Name of the preset.
1834 void DeleteGRFPresetFromConfig(const char *config_name)
1836 size_t len = strlen(config_name) + 8;
1837 char *section = (char*)alloca(len);
1838 seprintf(section, section + len - 1, "preset-%s", config_name);
1840 IniFile *ini = IniLoadConfig();
1841 ini->RemoveGroup(section);
1842 ini->SaveToDisk(_config_file);
1843 delete ini;
1846 const SettingDesc *GetSettingDescription(uint index)
1848 if (index >= lengthof(_settings)) return NULL;
1849 return &_settings[index];
1853 * Network-safe changing of settings (server-only).
1854 * @param tile unused
1855 * @param flags operation to perform
1856 * @param p1 the index of the setting in the SettingDesc array which identifies it
1857 * @param p2 the new value for the setting
1858 * The new value is properly clamped to its minimum/maximum when setting
1859 * @param text unused
1860 * @return the cost of this operation or an error
1861 * @see _settings
1863 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1865 const SettingDesc *sd = GetSettingDescription(p1);
1867 if (sd == NULL) return CMD_ERROR;
1868 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
1870 if (!sd->IsEditable(true)) return CMD_ERROR;
1872 if (flags & DC_EXEC) {
1873 void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
1875 int32 oldval = (int32)ReadValue(var, sd->save.conv);
1876 int32 newval = (int32)p2;
1878 Write_ValidateSetting(var, sd, newval);
1879 newval = (int32)ReadValue(var, sd->save.conv);
1881 if (oldval == newval) return CommandCost();
1883 if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
1884 WriteValue(var, sd->save.conv, (int64)oldval);
1885 return CommandCost();
1888 if (sd->desc.flags & SGF_NO_NETWORK) {
1889 GamelogStartAction(GLAT_SETTING);
1890 GamelogSetting(sd->desc.name, oldval, newval);
1891 GamelogStopAction();
1894 SetWindowClassesDirty(WC_GAME_OPTIONS);
1897 return CommandCost();
1901 * Change one of the per-company settings.
1902 * @param tile unused
1903 * @param flags operation to perform
1904 * @param p1 the index of the setting in the _company_settings array which identifies it
1905 * @param p2 the new value for the setting
1906 * The new value is properly clamped to its minimum/maximum when setting
1907 * @param text unused
1908 * @return the cost of this operation or an error
1910 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1912 if (p1 >= lengthof(_company_settings)) return CMD_ERROR;
1913 const SettingDesc *sd = &_company_settings[p1];
1915 if (flags & DC_EXEC) {
1916 void *var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
1918 int32 oldval = (int32)ReadValue(var, sd->save.conv);
1919 int32 newval = (int32)p2;
1921 Write_ValidateSetting(var, sd, newval);
1922 newval = (int32)ReadValue(var, sd->save.conv);
1924 if (oldval == newval) return CommandCost();
1926 if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
1927 WriteValue(var, sd->save.conv, (int64)oldval);
1928 return CommandCost();
1931 SetWindowClassesDirty(WC_GAME_OPTIONS);
1934 return CommandCost();
1938 * Top function to save the new value of an element of the Settings struct
1939 * @param index offset in the SettingDesc array of the Settings struct which
1940 * identifies the setting member we want to change
1941 * @param value new value of the setting
1942 * @param force_newgame force the newgame settings
1944 bool SetSettingValue(uint index, int32 value, bool force_newgame)
1946 const SettingDesc *sd = &_settings[index];
1947 /* If an item is company-based, we do not send it over the network
1948 * (if any) to change. Also *hack*hack* we update the _newgame version
1949 * of settings because changing a company-based setting in a game also
1950 * changes its defaults. At least that is the convention we have chosen */
1951 if (sd->save.conv & SLF_NO_NETWORK_SYNC) {
1952 void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
1953 Write_ValidateSetting(var, sd, value);
1955 if (_game_mode != GM_MENU) {
1956 void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
1957 Write_ValidateSetting(var2, sd, value);
1959 if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
1961 SetWindowClassesDirty(WC_GAME_OPTIONS);
1963 return true;
1966 if (force_newgame) {
1967 void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
1968 Write_ValidateSetting(var2, sd, value);
1969 return true;
1972 /* send non-company-based settings over the network */
1973 if (!_networking || (_networking && _network_server)) {
1974 return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
1976 return false;
1980 * Top function to save the new value of an element of the Settings struct
1981 * @param index offset in the SettingDesc array of the CompanySettings struct
1982 * which identifies the setting member we want to change
1983 * @param value new value of the setting
1985 void SetCompanySetting(uint index, int32 value)
1987 const SettingDesc *sd = &_company_settings[index];
1988 if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
1989 DoCommandP(0, index, value, CMD_CHANGE_COMPANY_SETTING);
1990 } else {
1991 void *var = GetVariableAddress(&_settings_client.company, &sd->save);
1992 Write_ValidateSetting(var, sd, value);
1993 if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
1998 * Set the company settings for a new company to their default values.
2000 void SetDefaultCompanySettings(CompanyID cid)
2002 Company *c = Company::Get(cid);
2003 const SettingDesc *sd;
2004 for (sd = _company_settings; sd->save.cmd != SL_END; sd++) {
2005 void *var = GetVariableAddress(&c->settings, &sd->save);
2006 Write_ValidateSetting(var, sd, (int32)(size_t)sd->desc.def);
2010 #if defined(ENABLE_NETWORK)
2012 * Sync all company settings in a multiplayer game.
2014 void SyncCompanySettings()
2016 const SettingDesc *sd;
2017 uint i = 0;
2018 for (sd = _company_settings; sd->save.cmd != SL_END; sd++, i++) {
2019 const void *old_var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
2020 const void *new_var = GetVariableAddress(&_settings_client.company, &sd->save);
2021 uint32 old_value = (uint32)ReadValue(old_var, sd->save.conv);
2022 uint32 new_value = (uint32)ReadValue(new_var, sd->save.conv);
2023 if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, NULL, NULL, _local_company, 0);
2026 #endif /* ENABLE_NETWORK */
2029 * Get the index in the _company_settings array of a setting
2030 * @param name The name of the setting
2031 * @return The index in the _company_settings array
2033 uint GetCompanySettingIndex(const char *name)
2035 uint i;
2036 const SettingDesc *sd = GetSettingFromName(name, &i);
2037 assert(sd != NULL && (sd->desc.flags & SGF_PER_COMPANY) != 0);
2038 return i;
2042 * Set a setting value with a string.
2043 * @param index the settings index.
2044 * @param value the value to write
2045 * @param force_newgame force the newgame settings
2046 * @note Strings WILL NOT be synced over the network
2048 bool SetSettingValue(uint index, const char *value, bool force_newgame)
2050 const SettingDesc *sd = &_settings[index];
2051 assert(sd->save.conv & SLF_NO_NETWORK_SYNC);
2053 if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
2054 char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
2055 free(*var);
2056 *var = strcmp(value, "(null)") == 0 ? NULL : stredup(value);
2057 } else {
2058 char *var = (char*)GetVariableAddress(NULL, &sd->save);
2059 strecpy(var, value, &var[sd->save.length - 1]);
2061 if (sd->desc.proc != NULL) sd->desc.proc(0);
2063 return true;
2067 * Given a name of setting, return a setting description of it.
2068 * @param name Name of the setting to return a setting description of
2069 * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
2070 * @return Pointer to the setting description of setting \a name if it can be found,
2071 * \c NULL indicates failure to obtain the description
2073 const SettingDesc *GetSettingFromName(const char *name, uint *i)
2075 const SettingDesc *sd;
2077 /* First check all full names */
2078 for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2079 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2080 if (strcmp(sd->desc.name, name) == 0) return sd;
2083 /* Then check the shortcut variant of the name. */
2084 for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2085 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2086 const char *short_name = strchr(sd->desc.name, '.');
2087 if (short_name != NULL) {
2088 short_name++;
2089 if (strcmp(short_name, name) == 0) return sd;
2093 if (strncmp(name, "company.", 8) == 0) name += 8;
2094 /* And finally the company-based settings */
2095 for (*i = 0, sd = _company_settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2096 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2097 if (strcmp(sd->desc.name, name) == 0) return sd;
2100 return NULL;
2103 /* Those 2 functions need to be here, else we have to make some stuff non-static
2104 * and besides, it is also better to keep stuff like this at the same place */
2105 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
2107 uint index;
2108 const SettingDesc *sd = GetSettingFromName(name, &index);
2110 if (sd == NULL) {
2111 IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2112 return;
2115 bool success;
2116 if (sd->desc.cmd == SDT_STRING) {
2117 success = SetSettingValue(index, value, force_newgame);
2118 } else {
2119 uint32 val;
2120 extern bool GetArgumentInteger(uint32 *value, const char *arg);
2121 success = GetArgumentInteger(&val, value);
2122 if (!success) {
2123 IConsolePrintF(CC_ERROR, "'%s' is not an integer.", value);
2124 return;
2127 success = SetSettingValue(index, val, force_newgame);
2130 if (!success) {
2131 if (_network_server) {
2132 IConsoleError("This command/variable is not available during network games.");
2133 } else {
2134 IConsoleError("This command/variable is only available to a network server.");
2139 void IConsoleSetSetting(const char *name, int value)
2141 uint index;
2142 const SettingDesc *sd = GetSettingFromName(name, &index);
2143 assert(sd != NULL);
2144 SetSettingValue(index, value);
2148 * Output value of a specific setting to the console
2149 * @param name Name of the setting to output its value
2150 * @param force_newgame force the newgame settings
2152 void IConsoleGetSetting(const char *name, bool force_newgame)
2154 char value[20];
2155 uint index;
2156 const SettingDesc *sd = GetSettingFromName(name, &index);
2157 const void *ptr;
2159 if (sd == NULL) {
2160 IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2161 return;
2164 ptr = GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
2166 if (sd->desc.cmd == SDT_STRING) {
2167 IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char * const *)ptr : (const char *)ptr);
2168 } else {
2169 if (sd->desc.cmd == SDT_BOOLX) {
2170 seprintf(value, lastof(value), (*(const bool*)ptr != 0) ? "on" : "off");
2171 } else {
2172 seprintf(value, lastof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
2175 IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
2176 name, value, (sd->desc.flags & SGF_0ISDISABLED) ? "(0) " : "", sd->desc.min, sd->desc.max);
2181 * List all settings and their value to the console
2183 * @param prefilter If not \c NULL, only list settings with names that begin with \a prefilter prefix
2185 void IConsoleListSettings(const char *prefilter)
2187 IConsolePrintF(CC_WARNING, "All settings with their current value:");
2189 for (const SettingDesc *sd = _settings; sd->save.cmd != SL_END; sd++) {
2190 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2191 if (prefilter != NULL && strstr(sd->desc.name, prefilter) == NULL) continue;
2192 char value[80];
2193 const void *ptr = GetVariableAddress(&GetGameSettings(), &sd->save);
2195 if (sd->desc.cmd == SDT_BOOLX) {
2196 seprintf(value, lastof(value), (*(const bool *)ptr != 0) ? "on" : "off");
2197 } else if (sd->desc.cmd == SDT_STRING) {
2198 seprintf(value, lastof(value), "%s", (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char * const *)ptr : (const char *)ptr);
2199 } else {
2200 seprintf(value, lastof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
2202 IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
2205 IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
2209 * Save and load handler for settings
2210 * @param osd SettingDesc struct containing all information
2211 * @param object can be either NULL in which case we load global variables or
2212 * a pointer to a struct which is getting saved
2214 static void LoadSettings(const SettingDesc *osd, void *object)
2216 for (; osd->save.cmd != SL_END; osd++) {
2217 const SaveLoad *sld = &osd->save;
2218 void *ptr = GetVariableAddress(object, sld);
2220 if (!SlObjectMember(ptr, sld)) continue;
2221 if (IsNumericType(sld->conv)) Write_ValidateSetting(ptr, osd, ReadValue(ptr, sld->conv));
2226 * Save and load handler for settings
2227 * @param sd SettingDesc struct containing all information
2228 * @param object can be either NULL in which case we load global variables or
2229 * a pointer to a struct which is getting saved
2231 static void SaveSettings(const SettingDesc *sd, void *object)
2233 /* We need to write the CH_RIFF header, but unfortunately can't call
2234 * SlCalcLength() because we have a different format. So do this manually */
2235 const SettingDesc *i;
2236 size_t length = 0;
2237 for (i = sd; i->save.cmd != SL_END; i++) {
2238 length += SlCalcObjMemberLength(object, &i->save);
2240 SlSetLength(length);
2242 for (i = sd; i->save.cmd != SL_END; i++) {
2243 void *ptr = GetVariableAddress(object, &i->save);
2244 SlObjectMember(ptr, &i->save);
2248 static void Load_OPTS()
2250 /* Copy over default setting since some might not get loaded in
2251 * a networking environment. This ensures for example that the local
2252 * autosave-frequency stays when joining a network-server */
2253 PrepareOldDiffCustom();
2254 LoadSettings(_gameopt_settings, &_settings_game);
2255 HandleOldDiffCustom(true);
2258 static void Load_PATS()
2260 /* Copy over default setting since some might not get loaded in
2261 * a networking environment. This ensures for example that the local
2262 * currency setting stays when joining a network-server */
2263 LoadSettings(_settings, &_settings_game);
2266 static void Check_PATS()
2268 LoadSettings(_settings, &_load_check_data.settings);
2271 static void Save_PATS()
2273 SaveSettings(_settings, &_settings_game);
2276 void CheckConfig()
2279 * Increase old default values for pf_maxdepth and pf_maxlength
2280 * to support big networks.
2282 if (_settings_newgame.pf.opf.pf_maxdepth == 16 && _settings_newgame.pf.opf.pf_maxlength == 512) {
2283 _settings_newgame.pf.opf.pf_maxdepth = 48;
2284 _settings_newgame.pf.opf.pf_maxlength = 4096;
2288 extern const ChunkHandler _setting_chunk_handlers[] = {
2289 { 'OPTS', NULL, Load_OPTS, NULL, NULL, CH_RIFF},
2290 { 'PATS', Save_PATS, Load_PATS, NULL, Check_PATS, CH_RIFF | CH_LAST},
2293 static bool IsSignedVarMemType(VarType vt)
2295 switch (GetVarMemType(vt)) {
2296 case SLE_VAR_I8:
2297 case SLE_VAR_I16:
2298 case SLE_VAR_I32:
2299 case SLE_VAR_I64:
2300 return true;
2302 return false;