summaryrefslogtreecommitdiff
path: root/src/ai/ai_core.cpp
blob: a8e96085bf1aa423a84f47dc53a0a79bf49df96a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/* $Id$ */

/*
 * This file is part of OpenTTD.
 * 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.
 * 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.
 * 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/>.
 */

/** @file ai_core.cpp Implementation of AI. */

#include "../stdafx.h"
#include "../core/bitmath_func.hpp"
#include "../company_base.h"
#include "../company_func.h"
#include "../debug.h"
#include "../network/network.h"
#include "../window_func.h"
#include "../command_func.h"
#include "ai.hpp"
#include "ai_scanner.hpp"
#include "ai_instance.hpp"
#include "ai_config.hpp"
#include "api/ai_error.hpp"

/* static */ uint AI::frame_counter = 0;
/* static */ AIScanner *AI::ai_scanner = NULL;

/* static */ bool AI::CanStartNew()
{
	/* Only allow new AIs on the server and only when that is allowed in multiplayer */
	return !_networking || (_network_server && _settings_game.ai.ai_in_multiplayer);
}

/* static */ void AI::StartNew(CompanyID company)
{
	assert(Company::IsValidID(company));

	/* Clients shouldn't start AIs */
	if (_networking && !_network_server) return;

	AIInfo *info = AIConfig::GetConfig(company)->GetInfo();
	if (info == NULL) {
		info = AI::ai_scanner->SelectRandomAI();
		assert(info != NULL);
		/* Load default data and store the name in the settings */
		AIConfig::GetConfig(company)->ChangeAI(info->GetName());
	}

	_current_company = company;
	Company *c = Company::Get(company);

	c->ai_info = info;
	assert(c->ai_instance == NULL);
	c->ai_instance = new AIInstance(info);

	InvalidateWindowData(WC_AI_DEBUG, 0, -1);
	return;
}

/* static */ void AI::GameLoop()
{
	/* If we are in networking, only servers run this function, and that only if it is allowed */
	if (_networking && (!_network_server || !_settings_game.ai.ai_in_multiplayer)) return;

	/* The speed with which AIs go, is limited by the 'competitor_speed' */
	AI::frame_counter++;
	assert(_settings_game.difficulty.competitor_speed <= 4);
	if ((AI::frame_counter & ((1 << (4 - _settings_game.difficulty.competitor_speed)) - 1)) != 0) return;

	const Company *c;
	FOR_ALL_COMPANIES(c) {
		if (c->is_ai) {
			_current_company = c->index;
			c->ai_instance->GameLoop();
		}
	}

	/* Occasionally collect garbage; every 255 ticks do one company.
	 * Effectively collecting garbage once every two months per AI. */
	if ((AI::frame_counter & 255) == 0) {
		CompanyID cid = (CompanyID)GB(AI::frame_counter, 8, 4);
		if (Company::IsValidAiID(cid)) Company::Get(cid)->ai_instance->CollectGarbage();
	}

	_current_company = OWNER_NONE;
}

/* static */ uint AI::GetTick()
{
	return AI::frame_counter;
}

/* static */ void AI::Stop(CompanyID company)
{
	if (_networking && !_network_server) return;

	CompanyID old_company = _current_company;
	_current_company = company;
	Company *c = Company::Get(company);

	delete c->ai_instance;
	c->ai_instance = NULL;

	_current_company = old_company;

	InvalidateWindowData(WC_AI_DEBUG, 0, -1);
}

/* static */ void AI::KillAll()
{
	/* It might happen there are no companies .. than we have nothing to loop */
	if (Company::GetPoolSize() == 0) return;

	const Company *c;
	FOR_ALL_COMPANIES(c) {
		if (c->is_ai) AI::Stop(c->index);
	}
}

/* static */ void AI::Initialize()
{
	if (AI::ai_scanner != NULL) AI::Uninitialize(true);

	AI::frame_counter = 0;
	if (AI::ai_scanner == NULL) AI::ai_scanner = new AIScanner();
}

/* static */ void AI::Uninitialize(bool keepConfig)
{
	AI::KillAll();

	if (keepConfig) {
		/* Run a rescan, which indexes all AIInfos again, and check if we can
		 *  still load all the AIS, while keeping the configs in place */
		Rescan();
	} else {
		delete AI::ai_scanner;
		AI::ai_scanner = NULL;

		for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
			if (_settings_game.ai_config[c] != NULL) {
				delete _settings_game.ai_config[c];
				_settings_game.ai_config[c] = NULL;
			}
			if (_settings_newgame.ai_config[c] != NULL) {
				delete _settings_newgame.ai_config[c];
				_settings_newgame.ai_config[c] = NULL;
			}
		}
	}
}

/* static */ void AI::ResetConfig()
{
	/* Check for both newgame as current game if we can reload the AIInfo insde
	 *  the AIConfig. If not, remove the AI from the list (which will assign
	 *  a random new AI on reload). */
	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
		if (_settings_game.ai_config[c] != NULL && _settings_game.ai_config[c]->HasAI()) {
			if (!_settings_game.ai_config[c]->ResetInfo()) {
				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());
				_settings_game.ai_config[c]->ChangeAI(NULL);
			}
		}
		if (_settings_newgame.ai_config[c] != NULL && _settings_newgame.ai_config[c]->HasAI()) {
			if (!_settings_newgame.ai_config[c]->ResetInfo()) {
				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());
				_settings_newgame.ai_config[c]->ChangeAI(NULL);
			}
		}
	}
}

/* static */ void AI::NewEvent(CompanyID company, AIEvent *event)
{
	/* AddRef() and Release() need to be called at least once, so do it here */
	event->AddRef();

	/* Clients should ignore events */
	if (_networking && !_network_server) {
		event->Release();
		return;
	}

	/* Only AIs can have an event-queue */
	if (!Company::IsValidAiID(company)) {
		event->Release();
		return;
	}

	/* Queue the event */
	CompanyID old_company = _current_company;
	_current_company = company;
	AIEventController::InsertEvent(event);
	_current_company = old_company;

	event->Release();
}

/* static */ void AI::BroadcastNewEvent(AIEvent *event, CompanyID skip_company)
{
	/* AddRef() and Release() need to be called at least once, so do it here */
	event->AddRef();

	/* Clients should ignore events */
	if (_networking && !_network_server) {
		event->Release();
		return;
	}

	/* Try to send the event to all AIs */
	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
		if (c != skip_company) AI::NewEvent(c, event);
	}

	event->Release();
}

void CcAI(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
	AIObject::SetLastCommandRes(success);

	if (!success) {
		AIObject::SetLastError(AIError::StringToError(_error_message));
	} else {
		AIObject::IncreaseDoCommandCosts(AIObject::GetLastCost());
	}

	Company::Get(_current_company)->ai_instance->Continue();
}

/* static */ void AI::Save(CompanyID company)
{
	if (!_networking || _network_server) {
		Company *c = Company::GetIfValid(company);
		assert(c != NULL && c->ai_instance != NULL);

		CompanyID old_company = _current_company;
		_current_company = company;
		c->ai_instance->Save();
		_current_company = old_company;
	} else {
		AIInstance::SaveEmpty();
	}
}

/* static */ void AI::Load(CompanyID company, int version)
{
	if (!_networking || _network_server) {
		Company *c = Company::GetIfValid(company);
		assert(c != NULL && c->ai_instance != NULL);

		CompanyID old_company = _current_company;
		_current_company = company;
		c->ai_instance->Load(version);
		_current_company = old_company;
	} else {
		/* Read, but ignore, the load data */
		AIInstance::LoadEmpty();
	}
}

/* static */ int AI::GetStartNextTime()
{
	/* Find the first company which doesn't exist yet */
	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
		if (!Company::IsValidID(c)) return AIConfig::GetConfig(c)->GetSetting("start_date");
	}

	/* Currently no AI can be started, check again in a year. */
	return DAYS_IN_YEAR;
}

/* static */ char *AI::GetConsoleList(char *p, const char *last)
{
	return AI::ai_scanner->GetAIConsoleList(p, last);
}

/* static */ const AIInfoList *AI::GetInfoList()
{
	return AI::ai_scanner->GetAIInfoList();
}

/* static */ const AIInfoList *AI::GetUniqueInfoList()
{
	return AI::ai_scanner->GetUniqueAIInfoList();
}

/* static */ AIInfo *AI::FindInfo(const char *name, int version)
{
	return AI::ai_scanner->FindInfo(name, version);
}

/* static */ bool AI::ImportLibrary(const char *library, const char *class_name, int version, HSQUIRRELVM vm)
{
	return AI::ai_scanner->ImportLibrary(library, class_name, version, vm, Company::Get(_current_company)->ai_instance->GetController());
}

/* static */ void AI::Rescan()
{
	AI::ai_scanner->RescanAIDir();
	ResetConfig();
}