Debian Codegraph @

engine/ai/ai.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name ai.cpp - The computer player AI main file. */
11 //
12 // (c) Copyright 2000-2009 by Lutz Sammer, Ludovic Pollet, and
13 // Jimmy Salmon
14 //
15 // This program is free software; you can redistribute it and/or modify
16 // it under the terms of the GNU General Public License as published by
17 // the Free Software Foundation; only version 2 of the License.
18 //
19 // This program is distributed in the hope that it will be useful,
20 // but WITHOUT ANY WARRANTY; without even the implied warranty of
21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 // GNU General Public License for more details.
23 //
24 // You should have received a copy of the GNU General Public License
25 // along with this program; if not, write to the Free Software
26 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 // 02111-1307, USA.
28 //
29
30
31 //@{
32
33 //----------------------------------------------------------------------------
34 // Documentation
35 //----------------------------------------------------------------------------
36
37 /**
38 ** @page AiModule Module - AI
39 **
40 ** @section aibasics What is it?
41 **
42 ** @subsection aiscripted What is scripted AI?
43 **
44 ** The AI script tells the engine build 4 workers, than build 3 footman,
45 ** than attack the player, than sleep 100 frames.
46 **
47 ** @section API The AI API
48 **
49 ** @subsection aimanage Management calls
50 **
51 ** Manage the inititialse and cleanup of the AI players.
52 **
53 ** ::InitAiModule()
54 **
55 ** Initialise all global varaibles and structures.
56 ** Called before AiInit, or before game loading.
57 **
58 ** ::AiInit(::CPlayer)
59 **
60 ** Called for each player, to setup the AI structures
61 ** CPlayer::Ai in the player structure and possibly call
62 ** AI initialization scripts. It can use CPlayer::AiName to
63 ** select different AI's.
64 **
65 ** ::CleanAi()
66 **
67 ** Called to release all the memory for all AI structures.
68 ** Must handle self which players contains AI structures.
69 **
70 ** ::SaveAi(::FILE *)
71 **
72 ** Save the AI structures of all players to file.
73 ** Must handle self which players contains AI structures.
74 **
75 **
76 ** @subsection aipcall Periodic calls
77 **
78 ** This functions are called regular for all AI players.
79 **
80 ** ::AiEachCycle(::Player)
81 **
82 ** Called each game cycle, to handle quick checks, which needs
83 ** less CPU.
84 **
85 ** ::AiEachSecond(::Player)
86 **
87 ** Called each second, to handle more CPU intensive things.
88 **
89 **
90 ** @subsection aiecall Event call-backs
91 **
92 ** This functions are called, when some special events happens.
93 **
94 ** ::AiHelpMe()
95 **
96 ** Called if a unit owned by the AI is attacked.
97 **
98 ** ::AiUnitKilled()
99 **
100 ** Called if a unit owned by the AI is killed.
101 **
102 ** ::AiWorkComplete()
103 **
104 ** Called if a unit has completed its work.
105 **
106 ** ::AiCanNotBuild()
107 **
108 ** Called if the AI unit can't build the requested unit-type.
109 **
110 ** ::AiCanNotReach()
111 **
112 ** Called if the AI unit can't reach the building place.
113 **
114 ** ::AiTrainingComplete()
115 **
116 ** Called if AI unit has completed training a new unit.
117 */
118
119 /*----------------------------------------------------------------------------
120 -- Includes
121 ----------------------------------------------------------------------------*/
122
123 #include <string.h>
124 #include <stdio.h>
125 #include <stdlib.h>
126
127 #include "stratagus.h"
128
129 #include "player.h"
130 #include "unit.h"
131 #include "unittype.h"
132 #include "upgrade.h"
133 #include "script.h"
134 #include "actions.h"
135 #include "map.h"
136 #include "pathfinder.h"
137 #include "ai_local.h"
138 #include "iolib.h"
139
140 /*----------------------------------------------------------------------------
141 -- Variables
142 ----------------------------------------------------------------------------*/
143
144 /** List of all AI types.
145 * DefineAiType keeps this in sync with the AiTypes Lua variable. */
146 std::vector<CAiType *> AiTypes;
147
148 AiHelper AiHelpers; /// AI helper variables
149
150 PlayerAi *AiPlayer; /// Current AI player
151
152 /*----------------------------------------------------------------------------
153 -- Lowlevel functions
154 ----------------------------------------------------------------------------*/
155
156 /**
157 ** Execute a Lua function of the AI type.
158 */
159 static void AiExecuteFunction(const char *field)
160 {
161 if (AiPlayer->AiType != NULL)
162 {
163 lua_getfield(Lua, LUA_GLOBALSINDEX, "AiTypes");
164 lua_getfield(Lua, -1, AiPlayer->AiType->Name.c_str());
165 lua_getfield(Lua, -1, field);
166 if (!lua_isnil(Lua, -1))
167 {
168 LuaCall(0, 1); // removes the function from the stack
169 lua_pop(Lua, 2); // remove the tables too
170 }
171 else
172 {
173 lua_pop(Lua, 3);
174 }
175 }
176 }
177
178 /**
179 ** Check if everything is fine, send new requests to resource manager.
180 */
181 static void AiCheckUnits()
182 {
183 int counter[UnitTypeMax];
184 int attacking[UnitTypeMax];
185 const int *unit_types_count;
186 int i;
187
188 memset(counter, 0, sizeof(counter));
189 memset(attacking, 0, sizeof(attacking));
190
191 //
192 // Count the already made build requests.
193 //
194 for (i = 0; i < (int)AiPlayer->UnitTypeBuilt.size(); ++i)
195 {
196 AiBuildQueue *queue = &AiPlayer->UnitTypeBuilt[i];
197 counter[queue->Type->Slot] += queue->Want;
198 }
199
200 unit_types_count = AiPlayer->Player->UnitTypesCount;
201
202 //
203 // Look if some unit-types are missing.
204 //
205 for (i = 0; i < (int)AiPlayer->UnitTypeRequests.size(); ++i)
206 {
207 int slot = AiPlayer->UnitTypeRequests[i].Type->Slot;
208 int count = AiPlayer->UnitTypeRequests[i].Count;
209 int e;
210
211 //
212 // Add equivalent units
213 //
214 e = unit_types_count[slot];
215 if (slot < (int)AiHelpers.Equiv.size())
216 {
217 for (int j = 0; j < (int)AiHelpers.Equiv[slot].size(); ++j)
218 {
219 e += unit_types_count[AiHelpers.Equiv[slot][j]->Slot];
220 }
221 }
222
223 if (count > e + counter[slot])
224 {
225 // Request it.
226 AiAddUnitTypeRequest(AiPlayer->UnitTypeRequests[i].Type,
227 count - e - counter[slot]);
228 counter[slot] += count - e - counter[slot];
229 }
230 counter[slot] -= count;
231 }
232
233 //
234 // Look through the forces what is missing.
235 //
236 for (i = AI_MAX_FORCES; i < AI_MAX_ATTACKING_FORCES; ++i)
237 {
238 for (int j = 0; j < (int)AiPlayer->Force[i].Units.size(); ++j)
239 {
240 attacking[AiPlayer->Force[i].Units[j]->Type->Slot]++;
241 }
242 }
243
244 //
245 // create missing units
246 //
247 for (i = 0; i < AI_MAX_FORCES; ++i)
248 {
249 // No troops for attacking force
250 if (!AiPlayer->Force[i].Defending && AiPlayer->Force[i].Attacking)
251 {
252 continue;
253 }
254
255 for (int j = 0; j < (int)AiPlayer->Force[i].UnitTypes.size(); ++j)
256 {
257 const AiUnitType *aiut = &AiPlayer->Force[i].UnitTypes[j];
258 int slot = aiut->Type->Slot;
259 int want = aiut->Want;
260 if (want > unit_types_count[slot] + counter[slot] - attacking[slot])
261 {
262 // Request it.
263 AiAddUnitTypeRequest(aiut->Type,
264 want - (unit_types_count[slot] + counter[slot] - attacking[slot]));
265 counter[slot] += want - (unit_types_count[slot] + counter[slot] - attacking[slot]);
266 AiPlayer->Force[i].Completed = false;
267 }
268 counter[slot] -= want;
269 }
270 }
271 }
272
273 /*----------------------------------------------------------------------------
274 -- Functions
275 ----------------------------------------------------------------------------*/
276
277 /**
278 ** Save state of player AI.
279 **
280 ** @param file Output file.
281 ** @param plynr Player number.
282 ** @param ai Player AI.
283 */
284 static void SaveAiPlayer(CFile *file, int plynr, PlayerAi *ai)
285 {
286 int i;
287
288 file->printf("DefineAiPlayer(%d,\n", plynr);
289 file->printf(" \"ai-type\", \"%s\",\n", ai->AiType->Name.c_str());
290
291 file->printf(" \"script-debug\", %s,\n", ai->ScriptDebug ? "true" : "false");
292 file->printf(" \"sleep-cycles\", %lu,\n", ai->SleepCycles);
293
294 //
295 // All forces
296 //
297 for (i = 0; i < AI_MAX_ATTACKING_FORCES; ++i)
298 {
299 int j;
300
301 file->printf(" \"force\", {%d, %s%s%s", i,
302 ai->Force[i].Completed ? "\"complete\"," : "\"recruit\",",
303 ai->Force[i].Attacking ? " \"attack\"," : "",
304 ai->Force[i].Defending ? " \"defend\"," : "");
305
306 file->printf(" \"role\", ");
307 switch (ai->Force[i].Role)
308 {
309 case AiForceRoleAttack:
310 file->printf("\"attack\",");
311 break;
312 case AiForceRoleDefend:
313 file->printf("\"defend\",");
314 break;
315 default:
316 file->printf("\"unknown-%d\",", ai->Force[i].Role);
317 break;
318 }
319
320 file->printf("\n \"types\", { ");
321 for (j = 0; j < (int)ai->Force[i].UnitTypes.size(); ++j)
322 {
323 const AiUnitType *aut = &ai->Force[i].UnitTypes[j];
324 file->printf("%d, \"%s\", ", aut->Want, aut->Type->Ident.c_str());
325 }
326 file->printf("},\n \"units\", {");
327 for (j = 0; j < (int)ai->Force[i].Units.size(); ++j)
328 {
329 const CUnit *aiunit = ai->Force[i].Units[j];
330 file->printf(" %d, \"%s\",", UnitNumber(aiunit),
331 aiunit->Type->Ident.c_str());
332 }
333 file->printf("},\n \"state\", %d, \"goalx\", %d, \"goaly\", %d,",
334 ai->Force[i].State, ai->Force[i].GoalX, ai->Force[i].GoalY);
335 file->printf("},\n");
336 }
337
338 file->printf(" \"needed\", {");
339 for (i = 0; i < MaxCosts; ++i)
340 {
341 file->printf("\"%s\", %d, ", DefaultResourceNames[i].c_str(), ai->Needed[i]);
342 }
343 file->printf("},\n");
344
345 file->printf(" \"need-mask\", {");
346 for (i = 0; i < MaxCosts; ++i)
347 {
348 if (ai->NeededMask & (1 << i))
349 {
350 file->printf("\"%s\", ", DefaultResourceNames[i].c_str());
351 }
352 }
353 file->printf("},\n");
354
355 //
356 // Requests
357 //
358 file->printf(" \"last-can-not-move-cycle\", %lu,\n", ai->LastCanNotMoveGameCycle);
359 file->printf(" \"unit-type\", {");
360 for (i = 0; i < (int)ai->UnitTypeRequests.size(); ++i)
361 {
362 file->printf("\"%s\", ", ai->UnitTypeRequests[i].Type->Ident.c_str());
363 file->printf("%d, ", ai->UnitTypeRequests[i].Count);
364 }
365 file->printf("},\n");
366
367 //
368 // Building queue
369 //
370 file->printf(" \"building\", {");
371 for (i = 0; i < (int)ai->UnitTypeBuilt.size(); ++i)
372 {
373 const AiBuildQueue *queue = &ai->UnitTypeBuilt[i];
374 file->printf("\"%s\", %d, %d, ", queue->Type->Ident.c_str(), queue->Made, queue->Want);
375 }
376 file->printf("},\n");
377
378 file->printf(" \"repair-building\", %u,\n", ai->LastRepairBuilding);
379
380 file->printf(" \"repair-workers\", {");
381 for (i = 0; i < UnitMax; ++i)
382 {
383 if (ai->TriedRepairWorkers[i])
384 {
385 file->printf("%d, %d, ", i, ai->TriedRepairWorkers[i]);
386 }
387 }
388 file->printf("})\n\n");
389 }
390
391 /**
392 ** Save state of player AIs.
393 **
394 ** @param file Output file.
395 */
396 static void SaveAiPlayers(CFile *file)
397 {
398 for (int p = 0; p < PlayerMax; ++p)
399 {
400 if (Players[p].Ai)
401 {
402 SaveAiPlayer(file, p, Players[p].Ai);
403 }
404 }
405 }
406
407 /**
408 ** Save state of AI to file.
409 **
410 ** @param file Output file.
411 */
412 void SaveAi(CFile *file)
413 {
414 file->printf("\n--- -----------------------------------------\n");
415
416 SaveAiPlayers(file);
417 }
418
419 /**
420 ** Setup all at start.
421 **
422 ** @param player The player structure pointer.
423 */
424 void AiInit(CPlayer *player)
425 {
426 PlayerAi *pai;
427 CAiType *ait;
428 CAiType *passive = NULL;
429 size_t i;
430
431 pai = new PlayerAi;
432 if (!pai)
433 {
434 fprintf(stderr, "Out of memory.\n");
435 exit(0);
436 }
437
438 pai->Player = player;
439 ait = NULL;
440
441 DebugPrint("Player %d (%s) looking for \"%s\"\n" _C_
442 player->Index _C_
443 player->Name.c_str() _C_
444 player->AiName.c_str());
445
446 //
447 // Search correct AI type.
448 //
449 if (AiTypes.empty())
450 {
451 fprintf(stderr, "AI: Got no scripts at all! You need at least the \"ai-passive\" fallback script.\n");
452 fprintf(stderr, "AI: Look at the DefineAi() documentation.\n");
453 Exit(1);
454 }
455 for (i = 0; i < AiTypes.size(); ++i)
456 {
457 ait = AiTypes[i];
458 if (player->AiName.empty() || ait->Name == player->AiName)
459 {
460 break;
461 }
462
463 if (ait->Name == "ai-passive")
464 {
465 passive = ait;
466 }
467 }
468 if (i == AiTypes.size())
469 {
470 DebugPrint("AI: Script \"%s\" not found!\n" _C_
471 player->AiName.c_str());
472
473 // Fall back to the passive script only, because it
474 // does not require any kind of saved AI state.
475 // Furthermore, it does not alter the existing AI
476 // state, so the game can be saved with this fallback
477 // and then loaded into a build that does support the
478 // correct script.
479 if (passive == NULL)
480 {
481 fprintf(stderr, "AI: Script \"ai-passive\" not found either! Cannot continue.\n");
482 Exit(1);
483 }
484
485 ait = passive;
486 DebugPrint("AI: Using fallback \"%s\".\n" _C_
487 ait->Name.c_str());
488 }
489
490 pai->AiType = ait;
491 player->Ai = pai;
492
493 // Initialize the AI state of the player if it has not been
494 // already initialized, i.e. we're not loading a saved game.
495 lua_getfield(Lua, LUA_GLOBALSINDEX, "AiState"); // stack: AiState
496 Assert(lua_istable(Lua, -1));
497 lua_pushnumber(Lua, player->Index); // stack: AiState, player
498 lua_gettable(Lua, -2); // stack: AiState, AiState[player]
499 bool needs_init = lua_isnil(Lua, -1);
500 lua_pop(Lua, 2);
501 if (needs_init)
502 {
503 AiPlayer = pai;
504 AiExecuteFunction("Init");
505 }
506
507 // Cause a reproduceable crash if something expected us to
508 // preserve the value of AiPlayer.
509 AiPlayer = NULL;
510 }
511
512 /**
513 ** Initialize global structures of the AI
514 */
515 void InitAiModule()
516 {
517 AiResetUnitTypeEquiv();
518 }
519
520 /**
521 ** Cleanup the AI in order to enable to restart a game.
522 */
523 void CleanAi()
524 {
525 for (int p = 0; p < PlayerMax; ++p)
526 {
527 if (Players[p].Ai)
528 {
529 delete Players[p].Ai;
530 Players[p].Ai = NULL;
531 }
532 }
533 }
534
535 /**
536 ** Free all AI resources.
537 */
538 void FreeAi()
539 {
540 CleanAi();
541
542 //
543 // Free AiTypes.
544 //
545 for (size_t i = 0; i < AiTypes.size(); ++i)
546 {
547 delete AiTypes[i];
548 }
549 AiTypes.clear();
550
551 //
552 // Free AiHelpers.
553 //
554 AiHelpers.Train.clear();
555 AiHelpers.Build.clear();
556 AiHelpers.Repair.clear();
557 AiHelpers.UnitLimit.clear();
558 AiHelpers.Equiv.clear();
559
560 AiResetUnitTypeEquiv();
561 }
562
563 /*----------------------------------------------------------------------------
564 -- Support functions
565 ----------------------------------------------------------------------------*/
566
567 /**
568 ** Remove unit-type from build list.
569 **
570 ** @param pai Computer AI player.
571 ** @param type Unit-type which is now available.
572 ** @return True, if unit-type was found in list.
573 */
574 static int AiRemoveFromBuilt2(PlayerAi *pai, const CUnitType *type)
575 {
576 std::vector<AiBuildQueue>::iterator i;
577
578 for (i = pai->UnitTypeBuilt.begin(); i != pai->UnitTypeBuilt.end(); ++i)
579 {
580 Assert((*i).Want);
581 if (type == (*i).Type && (*i).Made)
582 {
583 --(*i).Made;
584 if (!--(*i).Want)
585 {
586 pai->UnitTypeBuilt.erase(i);
587 }
588 return 1;
589 }
590 }
591 return 0;
592 }
593
594 /**
595 ** Remove unit-type from build list.
596 **
597 ** @param pai Computer AI player.
598 ** @param type Unit-type which is now available.
599 */
600 static void AiRemoveFromBuilt(PlayerAi *pai, const CUnitType *type)
601 {
602 int equivalents[UnitTypeMax + 1];
603 int equivalentsCount;
604
605 if (AiRemoveFromBuilt2(pai, type))
606 {
607 return;
608 }
609
610 //
611 // This could happen if an upgrade is ready, look for equivalent units.
612 //
613 equivalentsCount = AiFindUnitTypeEquiv(type, equivalents);
614 for (int i = 0; i < equivalentsCount; ++i)
615 {
616 if (AiRemoveFromBuilt2(pai, UnitTypes[equivalents[i]]))
617 {
618 return;
619 }
620 }
621
622 if (pai->Player == ThisPlayer)
623 {
624 DebugPrint("My guess is that you built something under ai me. naughty boy!\n");
625 return;
626 }
627
628 Assert(0);
629 }
630
631 /**
632 ** Reduce made unit-type from build list.
633 **
634 ** @param pai Computer AI player.
635 ** @param type Unit-type which is now available.
636 ** @return True if the unit-type could be reduced.
637 */
638 static int AiReduceMadeInBuilt2(PlayerAi *pai, const CUnitType *type)
639 {
640 std::vector<AiBuildQueue>::iterator i;
641
642 for (i = pai->UnitTypeBuilt.begin(); i != pai->UnitTypeBuilt.end(); ++i)
643 {
644 if (type == (*i).Type && (*i).Made)
645 {
646 (*i).Made--;
647 return 1;
648 }
649 }
650 return 0;
651 }
652
653 /**
654 ** Reduce made unit-type from build list.
655 **
656 ** @param pai Computer AI player.
657 ** @param type Unit-type which is now available.
658 */
659 static void AiReduceMadeInBuilt(PlayerAi *pai, const CUnitType *type)
660 {
661 int equivs[UnitTypeMax + 1];
662 int equivnb;
663
664 if (AiReduceMadeInBuilt2(pai, type))
665 {
666 return;
667 }
668 //
669 // This could happen if an upgrade is ready, look for equivalent units.
670 //
671 equivnb = AiFindUnitTypeEquiv(type, equivs);
672
673 for (size_t i = 0; i < (size_t)equivnb; ++i)
674 {
675 if (AiReduceMadeInBuilt2(pai, UnitTypes[equivs[i]]))
676 {
677 return;
678 }
679 }
680
681 Assert(0);
682 }
683
684 /*----------------------------------------------------------------------------
685 -- Callback Functions
686 ----------------------------------------------------------------------------*/
687
688 /**
689 ** Called if a Unit is Attacked
690 **
691 ** @param attacker Pointer to attacker unit.
692 ** @param defender Pointer to unit that is being attacked.
693 */
694 void AiHelpMe(const CUnit *attacker, CUnit *defender)
695 {
696 PlayerAi *pai;
697 CUnit *aiunit;
698 int force;
699 int destx, desty;
700
701 DebugPrint("%d: %d(%s) attacked at %d,%d\n" _C_
702 defender->Player->Index _C_ UnitNumber(defender) _C_
703 defender->Type->Ident.c_str() _C_ defender->X _C_ defender->Y);
704
705 AiPlayer = pai = defender->Player->Ai;
706 if (pai->Force[0].Attacking)
707 {
708 // Force 0 busy
709 return;
710 }
711
712 //
713 // If unit belongs to an attacking force, don't defend it.
714 //
715 for (force = 0; force < AI_MAX_ATTACKING_FORCES; ++force)
716 {
717 if (!pai->Force[force].Attacking)
718 {
719 // none attacking
720 // FIXME, send the force for help
721 continue;
722 }
723
724 for (size_t i = 0; i < pai->Force[force].Units.size(); ++i)
725 {
726 aiunit = pai->Force[force].Units[i];
727 if (defender == aiunit)
728 {
729 return;
730 }
731 }
732 }
733
734 //
735 // Send forces
736 //
737 destx = attacker ? attacker->X : defender->X;
738 desty = attacker ? attacker->Y : defender->Y;
739
740 // Send force 0 defending
741 AiAttackWithForceAt(0, destx, desty);
742 pai->Force[0].Defending = true;
743
744 // Also send force 1 if not already attacking
745 if (!pai->Force[1].Attacking)
746 {
747 pai->Force[1].Defending = true;
748 AiAttackWithForceAt(1, destx, desty);
749 }
750 }
751
752 /**
753 ** Called when a unit is killed.
754 **
755 ** @param unit Pointer to unit.
756 */
757 void AiUnitKilled(CUnit *unit)
758 {
759 DebugPrint("%d: %d(%s) killed\n" _C_
760 unit->Player->Index _C_ UnitNumber(unit) _C_ unit->Type->Ident.c_str());
761
762 Assert(unit->Player->Type != PlayerPerson);
763
764 // FIXME: must handle all orders...
765 switch (unit->Orders[0]->Action)
766 {
767 case UnitActionStill:
768 case UnitActionAttack:
769 case UnitActionMove:
770 break;
771
772 case UnitActionBuilt:
773 DebugPrint("%d: %d(%s) killed, under construction!\n" _C_
774 unit->Player->Index _C_ UnitNumber(unit) _C_ unit->Type->Ident.c_str());
775 AiReduceMadeInBuilt(unit->Player->Ai, unit->Type);
776 break;
777
778 case UnitActionBuild:
779 DebugPrint("%d: %d(%s) killed, with order %s!\n" _C_
780 unit->Player->Index _C_ UnitNumber(unit) _C_
781 unit->Type->Ident.c_str() _C_ unit->Orders[0]->Type->Ident.c_str());
782 if (!unit->Orders[0]->Goal)
783 {
784 AiReduceMadeInBuilt(unit->Player->Ai, unit->Orders[0]->Type);
785 }
786 break;
787
788 default:
789 DebugPrint("FIXME: %d: %d(%s) killed, with order %d!\n" _C_
790 unit->Player->Index _C_ UnitNumber(unit) _C_
791 unit->Type->Ident.c_str() _C_ unit->Orders[0]->Action);
792 break;
793 }
794 }
795
796 /**
797 ** Called when work complete (Buildings).
798 **
799 ** @param unit The unit that was building the building.
800 ** @param newUnit New unit that was built.
801 */
802 void AiWorkComplete(CUnit *unit, CUnit *newUnit)
803 {
804 if (unit)
805 {
806 DebugPrint("%d: %d(%s) build %s at %d,%d completed\n" _C_
807 newUnit->Player->Index _C_ UnitNumber(unit) _C_ unit->Type->Ident.c_str() _C_
808 newUnit->Type->Ident.c_str() _C_ unit->X _C_ unit->Y);
809 }
810 else
811 {
812 DebugPrint("%d: building %s at %d,%d completed\n" _C_
813 newUnit->Player->Index _C_ newUnit->Type->Ident.c_str() _C_ newUnit->X _C_ newUnit->Y);
814 }
815
816 Assert(newUnit->Player->Type != PlayerPerson);
817 AiRemoveFromBuilt(newUnit->Player->Ai, newUnit->Type);
818 }
819
820 /**
821 ** Called if building can't be built.
822 **
823 ** @param unit The unit trying to build.
824 ** @param unitType Unit type trying to be built.
825 */
826 void AiCanNotBuild(CUnit *unit, const CUnitType *unitType)
827 {
828 DebugPrint("%d: %d(%s) Can't build %s at %d,%d\n" _C_
829 unit->Player->Index _C_ UnitNumber(unit) _C_ unit->Type->Ident.c_str() _C_
830 unitType->Ident.c_str() _C_ unit->X _C_ unit->Y);
831
832 Assert(unit->Player->Type != PlayerPerson);
833 AiReduceMadeInBuilt(unit->Player->Ai, unitType);
834 }
835
836 /**
837 ** Called if building place can't be reached.
838 **
839 ** @param unit The unit trying to build.
840 ** @param unitType Unit type trying to be built.
841 */
842 void AiCanNotReach(CUnit *unit, const CUnitType *unitType)
843 {
844 Assert(unit->Player->Type != PlayerPerson);
845 AiReduceMadeInBuilt(unit->Player->Ai, unitType);
846 }
847
848 /**
849 ** Try to move a unit that's in the way
850 */
851 static void AiMoveUnitInTheWay(CUnit *unit)
852 {
853 static int dirs[8][2] = {{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};
854 int ux0;
855 int uy0;
856 int ux1;
857 int uy1;
858 int bx0;
859 int by0;
860 int bx1;
861 int by1;
862 int x;
863 int y;
864 int trycount,i;
865 CUnit *blocker;
866 CUnitType *unittype;
867 CUnitType *blockertype;
868 CUnit *movableunits[16];
869 int movablepos[16][2];
870 int movablenb;
871
872 AiPlayer = unit->Player->Ai;
873 unittype = unit->Type;
874
875 ux0 = unit->X;
876 uy0 = unit->Y;
877 ux1 = ux0 + unittype->TileWidth - 1;
878 uy1 = uy0 + unittype->TileHeight - 1;
879
880 movablenb = 0;
881
882
883 // Try to make some unit moves around it
884 for (i = 0; i < NumUnits; ++i)
885 {
886 blocker = Units[i];
887
888 if (blocker->IsUnusable())
889 {
890 continue;
891 }
892
893 if (!blocker->IsIdle())
894 {
895 continue;
896 }
897
898 if (blocker->Player != unit->Player)
899 {
900 // Not allied
901 if (!(blocker->Player->Allied & (1 << unit->Player->Index)))
902 {
903 continue;
904 }
905 }
906
907 blockertype = blocker->Type;
908
909 if (blockertype->UnitType != unittype->UnitType)
910 {
911 continue;
912 }
913
914 if (!CanMove(blocker))
915 {
916 continue;
917 }
918
919 bx0 = blocker->X;
920 by0 = blocker->Y;
921 bx1 = bx0 + blocker->Type->TileWidth - 1;
922 by1 = by0 + blocker->Type->TileHeight - 1;;
923
924 // Check for collision
925 if (!((ux0 == bx1 + 1 || ux1 == bx0 - 1) &&
926 (std::max(by0, uy0) <= std::min(by1, uy1))) &&
927 !((uy0 == by1 + 1 || uy1 == by0 - 1) &&
928 (std::max(bx0, ux0) <= std::min(bx1, ux1))))
929 {
930 continue;
931 }
932
933 if (unit == blocker)
934 {
935 continue;
936 }
937
938 // Move blocker in a rand dir
939 i = SyncRand() & 7;
940 trycount = 8;
941 while (trycount > 0)
942 {
943 i = (i + 1) & 7;
944 --trycount;
945
946 x = blocker->X + dirs[i][0];
947 y = blocker->Y + dirs[i][1];
948
949 // Out of the map => no !
950 if (x < 0 || y < 0 || x >= Map.Info.MapWidth || y >= Map.Info.MapHeight)
951 {
952 continue;
953 }
954 // move to blocker ? => no !
955 if (x == ux0 && y == uy0)
956 {
957 continue;
958 }
959
960 movableunits[movablenb] = blocker;
961 movablepos[movablenb][0] = x;
962 movablepos[movablenb][1] = y;
963
964 ++movablenb;
965 trycount = 0;
966 }
967 if (movablenb >= 16)
968 {
969 break;
970 }
971 }
972
973 // Don't move more than 1 unit.
974 if (movablenb)
975 {
976 i = SyncRand() % movablenb;
977 CommandMove(movableunits[i], movablepos[i][0], movablepos[i][1], FlushCommands);
978 }
979 }
980
981 /**
982 ** Called if a unit can't move. Try to move unit in the way
983 **
984 ** @param unit Pointer to unit what builds the building.
985 **
986 ** @pre The unit's field flags must have been marked
987 ** on the map; see MarkUnitFieldFlags.
988 */
989 void AiCanNotMove(CUnit *unit)
990 {
991 // Please do not use UnmarkUnitFieldFlags and MarkUnitFieldFlags
992 // around AiCanNotMove calls.
993 Assert((Map.Field(unit->X, unit->Y)->Flags & unit->Type->FieldFlags) != 0);
994
995 AiPlayer = unit->Player->Ai;
996
997 if (GameCycle >= AiPlayer->LastCanNotMoveGameCycle + CYCLES_PER_SECOND)
998 {
999 int gx, gy, gw, gh;
1000 int minrange, maxrange;
1001
1002 if (unit->Orders[0]->Goal)
1003 {
1004 gw = unit->Orders[0]->Goal->Type->TileWidth;
1005 gh = unit->Orders[0]->Goal->Type->TileHeight;
1006 gx = unit->Orders[0]->Goal->X;
1007 gy = unit->Orders[0]->Goal->Y;
1008 maxrange = unit->Orders[0]->Range;
1009 minrange = unit->Orders[0]->MinRange;
1010 }
1011 else
1012 {
1013 // Take care of non square goals :)
1014 // If goal is non square, range states a non-existant goal rather
1015 // than a tile.
1016 gw = unit->Orders[0]->Width;
1017 gh = unit->Orders[0]->Height;
1018 maxrange = unit->Orders[0]->Range;
1019 minrange = unit->Orders[0]->MinRange;
1020 gx = unit->Orders[0]->X;
1021 gy = unit->Orders[0]->Y;
1022 }
1023
1024 if (unit->Type->UnitType == UnitTypeFly ||
1025 PlaceReachable(unit, gx, gy, gw, gh, minrange, maxrange))
1026 {
1027 // Path probably closed by unit here
1028 AiMoveUnitInTheWay(unit);
1029 }
1030 }
1031
1032 AiPlayer->LastCanNotMoveGameCycle = GameCycle;
1033 }
1034
1035 /**
1036 ** Called when training of a unit is completed.
1037 **
1038 ** @param unit Unit that trained the new unit.
1039 ** @param newUnit The new unit.
1040 */
1041 void AiTrainingComplete(CUnit *unit, CUnit *newUnit)
1042 {
1043 DebugPrint("%d: %d(%s) training %s at %d,%d completed\n" _C_
1044 unit->Player->Index _C_ UnitNumber(unit) _C_ unit->Type->Ident.c_str() _C_
1045 newUnit->Type->Ident.c_str() _C_ unit->X _C_ unit->Y);
1046
1047 Assert(unit->Player->Type != PlayerPerson);
1048
1049 AiRemoveFromBuilt(unit->Player->Ai, newUnit->Type);
1050
1051 AiPlayer = unit->Player->Ai;
1052 AiCleanForces();
1053 AiAssignToForce(newUnit);
1054 }
1055
1056 /**
1057 ** This is called for each player, each game cycle.
1058 **
1059 ** @param player The player structure pointer.
1060 */
1061 void AiEachCycle(CPlayer *player)
1062 {
1063 AiPlayer = player->Ai;
1064 }
1065
1066 /**
1067 ** This is called for each player each second.
1068 **
1069 ** @param player The player structure pointer.
1070 */
1071 void AiEachSecond(CPlayer *player)
1072 {
1073 AiPlayer = player->Ai;
1074 Assert(AiPlayer != NULL);
1075
1076 // Advance script
1077 AiExecuteFunction("EachSecond");
1078
1079 // Look if everything is fine.
1080 AiCheckUnits();
1081
1082 // Handle the resource manager.
1083 AiResourceManager();
1084
1085 // Handle the force manager.
1086 AiForceManager();
1087
1088 // Check for magic actions.
1089 AiCheckMagic();
1090 }
1091
1092 //@}