(svn r28004) -Update from Eints:
[openttd.git] / src / settings.cpp
blobd819450221307be6e93072218ac8434593cdf8ad
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"
68 #include "void_map.h"
69 #include "station_base.h"
71 #include "table/strings.h"
72 #include "table/settings.h"
74 #include "safeguards.h"
76 ClientSettings _settings_client;
77 GameSettings _settings_game; ///< Game settings of a running game or the scenario editor.
78 GameSettings _settings_newgame; ///< Game settings for new games (updated from the intro screen).
79 VehicleDefaultSettings _old_vds; ///< Used for loading default vehicles settings from old savegames
80 char *_config_file; ///< Configuration file of OpenTTD
82 typedef std::list<ErrorMessageData> ErrorList;
83 static ErrorList _settings_error_list; ///< Errors while loading minimal settings.
86 typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
87 typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList *list);
89 static bool IsSignedVarMemType(VarType vt);
91 /**
92 * Groups in openttd.cfg that are actually lists.
94 static const char * const _list_group_names[] = {
95 "bans",
96 "newgrf",
97 "servers",
98 "server_bind_addresses",
99 NULL
103 * Find the index value of a ONEofMANY type in a string separated by |
104 * @param many full domain of values the ONEofMANY setting can have
105 * @param one the current value of the setting for which a value needs found
106 * @param onelen force calculation of the *one parameter
107 * @return the integer index of the full-list, or -1 if not found
109 static size_t LookupOneOfMany(const char *many, const char *one, size_t onelen = 0)
111 const char *s;
112 size_t idx;
114 if (onelen == 0) onelen = strlen(one);
116 /* check if it's an integer */
117 if (*one >= '0' && *one <= '9') return strtoul(one, NULL, 0);
119 idx = 0;
120 for (;;) {
121 /* find end of item */
122 s = many;
123 while (*s != '|' && *s != 0) s++;
124 if ((size_t)(s - many) == onelen && !memcmp(one, many, onelen)) return idx;
125 if (*s == 0) return (size_t)-1;
126 many = s + 1;
127 idx++;
132 * Find the set-integer value MANYofMANY type in a string
133 * @param many full domain of values the MANYofMANY setting can have
134 * @param str the current string value of the setting, each individual
135 * of separated by a whitespace,tab or | character
136 * @return the 'fully' set integer, or -1 if a set is not found
138 static size_t LookupManyOfMany(const char *many, const char *str)
140 const char *s;
141 size_t r;
142 size_t res = 0;
144 for (;;) {
145 /* skip "whitespace" */
146 while (*str == ' ' || *str == '\t' || *str == '|') str++;
147 if (*str == 0) break;
149 s = str;
150 while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
152 r = LookupOneOfMany(many, str, s - str);
153 if (r == (size_t)-1) return r;
155 SetBit(res, (uint8)r); // value found, set it
156 if (*s == 0) break;
157 str = s + 1;
159 return res;
163 * Parse an integerlist string and set each found value
164 * @param p the string to be parsed. Each element in the list is separated by a
165 * comma or a space character
166 * @param items pointer to the integerlist-array that will be filled with values
167 * @param maxitems the maximum number of elements the integerlist-array has
168 * @return returns the number of items found, or -1 on an error
170 static int ParseIntList(const char *p, int *items, int maxitems)
172 int n = 0; // number of items read so far
173 bool comma = false; // do we accept comma?
175 while (*p != '\0') {
176 switch (*p) {
177 case ',':
178 /* Do not accept multiple commas between numbers */
179 if (!comma) return -1;
180 comma = false;
181 FALLTHROUGH;
183 case ' ':
184 p++;
185 break;
187 default: {
188 if (n == maxitems) return -1; // we don't accept that many numbers
189 char *end;
190 long v = strtol(p, &end, 0);
191 if (p == end) return -1; // invalid character (not a number)
192 if (sizeof(int) < sizeof(long)) v = ClampToI32(v);
193 items[n++] = v;
194 p = end; // first non-number
195 comma = true; // we accept comma now
196 break;
201 /* If we have read comma but no number after it, fail.
202 * We have read comma when (n != 0) and comma is not allowed */
203 if (n != 0 && !comma) return -1;
205 return n;
209 * Load parsed string-values into an integer-array (intlist)
210 * @param str the string that contains the values (and will be parsed)
211 * @param array pointer to the integer-arrays that will be filled
212 * @param nelems the number of elements the array holds. Maximum is 64 elements
213 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
214 * @return return true on success and false on error
216 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
218 int items[64];
219 int i, nitems;
221 if (str == NULL) {
222 memset(items, 0, sizeof(items));
223 nitems = nelems;
224 } else {
225 nitems = ParseIntList(str, items, lengthof(items));
226 if (nitems != nelems) return false;
229 switch (type) {
230 case SLE_VAR_BL:
231 case SLE_VAR_I8:
232 case SLE_VAR_U8:
233 for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
234 break;
236 case SLE_VAR_I16:
237 case SLE_VAR_U16:
238 for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
239 break;
241 case SLE_VAR_I32:
242 case SLE_VAR_U32:
243 for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
244 break;
246 default: NOT_REACHED();
249 return true;
253 * Convert an integer-array (intlist) to a string representation. Each value
254 * is separated by a comma or a space character
255 * @param buf output buffer where the string-representation will be stored
256 * @param last last item to write to in the output buffer
257 * @param array pointer to the integer-arrays that is read from
258 * @param nelems the number of elements the array holds.
259 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
261 static void MakeIntList(char *buf, const char *last, const void *array, int nelems, VarType type)
263 int i, v = 0;
264 const byte *p = (const byte *)array;
266 for (i = 0; i != nelems; i++) {
267 switch (type) {
268 case SLE_VAR_BL:
269 case SLE_VAR_I8: v = *(const int8 *)p; p += 1; break;
270 case SLE_VAR_U8: v = *(const uint8 *)p; p += 1; break;
271 case SLE_VAR_I16: v = *(const int16 *)p; p += 2; break;
272 case SLE_VAR_U16: v = *(const uint16 *)p; p += 2; break;
273 case SLE_VAR_I32: v = *(const int32 *)p; p += 4; break;
274 case SLE_VAR_U32: v = *(const uint32 *)p; p += 4; break;
275 default: NOT_REACHED();
277 buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
282 * Convert a ONEofMANY structure to a string representation.
283 * @param buf output buffer where the string-representation will be stored
284 * @param last last item to write to in the output buffer
285 * @param many the full-domain string of possible values
286 * @param id the value of the variable and whose string-representation must be found
288 static void MakeOneOfMany(char *buf, const char *last, const char *many, int id)
290 int orig_id = id;
292 /* Look for the id'th element */
293 while (--id >= 0) {
294 for (; *many != '|'; many++) {
295 if (*many == '\0') { // not found
296 seprintf(buf, last, "%d", orig_id);
297 return;
300 many++; // pass the |-character
303 /* copy string until next item (|) or the end of the list if this is the last one */
304 while (*many != '\0' && *many != '|' && buf < last) *buf++ = *many++;
305 *buf = '\0';
309 * Convert a MANYofMANY structure to a string representation.
310 * @param buf output buffer where the string-representation will be stored
311 * @param last last item to write to in the output buffer
312 * @param many the full-domain string of possible values
313 * @param x the value of the variable and whose string-representation must
314 * be found in the bitmasked many string
316 static void MakeManyOfMany(char *buf, const char *last, const char *many, uint32 x)
318 const char *start;
319 int i = 0;
320 bool init = true;
322 for (; x != 0; x >>= 1, i++) {
323 start = many;
324 while (*many != 0 && *many != '|') many++; // advance to the next element
326 if (HasBit(x, 0)) { // item found, copy it
327 if (!init) buf += seprintf(buf, last, "|");
328 init = false;
329 if (start == many) {
330 buf += seprintf(buf, last, "%d", i);
331 } else {
332 memcpy(buf, start, many - start);
333 buf += many - start;
337 if (*many == '|') many++;
340 *buf = '\0';
344 * Convert a string representation (external) of a setting to the internal rep.
345 * @param desc SettingDesc struct that holds all information about the variable
346 * @param orig_str input string that will be parsed based on the type of desc
347 * @return return the parsed value of the setting
349 static const void *StringToVal(const SettingDescBase *desc, const char *orig_str)
351 const char *str = orig_str == NULL ? "" : orig_str;
353 switch (desc->cmd) {
354 case SDT_NUMX: {
355 char *end;
356 size_t val = strtoul(str, &end, 0);
357 if (end == str) {
358 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
359 msg.SetDParamStr(0, str);
360 msg.SetDParamStr(1, desc->name);
361 _settings_error_list.push_back(msg);
362 return desc->def;
364 if (*end != '\0') {
365 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_TRAILING_CHARACTERS);
366 msg.SetDParamStr(0, desc->name);
367 _settings_error_list.push_back(msg);
369 return (void*)val;
372 case SDT_ONEOFMANY: {
373 size_t r = LookupOneOfMany(desc->many, str);
374 /* if the first attempt of conversion from string to the appropriate value fails,
375 * look if we have defined a converter from old value to new value. */
376 if (r == (size_t)-1 && desc->proc_cnvt != NULL) r = desc->proc_cnvt(str);
377 if (r != (size_t)-1) return (void*)r; // and here goes converted value
379 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
380 msg.SetDParamStr(0, str);
381 msg.SetDParamStr(1, desc->name);
382 _settings_error_list.push_back(msg);
383 return desc->def;
386 case SDT_MANYOFMANY: {
387 size_t r = LookupManyOfMany(desc->many, str);
388 if (r != (size_t)-1) return (void*)r;
389 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
390 msg.SetDParamStr(0, str);
391 msg.SetDParamStr(1, desc->name);
392 _settings_error_list.push_back(msg);
393 return desc->def;
396 case SDT_BOOLX: {
397 if (strcmp(str, "true") == 0 || strcmp(str, "on") == 0 || strcmp(str, "1") == 0) return (void*)true;
398 if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return (void*)false;
400 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
401 msg.SetDParamStr(0, str);
402 msg.SetDParamStr(1, desc->name);
403 _settings_error_list.push_back(msg);
404 return desc->def;
407 case SDT_STRING: return orig_str;
408 case SDT_INTLIST: return str;
409 default: break;
412 return NULL;
416 * Set the value of a setting and if needed clamp the value to
417 * the preset minimum and maximum.
418 * @param ptr the variable itself
419 * @param sd pointer to the 'information'-database of the variable
420 * @param val signed long version of the new value
421 * @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
422 * SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now
424 static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
426 const SettingDescBase *sdb = &sd->desc;
428 if (sdb->cmd != SDT_BOOLX &&
429 sdb->cmd != SDT_NUMX &&
430 sdb->cmd != SDT_ONEOFMANY &&
431 sdb->cmd != SDT_MANYOFMANY) {
432 return;
435 /* We cannot know the maximum value of a bitset variable, so just have faith */
436 if (sdb->cmd != SDT_MANYOFMANY) {
437 /* We need to take special care of the uint32 type as we receive from the function
438 * a signed integer. While here also bail out on 64-bit settings as those are not
439 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
440 * 32-bit variable
441 * TODO: Support 64-bit settings/variables */
442 switch (GetVarMemType(sd->save.conv)) {
443 case SLE_VAR_NULL: return;
444 case SLE_VAR_BL:
445 case SLE_VAR_I8:
446 case SLE_VAR_U8:
447 case SLE_VAR_I16:
448 case SLE_VAR_U16:
449 case SLE_VAR_I32: {
450 /* Override the minimum value. No value below sdb->min, except special value 0 */
451 if (!(sdb->flags & SGF_0ISDISABLED) || val != 0) val = Clamp(val, sdb->min, sdb->max);
452 break;
454 case SLE_VAR_U32: {
455 /* Override the minimum value. No value below sdb->min, except special value 0 */
456 uint min = ((sdb->flags & SGF_0ISDISABLED) && (uint)val <= (uint)sdb->min) ? 0 : sdb->min;
457 WriteValue(ptr, SLE_VAR_U32, (int64)ClampU(val, min, sdb->max));
458 return;
460 case SLE_VAR_I64:
461 case SLE_VAR_U64:
462 default: NOT_REACHED();
466 WriteValue(ptr, sd->save.conv, (int64)val);
470 * Load values from a group of an IniFile structure into the internal representation
471 * @param ini pointer to IniFile structure that holds administrative information
472 * @param sd pointer to SettingDesc structure whose internally pointed variables will
473 * be given values
474 * @param grpname the group of the IniFile to search in for the new values
475 * @param object pointer to the object been loaded
477 static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
479 IniGroup *group;
480 IniGroup *group_def = ini->GetGroup(grpname);
481 IniItem *item;
482 const void *p;
483 void *ptr;
484 const char *s;
486 for (; sd->save.cmd != SL_END; sd++) {
487 const SettingDescBase *sdb = &sd->desc;
488 const SaveLoad *sld = &sd->save;
490 if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
492 /* For settings.xx.yy load the settings from [xx] yy = ? */
493 s = strchr(sdb->name, '.');
494 if (s != NULL) {
495 group = ini->GetGroup(sdb->name, s - sdb->name);
496 s++;
497 } else {
498 s = sdb->name;
499 group = group_def;
502 item = group->GetItem(s, false);
503 if (item == NULL && group != group_def) {
504 /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
505 * did not exist (e.g. loading old config files with a [settings] section */
506 item = group_def->GetItem(s, false);
508 if (item == NULL) {
509 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
510 * did not exist (e.g. loading old config files with a [yapf] section */
511 const char *sc = strchr(s, '.');
512 if (sc != NULL) item = ini->GetGroup(s, sc - s)->GetItem(sc + 1, false);
515 p = (item == NULL) ? sdb->def : StringToVal(sdb, item->value);
516 ptr = GetVariableAddress(object, sld);
518 switch (sdb->cmd) {
519 case SDT_BOOLX: // All four are various types of (integer) numbers
520 case SDT_NUMX:
521 case SDT_ONEOFMANY:
522 case SDT_MANYOFMANY:
523 Write_ValidateSetting(ptr, sd, (int32)(size_t)p);
524 break;
526 case SDT_STRING:
527 switch (GetVarMemType(sld->conv)) {
528 case SLE_VAR_STRB:
529 case SLE_VAR_STRBQ:
530 if (p != NULL) strecpy((char*)ptr, (const char*)p, (char*)ptr + sld->length - 1);
531 break;
533 case SLE_VAR_STR:
534 case SLE_VAR_STRQ:
535 free(*(char**)ptr);
536 *(char**)ptr = p == NULL ? NULL : stredup((const char*)p);
537 break;
539 case SLE_VAR_CHAR: if (p != NULL) *(char *)ptr = *(const char *)p; break;
541 default: NOT_REACHED();
543 break;
545 case SDT_INTLIST: {
546 if (!LoadIntList((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) {
547 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY);
548 msg.SetDParamStr(0, sdb->name);
549 _settings_error_list.push_back(msg);
551 /* Use default */
552 LoadIntList((const char*)sdb->def, ptr, sld->length, GetVarMemType(sld->conv));
553 } else if (sd->desc.proc_cnvt != NULL) {
554 sd->desc.proc_cnvt((const char*)p);
556 break;
558 default: NOT_REACHED();
564 * Save the values of settings to the inifile.
565 * @param ini pointer to IniFile structure
566 * @param sd read-only SettingDesc structure which contains the unmodified,
567 * loaded values of the configuration file and various information about it
568 * @param grpname holds the name of the group (eg. [network]) where these will be saved
569 * @param object pointer to the object been saved
570 * The function works as follows: for each item in the SettingDesc structure we
571 * have a look if the value has changed since we started the game (the original
572 * values are reloaded when saving). If settings indeed have changed, we get
573 * these and save them.
575 static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
577 IniGroup *group_def = NULL, *group;
578 IniItem *item;
579 char buf[512];
580 const char *s;
581 void *ptr;
583 for (; sd->save.cmd != SL_END; sd++) {
584 const SettingDescBase *sdb = &sd->desc;
585 const SaveLoad *sld = &sd->save;
587 /* If the setting is not saved to the configuration
588 * file, just continue with the next setting */
589 if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
590 if (sld->conv & SLF_NOT_IN_CONFIG) continue;
592 /* XXX - wtf is this?? (group override?) */
593 s = strchr(sdb->name, '.');
594 if (s != NULL) {
595 group = ini->GetGroup(sdb->name, s - sdb->name);
596 s++;
597 } else {
598 if (group_def == NULL) group_def = ini->GetGroup(grpname);
599 s = sdb->name;
600 group = group_def;
603 item = group->GetItem(s, true);
604 ptr = GetVariableAddress(object, sld);
606 if (item->value != NULL) {
607 /* check if the value is the same as the old value */
608 const void *p = StringToVal(sdb, item->value);
610 /* The main type of a variable/setting is in bytes 8-15
611 * The subtype (what kind of numbers do we have there) is in 0-7 */
612 switch (sdb->cmd) {
613 case SDT_BOOLX:
614 case SDT_NUMX:
615 case SDT_ONEOFMANY:
616 case SDT_MANYOFMANY:
617 switch (GetVarMemType(sld->conv)) {
618 case SLE_VAR_BL:
619 if (*(bool*)ptr == (p != NULL)) continue;
620 break;
622 case SLE_VAR_I8:
623 case SLE_VAR_U8:
624 if (*(byte*)ptr == (byte)(size_t)p) continue;
625 break;
627 case SLE_VAR_I16:
628 case SLE_VAR_U16:
629 if (*(uint16*)ptr == (uint16)(size_t)p) continue;
630 break;
632 case SLE_VAR_I32:
633 case SLE_VAR_U32:
634 if (*(uint32*)ptr == (uint32)(size_t)p) continue;
635 break;
637 default: NOT_REACHED();
639 break;
641 default: break; // Assume the other types are always changed
645 /* Value has changed, get the new value and put it into a buffer */
646 switch (sdb->cmd) {
647 case SDT_BOOLX:
648 case SDT_NUMX:
649 case SDT_ONEOFMANY:
650 case SDT_MANYOFMANY: {
651 uint32 i = (uint32)ReadValue(ptr, sld->conv);
653 switch (sdb->cmd) {
654 case SDT_BOOLX: strecpy(buf, (i != 0) ? "true" : "false", lastof(buf)); break;
655 case SDT_NUMX: seprintf(buf, lastof(buf), IsSignedVarMemType(sld->conv) ? "%d" : "%u", i); break;
656 case SDT_ONEOFMANY: MakeOneOfMany(buf, lastof(buf), sdb->many, i); break;
657 case SDT_MANYOFMANY: MakeManyOfMany(buf, lastof(buf), sdb->many, i); break;
658 default: NOT_REACHED();
660 break;
663 case SDT_STRING:
664 switch (GetVarMemType(sld->conv)) {
665 case SLE_VAR_STRB: strecpy(buf, (char*)ptr, lastof(buf)); break;
666 case SLE_VAR_STRBQ:seprintf(buf, lastof(buf), "\"%s\"", (char*)ptr); break;
667 case SLE_VAR_STR: strecpy(buf, *(char**)ptr, lastof(buf)); break;
669 case SLE_VAR_STRQ:
670 if (*(char**)ptr == NULL) {
671 buf[0] = '\0';
672 } else {
673 seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
675 break;
677 case SLE_VAR_CHAR: buf[0] = *(char*)ptr; buf[1] = '\0'; break;
678 default: NOT_REACHED();
680 break;
682 case SDT_INTLIST:
683 MakeIntList(buf, lastof(buf), ptr, sld->length, GetVarMemType(sld->conv));
684 break;
686 default: NOT_REACHED();
689 /* The value is different, that means we have to write it to the ini */
690 free(item->value);
691 item->value = stredup(buf);
696 * Loads all items from a 'grpname' section into a list
697 * The list parameter can be a NULL pointer, in this case nothing will be
698 * saved and a callback function should be defined that will take over the
699 * list-handling and store the data itself somewhere.
700 * @param ini IniFile handle to the ini file with the source data
701 * @param grpname character string identifying the section-header of the ini file that will be parsed
702 * @param list new list with entries of the given section
704 static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *list)
706 IniGroup *group = ini->GetGroup(grpname);
708 if (group == NULL || list == NULL) return;
710 list->Clear();
712 for (const IniItem *item = group->item; item != NULL; item = item->next) {
713 if (item->name != NULL) *list->Append() = stredup(item->name);
718 * Saves all items from a list into the 'grpname' section
719 * The list parameter can be a NULL pointer, in this case a callback function
720 * should be defined that will provide the source data to be saved.
721 * @param ini IniFile handle to the ini file where the destination data is saved
722 * @param grpname character string identifying the section-header of the ini file
723 * @param list pointer to an string(pointer) array that will be used as the
724 * source to be saved into the relevant ini section
726 static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *list)
728 IniGroup *group = ini->GetGroup(grpname);
730 if (group == NULL || list == NULL) return;
731 group->Clear();
733 for (char **iter = list->Begin(); iter != list->End(); iter++) {
734 group->GetItem(*iter, true)->SetValue("");
739 * Load a WindowDesc from config.
740 * @param ini IniFile handle to the ini file with the source data
741 * @param grpname character string identifying the section-header of the ini file that will be parsed
742 * @param desc Destination WindowDesc
744 void IniLoadWindowSettings(IniFile *ini, const char *grpname, void *desc)
746 IniLoadSettings(ini, _window_settings, grpname, desc);
750 * Save a WindowDesc to config.
751 * @param ini IniFile handle to the ini file where the destination data is saved
752 * @param grpname character string identifying the section-header of the ini file
753 * @param desc Source WindowDesc
755 void IniSaveWindowSettings(IniFile *ini, const char *grpname, void *desc)
757 IniSaveSettings(ini, _window_settings, grpname, desc);
761 * Check whether the setting is editable in the current gamemode.
762 * @param do_command true if this is about checking a command from the server.
763 * @return true if editable.
765 bool SettingDesc::IsEditable(bool do_command) const
767 if (!do_command && !(this->save.conv & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(this->desc.flags & SGF_PER_COMPANY)) return false;
768 if ((this->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return false;
769 if ((this->desc.flags & SGF_NO_NETWORK) && _networking) return false;
770 if ((this->desc.flags & SGF_NEWGAME_ONLY) &&
771 (_game_mode == GM_NORMAL ||
772 (_game_mode == GM_EDITOR && !(this->desc.flags & SGF_SCENEDIT_TOO)))) return false;
773 return true;
777 * Return the type of the setting.
778 * @return type of setting
780 SettingType SettingDesc::GetType() const
782 if (this->desc.flags & SGF_PER_COMPANY) return ST_COMPANY;
783 return (this->save.conv & SLF_NOT_IN_SAVE) ? ST_CLIENT : ST_GAME;
786 /* Begin - Callback Functions for the various settings. */
788 /** Reposition the main toolbar as the setting changed. */
789 static bool v_PositionMainToolbar(int32 p1)
791 if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
792 return true;
795 /** Reposition the statusbar as the setting changed. */
796 static bool v_PositionStatusbar(int32 p1)
798 if (_game_mode != GM_MENU) {
799 PositionStatusbar(NULL);
800 PositionNewsMessage(NULL);
801 PositionNetworkChatWindow(NULL);
803 return true;
806 static bool PopulationInLabelActive(int32 p1)
808 UpdateAllTownVirtCoords();
809 return true;
812 static bool RedrawScreen(int32 p1)
814 MarkWholeScreenDirty();
815 return true;
819 * Redraw the smallmap after a colour scheme change.
820 * @param p1 Callback parameter.
821 * @return Always true.
823 static bool RedrawSmallmap(int32 p1)
825 BuildLandLegend();
826 BuildOwnerLegend();
827 SetWindowClassesDirty(WC_SMALLMAP);
828 return true;
831 static bool InvalidateDetailsWindow(int32 p1)
833 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
834 return true;
837 static bool StationSpreadChanged(int32 p1)
839 InvalidateWindowData(WC_SELECT_STATION, 0);
840 InvalidateWindowData(WC_BUILD_STATION, 0);
841 return true;
844 static bool InvalidateBuildIndustryWindow(int32 p1)
846 InvalidateWindowData(WC_BUILD_INDUSTRY, 0);
847 return true;
850 static bool CloseSignalGUI(int32 p1)
852 if (p1 == 0) {
853 DeleteWindowByClass(WC_BUILD_SIGNAL);
855 return true;
858 static bool InvalidateTownViewWindow(int32 p1)
860 InvalidateWindowClassesData(WC_TOWN_VIEW, p1);
861 return true;
864 static bool DeleteSelectStationWindow(int32 p1)
866 DeleteWindowById(WC_SELECT_STATION, 0);
867 return true;
870 static bool UpdateConsists(int32 p1)
872 Train *t;
873 FOR_ALL_TRAINS(t) {
874 /* Update the consist of all trains so the maximum speed is set correctly. */
875 if (t->IsFrontEngine() || t->IsFreeWagon()) t->ConsistChanged(CCF_TRACK);
877 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
878 return true;
881 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
882 static bool CheckInterval(int32 p1)
884 bool update_vehicles;
885 VehicleDefaultSettings *vds;
886 if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
887 vds = &_settings_client.company.vehicle;
888 update_vehicles = false;
889 } else {
890 vds = &Company::Get(_current_company)->settings.vehicle;
891 update_vehicles = true;
894 if (p1 != 0) {
895 vds->servint_trains = 50;
896 vds->servint_roadveh = 50;
897 vds->servint_aircraft = 50;
898 vds->servint_ships = 50;
899 } else {
900 vds->servint_trains = 150;
901 vds->servint_roadveh = 150;
902 vds->servint_aircraft = 100;
903 vds->servint_ships = 360;
906 if (update_vehicles) {
907 const Company *c = Company::Get(_current_company);
908 Vehicle *v;
909 FOR_ALL_VEHICLES(v) {
910 if (v->owner == _current_company && v->IsPrimaryVehicle() && !v->ServiceIntervalIsCustom()) {
911 v->SetServiceInterval(CompanyServiceInterval(c, v->type));
912 v->SetServiceIntervalIsPercent(p1 != 0);
917 InvalidateDetailsWindow(0);
919 return true;
922 static bool UpdateInterval(VehicleType type, int32 p1)
924 bool update_vehicles;
925 VehicleDefaultSettings *vds;
926 if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
927 vds = &_settings_client.company.vehicle;
928 update_vehicles = false;
929 } else {
930 vds = &Company::Get(_current_company)->settings.vehicle;
931 update_vehicles = true;
934 /* Test if the interval is valid */
935 uint16 interval = GetServiceIntervalClamped(p1, vds->servint_ispercent);
936 if (interval != p1) return false;
938 if (update_vehicles) {
939 Vehicle *v;
940 FOR_ALL_VEHICLES(v) {
941 if (v->owner == _current_company && v->type == type && v->IsPrimaryVehicle() && !v->ServiceIntervalIsCustom()) {
942 v->SetServiceInterval(p1);
947 InvalidateDetailsWindow(0);
949 return true;
952 static bool UpdateIntervalTrains(int32 p1)
954 return UpdateInterval(VEH_TRAIN, p1);
957 static bool UpdateIntervalRoadVeh(int32 p1)
959 return UpdateInterval(VEH_ROAD, p1);
962 static bool UpdateIntervalShips(int32 p1)
964 return UpdateInterval(VEH_SHIP, p1);
967 static bool UpdateIntervalAircraft(int32 p1)
969 return UpdateInterval(VEH_AIRCRAFT, p1);
972 static bool TrainAccelerationModelChanged(int32 p1)
974 Train *t;
975 FOR_ALL_TRAINS(t) {
976 if (t->IsFrontEngine()) {
977 t->tcache.cached_max_curve_speed = t->GetCurveSpeedLimit();
978 t->UpdateAcceleration();
982 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
983 SetWindowClassesDirty(WC_ENGINE_PREVIEW);
984 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
985 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
987 return true;
991 * This function updates the train acceleration cache after a steepness change.
992 * @param p1 Callback parameter.
993 * @return Always true.
995 static bool TrainSlopeSteepnessChanged(int32 p1)
997 Train *t;
998 FOR_ALL_TRAINS(t) {
999 if (t->IsFrontEngine()) t->CargoChanged();
1002 return true;
1006 * This function updates realistic acceleration caches when the setting "Road vehicle acceleration model" is set.
1007 * @param p1 Callback parameter
1008 * @return Always true
1010 static bool RoadVehAccelerationModelChanged(int32 p1)
1012 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
1013 RoadVehicle *rv;
1014 FOR_ALL_ROADVEHICLES(rv) {
1015 if (rv->IsFrontEngine()) {
1016 rv->CargoChanged();
1021 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1022 SetWindowClassesDirty(WC_ENGINE_PREVIEW);
1023 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
1024 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
1026 return true;
1030 * This function updates the road vehicle acceleration cache after a steepness change.
1031 * @param p1 Callback parameter.
1032 * @return Always true.
1034 static bool RoadVehSlopeSteepnessChanged(int32 p1)
1036 RoadVehicle *rv;
1037 FOR_ALL_ROADVEHICLES(rv) {
1038 if (rv->IsFrontEngine()) rv->CargoChanged();
1041 return true;
1044 static bool DragSignalsDensityChanged(int32)
1046 InvalidateWindowData(WC_BUILD_SIGNAL, 0);
1048 return true;
1051 static bool TownFoundingChanged(int32 p1)
1053 if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
1054 DeleteWindowById(WC_FOUND_TOWN, 0);
1055 return true;
1057 InvalidateWindowData(WC_FOUND_TOWN, 0);
1058 return true;
1061 static bool InvalidateVehTimetableWindow(int32 p1)
1063 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE, VIWD_MODIFY_ORDERS);
1064 return true;
1067 static bool ZoomMinMaxChanged(int32 p1)
1069 extern void ConstrainAllViewportsZoom();
1070 ConstrainAllViewportsZoom();
1071 GfxClearSpriteCache();
1072 if (_settings_client.gui.zoom_min > _gui_zoom) {
1073 /* Restrict GUI zoom if it is no longer available. */
1074 _gui_zoom = _settings_client.gui.zoom_min;
1075 UpdateCursorSize();
1076 LoadStringWidthTable();
1078 return true;
1082 * Update any possible saveload window and delete any newgrf dialogue as
1083 * its widget parts might change. Reinit all windows as it allows access to the
1084 * newgrf debug button.
1085 * @param p1 unused.
1086 * @return Always true.
1088 static bool InvalidateNewGRFChangeWindows(int32 p1)
1090 InvalidateWindowClassesData(WC_SAVELOAD);
1091 DeleteWindowByClass(WC_GAME_OPTIONS);
1092 ReInitAllWindows();
1093 return true;
1096 static bool InvalidateCompanyLiveryWindow(int32 p1)
1098 InvalidateWindowClassesData(WC_COMPANY_COLOUR);
1099 return RedrawScreen(p1);
1102 static bool InvalidateIndustryViewWindow(int32 p1)
1104 InvalidateWindowClassesData(WC_INDUSTRY_VIEW);
1105 return true;
1108 static bool InvalidateAISettingsWindow(int32 p1)
1110 InvalidateWindowClassesData(WC_AI_SETTINGS);
1111 return true;
1115 * Update the town authority window after a town authority setting change.
1116 * @param p1 Unused.
1117 * @return Always true.
1119 static bool RedrawTownAuthority(int32 p1)
1121 SetWindowClassesDirty(WC_TOWN_AUTHORITY);
1122 return true;
1126 * Invalidate the company infrastructure details window after a infrastructure maintenance setting change.
1127 * @param p1 Unused.
1128 * @return Always true.
1130 static bool InvalidateCompanyInfrastructureWindow(int32 p1)
1132 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
1133 return true;
1137 * Invalidate the company details window after the shares setting changed.
1138 * @param p1 Unused.
1139 * @return Always true.
1141 static bool InvalidateCompanyWindow(int32 p1)
1143 InvalidateWindowClassesData(WC_COMPANY);
1144 return true;
1147 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
1148 static void ValidateSettings()
1150 /* Do not allow a custom sea level with the original land generator. */
1151 if (_settings_newgame.game_creation.land_generator == LG_ORIGINAL &&
1152 _settings_newgame.difficulty.quantity_sea_lakes == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) {
1153 _settings_newgame.difficulty.quantity_sea_lakes = CUSTOM_SEA_LEVEL_MIN_PERCENTAGE;
1157 static bool DifficultyNoiseChange(int32 i)
1159 if (_game_mode == GM_NORMAL) {
1160 UpdateAirportsNoise();
1161 if (_settings_game.economy.station_noise_level) {
1162 InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
1166 return true;
1169 static bool MaxNoAIsChange(int32 i)
1171 if (GetGameSettings().difficulty.max_no_competitors != 0 &&
1172 AI::GetInfoList()->size() == 0 &&
1173 (!_networking || _network_server)) {
1174 ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, WL_CRITICAL);
1177 return true;
1181 * Check whether the road side may be changed.
1182 * @param p1 unused
1183 * @return true if the road side may be changed.
1185 static bool CheckRoadSide(int p1)
1187 extern bool RoadVehiclesAreBuilt();
1188 return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
1192 * Conversion callback for _gameopt_settings_game.landscape
1193 * It converts (or try) between old values and the new ones,
1194 * without losing initial setting of the user
1195 * @param value that was read from config file
1196 * @return the "hopefully" converted value
1198 static size_t ConvertLandscape(const char *value)
1200 /* try with the old values */
1201 return LookupOneOfMany("normal|hilly|desert|candy", value);
1204 static bool CheckFreeformEdges(int32 p1)
1206 if (_game_mode == GM_MENU) return true;
1207 if (p1 != 0) {
1208 Ship *s;
1209 FOR_ALL_SHIPS(s) {
1210 /* Check if there is a ship on the northern border. */
1211 if (TileX(s->tile) == 0 || TileY(s->tile) == 0) {
1212 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
1213 return false;
1216 BaseStation *st;
1217 FOR_ALL_BASE_STATIONS(st) {
1218 /* Check if there is a non-deleted buoy on the northern border. */
1219 if (st->IsInUse() && (TileX(st->xy) == 0 || TileY(st->xy) == 0)) {
1220 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
1221 return false;
1224 for (uint i = 0; i < MapSizeX(); i++) MakeVoid(TileXY(i, 0));
1225 for (uint i = 0; i < MapSizeY(); i++) MakeVoid(TileXY(0, i));
1226 } else {
1227 for (uint i = 0; i < MapMaxX(); i++) {
1228 if (TileHeight(TileXY(i, 1)) != 0) {
1229 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1230 return false;
1233 for (uint i = 1; i < MapMaxX(); i++) {
1234 if (!IsTileType(TileXY(i, MapMaxY() - 1), MP_WATER) || TileHeight(TileXY(1, MapMaxY())) != 0) {
1235 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1236 return false;
1239 for (uint i = 0; i < MapMaxY(); i++) {
1240 if (TileHeight(TileXY(1, i)) != 0) {
1241 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1242 return false;
1245 for (uint i = 1; i < MapMaxY(); i++) {
1246 if (!IsTileType(TileXY(MapMaxX() - 1, i), MP_WATER) || TileHeight(TileXY(MapMaxX(), i)) != 0) {
1247 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1248 return false;
1251 /* Make tiles at the border water again. */
1252 for (uint i = 0; i < MapMaxX(); i++) {
1253 SetTileHeight(TileXY(i, 0), 0);
1254 SetTileType(TileXY(i, 0), MP_WATER);
1256 for (uint i = 0; i < MapMaxY(); i++) {
1257 SetTileHeight(TileXY(0, i), 0);
1258 SetTileType(TileXY(0, i), MP_WATER);
1261 MarkWholeScreenDirty();
1262 return true;
1266 * Changing the setting "allow multiple NewGRF sets" is not allowed
1267 * if there are vehicles.
1269 static bool ChangeDynamicEngines(int32 p1)
1271 if (_game_mode == GM_MENU) return true;
1273 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
1274 ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, WL_ERROR);
1275 return false;
1278 return true;
1281 static bool ChangeMaxHeightLevel(int32 p1)
1283 if (_game_mode == GM_NORMAL) return false;
1284 if (_game_mode != GM_EDITOR) return true;
1286 /* Check if at least one mountain on the map is higher than the new value.
1287 * If yes, disallow the change. */
1288 for (TileIndex t = 0; t < MapSize(); t++) {
1289 if ((int32)TileHeight(t) > p1) {
1290 ShowErrorMessage(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN, INVALID_STRING_ID, WL_ERROR);
1291 /* Return old, unchanged value */
1292 return false;
1296 /* The smallmap uses an index from heightlevels to colours. Trigger rebuilding it. */
1297 InvalidateWindowClassesData(WC_SMALLMAP, 2);
1299 return true;
1302 static bool StationCatchmentChanged(int32 p1)
1304 Station::RecomputeIndustriesNearForAll();
1305 return true;
1308 static bool MaxVehiclesChanged(int32 p1)
1310 InvalidateWindowClassesData(WC_BUILD_TOOLBAR);
1311 MarkWholeScreenDirty();
1312 return true;
1316 #ifdef ENABLE_NETWORK
1318 static bool UpdateClientName(int32 p1)
1320 NetworkUpdateClientName();
1321 return true;
1324 static bool UpdateServerPassword(int32 p1)
1326 if (strcmp(_settings_client.network.server_password, "*") == 0) {
1327 _settings_client.network.server_password[0] = '\0';
1330 return true;
1333 static bool UpdateRconPassword(int32 p1)
1335 if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
1336 _settings_client.network.rcon_password[0] = '\0';
1339 return true;
1342 static bool UpdateClientConfigValues(int32 p1)
1344 if (_network_server) NetworkServerSendConfigUpdate();
1346 return true;
1349 #endif /* ENABLE_NETWORK */
1352 /* End - Callback Functions */
1355 * Prepare for reading and old diff_custom by zero-ing the memory.
1357 static void PrepareOldDiffCustom()
1359 memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
1363 * Reading of the old diff_custom array and transforming it to the new format.
1364 * @param savegame is it read from the config or savegame. In the latter case
1365 * we are sure there is an array; in the former case we have
1366 * to check that.
1368 static void HandleOldDiffCustom(bool savegame)
1370 uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && IsSavegameVersionBefore(4)) ? 1 : 0);
1372 if (!savegame) {
1373 /* If we did read to old_diff_custom, then at least one value must be non 0. */
1374 bool old_diff_custom_used = false;
1375 for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
1376 old_diff_custom_used = (_old_diff_custom[i] != 0);
1379 if (!old_diff_custom_used) return;
1382 for (uint i = 0; i < options_to_load; i++) {
1383 const SettingDesc *sd = &_settings[i];
1384 /* Skip deprecated options */
1385 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1386 void *var = GetVariableAddress(savegame ? &_settings_game : &_settings_newgame, &sd->save);
1387 Write_ValidateSetting(var, sd, (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]));
1391 static void AILoadConfig(IniFile *ini, const char *grpname)
1393 IniGroup *group = ini->GetGroup(grpname);
1394 IniItem *item;
1396 /* Clean any configured AI */
1397 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1398 AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME)->Change(NULL);
1401 /* If no group exists, return */
1402 if (group == NULL) return;
1404 CompanyID c = COMPANY_FIRST;
1405 for (item = group->item; c < MAX_COMPANIES && item != NULL; c++, item = item->next) {
1406 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1408 config->Change(item->name);
1409 if (!config->HasScript()) {
1410 if (strcmp(item->name, "none") != 0) {
1411 DEBUG(script, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item->name);
1412 continue;
1415 if (item->value != NULL) config->StringToSettings(item->value);
1419 static void GameLoadConfig(IniFile *ini, const char *grpname)
1421 IniGroup *group = ini->GetGroup(grpname);
1422 IniItem *item;
1424 /* Clean any configured GameScript */
1425 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME)->Change(NULL);
1427 /* If no group exists, return */
1428 if (group == NULL) return;
1430 item = group->item;
1431 if (item == NULL) return;
1433 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1435 config->Change(item->name);
1436 if (!config->HasScript()) {
1437 if (strcmp(item->name, "none") != 0) {
1438 DEBUG(script, 0, "The GameScript by the name '%s' was no longer found, and removed from the list.", item->name);
1439 return;
1442 if (item->value != NULL) config->StringToSettings(item->value);
1446 * Convert a character to a hex nibble value, or \c -1 otherwise.
1447 * @param c Character to convert.
1448 * @return Hex value of the character, or \c -1 if not a hex digit.
1450 static int DecodeHexNibble(char c)
1452 if (c >= '0' && c <= '9') return c - '0';
1453 if (c >= 'A' && c <= 'F') return c + 10 - 'A';
1454 if (c >= 'a' && c <= 'f') return c + 10 - 'a';
1455 return -1;
1459 * Parse a sequence of characters (supposedly hex digits) into a sequence of bytes.
1460 * After the hex number should be a \c '|' character.
1461 * @param pos First character to convert.
1462 * @param dest [out] Output byte array to write the bytes.
1463 * @param dest_size Number of bytes in \a dest.
1464 * @return Whether reading was successful.
1466 static bool DecodeHexText(char *pos, uint8 *dest, size_t dest_size)
1468 while (dest_size > 0) {
1469 int hi = DecodeHexNibble(pos[0]);
1470 int lo = (hi >= 0) ? DecodeHexNibble(pos[1]) : -1;
1471 if (lo < 0) return false;
1472 *dest++ = (hi << 4) | lo;
1473 pos += 2;
1474 dest_size--;
1476 return *pos == '|';
1480 * Load a GRF configuration
1481 * @param ini The configuration to read from.
1482 * @param grpname Group name containing the configuration of the GRF.
1483 * @param is_static GRF is static.
1485 static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
1487 IniGroup *group = ini->GetGroup(grpname);
1488 IniItem *item;
1489 GRFConfig *first = NULL;
1490 GRFConfig **curr = &first;
1492 if (group == NULL) return NULL;
1494 for (item = group->item; item != NULL; item = item->next) {
1495 GRFConfig *c = NULL;
1497 uint8 grfid_buf[4], md5sum[16];
1498 char *filename = item->name;
1499 bool has_grfid = false;
1500 bool has_md5sum = false;
1502 /* Try reading "<grfid>|" and on success, "<md5sum>|". */
1503 has_grfid = DecodeHexText(filename, grfid_buf, lengthof(grfid_buf));
1504 if (has_grfid) {
1505 filename += 1 + 2 * lengthof(grfid_buf);
1506 has_md5sum = DecodeHexText(filename, md5sum, lengthof(md5sum));
1507 if (has_md5sum) filename += 1 + 2 * lengthof(md5sum);
1509 uint32 grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
1510 if (has_md5sum) {
1511 const GRFConfig *s = FindGRFConfig(grfid, FGCM_EXACT, md5sum);
1512 if (s != NULL) c = new GRFConfig(*s);
1514 if (c == NULL && !FioCheckFileExists(filename, NEWGRF_DIR)) {
1515 const GRFConfig *s = FindGRFConfig(grfid, FGCM_NEWEST_VALID);
1516 if (s != NULL) c = new GRFConfig(*s);
1519 if (c == NULL) c = new GRFConfig(filename);
1521 /* Parse parameters */
1522 if (!StrEmpty(item->value)) {
1523 int count = ParseIntList(item->value, (int*)c->param, lengthof(c->param));
1524 if (count < 0) {
1525 SetDParamStr(0, filename);
1526 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY, WL_CRITICAL);
1527 count = 0;
1529 c->num_params = count;
1532 /* Check if item is valid */
1533 if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
1534 if (c->status == GCS_NOT_FOUND) {
1535 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND);
1536 } else if (HasBit(c->flags, GCF_UNSAFE)) {
1537 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE);
1538 } else if (HasBit(c->flags, GCF_SYSTEM)) {
1539 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM);
1540 } else if (HasBit(c->flags, GCF_INVALID)) {
1541 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE);
1542 } else {
1543 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN);
1546 SetDParamStr(0, StrEmpty(filename) ? item->name : filename);
1547 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_GRF, WL_CRITICAL);
1548 delete c;
1549 continue;
1552 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1553 bool duplicate = false;
1554 for (const GRFConfig *gc = first; gc != NULL; gc = gc->next) {
1555 if (gc->ident.grfid == c->ident.grfid) {
1556 SetDParamStr(0, c->filename);
1557 SetDParamStr(1, gc->filename);
1558 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_DUPLICATE_GRFID, WL_CRITICAL);
1559 duplicate = true;
1560 break;
1563 if (duplicate) {
1564 delete c;
1565 continue;
1568 /* Mark file as static to avoid saving in savegame. */
1569 if (is_static) SetBit(c->flags, GCF_STATIC);
1571 /* Add item to list */
1572 *curr = c;
1573 curr = &c->next;
1576 return first;
1579 static void AISaveConfig(IniFile *ini, const char *grpname)
1581 IniGroup *group = ini->GetGroup(grpname);
1583 if (group == NULL) return;
1584 group->Clear();
1586 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1587 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1588 const char *name;
1589 char value[1024];
1590 config->SettingsToString(value, lastof(value));
1592 if (config->HasScript()) {
1593 name = config->GetName();
1594 } else {
1595 name = "none";
1598 IniItem *item = new IniItem(group, name);
1599 item->SetValue(value);
1603 static void GameSaveConfig(IniFile *ini, const char *grpname)
1605 IniGroup *group = ini->GetGroup(grpname);
1607 if (group == NULL) return;
1608 group->Clear();
1610 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1611 const char *name;
1612 char value[1024];
1613 config->SettingsToString(value, lastof(value));
1615 if (config->HasScript()) {
1616 name = config->GetName();
1617 } else {
1618 name = "none";
1621 IniItem *item = new IniItem(group, name);
1622 item->SetValue(value);
1626 * Save the version of OpenTTD to the ini file.
1627 * @param ini the ini to write to
1629 static void SaveVersionInConfig(IniFile *ini)
1631 IniGroup *group = ini->GetGroup("version");
1633 char version[9];
1634 seprintf(version, lastof(version), "%08X", _openttd_newgrf_version);
1636 const char * const versions[][2] = {
1637 { "version_string", _openttd_revision },
1638 { "version_number", version }
1641 for (uint i = 0; i < lengthof(versions); i++) {
1642 group->GetItem(versions[i][0], true)->SetValue(versions[i][1]);
1646 /* Save a GRF configuration to the given group name */
1647 static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
1649 ini->RemoveGroup(grpname);
1650 IniGroup *group = ini->GetGroup(grpname);
1651 const GRFConfig *c;
1653 for (c = list; c != NULL; c = c->next) {
1654 /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1655 char key[4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH];
1656 char params[512];
1657 GRFBuildParamList(params, c, lastof(params));
1659 char *pos = key + seprintf(key, lastof(key), "%08X|", BSWAP32(c->ident.grfid));
1660 pos = md5sumToString(pos, lastof(key), c->ident.md5sum);
1661 seprintf(pos, lastof(key), "|%s", c->filename);
1662 group->GetItem(key, true)->SetValue(params);
1666 /* Common handler for saving/loading variables to the configuration file */
1667 static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list, bool basic_settings = true, bool other_settings = true)
1669 if (basic_settings) {
1670 proc(ini, (const SettingDesc*)_misc_settings, "misc", NULL);
1671 #if defined(WIN32) && !defined(DEDICATED)
1672 proc(ini, (const SettingDesc*)_win32_settings, "win32", NULL);
1673 #endif /* WIN32 */
1676 if (other_settings) {
1677 proc(ini, _settings, "patches", &_settings_newgame);
1678 proc(ini, _currency_settings,"currency", &_custom_currency);
1679 proc(ini, _company_settings, "company", &_settings_client.company);
1681 #ifdef ENABLE_NETWORK
1682 proc_list(ini, "server_bind_addresses", &_network_bind_list);
1683 proc_list(ini, "servers", &_network_host_list);
1684 proc_list(ini, "bans", &_network_ban_list);
1685 #endif /* ENABLE_NETWORK */
1689 static IniFile *IniLoadConfig()
1691 IniFile *ini = new IniFile(_list_group_names);
1692 ini->LoadFromDisk(_config_file, NO_DIRECTORY);
1693 return ini;
1697 * Load the values from the configuration files
1698 * @param minimal Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1700 void LoadFromConfig(bool minimal)
1702 IniFile *ini = IniLoadConfig();
1703 if (!minimal) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1705 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1706 HandleSettingDescs(ini, IniLoadSettings, IniLoadSettingList, minimal, !minimal);
1708 if (!minimal) {
1709 _grfconfig_newgame = GRFLoadConfig(ini, "newgrf", false);
1710 _grfconfig_static = GRFLoadConfig(ini, "newgrf-static", true);
1711 AILoadConfig(ini, "ai_players");
1712 GameLoadConfig(ini, "game_scripts");
1714 PrepareOldDiffCustom();
1715 IniLoadSettings(ini, _gameopt_settings, "gameopt", &_settings_newgame);
1716 HandleOldDiffCustom(false);
1718 ValidateSettings();
1720 /* Display sheduled errors */
1721 extern void ScheduleErrorMessage(ErrorList &datas);
1722 ScheduleErrorMessage(_settings_error_list);
1723 if (FindWindowById(WC_ERRMSG, 0) == NULL) ShowFirstError();
1726 delete ini;
1729 /** Save the values to the configuration file */
1730 void SaveToConfig()
1732 IniFile *ini = IniLoadConfig();
1734 /* Remove some obsolete groups. These have all been loaded into other groups. */
1735 ini->RemoveGroup("patches");
1736 ini->RemoveGroup("yapf");
1737 ini->RemoveGroup("gameopt");
1739 HandleSettingDescs(ini, IniSaveSettings, IniSaveSettingList);
1740 GRFSaveConfig(ini, "newgrf", _grfconfig_newgame);
1741 GRFSaveConfig(ini, "newgrf-static", _grfconfig_static);
1742 AISaveConfig(ini, "ai_players");
1743 GameSaveConfig(ini, "game_scripts");
1744 SaveVersionInConfig(ini);
1745 ini->SaveToDisk(_config_file);
1746 delete ini;
1750 * Get the list of known NewGrf presets.
1751 * @param list[inout] Pointer to list for storing the preset names.
1753 void GetGRFPresetList(GRFPresetList *list)
1755 list->Clear();
1757 IniFile *ini = IniLoadConfig();
1758 IniGroup *group;
1759 for (group = ini->group; group != NULL; group = group->next) {
1760 if (strncmp(group->name, "preset-", 7) == 0) {
1761 *list->Append() = stredup(group->name + 7);
1765 delete ini;
1769 * Load a NewGRF configuration by preset-name.
1770 * @param config_name Name of the preset.
1771 * @return NewGRF configuration.
1772 * @see GetGRFPresetList
1774 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
1776 size_t len = strlen(config_name) + 8;
1777 char *section = (char*)alloca(len);
1778 seprintf(section, section + len - 1, "preset-%s", config_name);
1780 IniFile *ini = IniLoadConfig();
1781 GRFConfig *config = GRFLoadConfig(ini, section, false);
1782 delete ini;
1784 return config;
1788 * Save a NewGRF configuration with a preset name.
1789 * @param config_name Name of the preset.
1790 * @param config NewGRF configuration to save.
1791 * @see GetGRFPresetList
1793 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
1795 size_t len = strlen(config_name) + 8;
1796 char *section = (char*)alloca(len);
1797 seprintf(section, section + len - 1, "preset-%s", config_name);
1799 IniFile *ini = IniLoadConfig();
1800 GRFSaveConfig(ini, section, config);
1801 ini->SaveToDisk(_config_file);
1802 delete ini;
1806 * Delete a NewGRF configuration by preset name.
1807 * @param config_name Name of the preset.
1809 void DeleteGRFPresetFromConfig(const char *config_name)
1811 size_t len = strlen(config_name) + 8;
1812 char *section = (char*)alloca(len);
1813 seprintf(section, section + len - 1, "preset-%s", config_name);
1815 IniFile *ini = IniLoadConfig();
1816 ini->RemoveGroup(section);
1817 ini->SaveToDisk(_config_file);
1818 delete ini;
1821 const SettingDesc *GetSettingDescription(uint index)
1823 if (index >= lengthof(_settings)) return NULL;
1824 return &_settings[index];
1828 * Network-safe changing of settings (server-only).
1829 * @param tile unused
1830 * @param flags operation to perform
1831 * @param p1 the index of the setting in the SettingDesc 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
1836 * @see _settings
1838 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1840 const SettingDesc *sd = GetSettingDescription(p1);
1842 if (sd == NULL) return CMD_ERROR;
1843 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
1845 if (!sd->IsEditable(true)) return CMD_ERROR;
1847 if (flags & DC_EXEC) {
1848 void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
1850 int32 oldval = (int32)ReadValue(var, sd->save.conv);
1851 int32 newval = (int32)p2;
1853 Write_ValidateSetting(var, sd, newval);
1854 newval = (int32)ReadValue(var, sd->save.conv);
1856 if (oldval == newval) return CommandCost();
1858 if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
1859 WriteValue(var, sd->save.conv, (int64)oldval);
1860 return CommandCost();
1863 if (sd->desc.flags & SGF_NO_NETWORK) {
1864 GamelogStartAction(GLAT_SETTING);
1865 GamelogSetting(sd->desc.name, oldval, newval);
1866 GamelogStopAction();
1869 SetWindowClassesDirty(WC_GAME_OPTIONS);
1872 return CommandCost();
1876 * Change one of the per-company settings.
1877 * @param tile unused
1878 * @param flags operation to perform
1879 * @param p1 the index of the setting in the _company_settings array which identifies it
1880 * @param p2 the new value for the setting
1881 * The new value is properly clamped to its minimum/maximum when setting
1882 * @param text unused
1883 * @return the cost of this operation or an error
1885 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1887 if (p1 >= lengthof(_company_settings)) return CMD_ERROR;
1888 const SettingDesc *sd = &_company_settings[p1];
1890 if (flags & DC_EXEC) {
1891 void *var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
1893 int32 oldval = (int32)ReadValue(var, sd->save.conv);
1894 int32 newval = (int32)p2;
1896 Write_ValidateSetting(var, sd, newval);
1897 newval = (int32)ReadValue(var, sd->save.conv);
1899 if (oldval == newval) return CommandCost();
1901 if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
1902 WriteValue(var, sd->save.conv, (int64)oldval);
1903 return CommandCost();
1906 SetWindowClassesDirty(WC_GAME_OPTIONS);
1909 return CommandCost();
1913 * Top function to save the new value of an element of the Settings struct
1914 * @param index offset in the SettingDesc array of the Settings struct which
1915 * identifies the setting member we want to change
1916 * @param value new value of the setting
1917 * @param force_newgame force the newgame settings
1919 bool SetSettingValue(uint index, int32 value, bool force_newgame)
1921 const SettingDesc *sd = &_settings[index];
1922 /* If an item is company-based, we do not send it over the network
1923 * (if any) to change. Also *hack*hack* we update the _newgame version
1924 * of settings because changing a company-based setting in a game also
1925 * changes its defaults. At least that is the convention we have chosen */
1926 if (sd->save.conv & SLF_NO_NETWORK_SYNC) {
1927 void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
1928 Write_ValidateSetting(var, sd, value);
1930 if (_game_mode != GM_MENU) {
1931 void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
1932 Write_ValidateSetting(var2, sd, value);
1934 if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
1936 SetWindowClassesDirty(WC_GAME_OPTIONS);
1938 return true;
1941 if (force_newgame) {
1942 void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
1943 Write_ValidateSetting(var2, sd, value);
1944 return true;
1947 /* send non-company-based settings over the network */
1948 if (!_networking || (_networking && _network_server)) {
1949 return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
1951 return false;
1955 * Top function to save the new value of an element of the Settings struct
1956 * @param index offset in the SettingDesc array of the CompanySettings struct
1957 * which identifies the setting member we want to change
1958 * @param value new value of the setting
1960 void SetCompanySetting(uint index, int32 value)
1962 const SettingDesc *sd = &_company_settings[index];
1963 if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
1964 DoCommandP(0, index, value, CMD_CHANGE_COMPANY_SETTING);
1965 } else {
1966 void *var = GetVariableAddress(&_settings_client.company, &sd->save);
1967 Write_ValidateSetting(var, sd, value);
1968 if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
1973 * Set the company settings for a new company to their default values.
1975 void SetDefaultCompanySettings(CompanyID cid)
1977 Company *c = Company::Get(cid);
1978 const SettingDesc *sd;
1979 for (sd = _company_settings; sd->save.cmd != SL_END; sd++) {
1980 void *var = GetVariableAddress(&c->settings, &sd->save);
1981 Write_ValidateSetting(var, sd, (int32)(size_t)sd->desc.def);
1985 #if defined(ENABLE_NETWORK)
1987 * Sync all company settings in a multiplayer game.
1989 void SyncCompanySettings()
1991 const SettingDesc *sd;
1992 uint i = 0;
1993 for (sd = _company_settings; sd->save.cmd != SL_END; sd++, i++) {
1994 const void *old_var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
1995 const void *new_var = GetVariableAddress(&_settings_client.company, &sd->save);
1996 uint32 old_value = (uint32)ReadValue(old_var, sd->save.conv);
1997 uint32 new_value = (uint32)ReadValue(new_var, sd->save.conv);
1998 if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, NULL, NULL, _local_company);
2001 #endif /* ENABLE_NETWORK */
2004 * Get the index in the _company_settings array of a setting
2005 * @param name The name of the setting
2006 * @return The index in the _company_settings array
2008 uint GetCompanySettingIndex(const char *name)
2010 uint i;
2011 const SettingDesc *sd = GetSettingFromName(name, &i);
2012 assert(sd != NULL && (sd->desc.flags & SGF_PER_COMPANY) != 0);
2013 return i;
2017 * Set a setting value with a string.
2018 * @param index the settings index.
2019 * @param value the value to write
2020 * @param force_newgame force the newgame settings
2021 * @note Strings WILL NOT be synced over the network
2023 bool SetSettingValue(uint index, const char *value, bool force_newgame)
2025 const SettingDesc *sd = &_settings[index];
2026 assert(sd->save.conv & SLF_NO_NETWORK_SYNC);
2028 if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
2029 char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
2030 free(*var);
2031 *var = strcmp(value, "(null)") == 0 ? NULL : stredup(value);
2032 } else {
2033 char *var = (char*)GetVariableAddress(NULL, &sd->save);
2034 strecpy(var, value, &var[sd->save.length - 1]);
2036 if (sd->desc.proc != NULL) sd->desc.proc(0);
2038 return true;
2042 * Given a name of setting, return a setting description of it.
2043 * @param name Name of the setting to return a setting description of
2044 * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
2045 * @return Pointer to the setting description of setting \a name if it can be found,
2046 * \c NULL indicates failure to obtain the description
2048 const SettingDesc *GetSettingFromName(const char *name, uint *i)
2050 const SettingDesc *sd;
2052 /* First check all full names */
2053 for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2054 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2055 if (strcmp(sd->desc.name, name) == 0) return sd;
2058 /* Then check the shortcut variant of the name. */
2059 for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2060 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2061 const char *short_name = strchr(sd->desc.name, '.');
2062 if (short_name != NULL) {
2063 short_name++;
2064 if (strcmp(short_name, name) == 0) return sd;
2068 if (strncmp(name, "company.", 8) == 0) name += 8;
2069 /* And finally the company-based settings */
2070 for (*i = 0, sd = _company_settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2071 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2072 if (strcmp(sd->desc.name, name) == 0) return sd;
2075 return NULL;
2078 /* Those 2 functions need to be here, else we have to make some stuff non-static
2079 * and besides, it is also better to keep stuff like this at the same place */
2080 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
2082 uint index;
2083 const SettingDesc *sd = GetSettingFromName(name, &index);
2085 if (sd == NULL) {
2086 IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2087 return;
2090 bool success;
2091 if (sd->desc.cmd == SDT_STRING) {
2092 success = SetSettingValue(index, value, force_newgame);
2093 } else {
2094 uint32 val;
2095 extern bool GetArgumentInteger(uint32 *value, const char *arg);
2096 success = GetArgumentInteger(&val, value);
2097 if (!success) {
2098 IConsolePrintF(CC_ERROR, "'%s' is not an integer.", value);
2099 return;
2102 success = SetSettingValue(index, val, force_newgame);
2105 if (!success) {
2106 if (_network_server) {
2107 IConsoleError("This command/variable is not available during network games.");
2108 } else {
2109 IConsoleError("This command/variable is only available to a network server.");
2114 void IConsoleSetSetting(const char *name, int value)
2116 uint index;
2117 const SettingDesc *sd = GetSettingFromName(name, &index);
2118 assert(sd != NULL);
2119 SetSettingValue(index, value);
2123 * Output value of a specific setting to the console
2124 * @param name Name of the setting to output its value
2125 * @param force_newgame force the newgame settings
2127 void IConsoleGetSetting(const char *name, bool force_newgame)
2129 char value[20];
2130 uint index;
2131 const SettingDesc *sd = GetSettingFromName(name, &index);
2132 const void *ptr;
2134 if (sd == NULL) {
2135 IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2136 return;
2139 ptr = GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
2141 if (sd->desc.cmd == SDT_STRING) {
2142 IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char * const *)ptr : (const char *)ptr);
2143 } else {
2144 if (sd->desc.cmd == SDT_BOOLX) {
2145 seprintf(value, lastof(value), (*(const bool*)ptr != 0) ? "on" : "off");
2146 } else {
2147 seprintf(value, lastof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
2150 IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
2151 name, value, (sd->desc.flags & SGF_0ISDISABLED) ? "(0) " : "", sd->desc.min, sd->desc.max);
2156 * List all settings and their value to the console
2158 * @param prefilter If not \c NULL, only list settings with names that begin with \a prefilter prefix
2160 void IConsoleListSettings(const char *prefilter)
2162 IConsolePrintF(CC_WARNING, "All settings with their current value:");
2164 for (const SettingDesc *sd = _settings; sd->save.cmd != SL_END; sd++) {
2165 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2166 if (prefilter != NULL && strstr(sd->desc.name, prefilter) == NULL) continue;
2167 char value[80];
2168 const void *ptr = GetVariableAddress(&GetGameSettings(), &sd->save);
2170 if (sd->desc.cmd == SDT_BOOLX) {
2171 seprintf(value, lastof(value), (*(const bool *)ptr != 0) ? "on" : "off");
2172 } else if (sd->desc.cmd == SDT_STRING) {
2173 seprintf(value, lastof(value), "%s", (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char * const *)ptr : (const char *)ptr);
2174 } else {
2175 seprintf(value, lastof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
2177 IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
2180 IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
2184 * Save and load handler for settings
2185 * @param osd SettingDesc struct containing all information
2186 * @param object can be either NULL in which case we load global variables or
2187 * a pointer to a struct which is getting saved
2189 static void LoadSettings(const SettingDesc *osd, void *object)
2191 for (; osd->save.cmd != SL_END; osd++) {
2192 const SaveLoad *sld = &osd->save;
2193 void *ptr = GetVariableAddress(object, sld);
2195 if (!SlObjectMember(ptr, sld)) continue;
2196 if (IsNumericType(sld->conv)) Write_ValidateSetting(ptr, osd, ReadValue(ptr, sld->conv));
2201 * Save and load handler for settings
2202 * @param sd SettingDesc struct containing all information
2203 * @param object can be either NULL in which case we load global variables or
2204 * a pointer to a struct which is getting saved
2206 static void SaveSettings(const SettingDesc *sd, void *object)
2208 /* We need to write the CH_RIFF header, but unfortunately can't call
2209 * SlCalcLength() because we have a different format. So do this manually */
2210 const SettingDesc *i;
2211 size_t length = 0;
2212 for (i = sd; i->save.cmd != SL_END; i++) {
2213 length += SlCalcObjMemberLength(object, &i->save);
2215 SlSetLength(length);
2217 for (i = sd; i->save.cmd != SL_END; i++) {
2218 void *ptr = GetVariableAddress(object, &i->save);
2219 SlObjectMember(ptr, &i->save);
2223 static void Load_OPTS()
2225 /* Copy over default setting since some might not get loaded in
2226 * a networking environment. This ensures for example that the local
2227 * autosave-frequency stays when joining a network-server */
2228 PrepareOldDiffCustom();
2229 LoadSettings(_gameopt_settings, &_settings_game);
2230 HandleOldDiffCustom(true);
2233 static void Load_PATS()
2235 /* Copy over default setting since some might not get loaded in
2236 * a networking environment. This ensures for example that the local
2237 * currency setting stays when joining a network-server */
2238 LoadSettings(_settings, &_settings_game);
2241 static void Check_PATS()
2243 LoadSettings(_settings, &_load_check_data.settings);
2246 static void Save_PATS()
2248 SaveSettings(_settings, &_settings_game);
2251 void CheckConfig()
2254 * Increase old default values for pf_maxdepth and pf_maxlength
2255 * to support big networks.
2257 if (_settings_newgame.pf.opf.pf_maxdepth == 16 && _settings_newgame.pf.opf.pf_maxlength == 512) {
2258 _settings_newgame.pf.opf.pf_maxdepth = 48;
2259 _settings_newgame.pf.opf.pf_maxlength = 4096;
2263 extern const ChunkHandler _setting_chunk_handlers[] = {
2264 { 'OPTS', NULL, Load_OPTS, NULL, NULL, CH_RIFF},
2265 { 'PATS', Save_PATS, Load_PATS, NULL, Check_PATS, CH_RIFF | CH_LAST},
2268 static bool IsSignedVarMemType(VarType vt)
2270 switch (GetVarMemType(vt)) {
2271 case SLE_VAR_I8:
2272 case SLE_VAR_I16:
2273 case SLE_VAR_I32:
2274 case SLE_VAR_I64:
2275 return true;
2277 return false;