settings.cpp

Go to the documentation of this file.
00001 /* $Id: settings.cpp 19875 2010-05-21 16:03:29Z rubidium $ */
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 
00025 #include "stdafx.h"
00026 #include "currency.h"
00027 #include "screenshot.h"
00028 #include "variables.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 "strings_func.h"
00040 #include "vehicle_func.h"
00041 #include "sound_func.h"
00042 #include "company_func.h"
00043 #include "rev.h"
00044 #ifdef WITH_FREETYPE
00045 #include "fontcache.h"
00046 #endif
00047 #include "textbuf_gui.h"
00048 #include "rail_gui.h"
00049 #include "elrail_func.h"
00050 #include "gui.h"
00051 #include "town.h"
00052 #include "video/video_driver.hpp"
00053 #include "sound/sound_driver.hpp"
00054 #include "music/music_driver.hpp"
00055 #include "blitter/factory.hpp"
00056 #include "base_media_base.h"
00057 #include "gamelog.h"
00058 #include "settings_func.h"
00059 #include "ini_type.h"
00060 #include "ai/ai_config.hpp"
00061 #include "ai/ai.hpp"
00062 #include "newgrf.h"
00063 #include "ship.h"
00064 #include "company_base.h"
00065 #include "engine_base.h"
00066 #include "smallmap_gui.h"
00067 
00068 #include "void_map.h"
00069 #include "station_base.h"
00070 
00071 #include "table/strings.h"
00072 #include "table/settings.h"
00073 
00074 ClientSettings _settings_client;
00075 GameSettings _settings_game;
00076 GameSettings _settings_newgame;
00077 VehicleDefaultSettings _old_vds; 
00078 
00079 typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
00080 typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList *list);
00081 
00082 static bool IsSignedVarMemType(VarType vt);
00083 
00087 static const char * const _list_group_names[] = {
00088   "bans",
00089   "newgrf",
00090   "servers",
00091   "server_bind_addresses",
00092   NULL
00093 };
00094 
00100 static int lookup_oneofmany(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')
00109     return strtoul(one, NULL, 0);
00110 
00111   idx = 0;
00112   for (;;) {
00113     /* find end of item */
00114     s = many;
00115     while (*s != '|' && *s != 0) s++;
00116     if ((size_t)(s - many) == onelen && !memcmp(one, many, onelen)) return idx;
00117     if (*s == 0) return -1;
00118     many = s + 1;
00119     idx++;
00120   }
00121 }
00122 
00128 static uint32 lookup_manyofmany(const char *many, const char *str)
00129 {
00130   const char *s;
00131   int r;
00132   uint32 res = 0;
00133 
00134   for (;;) {
00135     /* skip "whitespace" */
00136     while (*str == ' ' || *str == '\t' || *str == '|') str++;
00137     if (*str == 0) break;
00138 
00139     s = str;
00140     while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
00141 
00142     r = lookup_oneofmany(many, str, s - str);
00143     if (r == -1) return (uint32)-1;
00144 
00145     SetBit(res, r); // value found, set it
00146     if (*s == 0) break;
00147     str = s + 1;
00148   }
00149   return res;
00150 }
00151 
00158 static int parse_intlist(const char *p, int *items, int maxitems)
00159 {
00160   int n = 0, v;
00161   char *end;
00162 
00163   for (;;) {
00164     v = strtol(p, &end, 0);
00165     if (p == end || n == maxitems) return -1;
00166     p = end;
00167     items[n++] = v;
00168     if (*p == '\0') break;
00169     if (*p != ',' && *p != ' ') return -1;
00170     p++;
00171   }
00172 
00173   return n;
00174 }
00175 
00182 static bool load_intlist(const char *str, void *array, int nelems, VarType type)
00183 {
00184   int items[64];
00185   int i, nitems;
00186 
00187   if (str == NULL) {
00188     memset(items, 0, sizeof(items));
00189     nitems = nelems;
00190   } else {
00191     nitems = parse_intlist(str, items, lengthof(items));
00192     if (nitems != nelems) return false;
00193   }
00194 
00195   switch (type) {
00196   case SLE_VAR_BL:
00197   case SLE_VAR_I8:
00198   case SLE_VAR_U8:
00199     for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
00200     break;
00201   case SLE_VAR_I16:
00202   case SLE_VAR_U16:
00203     for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
00204     break;
00205   case SLE_VAR_I32:
00206   case SLE_VAR_U32:
00207     for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
00208     break;
00209   default: NOT_REACHED();
00210   }
00211 
00212   return true;
00213 }
00214 
00222 static void make_intlist(char *buf, const char *last, const void *array, int nelems, VarType type)
00223 {
00224   int i, v = 0;
00225   byte *p = (byte*)array;
00226 
00227   for (i = 0; i != nelems; i++) {
00228     switch (type) {
00229     case SLE_VAR_BL:
00230     case SLE_VAR_I8:  v = *(int8*)p;   p += 1; break;
00231     case SLE_VAR_U8:  v = *(byte*)p;   p += 1; break;
00232     case SLE_VAR_I16: v = *(int16*)p;  p += 2; break;
00233     case SLE_VAR_U16: v = *(uint16*)p; p += 2; break;
00234     case SLE_VAR_I32: v = *(int32*)p;  p += 4; break;
00235     case SLE_VAR_U32: v = *(uint32*)p; p += 4; break;
00236     default: NOT_REACHED();
00237     }
00238     buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
00239   }
00240 }
00241 
00247 static void make_oneofmany(char *buf, const char *last, const char *many, int id)
00248 {
00249   int orig_id = id;
00250 
00251   /* Look for the id'th element */
00252   while (--id >= 0) {
00253     for (; *many != '|'; many++) {
00254       if (*many == '\0') { // not found
00255         seprintf(buf, last, "%d", orig_id);
00256         return;
00257       }
00258     }
00259     many++; // pass the |-character
00260   }
00261 
00262   /* copy string until next item (|) or the end of the list if this is the last one */
00263   while (*many != '\0' && *many != '|' && buf < last) *buf++ = *many++;
00264   *buf = '\0';
00265 }
00266 
00273 static void make_manyofmany(char *buf, const char *last, const char *many, uint32 x)
00274 {
00275   const char *start;
00276   int i = 0;
00277   bool init = true;
00278 
00279   for (; x != 0; x >>= 1, i++) {
00280     start = many;
00281     while (*many != 0 && *many != '|') many++; // advance to the next element
00282 
00283     if (HasBit(x, 0)) { // item found, copy it
00284       if (!init) buf += seprintf(buf, last, "|");
00285       init = false;
00286       if (start == many) {
00287         buf += seprintf(buf, last, "%d", i);
00288       } else {
00289         memcpy(buf, start, many - start);
00290         buf += many - start;
00291       }
00292     }
00293 
00294     if (*many == '|') many++;
00295   }
00296 
00297   *buf = '\0';
00298 }
00299 
00304 static const void *string_to_val(const SettingDescBase *desc, const char *orig_str)
00305 {
00306   const char *str = orig_str == NULL ? "" : orig_str;
00307   switch (desc->cmd) {
00308   case SDT_NUMX: {
00309     char *end;
00310     unsigned long val = strtoul(str, &end, 0);
00311     if (*end != '\0') ShowInfoF("ini: trailing characters at end of setting '%s'", desc->name);
00312     return (void*)val;
00313   }
00314   case SDT_ONEOFMANY: {
00315     long r = lookup_oneofmany(desc->many, str);
00316     /* if the first attempt of conversion from string to the appropriate value fails,
00317      * look if we have defined a converter from old value to new value. */
00318     if (r == -1 && desc->proc_cnvt != NULL) r = desc->proc_cnvt(str);
00319     if (r != -1) return (void*)r; // and here goes converted value
00320     ShowInfoF("ini: invalid value '%s' for '%s'", str, desc->name); // sorry, we failed
00321     return 0;
00322   }
00323   case SDT_MANYOFMANY: {
00324     unsigned long r = lookup_manyofmany(desc->many, str);
00325     if (r != (unsigned long)-1) return (void*)r;
00326     ShowInfoF("ini: invalid value '%s' for '%s'", str, desc->name);
00327     return 0;
00328   }
00329   case SDT_BOOLX:
00330     if (strcmp(str, "true")  == 0 || strcmp(str, "on")  == 0 || strcmp(str, "1") == 0)
00331       return (void*)true;
00332     if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0)
00333       return (void*)false;
00334     ShowInfoF("ini: invalid setting value '%s' for '%s'", str, desc->name);
00335     break;
00336 
00337   case SDT_STRING: return orig_str;
00338   case SDT_INTLIST: return str;
00339   default: break;
00340   }
00341 
00342   return NULL;
00343 }
00344 
00352 static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
00353 {
00354   const SettingDescBase *sdb = &sd->desc;
00355 
00356   if (sdb->cmd != SDT_BOOLX &&
00357       sdb->cmd != SDT_NUMX &&
00358       sdb->cmd != SDT_ONEOFMANY &&
00359       sdb->cmd != SDT_MANYOFMANY) {
00360     return;
00361   }
00362 
00363   /* We cannot know the maximum value of a bitset variable, so just have faith */
00364   if (sdb->cmd != SDT_MANYOFMANY) {
00365     /* We need to take special care of the uint32 type as we receive from the function
00366      * a signed integer. While here also bail out on 64-bit settings as those are not
00367      * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
00368      * 32-bit variable
00369      * TODO: Support 64-bit settings/variables */
00370     switch (GetVarMemType(sd->save.conv)) {
00371       case SLE_VAR_NULL: return;
00372       case SLE_VAR_BL:
00373       case SLE_VAR_I8:
00374       case SLE_VAR_U8:
00375       case SLE_VAR_I16:
00376       case SLE_VAR_U16:
00377       case SLE_VAR_I32: {
00378         /* Override the minimum value. No value below sdb->min, except special value 0 */
00379         if (!(sdb->flags & SGF_0ISDISABLED) || val != 0) val = Clamp(val, sdb->min, sdb->max);
00380       } break;
00381       case SLE_VAR_U32: {
00382         /* Override the minimum value. No value below sdb->min, except special value 0 */
00383         uint min = ((sdb->flags & SGF_0ISDISABLED) && (uint)val <= (uint)sdb->min) ? 0 : sdb->min;
00384         WriteValue(ptr, SLE_VAR_U32, (int64)ClampU(val, min, sdb->max));
00385         return;
00386       }
00387       case SLE_VAR_I64:
00388       case SLE_VAR_U64:
00389       default: NOT_REACHED();
00390     }
00391   }
00392 
00393   WriteValue(ptr, sd->save.conv, (int64)val);
00394 }
00395 
00402 static void ini_load_settings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
00403 {
00404   IniGroup *group;
00405   IniGroup *group_def = ini->GetGroup(grpname);
00406   IniItem *item;
00407   const void *p;
00408   void *ptr;
00409   const char *s;
00410 
00411   for (; sd->save.cmd != SL_END; sd++) {
00412     const SettingDescBase *sdb = &sd->desc;
00413     const SaveLoad        *sld = &sd->save;
00414 
00415     if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
00416 
00417     /* For settings.xx.yy load the settings from [xx] yy = ? */
00418     s = strchr(sdb->name, '.');
00419     if (s != NULL) {
00420       group = ini->GetGroup(sdb->name, s - sdb->name);
00421       s++;
00422     } else {
00423       s = sdb->name;
00424       group = group_def;
00425     }
00426 
00427     item = group->GetItem(s, false);
00428     if (item == NULL && group != group_def) {
00429       /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
00430        * did not exist (e.g. loading old config files with a [settings] section */
00431       item = group_def->GetItem(s, false);
00432     }
00433     if (item == NULL) {
00434       /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
00435        * did not exist (e.g. loading old config files with a [yapf] section */
00436       const char *sc = strchr(s, '.');
00437       if (sc != NULL) item = ini->GetGroup(s, sc - s)->GetItem(sc + 1, false);
00438     }
00439 
00440     p = (item == NULL) ? sdb->def : string_to_val(sdb, item->value);
00441     ptr = GetVariableAddress(object, sld);
00442 
00443     switch (sdb->cmd) {
00444     case SDT_BOOLX: // All four are various types of (integer) numbers
00445     case SDT_NUMX:
00446     case SDT_ONEOFMANY:
00447     case SDT_MANYOFMANY:
00448       Write_ValidateSetting(ptr, sd, (int32)(size_t)p); break;
00449 
00450     case SDT_STRING:
00451       switch (GetVarMemType(sld->conv)) {
00452         case SLE_VAR_STRB:
00453         case SLE_VAR_STRBQ:
00454           if (p != NULL) ttd_strlcpy((char*)ptr, (const char*)p, sld->length);
00455           break;
00456         case SLE_VAR_STR:
00457         case SLE_VAR_STRQ:
00458           free(*(char**)ptr);
00459           *(char**)ptr = p == NULL ? NULL : strdup((const char*)p);
00460           break;
00461         case SLE_VAR_CHAR: if (p != NULL) *(char*)ptr = *(char*)p; break;
00462         default: NOT_REACHED();
00463       }
00464       break;
00465 
00466     case SDT_INTLIST: {
00467       if (!load_intlist((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) {
00468         ShowInfoF("ini: error in array '%s'", sdb->name);
00469       } else if (sd->desc.proc_cnvt != NULL) {
00470         sd->desc.proc_cnvt((const char*)p);
00471       }
00472       break;
00473     }
00474     default: NOT_REACHED();
00475     }
00476   }
00477 }
00478 
00490 static void ini_save_settings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
00491 {
00492   IniGroup *group_def = NULL, *group;
00493   IniItem *item;
00494   char buf[512];
00495   const char *s;
00496   void *ptr;
00497 
00498   for (; sd->save.cmd != SL_END; sd++) {
00499     const SettingDescBase *sdb = &sd->desc;
00500     const SaveLoad        *sld = &sd->save;
00501 
00502     /* If the setting is not saved to the configuration
00503      * file, just continue with the next setting */
00504     if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
00505     if (sld->conv & SLF_CONFIG_NO) continue;
00506 
00507     /* XXX - wtf is this?? (group override?) */
00508     s = strchr(sdb->name, '.');
00509     if (s != NULL) {
00510       group = ini->GetGroup(sdb->name, s - sdb->name);
00511       s++;
00512     } else {
00513       if (group_def == NULL) group_def = ini->GetGroup(grpname);
00514       s = sdb->name;
00515       group = group_def;
00516     }
00517 
00518     item = group->GetItem(s, true);
00519     ptr = GetVariableAddress(object, sld);
00520 
00521     if (item->value != NULL) {
00522       /* check if the value is the same as the old value */
00523       const void *p = string_to_val(sdb, item->value);
00524 
00525       /* The main type of a variable/setting is in bytes 8-15
00526        * The subtype (what kind of numbers do we have there) is in 0-7 */
00527       switch (sdb->cmd) {
00528       case SDT_BOOLX:
00529       case SDT_NUMX:
00530       case SDT_ONEOFMANY:
00531       case SDT_MANYOFMANY:
00532         switch (GetVarMemType(sld->conv)) {
00533         case SLE_VAR_BL:
00534           if (*(bool*)ptr == (p != NULL)) continue;
00535           break;
00536         case SLE_VAR_I8:
00537         case SLE_VAR_U8:
00538           if (*(byte*)ptr == (byte)(unsigned long)p) continue;
00539           break;
00540         case SLE_VAR_I16:
00541         case SLE_VAR_U16:
00542           if (*(uint16*)ptr == (uint16)(unsigned long)p) continue;
00543           break;
00544         case SLE_VAR_I32:
00545         case SLE_VAR_U32:
00546           if (*(uint32*)ptr == (uint32)(unsigned long)p) continue;
00547           break;
00548         default: NOT_REACHED();
00549         }
00550         break;
00551       default: break; // Assume the other types are always changed
00552       }
00553     }
00554 
00555     /* Value has changed, get the new value and put it into a buffer */
00556     switch (sdb->cmd) {
00557     case SDT_BOOLX:
00558     case SDT_NUMX:
00559     case SDT_ONEOFMANY:
00560     case SDT_MANYOFMANY: {
00561       uint32 i = (uint32)ReadValue(ptr, sld->conv);
00562 
00563       switch (sdb->cmd) {
00564       case SDT_BOOLX:      strecpy(buf, (i != 0) ? "true" : "false", lastof(buf)); break;
00565       case SDT_NUMX:       seprintf(buf, lastof(buf), IsSignedVarMemType(sld->conv) ? "%d" : "%u", i); break;
00566       case SDT_ONEOFMANY:  make_oneofmany(buf, lastof(buf), sdb->many, i); break;
00567       case SDT_MANYOFMANY: make_manyofmany(buf, lastof(buf), sdb->many, i); break;
00568       default: NOT_REACHED();
00569       }
00570     } break;
00571 
00572     case SDT_STRING:
00573       switch (GetVarMemType(sld->conv)) {
00574       case SLE_VAR_STRB: strecpy(buf, (char*)ptr, lastof(buf)); break;
00575       case SLE_VAR_STRBQ:seprintf(buf, lastof(buf), "\"%s\"", (char*)ptr); break;
00576       case SLE_VAR_STR:  strecpy(buf, *(char**)ptr, lastof(buf)); break;
00577       case SLE_VAR_STRQ:
00578         if (*(char**)ptr == NULL) {
00579           buf[0] = '\0';
00580         } else {
00581           seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
00582         }
00583         break;
00584       case SLE_VAR_CHAR: buf[0] = *(char*)ptr; buf[1] = '\0'; break;
00585       default: NOT_REACHED();
00586       }
00587       break;
00588 
00589     case SDT_INTLIST:
00590       make_intlist(buf, lastof(buf), ptr, sld->length, GetVarMemType(sld->conv));
00591       break;
00592     default: NOT_REACHED();
00593     }
00594 
00595     /* The value is different, that means we have to write it to the ini */
00596     free(item->value);
00597     item->value = strdup(buf);
00598   }
00599 }
00600 
00609 static void ini_load_setting_list(IniFile *ini, const char *grpname, StringList *list)
00610 {
00611   IniGroup *group = ini->GetGroup(grpname);
00612 
00613   if (group == NULL || list == NULL) return;
00614 
00615   list->Clear();
00616 
00617   for (const IniItem *item = group->item; item != NULL; item = item->next) {
00618     if (item->name != NULL) *list->Append() = strdup(item->name);
00619   }
00620 }
00621 
00630 static void ini_save_setting_list(IniFile *ini, const char *grpname, StringList *list)
00631 {
00632   IniGroup *group = ini->GetGroup(grpname);
00633 
00634   if (group == NULL || list == NULL) return;
00635   group->Clear();
00636 
00637   for (char **iter = list->Begin(); iter != list->End(); iter++) {
00638     group->GetItem(*iter, true)->SetValue("");
00639   }
00640 }
00641 
00642 /* Begin - Callback Functions for the various settings
00643  * virtual PositionMainToolbar function, calls the right one.*/
00644 static bool v_PositionMainToolbar(int32 p1)
00645 {
00646   if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
00647   return true;
00648 }
00649 
00650 static bool PopulationInLabelActive(int32 p1)
00651 {
00652   UpdateAllTownVirtCoords();
00653   return true;
00654 }
00655 
00656 static bool RedrawScreen(int32 p1)
00657 {
00658   MarkWholeScreenDirty();
00659   return true;
00660 }
00661 
00667 static bool RedrawSmallmap(int32 p1)
00668 {
00669   BuildLandLegend();
00670   SetWindowClassesDirty(WC_SMALLMAP);
00671   return true;
00672 }
00673 
00674 static bool InvalidateDetailsWindow(int32 p1)
00675 {
00676   SetWindowClassesDirty(WC_VEHICLE_DETAILS);
00677   return true;
00678 }
00679 
00680 static bool InvalidateStationBuildWindow(int32 p1)
00681 {
00682   SetWindowDirty(WC_BUILD_STATION, 0);
00683   return true;
00684 }
00685 
00686 static bool InvalidateBuildIndustryWindow(int32 p1)
00687 {
00688   InvalidateWindowData(WC_BUILD_INDUSTRY, 0);
00689   return true;
00690 }
00691 
00692 static bool CloseSignalGUI(int32 p1)
00693 {
00694   if (p1 == 0) {
00695     DeleteWindowByClass(WC_BUILD_SIGNAL);
00696   }
00697   return true;
00698 }
00699 
00700 static bool InvalidateTownViewWindow(int32 p1)
00701 {
00702   InvalidateWindowClassesData(WC_TOWN_VIEW, p1);
00703   return true;
00704 }
00705 
00706 static bool DeleteSelectStationWindow(int32 p1)
00707 {
00708   DeleteWindowById(WC_SELECT_STATION, 0);
00709   return true;
00710 }
00711 
00712 static bool UpdateConsists(int32 p1)
00713 {
00714   Train *t;
00715   FOR_ALL_TRAINS(t) {
00716     /* Update the consist of all trains so the maximum speed is set correctly. */
00717     if (t->IsFrontEngine() || t->IsFreeWagon()) t->ConsistChanged(true);
00718   }
00719   return true;
00720 }
00721 
00722 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
00723 static bool CheckInterval(int32 p1)
00724 {
00725   VehicleDefaultSettings *vds;
00726   if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
00727     vds = &_settings_client.company.vehicle;
00728   } else {
00729     vds = &Company::Get(_current_company)->settings.vehicle;
00730   }
00731 
00732   if (p1) {
00733     vds->servint_trains   = 50;
00734     vds->servint_roadveh  = 50;
00735     vds->servint_aircraft = 50;
00736     vds->servint_ships    = 50;
00737   } else {
00738     vds->servint_trains   = 150;
00739     vds->servint_roadveh  = 150;
00740     vds->servint_aircraft = 360;
00741     vds->servint_ships    = 100;
00742   }
00743 
00744   InvalidateDetailsWindow(0);
00745 
00746   return true;
00747 }
00748 
00749 static bool TrainAccelerationModelChanged(int32 p1)
00750 {
00751   Train *t;
00752   FOR_ALL_TRAINS(t) {
00753     if (t->IsFrontEngine()) {
00754       t->tcache.cached_max_curve_speed = t->GetCurveSpeedLimit();
00755       t->UpdateAcceleration();
00756     }
00757   }
00758 
00759   return true;
00760 }
00761 
00767 static bool TrainSlopeSteepnessChanged(int32 p1)
00768 {
00769   Train *t;
00770   FOR_ALL_TRAINS(t) {
00771     if (t->IsFrontEngine()) t->CargoChanged();
00772   }
00773 
00774   return true;
00775 }
00776 
00777 static bool DragSignalsDensityChanged(int32)
00778 {
00779   InvalidateWindowData(WC_BUILD_SIGNAL, 0);
00780 
00781   return true;
00782 }
00783 
00784 static bool TownFoundingChanged(int32 p1)
00785 {
00786   if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
00787     DeleteWindowById(WC_FOUND_TOWN, 0);
00788     return true;
00789   }
00790   InvalidateWindowData(WC_FOUND_TOWN, 0);
00791   return true;
00792 }
00793 
00794 static bool InvalidateVehTimetableWindow(int32 p1)
00795 {
00796   InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE, -2);
00797   return true;
00798 }
00799 
00800 /*
00801  * A: competitors
00802  * B: competitor start time. Deprecated since savegame version 110.
00803  * C: town count (3 = high, 0 = very low)
00804  * D: industry count (4 = high, 0 = none)
00805  * E: inital loan (in GBP)
00806  * F: interest rate
00807  * G: running costs (0 = low, 2 = high)
00808  * H: construction speed of competitors (0 = very slow, 4 = very fast)
00809  * I: competitor intelligence. Deprecated since savegame version 110.
00810  * J: breakdowns (0 = off, 2 = normal)
00811  * K: subsidy multiplier (0 = 1.5, 3 = 4.0)
00812  * L: construction cost (0-2)
00813  * M: terrain type (0 = very flat, 3 = mountainous)
00814  * N: amount of water (0 = very low, 3 = high)
00815  * O: economy (0 = steady, 1 = fluctuating)
00816  * P: Train reversing (0 = end of line + stations, 1 = end of line)
00817  * Q: disasters
00818  * R: area restructuring (0 = permissive, 2 = hostile)
00819  * S: the difficulty level
00820  */
00821 static const DifficultySettings _default_game_diff[3] = { /*
00822    A, C, D,      E, F, G, H, J, K, L, M, N, O, P, Q, R, S*/
00823   {2, 2, 4, 300000, 2, 0, 2, 1, 2, 0, 1, 0, 0, 0, 0, 0, 0}, 
00824   {4, 2, 3, 150000, 3, 1, 3, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1}, 
00825   {7, 3, 3, 100000, 4, 1, 3, 2, 0, 2, 3, 2, 1, 1, 1, 2, 2}, 
00826 };
00827 
00828 void SetDifficultyLevel(int mode, DifficultySettings *gm_opt)
00829 {
00830   assert(mode <= 3);
00831 
00832   if (mode != 3) {
00833     *gm_opt = _default_game_diff[mode];
00834   } else {
00835     gm_opt->diff_level = 3;
00836   }
00837 }
00838 
00843 static void CheckDifficultyLevels()
00844 {
00845   if (_settings_newgame.difficulty.diff_level != 3) {
00846     SetDifficultyLevel(_settings_newgame.difficulty.diff_level, &_settings_newgame.difficulty);
00847   }
00848 }
00849 
00850 static bool DifficultyReset(int32 level)
00851 {
00852   SetDifficultyLevel(level, (_game_mode == GM_MENU) ? &_settings_newgame.difficulty : &_settings_game.difficulty);
00853   return true;
00854 }
00855 
00856 static bool DifficultyChange(int32)
00857 {
00858   if (_game_mode == GM_MENU) {
00859     if (_settings_newgame.difficulty.diff_level != 3) {
00860       ShowErrorMessage(STR_WARNING_DIFFICULTY_TO_CUSTOM, INVALID_STRING_ID, 0, 0);
00861       _settings_newgame.difficulty.diff_level = 3;
00862     }
00863     SetWindowClassesDirty(WC_SELECT_GAME);
00864   } else {
00865     _settings_game.difficulty.diff_level = 3;
00866   }
00867 
00868   /* If we are a network-client, update the difficult setting (if it is open).
00869    * Use this instead of just dirtying the window because we need to load in
00870    * the new difficulty settings */
00871   if (_networking && FindWindowById(WC_GAME_OPTIONS, 0) != NULL) {
00872     ShowGameDifficulty();
00873   }
00874 
00875   return true;
00876 }
00877 
00878 static bool DifficultyNoiseChange(int32 i)
00879 {
00880   if (_game_mode == GM_NORMAL) {
00881     UpdateAirportsNoise();
00882     if (_settings_game.economy.station_noise_level) {
00883       InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
00884     }
00885   }
00886 
00887   return DifficultyChange(i);
00888 }
00889 
00890 static bool MaxNoAIsChange(int32 i)
00891 {
00892   if (((_game_mode == GM_MENU) ? _settings_newgame.difficulty : _settings_game.difficulty).max_no_competitors != 0 &&
00893 #ifdef ENABLE_AI
00894       AI::GetInfoList()->size() == 0 &&
00895 #endif /* ENABLE_AI */
00896       (!_networking || _network_server)) {
00897     ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, 0, 0, true);
00898   }
00899 
00900   return DifficultyChange(i);
00901 }
00902 
00908 static bool CheckRoadSide(int p1)
00909 {
00910   extern bool RoadVehiclesAreBuilt();
00911   return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
00912 }
00913 
00920 static int32 ConvertLandscape(const char *value)
00921 {
00922   /* try with the old values */
00923   return lookup_oneofmany("normal|hilly|desert|candy", value);
00924 }
00925 
00926 static bool CheckFreeformEdges(int32 p1)
00927 {
00928   if (_game_mode == GM_MENU) return true;
00929   if (p1 != 0) {
00930     Ship *s;
00931     FOR_ALL_SHIPS(s) {
00932       if (TileX(s->tile) == 0 || TileY(s->tile) == 0) {
00933         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, 0, 0);
00934         return false;
00935       }
00936     }
00937     Station *st;
00938     FOR_ALL_STATIONS(st) {
00939       if (TileX(st->xy) == 0 || TileY(st->xy) == 0) {
00940         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, 0, 0);
00941         return false;
00942       }
00943     }
00944     for (uint i = 0; i < MapSizeX(); i++) MakeVoid(TileXY(i, 0));
00945     for (uint i = 0; i < MapSizeY(); i++) MakeVoid(TileXY(0, i));
00946   } else {
00947     for (uint i = 0; i < MapMaxX(); i++) {
00948       if (TileHeight(TileXY(i, 1)) != 0) {
00949         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, 0, 0);
00950         return false;
00951       }
00952     }
00953     for (uint i = 1; i < MapMaxX(); i++) {
00954       if (!IsTileType(TileXY(i, MapMaxY() - 1), MP_WATER) || TileHeight(TileXY(1, MapMaxY())) != 0) {
00955         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, 0, 0);
00956         return false;
00957       }
00958     }
00959     for (uint i = 0; i < MapMaxY(); i++) {
00960       if (TileHeight(TileXY(1, i)) != 0) {
00961         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, 0, 0);
00962         return false;
00963       }
00964     }
00965     for (uint i = 1; i < MapMaxY(); i++) {
00966       if (!IsTileType(TileXY(MapMaxX() - 1, i), MP_WATER) || TileHeight(TileXY(MapMaxX(), i)) != 0) {
00967         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, 0, 0);
00968         return false;
00969       }
00970     }
00971     /* Make tiles at the border water again. */
00972     for (uint i = 0; i < MapMaxX(); i++) {
00973       SetTileHeight(TileXY(i, 0), 0);
00974       SetTileType(TileXY(i, 0), MP_WATER);
00975     }
00976     for (uint i = 0; i < MapMaxY(); i++) {
00977       SetTileHeight(TileXY(0, i), 0);
00978       SetTileType(TileXY(0, i), MP_WATER);
00979     }
00980   }
00981   MarkWholeScreenDirty();
00982   return true;
00983 }
00984 
00989 static bool ChangeDynamicEngines(int32 p1)
00990 {
00991   if (_game_mode == GM_MENU) return true;
00992 
00993   const Vehicle *v;
00994   FOR_ALL_VEHICLES(v) {
00995     if (IsCompanyBuildableVehicleType(v)) {
00996       ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, 0, 0);
00997       return false;
00998     }
00999   }
01000 
01001   /* Reset the engines, they will get new EngineIDs */
01002   _engine_mngr.ResetToDefaultMapping();
01003   ReloadNewGRFData();
01004 
01005   return true;
01006 }
01007 
01008 static bool StationCatchmentChanged(int32 p1)
01009 {
01010   Station::RecomputeIndustriesNearForAll();
01011   return true;
01012 }
01013 
01014 #ifdef ENABLE_NETWORK
01015 
01016 static bool UpdateClientName(int32 p1)
01017 {
01018   NetworkUpdateClientName();
01019   return true;
01020 }
01021 
01022 static bool UpdateServerPassword(int32 p1)
01023 {
01024   if (strcmp(_settings_client.network.server_password, "*") == 0) {
01025     _settings_client.network.server_password[0] = '\0';
01026   }
01027 
01028   return true;
01029 }
01030 
01031 static bool UpdateRconPassword(int32 p1)
01032 {
01033   if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
01034     _settings_client.network.rcon_password[0] = '\0';
01035   }
01036 
01037   return true;
01038 }
01039 
01040 static bool UpdateClientConfigValues(int32 p1)
01041 {
01042   if (_network_server) NetworkServerSendConfigUpdate();
01043 
01044   return true;
01045 }
01046 
01047 #endif /* ENABLE_NETWORK */
01048 
01049 
01050 /* End - Callback Functions */
01051 
01055 static void PrepareOldDiffCustom()
01056 {
01057   memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
01058 }
01059 
01066 static void HandleOldDiffCustom(bool savegame)
01067 {
01068   uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && CheckSavegameVersion(4)) ? 1 : 0);
01069 
01070   if (!savegame) {
01071     /* If we did read to old_diff_custom, then at least one value must be non 0. */
01072     bool old_diff_custom_used = false;
01073     for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
01074       old_diff_custom_used = (_old_diff_custom[i] != 0);
01075     }
01076 
01077     if (!old_diff_custom_used) return;
01078   }
01079 
01080   for (uint i = 0; i < options_to_load; i++) {
01081     const SettingDesc *sd = &_settings[i];
01082     /* Skip deprecated options */
01083     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01084     void *var = GetVariableAddress(savegame ? &_settings_game : &_settings_newgame, &sd->save);
01085     Write_ValidateSetting(var, sd, (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]));
01086   }
01087 }
01088 
01093 static bool ConvertOldNewsSetting(const char *name, const char *value)
01094 {
01095   if (strcasecmp(name, "openclose") == 0) {
01096     /* openclose has been split in "open" and "close".
01097      * So the job is now to decrypt the value of the old news config
01098      * and give it to the two newly introduced ones*/
01099 
01100     NewsDisplay display = ND_OFF; // default
01101     if (strcasecmp(value, "full") == 0) {
01102       display = ND_FULL;
01103     } else if (strcasecmp(value, "summarized") == 0) {
01104       display = ND_SUMMARY;
01105     }
01106     /* tranfert of values */
01107     _news_type_data[NT_INDUSTRY_OPEN].display = display;
01108     _news_type_data[NT_INDUSTRY_CLOSE].display = display;
01109     return true;
01110   }
01111   return false;
01112 }
01113 
01114 static void NewsDisplayLoadConfig(IniFile *ini, const char *grpname)
01115 {
01116   IniGroup *group = ini->GetGroup(grpname);
01117   IniItem *item;
01118 
01119   /* If no group exists, return */
01120   if (group == NULL) return;
01121 
01122   for (item = group->item; item != NULL; item = item->next) {
01123     int news_item = -1;
01124     for (int i = 0; i < NT_END; i++) {
01125       if (strcasecmp(item->name, _news_type_data[i].name) == 0) {
01126         news_item = i;
01127         break;
01128       }
01129     }
01130 
01131     /* the config been read is not within current aceptable config */
01132     if (news_item == -1) {
01133       /* if the conversion function cannot process it, advice by a debug warning*/
01134       if (!ConvertOldNewsSetting(item->name, item->value)) {
01135         DEBUG(misc, 0, "Invalid display option: %s", item->name);
01136       }
01137       /* in all cases, there is nothing left to do */
01138       continue;
01139     }
01140 
01141     if (StrEmpty(item->value)) {
01142       DEBUG(misc, 0, "Empty display value for newstype %s", item->name);
01143       continue;
01144     } else if (strcasecmp(item->value, "full") == 0) {
01145       _news_type_data[news_item].display = ND_FULL;
01146     } else if (strcasecmp(item->value, "off") == 0) {
01147       _news_type_data[news_item].display = ND_OFF;
01148     } else if (strcasecmp(item->value, "summarized") == 0) {
01149       _news_type_data[news_item].display = ND_SUMMARY;
01150     } else {
01151       DEBUG(misc, 0, "Invalid display value for newstype %s: %s", item->name, item->value);
01152       continue;
01153     }
01154   }
01155 }
01156 
01157 static void AILoadConfig(IniFile *ini, const char *grpname)
01158 {
01159 #ifdef ENABLE_AI
01160   IniGroup *group = ini->GetGroup(grpname);
01161   IniItem *item;
01162 
01163   /* Clean any configured AI */
01164   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
01165     AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME)->ChangeAI(NULL);
01166   }
01167 
01168   /* If no group exists, return */
01169   if (group == NULL) return;
01170 
01171   CompanyID c = COMPANY_FIRST;
01172   for (item = group->item; c < MAX_COMPANIES && item != NULL; c++, item = item->next) {
01173     AIConfig *config = AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME);
01174 
01175     config->ChangeAI(item->name);
01176     if (!config->HasAI()) {
01177       if (strcmp(item->name, "none") != 0) {
01178         DEBUG(ai, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item->name);
01179         continue;
01180       }
01181     }
01182     if (item->value != NULL) config->StringToSettings(item->value);
01183   }
01184 #endif /* ENABLE_AI */
01185 }
01186 
01187 /* Load a GRF configuration from the given group name */
01188 static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
01189 {
01190   IniGroup *group = ini->GetGroup(grpname);
01191   IniItem *item;
01192   GRFConfig *first = NULL;
01193   GRFConfig **curr = &first;
01194 
01195   if (group == NULL) return NULL;
01196 
01197   for (item = group->item; item != NULL; item = item->next) {
01198     GRFConfig *c = CallocT<GRFConfig>(1);
01199     c->filename = strdup(item->name);
01200 
01201     /* Parse parameters */
01202     if (!StrEmpty(item->value)) {
01203       c->num_params = parse_intlist(item->value, (int*)c->param, lengthof(c->param));
01204       if (c->num_params == (byte)-1) {
01205         ShowInfoF("ini: error in array '%s'", item->name);
01206         c->num_params = 0;
01207       }
01208     }
01209 
01210     /* Check if item is valid */
01211     if (!FillGRFDetails(c, is_static)) {
01212       const char *msg;
01213 
01214       if (c->status == GCS_NOT_FOUND) {
01215         msg = "not found";
01216       } else if (HasBit(c->flags, GCF_UNSAFE)) {
01217         msg = "unsafe for static use";
01218       } else if (HasBit(c->flags, GCF_SYSTEM)) {
01219         msg = "system NewGRF";
01220       } else {
01221         msg = "unknown";
01222       }
01223 
01224       ShowInfoF("ini: ignoring invalid NewGRF '%s': %s", item->name, msg);
01225       ClearGRFConfig(&c);
01226       continue;
01227     }
01228 
01229     /* Check for duplicate GRFID (will also check for duplicate filenames) */
01230     bool duplicate = false;
01231     for (const GRFConfig *gc = first; gc != NULL; gc = gc->next) {
01232       if (gc->grfid == c->grfid) {
01233         ShowInfoF("ini: ignoring  NewGRF '%s': duplicate GRF ID with '%s'", item->name, gc->filename);
01234         duplicate = true;
01235         break;
01236       }
01237     }
01238     if (duplicate) {
01239       ClearGRFConfig(&c);
01240       continue;
01241     }
01242 
01243     /* Mark file as static to avoid saving in savegame. */
01244     if (is_static) SetBit(c->flags, GCF_STATIC);
01245 
01246     /* Add item to list */
01247     *curr = c;
01248     curr = &c->next;
01249   }
01250 
01251   return first;
01252 }
01253 
01254 static void NewsDisplaySaveConfig(IniFile *ini, const char *grpname)
01255 {
01256   IniGroup *group = ini->GetGroup(grpname);
01257 
01258   for (int i = 0; i < NT_END; i++) {
01259     const char *value;
01260     int v = _news_type_data[i].display;
01261 
01262     value = (v == ND_OFF ? "off" : (v == ND_SUMMARY ? "summarized" : "full"));
01263 
01264     group->GetItem(_news_type_data[i].name, true)->SetValue(value);
01265   }
01266 }
01267 
01268 static void AISaveConfig(IniFile *ini, const char *grpname)
01269 {
01270 #ifdef ENABLE_AI
01271   IniGroup *group = ini->GetGroup(grpname);
01272 
01273   if (group == NULL) return;
01274   group->Clear();
01275 
01276   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
01277     AIConfig *config = AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME);
01278     const char *name;
01279     char value[1024];
01280     config->SettingsToString(value, lengthof(value));
01281 
01282     if (config->HasAI()) {
01283       name = config->GetName();
01284     } else {
01285       name = "none";
01286     }
01287 
01288     IniItem *item = new IniItem(group, name, strlen(name));
01289     item->SetValue(value);
01290   }
01291 #endif /* ENABLE_AI */
01292 }
01293 
01298 static void SaveVersionInConfig(IniFile *ini)
01299 {
01300   IniGroup *group = ini->GetGroup("version");
01301 
01302   char version[9];
01303   snprintf(version, lengthof(version), "%08X", _openttd_newgrf_version);
01304 
01305   const char * const versions[][2] = {
01306     { "version_string", _openttd_revision },
01307     { "version_number", version }
01308   };
01309 
01310   for (uint i = 0; i < lengthof(versions); i++) {
01311     group->GetItem(versions[i][0], true)->SetValue(versions[i][1]);
01312   }
01313 }
01314 
01315 /* Save a GRF configuration to the given group name */
01316 static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
01317 {
01318   ini->RemoveGroup(grpname);
01319   IniGroup *group = ini->GetGroup(grpname);
01320   const GRFConfig *c;
01321 
01322   for (c = list; c != NULL; c = c->next) {
01323     char params[512];
01324     GRFBuildParamList(params, c, lastof(params));
01325 
01326     group->GetItem(c->filename, true)->SetValue(params);
01327   }
01328 }
01329 
01330 /* Common handler for saving/loading variables to the configuration file */
01331 static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list)
01332 {
01333   proc(ini, (const SettingDesc*)_misc_settings,    "misc",  NULL);
01334   proc(ini, (const SettingDesc*)_music_settings,   "music", &msf);
01335 #if defined(WIN32) && !defined(DEDICATED)
01336   proc(ini, (const SettingDesc*)_win32_settings,   "win32", NULL);
01337 #endif /* WIN32 */
01338 
01339   proc(ini, _settings,         "patches",  &_settings_newgame);
01340   proc(ini, _currency_settings,"currency", &_custom_currency);
01341   proc(ini, _company_settings, "company",  &_settings_client.company);
01342 
01343 #ifdef ENABLE_NETWORK
01344   proc_list(ini, "server_bind_addresses", &_network_bind_list);
01345   proc_list(ini, "servers", &_network_host_list);
01346   proc_list(ini, "bans",    &_network_ban_list);
01347 #endif /* ENABLE_NETWORK */
01348 }
01349 
01350 static IniFile *IniLoadConfig()
01351 {
01352   IniFile *ini = new IniFile(_list_group_names);
01353   ini->LoadFromDisk(_config_file);
01354   return ini;
01355 }
01356 
01358 void LoadFromConfig()
01359 {
01360   IniFile *ini = IniLoadConfig();
01361   ResetCurrencies(false); // Initialize the array of curencies, without preserving the custom one
01362 
01363   HandleSettingDescs(ini, ini_load_settings, ini_load_setting_list);
01364   _grfconfig_newgame = GRFLoadConfig(ini, "newgrf", false);
01365   _grfconfig_static  = GRFLoadConfig(ini, "newgrf-static", true);
01366   NewsDisplayLoadConfig(ini, "news_display");
01367   AILoadConfig(ini, "ai_players");
01368 
01369   PrepareOldDiffCustom();
01370   ini_load_settings(ini, _gameopt_settings, "gameopt",  &_settings_newgame);
01371   HandleOldDiffCustom(false);
01372 
01373   CheckDifficultyLevels();
01374   delete ini;
01375 }
01376 
01378 void SaveToConfig()
01379 {
01380   IniFile *ini = IniLoadConfig();
01381 
01382   /* Remove some obsolete groups. These have all been loaded into other groups. */
01383   ini->RemoveGroup("patches");
01384   ini->RemoveGroup("yapf");
01385   ini->RemoveGroup("gameopt");
01386 
01387   HandleSettingDescs(ini, ini_save_settings, ini_save_setting_list);
01388   GRFSaveConfig(ini, "newgrf", _grfconfig_newgame);
01389   GRFSaveConfig(ini, "newgrf-static", _grfconfig_static);
01390   NewsDisplaySaveConfig(ini, "news_display");
01391   AISaveConfig(ini, "ai_players");
01392   SaveVersionInConfig(ini);
01393   ini->SaveToDisk(_config_file);
01394   delete ini;
01395 }
01396 
01397 void GetGRFPresetList(GRFPresetList *list)
01398 {
01399   list->Clear();
01400 
01401   IniFile *ini = IniLoadConfig();
01402   IniGroup *group;
01403   for (group = ini->group; group != NULL; group = group->next) {
01404     if (strncmp(group->name, "preset-", 7) == 0) {
01405       *list->Append() = strdup(group->name + 7);
01406     }
01407   }
01408 
01409   delete ini;
01410 }
01411 
01412 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
01413 {
01414   char *section = (char*)alloca(strlen(config_name) + 8);
01415   sprintf(section, "preset-%s", config_name);
01416 
01417   IniFile *ini = IniLoadConfig();
01418   GRFConfig *config = GRFLoadConfig(ini, section, false);
01419   delete ini;
01420 
01421   return config;
01422 }
01423 
01424 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
01425 {
01426   char *section = (char*)alloca(strlen(config_name) + 8);
01427   sprintf(section, "preset-%s", config_name);
01428 
01429   IniFile *ini = IniLoadConfig();
01430   GRFSaveConfig(ini, section, config);
01431   ini->SaveToDisk(_config_file);
01432   delete ini;
01433 }
01434 
01435 void DeleteGRFPresetFromConfig(const char *config_name)
01436 {
01437   char *section = (char*)alloca(strlen(config_name) + 8);
01438   sprintf(section, "preset-%s", config_name);
01439 
01440   IniFile *ini = IniLoadConfig();
01441   ini->RemoveGroup(section);
01442   ini->SaveToDisk(_config_file);
01443   delete ini;
01444 }
01445 
01446 static const SettingDesc *GetSettingDescription(uint index)
01447 {
01448   if (index >= lengthof(_settings)) return NULL;
01449   return &_settings[index];
01450 }
01451 
01462 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01463 {
01464   const SettingDesc *sd = GetSettingDescription(p1);
01465 
01466   if (sd == NULL) return CMD_ERROR;
01467   if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
01468 
01469   if ((sd->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return CMD_ERROR;
01470   if ((sd->desc.flags & SGF_NO_NETWORK) && _networking) return CMD_ERROR;
01471   if ((sd->desc.flags & SGF_NEWGAME_ONLY) &&
01472       (_game_mode == GM_NORMAL ||
01473       (_game_mode == GM_EDITOR && (sd->desc.flags & SGF_SCENEDIT_TOO) == 0))) {
01474     return CMD_ERROR;
01475   }
01476 
01477   if (flags & DC_EXEC) {
01478     GameSettings *s = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;
01479     void *var = GetVariableAddress(s, &sd->save);
01480 
01481     int32 oldval = (int32)ReadValue(var, sd->save.conv);
01482     int32 newval = (int32)p2;
01483 
01484     Write_ValidateSetting(var, sd, newval);
01485     newval = (int32)ReadValue(var, sd->save.conv);
01486 
01487     if (oldval == newval) return CommandCost();
01488 
01489     if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
01490       WriteValue(var, sd->save.conv, (int64)oldval);
01491       return CommandCost();
01492     }
01493 
01494     if (sd->desc.flags & SGF_NO_NETWORK) {
01495       GamelogStartAction(GLAT_SETTING);
01496       GamelogSetting(sd->desc.name, oldval, newval);
01497       GamelogStopAction();
01498     }
01499 
01500     SetWindowDirty(WC_GAME_OPTIONS, 0);
01501   }
01502 
01503   return CommandCost();
01504 }
01505 
01515 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01516 {
01517   if (p1 >= lengthof(_company_settings)) return CMD_ERROR;
01518   const SettingDesc *sd = &_company_settings[p1];
01519 
01520   if (flags & DC_EXEC) {
01521     void *var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
01522 
01523     int32 oldval = (int32)ReadValue(var, sd->save.conv);
01524     int32 newval = (int32)p2;
01525 
01526     Write_ValidateSetting(var, sd, newval);
01527     newval = (int32)ReadValue(var, sd->save.conv);
01528 
01529     if (oldval == newval) return CommandCost();
01530 
01531     if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
01532       WriteValue(var, sd->save.conv, (int64)oldval);
01533       return CommandCost();
01534     }
01535 
01536     SetWindowDirty(WC_GAME_OPTIONS, 0);
01537   }
01538 
01539   return CommandCost();
01540 }
01541 
01548 bool SetSettingValue(uint index, int32 value, bool force_newgame)
01549 {
01550   const SettingDesc *sd = &_settings[index];
01551   /* If an item is company-based, we do not send it over the network
01552    * (if any) to change. Also *hack*hack* we update the _newgame version
01553    * of settings because changing a company-based setting in a game also
01554    * changes its defaults. At least that is the convention we have chosen */
01555   if (sd->save.conv & SLF_NETWORK_NO) {
01556     void *var = GetVariableAddress((_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game, &sd->save);
01557     Write_ValidateSetting(var, sd, value);
01558 
01559     if (_game_mode != GM_MENU) {
01560       void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
01561       Write_ValidateSetting(var2, sd, value);
01562     }
01563     if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
01564     SetWindowDirty(WC_GAME_OPTIONS, 0);
01565     return true;
01566   }
01567 
01568   if (force_newgame) {
01569     void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
01570     Write_ValidateSetting(var2, sd, value);
01571     return true;
01572   }
01573 
01574   /* send non-company-based settings over the network */
01575   if (!_networking || (_networking && _network_server)) {
01576     return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
01577   }
01578   return false;
01579 }
01580 
01586 void SetCompanySetting(uint index, int32 value)
01587 {
01588   const SettingDesc *sd = &_company_settings[index];
01589   if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
01590     DoCommandP(0, index, value, CMD_CHANGE_COMPANY_SETTING);
01591   } else {
01592     void *var = GetVariableAddress(&_settings_client.company, &sd->save);
01593     Write_ValidateSetting(var, sd, value);
01594     if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
01595   }
01596 }
01597 
01601 void SetDefaultCompanySettings(CompanyID cid)
01602 {
01603   Company *c = Company::Get(cid);
01604   const SettingDesc *sd;
01605   for (sd = _company_settings; sd->save.cmd != SL_END; sd++) {
01606     void *var = GetVariableAddress(&c->settings, &sd->save);
01607     Write_ValidateSetting(var, sd, (int32)(size_t)sd->desc.def);
01608   }
01609 }
01610 
01611 #if defined(ENABLE_NETWORK)
01612 
01615 void SyncCompanySettings()
01616 {
01617   const SettingDesc *sd;
01618   uint i = 0;
01619   for (sd = _company_settings; sd->save.cmd != SL_END; sd++, i++) {
01620     const void *old_var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
01621     const void *new_var = GetVariableAddress(&_settings_client.company, &sd->save);
01622     uint32 old_value = (uint32)ReadValue(old_var, sd->save.conv);
01623     uint32 new_value = (uint32)ReadValue(new_var, sd->save.conv);
01624     if (old_value != new_value) NetworkSend_Command(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, NULL, NULL, _local_company);
01625   }
01626 }
01627 #endif /* ENABLE_NETWORK */
01628 
01634 uint GetCompanySettingIndex(const char *name)
01635 {
01636   uint i;
01637   const SettingDesc *sd = GetSettingFromName(name, &i);
01638   assert(sd != NULL && (sd->desc.flags & SGF_PER_COMPANY) != 0);
01639   return i;
01640 }
01641 
01649 bool SetSettingValue(uint index, const char *value, bool force_newgame)
01650 {
01651   const SettingDesc *sd = &_settings[index];
01652   assert(sd->save.conv & SLF_NETWORK_NO);
01653 
01654   if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
01655     char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
01656     free(*var);
01657     *var = strcmp(value, "(null)") == 0 ? NULL : strdup(value);
01658   } else {
01659     char *var = (char*)GetVariableAddress(NULL, &sd->save);
01660     ttd_strlcpy(var, value, sd->save.length);
01661   }
01662   if (sd->desc.proc != NULL) sd->desc.proc(0);
01663 
01664   return true;
01665 }
01666 
01674 const SettingDesc *GetSettingFromName(const char *name, uint *i)
01675 {
01676   const SettingDesc *sd;
01677 
01678   /* First check all full names */
01679   for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01680     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01681     if (strcmp(sd->desc.name, name) == 0) return sd;
01682   }
01683 
01684   /* Then check the shortcut variant of the name. */
01685   for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01686     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01687     const char *short_name = strchr(sd->desc.name, '.');
01688     if (short_name != NULL) {
01689       short_name++;
01690       if (strcmp(short_name, name) == 0) return sd;
01691     }
01692   }
01693 
01694   if (strncmp(name, "company.", 8) == 0) name += 8;
01695   /* And finally the company-based settings */
01696   for (*i = 0, sd = _company_settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01697     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01698     if (strcmp(sd->desc.name, name) == 0) return sd;
01699   }
01700 
01701   return NULL;
01702 }
01703 
01704 /* Those 2 functions need to be here, else we have to make some stuff non-static
01705  * and besides, it is also better to keep stuff like this at the same place */
01706 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
01707 {
01708   uint index;
01709   const SettingDesc *sd = GetSettingFromName(name, &index);
01710 
01711   if (sd == NULL) {
01712     IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
01713     return;
01714   }
01715 
01716   bool success;
01717   if (sd->desc.cmd == SDT_STRING) {
01718     success = SetSettingValue(index, value, force_newgame);
01719   } else {
01720     uint32 val;
01721     extern bool GetArgumentInteger(uint32 *value, const char *arg);
01722     success = GetArgumentInteger(&val, value);
01723     if (!success) {
01724       IConsolePrintF(CC_ERROR, "'%s' is not an integer.", value);
01725       return;
01726     }
01727 
01728     success = SetSettingValue(index, val, force_newgame);
01729   }
01730 
01731   if (!success) {
01732     if (_network_server) {
01733       IConsoleError("This command/variable is not available during network games.");
01734     } else {
01735       IConsoleError("This command/variable is only available to a network server.");
01736     }
01737   }
01738 }
01739 
01740 void IConsoleSetSetting(const char *name, int value)
01741 {
01742   uint index;
01743   const SettingDesc *sd = GetSettingFromName(name, &index);
01744   assert(sd != NULL);
01745   SetSettingValue(index, value);
01746 }
01747 
01753 void IConsoleGetSetting(const char *name, bool force_newgame)
01754 {
01755   char value[20];
01756   uint index;
01757   const SettingDesc *sd = GetSettingFromName(name, &index);
01758   const void *ptr;
01759 
01760   if (sd == NULL) {
01761     IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
01762     return;
01763   }
01764 
01765   ptr = GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
01766 
01767   if (sd->desc.cmd == SDT_STRING) {
01768     IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char **)ptr : (const char *)ptr);
01769   } else {
01770     if (sd->desc.cmd == SDT_BOOLX) {
01771       snprintf(value, sizeof(value), (*(bool*)ptr == 1) ? "on" : "off");
01772     } else {
01773       snprintf(value, sizeof(value), "%d", (int32)ReadValue(ptr, sd->save.conv));
01774     }
01775 
01776     IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s' (min: %s%d, max: %d)",
01777       name, value, (sd->desc.flags & SGF_0ISDISABLED) ? "(0) " : "", sd->desc.min, sd->desc.max);
01778   }
01779 }
01780 
01786 void IConsoleListSettings(const char *prefilter)
01787 {
01788   IConsolePrintF(CC_WARNING, "All settings with their current value:");
01789 
01790   for (const SettingDesc *sd = _settings; sd->save.cmd != SL_END; sd++) {
01791     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01792     if (prefilter != NULL && strstr(sd->desc.name, prefilter) == NULL) continue;
01793     char value[80];
01794     const void *ptr = GetVariableAddress((_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game, &sd->save);
01795 
01796     if (sd->desc.cmd == SDT_BOOLX) {
01797       snprintf(value, lengthof(value), (*(bool*)ptr == 1) ? "on" : "off");
01798     } else if (sd->desc.cmd == SDT_STRING) {
01799       snprintf(value, sizeof(value), "%s", (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char **)ptr : (const char *)ptr);
01800     } else {
01801       snprintf(value, lengthof(value), "%d", (uint32)ReadValue(ptr, sd->save.conv));
01802     }
01803     IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
01804   }
01805 
01806   IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
01807 }
01808 
01813 static void LoadSettings(const SettingDesc *osd, void *object)
01814 {
01815   for (; osd->save.cmd != SL_END; osd++) {
01816     const SaveLoad *sld = &osd->save;
01817     void *ptr = GetVariableAddress(object, sld);
01818 
01819     if (!SlObjectMember(ptr, sld)) continue;
01820     if (IsNumericType(sld->conv)) Write_ValidateSetting(ptr, osd, ReadValue(ptr, sld->conv));
01821   }
01822 }
01823 
01828 static inline void LoadSettingsGlobList(const SettingDescGlobVarList *sdg)
01829 {
01830   LoadSettings((const SettingDesc*)sdg, NULL);
01831 }
01832 
01837 static void SaveSettings(const SettingDesc *sd, void *object)
01838 {
01839   /* We need to write the CH_RIFF header, but unfortunately can't call
01840    * SlCalcLength() because we have a different format. So do this manually */
01841   const SettingDesc *i;
01842   size_t length = 0;
01843   for (i = sd; i->save.cmd != SL_END; i++) {
01844     length += SlCalcObjMemberLength(object, &i->save);
01845   }
01846   SlSetLength(length);
01847 
01848   for (i = sd; i->save.cmd != SL_END; i++) {
01849     void *ptr = GetVariableAddress(object, &i->save);
01850     SlObjectMember(ptr, &i->save);
01851   }
01852 }
01853 
01857 static inline void SaveSettingsGlobList(const SettingDescGlobVarList *sdg)
01858 {
01859   SaveSettings((const SettingDesc*)sdg, NULL);
01860 }
01861 
01862 static void Load_OPTS()
01863 {
01864   /* Copy over default setting since some might not get loaded in
01865    * a networking environment. This ensures for example that the local
01866    * autosave-frequency stays when joining a network-server */
01867   PrepareOldDiffCustom();
01868   LoadSettings(_gameopt_settings, &_settings_game);
01869   HandleOldDiffCustom(true);
01870 }
01871 
01872 static void Load_PATS()
01873 {
01874   /* Copy over default setting since some might not get loaded in
01875    * a networking environment. This ensures for example that the local
01876    * signal_side stays when joining a network-server */
01877   LoadSettings(_settings, &_settings_game);
01878 }
01879 
01880 static void Save_PATS()
01881 {
01882   SaveSettings(_settings, &_settings_game);
01883 }
01884 
01885 void CheckConfig()
01886 {
01887   /*
01888    * Increase old default values for pf_maxdepth and pf_maxlength
01889    * to support big networks.
01890    */
01891   if (_settings_newgame.pf.opf.pf_maxdepth == 16 && _settings_newgame.pf.opf.pf_maxlength == 512) {
01892     _settings_newgame.pf.opf.pf_maxdepth = 48;
01893     _settings_newgame.pf.opf.pf_maxlength = 4096;
01894   }
01895 }
01896 
01897 extern const ChunkHandler _setting_chunk_handlers[] = {
01898   { 'OPTS', NULL,      Load_OPTS, NULL, CH_RIFF},
01899   { 'PATS', Save_PATS, Load_PATS, NULL, CH_RIFF | CH_LAST},
01900 };
01901 
01902 static bool IsSignedVarMemType(VarType vt)
01903 {
01904   switch (GetVarMemType(vt)) {
01905     case SLE_VAR_I8:
01906     case SLE_VAR_I16:
01907     case SLE_VAR_I32:
01908     case SLE_VAR_I64:
01909       return true;
01910   }
01911   return false;
01912 }

Generated on Tue Sep 14 17:06:54 2010 for OpenTTD by  doxygen 1.6.1