settings.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00026 #include "stdafx.h"
00027 #include "currency.h"
00028 #include "screenshot.h"
00029 #include "network/network.h"
00030 #include "network/network_func.h"
00031 #include "settings_internal.h"
00032 #include "command_func.h"
00033 #include "console_func.h"
00034 #include "pathfinder/pathfinder_type.h"
00035 #include "genworld.h"
00036 #include "train.h"
00037 #include "news_func.h"
00038 #include "window_func.h"
00039 #include "sound_func.h"
00040 #include "company_func.h"
00041 #include "rev.h"
00042 #ifdef WITH_FREETYPE
00043 #include "fontcache.h"
00044 #endif
00045 #include "textbuf_gui.h"
00046 #include "rail_gui.h"
00047 #include "elrail_func.h"
00048 #include "gui.h"
00049 #include "town.h"
00050 #include "video/video_driver.hpp"
00051 #include "sound/sound_driver.hpp"
00052 #include "music/music_driver.hpp"
00053 #include "blitter/factory.hpp"
00054 #include "base_media_base.h"
00055 #include "gamelog.h"
00056 #include "settings_func.h"
00057 #include "ini_type.h"
00058 #include "ai/ai_config.hpp"
00059 #include "ai/ai.hpp"
00060 #include "ship.h"
00061 #include "smallmap_gui.h"
00062 #include "roadveh.h"
00063 #include "fios.h"
00064 
00065 #include "void_map.h"
00066 #include "station_base.h"
00067 
00068 #include "table/strings.h"
00069 #include "table/settings.h"
00070 
00071 ClientSettings _settings_client;
00072 GameSettings _settings_game;     
00073 GameSettings _settings_newgame;  
00074 VehicleDefaultSettings _old_vds; 
00075 char *_config_file; 
00076 
00077 typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
00078 typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList *list);
00079 
00080 static bool IsSignedVarMemType(VarType vt);
00081 
00085 static const char * const _list_group_names[] = {
00086   "bans",
00087   "newgrf",
00088   "servers",
00089   "server_bind_addresses",
00090   NULL
00091 };
00092 
00100 static int LookupOneOfMany(const char *many, const char *one, size_t onelen = 0)
00101 {
00102   const char *s;
00103   int idx;
00104 
00105   if (onelen == 0) onelen = strlen(one);
00106 
00107   /* check if it's an integer */
00108   if (*one >= '0' && *one <= '9') return strtoul(one, NULL, 0);
00109 
00110   idx = 0;
00111   for (;;) {
00112     /* find end of item */
00113     s = many;
00114     while (*s != '|' && *s != 0) s++;
00115     if ((size_t)(s - many) == onelen && !memcmp(one, many, onelen)) return idx;
00116     if (*s == 0) return -1;
00117     many = s + 1;
00118     idx++;
00119   }
00120 }
00121 
00129 static uint32 LookupManyOfMany(const char *many, const char *str)
00130 {
00131   const char *s;
00132   int r;
00133   uint32 res = 0;
00134 
00135   for (;;) {
00136     /* skip "whitespace" */
00137     while (*str == ' ' || *str == '\t' || *str == '|') str++;
00138     if (*str == 0) break;
00139 
00140     s = str;
00141     while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
00142 
00143     r = LookupOneOfMany(many, str, s - str);
00144     if (r == -1) return (uint32)-1;
00145 
00146     SetBit(res, r); // value found, set it
00147     if (*s == 0) break;
00148     str = s + 1;
00149   }
00150   return res;
00151 }
00152 
00161 static int ParseIntList(const char *p, int *items, int maxitems)
00162 {
00163   int n = 0; // number of items read so far
00164   bool comma = false; // do we accept comma?
00165 
00166   while (*p != '\0') {
00167     switch (*p) {
00168       case ',':
00169         /* Do not accept multiple commas between numbers */
00170         if (!comma) return -1;
00171         comma = false;
00172         /* FALL THROUGH */
00173       case ' ':
00174         p++;
00175         break;
00176 
00177       default: {
00178         if (n == maxitems) return -1; // we don't accept that many numbers
00179         char *end;
00180         long v = strtol(p, &end, 0);
00181         if (p == end) return -1; // invalid character (not a number)
00182         if (sizeof(int) < sizeof(long)) v = ClampToI32(v);
00183         items[n++] = v;
00184         p = end; // first non-number
00185         comma = true; // we accept comma now
00186         break;
00187       }
00188     }
00189   }
00190 
00191   /* If we have read comma but no number after it, fail.
00192    * We have read comma when (n != 0) and comma is not allowed */
00193   if (n != 0 && !comma) return -1;
00194 
00195   return n;
00196 }
00197 
00206 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
00207 {
00208   int items[64];
00209   int i, nitems;
00210 
00211   if (str == NULL) {
00212     memset(items, 0, sizeof(items));
00213     nitems = nelems;
00214   } else {
00215     nitems = ParseIntList(str, items, lengthof(items));
00216     if (nitems != nelems) return false;
00217   }
00218 
00219   switch (type) {
00220   case SLE_VAR_BL:
00221   case SLE_VAR_I8:
00222   case SLE_VAR_U8:
00223     for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
00224     break;
00225   case SLE_VAR_I16:
00226   case SLE_VAR_U16:
00227     for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
00228     break;
00229   case SLE_VAR_I32:
00230   case SLE_VAR_U32:
00231     for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
00232     break;
00233   default: NOT_REACHED();
00234   }
00235 
00236   return true;
00237 }
00238 
00248 static void MakeIntList(char *buf, const char *last, const void *array, int nelems, VarType type)
00249 {
00250   int i, v = 0;
00251   byte *p = (byte*)array;
00252 
00253   for (i = 0; i != nelems; i++) {
00254     switch (type) {
00255     case SLE_VAR_BL:
00256     case SLE_VAR_I8:  v = *(int8*)p;   p += 1; break;
00257     case SLE_VAR_U8:  v = *(byte*)p;   p += 1; break;
00258     case SLE_VAR_I16: v = *(int16*)p;  p += 2; break;
00259     case SLE_VAR_U16: v = *(uint16*)p; p += 2; break;
00260     case SLE_VAR_I32: v = *(int32*)p;  p += 4; break;
00261     case SLE_VAR_U32: v = *(uint32*)p; p += 4; break;
00262     default: NOT_REACHED();
00263     }
00264     buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
00265   }
00266 }
00267 
00275 static void MakeOneOfMany(char *buf, const char *last, const char *many, int id)
00276 {
00277   int orig_id = id;
00278 
00279   /* Look for the id'th element */
00280   while (--id >= 0) {
00281     for (; *many != '|'; many++) {
00282       if (*many == '\0') { // not found
00283         seprintf(buf, last, "%d", orig_id);
00284         return;
00285       }
00286     }
00287     many++; // pass the |-character
00288   }
00289 
00290   /* copy string until next item (|) or the end of the list if this is the last one */
00291   while (*many != '\0' && *many != '|' && buf < last) *buf++ = *many++;
00292   *buf = '\0';
00293 }
00294 
00303 static void MakeManyOfMany(char *buf, const char *last, const char *many, uint32 x)
00304 {
00305   const char *start;
00306   int i = 0;
00307   bool init = true;
00308 
00309   for (; x != 0; x >>= 1, i++) {
00310     start = many;
00311     while (*many != 0 && *many != '|') many++; // advance to the next element
00312 
00313     if (HasBit(x, 0)) { // item found, copy it
00314       if (!init) buf += seprintf(buf, last, "|");
00315       init = false;
00316       if (start == many) {
00317         buf += seprintf(buf, last, "%d", i);
00318       } else {
00319         memcpy(buf, start, many - start);
00320         buf += many - start;
00321       }
00322     }
00323 
00324     if (*many == '|') many++;
00325   }
00326 
00327   *buf = '\0';
00328 }
00329 
00336 static const void *StringToVal(const SettingDescBase *desc, const char *orig_str)
00337 {
00338   const char *str = orig_str == NULL ? "" : orig_str;
00339   switch (desc->cmd) {
00340   case SDT_NUMX: {
00341     char *end;
00342     unsigned long val = strtoul(str, &end, 0);
00343     if (*end != '\0') ShowInfoF("ini: trailing characters at end of setting '%s'", desc->name);
00344     return (void*)val;
00345   }
00346   case SDT_ONEOFMANY: {
00347     long r = LookupOneOfMany(desc->many, str);
00348     /* if the first attempt of conversion from string to the appropriate value fails,
00349      * look if we have defined a converter from old value to new value. */
00350     if (r == -1 && desc->proc_cnvt != NULL) r = desc->proc_cnvt(str);
00351     if (r != -1) return (void*)r; // and here goes converted value
00352     ShowInfoF("ini: invalid value '%s' for '%s'", str, desc->name); // sorry, we failed
00353     return 0;
00354   }
00355   case SDT_MANYOFMANY: {
00356     unsigned long r = LookupManyOfMany(desc->many, str);
00357     if (r != (unsigned long)-1) return (void*)r;
00358     ShowInfoF("ini: invalid value '%s' for '%s'", str, desc->name);
00359     return 0;
00360   }
00361   case SDT_BOOLX:
00362     if (strcmp(str, "true")  == 0 || strcmp(str, "on")  == 0 || strcmp(str, "1") == 0) return (void*)true;
00363     if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return (void*)false;
00364     ShowInfoF("ini: invalid setting value '%s' for '%s'", str, desc->name);
00365     break;
00366 
00367   case SDT_STRING: return orig_str;
00368   case SDT_INTLIST: return str;
00369   default: break;
00370   }
00371 
00372   return NULL;
00373 }
00374 
00384 static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
00385 {
00386   const SettingDescBase *sdb = &sd->desc;
00387 
00388   if (sdb->cmd != SDT_BOOLX &&
00389       sdb->cmd != SDT_NUMX &&
00390       sdb->cmd != SDT_ONEOFMANY &&
00391       sdb->cmd != SDT_MANYOFMANY) {
00392     return;
00393   }
00394 
00395   /* We cannot know the maximum value of a bitset variable, so just have faith */
00396   if (sdb->cmd != SDT_MANYOFMANY) {
00397     /* We need to take special care of the uint32 type as we receive from the function
00398      * a signed integer. While here also bail out on 64-bit settings as those are not
00399      * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
00400      * 32-bit variable
00401      * TODO: Support 64-bit settings/variables */
00402     switch (GetVarMemType(sd->save.conv)) {
00403       case SLE_VAR_NULL: return;
00404       case SLE_VAR_BL:
00405       case SLE_VAR_I8:
00406       case SLE_VAR_U8:
00407       case SLE_VAR_I16:
00408       case SLE_VAR_U16:
00409       case SLE_VAR_I32: {
00410         /* Override the minimum value. No value below sdb->min, except special value 0 */
00411         if (!(sdb->flags & SGF_0ISDISABLED) || val != 0) val = Clamp(val, sdb->min, sdb->max);
00412         break;
00413       }
00414       case SLE_VAR_U32: {
00415         /* Override the minimum value. No value below sdb->min, except special value 0 */
00416         uint min = ((sdb->flags & SGF_0ISDISABLED) && (uint)val <= (uint)sdb->min) ? 0 : sdb->min;
00417         WriteValue(ptr, SLE_VAR_U32, (int64)ClampU(val, min, sdb->max));
00418         return;
00419       }
00420       case SLE_VAR_I64:
00421       case SLE_VAR_U64:
00422       default: NOT_REACHED();
00423     }
00424   }
00425 
00426   WriteValue(ptr, sd->save.conv, (int64)val);
00427 }
00428 
00437 static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
00438 {
00439   IniGroup *group;
00440   IniGroup *group_def = ini->GetGroup(grpname);
00441   IniItem *item;
00442   const void *p;
00443   void *ptr;
00444   const char *s;
00445 
00446   for (; sd->save.cmd != SL_END; sd++) {
00447     const SettingDescBase *sdb = &sd->desc;
00448     const SaveLoad        *sld = &sd->save;
00449 
00450     if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
00451 
00452     /* For settings.xx.yy load the settings from [xx] yy = ? */
00453     s = strchr(sdb->name, '.');
00454     if (s != NULL) {
00455       group = ini->GetGroup(sdb->name, s - sdb->name);
00456       s++;
00457     } else {
00458       s = sdb->name;
00459       group = group_def;
00460     }
00461 
00462     item = group->GetItem(s, false);
00463     if (item == NULL && group != group_def) {
00464       /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
00465        * did not exist (e.g. loading old config files with a [settings] section */
00466       item = group_def->GetItem(s, false);
00467     }
00468     if (item == NULL) {
00469       /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
00470        * did not exist (e.g. loading old config files with a [yapf] section */
00471       const char *sc = strchr(s, '.');
00472       if (sc != NULL) item = ini->GetGroup(s, sc - s)->GetItem(sc + 1, false);
00473     }
00474 
00475     p = (item == NULL) ? sdb->def : StringToVal(sdb, item->value);
00476     ptr = GetVariableAddress(object, sld);
00477 
00478     switch (sdb->cmd) {
00479     case SDT_BOOLX: // All four are various types of (integer) numbers
00480     case SDT_NUMX:
00481     case SDT_ONEOFMANY:
00482     case SDT_MANYOFMANY:
00483       Write_ValidateSetting(ptr, sd, (int32)(size_t)p); break;
00484 
00485     case SDT_STRING:
00486       switch (GetVarMemType(sld->conv)) {
00487         case SLE_VAR_STRB:
00488         case SLE_VAR_STRBQ:
00489           if (p != NULL) ttd_strlcpy((char*)ptr, (const char*)p, sld->length);
00490           break;
00491         case SLE_VAR_STR:
00492         case SLE_VAR_STRQ:
00493           free(*(char**)ptr);
00494           *(char**)ptr = p == NULL ? NULL : strdup((const char*)p);
00495           break;
00496         case SLE_VAR_CHAR: if (p != NULL) *(char*)ptr = *(char*)p; break;
00497         default: NOT_REACHED();
00498       }
00499       break;
00500 
00501     case SDT_INTLIST: {
00502       if (!LoadIntList((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) {
00503         ShowInfoF("ini: error in array '%s'", sdb->name);
00504       } else if (sd->desc.proc_cnvt != NULL) {
00505         sd->desc.proc_cnvt((const char*)p);
00506       }
00507       break;
00508     }
00509     default: NOT_REACHED();
00510     }
00511   }
00512 }
00513 
00526 static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
00527 {
00528   IniGroup *group_def = NULL, *group;
00529   IniItem *item;
00530   char buf[512];
00531   const char *s;
00532   void *ptr;
00533 
00534   for (; sd->save.cmd != SL_END; sd++) {
00535     const SettingDescBase *sdb = &sd->desc;
00536     const SaveLoad        *sld = &sd->save;
00537 
00538     /* If the setting is not saved to the configuration
00539      * file, just continue with the next setting */
00540     if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
00541     if (sld->conv & SLF_CONFIG_NO) continue;
00542 
00543     /* XXX - wtf is this?? (group override?) */
00544     s = strchr(sdb->name, '.');
00545     if (s != NULL) {
00546       group = ini->GetGroup(sdb->name, s - sdb->name);
00547       s++;
00548     } else {
00549       if (group_def == NULL) group_def = ini->GetGroup(grpname);
00550       s = sdb->name;
00551       group = group_def;
00552     }
00553 
00554     item = group->GetItem(s, true);
00555     ptr = GetVariableAddress(object, sld);
00556 
00557     if (item->value != NULL) {
00558       /* check if the value is the same as the old value */
00559       const void *p = StringToVal(sdb, item->value);
00560 
00561       /* The main type of a variable/setting is in bytes 8-15
00562        * The subtype (what kind of numbers do we have there) is in 0-7 */
00563       switch (sdb->cmd) {
00564       case SDT_BOOLX:
00565       case SDT_NUMX:
00566       case SDT_ONEOFMANY:
00567       case SDT_MANYOFMANY:
00568         switch (GetVarMemType(sld->conv)) {
00569         case SLE_VAR_BL:
00570           if (*(bool*)ptr == (p != NULL)) continue;
00571           break;
00572         case SLE_VAR_I8:
00573         case SLE_VAR_U8:
00574           if (*(byte*)ptr == (byte)(unsigned long)p) continue;
00575           break;
00576         case SLE_VAR_I16:
00577         case SLE_VAR_U16:
00578           if (*(uint16*)ptr == (uint16)(unsigned long)p) continue;
00579           break;
00580         case SLE_VAR_I32:
00581         case SLE_VAR_U32:
00582           if (*(uint32*)ptr == (uint32)(unsigned long)p) continue;
00583           break;
00584         default: NOT_REACHED();
00585         }
00586         break;
00587       default: break; // Assume the other types are always changed
00588       }
00589     }
00590 
00591     /* Value has changed, get the new value and put it into a buffer */
00592     switch (sdb->cmd) {
00593     case SDT_BOOLX:
00594     case SDT_NUMX:
00595     case SDT_ONEOFMANY:
00596     case SDT_MANYOFMANY: {
00597       uint32 i = (uint32)ReadValue(ptr, sld->conv);
00598 
00599       switch (sdb->cmd) {
00600       case SDT_BOOLX:      strecpy(buf, (i != 0) ? "true" : "false", lastof(buf)); break;
00601       case SDT_NUMX:       seprintf(buf, lastof(buf), IsSignedVarMemType(sld->conv) ? "%d" : "%u", i); break;
00602       case SDT_ONEOFMANY:  MakeOneOfMany(buf, lastof(buf), sdb->many, i); break;
00603       case SDT_MANYOFMANY: MakeManyOfMany(buf, lastof(buf), sdb->many, i); break;
00604       default: NOT_REACHED();
00605       }
00606       break;
00607     }
00608 
00609     case SDT_STRING:
00610       switch (GetVarMemType(sld->conv)) {
00611       case SLE_VAR_STRB: strecpy(buf, (char*)ptr, lastof(buf)); break;
00612       case SLE_VAR_STRBQ:seprintf(buf, lastof(buf), "\"%s\"", (char*)ptr); break;
00613       case SLE_VAR_STR:  strecpy(buf, *(char**)ptr, lastof(buf)); break;
00614       case SLE_VAR_STRQ:
00615         if (*(char**)ptr == NULL) {
00616           buf[0] = '\0';
00617         } else {
00618           seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
00619         }
00620         break;
00621       case SLE_VAR_CHAR: buf[0] = *(char*)ptr; buf[1] = '\0'; break;
00622       default: NOT_REACHED();
00623       }
00624       break;
00625 
00626     case SDT_INTLIST:
00627       MakeIntList(buf, lastof(buf), ptr, sld->length, GetVarMemType(sld->conv));
00628       break;
00629     default: NOT_REACHED();
00630     }
00631 
00632     /* The value is different, that means we have to write it to the ini */
00633     free(item->value);
00634     item->value = strdup(buf);
00635   }
00636 }
00637 
00647 static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *list)
00648 {
00649   IniGroup *group = ini->GetGroup(grpname);
00650 
00651   if (group == NULL || list == NULL) return;
00652 
00653   list->Clear();
00654 
00655   for (const IniItem *item = group->item; item != NULL; item = item->next) {
00656     if (item->name != NULL) *list->Append() = strdup(item->name);
00657   }
00658 }
00659 
00669 static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *list)
00670 {
00671   IniGroup *group = ini->GetGroup(grpname);
00672 
00673   if (group == NULL || list == NULL) return;
00674   group->Clear();
00675 
00676   for (char **iter = list->Begin(); iter != list->End(); iter++) {
00677     group->GetItem(*iter, true)->SetValue("");
00678   }
00679 }
00680 
00681 /* Begin - Callback Functions for the various settings. */
00682 
00684 static bool v_PositionMainToolbar(int32 p1)
00685 {
00686   if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
00687   return true;
00688 }
00689 
00691 static bool v_PositionStatusbar(int32 p1)
00692 {
00693   if (_game_mode != GM_MENU) {
00694     PositionStatusbar(NULL);
00695     PositionNewsMessage(NULL);
00696     PositionNetworkChatWindow(NULL);
00697   }
00698   return true;
00699 }
00700 
00701 static bool PopulationInLabelActive(int32 p1)
00702 {
00703   UpdateAllTownVirtCoords();
00704   return true;
00705 }
00706 
00707 static bool RedrawScreen(int32 p1)
00708 {
00709   MarkWholeScreenDirty();
00710   return true;
00711 }
00712 
00718 static bool RedrawSmallmap(int32 p1)
00719 {
00720   BuildLandLegend();
00721   BuildOwnerLegend();
00722   SetWindowClassesDirty(WC_SMALLMAP);
00723   return true;
00724 }
00725 
00726 static bool InvalidateDetailsWindow(int32 p1)
00727 {
00728   SetWindowClassesDirty(WC_VEHICLE_DETAILS);
00729   return true;
00730 }
00731 
00732 static bool InvalidateStationBuildWindow(int32 p1)
00733 {
00734   SetWindowDirty(WC_BUILD_STATION, 0);
00735   return true;
00736 }
00737 
00738 static bool InvalidateBuildIndustryWindow(int32 p1)
00739 {
00740   InvalidateWindowData(WC_BUILD_INDUSTRY, 0);
00741   return true;
00742 }
00743 
00744 static bool CloseSignalGUI(int32 p1)
00745 {
00746   if (p1 == 0) {
00747     DeleteWindowByClass(WC_BUILD_SIGNAL);
00748   }
00749   return true;
00750 }
00751 
00752 static bool InvalidateTownViewWindow(int32 p1)
00753 {
00754   InvalidateWindowClassesData(WC_TOWN_VIEW, p1);
00755   return true;
00756 }
00757 
00758 static bool DeleteSelectStationWindow(int32 p1)
00759 {
00760   DeleteWindowById(WC_SELECT_STATION, 0);
00761   return true;
00762 }
00763 
00764 static bool UpdateConsists(int32 p1)
00765 {
00766   Train *t;
00767   FOR_ALL_TRAINS(t) {
00768     /* Update the consist of all trains so the maximum speed is set correctly. */
00769     if (t->IsFrontEngine() || t->IsFreeWagon()) t->ConsistChanged(true);
00770   }
00771   return true;
00772 }
00773 
00774 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
00775 static bool CheckInterval(int32 p1)
00776 {
00777   VehicleDefaultSettings *vds;
00778   if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
00779     vds = &_settings_client.company.vehicle;
00780   } else {
00781     vds = &Company::Get(_current_company)->settings.vehicle;
00782   }
00783 
00784   if (p1) {
00785     vds->servint_trains   = 50;
00786     vds->servint_roadveh  = 50;
00787     vds->servint_aircraft = 50;
00788     vds->servint_ships    = 50;
00789   } else {
00790     vds->servint_trains   = 150;
00791     vds->servint_roadveh  = 150;
00792     vds->servint_aircraft = 100;
00793     vds->servint_ships    = 360;
00794   }
00795 
00796   InvalidateDetailsWindow(0);
00797 
00798   return true;
00799 }
00800 
00801 static bool TrainAccelerationModelChanged(int32 p1)
00802 {
00803   Train *t;
00804   FOR_ALL_TRAINS(t) {
00805     if (t->IsFrontEngine()) {
00806       t->tcache.cached_max_curve_speed = t->GetCurveSpeedLimit();
00807       t->UpdateAcceleration();
00808     }
00809   }
00810 
00811   /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
00812   SetWindowClassesDirty(WC_ENGINE_PREVIEW);
00813   InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
00814   SetWindowClassesDirty(WC_VEHICLE_DETAILS);
00815 
00816   return true;
00817 }
00818 
00824 static bool TrainSlopeSteepnessChanged(int32 p1)
00825 {
00826   Train *t;
00827   FOR_ALL_TRAINS(t) {
00828     if (t->IsFrontEngine()) t->CargoChanged();
00829   }
00830 
00831   return true;
00832 }
00833 
00839 static bool RoadVehAccelerationModelChanged(int32 p1)
00840 {
00841   if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
00842     RoadVehicle *rv;
00843     FOR_ALL_ROADVEHICLES(rv) {
00844       if (rv->IsFrontEngine()) {
00845         rv->CargoChanged();
00846       }
00847     }
00848   }
00849 
00850   /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
00851   SetWindowClassesDirty(WC_ENGINE_PREVIEW);
00852   InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
00853   SetWindowClassesDirty(WC_VEHICLE_DETAILS);
00854 
00855   return true;
00856 }
00857 
00863 static bool RoadVehSlopeSteepnessChanged(int32 p1)
00864 {
00865   RoadVehicle *rv;
00866   FOR_ALL_ROADVEHICLES(rv) {
00867     if (rv->IsFrontEngine()) rv->CargoChanged();
00868   }
00869 
00870   return true;
00871 }
00872 
00873 static bool DragSignalsDensityChanged(int32)
00874 {
00875   InvalidateWindowData(WC_BUILD_SIGNAL, 0);
00876 
00877   return true;
00878 }
00879 
00880 static bool TownFoundingChanged(int32 p1)
00881 {
00882   if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
00883     DeleteWindowById(WC_FOUND_TOWN, 0);
00884     return true;
00885   }
00886   InvalidateWindowData(WC_FOUND_TOWN, 0);
00887   return true;
00888 }
00889 
00890 static bool InvalidateVehTimetableWindow(int32 p1)
00891 {
00892   InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE, -2);
00893   return true;
00894 }
00895 
00903 static bool InvalidateNewGRFChangeWindows(int32 p1)
00904 {
00905   InvalidateWindowClassesData(WC_SAVELOAD);
00906   DeleteWindowByClass(WC_GAME_OPTIONS);
00907   ReInitAllWindows();
00908   return true;
00909 }
00910 
00911 static bool InvalidateCompanyLiveryWindow(int32 p1)
00912 {
00913   InvalidateWindowClassesData(WC_COMPANY_COLOUR);
00914   return RedrawScreen(p1);
00915 }
00916 
00917 static bool InvalidateIndustryViewWindow(int32 p1)
00918 {
00919   InvalidateWindowClassesData(WC_INDUSTRY_VIEW);
00920   return true;
00921 }
00922 
00928 static bool RedrawTownAuthority(int32 p1)
00929 {
00930   SetWindowClassesDirty(WC_TOWN_AUTHORITY);
00931   return true;
00932 }
00933 
00934 /*
00935  * A: competitors
00936  * B: competitor start time. Deprecated since savegame version 110.
00937  * C: town count (3 = high, 0 = very low)
00938  * D: industry count (4 = high, 0 = none)
00939  * E: inital loan (in GBP)
00940  * F: interest rate
00941  * G: running costs (0 = low, 2 = high)
00942  * H: construction speed of competitors (0 = very slow, 4 = very fast)
00943  * I: competitor intelligence. Deprecated since savegame version 110.
00944  * J: breakdowns (0 = off, 2 = normal)
00945  * K: subsidy multiplier (0 = 1.5, 3 = 4.0)
00946  * L: construction cost (0-2)
00947  * M: terrain type (0 = very flat, 3 = mountainous)
00948  * N: amount of water (0 = very low, 3 = high)
00949  * O: economy (0 = steady, 1 = fluctuating)
00950  * P: Train reversing (0 = end of line + stations, 1 = end of line)
00951  * Q: disasters
00952  * R: area restructuring (0 = permissive, 2 = hostile)
00953  * S: the difficulty level
00954  */
00955 static const DifficultySettings _default_game_diff[3] = { /*
00956    A, C, D,      E, F, G, H, J, K, L, M, N, O, P, Q, R, S*/
00957   {2, 2, 4, 300000, 2, 0, 2, 1, 2, 0, 1, 0, 0, 0, 0, 0, 0}, 
00958   {4, 2, 3, 150000, 3, 1, 3, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1}, 
00959   {7, 3, 3, 100000, 4, 1, 3, 2, 0, 2, 3, 2, 1, 1, 1, 2, 2}, 
00960 };
00961 
00962 void SetDifficultyLevel(int mode, DifficultySettings *gm_opt)
00963 {
00964   assert(mode <= 3);
00965 
00966   if (mode != 3) {
00967     *gm_opt = _default_game_diff[mode];
00968   } else {
00969     gm_opt->diff_level = 3;
00970   }
00971 }
00972 
00974 static void ValidateSettings()
00975 {
00976   /* Force the difficulty levels to correct values if they are invalid. */
00977   if (_settings_newgame.difficulty.diff_level != 3) {
00978     SetDifficultyLevel(_settings_newgame.difficulty.diff_level, &_settings_newgame.difficulty);
00979   }
00980 
00981   /* Do not allow a custom sea level with the original land generator. */
00982   if (_settings_newgame.game_creation.land_generator == 0 &&
00983       _settings_newgame.difficulty.quantity_sea_lakes == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) {
00984     _settings_newgame.difficulty.quantity_sea_lakes = CUSTOM_SEA_LEVEL_MIN_PERCENTAGE;
00985   }
00986 }
00987 
00988 static bool DifficultyReset(int32 level)
00989 {
00990   /* In game / in the scenario editor you can set the difficulty level only to custom. This is
00991    * needed by the AI Gui code that sets the difficulty level when you change any AI settings. */
00992   if (_game_mode != GM_MENU && level != 3) return false;
00993   SetDifficultyLevel(level, &GetGameSettings().difficulty);
00994   return true;
00995 }
00996 
00997 static bool DifficultyChange(int32)
00998 {
00999   if (_game_mode == GM_MENU) {
01000     if (_settings_newgame.difficulty.diff_level != 3) {
01001       ShowErrorMessage(STR_WARNING_DIFFICULTY_TO_CUSTOM, INVALID_STRING_ID, WL_WARNING);
01002       _settings_newgame.difficulty.diff_level = 3;
01003     }
01004     SetWindowClassesDirty(WC_SELECT_GAME);
01005   } else {
01006     _settings_game.difficulty.diff_level = 3;
01007   }
01008 
01009   /* If we are a network-client, update the difficult setting (if it is open).
01010    * Use this instead of just dirtying the window because we need to load in
01011    * the new difficulty settings */
01012   if (_networking && FindWindowById(WC_GAME_OPTIONS, 0) != NULL) {
01013     ShowGameDifficulty();
01014   }
01015 
01016   return true;
01017 }
01018 
01019 static bool DifficultyNoiseChange(int32 i)
01020 {
01021   if (_game_mode == GM_NORMAL) {
01022     UpdateAirportsNoise();
01023     if (_settings_game.economy.station_noise_level) {
01024       InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
01025     }
01026   }
01027 
01028   return DifficultyChange(i);
01029 }
01030 
01031 static bool MaxNoAIsChange(int32 i)
01032 {
01033   if (GetGameSettings().difficulty.max_no_competitors != 0 &&
01034 #ifdef ENABLE_AI
01035       AI::GetInfoList()->size() == 0 &&
01036 #endif /* ENABLE_AI */
01037       (!_networking || _network_server)) {
01038     ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, WL_CRITICAL);
01039   }
01040 
01041   return DifficultyChange(i);
01042 }
01043 
01049 static bool CheckRoadSide(int p1)
01050 {
01051   extern bool RoadVehiclesAreBuilt();
01052   return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
01053 }
01054 
01062 static int32 ConvertLandscape(const char *value)
01063 {
01064   /* try with the old values */
01065   return LookupOneOfMany("normal|hilly|desert|candy", value);
01066 }
01067 
01068 static bool CheckFreeformEdges(int32 p1)
01069 {
01070   if (_game_mode == GM_MENU) return true;
01071   if (p1 != 0) {
01072     Ship *s;
01073     FOR_ALL_SHIPS(s) {
01074       if (TileX(s->tile) == 0 || TileY(s->tile) == 0) {
01075         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
01076         return false;
01077       }
01078     }
01079     Station *st;
01080     FOR_ALL_STATIONS(st) {
01081       if (TileX(st->xy) == 0 || TileY(st->xy) == 0) {
01082         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
01083         return false;
01084       }
01085     }
01086     for (uint i = 0; i < MapSizeX(); i++) MakeVoid(TileXY(i, 0));
01087     for (uint i = 0; i < MapSizeY(); i++) MakeVoid(TileXY(0, i));
01088   } else {
01089     for (uint i = 0; i < MapMaxX(); i++) {
01090       if (TileHeight(TileXY(i, 1)) != 0) {
01091         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
01092         return false;
01093       }
01094     }
01095     for (uint i = 1; i < MapMaxX(); i++) {
01096       if (!IsTileType(TileXY(i, MapMaxY() - 1), MP_WATER) || TileHeight(TileXY(1, MapMaxY())) != 0) {
01097         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
01098         return false;
01099       }
01100     }
01101     for (uint i = 0; i < MapMaxY(); i++) {
01102       if (TileHeight(TileXY(1, i)) != 0) {
01103         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
01104         return false;
01105       }
01106     }
01107     for (uint i = 1; i < MapMaxY(); i++) {
01108       if (!IsTileType(TileXY(MapMaxX() - 1, i), MP_WATER) || TileHeight(TileXY(MapMaxX(), i)) != 0) {
01109         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
01110         return false;
01111       }
01112     }
01113     /* Make tiles at the border water again. */
01114     for (uint i = 0; i < MapMaxX(); i++) {
01115       SetTileHeight(TileXY(i, 0), 0);
01116       SetTileType(TileXY(i, 0), MP_WATER);
01117     }
01118     for (uint i = 0; i < MapMaxY(); i++) {
01119       SetTileHeight(TileXY(0, i), 0);
01120       SetTileType(TileXY(0, i), MP_WATER);
01121     }
01122   }
01123   MarkWholeScreenDirty();
01124   return true;
01125 }
01126 
01131 static bool ChangeDynamicEngines(int32 p1)
01132 {
01133   if (_game_mode == GM_MENU) return true;
01134 
01135   if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
01136     ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, WL_ERROR);
01137     return false;
01138   }
01139 
01140   return true;
01141 }
01142 
01143 static bool StationCatchmentChanged(int32 p1)
01144 {
01145   Station::RecomputeIndustriesNearForAll();
01146   return true;
01147 }
01148 
01149 
01150 #ifdef ENABLE_NETWORK
01151 
01152 static bool UpdateClientName(int32 p1)
01153 {
01154   NetworkUpdateClientName();
01155   return true;
01156 }
01157 
01158 static bool UpdateServerPassword(int32 p1)
01159 {
01160   if (strcmp(_settings_client.network.server_password, "*") == 0) {
01161     _settings_client.network.server_password[0] = '\0';
01162   }
01163 
01164   return true;
01165 }
01166 
01167 static bool UpdateRconPassword(int32 p1)
01168 {
01169   if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
01170     _settings_client.network.rcon_password[0] = '\0';
01171   }
01172 
01173   return true;
01174 }
01175 
01176 static bool UpdateClientConfigValues(int32 p1)
01177 {
01178   if (_network_server) NetworkServerSendConfigUpdate();
01179 
01180   return true;
01181 }
01182 
01183 #endif /* ENABLE_NETWORK */
01184 
01185 
01186 /* End - Callback Functions */
01187 
01191 static void PrepareOldDiffCustom()
01192 {
01193   memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
01194 }
01195 
01202 static void HandleOldDiffCustom(bool savegame)
01203 {
01204   uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && IsSavegameVersionBefore(4)) ? 1 : 0);
01205 
01206   if (!savegame) {
01207     /* If we did read to old_diff_custom, then at least one value must be non 0. */
01208     bool old_diff_custom_used = false;
01209     for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
01210       old_diff_custom_used = (_old_diff_custom[i] != 0);
01211     }
01212 
01213     if (!old_diff_custom_used) return;
01214   }
01215 
01216   for (uint i = 0; i < options_to_load; i++) {
01217     const SettingDesc *sd = &_settings[i];
01218     /* Skip deprecated options */
01219     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01220     void *var = GetVariableAddress(savegame ? &_settings_game : &_settings_newgame, &sd->save);
01221     Write_ValidateSetting(var, sd, (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]));
01222   }
01223 }
01224 
01231 static bool ConvertOldNewsSetting(const char *name, const char *value)
01232 {
01233   if (strcasecmp(name, "openclose") == 0) {
01234     /* openclose has been split in "open" and "close".
01235      * So the job is now to decrypt the value of the old news config
01236      * and give it to the two newly introduced ones*/
01237 
01238     NewsDisplay display = ND_OFF; // default
01239     if (strcasecmp(value, "full") == 0) {
01240       display = ND_FULL;
01241     } else if (strcasecmp(value, "summarized") == 0) {
01242       display = ND_SUMMARY;
01243     }
01244     /* tranfert of values */
01245     _news_type_data[NT_INDUSTRY_OPEN].display = display;
01246     _news_type_data[NT_INDUSTRY_CLOSE].display = display;
01247     return true;
01248   }
01249   return false;
01250 }
01251 
01257 static void NewsDisplayLoadConfig(IniFile *ini, const char *grpname)
01258 {
01259   IniGroup *group = ini->GetGroup(grpname);
01260   IniItem *item;
01261 
01262   /* If no group exists, return */
01263   if (group == NULL) return;
01264 
01265   for (item = group->item; item != NULL; item = item->next) {
01266     int news_item = -1;
01267     for (int i = 0; i < NT_END; i++) {
01268       if (strcasecmp(item->name, _news_type_data[i].name) == 0) {
01269         news_item = i;
01270         break;
01271       }
01272     }
01273 
01274     /* the config been read is not within current aceptable config */
01275     if (news_item == -1) {
01276       /* if the conversion function cannot process it, advice by a debug warning*/
01277       if (!ConvertOldNewsSetting(item->name, item->value)) {
01278         DEBUG(misc, 0, "Invalid display option: %s", item->name);
01279       }
01280       /* in all cases, there is nothing left to do */
01281       continue;
01282     }
01283 
01284     if (StrEmpty(item->value)) {
01285       DEBUG(misc, 0, "Empty display value for newstype %s", item->name);
01286       continue;
01287     } else if (strcasecmp(item->value, "full") == 0) {
01288       _news_type_data[news_item].display = ND_FULL;
01289     } else if (strcasecmp(item->value, "off") == 0) {
01290       _news_type_data[news_item].display = ND_OFF;
01291     } else if (strcasecmp(item->value, "summarized") == 0) {
01292       _news_type_data[news_item].display = ND_SUMMARY;
01293     } else {
01294       DEBUG(misc, 0, "Invalid display value for newstype %s: %s", item->name, item->value);
01295       continue;
01296     }
01297   }
01298 }
01299 
01300 static void AILoadConfig(IniFile *ini, const char *grpname)
01301 {
01302 #ifdef ENABLE_AI
01303   IniGroup *group = ini->GetGroup(grpname);
01304   IniItem *item;
01305 
01306   /* Clean any configured AI */
01307   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
01308     AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME)->ChangeAI(NULL);
01309   }
01310 
01311   /* If no group exists, return */
01312   if (group == NULL) return;
01313 
01314   CompanyID c = COMPANY_FIRST;
01315   for (item = group->item; c < MAX_COMPANIES && item != NULL; c++, item = item->next) {
01316     AIConfig *config = AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME);
01317 
01318     config->ChangeAI(item->name);
01319     if (!config->HasAI()) {
01320       if (strcmp(item->name, "none") != 0) {
01321         DEBUG(ai, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item->name);
01322         continue;
01323       }
01324     }
01325     if (item->value != NULL) config->StringToSettings(item->value);
01326   }
01327 #endif /* ENABLE_AI */
01328 }
01329 
01336 static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
01337 {
01338   IniGroup *group = ini->GetGroup(grpname);
01339   IniItem *item;
01340   GRFConfig *first = NULL;
01341   GRFConfig **curr = &first;
01342 
01343   if (group == NULL) return NULL;
01344 
01345   for (item = group->item; item != NULL; item = item->next) {
01346     GRFConfig *c = new GRFConfig(item->name);
01347 
01348     /* Parse parameters */
01349     if (!StrEmpty(item->value)) {
01350       c->num_params = ParseIntList(item->value, (int*)c->param, lengthof(c->param));
01351       if (c->num_params == (byte)-1) {
01352         ShowInfoF("ini: error in array '%s'", item->name);
01353         c->num_params = 0;
01354       }
01355     }
01356 
01357     /* Check if item is valid */
01358     if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
01359       const char *msg;
01360 
01361       if (c->status == GCS_NOT_FOUND) {
01362         msg = "not found";
01363       } else if (HasBit(c->flags, GCF_UNSAFE)) {
01364         msg = "unsafe for static use";
01365       } else if (HasBit(c->flags, GCF_SYSTEM)) {
01366         msg = "system NewGRF";
01367       } else if (HasBit(c->flags, GCF_INVALID)) {
01368         msg = "incompatible to this version of OpenTTD";
01369       } else {
01370         msg = "unknown";
01371       }
01372 
01373       ShowInfoF("ini: ignoring invalid NewGRF '%s': %s", item->name, msg);
01374       delete c;
01375       continue;
01376     }
01377 
01378     /* Check for duplicate GRFID (will also check for duplicate filenames) */
01379     bool duplicate = false;
01380     for (const GRFConfig *gc = first; gc != NULL; gc = gc->next) {
01381       if (gc->ident.grfid == c->ident.grfid) {
01382         ShowInfoF("ini: ignoring  NewGRF '%s': duplicate GRF ID with '%s'", item->name, gc->filename);
01383         duplicate = true;
01384         break;
01385       }
01386     }
01387     if (duplicate) {
01388       delete c;
01389       continue;
01390     }
01391 
01392     /* Mark file as static to avoid saving in savegame. */
01393     if (is_static) SetBit(c->flags, GCF_STATIC);
01394 
01395     /* Add item to list */
01396     *curr = c;
01397     curr = &c->next;
01398   }
01399 
01400   return first;
01401 }
01402 
01408 static void NewsDisplaySaveConfig(IniFile *ini, const char *grpname)
01409 {
01410   IniGroup *group = ini->GetGroup(grpname);
01411 
01412   for (int i = 0; i < NT_END; i++) {
01413     const char *value;
01414     int v = _news_type_data[i].display;
01415 
01416     value = (v == ND_OFF ? "off" : (v == ND_SUMMARY ? "summarized" : "full"));
01417 
01418     group->GetItem(_news_type_data[i].name, true)->SetValue(value);
01419   }
01420 }
01421 
01422 static void AISaveConfig(IniFile *ini, const char *grpname)
01423 {
01424 #ifdef ENABLE_AI
01425   IniGroup *group = ini->GetGroup(grpname);
01426 
01427   if (group == NULL) return;
01428   group->Clear();
01429 
01430   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
01431     AIConfig *config = AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME);
01432     const char *name;
01433     char value[1024];
01434     config->SettingsToString(value, lengthof(value));
01435 
01436     if (config->HasAI()) {
01437       name = config->GetName();
01438     } else {
01439       name = "none";
01440     }
01441 
01442     IniItem *item = new IniItem(group, name, strlen(name));
01443     item->SetValue(value);
01444   }
01445 #endif /* ENABLE_AI */
01446 }
01447 
01452 static void SaveVersionInConfig(IniFile *ini)
01453 {
01454   IniGroup *group = ini->GetGroup("version");
01455 
01456   char version[9];
01457   snprintf(version, lengthof(version), "%08X", _openttd_newgrf_version);
01458 
01459   const char * const versions[][2] = {
01460     { "version_string", _openttd_revision },
01461     { "version_number", version }
01462   };
01463 
01464   for (uint i = 0; i < lengthof(versions); i++) {
01465     group->GetItem(versions[i][0], true)->SetValue(versions[i][1]);
01466   }
01467 }
01468 
01469 /* Save a GRF configuration to the given group name */
01470 static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
01471 {
01472   ini->RemoveGroup(grpname);
01473   IniGroup *group = ini->GetGroup(grpname);
01474   const GRFConfig *c;
01475 
01476   for (c = list; c != NULL; c = c->next) {
01477     char params[512];
01478     GRFBuildParamList(params, c, lastof(params));
01479 
01480     group->GetItem(c->filename, true)->SetValue(params);
01481   }
01482 }
01483 
01484 /* Common handler for saving/loading variables to the configuration file */
01485 static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list)
01486 {
01487   proc(ini, (const SettingDesc*)_misc_settings,    "misc",  NULL);
01488   proc(ini, (const SettingDesc*)_music_settings,   "music", &_msf);
01489 #if defined(WIN32) && !defined(DEDICATED)
01490   proc(ini, (const SettingDesc*)_win32_settings,   "win32", NULL);
01491 #endif /* WIN32 */
01492 
01493   proc(ini, _settings,         "patches",  &_settings_newgame);
01494   proc(ini, _currency_settings,"currency", &_custom_currency);
01495   proc(ini, _company_settings, "company",  &_settings_client.company);
01496 
01497 #ifdef ENABLE_NETWORK
01498   proc_list(ini, "server_bind_addresses", &_network_bind_list);
01499   proc_list(ini, "servers", &_network_host_list);
01500   proc_list(ini, "bans",    &_network_ban_list);
01501 #endif /* ENABLE_NETWORK */
01502 }
01503 
01504 static IniFile *IniLoadConfig()
01505 {
01506   IniFile *ini = new IniFile(_list_group_names);
01507   ini->LoadFromDisk(_config_file);
01508   return ini;
01509 }
01510 
01512 void LoadFromConfig()
01513 {
01514   IniFile *ini = IniLoadConfig();
01515   ResetCurrencies(false); // Initialize the array of curencies, without preserving the custom one
01516 
01517   HandleSettingDescs(ini, IniLoadSettings, IniLoadSettingList);
01518   _grfconfig_newgame = GRFLoadConfig(ini, "newgrf", false);
01519   _grfconfig_static  = GRFLoadConfig(ini, "newgrf-static", true);
01520   NewsDisplayLoadConfig(ini, "news_display");
01521   AILoadConfig(ini, "ai_players");
01522 
01523   PrepareOldDiffCustom();
01524   IniLoadSettings(ini, _gameopt_settings, "gameopt", &_settings_newgame);
01525   HandleOldDiffCustom(false);
01526 
01527   ValidateSettings();
01528   delete ini;
01529 }
01530 
01532 void SaveToConfig()
01533 {
01534   IniFile *ini = IniLoadConfig();
01535 
01536   /* Remove some obsolete groups. These have all been loaded into other groups. */
01537   ini->RemoveGroup("patches");
01538   ini->RemoveGroup("yapf");
01539   ini->RemoveGroup("gameopt");
01540 
01541   HandleSettingDescs(ini, IniSaveSettings, IniSaveSettingList);
01542   GRFSaveConfig(ini, "newgrf", _grfconfig_newgame);
01543   GRFSaveConfig(ini, "newgrf-static", _grfconfig_static);
01544   NewsDisplaySaveConfig(ini, "news_display");
01545   AISaveConfig(ini, "ai_players");
01546   SaveVersionInConfig(ini);
01547   ini->SaveToDisk(_config_file);
01548   delete ini;
01549 }
01550 
01555 void GetGRFPresetList(GRFPresetList *list)
01556 {
01557   list->Clear();
01558 
01559   IniFile *ini = IniLoadConfig();
01560   IniGroup *group;
01561   for (group = ini->group; group != NULL; group = group->next) {
01562     if (strncmp(group->name, "preset-", 7) == 0) {
01563       *list->Append() = strdup(group->name + 7);
01564     }
01565   }
01566 
01567   delete ini;
01568 }
01569 
01576 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
01577 {
01578   char *section = (char*)alloca(strlen(config_name) + 8);
01579   sprintf(section, "preset-%s", config_name);
01580 
01581   IniFile *ini = IniLoadConfig();
01582   GRFConfig *config = GRFLoadConfig(ini, section, false);
01583   delete ini;
01584 
01585   return config;
01586 }
01587 
01594 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
01595 {
01596   char *section = (char*)alloca(strlen(config_name) + 8);
01597   sprintf(section, "preset-%s", config_name);
01598 
01599   IniFile *ini = IniLoadConfig();
01600   GRFSaveConfig(ini, section, config);
01601   ini->SaveToDisk(_config_file);
01602   delete ini;
01603 }
01604 
01609 void DeleteGRFPresetFromConfig(const char *config_name)
01610 {
01611   char *section = (char*)alloca(strlen(config_name) + 8);
01612   sprintf(section, "preset-%s", config_name);
01613 
01614   IniFile *ini = IniLoadConfig();
01615   ini->RemoveGroup(section);
01616   ini->SaveToDisk(_config_file);
01617   delete ini;
01618 }
01619 
01620 static const SettingDesc *GetSettingDescription(uint index)
01621 {
01622   if (index >= lengthof(_settings)) return NULL;
01623   return &_settings[index];
01624 }
01625 
01637 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01638 {
01639   const SettingDesc *sd = GetSettingDescription(p1);
01640 
01641   if (sd == NULL) return CMD_ERROR;
01642   if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
01643 
01644   if ((sd->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return CMD_ERROR;
01645   if ((sd->desc.flags & SGF_NO_NETWORK) && _networking) return CMD_ERROR;
01646   if ((sd->desc.flags & SGF_NEWGAME_ONLY) &&
01647       (_game_mode == GM_NORMAL ||
01648       (_game_mode == GM_EDITOR && (sd->desc.flags & SGF_SCENEDIT_TOO) == 0))) {
01649     return CMD_ERROR;
01650   }
01651 
01652   if (flags & DC_EXEC) {
01653     void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
01654 
01655     int32 oldval = (int32)ReadValue(var, sd->save.conv);
01656     int32 newval = (int32)p2;
01657 
01658     Write_ValidateSetting(var, sd, newval);
01659     newval = (int32)ReadValue(var, sd->save.conv);
01660 
01661     if (oldval == newval) return CommandCost();
01662 
01663     if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
01664       WriteValue(var, sd->save.conv, (int64)oldval);
01665       return CommandCost();
01666     }
01667 
01668     if (sd->desc.flags & SGF_NO_NETWORK) {
01669       GamelogStartAction(GLAT_SETTING);
01670       GamelogSetting(sd->desc.name, oldval, newval);
01671       GamelogStopAction();
01672     }
01673 
01674     SetWindowDirty(WC_GAME_OPTIONS, 0);
01675   }
01676 
01677   return CommandCost();
01678 }
01679 
01690 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01691 {
01692   if (p1 >= lengthof(_company_settings)) return CMD_ERROR;
01693   const SettingDesc *sd = &_company_settings[p1];
01694 
01695   if (flags & DC_EXEC) {
01696     void *var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
01697 
01698     int32 oldval = (int32)ReadValue(var, sd->save.conv);
01699     int32 newval = (int32)p2;
01700 
01701     Write_ValidateSetting(var, sd, newval);
01702     newval = (int32)ReadValue(var, sd->save.conv);
01703 
01704     if (oldval == newval) return CommandCost();
01705 
01706     if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
01707       WriteValue(var, sd->save.conv, (int64)oldval);
01708       return CommandCost();
01709     }
01710 
01711     SetWindowDirty(WC_GAME_OPTIONS, 0);
01712   }
01713 
01714   return CommandCost();
01715 }
01716 
01724 bool SetSettingValue(uint index, int32 value, bool force_newgame)
01725 {
01726   const SettingDesc *sd = &_settings[index];
01727   /* If an item is company-based, we do not send it over the network
01728    * (if any) to change. Also *hack*hack* we update the _newgame version
01729    * of settings because changing a company-based setting in a game also
01730    * changes its defaults. At least that is the convention we have chosen */
01731   if (sd->save.conv & SLF_NETWORK_NO) {
01732     void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
01733     Write_ValidateSetting(var, sd, value);
01734 
01735     if (_game_mode != GM_MENU) {
01736       void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
01737       Write_ValidateSetting(var2, sd, value);
01738     }
01739     if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
01740     SetWindowDirty(WC_GAME_OPTIONS, 0);
01741     return true;
01742   }
01743 
01744   if (force_newgame) {
01745     void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
01746     Write_ValidateSetting(var2, sd, value);
01747     return true;
01748   }
01749 
01750   /* send non-company-based settings over the network */
01751   if (!_networking || (_networking && _network_server)) {
01752     return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
01753   }
01754   return false;
01755 }
01756 
01763 void SetCompanySetting(uint index, int32 value)
01764 {
01765   const SettingDesc *sd = &_company_settings[index];
01766   if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
01767     DoCommandP(0, index, value, CMD_CHANGE_COMPANY_SETTING);
01768   } else {
01769     void *var = GetVariableAddress(&_settings_client.company, &sd->save);
01770     Write_ValidateSetting(var, sd, value);
01771     if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
01772   }
01773 }
01774 
01778 void SetDefaultCompanySettings(CompanyID cid)
01779 {
01780   Company *c = Company::Get(cid);
01781   const SettingDesc *sd;
01782   for (sd = _company_settings; sd->save.cmd != SL_END; sd++) {
01783     void *var = GetVariableAddress(&c->settings, &sd->save);
01784     Write_ValidateSetting(var, sd, (int32)(size_t)sd->desc.def);
01785   }
01786 }
01787 
01788 #if defined(ENABLE_NETWORK)
01789 
01792 void SyncCompanySettings()
01793 {
01794   const SettingDesc *sd;
01795   uint i = 0;
01796   for (sd = _company_settings; sd->save.cmd != SL_END; sd++, i++) {
01797     const void *old_var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
01798     const void *new_var = GetVariableAddress(&_settings_client.company, &sd->save);
01799     uint32 old_value = (uint32)ReadValue(old_var, sd->save.conv);
01800     uint32 new_value = (uint32)ReadValue(new_var, sd->save.conv);
01801     if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, NULL, NULL, _local_company);
01802   }
01803 }
01804 #endif /* ENABLE_NETWORK */
01805 
01811 uint GetCompanySettingIndex(const char *name)
01812 {
01813   uint i;
01814   const SettingDesc *sd = GetSettingFromName(name, &i);
01815   assert(sd != NULL && (sd->desc.flags & SGF_PER_COMPANY) != 0);
01816   return i;
01817 }
01818 
01826 bool SetSettingValue(uint index, const char *value, bool force_newgame)
01827 {
01828   const SettingDesc *sd = &_settings[index];
01829   assert(sd->save.conv & SLF_NETWORK_NO);
01830 
01831   if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
01832     char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
01833     free(*var);
01834     *var = strcmp(value, "(null)") == 0 ? NULL : strdup(value);
01835   } else {
01836     char *var = (char*)GetVariableAddress(NULL, &sd->save);
01837     ttd_strlcpy(var, value, sd->save.length);
01838   }
01839   if (sd->desc.proc != NULL) sd->desc.proc(0);
01840 
01841   return true;
01842 }
01843 
01851 const SettingDesc *GetSettingFromName(const char *name, uint *i)
01852 {
01853   const SettingDesc *sd;
01854 
01855   /* First check all full names */
01856   for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01857     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01858     if (strcmp(sd->desc.name, name) == 0) return sd;
01859   }
01860 
01861   /* Then check the shortcut variant of the name. */
01862   for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01863     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01864     const char *short_name = strchr(sd->desc.name, '.');
01865     if (short_name != NULL) {
01866       short_name++;
01867       if (strcmp(short_name, name) == 0) return sd;
01868     }
01869   }
01870 
01871   if (strncmp(name, "company.", 8) == 0) name += 8;
01872   /* And finally the company-based settings */
01873   for (*i = 0, sd = _company_settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01874     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01875     if (strcmp(sd->desc.name, name) == 0) return sd;
01876   }
01877 
01878   return NULL;
01879 }
01880 
01881 /* Those 2 functions need to be here, else we have to make some stuff non-static
01882  * and besides, it is also better to keep stuff like this at the same place */
01883 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
01884 {
01885   uint index;
01886   const SettingDesc *sd = GetSettingFromName(name, &index);
01887 
01888   if (sd == NULL) {
01889     IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
01890     return;
01891   }
01892 
01893   bool success;
01894   if (sd->desc.cmd == SDT_STRING) {
01895     success = SetSettingValue(index, value, force_newgame);
01896   } else {
01897     uint32 val;
01898     extern bool GetArgumentInteger(uint32 *value, const char *arg);
01899     success = GetArgumentInteger(&val, value);
01900     if (!success) {
01901       IConsolePrintF(CC_ERROR, "'%s' is not an integer.", value);
01902       return;
01903     }
01904 
01905     success = SetSettingValue(index, val, force_newgame);
01906   }
01907 
01908   if (!success) {
01909     if (_network_server) {
01910       IConsoleError("This command/variable is not available during network games.");
01911     } else {
01912       IConsoleError("This command/variable is only available to a network server.");
01913     }
01914   }
01915 }
01916 
01917 void IConsoleSetSetting(const char *name, int value)
01918 {
01919   uint index;
01920   const SettingDesc *sd = GetSettingFromName(name, &index);
01921   assert(sd != NULL);
01922   SetSettingValue(index, value);
01923 }
01924 
01930 void IConsoleGetSetting(const char *name, bool force_newgame)
01931 {
01932   char value[20];
01933   uint index;
01934   const SettingDesc *sd = GetSettingFromName(name, &index);
01935   const void *ptr;
01936 
01937   if (sd == NULL) {
01938     IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
01939     return;
01940   }
01941 
01942   ptr = GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
01943 
01944   if (sd->desc.cmd == SDT_STRING) {
01945     IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char **)ptr : (const char *)ptr);
01946   } else {
01947     if (sd->desc.cmd == SDT_BOOLX) {
01948       snprintf(value, sizeof(value), (*(bool*)ptr == 1) ? "on" : "off");
01949     } else {
01950       snprintf(value, sizeof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
01951     }
01952 
01953     IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
01954       name, value, (sd->desc.flags & SGF_0ISDISABLED) ? "(0) " : "", sd->desc.min, sd->desc.max);
01955   }
01956 }
01957 
01963 void IConsoleListSettings(const char *prefilter)
01964 {
01965   IConsolePrintF(CC_WARNING, "All settings with their current value:");
01966 
01967   for (const SettingDesc *sd = _settings; sd->save.cmd != SL_END; sd++) {
01968     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01969     if (prefilter != NULL && strstr(sd->desc.name, prefilter) == NULL) continue;
01970     char value[80];
01971     const void *ptr = GetVariableAddress(&GetGameSettings(), &sd->save);
01972 
01973     if (sd->desc.cmd == SDT_BOOLX) {
01974       snprintf(value, lengthof(value), (*(bool*)ptr == 1) ? "on" : "off");
01975     } else if (sd->desc.cmd == SDT_STRING) {
01976       snprintf(value, sizeof(value), "%s", (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char **)ptr : (const char *)ptr);
01977     } else {
01978       snprintf(value, lengthof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
01979     }
01980     IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
01981   }
01982 
01983   IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
01984 }
01985 
01992 static void LoadSettings(const SettingDesc *osd, void *object)
01993 {
01994   for (; osd->save.cmd != SL_END; osd++) {
01995     const SaveLoad *sld = &osd->save;
01996     void *ptr = GetVariableAddress(object, sld);
01997 
01998     if (!SlObjectMember(ptr, sld)) continue;
01999     if (IsNumericType(sld->conv)) Write_ValidateSetting(ptr, osd, ReadValue(ptr, sld->conv));
02000   }
02001 }
02002 
02009 static void SaveSettings(const SettingDesc *sd, void *object)
02010 {
02011   /* We need to write the CH_RIFF header, but unfortunately can't call
02012    * SlCalcLength() because we have a different format. So do this manually */
02013   const SettingDesc *i;
02014   size_t length = 0;
02015   for (i = sd; i->save.cmd != SL_END; i++) {
02016     length += SlCalcObjMemberLength(object, &i->save);
02017   }
02018   SlSetLength(length);
02019 
02020   for (i = sd; i->save.cmd != SL_END; i++) {
02021     void *ptr = GetVariableAddress(object, &i->save);
02022     SlObjectMember(ptr, &i->save);
02023   }
02024 }
02025 
02026 static void Load_OPTS()
02027 {
02028   /* Copy over default setting since some might not get loaded in
02029    * a networking environment. This ensures for example that the local
02030    * autosave-frequency stays when joining a network-server */
02031   PrepareOldDiffCustom();
02032   LoadSettings(_gameopt_settings, &_settings_game);
02033   HandleOldDiffCustom(true);
02034 }
02035 
02036 static void Load_PATS()
02037 {
02038   /* Copy over default setting since some might not get loaded in
02039    * a networking environment. This ensures for example that the local
02040    * signal_side stays when joining a network-server */
02041   LoadSettings(_settings, &_settings_game);
02042 }
02043 
02044 static void Check_PATS()
02045 {
02046   LoadSettings(_settings, &_load_check_data.settings);
02047 }
02048 
02049 static void Save_PATS()
02050 {
02051   SaveSettings(_settings, &_settings_game);
02052 }
02053 
02054 void CheckConfig()
02055 {
02056   /*
02057    * Increase old default values for pf_maxdepth and pf_maxlength
02058    * to support big networks.
02059    */
02060   if (_settings_newgame.pf.opf.pf_maxdepth == 16 && _settings_newgame.pf.opf.pf_maxlength == 512) {
02061     _settings_newgame.pf.opf.pf_maxdepth = 48;
02062     _settings_newgame.pf.opf.pf_maxlength = 4096;
02063   }
02064 }
02065 
02066 extern const ChunkHandler _setting_chunk_handlers[] = {
02067   { 'OPTS', NULL,      Load_OPTS, NULL, NULL,       CH_RIFF},
02068   { 'PATS', Save_PATS, Load_PATS, NULL, Check_PATS, CH_RIFF | CH_LAST},
02069 };
02070 
02071 static bool IsSignedVarMemType(VarType vt)
02072 {
02073   switch (GetVarMemType(vt)) {
02074     case SLE_VAR_I8:
02075     case SLE_VAR_I16:
02076     case SLE_VAR_I32:
02077     case SLE_VAR_I64:
02078       return true;
02079   }
02080   return false;
02081 }

Generated on Thu Apr 14 00:48:19 2011 for OpenTTD by  doxygen 1.6.1