OpenTTD
settings.cpp
Go to the documentation of this file.
1 /* $Id: settings.cpp 27893 2017-08-13 18:38:42Z frosch $ */
2 
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  */
9 
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"
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 
68 #include "void_map.h"
69 #include "station_base.h"
70 
71 #include "table/strings.h"
72 #include "table/settings.h"
73 
74 #include "safeguards.h"
75 
80 char *_config_file;
81 
82 typedef std::list<ErrorMessageData> ErrorList;
84 
85 
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);
88 
89 static bool IsSignedVarMemType(VarType vt);
90 
94 static const char * const _list_group_names[] = {
95  "bans",
96  "newgrf",
97  "servers",
98  "server_bind_addresses",
99  NULL
100 };
101 
109 static size_t LookupOneOfMany(const char *many, const char *one, size_t onelen = 0)
110 {
111  const char *s;
112  size_t idx;
113 
114  if (onelen == 0) onelen = strlen(one);
115 
116  /* check if it's an integer */
117  if (*one >= '0' && *one <= '9') return strtoul(one, NULL, 0);
118 
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++;
128  }
129 }
130 
138 static size_t LookupManyOfMany(const char *many, const char *str)
139 {
140  const char *s;
141  size_t r;
142  size_t res = 0;
143 
144  for (;;) {
145  /* skip "whitespace" */
146  while (*str == ' ' || *str == '\t' || *str == '|') str++;
147  if (*str == 0) break;
148 
149  s = str;
150  while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
151 
152  r = LookupOneOfMany(many, str, s - str);
153  if (r == (size_t)-1) return r;
154 
155  SetBit(res, (uint8)r); // value found, set it
156  if (*s == 0) break;
157  str = s + 1;
158  }
159  return res;
160 }
161 
170 static int ParseIntList(const char *p, int *items, int maxitems)
171 {
172  int n = 0; // number of items read so far
173  bool comma = false; // do we accept comma?
174 
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;
182 
183  case ' ':
184  p++;
185  break;
186 
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;
197  }
198  }
199  }
200 
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;
204 
205  return n;
206 }
207 
216 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
217 {
218  int items[64];
219  int i, nitems;
220 
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;
227  }
228 
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;
235 
236  case SLE_VAR_I16:
237  case SLE_VAR_U16:
238  for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
239  break;
240 
241  case SLE_VAR_I32:
242  case SLE_VAR_U32:
243  for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
244  break;
245 
246  default: NOT_REACHED();
247  }
248 
249  return true;
250 }
251 
261 static void MakeIntList(char *buf, const char *last, const void *array, int nelems, VarType type)
262 {
263  int i, v = 0;
264  const byte *p = (const byte *)array;
265 
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();
276  }
277  buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
278  }
279 }
280 
288 static void MakeOneOfMany(char *buf, const char *last, const char *many, int id)
289 {
290  int orig_id = id;
291 
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;
298  }
299  }
300  many++; // pass the |-character
301  }
302 
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';
306 }
307 
316 static void MakeManyOfMany(char *buf, const char *last, const char *many, uint32 x)
317 {
318  const char *start;
319  int i = 0;
320  bool init = true;
321 
322  for (; x != 0; x >>= 1, i++) {
323  start = many;
324  while (*many != 0 && *many != '|') many++; // advance to the next element
325 
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;
334  }
335  }
336 
337  if (*many == '|') many++;
338  }
339 
340  *buf = '\0';
341 }
342 
349 static const void *StringToVal(const SettingDescBase *desc, const char *orig_str)
350 {
351  const char *str = orig_str == NULL ? "" : orig_str;
352 
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;
363  }
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);
368  }
369  return (void*)val;
370  }
371 
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
378 
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;
384  }
385 
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;
394  }
395 
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;
399 
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;
405  }
406 
407  case SDT_STRING: return orig_str;
408  case SDT_INTLIST: return str;
409  default: break;
410  }
411 
412  return NULL;
413 }
414 
424 static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
425 {
426  const SettingDescBase *sdb = &sd->desc;
427 
428  if (sdb->cmd != SDT_BOOLX &&
429  sdb->cmd != SDT_NUMX &&
430  sdb->cmd != SDT_ONEOFMANY &&
431  sdb->cmd != SDT_MANYOFMANY) {
432  return;
433  }
434 
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;
453  }
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;
459  }
460  case SLE_VAR_I64:
461  case SLE_VAR_U64:
462  default: NOT_REACHED();
463  }
464  }
465 
466  WriteValue(ptr, sd->save.conv, (int64)val);
467 }
468 
477 static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
478 {
479  IniGroup *group;
480  IniGroup *group_def = ini->GetGroup(grpname);
481  IniItem *item;
482  const void *p;
483  void *ptr;
484  const char *s;
485 
486  for (; sd->save.cmd != SL_END; sd++) {
487  const SettingDescBase *sdb = &sd->desc;
488  const SaveLoad *sld = &sd->save;
489 
490  if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
491 
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;
500  }
501 
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);
507  }
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);
513  }
514 
515  p = (item == NULL) ? sdb->def : StringToVal(sdb, item->value);
516  ptr = GetVariableAddress(object, sld);
517 
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;
525 
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;
532 
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;
538 
539  case SLE_VAR_CHAR: if (p != NULL) *(char *)ptr = *(const char *)p; break;
540 
541  default: NOT_REACHED();
542  }
543  break;
544 
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);
550 
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);
555  }
556  break;
557  }
558  default: NOT_REACHED();
559  }
560  }
561 }
562 
575 static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
576 {
577  IniGroup *group_def = NULL, *group;
578  IniItem *item;
579  char buf[512];
580  const char *s;
581  void *ptr;
582 
583  for (; sd->save.cmd != SL_END; sd++) {
584  const SettingDescBase *sdb = &sd->desc;
585  const SaveLoad *sld = &sd->save;
586 
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;
591 
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;
601  }
602 
603  item = group->GetItem(s, true);
604  ptr = GetVariableAddress(object, sld);
605 
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);
609 
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;
621 
622  case SLE_VAR_I8:
623  case SLE_VAR_U8:
624  if (*(byte*)ptr == (byte)(size_t)p) continue;
625  break;
626 
627  case SLE_VAR_I16:
628  case SLE_VAR_U16:
629  if (*(uint16*)ptr == (uint16)(size_t)p) continue;
630  break;
631 
632  case SLE_VAR_I32:
633  case SLE_VAR_U32:
634  if (*(uint32*)ptr == (uint32)(size_t)p) continue;
635  break;
636 
637  default: NOT_REACHED();
638  }
639  break;
640 
641  default: break; // Assume the other types are always changed
642  }
643  }
644 
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);
652 
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();
659  }
660  break;
661  }
662 
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;
668 
669  case SLE_VAR_STRQ:
670  if (*(char**)ptr == NULL) {
671  buf[0] = '\0';
672  } else {
673  seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
674  }
675  break;
676 
677  case SLE_VAR_CHAR: buf[0] = *(char*)ptr; buf[1] = '\0'; break;
678  default: NOT_REACHED();
679  }
680  break;
681 
682  case SDT_INTLIST:
683  MakeIntList(buf, lastof(buf), ptr, sld->length, GetVarMemType(sld->conv));
684  break;
685 
686  default: NOT_REACHED();
687  }
688 
689  /* The value is different, that means we have to write it to the ini */
690  free(item->value);
691  item->value = stredup(buf);
692  }
693 }
694 
704 static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *list)
705 {
706  IniGroup *group = ini->GetGroup(grpname);
707 
708  if (group == NULL || list == NULL) return;
709 
710  list->Clear();
711 
712  for (const IniItem *item = group->item; item != NULL; item = item->next) {
713  if (item->name != NULL) *list->Append() = stredup(item->name);
714  }
715 }
716 
726 static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *list)
727 {
728  IniGroup *group = ini->GetGroup(grpname);
729 
730  if (group == NULL || list == NULL) return;
731  group->Clear();
732 
733  for (char **iter = list->Begin(); iter != list->End(); iter++) {
734  group->GetItem(*iter, true)->SetValue("");
735  }
736 }
737 
744 void IniLoadWindowSettings(IniFile *ini, const char *grpname, void *desc)
745 {
746  IniLoadSettings(ini, _window_settings, grpname, desc);
747 }
748 
755 void IniSaveWindowSettings(IniFile *ini, const char *grpname, void *desc)
756 {
757  IniSaveSettings(ini, _window_settings, grpname, desc);
758 }
759 
765 bool SettingDesc::IsEditable(bool do_command) const
766 {
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;
774 }
775 
781 {
782  if (this->desc.flags & SGF_PER_COMPANY) return ST_COMPANY;
783  return (this->save.conv & SLF_NOT_IN_SAVE) ? ST_CLIENT : ST_GAME;
784 }
785 
786 /* Begin - Callback Functions for the various settings. */
787 
789 static bool v_PositionMainToolbar(int32 p1)
790 {
791  if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
792  return true;
793 }
794 
796 static bool v_PositionStatusbar(int32 p1)
797 {
798  if (_game_mode != GM_MENU) {
799  PositionStatusbar(NULL);
800  PositionNewsMessage(NULL);
802  }
803  return true;
804 }
805 
806 static bool PopulationInLabelActive(int32 p1)
807 {
809  return true;
810 }
811 
812 static bool RedrawScreen(int32 p1)
813 {
815  return true;
816 }
817 
823 static bool RedrawSmallmap(int32 p1)
824 {
825  BuildLandLegend();
828  return true;
829 }
830 
831 static bool InvalidateDetailsWindow(int32 p1)
832 {
834  return true;
835 }
836 
837 static bool StationSpreadChanged(int32 p1)
838 {
841  return true;
842 }
843 
844 static bool InvalidateBuildIndustryWindow(int32 p1)
845 {
847  return true;
848 }
849 
850 static bool CloseSignalGUI(int32 p1)
851 {
852  if (p1 == 0) {
854  }
855  return true;
856 }
857 
858 static bool InvalidateTownViewWindow(int32 p1)
859 {
861  return true;
862 }
863 
864 static bool DeleteSelectStationWindow(int32 p1)
865 {
867  return true;
868 }
869 
870 static bool UpdateConsists(int32 p1)
871 {
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);
876  }
878  return true;
879 }
880 
881 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
882 static bool CheckInterval(int32 p1)
883 {
884  bool update_vehicles;
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;
892  }
893 
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;
904  }
905 
906  if (update_vehicles) {
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);
913  }
914  }
915  }
916 
917  InvalidateDetailsWindow(0);
918 
919  return true;
920 }
921 
922 static bool UpdateInterval(VehicleType type, int32 p1)
923 {
924  bool update_vehicles;
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;
932  }
933 
934  /* Test if the interval is valid */
935  uint16 interval = GetServiceIntervalClamped(p1, vds->servint_ispercent);
936  if (interval != p1) return false;
937 
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);
943  }
944  }
945  }
946 
947  InvalidateDetailsWindow(0);
948 
949  return true;
950 }
951 
952 static bool UpdateIntervalTrains(int32 p1)
953 {
954  return UpdateInterval(VEH_TRAIN, p1);
955 }
956 
957 static bool UpdateIntervalRoadVeh(int32 p1)
958 {
959  return UpdateInterval(VEH_ROAD, p1);
960 }
961 
962 static bool UpdateIntervalShips(int32 p1)
963 {
964  return UpdateInterval(VEH_SHIP, p1);
965 }
966 
967 static bool UpdateIntervalAircraft(int32 p1)
968 {
969  return UpdateInterval(VEH_AIRCRAFT, p1);
970 }
971 
972 static bool TrainAccelerationModelChanged(int32 p1)
973 {
974  Train *t;
975  FOR_ALL_TRAINS(t) {
976  if (t->IsFrontEngine()) {
978  t->UpdateAcceleration();
979  }
980  }
981 
982  /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
986 
987  return true;
988 }
989 
995 static bool TrainSlopeSteepnessChanged(int32 p1)
996 {
997  Train *t;
998  FOR_ALL_TRAINS(t) {
999  if (t->IsFrontEngine()) t->CargoChanged();
1000  }
1001 
1002  return true;
1003 }
1004 
1010 static bool RoadVehAccelerationModelChanged(int32 p1)
1011 {
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();
1017  }
1018  }
1019  }
1020 
1021  /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1025 
1026  return true;
1027 }
1028 
1034 static bool RoadVehSlopeSteepnessChanged(int32 p1)
1035 {
1036  RoadVehicle *rv;
1037  FOR_ALL_ROADVEHICLES(rv) {
1038  if (rv->IsFrontEngine()) rv->CargoChanged();
1039  }
1040 
1041  return true;
1042 }
1043 
1044 static bool DragSignalsDensityChanged(int32)
1045 {
1047 
1048  return true;
1049 }
1050 
1051 static bool TownFoundingChanged(int32 p1)
1052 {
1053  if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
1055  return true;
1056  }
1058  return true;
1059 }
1060 
1061 static bool InvalidateVehTimetableWindow(int32 p1)
1062 {
1064  return true;
1065 }
1066 
1067 static bool ZoomMinMaxChanged(int32 p1)
1068 {
1069  extern void ConstrainAllViewportsZoom();
1070  ConstrainAllViewportsZoom();
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();
1077  }
1078  return true;
1079 }
1080 
1088 static bool InvalidateNewGRFChangeWindows(int32 p1)
1089 {
1092  ReInitAllWindows();
1093  return true;
1094 }
1095 
1096 static bool InvalidateCompanyLiveryWindow(int32 p1)
1097 {
1099  return RedrawScreen(p1);
1100 }
1101 
1102 static bool InvalidateIndustryViewWindow(int32 p1)
1103 {
1105  return true;
1106 }
1107 
1108 static bool InvalidateAISettingsWindow(int32 p1)
1109 {
1111  return true;
1112 }
1113 
1119 static bool RedrawTownAuthority(int32 p1)
1120 {
1122  return true;
1123 }
1124 
1131 {
1133  return true;
1134 }
1135 
1141 static bool InvalidateCompanyWindow(int32 p1)
1142 {
1144  return true;
1145 }
1146 
1148 static void ValidateSettings()
1149 {
1150  /* Do not allow a custom sea level with the original land generator. */
1151  if (_settings_newgame.game_creation.land_generator == LG_ORIGINAL &&
1154  }
1155 }
1156 
1157 static bool DifficultyNoiseChange(int32 i)
1158 {
1159  if (_game_mode == GM_NORMAL) {
1161  if (_settings_game.economy.station_noise_level) {
1163  }
1164  }
1165 
1166  return true;
1167 }
1168 
1169 static bool MaxNoAIsChange(int32 i)
1170 {
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);
1175  }
1176 
1177  return true;
1178 }
1179 
1185 static bool CheckRoadSide(int p1)
1186 {
1187  extern bool RoadVehiclesAreBuilt();
1188  return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
1189 }
1190 
1198 static size_t ConvertLandscape(const char *value)
1199 {
1200  /* try with the old values */
1201  return LookupOneOfMany("normal|hilly|desert|candy", value);
1202 }
1203 
1204 static bool CheckFreeformEdges(int32 p1)
1205 {
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;
1214  }
1215  }
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;
1222  }
1223  }
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;
1231  }
1232  }
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;
1237  }
1238  }
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;
1243  }
1244  }
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;
1249  }
1250  }
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);
1255  }
1256  for (uint i = 0; i < MapMaxY(); i++) {
1257  SetTileHeight(TileXY(0, i), 0);
1258  SetTileType(TileXY(0, i), MP_WATER);
1259  }
1260  }
1262  return true;
1263 }
1264 
1269 static bool ChangeDynamicEngines(int32 p1)
1270 {
1271  if (_game_mode == GM_MENU) return true;
1272 
1274  ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, WL_ERROR);
1275  return false;
1276  }
1277 
1278  return true;
1279 }
1280 
1281 static bool ChangeMaxHeightLevel(int32 p1)
1282 {
1283  if (_game_mode == GM_NORMAL) return false;
1284  if (_game_mode != GM_EDITOR) return true;
1285 
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;
1293  }
1294  }
1295 
1296  /* The smallmap uses an index from heightlevels to colours. Trigger rebuilding it. */
1298 
1299  return true;
1300 }
1301 
1302 static bool StationCatchmentChanged(int32 p1)
1303 {
1305  return true;
1306 }
1307 
1308 static bool MaxVehiclesChanged(int32 p1)
1309 {
1312  return true;
1313 }
1314 
1315 
1316 #ifdef ENABLE_NETWORK
1317 
1318 static bool UpdateClientName(int32 p1)
1319 {
1321  return true;
1322 }
1323 
1324 static bool UpdateServerPassword(int32 p1)
1325 {
1326  if (strcmp(_settings_client.network.server_password, "*") == 0) {
1327  _settings_client.network.server_password[0] = '\0';
1328  }
1329 
1330  return true;
1331 }
1332 
1333 static bool UpdateRconPassword(int32 p1)
1334 {
1335  if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
1336  _settings_client.network.rcon_password[0] = '\0';
1337  }
1338 
1339  return true;
1340 }
1341 
1342 static bool UpdateClientConfigValues(int32 p1)
1343 {
1345 
1346  return true;
1347 }
1348 
1349 #endif /* ENABLE_NETWORK */
1350 
1351 
1352 /* End - Callback Functions */
1353 
1358 {
1359  memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
1360 }
1361 
1368 static void HandleOldDiffCustom(bool savegame)
1369 {
1370  uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && IsSavegameVersionBefore(4)) ? 1 : 0);
1371 
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);
1377  }
1378 
1379  if (!old_diff_custom_used) return;
1380  }
1381 
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]));
1388  }
1389 }
1390 
1391 static void AILoadConfig(IniFile *ini, const char *grpname)
1392 {
1393  IniGroup *group = ini->GetGroup(grpname);
1394  IniItem *item;
1395 
1396  /* Clean any configured AI */
1397  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1399  }
1400 
1401  /* If no group exists, return */
1402  if (group == NULL) return;
1403 
1405  for (item = group->item; c < MAX_COMPANIES && item != NULL; c++, item = item->next) {
1407 
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;
1413  }
1414  }
1415  if (item->value != NULL) config->StringToSettings(item->value);
1416  }
1417 }
1418 
1419 static void GameLoadConfig(IniFile *ini, const char *grpname)
1420 {
1421  IniGroup *group = ini->GetGroup(grpname);
1422  IniItem *item;
1423 
1424  /* Clean any configured GameScript */
1426 
1427  /* If no group exists, return */
1428  if (group == NULL) return;
1429 
1430  item = group->item;
1431  if (item == NULL) return;
1432 
1434 
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;
1440  }
1441  }
1442  if (item->value != NULL) config->StringToSettings(item->value);
1443 }
1444 
1450 static int DecodeHexNibble(char c)
1451 {
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;
1456 }
1457 
1466 static bool DecodeHexText(char *pos, uint8 *dest, size_t dest_size)
1467 {
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--;
1475  }
1476  return *pos == '|';
1477 }
1478 
1485 static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
1486 {
1487  IniGroup *group = ini->GetGroup(grpname);
1488  IniItem *item;
1489  GRFConfig *first = NULL;
1490  GRFConfig **curr = &first;
1491 
1492  if (group == NULL) return NULL;
1493 
1494  for (item = group->item; item != NULL; item = item->next) {
1495  GRFConfig *c = NULL;
1496 
1497  uint8 grfid_buf[4], md5sum[16];
1498  char *filename = item->name;
1499  bool has_grfid = false;
1500  bool has_md5sum = false;
1501 
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);
1508 
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);
1513  }
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);
1517  }
1518  }
1519  if (c == NULL) c = new GRFConfig(filename);
1520 
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;
1528  }
1529  c->num_params = count;
1530  }
1531 
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);
1544  }
1545 
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;
1550  }
1551 
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;
1561  }
1562  }
1563  if (duplicate) {
1564  delete c;
1565  continue;
1566  }
1567 
1568  /* Mark file as static to avoid saving in savegame. */
1569  if (is_static) SetBit(c->flags, GCF_STATIC);
1570 
1571  /* Add item to list */
1572  *curr = c;
1573  curr = &c->next;
1574  }
1575 
1576  return first;
1577 }
1578 
1579 static void AISaveConfig(IniFile *ini, const char *grpname)
1580 {
1581  IniGroup *group = ini->GetGroup(grpname);
1582 
1583  if (group == NULL) return;
1584  group->Clear();
1585 
1586  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1588  const char *name;
1589  char value[1024];
1590  config->SettingsToString(value, lastof(value));
1591 
1592  if (config->HasScript()) {
1593  name = config->GetName();
1594  } else {
1595  name = "none";
1596  }
1597 
1598  IniItem *item = new IniItem(group, name);
1599  item->SetValue(value);
1600  }
1601 }
1602 
1603 static void GameSaveConfig(IniFile *ini, const char *grpname)
1604 {
1605  IniGroup *group = ini->GetGroup(grpname);
1606 
1607  if (group == NULL) return;
1608  group->Clear();
1609 
1611  const char *name;
1612  char value[1024];
1613  config->SettingsToString(value, lastof(value));
1614 
1615  if (config->HasScript()) {
1616  name = config->GetName();
1617  } else {
1618  name = "none";
1619  }
1620 
1621  IniItem *item = new IniItem(group, name);
1622  item->SetValue(value);
1623 }
1624 
1629 static void SaveVersionInConfig(IniFile *ini)
1630 {
1631  IniGroup *group = ini->GetGroup("version");
1632 
1633  char version[9];
1634  seprintf(version, lastof(version), "%08X", _openttd_newgrf_version);
1635 
1636  const char * const versions[][2] = {
1637  { "version_string", _openttd_revision },
1638  { "version_number", version }
1639  };
1640 
1641  for (uint i = 0; i < lengthof(versions); i++) {
1642  group->GetItem(versions[i][0], true)->SetValue(versions[i][1]);
1643  }
1644 }
1645 
1646 /* Save a GRF configuration to the given group name */
1647 static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
1648 {
1649  ini->RemoveGroup(grpname);
1650  IniGroup *group = ini->GetGroup(grpname);
1651  const GRFConfig *c;
1652 
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));
1658 
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);
1663  }
1664 }
1665 
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)
1668 {
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 */
1674  }
1675 
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);
1680 
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 */
1686  }
1687 }
1688 
1689 static IniFile *IniLoadConfig()
1690 {
1691  IniFile *ini = new IniFile(_list_group_names);
1693  return ini;
1694 }
1695 
1700 void LoadFromConfig(bool minimal)
1701 {
1702  IniFile *ini = IniLoadConfig();
1703  if (!minimal) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1704 
1705  /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1706  HandleSettingDescs(ini, IniLoadSettings, IniLoadSettingList, minimal, !minimal);
1707 
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");
1713 
1715  IniLoadSettings(ini, _gameopt_settings, "gameopt", &_settings_newgame);
1716  HandleOldDiffCustom(false);
1717 
1718  ValidateSettings();
1719 
1720  /* Display sheduled errors */
1721  extern void ScheduleErrorMessage(ErrorList &datas);
1723  if (FindWindowById(WC_ERRMSG, 0) == NULL) ShowFirstError();
1724  }
1725 
1726  delete ini;
1727 }
1728 
1731 {
1732  IniFile *ini = IniLoadConfig();
1733 
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");
1738 
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;
1747 }
1748 
1754 {
1755  list->Clear();
1756 
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);
1762  }
1763  }
1764 
1765  delete ini;
1766 }
1767 
1774 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
1775 {
1776  size_t len = strlen(config_name) + 8;
1777  char *section = (char*)alloca(len);
1778  seprintf(section, section + len - 1, "preset-%s", config_name);
1779 
1780  IniFile *ini = IniLoadConfig();
1781  GRFConfig *config = GRFLoadConfig(ini, section, false);
1782  delete ini;
1783 
1784  return config;
1785 }
1786 
1793 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
1794 {
1795  size_t len = strlen(config_name) + 8;
1796  char *section = (char*)alloca(len);
1797  seprintf(section, section + len - 1, "preset-%s", config_name);
1798 
1799  IniFile *ini = IniLoadConfig();
1800  GRFSaveConfig(ini, section, config);
1801  ini->SaveToDisk(_config_file);
1802  delete ini;
1803 }
1804 
1809 void DeleteGRFPresetFromConfig(const char *config_name)
1810 {
1811  size_t len = strlen(config_name) + 8;
1812  char *section = (char*)alloca(len);
1813  seprintf(section, section + len - 1, "preset-%s", config_name);
1814 
1815  IniFile *ini = IniLoadConfig();
1816  ini->RemoveGroup(section);
1817  ini->SaveToDisk(_config_file);
1818  delete ini;
1819 }
1820 
1821 const SettingDesc *GetSettingDescription(uint index)
1822 {
1823  if (index >= lengthof(_settings)) return NULL;
1824  return &_settings[index];
1825 }
1826 
1838 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1839 {
1840  const SettingDesc *sd = GetSettingDescription(p1);
1841 
1842  if (sd == NULL) return CMD_ERROR;
1844 
1845  if (!sd->IsEditable(true)) return CMD_ERROR;
1846 
1847  if (flags & DC_EXEC) {
1848  void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
1849 
1850  int32 oldval = (int32)ReadValue(var, sd->save.conv);
1851  int32 newval = (int32)p2;
1852 
1853  Write_ValidateSetting(var, sd, newval);
1854  newval = (int32)ReadValue(var, sd->save.conv);
1855 
1856  if (oldval == newval) return CommandCost();
1857 
1858  if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
1859  WriteValue(var, sd->save.conv, (int64)oldval);
1860  return CommandCost();
1861  }
1862 
1863  if (sd->desc.flags & SGF_NO_NETWORK) {
1865  GamelogSetting(sd->desc.name, oldval, newval);
1867  }
1868 
1870  }
1871 
1872  return CommandCost();
1873 }
1874 
1885 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1886 {
1887  if (p1 >= lengthof(_company_settings)) return CMD_ERROR;
1888  const SettingDesc *sd = &_company_settings[p1];
1889 
1890  if (flags & DC_EXEC) {
1891  void *var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
1892 
1893  int32 oldval = (int32)ReadValue(var, sd->save.conv);
1894  int32 newval = (int32)p2;
1895 
1896  Write_ValidateSetting(var, sd, newval);
1897  newval = (int32)ReadValue(var, sd->save.conv);
1898 
1899  if (oldval == newval) return CommandCost();
1900 
1901  if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
1902  WriteValue(var, sd->save.conv, (int64)oldval);
1903  return CommandCost();
1904  }
1905 
1907  }
1908 
1909  return CommandCost();
1910 }
1911 
1919 bool SetSettingValue(uint index, int32 value, bool force_newgame)
1920 {
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);
1929 
1930  if (_game_mode != GM_MENU) {
1931  void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
1932  Write_ValidateSetting(var2, sd, value);
1933  }
1934  if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
1935 
1937 
1938  return true;
1939  }
1940 
1941  if (force_newgame) {
1942  void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
1943  Write_ValidateSetting(var2, sd, value);
1944  return true;
1945  }
1946 
1947  /* send non-company-based settings over the network */
1948  if (!_networking || (_networking && _network_server)) {
1949  return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
1950  }
1951  return false;
1952 }
1953 
1960 void SetCompanySetting(uint index, int32 value)
1961 {
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));
1969  }
1970 }
1971 
1976 {
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);
1982  }
1983 }
1984 
1985 #if defined(ENABLE_NETWORK)
1986 
1990 {
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);
1999  }
2000 }
2001 #endif /* ENABLE_NETWORK */
2002 
2008 uint GetCompanySettingIndex(const char *name)
2009 {
2010  uint i;
2011  const SettingDesc *sd = GetSettingFromName(name, &i);
2012  assert(sd != NULL && (sd->desc.flags & SGF_PER_COMPANY) != 0);
2013  return i;
2014 }
2015 
2023 bool SetSettingValue(uint index, const char *value, bool force_newgame)
2024 {
2025  const SettingDesc *sd = &_settings[index];
2026  assert(sd->save.conv & SLF_NO_NETWORK_SYNC);
2027 
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]);
2035  }
2036  if (sd->desc.proc != NULL) sd->desc.proc(0);
2037 
2038  return true;
2039 }
2040 
2048 const SettingDesc *GetSettingFromName(const char *name, uint *i)
2049 {
2050  const SettingDesc *sd;
2051 
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;
2056  }
2057 
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;
2065  }
2066  }
2067 
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;
2073  }
2074 
2075  return NULL;
2076 }
2077 
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)
2081 {
2082  uint index;
2083  const SettingDesc *sd = GetSettingFromName(name, &index);
2084 
2085  if (sd == NULL) {
2086  IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2087  return;
2088  }
2089 
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;
2100  }
2101 
2102  success = SetSettingValue(index, val, force_newgame);
2103  }
2104 
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.");
2110  }
2111  }
2112 }
2113 
2114 void IConsoleSetSetting(const char *name, int value)
2115 {
2116  uint index;
2117  const SettingDesc *sd = GetSettingFromName(name, &index);
2118  assert(sd != NULL);
2119  SetSettingValue(index, value);
2120 }
2121 
2127 void IConsoleGetSetting(const char *name, bool force_newgame)
2128 {
2129  char value[20];
2130  uint index;
2131  const SettingDesc *sd = GetSettingFromName(name, &index);
2132  const void *ptr;
2133 
2134  if (sd == NULL) {
2135  IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2136  return;
2137  }
2138 
2139  ptr = GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
2140 
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));
2148  }
2149 
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);
2152  }
2153 }
2154 
2160 void IConsoleListSettings(const char *prefilter)
2161 {
2162  IConsolePrintF(CC_WARNING, "All settings with their current value:");
2163 
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);
2169 
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));
2176  }
2177  IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
2178  }
2179 
2180  IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
2181 }
2182 
2189 static void LoadSettings(const SettingDesc *osd, void *object)
2190 {
2191  for (; osd->save.cmd != SL_END; osd++) {
2192  const SaveLoad *sld = &osd->save;
2193  void *ptr = GetVariableAddress(object, sld);
2194 
2195  if (!SlObjectMember(ptr, sld)) continue;
2196  if (IsNumericType(sld->conv)) Write_ValidateSetting(ptr, osd, ReadValue(ptr, sld->conv));
2197  }
2198 }
2199 
2206 static void SaveSettings(const SettingDesc *sd, void *object)
2207 {
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);
2214  }
2215  SlSetLength(length);
2216 
2217  for (i = sd; i->save.cmd != SL_END; i++) {
2218  void *ptr = GetVariableAddress(object, &i->save);
2219  SlObjectMember(ptr, &i->save);
2220  }
2221 }
2222 
2223 static void Load_OPTS()
2224 {
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 */
2229  LoadSettings(_gameopt_settings, &_settings_game);
2230  HandleOldDiffCustom(true);
2231 }
2232 
2233 static void Load_PATS()
2234 {
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);
2239 }
2240 
2241 static void Check_PATS()
2242 {
2243  LoadSettings(_settings, &_load_check_data.settings);
2244 }
2245 
2246 static void Save_PATS()
2247 {
2248  SaveSettings(_settings, &_settings_game);
2249 }
2250 
2251 void CheckConfig()
2252 {
2253  /*
2254  * Increase old default values for pf_maxdepth and pf_maxlength
2255  * to support big networks.
2256  */
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;
2260  }
2261 }
2262 
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},
2266 };
2267 
2268 static bool IsSignedVarMemType(VarType vt)
2269 {
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;
2276  }
2277  return false;
2278 }