1 /***********************************************************************
2  Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License as published by
5    the Free Software Foundation; either version 2, or (at your option)
6    any later version.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 ***********************************************************************/
13 
14 #ifdef HAVE_CONFIG_H
15 #include <fc_config.h>
16 #endif
17 
18 /* utility */
19 #include "bitvector.h"
20 #include "log.h"
21 #include "mem.h"
22 #include "shared.h"
23 
24 /* common */
25 #include "city.h"
26 #include "combat.h"
27 #include "game.h"
28 #include "government.h"
29 #include "map.h"
30 #include "movement.h"
31 #include "packets.h"
32 #include "player.h"
33 #include "unit.h"
34 #include "unitlist.h"
35 
36 /* common/aicore */
37 #include "citymap.h"
38 #include "pf_tools.h"
39 
40 /* server */
41 #include "barbarian.h"
42 #include "citytools.h"
43 #include "cityturn.h"
44 #include "maphand.h"
45 #include "plrhand.h"
46 #include "score.h"
47 #include "srv_log.h"
48 #include "unithand.h"
49 #include "unittools.h"
50 
51 /* server/advisors */
52 #include "advdata.h"
53 #include "advgoto.h"
54 #include "advtools.h"
55 #include "autosettlers.h"
56 #include "infracache.h" /* adv_city */
57 
58 /* ai */
59 #include "handicaps.h"
60 
61 /* ai/default */
62 #include "aidata.h"
63 #include "aiferry.h"
64 #include "aiguard.h"
65 #include "ailog.h"
66 #include "aiplayer.h"
67 #include "aitech.h"
68 #include "aiunit.h"
69 #include "daimilitary.h"
70 
71 #include "aitools.h"
72 
73 /**************************************************************************
74   Return the (untranslated) rule name of the ai_unit_task.
75   You don't have to free the return pointer.
76 **************************************************************************/
dai_unit_task_rule_name(const enum ai_unit_task task)77 const char *dai_unit_task_rule_name(const enum ai_unit_task task)
78 {
79   switch(task) {
80    case AIUNIT_NONE:
81      return "None";
82    case AIUNIT_AUTO_SETTLER:
83      return "Auto settler";
84    case AIUNIT_BUILD_CITY:
85      return "Build city";
86    case AIUNIT_DEFEND_HOME:
87      return "Defend home";
88    case AIUNIT_ATTACK:
89      return "Attack";
90    case AIUNIT_ESCORT:
91      return "Escort";
92    case AIUNIT_EXPLORE:
93      return "Explore";
94    case AIUNIT_RECOVER:
95      return "Recover";
96    case AIUNIT_HUNTER:
97      return "Hunter";
98    case AIUNIT_TRADE:
99      return "Trade";
100    case AIUNIT_WONDER:
101      return "Wonder";
102   }
103   /* no default, ensure all types handled somehow */
104   log_error("Unsupported ai_unit_task %d.", task);
105   return NULL;
106 }
107 
108 /**************************************************************************
109   Return the (untranslated) rule name of the adv_choice.
110   You don't have to free the return pointer.
111 **************************************************************************/
dai_choice_rule_name(const struct adv_choice * choice)112 const char *dai_choice_rule_name(const struct adv_choice *choice)
113 {
114   switch (choice->type) {
115   case CT_NONE:
116     return "(nothing)";
117   case CT_BUILDING:
118     return improvement_rule_name(choice->value.building);
119   case CT_CIVILIAN:
120   case CT_ATTACKER:
121   case CT_DEFENDER:
122     return utype_rule_name(choice->value.utype);
123   case CT_LAST:
124     return "(unknown)";
125   };
126   /* no default, ensure all types handled somehow */
127   log_error("Unsupported ai_unit_task %d.", choice->type);
128   return NULL;
129 }
130 
131 /**************************************************************************
132   Amortize a want modified by the shields (build_cost) we risk losing.
133   We add the build time of the unit(s) we risk to amortize delay.  The
134   build time is calculated as the build cost divided by the production
135   output of the unit's homecity or the city where we want to produce
136   the unit. If the city has less than average shield output, we
137   instead use the average, to encourage long-term thinking.
138 **************************************************************************/
military_amortize(struct player * pplayer,struct city * pcity,int value,int delay,int build_cost)139 int military_amortize(struct player *pplayer, struct city *pcity,
140                       int value, int delay, int build_cost)
141 {
142   struct adv_data *ai = adv_data_get(pplayer, NULL);
143   int city_output = (pcity ? pcity->surplus[O_SHIELD] : 1);
144   int output = MAX(city_output, ai->stats.average_production);
145   int build_time = build_cost / MAX(output, 1);
146 
147   if (value <= 0) {
148     return 0;
149   }
150 
151   return amortize(value, delay + build_time);
152 }
153 
154 /**********************************************************************
155   There are some signs that a player might be dangerous: We are at
156   war with him, he has done lots of ignoble things to us, he is an
157   ally of one of our enemies (a ticking bomb to be sure), he is
158   our war target, we don't like him, diplomatic state is neutral
159   or we have case fire.
160   This function is used for example to check if pplayer can leave
161   his city undefended when aplayer's units are near it.
162 ***********************************************************************/
dai_consider_plr_dangerous(struct ai_type * ait,struct player * plr1,struct player * plr2,enum override_bool * result)163 void dai_consider_plr_dangerous(struct ai_type *ait, struct player *plr1,
164                                 struct player *plr2,
165 				enum override_bool *result)
166 {
167   struct ai_dip_intel *adip;
168 
169   adip = dai_diplomacy_get(ait, plr1, plr2);
170 
171   if (adip->countdown >= 0) {
172     /* Don't trust our war target */
173     *result = OVERRIDE_TRUE;
174   }
175 }
176 
177 /****************************************************************************
178   A helper function for ai_gothere.  Estimates the dangers we will
179   be facing at our destination and tries to find/request a bodyguard if
180   needed.
181 ****************************************************************************/
dai_gothere_bodyguard(struct ai_type * ait,struct unit * punit,struct tile * dest_tile)182 static bool dai_gothere_bodyguard(struct ai_type *ait,
183                                   struct unit *punit, struct tile *dest_tile)
184 {
185   struct player *pplayer = unit_owner(punit);
186   unsigned int danger = 0;
187   struct city *dcity;
188   struct unit *guard = aiguard_guard_of(ait, punit);
189   const struct veteran_level *vlevel;
190   bool bg_needed = FALSE;
191 
192   if (is_barbarian(unit_owner(punit))) {
193     /* barbarians must have more courage (ie less brains) */
194     aiguard_clear_guard(ait, punit);
195     return FALSE;
196   }
197 
198   /* Estimate enemy attack power. */
199   unit_list_iterate(dest_tile->units, aunit) {
200     if (POTENTIALLY_HOSTILE_PLAYER(ait, pplayer, unit_owner(aunit))) {
201       danger += adv_unit_att_rating(aunit);
202     }
203   } unit_list_iterate_end;
204   dcity = tile_city(dest_tile);
205   if (dcity && POTENTIALLY_HOSTILE_PLAYER(ait, pplayer, city_owner(dcity))) {
206     /* Assume enemy will build another defender, add it's attack strength */
207     struct unit_type *d_type = dai_choose_defender_versus(dcity, punit);
208 
209     if (d_type) {
210       /* Enemy really can build something */
211       danger +=
212         adv_unittype_att_rating(d_type, do_make_unit_veteran(dcity, d_type),
213                                 SINGLE_MOVE, d_type->hp);
214     }
215   }
216   danger *= POWER_DIVIDER;
217 
218   /* If we are fast, there is less danger.
219    * FIXME: that assumes that most units have move_rate == SINGLE_MOVE;
220    * not true for all rulesets */
221   danger /= (unit_type_get(punit)->move_rate / SINGLE_MOVE);
222   if (unit_has_type_flag(punit, UTYF_IGTER)) {
223     danger /= 1.5;
224   }
225 
226   vlevel = utype_veteran_level(unit_type_get(punit), punit->veteran);
227   fc_assert_ret_val(vlevel != NULL, FALSE);
228 
229   /* We look for the bodyguard where we stand. */
230   if (guard == NULL || unit_tile(guard) != unit_tile(punit)) {
231     int my_def = (punit->hp * unit_type_get(punit)->defense_strength
232                   * POWER_FACTOR * vlevel->power_fact / 100);
233 
234     if (danger >= my_def) {
235       UNIT_LOG(LOGLEVEL_BODYGUARD, punit,
236                "want bodyguard @(%d, %d) danger=%d, my_def=%d",
237                TILE_XY(dest_tile), danger, my_def);
238       aiguard_request_guard(ait, punit);
239       bg_needed = TRUE;
240     } else {
241       aiguard_clear_guard(ait, punit);
242       bg_needed = FALSE;
243     }
244   } else if (guard != NULL) {
245     bg_needed = TRUE;
246   }
247 
248   /* What if we have a bodyguard, but don't need one? */
249 
250   return bg_needed;
251 }
252 
253 #define LOGLEVEL_GOTHERE LOG_DEBUG
254 /****************************************************************************
255   This is ferry-enabled goto.  Should not normally be used for non-ferried
256   units (i.e. planes or ships), use dai_unit_goto instead.
257 
258   Return values: TRUE if got to or next to our destination, FALSE otherwise.
259 
260   TODO: A big one is rendezvous points.  When this is implemented, we won't
261   have to be at the coast to ask for a boat to come to us.
262 ****************************************************************************/
dai_gothere(struct ai_type * ait,struct player * pplayer,struct unit * punit,struct tile * dest_tile)263 bool dai_gothere(struct ai_type *ait, struct player *pplayer,
264                  struct unit *punit, struct tile *dest_tile)
265 {
266   CHECK_UNIT(punit);
267   bool bg_needed;
268 
269   if (same_pos(dest_tile, unit_tile(punit)) || punit->moves_left <= 0) {
270     /* Nowhere to go */
271     return TRUE;
272   }
273 
274   /* See if we need a bodyguard at our destination */
275   /* FIXME: If bodyguard is _really_ necessary, don't go anywhere */
276   bg_needed = dai_gothere_bodyguard(ait, punit, dest_tile);
277 
278   if (unit_transported(punit)
279       || !goto_is_sane(punit, dest_tile)) {
280     /* Must go by boat, call an aiferryboat function */
281     if (!aiferry_gobyboat(ait, pplayer, punit, dest_tile,
282                           bg_needed)) {
283       return FALSE;
284     }
285   }
286 
287   /* Go where we should be going if we can, and are at our destination
288    * if we are on a ferry */
289   if (goto_is_sane(punit, dest_tile) && punit->moves_left > 0) {
290     punit->goto_tile = dest_tile;
291     UNIT_LOG(LOGLEVEL_GOTHERE, punit, "Walking to (%d,%d)", TILE_XY(dest_tile));
292     if (!dai_unit_goto(ait, punit, dest_tile)) {
293       /* died */
294       return FALSE;
295     }
296     /* liable to bump into someone that will kill us.  Should avoid? */
297   } else {
298     UNIT_LOG(LOGLEVEL_GOTHERE, punit, "Not moving");
299     return FALSE;
300   }
301 
302   if (def_ai_unit_data(punit, ait)->ferryboat > 0
303       && !unit_transported(punit)) {
304     /* We probably just landed, release our boat */
305     aiferry_clear_boat(ait, punit);
306   }
307 
308   /* Dead unit shouldn't reach this point */
309   CHECK_UNIT(punit);
310 
311   return (same_pos(unit_tile(punit), dest_tile)
312           || is_tiles_adjacent(unit_tile(punit), dest_tile));
313 }
314 
315 /**************************************************************************
316   Returns the destination for a unit moving towards a given final destination.
317   That is, it gives a suitable way-point, if necessary.
318   For example, aircraft need these way-points to refuel.
319 **************************************************************************/
immediate_destination(struct unit * punit,struct tile * dest_tile)320 struct tile *immediate_destination(struct unit *punit,
321                                    struct tile *dest_tile)
322 {
323   if (!same_pos(unit_tile(punit), dest_tile)
324       && utype_fuel(unit_type_get(punit))) {
325     struct pf_parameter parameter;
326     struct pf_map *pfm;
327     struct pf_path *path;
328     size_t i;
329     struct player *pplayer = unit_owner(punit);
330 
331     pft_fill_unit_parameter(&parameter, punit);
332     parameter.omniscience = !has_handicap(pplayer, H_MAP);
333     pfm = pf_map_new(&parameter);
334     path = pf_map_path(pfm, punit->goto_tile);
335 
336     if (path) {
337       for (i = 1; i < path->length; i++) {
338         if (path->positions[i].tile == path->positions[i - 1].tile) {
339           /* The path-finding code advices us to wait there to refuel. */
340           struct tile *ptile = path->positions[i].tile;
341 
342           pf_path_destroy(path);
343           pf_map_destroy(pfm);
344           return ptile;
345         }
346       }
347       pf_path_destroy(path);
348       pf_map_destroy(pfm);
349       /* Seems it's the immediate destination */
350       return punit->goto_tile;
351     }
352 
353     pf_map_destroy(pfm);
354     log_verbose("Did not find an air-route for "
355                 "%s %s[%d] (%d,%d)->(%d,%d)",
356                 nation_rule_name(nation_of_unit(punit)),
357                 unit_rule_name(punit),
358                 punit->id,
359                 TILE_XY(unit_tile(punit)),
360                 TILE_XY(dest_tile));
361     /* Prevent take off */
362     return unit_tile(punit);
363   }
364 
365   /* else does not need way-points */
366   return dest_tile;
367 }
368 
369 /**************************************************************************
370   Log the cost of travelling a path.
371 **************************************************************************/
dai_log_path(struct unit * punit,struct pf_path * path,struct pf_parameter * parameter)372 void dai_log_path(struct unit *punit,
373                   struct pf_path *path, struct pf_parameter *parameter)
374 {
375   const struct pf_position *last = pf_path_last_position(path);
376   const int cc = PF_TURN_FACTOR * last->total_MC
377                  + parameter->move_rate * last->total_EC;
378   const int tc = cc / (PF_TURN_FACTOR *parameter->move_rate);
379 
380   UNIT_LOG(LOG_DEBUG, punit, "path L=%d T=%d(%d) MC=%d EC=%d CC=%d",
381 	   path->length - 1, last->turn, tc,
382 	   last->total_MC, last->total_EC, cc);
383 }
384 
385 /**************************************************************************
386   Go to specified destination, subject to given PF constraints,
387   but do not disturb existing role or activity
388   and do not clear the role's destination. Return FALSE iff we died.
389 
390   parameter: the PF constraints on the computed path. The unit will move
391   as far along the computed path is it can; the movement code will impose
392   all the real constraints (ZoC, etc).
393 **************************************************************************/
dai_unit_goto_constrained(struct ai_type * ait,struct unit * punit,struct tile * ptile,struct pf_parameter * parameter)394 bool dai_unit_goto_constrained(struct ai_type *ait, struct unit *punit,
395                                struct tile *ptile,
396                                struct pf_parameter *parameter)
397 {
398   bool alive = TRUE;
399   struct pf_map *pfm;
400   struct pf_path *path;
401 
402   UNIT_LOG(LOG_DEBUG, punit, "constrained goto to %d,%d", TILE_XY(ptile));
403 
404   if (same_pos(unit_tile(punit), ptile)) {
405     /* Was not an error in previous versions but now is dubious... */
406     UNIT_LOG(LOG_DEBUG, punit, "constrained goto: already there!");
407     send_unit_info(NULL, punit);
408     return TRUE;
409   } else if (!goto_is_sane(punit, ptile)) {/* FIXME: why do we check it? */
410     UNIT_LOG(LOG_DEBUG, punit, "constrained goto: 'insane' goto!");
411     punit->activity = ACTIVITY_IDLE;
412     send_unit_info(NULL, punit);
413     return TRUE;
414   } else if(punit->moves_left == 0) {
415     UNIT_LOG(LOG_DEBUG, punit, "constrained goto: no moves left!");
416     send_unit_info(NULL, punit);
417     return TRUE;
418   }
419 
420   pfm = pf_map_new(parameter);
421   path = pf_map_path(pfm, ptile);
422 
423   if (path) {
424     dai_log_path(punit, path, parameter);
425     UNIT_LOG(LOG_DEBUG, punit, "constrained goto: following path.");
426     alive = adv_follow_path(punit, path, ptile);
427   } else {
428     UNIT_LOG(LOG_DEBUG, punit, "no path to destination");
429   }
430 
431   pf_path_destroy(path);
432   pf_map_destroy(pfm);
433 
434   return alive;
435 }
436 
437 /****************************************************************************
438   Use pathfinding to determine whether a GOTO is possible, considering all
439   aspects of the unit being moved and the terrain under consideration.
440   Don't bother with pathfinding if the unit is already there.
441 ****************************************************************************/
goto_is_sane(struct unit * punit,struct tile * ptile)442 bool goto_is_sane(struct unit *punit, struct tile *ptile)
443 {
444   bool can_get_there = FALSE;
445 
446   if (same_pos(unit_tile(punit), ptile)) {
447     can_get_there = TRUE;
448   } else {
449     struct pf_parameter parameter;
450     struct pf_map *pfm;
451 
452     pft_fill_unit_attack_param(&parameter, punit);
453     pfm = pf_map_new(&parameter);
454 
455     if (pf_map_move_cost(pfm, ptile) != PF_IMPOSSIBLE_MC) {
456       can_get_there = TRUE;
457     }
458     pf_map_destroy(pfm);
459   }
460   return can_get_there;
461 }
462 
463 /*
464  * The length of time, in turns, which is long enough to be optimistic
465  * that enemy units will have moved from their current position.
466  * WAG
467  */
468 #define LONG_TIME 4
469 /**************************************************************************
470   Set up the constraints on a path for an AI unit.
471 
472   parameter:
473      constraints (output)
474   risk_cost:
475      auxiliary data used by the constraints (output)
476   ptile:
477      the destination of the unit.
478      For ferries, the destination may be a coastal land tile,
479      in which case the ferry should stop on an adjacent tile.
480 **************************************************************************/
dai_fill_unit_param(struct ai_type * ait,struct pf_parameter * parameter,struct adv_risk_cost * risk_cost,struct unit * punit,struct tile * ptile)481 void dai_fill_unit_param(struct ai_type *ait, struct pf_parameter *parameter,
482                          struct adv_risk_cost *risk_cost,
483                          struct unit *punit, struct tile *ptile)
484 {
485   const bool long_path = LONG_TIME < (map_distance(unit_tile(punit),
486                                                    unit_tile(punit))
487                                       * SINGLE_MOVE
488                                       / unit_type_get(punit)->move_rate);
489   const bool barbarian = is_barbarian(unit_owner(punit));
490   bool is_ferry;
491   struct unit_ai *unit_data = def_ai_unit_data(punit, ait);
492   struct player *pplayer = unit_owner(punit);
493 
494   /* This function is now always omniscient and should not be used
495    * for human players any more. */
496   fc_assert(pplayer->ai_controlled);
497 
498   /* If a unit is hunting, don't expect it to be a ferry. */
499   is_ferry = (unit_data->task != AIUNIT_HUNTER
500               && dai_is_ferry(punit, ait));
501 
502   if (is_ferry) {
503     /* The destination may be a coastal land tile,
504      * in which case the ferry should stop on an adjacent tile. */
505     pft_fill_unit_overlap_param(parameter, punit);
506   } else if (!utype_fuel(unit_type_get(punit))
507              && is_military_unit(punit)
508              && (unit_data->task == AIUNIT_DEFEND_HOME
509                  || unit_data->task == AIUNIT_ATTACK
510                  || unit_data->task ==  AIUNIT_ESCORT
511                  || unit_data->task == AIUNIT_HUNTER)) {
512     /* Use attack movement for defenders and escorts so they can
513      * make defensive attacks */
514     pft_fill_unit_attack_param(parameter, punit);
515   } else {
516     pft_fill_unit_parameter(parameter, punit);
517   }
518   parameter->omniscience = !has_handicap(pplayer, H_MAP);
519 
520   /* Should we use the risk avoidance code?
521    * The risk avoidance code uses omniscience, so do not use for
522    * human-player units under temporary AI control.
523    * Barbarians bravely/stupidly ignore risks
524    */
525   if (!uclass_has_flag(unit_class_get(punit), UCF_UNREACHABLE)
526       && !barbarian) {
527     adv_avoid_risks(parameter, risk_cost, punit, NORMAL_STACKING_FEARFULNESS);
528   }
529 
530   /* Should we absolutely forbid ending a turn on a dangerous tile?
531    * Do not annoy human players by killing their units for them.
532    * For AI units be optimistic; allows attacks across dangerous terrain,
533    * and polar settlements.
534    * TODO: This is compatible with old code,
535    * but probably ought to be more cautious for non military units
536    */
537   if (!is_ferry && !utype_fuel(unit_type_get(punit))) {
538     parameter->get_moves_left_req = NULL;
539   }
540 
541   if (long_path) {
542     /* Move as far along the path to the destination as we can;
543      * that is, ignore the presence of enemy units when computing the
544      * path.
545      * Hopefully, ai_avoid_risks will have produced a path that avoids enemy
546      * ZoCs. Ignoring ZoCs allows us to move closer to a destination
547      * for which there is not yet a clear path.
548      * That is good if the destination is several turns away,
549      * so we can reasonably expect blocking enemy units to move or
550      * be destroyed. But it can be bad if the destination is one turn away
551      * or our destination is far but there are enemy units near us and on the
552      * shortest path to the destination.
553      */
554     parameter->get_zoc = NULL;
555   }
556 
557   if (unit_has_type_flag(punit, UTYF_SETTLERS)) {
558     parameter->get_TB = no_fights;
559   } else if (long_path && unit_is_cityfounder(punit)) {
560     /* Default tile behaviour;
561      * move as far along the path to the destination as we can;
562      * that is, ignore the presence of enemy units when computing the
563      * path.
564      */
565   } else if (unit_is_cityfounder(punit)) {
566     /* Short path */
567     parameter->get_TB = no_fights;
568   } else if (unit_has_type_role(punit, L_BARBARIAN_LEADER)) {
569     /* Avoid capture */
570     parameter->get_TB = no_fights;
571   } else if (is_ferry) {
572     /* Ferries are not warships */
573     parameter->get_TB = no_fights;
574   } else if (is_losing_hp(punit)) {
575     /* Losing hitpoints over time (helicopter in default rules) */
576     /* Default tile behaviour */
577   } else if (is_military_unit(punit)
578              || utype_may_act_at_all(unit_type_get(punit))) {
579     switch (unit_data->task) {
580     case AIUNIT_AUTO_SETTLER:
581     case AIUNIT_BUILD_CITY:
582       /* Strange, but not impossible */
583       parameter->get_TB = no_fights;
584       break;
585     case AIUNIT_DEFEND_HOME:
586     case AIUNIT_ATTACK: /* Includes spy actions */
587     case AIUNIT_ESCORT:
588     case AIUNIT_HUNTER:
589     case AIUNIT_TRADE:
590     case AIUNIT_WONDER:
591       parameter->get_TB = no_intermediate_fights;
592       break;
593     case AIUNIT_EXPLORE:
594     case AIUNIT_RECOVER:
595       parameter->get_TB = no_fights;
596       break;
597     case AIUNIT_NONE:
598       /* Default tile behaviour */
599       break;
600     }
601   } else {
602     /* Probably an explorer */
603     parameter->get_TB = no_fights;
604   }
605 
606   if (is_ferry) {
607     /* Show the destination in the client when watching an AI: */
608     punit->goto_tile = ptile;
609   }
610 }
611 
612 /**************************************************************************
613   Go to specified destination but do not disturb existing role or activity
614   and do not clear the role's destination. Return FALSE iff we died.
615 **************************************************************************/
dai_unit_goto(struct ai_type * ait,struct unit * punit,struct tile * ptile)616 bool dai_unit_goto(struct ai_type *ait, struct unit *punit, struct tile *ptile)
617 {
618   struct pf_parameter parameter;
619   struct adv_risk_cost risk_cost;
620 
621   UNIT_LOG(LOG_DEBUG, punit, "dai_unit_goto to %d,%d", TILE_XY(ptile));
622   dai_fill_unit_param(ait, &parameter, &risk_cost, punit, ptile);
623 
624   return dai_unit_goto_constrained(ait, punit, ptile, &parameter);
625 }
626 
627 /**************************************************************************
628   Adviser task for unit has been changed.
629 **************************************************************************/
dai_unit_new_adv_task(struct ai_type * ait,struct unit * punit,enum adv_unit_task task,struct tile * ptile)630 void dai_unit_new_adv_task(struct ai_type *ait, struct unit *punit,
631                            enum adv_unit_task task, struct tile *ptile)
632 {
633   /* Keep ai_unit_task in sync with adv task */
634   switch(task) {
635    case AUT_AUTO_SETTLER:
636      dai_unit_new_task(ait, punit, AIUNIT_AUTO_SETTLER, ptile);
637      break;
638    case AUT_BUILD_CITY:
639      dai_unit_new_task(ait, punit, AIUNIT_BUILD_CITY, ptile);
640      break;
641    case AUT_NONE:
642      dai_unit_new_task(ait, punit, AIUNIT_NONE, ptile);
643      break;
644   }
645 }
646 
647 /**************************************************************************
648   Ensure unit sanity by telling charge that we won't bodyguard it anymore,
649   tell bodyguard it can roam free if our job is done, add and remove city
650   spot reservation, and set destination. If we set a unit to hunter, also
651   reserve its target, and try to load it with cruise missiles or nukes
652   to bring along.
653 **************************************************************************/
dai_unit_new_task(struct ai_type * ait,struct unit * punit,enum ai_unit_task task,struct tile * ptile)654 void dai_unit_new_task(struct ai_type *ait, struct unit *punit,
655                        enum ai_unit_task task, struct tile *ptile)
656 {
657   struct unit *bodyguard = aiguard_guard_of(ait, punit);
658   struct unit_ai *unit_data = def_ai_unit_data(punit, ait);
659 
660   /* If the unit is under (human) orders we shouldn't control it.
661    * Allow removal of old role with AIUNIT_NONE. */
662   fc_assert_ret(!unit_has_orders(punit) || task == AIUNIT_NONE);
663 
664   UNIT_LOG(LOG_DEBUG, punit, "changing task from %s to %s",
665            dai_unit_task_rule_name(unit_data->task),
666            dai_unit_task_rule_name(task));
667 
668   /* Free our ferry.  Most likely it has been done already. */
669   if (task == AIUNIT_NONE || task == AIUNIT_DEFEND_HOME) {
670     aiferry_clear_boat(ait, punit);
671   }
672 
673   if (punit->activity == ACTIVITY_GOTO) {
674     /* It would indicate we're going somewhere otherwise */
675     unit_activity_handling(punit, ACTIVITY_IDLE);
676   }
677 
678   if (unit_data->task == AIUNIT_BUILD_CITY) {
679     if (punit->goto_tile) {
680       citymap_free_city_spot(punit->goto_tile, punit->id);
681     } else {
682       /* Print error message instead of crashing in citymap_free_city_spot()
683        * This probably means that some city spot reservation has not been
684        * properly cleared; bad for the AI, as it will leave that area
685        * uninhabited. */
686       log_error("%s was on city founding mission without target tile.",
687                 unit_rule_name(punit));
688     }
689   }
690 
691   if (unit_data->task == AIUNIT_HUNTER) {
692     /* Clear victim's hunted bit - we're no longer chasing. */
693     struct unit *target = game_unit_by_number(unit_data->target);
694 
695     if (target) {
696       BV_CLR(def_ai_unit_data(target, ait)->hunted,
697              player_index(unit_owner(punit)));
698       UNIT_LOG(LOGLEVEL_HUNT, target, "no longer hunted (new task %d, old %d)",
699                task, unit_data->task);
700     }
701   }
702 
703   aiguard_clear_charge(ait, punit);
704   /* Record the city to defend; our goto may be to transport. */
705   if (task == AIUNIT_DEFEND_HOME && ptile && tile_city(ptile)) {
706     aiguard_assign_guard_city(ait, tile_city(ptile), punit);
707   }
708 
709   unit_data->task = task;
710 
711   /* Verify and set the goto destination.  Eventually this can be a lot more
712    * stringent, but for now we don't want to break things too badly. */
713   punit->goto_tile = ptile; /* May be NULL. */
714 
715   if (unit_data->task == AIUNIT_NONE && bodyguard) {
716     dai_unit_new_task(ait, bodyguard, AIUNIT_NONE, NULL);
717   }
718 
719   /* Reserve city spot, _unless_ we want to add ourselves to a city. */
720   if (unit_data->task == AIUNIT_BUILD_CITY && !tile_city(ptile)) {
721     citymap_reserve_city_spot(ptile, punit->id);
722   }
723   if (unit_data->task == AIUNIT_HUNTER) {
724     /* Set victim's hunted bit - the hunt is on! */
725     struct unit *target = game_unit_by_number(unit_data->target);
726 
727     fc_assert_ret(target != NULL);
728     BV_SET(def_ai_unit_data(target, ait)->hunted, player_index(unit_owner(punit)));
729     UNIT_LOG(LOGLEVEL_HUNT, target, "is being hunted");
730 
731     /* Grab missiles lying around and bring them along */
732     unit_list_iterate(unit_tile(punit)->units, missile) {
733       if (unit_owner(missile) == unit_owner(punit)
734           && def_ai_unit_data(missile, ait)->task != AIUNIT_ESCORT
735           && !unit_transported(missile)
736           && unit_owner(missile) == unit_owner(punit)
737           && uclass_has_flag(unit_class_get(missile), UCF_MISSILE)
738           && can_unit_load(missile, punit)) {
739         UNIT_LOG(LOGLEVEL_HUNT, missile, "loaded on hunter");
740         dai_unit_new_task(ait, missile, AIUNIT_ESCORT, unit_tile(target));
741         unit_transport_load_send(missile, punit);
742       }
743     } unit_list_iterate_end;
744   }
745 
746   /* Map ai tasks to advisor tasks. For most ai tasks there is
747      no advisor, so AUT_NONE is set. */
748   switch(unit_data->task) {
749    case AIUNIT_AUTO_SETTLER:
750      punit->server.adv->task = AUT_AUTO_SETTLER;
751      break;
752    case AIUNIT_BUILD_CITY:
753      punit->server.adv->task = AUT_BUILD_CITY;
754      break;
755    default:
756      punit->server.adv->task = AUT_NONE;
757      break;
758   }
759 }
760 
761 /**************************************************************************
762   Try to make pcity our new homecity. Fails if we can't upkeep it. Assumes
763   success from server.
764 **************************************************************************/
dai_unit_make_homecity(struct unit * punit,struct city * pcity)765 bool dai_unit_make_homecity(struct unit *punit, struct city *pcity)
766 {
767   CHECK_UNIT(punit);
768   fc_assert_ret_val(unit_owner(punit) == city_owner(pcity), TRUE);
769 
770   if (punit->homecity == 0 && !unit_has_type_role(punit, L_EXPLORER)) {
771     /* This unit doesn't pay any upkeep while it doesn't have a homecity,
772      * so it would be stupid to give it one. There can also be good reasons
773      * why it doesn't have a homecity. */
774     /* However, until we can do something more useful with them, we
775        will assign explorers to a city so that they can be disbanded for
776        the greater good -- Per */
777     return FALSE;
778   }
779   if (pcity->surplus[O_SHIELD] >= unit_type_get(punit)->upkeep[O_SHIELD]
780       && pcity->surplus[O_FOOD] >= unit_type_get(punit)->upkeep[O_FOOD]) {
781     handle_unit_change_homecity(unit_owner(punit), punit->id, pcity->id);
782     return TRUE;
783   }
784   return FALSE;
785 }
786 
787 /**************************************************************************
788   Move a bodyguard along with another unit. We assume that unit has already
789   been moved to ptile which is a valid, safe tile, and that our
790   bodyguard has not. This is an ai_unit_* auxiliary function, do not use
791   elsewhere.
792 **************************************************************************/
dai_unit_bodyguard_move(struct ai_type * ait,struct unit * bodyguard,struct tile * ptile)793 static void dai_unit_bodyguard_move(struct ai_type *ait,
794                                     struct unit *bodyguard, struct tile *ptile)
795 {
796   struct unit *punit;
797   struct player *pplayer;
798 
799   fc_assert_ret(bodyguard != NULL);
800   pplayer = unit_owner(bodyguard);
801   fc_assert_ret(pplayer != NULL);
802   punit = aiguard_charge_unit(ait, bodyguard);
803   fc_assert_ret(punit != NULL);
804 
805   CHECK_GUARD(ait, bodyguard);
806   CHECK_CHARGE_UNIT(ait, punit);
807 
808   if (!is_tiles_adjacent(ptile, unit_tile(bodyguard))) {
809     return;
810   }
811 
812   if (bodyguard->moves_left <= 0) {
813     /* should generally should not happen */
814     BODYGUARD_LOG(ait, LOG_DEBUG, bodyguard, "was left behind by charge");
815     return;
816   }
817 
818   unit_activity_handling(bodyguard, ACTIVITY_IDLE);
819   (void) dai_unit_move(ait, bodyguard, ptile);
820 }
821 
822 /**************************************************************************
823   Move and attack with an ai unit. We do not wait for server reply.
824 **************************************************************************/
dai_unit_attack(struct ai_type * ait,struct unit * punit,struct tile * ptile)825 bool dai_unit_attack(struct ai_type *ait, struct unit *punit, struct tile *ptile)
826 {
827   struct unit *bodyguard = aiguard_guard_of(ait, punit);
828   int sanity = punit->id;
829   bool alive;
830 
831   CHECK_UNIT(punit);
832   fc_assert_ret_val(unit_owner(punit)->ai_controlled, TRUE);
833   fc_assert_ret_val(is_tiles_adjacent(unit_tile(punit), ptile), TRUE);
834 
835   unit_activity_handling(punit, ACTIVITY_IDLE);
836   /* Regular attack, Occupy City or other move. */
837   (void) unit_move_handling(punit, ptile, FALSE, TRUE, NULL);
838   alive = (game_unit_by_number(sanity) != NULL);
839 
840   if (alive && same_pos(ptile, unit_tile(punit))
841       && bodyguard != NULL  && def_ai_unit_data(bodyguard, ait)->charge == punit->id) {
842     dai_unit_bodyguard_move(ait, bodyguard, ptile);
843     /* Clumsy bodyguard might trigger an auto-attack */
844     alive = (game_unit_by_number(sanity) != NULL);
845   }
846 
847   return alive;
848 }
849 
850 /**************************************************************************
851   Ai unit moving function called from AI interface.
852 **************************************************************************/
dai_unit_move_or_attack(struct ai_type * ait,struct unit * punit,struct tile * ptile,struct pf_path * path,int step)853 void dai_unit_move_or_attack(struct ai_type *ait, struct unit *punit,
854                              struct tile *ptile, struct pf_path *path, int step)
855 {
856   if (step == path->length - 1) {
857     (void) dai_unit_attack(ait, punit, ptile);
858   } else {
859     (void) dai_unit_move(ait, punit, ptile);
860   }
861 }
862 
863 /**************************************************************************
864   Move a unit. Do not attack. Do not leave bodyguard.
865   For AI units.
866 
867   This function returns only when we have a reply from the server and
868   we can tell the calling function what happened to the move request.
869   (Right now it is not a big problem, since we call the server directly.)
870 **************************************************************************/
dai_unit_move(struct ai_type * ait,struct unit * punit,struct tile * ptile)871 bool dai_unit_move(struct ai_type *ait, struct unit *punit, struct tile *ptile)
872 {
873   struct unit *bodyguard;
874   int sanity = punit->id;
875   struct player *pplayer = unit_owner(punit);
876   const bool is_ai = pplayer->ai_controlled;
877   int mcost;
878 
879   CHECK_UNIT(punit);
880   fc_assert_ret_val_msg(is_tiles_adjacent(unit_tile(punit), ptile), FALSE,
881                         "Tiles not adjacent: Unit = %d, "
882                         "from = (%d, %d]) to = (%d, %d).",
883                         punit->id, TILE_XY(unit_tile(punit)),
884                         TILE_XY(ptile));
885 
886   /* if enemy, stop and give a chance for the ai attack function
887    * to handle this case */
888   if (is_enemy_unit_tile(ptile, pplayer)
889       || is_enemy_city_tile(ptile, pplayer)) {
890     UNIT_LOG(LOG_DEBUG, punit, "movement halted due to enemy presence");
891     return FALSE;
892   }
893 
894   /* barbarians shouldn't enter huts */
895   if (is_barbarian(pplayer) && tile_has_cause_extra(ptile, EC_HUT)) {
896     return FALSE;
897   }
898 
899   /* don't leave bodyguard behind */
900   if (is_ai
901       && (bodyguard = aiguard_guard_of(ait, punit))
902       && same_pos(unit_tile(punit), unit_tile(bodyguard))
903       && bodyguard->moves_left == 0) {
904     UNIT_LOG(LOGLEVEL_BODYGUARD, punit, "does not want to leave "
905              "its bodyguard");
906     return FALSE;
907   }
908 
909   /* Try not to end move next to an enemy if we can avoid it by waiting */
910   mcost = map_move_cost_unit(punit, ptile);
911   if (punit->moves_left <= mcost
912       && unit_move_rate(punit) > mcost
913       && adv_danger_at(punit, ptile)
914       && !adv_danger_at(punit,  unit_tile(punit))) {
915     UNIT_LOG(LOG_DEBUG, punit, "ending move early to stay out of trouble");
916     return FALSE;
917   }
918 
919   /* go */
920   unit_activity_handling(punit, ACTIVITY_IDLE);
921   /* Move */
922   (void) unit_move_handling(punit, ptile, FALSE, TRUE, NULL);
923 
924   /* handle the results */
925   if (game_unit_by_number(sanity) && same_pos(ptile, unit_tile(punit))) {
926     bodyguard = aiguard_guard_of(ait, punit);
927 
928     if (is_ai && bodyguard != NULL
929         && def_ai_unit_data(bodyguard, ait)->charge == punit->id) {
930       dai_unit_bodyguard_move(ait, bodyguard, ptile);
931     }
932     return TRUE;
933   }
934   return FALSE;
935 }
936 
937 /**************************************************************************
938   Calculate the value of the target unit including the other units which
939   will die in a successful attack
940 **************************************************************************/
stack_cost(struct unit * pattacker,struct unit * pdefender)941 int stack_cost(struct unit *pattacker, struct unit *pdefender)
942 {
943   struct tile *ptile = unit_tile(pdefender);
944   int victim_cost = 0;
945 
946   if (is_stack_vulnerable(ptile)) {
947     /* lotsa people die */
948     unit_list_iterate(ptile->units, aunit) {
949       if (unit_attack_unit_at_tile_result(pattacker, aunit, ptile) == ATT_OK) {
950         victim_cost += unit_build_shield_cost(aunit);
951       }
952     } unit_list_iterate_end;
953   } else if (unit_attack_unit_at_tile_result(pattacker, pdefender, ptile) == ATT_OK) {
954     /* Only one unit dies if attack is successful */
955     victim_cost = unit_build_shield_cost(pdefender);
956   }
957 
958   return victim_cost;
959 }
960 
961 /**************************************************************************
962   Change government, pretty fast...
963 **************************************************************************/
dai_government_change(struct player * pplayer,struct government * gov)964 void dai_government_change(struct player *pplayer, struct government *gov)
965 {
966   if (gov == government_of_player(pplayer)) {
967     return;
968   }
969 
970   handle_player_change_government(pplayer, government_number(gov));
971 
972   city_list_iterate(pplayer->cities, pcity) {
973     auto_arrange_workers(pcity); /* update cities */
974   } city_list_iterate_end;
975 }
976 
977 /**************************************************************************
978   Credits the AI wants to have in reserves. We need some gold to bribe
979   and incite cities.
980 
981   "I still don't trust this function" -- Syela
982 **************************************************************************/
dai_gold_reserve(struct player * pplayer)983 int dai_gold_reserve(struct player *pplayer)
984 {
985   int i = total_player_citizens(pplayer)*2;
986   return MAX(pplayer->ai_common.maxbuycost, i);
987 }
988 
989 /**************************************************************************
990   Adjust want for choice to 'value' percent
991 **************************************************************************/
adjust_choice(int value,struct adv_choice * choice)992 void adjust_choice(int value, struct adv_choice *choice)
993 {
994   choice->want = (choice->want *value)/100;
995 }
996 
997 /**************************************************************************
998   After call to this function best is better of cur and best
999 **************************************************************************/
copy_if_better_choice(struct adv_choice * cur,struct adv_choice * best)1000 void copy_if_better_choice(struct adv_choice *cur, struct adv_choice *best)
1001 {
1002   if (best->want < cur->want) {
1003     /* This simple minded copy works for now.
1004      *
1005      * TODO: We should get rid of this function. Choice structures should
1006      *       be accessed via pointers, and those pointers should be updated
1007      *       instead of copying whole structures.
1008      */
1009     *best = *cur;
1010   }
1011 }
1012 
1013 /**************************************************************************
1014   Does choice type refer to unit
1015 **************************************************************************/
is_unit_choice_type(enum choice_type type)1016 bool is_unit_choice_type(enum choice_type type)
1017 {
1018    return type == CT_CIVILIAN || type == CT_ATTACKER || type == CT_DEFENDER;
1019 }
1020 
1021 /**************************************************************************
1022   Calls dai_wants_role_unit to choose the best unit with the given role and
1023   set tech wants.  Sets choice->value.utype when we can build something.
1024 **************************************************************************/
dai_choose_role_unit(struct ai_type * ait,struct player * pplayer,struct city * pcity,struct adv_choice * choice,enum choice_type type,int role,int want,bool need_boat)1025 bool dai_choose_role_unit(struct ai_type *ait, struct player *pplayer,
1026                           struct city *pcity, struct adv_choice *choice,
1027                           enum choice_type type, int role, int want,
1028                           bool need_boat)
1029 {
1030   struct unit_type *iunit = dai_wants_role_unit(ait, pplayer, pcity, role, want);
1031 
1032   if (iunit != NULL) {
1033     choice->type = type;
1034     choice->value.utype = iunit;
1035     choice->want = want;
1036 
1037     choice->need_boat = need_boat;
1038 
1039     return TRUE;
1040   }
1041 
1042   return FALSE;
1043 }
1044 
1045 /**************************************************************************
1046   Consider overriding building target selected by common advisor code.
1047 **************************************************************************/
dai_build_adv_override(struct ai_type * ait,struct city * pcity,struct adv_choice * choice)1048 void dai_build_adv_override(struct ai_type *ait, struct city *pcity,
1049                             struct adv_choice *choice)
1050 {
1051   struct impr_type *chosen;
1052   int want;
1053 
1054   if (choice->type == CT_NONE) {
1055     want = 0;
1056     chosen = NULL;
1057   } else {
1058     want = choice->want;
1059     chosen = choice->value.building;
1060   }
1061 
1062   improvement_iterate(pimprove) {
1063     /* Advisor code did not consider wonders, let's do it here */
1064     if (is_wonder(pimprove)) {
1065       if (pcity->server.adv->building_want[improvement_index(pimprove)] > want
1066           && can_city_build_improvement_now(pcity, pimprove)) {
1067         want = pcity->server.adv->building_want[improvement_index(pimprove)];
1068         chosen = pimprove;
1069       }
1070     }
1071   } improvement_iterate_end;
1072 
1073   choice->want = want;
1074   choice->value.building = chosen;
1075 
1076   if (chosen) {
1077     choice->type = CT_BUILDING; /* In case advisor had not chosen anything */
1078 
1079     CITY_LOG(LOG_DEBUG, pcity, "ai wants most to build %s at %d",
1080              improvement_rule_name(chosen),
1081              want);
1082   }
1083 }
1084 
1085 /**********************************************************************
1086   "The following evaluates the unhappiness caused by military units
1087   in the field (or aggressive) at a city when at Republic or
1088   Democracy.
1089 
1090   Now generalised somewhat for government rulesets, though I'm not
1091   sure whether it is fully general for all possible parameters/
1092   combinations." --dwp
1093 **********************************************************************/
dai_assess_military_unhappiness(struct city * pcity)1094 bool dai_assess_military_unhappiness(struct city *pcity)
1095 {
1096   int free_unhappy = get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL);
1097   int unhap = 0;
1098 
1099   /* bail out now if happy_cost is 0 */
1100   if (get_player_bonus(city_owner(pcity), EFT_UNHAPPY_FACTOR) == 0) {
1101     return FALSE;
1102   }
1103 
1104   unit_list_iterate(pcity->units_supported, punit) {
1105     int happy_cost = city_unit_unhappiness(punit, &free_unhappy);
1106 
1107     if (happy_cost > 0) {
1108       unhap += happy_cost;
1109     }
1110   } unit_list_iterate_end;
1111 
1112   if (unhap < 0) {
1113     unhap = 0;
1114   }
1115   return (unhap > 0);
1116 }
1117