# ai_core.cpp

Go to the documentation of this file.

    00001 /* $Id: ai_core.cpp 18953 2010-01-29 21:38:55Z yexo $ */
    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
    00012 #include "../stdafx.h"
    00013 #include "../core/bitmath_func.hpp"
    00014 #include "../company_base.h"
    00015 #include "../company_func.h"
    00016 #include "../debug.h"
    00017 #include "../network/network.h"
    00018 #include "../window_func.h"
    00019 #include "../command_func.h"
    00020 #include "ai_scanner.hpp"
    00021 #include "ai_instance.hpp"
    00022 #include "ai_config.hpp"
    00023 #include "api/ai_error.hpp"
    00024
    00025 /* static */ uint AI::frame_counter = 0;
    00026 /* static */ AIScanner *AI::ai_scanner = NULL;
    00027
    00028 /* static */ bool AI::CanStartNew()
    00029 {
    00030   /* Only allow new AIs on the server and only when that is allowed in multiplayer */
    00031   return !_networking || (_network_server && _settings_game.ai.ai_in_multiplayer);
    00032 }
    00033
    00034 /* static */ void AI::StartNew(CompanyID company, bool rerandomise_ai)
    00035 {
    00036   assert(Company::IsValidID(company));
    00037
    00038   /* Clients shouldn't start AIs */
    00039   if (_networking && !_network_server) return;
    00040
    00041   AIConfig *config = AIConfig::GetConfig(company);
    00042   AIInfo *info = config->GetInfo();
    00043   if (info == NULL || (rerandomise_ai && config->IsRandomAI())) {
    00044     info = AI::ai_scanner->SelectRandomAI();
    00045     assert(info != NULL);
    00046     /* Load default data and store the name in the settings */
    00047     config->ChangeAI(info->GetName(), -1, false, true);
    00048   }
    00049
    00050   _current_company = company;
    00051   Company *c = Company::Get(company);
    00052
    00053   c->ai_info = info;
    00054   assert(c->ai_instance == NULL);
    00055   c->ai_instance = new AIInstance(info);
    00056
    00057   InvalidateWindowData(WC_AI_DEBUG, 0, -1);
    00058   return;
    00059 }
    00060
    00061 /* static */ void AI::GameLoop()
    00062 {
    00063   /* If we are in networking, only servers run this function, and that only if it is allowed */
    00064   if (_networking && (!_network_server || !_settings_game.ai.ai_in_multiplayer)) return;
    00065
    00066   /* The speed with which AIs go, is limited by the 'competitor_speed' */
    00067   AI::frame_counter++;
    00068   assert(_settings_game.difficulty.competitor_speed <= 4);
    00069   if ((AI::frame_counter & ((1 << (4 - _settings_game.difficulty.competitor_speed)) - 1)) != 0) return;
    00070
    00071   const Company *c;
    00072   FOR_ALL_COMPANIES(c) {
    00073     if (c->is_ai) {
    00074       _current_company = c->index;
    00075       c->ai_instance->GameLoop();
    00076     }
    00077   }
    00078
    00079   /* Occasionally collect garbage; every 255 ticks do one company.
    00080    * Effectively collecting garbage once every two months per AI. */
    00081   if ((AI::frame_counter & 255) == 0) {
    00082     CompanyID cid = (CompanyID)GB(AI::frame_counter, 8, 4);
    00083     if (Company::IsValidAiID(cid)) Company::Get(cid)->ai_instance->CollectGarbage();
    00084   }
    00085
    00086   _current_company = OWNER_NONE;
    00087 }
    00088
    00089 /* static */ uint AI::GetTick()
    00090 {
    00091   return AI::frame_counter;
    00092 }
    00093
    00094 /* static */ void AI::Stop(CompanyID company)
    00095 {
    00096   if (_networking && !_network_server) return;
    00097
    00098   CompanyID old_company = _current_company;
    00099   _current_company = company;
    00100   Company *c = Company::Get(company);
    00101
    00102   delete c->ai_instance;
    00103   c->ai_instance = NULL;
    00104
    00105   _current_company = old_company;
    00106
    00107   InvalidateWindowData(WC_AI_DEBUG, 0, -1);
    00108   DeleteWindowById(WC_AI_SETTINGS, company);
    00109 }
    00110
    00111 /* static */ void AI::KillAll()
    00112 {
    00113   /* It might happen there are no companies .. than we have nothing to loop */
    00114   if (Company::GetPoolSize() == 0) return;
    00115
    00116   const Company *c;
    00117   FOR_ALL_COMPANIES(c) {
    00118     if (c->is_ai) AI::Stop(c->index);
    00119   }
    00120 }
    00121
    00122 /* static */ void AI::Initialize()
    00123 {
    00124   if (AI::ai_scanner != NULL) AI::Uninitialize(true);
    00125
    00126   AI::frame_counter = 0;
    00127   if (AI::ai_scanner == NULL) AI::ai_scanner = new AIScanner();
    00128 }
    00129
    00130 /* static */ void AI::Uninitialize(bool keepConfig)
    00131 {
    00132   AI::KillAll();
    00133
    00134   if (keepConfig) {
    00135     /* Run a rescan, which indexes all AIInfos again, and check if we can
    00136      *  still load all the AIS, while keeping the configs in place */
    00137     Rescan();
    00138   } else {
    00139     delete AI::ai_scanner;
    00140     AI::ai_scanner = NULL;
    00141
    00142     for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
    00143       if (_settings_game.ai_config[c] != NULL) {
    00144         delete _settings_game.ai_config[c];
    00145         _settings_game.ai_config[c] = NULL;
    00146       }
    00147       if (_settings_newgame.ai_config[c] != NULL) {
    00148         delete _settings_newgame.ai_config[c];
    00149         _settings_newgame.ai_config[c] = NULL;
    00150       }
    00151     }
    00152   }
    00153 }
    00154
    00155 /* static */ void AI::ResetConfig()
    00156 {
    00157   /* Check for both newgame as current game if we can reload the AIInfo insde
    00158    *  the AIConfig. If not, remove the AI from the list (which will assign
    00159    *  a random new AI on reload). */
    00160   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
    00161     if (_settings_game.ai_config[c] != NULL && _settings_game.ai_config[c]->HasAI()) {
    00162       if (!_settings_game.ai_config[c]->ResetInfo()) {
    00163         DEBUG(ai, 0, "After a reload, the AI by the name '%s' was no longer found, and removed from the list.", _settings_game.ai_config[c]->GetName());
    00164         _settings_game.ai_config[c]->ChangeAI(NULL);
    00165       }
    00166     }
    00167     if (_settings_newgame.ai_config[c] != NULL && _settings_newgame.ai_config[c]->HasAI()) {
    00168       if (!_settings_newgame.ai_config[c]->ResetInfo()) {
    00169         DEBUG(ai, 0, "After a reload, the AI by the name '%s' was no longer found, and removed from the list.", _settings_newgame.ai_config[c]->GetName());
    00170         _settings_newgame.ai_config[c]->ChangeAI(NULL);
    00171       }
    00172     }
    00173   }
    00174 }
    00175
    00176 /* static */ void AI::NewEvent(CompanyID company, AIEvent *event)
    00177 {
    00178   /* AddRef() and Release() need to be called at least once, so do it here */
    00179   event->AddRef();
    00180
    00181   /* Clients should ignore events */
    00182   if (_networking && !_network_server) {
    00183     event->Release();
    00184     return;
    00185   }
    00186
    00187   /* Only AIs can have an event-queue */
    00188   if (!Company::IsValidAiID(company)) {
    00189     event->Release();
    00190     return;
    00191   }
    00192
    00193   /* Queue the event */
    00194   CompanyID old_company = _current_company;
    00195   _current_company = company;
    00196   AIEventController::InsertEvent(event);
    00197   _current_company = old_company;
    00198
    00199   event->Release();
    00200 }
    00201
    00202 /* static */ void AI::BroadcastNewEvent(AIEvent *event, CompanyID skip_company)
    00203 {
    00204   /* AddRef() and Release() need to be called at least once, so do it here */
    00205   event->AddRef();
    00206
    00207   /* Clients should ignore events */
    00208   if (_networking && !_network_server) {
    00209     event->Release();
    00210     return;
    00211   }
    00212
    00213   /* Try to send the event to all AIs */
    00214   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
    00215     if (c != skip_company) AI::NewEvent(c, event);
    00216   }
    00217
    00218   event->Release();
    00219 }
    00220
    00221 void CcAI(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
    00222 {
    00223   AIObject::SetLastCommandRes(result.Succeeded());
    00224
    00225   if (result.Failed()) {
    00226     AIObject::SetLastError(AIError::StringToError(result.GetErrorMessage()));
    00227   } else {
    00228     AIObject::IncreaseDoCommandCosts(result.GetCost());
    00229     AIObject::SetLastCost(result.GetCost());
    00230   }
    00231
    00232   Company::Get(_current_company)->ai_instance->Continue();
    00233 }
    00234
    00235 /* static */ void AI::Save(CompanyID company)
    00236 {
    00237   if (!_networking || _network_server) {
    00238     Company *c = Company::GetIfValid(company);
    00239     assert(c != NULL && c->ai_instance != NULL);
    00240
    00241     CompanyID old_company = _current_company;
    00242     _current_company = company;
    00243     c->ai_instance->Save();
    00244     _current_company = old_company;
    00245   } else {
    00246     AIInstance::SaveEmpty();
    00247   }
    00248 }
    00249
    00250 /* static */ void AI::Load(CompanyID company, int version)
    00251 {
    00252   if (!_networking || _network_server) {
    00253     Company *c = Company::GetIfValid(company);
    00254     assert(c != NULL && c->ai_instance != NULL);
    00255
    00256     CompanyID old_company = _current_company;
    00257     _current_company = company;
    00258     c->ai_instance->Load(version);
    00259     _current_company = old_company;
    00260   } else {
    00261     /* Read, but ignore, the load data */
    00262     AIInstance::LoadEmpty();
    00263   }
    00264 }
    00265
    00266 /* static */ int AI::GetStartNextTime()
    00267 {
    00268   /* Find the first company which doesn't exist yet */
    00269   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
    00270     if (!Company::IsValidID(c)) return AIConfig::GetConfig(c)->GetSetting("start_date");
    00271   }
    00272
    00273   /* Currently no AI can be started, check again in a year. */
    00274   return DAYS_IN_YEAR;
    00275 }
    00276
    00277 /* static */ char *AI::GetConsoleList(char *p, const char *last)
    00278 {
    00279   return AI::ai_scanner->GetAIConsoleList(p, last);
    00280 }
    00281
    00282 /* static */ const AIInfoList *AI::GetInfoList()
    00283 {
    00284   return AI::ai_scanner->GetAIInfoList();
    00285 }
    00286
    00287 /* static */ const AIInfoList *AI::GetUniqueInfoList()
    00288 {
    00289   return AI::ai_scanner->GetUniqueAIInfoList();
    00290 }
    00291
    00292 /* static */ AIInfo *AI::FindInfo(const char *name, int version, bool force_exact_match)
    00293 {
    00294   return AI::ai_scanner->FindInfo(name, version, force_exact_match);
    00295 }
    00296
    00297 /* static */ bool AI::ImportLibrary(const char *library, const char *class_name, int version, HSQUIRRELVM vm)
    00298 {
    00299   return AI::ai_scanner->ImportLibrary(library, class_name, version, vm, Company::Get(_current_company)->ai_instance->GetController());
    00300 }
    00301
    00302 /* static */ void AI::Rescan()
    00303 {
    00304   AI::ai_scanner->RescanAIDir();
    00305   ResetConfig();
    00306 }