File: CEconomy.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 (713 lines) | stat: -rw-r--r-- 21,472 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
#include "CEconomy.h"

#include <cfloat>

#include "headers/HEngine.h"

#include "CAI.h"
#include "CTaskHandler.h"
#include "CUnitTable.h"
#include "GameMap.hpp"
#include "CWishList.h"
#include "CDefenseMatrix.h"
#include "CGroup.h"
#include "CUnit.h"
#include "CRNG.h"
#include "CPathfinder.h"
#include "CConfigParser.h"
#include "CIntel.h"
#include "GameMap.hpp"

CEconomy::CEconomy(AIClasses *ai): ARegistrar(700, std::string("economy")) {
	this->ai = ai;
	state = 0;
	incomes  = 0;
	mNow     = mNowSummed     = eNow     = eNowSummed     = 0.0f;
	mIncome  = mIncomeSummed  = eIncome  = eIncomeSummed  = 0.0f;
	uMIncome = uMIncomeSummed = uEIncome = uEIncomeSummed = 0.0f;
	mUsage   = mUsageSummed   = eUsage   = eUsageSummed   = 0.0f;
	mStorage = eStorage                                   = 0.0f;
	mstall = estall = mexceeding = eexceeding = mRequest = eRequest = false;
	initialized = false;
	areMMakersEnabled = ai->gamemap->IsNonMetalMap();
}

CEconomy::~CEconomy()
{
	for(int i = 0; i < groups.size(); i++)
		delete groups[i];	
}

void CEconomy::init(CUnit &unit) {
	if(initialized)	return;
	// NOTE: expecting "unit" is a commander unit
	const UnitDef *ud = ai->cb->GetUnitDef(unit.key);
	UnitType *utCommander = UT(ud->id);
	windmap = ((ai->cb->GetMaxWind() + ai->cb->GetMinWind()) / 2.0f) >= 10.0f;
	//float avgWind   = (ai->cb->GetMinWind() + ai->cb->GetMaxWind()) / 2.0f;
	//float windProf  = avgWind / utWind->cost;
	//float solarProf = utSolar->energyMake / utSolar->cost;
	mStart = utCommander->def->metalMake;
	eStart = utCommander->def->energyMake;
	type   = ai->gamemap->IsKbotMap() ? KBOT : VEHICLE;
	initialized = true;
}
		
bool CEconomy::hasBegunBuilding(CGroup &group) {
	std::map<int, CUnit*>::iterator i;
	for (i = group.units.begin(); i != group.units.end(); i++) {
		CUnit *unit = i->second;
		if (ai->unittable->idle.find(unit->key) == ai->unittable->idle.end()
			|| !ai->unittable->idle[unit->key])
			return true;
	}
	
	return false;
}

bool CEconomy::hasFinishedBuilding(CGroup &group) {
	std::map<int, CUnit*>::iterator i;
	for (i = group.units.begin(); i != group.units.end(); i++) {
		CUnit *unit = i->second;
		if (ai->unittable->builders.find(unit->key) != ai->unittable->builders.end() &&
			ai->unittable->builders[unit->key]) {
			ai->unittable->builders[unit->key] = false;
			return true;
		}
	}
	
	return false;
}

CGroup* CEconomy::requestGroup() {
	CGroup *group = NULL;
	int index     = 0;

	/* Create a new slot */
	if (free.empty()) {
		group = new CGroup(ai);
		groups.push_back(group);
		index = groups.size()-1;
	}

	/* Use top free slot from stack */
	else {
		index = free.top(); free.pop();
		group = groups[index];
		group->reset();
	}

	lookup[group->key] = index;
	group->reg(*this);
	activeGroups[group->key] = group;

	return group;
}

void CEconomy::remove(ARegistrar &group) {
	LOG_II("CEconomy::remove group(" << group.key << ")")
	free.push(lookup[group.key]);
	lookup.erase(group.key);
	activeGroups.erase(group.key);
	takenMexes.erase(group.key);

	// NOTE: CEconomy is registered inside group, so the next lines 
	// are senseless because records.size() == 0 always
	std::list<ARegistrar*>::iterator i;
	for (i = records.begin(); i != records.end(); i++)
		(*i)->remove(group);
}

void CEconomy::addUnitOnCreated(CUnit &unit) {
	unsigned c = unit.type->cats;
	if (c&MEXTRACTOR) {
		CGroup *group = requestGroup();
		group->addUnit(unit);
		takenMexes[group->key] = group->pos();
		CUnit *builder = ai->unittable->getUnit((group->units.begin())->second->builtBy);
		takenMexes.erase(builder->group->key);
	}
}

void CEconomy::addUnitOnFinished(CUnit &unit) {
	LOG_II("CEconomy::addUnitOnFinished " << unit)

	unsigned c = unit.type->cats;
	if (c&FACTORY) {
		CGroup *group = requestGroup();
		group->addUnit(unit);
		ai->tasks->addFactoryTask(*group);
		
		/* TODO: put same factories in a single group. This requiers refactoring of task
		assisting, because when factory is dead assising tasks continue working on ex. factory
		position.

		CUnit *factory = CUnitTable::getUnitByDef(ai->unittable->factories, unit.def);
		if(factory && factory->group) {
			factory->group->addUnit(unit);
		} else {
			CGroup *group = requestGroup();
			group->addUnit(unit);
			ai->tasks->addFactoryTask(*group);
		}
		*/
		ai->unittable->factories[unit.key] = &unit;
	}

	else if (c&BUILDER && c&MOBILE) {
		CGroup *group = requestGroup();
		group->addUnit(unit);
	}

	else if (c&MMAKER) {
		ai->unittable->metalMakers[unit.key] = &unit;
	}
}

void CEconomy::buildOrAssist(CGroup &group, buildType bt, unsigned include, unsigned exclude) {
	ATask *task = canAssist(bt, group);
	if (task != NULL)
		ai->tasks->addAssistTask(*task, group);
	else {
		/* Retrieve the allowed buildable units */
		CUnit *unit = group.firstUnit();
		std::multimap<float, UnitType*> candidates;
		ai->unittable->getBuildables(unit->type, include, exclude, candidates);

		if (candidates.empty()) 
			return;

		/* Determine which of these we can afford */
		std::multimap<float, UnitType*>::iterator i = candidates.begin();
		int iterations = candidates.size() / (ai->cfgparser->getTotalStates() + 1 - state);
		bool affordable = false;
		while(iterations >= 0) {
			if (canAffordToBuild(group.firstUnit()->type, i->second))
				affordable = true;
			else
				break;

			if (i == --candidates.end())
				break;
			iterations--;
			i++;
		}
		
		/* Determine the location where to build */
		float3 pos = group.pos();
		float3 goal = pos;

		/* Perform the build */
		switch(bt) {
			case BUILD_EPROVIDER: {
				if (windmap && ai->cb->GetCurWind() >= 10.0f)
					ai->tasks->addBuildTask(bt, i->second, group, goal);
				else if (i->second->cats&WIND)
					ai->tasks->addBuildTask(bt, (++candidates.begin())->second, group, goal);
				else
					ai->tasks->addBuildTask(bt, i->second, group, goal);
				break;
			}

			case BUILD_MPROVIDER: {
				goal = getClosestOpenMetalSpot(group);
				bool canBuildMMaker = (eIncome - eUsage) >= METAL2ENERGY || eexceeding;
				if (goal != ZeroVector) {
					bool tooSmallIncome = mIncome < 3.0f;
					bool isComm  = unit->def->isCommander;
					if (tooSmallIncome || !isComm || ai->pathfinder->getETA(group, goal) < 30*10) {
						ai->tasks->addBuildTask(BUILD_MPROVIDER, i->second, group, goal);
					}
					else if (areMMakersEnabled && canBuildMMaker) {
						UnitType *mmaker = ai->unittable->canBuild(unit->type, LAND|MMAKER);
						if (mmaker != NULL)
							ai->tasks->addBuildTask(BUILD_MPROVIDER, mmaker, group, pos);
					}
				}
				else if (areMMakersEnabled && canBuildMMaker) {
					UnitType *mmaker = ai->unittable->canBuild(unit->type, LAND|MMAKER);
					if (mmaker != NULL)
						ai->tasks->addBuildTask(BUILD_MPROVIDER, mmaker, group, pos);
				}
				else {
					buildOrAssist(group, BUILD_EPROVIDER, EMAKER|LAND);
				}
				break;
			}

			case BUILD_MSTORAGE: case BUILD_ESTORAGE: {
				/* Start building storage after enough ingame time */
				if (!taskInProgress(bt) && ai->cb->GetCurrentFrame() > 30*60*7) {
					pos = ai->defensematrix->getBestDefendedPos(0);
					ai->tasks->addBuildTask(bt, i->second, group, pos);
				}
				break;
			}

			case FACTORY_BUILD: {
				int numFactories = ai->unittable->factories.size();
				if (numFactories > 1)
					pos = ai->defensematrix->getBestDefendedPos(numFactories);
				float m = mNow/mStorage;
				switch(state) {
					case 0: case 1: case 2: {
						if (m > 0.7f && !taskInProgress(bt) && affordable)
							ai->tasks->addBuildTask(bt, i->second, group, pos);
						break;
					}
					case 3: {
						if (m > 0.6f && !taskInProgress(bt))
							ai->tasks->addBuildTask(bt, i->second, group, pos);
						break;
					}
					case 4: {
						if (m > 0.5f && !taskInProgress(bt))
							ai->tasks->addBuildTask(bt, i->second, group, pos);
						break;
					}
					case 5: {
						if (m > 0.4f && !taskInProgress(bt))
							ai->tasks->addBuildTask(bt, i->second, group, pos);
						break;
					}
					case 6: {
						if (m > 0.3f && !taskInProgress(bt))
							ai->tasks->addBuildTask(bt, i->second, group, pos);
						break;
					}
					default: {
						if (m > 0.2f && !taskInProgress(bt))
							ai->tasks->addBuildTask(bt, i->second, group, pos);
					}
				}
				break;
			}
			
			case BUILD_AG_DEFENSE: case BUILD_AA_DEFENSE: {
				if (!taskInProgress(bt)) {
					pos = ai->defensematrix->getDefenseBuildSite(i->second);
					ai->tasks->addBuildTask(bt, i->second, group, pos);
				}
				break;
			}

			default: {
				if (affordable && !taskInProgress(bt))
					ai->tasks->addBuildTask(bt, i->second, group, goal);
				break;
			}
		}
	}
}

float3 CEconomy::getClosestOpenMetalSpot(CGroup &group) {
	float bestDist = FLT_MAX;
	float3 bestSpot = ZeroVector;
	float3 gpos = group.pos();
	float radius = ai->cb->GetExtractorRadius();

	std::list<float3>::iterator i;
	std::map<int, float3>::iterator j;
	for (i = GameMap::metalspots.begin(); i != GameMap::metalspots.end(); i++) {
		// TODO: compare with actual group properties
		if (i->y < 0.0f)
			continue;
		
		bool taken = false;
		for (j = takenMexes.begin(); j != takenMexes.end(); j++) {
			if ((*i - j->second).Length2D() < radius) {
				taken = true;
				break;
			}
		}
		if (taken) continue;

		float dist = (gpos - *i).Length2D();
		if (dist < bestDist) {
			bestDist = dist;
			bestSpot = *i;
		}
	}
	if (bestSpot != ZeroVector)
		takenMexes[group.key] = bestSpot;

	return bestSpot;
}

void CEconomy::update(int frame) {
	int builderGroupsNum = 0;

	/* See if we can improve our eco by controlling metalmakers */
	controlMetalMakers();

	/* If we are stalling, do something about it */
	preventStalling();

	/* Determine the allowed factory not yet in our arsenal */
	unsigned factory = getAllowedFactory();

	/* Update idle worker groups */
	std::map<int, CGroup*>::iterator i;
	for (i = activeGroups.begin(); i != activeGroups.end(); i++) {
		CGroup *group = i->second;
		CUnit *unit = group->firstUnit();

		// TODO: count only mobile groups? Should we count commander?
		if (group->speed > 0.0001f)
			builderGroupsNum++;

		if (group->busy || !ai->unittable->canPerformTask(*unit)) continue;

		float3 pos = group->pos();

		if (unit->def->isCommander) {
			/* If we are mstalling deal with it */
			if (mstall) {
				buildOrAssist(*group, BUILD_MPROVIDER, MEXTRACTOR|LAND);
				if (group->busy) continue;
			}
			/* If we are estalling deal with it */
			if (estall) {
				buildOrAssist(*group, BUILD_EPROVIDER, EMAKER|LAND);
				if (group->busy) continue;
			}
			/* If we don't have a factory, build one */
			if (ai->unittable->factories.empty()) {
				buildOrAssist(*group, BUILD_FACTORY, type|TECH1);
				if (group->busy) continue;
			}
			/* If we are exceeding and don't have estorage yet, build estorage */
			if (eexceeding && !ai->unittable->factories.empty()) {
				if (ai->unittable->energyStorages.size() >= ai->cfgparser->getMaxTechLevel())
					buildOrAssist(*group, BUILD_ESTORAGE, LAND|MMAKER);
				else
					buildOrAssist(*group, BUILD_ESTORAGE, LAND|ESTORAGE);
				if (group->busy) continue;
			}
			/* If we can assist a lab and it's close enough, do so */
			ATask *task = NULL;
			if ((task = canAssistFactory(*group)) != NULL) {
				ai->tasks->addAssistTask(*task, *group);
				if (group->busy) continue;
			}
		}
		else {
			/* If we are estalling deal with it */
			if (estall) {
				buildOrAssist(*group, BUILD_EPROVIDER, EMAKER|LAND);
				if (group->busy) continue;
			}
			/* If we are mstalling deal with it */
			if (mstall) {
				buildOrAssist(*group, BUILD_MPROVIDER, MEXTRACTOR|LAND);
				if (group->busy) continue;
			}
			/* See if this unit can build our desired factory */
			if (factory > 0) {
				buildOrAssist(*group, BUILD_FACTORY, factory);
				if (group->busy) continue;
			}
			/* See if we can build defense */
			if (ai->defensematrix->getClusters() > ai->unittable->defenses.size()) {
				buildOrAssist(*group, BUILD_AG_DEFENSE, DEFENSE, ANTIAIR);
				if (group->busy) continue;
			}
			/* If we are overflowing energy build a estorage */
			if (eexceeding) {
				if (ai->unittable->energyStorages.size() >= ai->cfgparser->getMaxTechLevel())
					buildOrAssist(*group, BUILD_ESTORAGE, LAND|MMAKER);
				else
					buildOrAssist(*group, BUILD_ESTORAGE, LAND|ESTORAGE);
				if (group->busy) continue;
			}
			/* If we are overflowing metal build an mstorage */
			if (mexceeding) {
				buildOrAssist(*group, BUILD_MSTORAGE, LAND|MSTORAGE);
				if (group->busy) continue;
			}
			/* If both requested, see what is required most */
			if (eRequest && mRequest) {
				if ((mNow / mStorage) > (eNow / eStorage))
					buildOrAssist(*group, BUILD_EPROVIDER, EMAKER|LAND);
				else
					buildOrAssist(*group, BUILD_MPROVIDER, MEXTRACTOR|LAND);
				if (group->busy) continue;
			}
			/* Else just provide that which is requested */
			if (eRequest) {
				buildOrAssist(*group, BUILD_EPROVIDER, EMAKER|LAND);
				if (group->busy) continue;
			}
			if (mRequest) {
				buildOrAssist(*group, BUILD_MPROVIDER, MEXTRACTOR|LAND);
				if (group->busy) continue;
			}
			ATask *task = NULL;
			/* If we can afford to assist a lab and it's close enough, do so */
			if ((task = canAssistFactory(*group)) != NULL) {
				ai->tasks->addAssistTask(*task, *group);
				if (group->busy) continue;
			}
			/* Otherwise just expand */
			if ((mNow / mStorage) > (eNow / eStorage))
				buildOrAssist(*group, BUILD_EPROVIDER, EMAKER|LAND);
			else
				buildOrAssist(*group, BUILD_MPROVIDER, MEXTRACTOR|LAND);
		}
	}

	if (builderGroupsNum < ai->cfgparser->getMaxWorkers() 
	&& (builderGroupsNum < ai->cfgparser->getMinWorkers()))
		ai->wishlist->push(BUILDER, HIGH);
	else if (builderGroupsNum < ai->cfgparser->getMaxWorkers())
		ai->wishlist->push(BUILDER, NORMAL);
}

unsigned CEconomy::getAllowedFactory() {
	int maxTech = ai->cfgparser->getMaxTechLevel();
	int primary = type;
	int secondary = type == KBOT ? VEHICLE : KBOT;
	int tertiary = HOVER;

	// TODO: make universal detection of what factory we can build per tech level
	for (int i = 0; i < maxTech; i++) {
		// assuming TECH1 = 1, TECH2 = 2, TECH3 = 4
		unsigned tech = 1 << i;
		
		/* There is no tech3 vehicle */
		
		if (tech == TECH3 && !ai->unittable->gotFactory(KBOT|tech))
			return KBOT|tech;

		if (!ai->unittable->gotFactory(primary|tech))
			return type|tech;

		if (!ai->unittable->gotFactory(secondary|tech))
			return secondary|tech;

		// TODO: make next decision on map terrain analysis
		bool isT1 = tech == TECH1;
		bool isHooverMap = ai->gamemap->IsHooverMap();
		bool isNewFactory = !ai->unittable->gotFactory(tertiary|tech);
		if (isT1 && isHooverMap && isNewFactory)
			return tertiary|tech;
	}

	return 0;
}

bool CEconomy::taskInProgress(buildType bt) {
	std::map<int, CTaskHandler::BuildTask*>::iterator i;
	for (i = ai->tasks->activeBuildTasks.begin(); i != ai->tasks->activeBuildTasks.end(); i++) {
		if (i->second->bt == bt)
			return true;
	}
	return false;
}

void CEconomy::controlMetalMakers() {
	float eRatio = eNow / eStorage;
	std::map<int, CUnit*>::iterator j;
	if (eRatio < 0.3f) {
		int success = 0;
		for (j = ai->unittable->metalMakers.begin(); j != ai->unittable->metalMakers.end(); j++) {
			CUnit *unit = j->second;
			if(unit->isOn()) {
				unit->setOnOff(false);
				success++;
			}
		}
		if (success > 0) {
			estall = false;
			areMMakersEnabled = false;
			return;
		}
	}

	if (eRatio > 0.7f) {
		int success = 0;
		for (j = ai->unittable->metalMakers.begin(); j != ai->unittable->metalMakers.end(); j++) {
			CUnit *unit = j->second;
			if(!unit->isOn()) {
				unit->setOnOff(true);
				success++;
			}
		}
		if (success > 0) {
			mstall = false;
			areMMakersEnabled = true;
			return;
		}
	}
}

void CEconomy::preventStalling() {
	/* If factorytask is on wait, unwait him */
	std::map<int, CTaskHandler::FactoryTask*>::iterator k;
	for (k = ai->tasks->activeFactoryTasks.begin(); k != ai->tasks->activeFactoryTasks.end(); k++)
		k->second->setWait(false);

	/* If we're not stalling, return */
	if (!mstall && !estall)
		return;

	/* Stop all guarding workers */
	std::map<int,CTaskHandler::AssistTask*>::iterator i;
	for (i = ai->tasks->activeAssistTasks.begin(); i != ai->tasks->activeAssistTasks.end(); i++) {
		/* If the assisting group is moving, continue */
		if (i->second->isMoving)
			continue;

		/* Don't stop those workers that are trying to fix the problem */
		if (i->second->assist->t == BUILD) {
			CTaskHandler::BuildTask* build = dynamic_cast<CTaskHandler::BuildTask*>(i->second->assist);
			if ((mstall || mRequest) && build->bt == BUILD_MPROVIDER)
				continue;

			if ((estall || eRequest) && build->bt == BUILD_EPROVIDER)
				continue;
		}

		/* Don't stop factory assisters, they will be dealt with later */
		if (i->second->assist->t == BUILD && i->second->assist->t != FACTORY_BUILD) {
			i->second->remove();
			return;
		}

		/* Unless it is the commander, he should be fixing the problem */
		if (i->second->group->units.begin()->second->def->isCommander) {
			if ((mstall && !eRequest) || (estall && !mstall)) {
				i->second->remove();
				return;
			}
		}
	}

	/* Wait all factories and their assisters */
	for (k = ai->tasks->activeFactoryTasks.begin(); k != ai->tasks->activeFactoryTasks.end(); k++)
		k->second->setWait(true);
}

void CEconomy::updateIncomes(int frame) {
	incomes++;

	mNowSummed    += ai->cb->GetMetal();
	eNowSummed    += ai->cb->GetEnergy();
	mIncomeSummed += ai->cb->GetMetalIncome();
	eIncomeSummed += ai->cb->GetEnergyIncome();
	mUsageSummed  += ai->cb->GetMetalUsage();
	eUsageSummed  += ai->cb->GetEnergyUsage();
	mStorage       = ai->cb->GetMetalStorage();
	eStorage       = ai->cb->GetEnergyStorage();

	mNow     = ai->cb->GetMetal();
	eNow     = ai->cb->GetEnergy();
	mIncome  = ai->cb->GetMetalIncome();
	eIncome  = ai->cb->GetEnergyIncome();
	mUsage   = alpha*(mUsageSummed / incomes) + (1.0f-alpha)*(ai->cb->GetMetalUsage());
	eUsage   = beta *(eUsageSummed / incomes) + (1.0f-beta) *(ai->cb->GetEnergyUsage());

	std::map<int, CUnit*>::iterator i;
	float mU = 0.0f, eU = 0.0f;
	for (i = ai->unittable->activeUnits.begin(); i != ai->unittable->activeUnits.end(); i++) {
		unsigned int c = i->second->type->cats;
		if (!(c&MMAKER) || !(c&EMAKER) || !(c&MEXTRACTOR)) {
			mU += i->second->type->metalMake;
			eU += i->second->type->energyMake;
		}
	}
	uMIncomeSummed += mU;
	uEIncomeSummed += eU;
	
	uMIncome   = alpha*(uMIncomeSummed / incomes) + (1.0f-alpha)*mU;
	uEIncome   = beta*(uEIncomeSummed / incomes) + (1.0f-beta)*eU;

	mstall     = (mNow < (mStorage*0.1f) && mUsage > mIncome) || mIncome < (mStart*2.0f);
	estall     = (eNow < (eStorage*0.1f) && eUsage > eIncome) || eIncome < (eStart*1.5f);

	mexceeding = (mNow > (mStorage*0.9f) && mUsage < mIncome);
	eexceeding = (eNow > (eStorage*0.9f) && eUsage < eIncome);

	mRequest   = (mNow < (mStorage*0.5f));
	eRequest   = (eNow < (eStorage*0.5f));

	int tstate = ai->cfgparser->determineState(mIncome, eIncome);
	if (tstate != state) {
		char buf[255];
		sprintf(buf, "State changed to %d, activated techlevel %d", tstate, ai->cfgparser->getMaxTechLevel());
		LOG_II(buf);
		state = tstate;
	}
}

ATask* CEconomy::canAssist(buildType t, CGroup &group) {
	std::map<int, CTaskHandler::BuildTask*>::iterator i;
	std::multimap<float, CTaskHandler::BuildTask*> suited;

	for (i = ai->tasks->activeBuildTasks.begin(); i != ai->tasks->activeBuildTasks.end(); i++) {
		CTaskHandler::BuildTask *buildtask = i->second;

		/* Only build tasks we are interested in */
		float travelTime;
		if (buildtask->bt != t || !buildtask->assistable(group, travelTime))
			continue;
		
		suited.insert(std::pair<float, CTaskHandler::BuildTask*>(travelTime, buildtask));
	}

	/* There are no suited tasks that require assistance */
	if (suited.empty())
		return NULL;

	bool isCommander = group.firstUnit()->def->isCommander;

	if (isCommander) {
		float3 g = (suited.begin())->second->pos;
		float eta = ai->pathfinder->getETA(group, g);

		/* Don't pursuit as commander when walkdistance is more then 10 seconds */
		if (eta > 30*10) return NULL;
	}

	return suited.begin()->second;
}

ATask* CEconomy::canAssistFactory(CGroup &group) {
	CUnit *unit = group.units.begin()->second;
	std::map<int, CTaskHandler::FactoryTask*>::iterator i;
	std::map<float, CTaskHandler::FactoryTask*> candidates;
	float3 pos = group.pos();

	for (i = ai->tasks->activeFactoryTasks.begin(); i != ai->tasks->activeFactoryTasks.end(); i++) {
		/* TODO: instead of euclid distance, use pathfinder distance */
		float dist = (pos - i->second->pos).Length2D();
		candidates[dist] = i->second;
	}

	if (candidates.empty())
		return NULL;

	if (unit->def->isCommander)
		return candidates.begin()->second;

	std::map<float, CTaskHandler::FactoryTask*>::iterator j;
	for (j = candidates.begin(); j != candidates.end(); j++) {
		if (!j->second->assistable(group))
			continue;
		return j->second;
	}

	return NULL;
}

bool CEconomy::canAffordToBuild(UnitType *builder, UnitType *utToBuild) {
	/* NOTE: "Salary" is provided every 32 logical frames */
	float buildTime   = (utToBuild->def->buildTime / builder->def->buildSpeed) * 32.0f;
	float mCost       = utToBuild->def->metalCost;
	float eCost       = utToBuild->def->energyCost;
	float mPrediction = (mIncome - mUsage - mCost/buildTime)*buildTime - mCost + mNow;
	float ePrediction = (eIncome - eUsage - eCost/buildTime)*buildTime - eCost + eNow;
	mRequest          = mPrediction < 0.0f;
	eRequest          = ePrediction < 0.0f;
	return (mPrediction >= 0.0f && ePrediction >= 0.0f && mNow/mStorage >= 0.1f);
}