File: SkirmishAIWrapper.cpp

package info (click to toggle)
spring 0.81.2.1%2Bdfsg1-6
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 28,496 kB
  • ctags: 37,096
  • sloc: cpp: 238,659; ansic: 13,784; java: 12,175; awk: 3,428; python: 1,159; xml: 738; perl: 405; sh: 297; makefile: 267; pascal: 228; objc: 192
file content (414 lines) | stat: -rw-r--r-- 11,569 bytes parent folder | download
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/*
	Copyright (c) 2008 Robin Vobruba <hoijui.quaero@gmail.com>

	This program 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 {} either version 2 of the License, or
	(at your option) any later version.

	This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "SkirmishAIWrapper.h"

#include "System/StdAfx.h"
#include "System/Platform/errorhandler.h"
#include "System/FileSystem/FileSystem.h"
#include "System/FileSystem/FileSystemHandler.h"
#include "System/LogOutput.h"
#include "System/mmgr.h"
#include "System/Util.h"
#include "Sim/Units/Unit.h"
#include "Sim/Units/UnitHandler.h"
#include "Sim/Misc/TeamHandler.h"
#include "ExternalAI/IGlobalAI.h"
#include "ExternalAI/SkirmishAI.h"
#include "ExternalAI/GlobalAICallback.h"
#include "ExternalAI/EngineOutHandler.h"
#include "ExternalAI/SkirmishAIHandler.h"
#include "ExternalAI/SkirmishAILibraryInfo.h"
#include "ExternalAI/SkirmishAIData.h"
#include "ExternalAI/SSkirmishAICallbackImpl.h"
#include "ExternalAI/IAILibraryManager.h"
#include "ExternalAI/Interface/AISEvents.h"
#include "ExternalAI/Interface/AISCommands.h"
#include "ExternalAI/Interface/SSkirmishAILibrary.h"

#include <sstream>
#include <iostream>
#include <fstream>

CR_BIND_DERIVED(CSkirmishAIWrapper, CObject, )
CR_REG_METADATA(CSkirmishAIWrapper, (
	CR_MEMBER(skirmishAIId),
	CR_MEMBER(teamId),
	CR_MEMBER(cheatEvents),
	CR_MEMBER(key),
	CR_SERIALIZER(Serialize),
	CR_POSTLOAD(PostLoad)
));

/// used only by creg
CSkirmishAIWrapper::CSkirmishAIWrapper():
		skirmishAIId((size_t) -1),
		teamId(-1),
		cheatEvents(false),
		ai(NULL),
		initialized(false),
		released(false),
		c_callback(NULL) {}

CSkirmishAIWrapper::CSkirmishAIWrapper(const size_t skirmishAIId):
		skirmishAIId(skirmishAIId),
		cheatEvents(false),
		ai(NULL),
		initialized(false),
		released(false),
		c_callback(NULL)
{
	const SkirmishAIData* aiData = skirmishAIHandler.GetSkirmishAI(skirmishAIId);

	teamId = aiData->team;
	SkirmishAIKey keyTmp(aiData->shortName, aiData->version);
	key    = aiLibManager->ResolveSkirmishAIKey(keyTmp);

	CreateCallback();
}

void CSkirmishAIWrapper::CreateCallback() {

	if (c_callback == NULL) {
		callback = new CGlobalAICallback(this);
		c_callback = skirmishAiCallback_getInstanceFor(teamId, callback);
	}
}

void CSkirmishAIWrapper::PreDestroy() {
	callback->noMessages = true;
}

CSkirmishAIWrapper::~CSkirmishAIWrapper() {
	if (ai) {
		if (initialized && !released) {
			Release();
		}

		delete ai;
		ai = NULL;

		skirmishAiCallback_release(teamId);
		c_callback = NULL;

		delete callback;
		callback = NULL;
	}
}

void CSkirmishAIWrapper::Serialize(creg::ISerializer* s) {
}

void CSkirmishAIWrapper::PostLoad() {
	//CreateCallback();
	LoadSkirmishAI(true);
}



bool CSkirmishAIWrapper::LoadSkirmishAI(bool postLoad) {

	ai = new CSkirmishAI(teamId, key, GetCallback());

	// check if initialization went ok
	if (skirmishAIHandler.IsLocalSkirmishAIDieing(skirmishAIId)) {
		return false;
	}

	IAILibraryManager* libManager = IAILibraryManager::GetInstance();
	libManager->FetchSkirmishAILibrary(key);

	const CSkirmishAILibraryInfo* infos = &*libManager->GetSkirmishAIInfos().find(key)->second;
	bool loadSupported = (infos->GetInfo(SKIRMISH_AI_PROPERTY_LOAD_SUPPORTED) == "yes");

	libManager->ReleaseSkirmishAILibrary(key);


	if (postLoad && !loadSupported) {
		// fallback code to help the AI if it
		// doesn't implement load/save support
		Init();
		for (size_t a = 0; a < uh->MaxUnits(); a++) {
			if (!uh->units[a])
				continue;

			if (uh->units[a]->team == teamId) {
				try {
					UnitCreated(a, -1);
				} CATCH_AI_EXCEPTION;
				if (!uh->units[a]->beingBuilt)
					try {
						UnitFinished(a);
					} CATCH_AI_EXCEPTION;
			} else {
				if ((uh->units[a]->allyteam == teamHandler->AllyTeam(teamId))
						|| teamHandler->Ally(teamHandler->AllyTeam(teamId), uh->units[a]->allyteam)) {
					// do nothing
				} else {
					if (uh->units[a]->losStatus[teamHandler->AllyTeam(teamId)] & (LOS_INRADAR | LOS_INLOS)) {
						try {
							EnemyEnterRadar(a);
						} CATCH_AI_EXCEPTION;
					}
					if (uh->units[a]->losStatus[teamHandler->AllyTeam(teamId)] & LOS_INLOS) {
						try {
							EnemyEnterLOS(a);
						} CATCH_AI_EXCEPTION;
					}
				}
			}
		}
	}

	return true;
}


void CSkirmishAIWrapper::Init() {

	if (ai == NULL) {
		bool loadOk = LoadSkirmishAI(false);
		if (!loadOk) {
			delete ai;
			ai = NULL;
			return;
		}
	}

	SInitEvent evtData = {teamId, GetCallback()};
	int error = ai->HandleEvent(EVENT_INIT, &evtData);
	if (error != 0) {
		// init failed
		logOutput.Print("Failed to handle init event: AI for team %d, error %d",
				teamId, error);
		skirmishAIHandler.SetLocalSkirmishAIDieing(skirmishAIId, 5 /* = AI failed to init */);
	} else {
		initialized = true;
	}
}

void CSkirmishAIWrapper::Dieing() {
	ai->Dieing();
}

void CSkirmishAIWrapper::Release(int reason) {

	if (initialized && !released) {
		SReleaseEvent evtData = {reason};
		ai->HandleEvent(EVENT_RELEASE, &evtData);

		released = true;

		// further cleanup is done in the destructor
	}
}

static void streamCopy(std::istream* in, std::ostream* out)
{
	static const size_t buffer_size = 128;
	char* buffer;

	buffer = new char[buffer_size];

	in->read(buffer, buffer_size);
	while (in->good()) {
		out->write(buffer, in->gcount());
		in->read(buffer, buffer_size);
	}
	out->write(buffer, in->gcount());

	delete[] buffer;
}

void CSkirmishAIWrapper::Load(std::istream* load_s)
{
	static const size_t tmpFileName_size = 1024;
	char* tmpFileName = new char[tmpFileName_size];
	SNPRINTF(tmpFileName, tmpFileName_size, "%s-team_%i.tmp", "load", teamId);
	std::string tmpFile = filesystem.LocateFile(tmpFileName,
			FileSystem::WRITE | FileSystem::CREATE_DIRS);
	delete[] tmpFileName;

	std::ofstream tmpFile_s;
	tmpFile_s.open(tmpFile.c_str(), std::ios::binary);
	streamCopy(load_s, &tmpFile_s);
	tmpFile_s.close();

	SLoadEvent evtData = {tmpFile.c_str()};
	ai->HandleEvent(EVENT_LOAD, &evtData);

	FileSystemHandler::DeleteFile(tmpFile);
}

void CSkirmishAIWrapper::Save(std::ostream* save_s)
{
	static const size_t tmpFileName_size = 1024;
	char* tmpFileName = new char[tmpFileName_size];
	SNPRINTF(tmpFileName, tmpFileName_size, "%s-team_%i.tmp", "save", teamId);
	std::string tmpFile = filesystem.LocateFile(tmpFileName,
			FileSystem::WRITE | FileSystem::CREATE_DIRS);
	delete[] tmpFileName;

	SSaveEvent evtData = {tmpFile.c_str()};
	ai->HandleEvent(EVENT_SAVE, &evtData);

	if (FileSystemHandler::FileExists(tmpFile)) {
		std::ifstream tmpFile_s;
		tmpFile_s.open(tmpFile.c_str(), std::ios::binary);
		streamCopy(&tmpFile_s, save_s);
		tmpFile_s.close();
		FileSystemHandler::DeleteFile(tmpFile);
	}
}

void CSkirmishAIWrapper::UnitIdle(int unitId) {
	SUnitIdleEvent evtData = {unitId};
	ai->HandleEvent(EVENT_UNIT_IDLE, &evtData);
}

void CSkirmishAIWrapper::UnitCreated(int unitId, int builderId) {
	SUnitCreatedEvent evtData = {unitId, builderId};
	ai->HandleEvent(EVENT_UNIT_CREATED, &evtData);
}

void CSkirmishAIWrapper::UnitFinished(int unitId) {
	SUnitFinishedEvent evtData = {unitId};
	ai->HandleEvent(EVENT_UNIT_FINISHED, &evtData);
}

void CSkirmishAIWrapper::UnitDestroyed(int unitId, int attackerUnitId) {

	SUnitDestroyedEvent evtData = {unitId, attackerUnitId};
	ai->HandleEvent(EVENT_UNIT_DESTROYED, &evtData);
}

void CSkirmishAIWrapper::UnitDamaged(int unitId, int attackerUnitId,
		float damage, const float3& dir, int weaponDefId, bool paralyzer) {

	SUnitDamagedEvent evtData = {unitId, attackerUnitId, damage,
			dir.toSAIFloat3(), weaponDefId, paralyzer};
	ai->HandleEvent(EVENT_UNIT_DAMAGED, &evtData);
}

void CSkirmishAIWrapper::UnitMoveFailed(int unitId) {
	SUnitMoveFailedEvent evtData = {unitId};
	ai->HandleEvent(EVENT_UNIT_MOVE_FAILED, &evtData);
}

void CSkirmishAIWrapper::UnitGiven(int unitId, int oldTeam, int newTeam) {
	SUnitGivenEvent evtData = {unitId, oldTeam, newTeam};
	ai->HandleEvent(EVENT_UNIT_GIVEN, &evtData);
}

void CSkirmishAIWrapper::UnitCaptured(int unitId, int oldTeam, int newTeam) {
	SUnitCapturedEvent evtData = {unitId, oldTeam, newTeam};
	ai->HandleEvent(EVENT_UNIT_CAPTURED, &evtData);
}

void CSkirmishAIWrapper::EnemyEnterLOS(int unitId) {
	SEnemyEnterLOSEvent evtData = {unitId};
	ai->HandleEvent(EVENT_ENEMY_ENTER_LOS, &evtData);
}

void CSkirmishAIWrapper::EnemyLeaveLOS(int unitId) {
	SEnemyLeaveLOSEvent evtData = {unitId};
	ai->HandleEvent(EVENT_ENEMY_LEAVE_LOS, &evtData);
}

void CSkirmishAIWrapper::EnemyEnterRadar(int unitId) {
	SEnemyEnterRadarEvent evtData = {unitId};
	ai->HandleEvent(EVENT_ENEMY_ENTER_RADAR, &evtData);
}

void CSkirmishAIWrapper::EnemyLeaveRadar(int unitId) {
	SEnemyLeaveRadarEvent evtData = {unitId};
	ai->HandleEvent(EVENT_ENEMY_LEAVE_RADAR, &evtData);
}

void CSkirmishAIWrapper::EnemyDestroyed(int enemyUnitId, int attackerUnitId) {
	SEnemyDestroyedEvent evtData = {enemyUnitId, attackerUnitId};
	ai->HandleEvent(EVENT_ENEMY_DESTROYED, &evtData);
}

void CSkirmishAIWrapper::EnemyDamaged(int enemyUnitId, int attackerUnitId,
		float damage, const float3& dir, int weaponDefId, bool paralyzer) {

	SEnemyDamagedEvent evtData = {enemyUnitId, attackerUnitId, damage,
			dir.toSAIFloat3(), weaponDefId, paralyzer};
	ai->HandleEvent(EVENT_ENEMY_DAMAGED, &evtData);
}

void CSkirmishAIWrapper::Update(int frame) {
	SUpdateEvent evtData = {frame};
	ai->HandleEvent(EVENT_UPDATE, &evtData);
}

void CSkirmishAIWrapper::GotChatMsg(const char* msg, int fromPlayerId) {
	SMessageEvent evtData = {fromPlayerId, msg};
	ai->HandleEvent(EVENT_MESSAGE, &evtData);
}

void CSkirmishAIWrapper::WeaponFired(int unitId, int weaponDefId) {
	SWeaponFiredEvent evtData = {unitId, weaponDefId};
	ai->HandleEvent(EVENT_WEAPON_FIRED, &evtData);
}

void CSkirmishAIWrapper::PlayerCommandGiven(
		const std::vector<int>& selectedUnits, const Command& c, int playerId) {

	unsigned int numUnits = selectedUnits.size();
	int* unitIds = new int[numUnits];

	for (unsigned int i = 0; i < numUnits; ++i) {
		unitIds[i] = selectedUnits.at(i);
	}

	int sCommandId;
	void* sCommandData = mallocSUnitCommand(-1, -1, &c, &sCommandId);

	SPlayerCommandEvent evtData = {unitIds, numUnits, sCommandId, sCommandData,
			playerId};
	ai->HandleEvent(EVENT_PLAYER_COMMAND, &evtData);
	delete [] unitIds;
}

void CSkirmishAIWrapper::CommandFinished(int unitId, int commandTopicId) {
	// TODO: add support for commandIds:
	// each issued command would have its own id
	const int commandId = -1;
	SCommandFinishedEvent evtData = {unitId, commandId, commandTopicId};
	ai->HandleEvent(EVENT_COMMAND_FINISHED, &evtData);
}

void CSkirmishAIWrapper::SeismicPing(int allyTeam, int unitId,
		const float3& pos, float strength) {

	SSeismicPingEvent evtData = {pos.toSAIFloat3(), strength};
	ai->HandleEvent(EVENT_SEISMIC_PING, &evtData);
}


int CSkirmishAIWrapper::GetTeamId() const { return teamId; }
const SkirmishAIKey& CSkirmishAIWrapper::GetKey() const { return key; }
const SSkirmishAICallback* CSkirmishAIWrapper::GetCallback() const { return c_callback; }

void CSkirmishAIWrapper::SetCheatEventsEnabled(bool enable) {
	cheatEvents = enable;
}
bool CSkirmishAIWrapper::IsCheatEventsEnabled() const {
	return cheatEvents;
}