Freeciv21
Develop your civilization from humble roots to a global empire
aidiplomat.cpp
Go to the documentation of this file.
1 /*
2  Copyright (c) 1996-2020 Freeciv21 and Freeciv contributors. This file is
3  part of Freeciv21. Freeciv21 is free software: you can redistribute it
4  and/or modify it under the terms of the GNU General Public License as
5  published by the Free Software Foundation, either version 3 of the
6  License, or (at your option) any later version. You should have received
7  a copy of the GNU General Public License along with Freeciv21. If not,
8  see https://www.gnu.org/licenses/.
9  */
10 
11 // utility
12 #include "bitvector.h"
13 #include "log.h"
14 #include "shared.h"
15 #include "timing.h"
16 
17 // common
18 #include "actions.h"
19 #include "city.h"
20 #include "combat.h"
21 #include "game.h"
22 #include "government.h"
23 #include "map.h"
24 #include "movement.h"
25 #include "nation.h"
26 #include "packets.h"
27 #include "player.h"
28 #include "research.h"
29 #include "unit.h"
30 #include "unitlist.h"
31 
32 // aicore
33 #include "aiactions.h"
34 #include "pf_tools.h"
35 
36 // server
37 #include "citytools.h"
38 #include "cityturn.h"
39 #include "diplomats.h"
40 #include "maphand.h"
41 #include "srv_log.h"
42 #include "unithand.h"
43 
44 /* server/advisors */
45 #include "advbuilding.h"
46 #include "advdata.h"
47 #include "advgoto.h"
48 
49 // ai
50 #include "handicaps.h"
51 
52 /* ai/default */
53 #include "aidata.h"
54 #include "aiguard.h"
55 #include "aihand.h"
56 #include "ailog.h"
57 #include "aiplayer.h"
58 #include "aitools.h"
59 #include "aiunit.h"
60 #include "daiactions.h"
61 #include "daicity.h"
62 
63 #include "aidiplomat.h"
64 
65 #define LOG_DIPLOMAT LOG_DEBUG
66 #define LOG_DIPLOMAT_BUILD LOG_DEBUG
67 
68 /* 3000 is a just a large number, but not hillariously large as the
69  * previously used one. This is important for diplomacy. - Per */
70 #define DIPLO_DEFENSE_WANT 3000
71 
72 class PFPath;
73 
74 static bool is_city_surrounded_by_our_spies(struct player *pplayer,
75  struct city *pcity);
76 
77 static void find_city_to_diplomat(struct player *pplayer, struct unit *punit,
78  struct city **ctarget, int *move_dist,
79  struct pf_map *pfm);
80 
84 static int count_stealable_techs(struct player *pplayer,
85  struct player *tplayer)
86 {
87  struct research *presearch = research_get(pplayer);
88  struct research *tresearch = research_get(tplayer);
89  int count = 0;
90 
92  {
93  if (research_invention_state(presearch, idx) != TECH_KNOWN
94  && research_invention_state(tresearch, idx) == TECH_KNOWN) {
95  count++;
96  }
97  }
99 
100  return count;
101 }
102 
109  struct player *pplayer,
110  struct city *pcity,
111  struct adv_choice *choice, int def)
112 {
113  /* Build a diplomat if our city is threatened by enemy diplomats, and
114  we have other defensive troops, and we don't already have a diplomat
115  to protect us. If we see an enemy diplomat and we don't have diplomat
116  tech... race it! */
117  struct ai_city *city_data = def_ai_city_data(pcity, ait);
118 
119  if (def != 0 && city_data->diplomat_threat && !city_data->has_diplomat) {
120  struct unit_type *ut = best_role_unit(pcity, UTYF_DIPLOMAT);
121 
122  if (ut) {
124  "A defensive diplomat will be built in city %s.",
125  city_name_get(pcity));
126  choice->want = 16000; // diplomat more important than soldiers
127  city_data->urgency = 1;
128  choice->type = CT_DEFENDER;
129  choice->value.utype = ut;
130  choice->need_boat = false;
131  adv_choice_set_use(choice, "defensive diplomat");
132  } else if (num_role_units(UTYF_DIPLOMAT) > 0) {
133  // We don't know diplomats yet...
135  "A defensive diplomat is wanted badly in city %s.",
136  city_name_get(pcity));
137  ut = get_role_unit(UTYF_DIPLOMAT, 0);
138  if (ut) {
139  struct ai_plr *plr_data = def_ai_player_data(pplayer, ait);
140 
141  plr_data->tech_want[advance_index(ut->require_advance)] +=
143  TECH_LOG(ait, LOG_DEBUG, pplayer, ut->require_advance,
144  "ai_choose_diplomat_defensive() + %d for %s",
146  }
147  }
148  }
149 }
150 
156  struct player *pplayer,
157  struct city *pcity,
158  struct adv_choice *choice)
159 {
160  struct unit_type *ut = best_role_unit(pcity, UTYF_DIPLOMAT);
161  struct ai_plr *ai = def_ai_player_data(pplayer, ait);
162  int expenses;
163 
164  dai_calc_data(pplayer, nullptr, &expenses, nullptr);
165 
166  if (!ut) {
167  // We don't know diplomats yet!
168  return;
169  }
170 
171  if (has_handicap(pplayer, H_DIPLOMAT)) {
172  // Diplomats are too tough on newbies
173  return;
174  }
175 
176  // Do we have a good reason for building diplomats?
177  {
178  const struct research *presearch = research_get(pplayer);
179  struct pf_map *pfm;
180  struct pf_parameter parameter;
181  struct city *acity;
182  int want, loss, p_success, p_failure, time_to_dest;
183  int gain_incite = 0, gain_theft = 0, gain = 1;
184  int incite_cost;
185  struct unit *punit = unit_virtual_create(
186  pplayer, pcity, ut, city_production_unit_veteran_level(pcity, ut));
187 
188  pft_fill_unit_parameter(&parameter, punit);
189  parameter.omniscience = !has_handicap(pplayer, H_MAP);
190  pfm = pf_map_new(&parameter);
191 
192  find_city_to_diplomat(pplayer, punit, &acity, &time_to_dest, pfm);
193 
194  pf_map_destroy(pfm);
195  unit_virtual_destroy(punit);
196 
197  if (acity == nullptr
198  || ai->stats.diplomat_reservations.contains(acity->id)) {
199  // Found no target or city already considered
200  return;
201  }
202  incite_cost = city_incite_cost(pplayer, acity);
203  if (POTENTIALLY_HOSTILE_PLAYER(ait, pplayer, city_owner(acity))
204  && (is_action_possible_on_city(ACTION_SPY_INCITE_CITY, pplayer,
205  acity)
206  || is_action_possible_on_city(ACTION_SPY_INCITE_CITY_ESC,
207  pplayer, acity))
208  && (incite_cost < INCITE_IMPOSSIBLE_COST)
209  && (incite_cost < pplayer->economic.gold - expenses)) {
210  /* incite gain (FIXME: we should count wonders too but need to
211  cache that somehow to avoid CPU hog -- Per) */
212  gain_incite = acity->prod[O_FOOD] * FOOD_WEIGHTING
213  + acity->prod[O_SHIELD] * SHIELD_WEIGHTING
214  + (acity->prod[O_LUXURY] + acity->prod[O_GOLD]
215  + acity->prod[O_SCIENCE])
216  * TRADE_WEIGHTING;
217  gain_incite *= SHIELD_WEIGHTING; // WAG cost to take city otherwise
218  gain_incite -= incite_cost * TRADE_WEIGHTING;
219  }
220  if ((research_get(city_owner(acity))->techs_researched
221  > presearch->techs_researched)
222  && (is_action_possible_on_city(ACTION_SPY_TARGETED_STEAL_TECH,
223  pplayer, acity)
224  || is_action_possible_on_city(ACTION_SPY_TARGETED_STEAL_TECH_ESC,
225  pplayer, acity)
226  || is_action_possible_on_city(ACTION_SPY_STEAL_TECH, pplayer,
227  acity)
228  || is_action_possible_on_city(ACTION_SPY_STEAL_TECH_ESC, pplayer,
229  acity))
230  && !pplayers_allied(pplayer, city_owner(acity))) {
231  // tech theft gain
232  /* FIXME: this value is right only when
233  * 'game.info.game.info.tech_cost_style' is set to
234  * TECH_COST_CIV1CIV2. */
235  gain_theft = (research_total_bulbs_required(
236  presearch, presearch->researching, false)
237  * TRADE_WEIGHTING);
238  }
239  gain = MAX(gain_incite, gain_theft);
240  loss = utype_build_shield_cost(pcity, ut) * SHIELD_WEIGHTING;
241 
242  // Probability to succeed, assuming no defending diplomat
243  p_success = game.server.diplchance;
244  // Probability to lose our unit
245  p_failure =
246  (utype_can_do_action(ut, ACTION_SPY_TARGETED_STEAL_TECH_ESC)
247  || utype_can_do_action(ut, ACTION_SPY_STEAL_TECH_ESC)
248  ? 100 - p_success
249  : 100);
250 
251  // Get the time to dest in turns (minimum 1 turn)
252  time_to_dest = (time_to_dest + ut->move_rate - 1) / ut->move_rate;
253  // Discourage long treks
254  time_to_dest *= ((time_to_dest + 1) / 2);
255 
256  // Almost kill_desire
257  want = (p_success * gain - p_failure * loss) / 100
258  - SHIELD_WEIGHTING * time_to_dest;
259  if (want <= 0) {
260  return;
261  }
262 
263  want = military_amortize(pplayer, pcity, want, time_to_dest,
264  utype_build_shield_cost(pcity, ut));
265 
266  if (!player_has_embassy(pplayer, city_owner(acity)) && want < 99
267  && (is_action_possible_on_city(ACTION_ESTABLISH_EMBASSY, pplayer,
268  acity)
269  || is_action_possible_on_city(ACTION_ESTABLISH_EMBASSY_STAY,
270  pplayer, acity))) {
272  "A diplomat desired in %s to establish an embassy with %s "
273  "in %s",
274  city_name_get(pcity), player_name(city_owner(acity)),
275  city_name_get(acity));
276  want = 99;
277  }
278  if (want > choice->want) {
280  "%s, %s: %s is desired with want %d to spy in %s (incite "
281  "want %d cost %d gold %d, tech theft want %d, ttd %d)",
282  player_name(pplayer), city_name_get(pcity),
283  utype_rule_name(ut), want, city_name_get(acity), gain_incite,
284  incite_cost, pplayer->economic.gold - expenses, gain_theft,
285  time_to_dest);
286  choice->want = want;
287  choice->type = CT_CIVILIAN; // so we don't build barracks for it
288  choice->value.utype = ut;
289  choice->need_boat = false;
290  adv_choice_set_use(choice, "offensive diplomat");
291  ai->stats.diplomat_reservations.insert(acity->id);
292  }
293  }
294 }
295 
305 static void dai_diplomat_city(struct ai_type *ait, struct unit *punit,
306  struct city *ctarget)
307 {
308  struct action *chosen_action;
309  adv_want chosen_action_utility;
310  int chosen_sub_tgt_id;
311  struct player *pplayer = unit_owner(punit);
312  struct player *tplayer = city_owner(ctarget);
313  int count_tech = count_stealable_techs(pplayer, tplayer);
314 
315  fc_assert_ret(is_ai(pplayer));
316 
317  if (punit->moves_left == 0) {
318  UNIT_LOG(LOG_ERROR, punit, "no moves left in ai_diplomat_city()!");
319  }
320 
321  unit_activity_handling(punit, ACTIVITY_IDLE);
322 
323  // Select the best potentially legal action.
324  // FIXME: what if it is illegal?
325  chosen_action = nullptr;
326  chosen_action_utility = -1;
327  chosen_sub_tgt_id = 0;
328  action_iterate(act_id)
329  {
330  struct action *paction = action_by_number(act_id);
331  adv_want action_utility;
332  int sub_tgt_id;
333 
334  if (action_get_actor_kind(paction) != AAK_UNIT
335  || action_get_target_kind(paction) != ATK_CITY) {
336  // Not relevant here.
337  continue;
338  }
339 
341  action_prob_vs_city(punit, action_number(paction), ctarget))) {
342  // Not possible.
343  continue;
344  }
345 
346  if (paction->target_complexity == ACT_TGT_COMPL_SIMPLE) {
347  // No sub target
348  sub_tgt_id = 0;
349  } else {
350  // Pick a suitable sub target.
351  sub_tgt_id =
352  dai_action_choose_sub_tgt_unit_vs_city(paction, punit, ctarget);
353  }
354 
355  action_utility = dai_action_value_unit_vs_city(paction, punit, ctarget,
356  sub_tgt_id, count_tech);
357 
358  if (chosen_action_utility < action_utility) {
359  chosen_action = paction;
360  chosen_action_utility = action_utility;
361  chosen_sub_tgt_id = sub_tgt_id;
362  }
363  }
365 
366  if (chosen_action != nullptr) {
367  // An action has been selected.
368 
370  punit, action_number(chosen_action), ctarget))) {
371  log_base(LOG_DIPLOMAT, "%s %s[%d] does %s at %s",
373  unit_rule_name(punit), punit->id,
374  action_rule_name(chosen_action), city_name_get(ctarget));
375  unit_do_action(pplayer, punit->id, ctarget->id, chosen_sub_tgt_id, "",
376  action_number(chosen_action));
377  return;
378  }
379  }
380 
381  // This can happen for a number of odd and esoteric reasons
382  UNIT_LOG(LOG_DIPLOMAT, punit,
383  "decides to stand idle outside enemy city %s!",
384  city_name_get(ctarget));
385  dai_unit_new_task(ait, punit, AIUNIT_NONE, nullptr);
386 }
387 
392 static bool is_city_surrounded_by_our_spies(struct player *pplayer,
393  struct city *enemy_city)
394 {
395  adjc_iterate(&(wld.map), city_tile(enemy_city), ptile)
396  {
397  if (has_handicap(pplayer, H_FOG)
398  && !map_is_known_and_seen(ptile, pplayer, V_MAIN)) {
399  // We cannot see danger at (ptile) => assume there is none.
400  continue;
401  }
402  unit_list_iterate(ptile->units, punit)
403  {
404  if (unit_owner(punit) == pplayer
406  return true;
407  }
408  }
410  }
412 
413  return false;
414 }
415 
420 static void find_city_to_diplomat(struct player *pplayer, struct unit *punit,
421  struct city **ctarget, int *move_dist,
422  struct pf_map *pfm)
423 {
424  bool has_embassy;
425  int incite_cost = 0; // incite cost
426  int expenses;
427  bool dipldef; // whether target is protected by diplomats
428 
429  fc_assert_ret(punit != nullptr);
430  *ctarget = nullptr;
431  *move_dist = -1;
432  dai_calc_data(pplayer, nullptr, &expenses, nullptr);
433 
434  pf_map_move_costs_iterate(pfm, ptile, move_cost, false)
435  {
436  struct city *acity;
437  struct player *aplayer;
438  bool can_incite;
439  bool can_steal;
440 
441  acity = tile_city(ptile);
442 
443  if (!acity) {
444  continue;
445  }
446  aplayer = city_owner(acity);
447 
448  has_embassy = player_has_embassy(pplayer, aplayer);
449 
450  if (aplayer == pplayer || is_barbarian(aplayer)
451  || (pplayers_allied(pplayer, aplayer) && has_embassy)) {
452  continue;
453  }
454 
455  incite_cost = city_incite_cost(pplayer, acity);
456  can_incite = (incite_cost < INCITE_IMPOSSIBLE_COST)
457  && (is_action_possible_on_city(ACTION_SPY_INCITE_CITY,
458  pplayer, acity)
460  ACTION_SPY_INCITE_CITY_ESC, pplayer, acity));
461 
462  can_steal =
463  is_action_possible_on_city(ACTION_SPY_STEAL_TECH, pplayer, acity)
464  || is_action_possible_on_city(ACTION_SPY_STEAL_TECH_ESC, pplayer,
465  acity)
466  || is_action_possible_on_city(ACTION_SPY_TARGETED_STEAL_TECH,
467  pplayer, acity)
468  || is_action_possible_on_city(ACTION_SPY_TARGETED_STEAL_TECH_ESC,
469  pplayer, acity);
470 
471  dipldef = (count_diplomats_on_tile(acity->tile) > 0);
472  /* Three actions to consider:
473  * 1. establishing embassy OR
474  * 2. stealing techs OR
475  * 3. inciting revolt */
476  if ((!has_embassy
477  && (is_action_possible_on_city(ACTION_ESTABLISH_EMBASSY, pplayer,
478  acity)
479  || is_action_possible_on_city(ACTION_ESTABLISH_EMBASSY_STAY,
480  pplayer, acity)))
481  || (diplomats_unignored_tech_stealings(punit, acity) == 0 && !dipldef
482  && can_steal
483  && (research_get(pplayer)->techs_researched
484  < research_get(aplayer)->techs_researched))
485  || (incite_cost < (pplayer->economic.gold - expenses) && can_incite
486  && !dipldef)) {
487  if (!is_city_surrounded_by_our_spies(pplayer, acity)) {
488  // We have the closest enemy city on the continent
489  *ctarget = acity;
490  *move_dist = move_cost;
491  break;
492  }
493  }
494  }
496 }
497 
501 static struct city *dai_diplomat_defend(struct ai_type *ait,
502  struct player *pplayer,
503  struct unit *punit,
504  const struct unit_type *utype,
505  struct pf_map *pfm)
506 {
507  int best_dist = 30; // any city closer than this is better than none
508  int best_urgency = 0;
509  struct city *ctarget = nullptr;
510  struct city *pcity = tile_city(unit_tile(punit));
511 
512  if (pcity && count_diplomats_on_tile(pcity->tile) == 1
513  && def_ai_city_data(pcity, ait)->urgency > 0) {
514  // Danger and we are only diplomat present - stay.
515  return pcity;
516  }
517 
518  pf_map_move_costs_iterate(pfm, ptile, move_cost, false)
519  {
520  struct city *acity;
521  struct player *aplayer;
522  int dipls, urgency;
523  struct ai_city *city_data;
524 
525  acity = tile_city(ptile);
526  if (!acity) {
527  continue;
528  }
529  aplayer = city_owner(acity);
530  if (aplayer != pplayer) {
531  continue;
532  }
533 
534  city_data = def_ai_city_data(acity, ait);
535  urgency = city_data->urgency;
536  dipls = (count_diplomats_on_tile(ptile)
537  - (same_pos(ptile, unit_tile(punit)) ? 1 : 0));
538  if (dipls == 0 && city_data->diplomat_threat) {
539  // We are _really_ needed there
540  urgency = (urgency + 1) * 5;
541  } else if (dipls > 0) {
542  // We are probably not needed there...
543  urgency /= 3;
544  }
545 
546  // This formula may not be optimal, but it works.
547  if (move_cost > best_dist) {
548  // punish city for being so far away
549  urgency /= static_cast<float>(move_cost / best_dist);
550  }
551 
552  if (urgency > best_urgency) {
553  // Found something worthy of our presence
554  ctarget = acity;
555  best_urgency = urgency;
556  // squelch divide-by-zero
557  best_dist = MAX(move_cost, 1);
558  }
559  }
561 
562  return ctarget;
563 }
564 
570 static bool dai_diplomat_bribe_nearby(struct ai_type *ait,
571  struct player *pplayer,
572  struct unit *punit, struct pf_map *pfm)
573 {
574  int gold_avail, expenses;
575 
576  dai_calc_data(pplayer, nullptr, &expenses, nullptr);
577  gold_avail = pplayer->economic.gold - expenses;
578 
579  pf_map_positions_iterate(pfm, pos, false)
580  {
581  struct tile *ptile = pos.tile;
582  bool threat = false;
583  int newval, bestval = 0, cost;
584  struct unit *pvictim = is_other_players_unit_tile(ptile, pplayer);
585  int sanity = punit->id;
586  const struct unit_type *ptype;
587 
588  if (pos.total_MC > punit->moves_left) {
589  // Didn't find anything within range.
590  break;
591  }
592 
593  if (!pvictim
594  || !POTENTIALLY_HOSTILE_PLAYER(ait, pplayer, unit_owner(pvictim))
595  || unit_list_size(ptile->units) > 1 || tile_city(ptile)
596  || !is_action_enabled_unit_on_unit(ACTION_SPY_BRIBE_UNIT, punit,
597  pvictim)) {
598  continue;
599  }
600 
601  // Calculate if enemy is a threat
602  // First find best defender on our tile
603  unit_list_iterate(ptile->units, aunit)
604  {
605  const struct unit_type *atype = unit_type_get(aunit);
606 
607  newval = DEFENSE_POWER(atype);
608  if (bestval < newval) {
609  bestval = newval;
610  }
611  }
613  // Compare with victim's attack power
614  ptype = unit_type_get(pvictim);
615  newval = ATTACK_POWER(ptype);
616  if (newval > bestval && unit_move_rate(pvictim) > pos.total_MC) {
617  // Enemy can probably kill us
618  threat = true;
619  } else {
620  // Enemy cannot reach us or probably not kill us
621  threat = false;
622  }
623 
624  if (has_handicap(pplayer, H_NOBRIBE_WF)) {
625  // Don't bribe workers or city founders!
627  || unit_can_do_action_result(pvictim, ACTRES_FOUND_CITY)) {
628  continue;
629  }
630  }
631 
632  // Should we make the expense?
633  cost = unit_bribe_cost(pvictim, pplayer);
634  if (!threat) {
635  // Don't empty our treasure without good reason!
636  gold_avail = pplayer->economic.gold - dai_gold_reserve(pplayer);
637  }
638  if (cost > gold_avail) {
639  // Can't afford
640  continue;
641  }
642 
643  // Found someone!
644  {
645  struct tile *bribee_tile;
646  PFPath path;
647 
648  bribee_tile =
649  mapstep(&(wld.map), pos.tile,
650  static_cast<direction8>(DIR_REVERSE(pos.dir_to_here)));
651  path = pf_map_path(pfm, bribee_tile);
652  if (path.empty() || !adv_unit_execute_path(punit, path)
653  || punit->moves_left <= 0) {
654  return false;
655  }
656  }
657 
659  action_prob_vs_unit(punit, ACTION_SPY_BRIBE_UNIT, pvictim))) {
660  unit_do_action(pplayer, punit->id, pvictim->id, -1, "",
661  ACTION_SPY_BRIBE_UNIT);
662  // autoattack might kill us as we move in
663  return game_unit_by_number(sanity) && punit->moves_left > 0;
665  punit, ACTION_SPY_SABOTAGE_UNIT_ESC, pvictim))
666  && threat) {
667  // don't stand around waiting for the final blow
668  unit_do_action(pplayer, punit->id, pvictim->id, -1, "",
669  ACTION_SPY_SABOTAGE_UNIT_ESC);
670  // autoattack might kill us as we move in
671  return game_unit_by_number(sanity) && punit->moves_left > 0;
672  } else {
673  // usually because we ended move early due to another unit
674  UNIT_LOG(LOG_DIPLOMAT, punit,
675  "could not bribe target (%d, %d), "
676  " %d moves left",
677  TILE_XY(pos.tile), punit->moves_left);
678  return false;
679  }
680  }
682 
683  return (punit->moves_left > 0);
684 }
685 
696 void dai_manage_diplomat(struct ai_type *ait, struct player *pplayer,
697  struct unit *punit)
698 {
699  struct city *pcity, *ctarget = nullptr;
700  struct pf_parameter parameter;
701  struct pf_map *pfm;
702  struct pf_position pos;
703  struct unit_ai *unit_data;
704 
705  CHECK_UNIT(punit);
706 
707  // Generate map
708  pft_fill_unit_parameter(&parameter, punit);
709  parameter.omniscience = !has_handicap(pplayer, H_MAP);
710  parameter.get_zoc = nullptr; // kludge
711  parameter.get_TB = no_intermediate_fights;
712  pfm = pf_map_new(&parameter);
713 
714  pcity = tile_city(unit_tile(punit));
715 
716  // Look for someone to bribe
717  if (!dai_diplomat_bribe_nearby(ait, pplayer, punit, pfm)) {
718  // Died or ran out of moves
719  pf_map_destroy(pfm);
720  return;
721  }
722 
723  // If we are the only diplomat in a threatened city, then stay to defend
724  pcity = tile_city(unit_tile(punit)); // we may have moved
725  if (pcity) {
726  struct ai_city *city_data = def_ai_city_data(pcity, ait);
727 
728  if (count_diplomats_on_tile(unit_tile(punit)) == 1
729  && (city_data->diplomat_threat || city_data->urgency > 0)) {
730  UNIT_LOG(LOG_DIPLOMAT, punit, "stays to protect %s (urg %d)",
731  city_name_get(pcity), city_data->urgency);
732  dai_unit_new_task(ait, punit, AIUNIT_NONE, nullptr); // abort mission
733  def_ai_unit_data(punit, ait)->done = true;
734  pf_map_destroy(pfm);
735  return;
736  }
737  }
738 
739  unit_data = def_ai_unit_data(punit, ait);
740 
741  // Check if existing target still makes sense
742  if (unit_data->task == AIUNIT_ATTACK
743  || unit_data->task == AIUNIT_DEFEND_HOME) {
744  bool failure = false;
745 
746  ctarget = tile_city(punit->goto_tile);
747  if (pf_map_position(pfm, punit->goto_tile, &pos) && ctarget) {
748  if (same_pos(ctarget->tile, unit_tile(punit))) {
749  failure = true;
750  } else if (pplayers_allied(pplayer, city_owner(ctarget))
751  && unit_data->task == AIUNIT_ATTACK
752  && player_has_embassy(pplayer, city_owner(ctarget))) {
753  // We probably incited this city with another diplomat
754  failure = true;
755  } else if (!pplayers_allied(pplayer, city_owner(ctarget))
756  && unit_data->task == AIUNIT_DEFEND_HOME) {
757  // We probably lost the city
758  failure = true;
759  }
760  } else {
761  // City vanished!
762  failure = true;
763  }
764  if (failure) {
765  UNIT_LOG(LOG_DIPLOMAT, punit, "mission aborted");
766  dai_unit_new_task(ait, punit, AIUNIT_NONE, nullptr);
767  }
768  }
769 
770  /* We may need a new map now. Both because we cannot get paths from an
771  * old map, and we need paths to move, and because fctd below requires
772  * a new map for its iterator. */
773  if (!same_pos(parameter.start_tile, unit_tile(punit))
774  || unit_data->task == AIUNIT_NONE) {
775  pf_map_destroy(pfm);
776  pft_fill_unit_parameter(&parameter, punit);
777  parameter.omniscience = !has_handicap(pplayer, H_MAP);
778  parameter.get_zoc = nullptr; // kludge
779  parameter.get_TB = no_intermediate_fights;
780  pfm = pf_map_new(&parameter);
781  }
782 
783  // If we are not busy, acquire a target.
784  if (unit_data->task == AIUNIT_NONE) {
785  enum ai_unit_task task;
786  int move_dist; // dummy
787 
788  find_city_to_diplomat(pplayer, punit, &ctarget, &move_dist, pfm);
789 
790  if (ctarget) {
791  task = AIUNIT_ATTACK;
792  aiguard_request_guard(ait, punit);
793  UNIT_LOG(LOG_DIPLOMAT, punit, "going on attack");
794  } else if ((ctarget = dai_diplomat_defend(ait, pplayer, punit,
795  unit_type_get(punit), pfm))
796  != nullptr) {
797  task = AIUNIT_DEFEND_HOME;
798  UNIT_LOG(LOG_DIPLOMAT, punit, "going to defend %s",
799  city_name_get(ctarget));
800  } else if ((ctarget = find_closest_city(unit_tile(punit), nullptr,
801  pplayer, true, false, false,
802  true, false, nullptr))
803  != nullptr) {
804  /* This should only happen if the entire continent was suddenly
805  * conquered. So we head for closest coastal city and wait for someone
806  * to code ferrying for diplomats, or hostile attacks from the sea. */
807  task = AIUNIT_DEFEND_HOME;
808  UNIT_LOG(LOG_DIPLOMAT, punit, "going idle");
809  } else {
810  UNIT_LOG(LOG_DIPLOMAT, punit, "could not find a job");
811  def_ai_unit_data(punit, ait)->done = true;
812  pf_map_destroy(pfm);
813  return;
814  }
815 
816  dai_unit_new_task(ait, punit, task, ctarget->tile);
817  fc_assert(punit->moves_left > 0 && ctarget
818  && unit_data->task != AIUNIT_NONE);
819  }
820 
821  CHECK_UNIT(punit);
822  if (ctarget == nullptr) {
823  UNIT_LOG(LOG_ERROR, punit, "ctarget not set (task == %d)",
824  unit_data->task);
825  pf_map_destroy(pfm);
826  return;
827  }
828 
829  // GOTO unless we want to stay
830  if (!same_pos(unit_tile(punit), ctarget->tile)) {
831  auto path = pf_map_path(pfm, punit->goto_tile);
832  if (!path.empty() && adv_unit_execute_path(punit, path)
833  && punit->moves_left > 0) {
834  // Check if we can do something with our destination now.
835  if (unit_data->task == AIUNIT_ATTACK) {
836  int dist = real_map_distance(unit_tile(punit), punit->goto_tile);
837 
838  UNIT_LOG(LOG_DIPLOMAT, punit, "attack, dist %d to %s", dist,
839  ctarget ? city_name_get(ctarget) : "(none)");
840  if (dist <= 1) {
841  // Do our stuff
842  dai_unit_new_task(ait, punit, AIUNIT_NONE, nullptr);
843  dai_diplomat_city(ait, punit, ctarget);
844  }
845  }
846  }
847  } else {
848  def_ai_unit_data(punit, ait)->done = true;
849  }
850  pf_map_destroy(pfm);
851 }
bool is_action_possible_on_city(action_id act_id, const struct player *actor_player, const struct city *target_city)
Returns TRUE if the wanted action can be done to the target city.
Definition: actions.cpp:5734
bool is_action_enabled_unit_on_unit(const action_id wanted_action, const struct unit *actor_unit, const struct unit *target_unit)
Returns TRUE if actor_unit can do wanted_action to target_unit as far as action enablers are concerne...
Definition: actions.cpp:4007
enum action_actor_kind action_get_actor_kind(const struct action *paction)
Get the actor kind of an action.
Definition: actions.cpp:1188
const char * action_rule_name(const struct action *action)
Get the rule name of the action.
Definition: actions.cpp:1343
bool action_prob_possible(const struct act_prob probability)
Returns TRUE iff the given action probability belongs to an action that may be possible.
Definition: actions.cpp:5380
struct act_prob action_prob_vs_city(const struct unit *actor_unit, const action_id act_id, const struct city *target_city)
Get the actor unit's probability of successfully performing the chosen action on the target city.
Definition: actions.cpp:4809
struct act_prob action_prob_vs_unit(const struct unit *actor_unit, const action_id act_id, const struct unit *target_unit)
Get the actor unit's probability of successfully performing the chosen action on the target unit.
Definition: actions.cpp:4871
int action_number(const struct action *action)
Get the universal number of the action.
Definition: actions.cpp:1338
struct action * action_by_number(action_id act_id)
Return the action with the given id.
Definition: actions.cpp:1149
enum action_target_kind action_get_target_kind(const struct action *paction)
Get the target kind of an action.
Definition: actions.cpp:1198
#define action_iterate_end
Definition: actions.h:383
#define action_iterate(_act_)
Definition: actions.h:378
#define TRADE_WEIGHTING
Definition: advbuilding.h:18
#define FOOD_WEIGHTING
Definition: advbuilding.h:16
#define SHIELD_WEIGHTING
Definition: advbuilding.h:17
#define adv_choice_set_use(_choice, _use)
Definition: advchoice.h:69
@ CT_CIVILIAN
Definition: advchoice.h:25
@ CT_DEFENDER
Definition: advchoice.h:27
bool adv_unit_execute_path(struct unit *punit, const PFPath &path)
This is a function to execute paths returned by the path-finding engine, for units controlled by advi...
Definition: advgoto.cpp:78
bool aia_utype_is_considered_spy(const struct unit_type *putype)
Returns TRUE if the specified unit type is able to perform diplomatic actions.
Definition: aiactions.cpp:45
bool aia_utype_is_considered_worker(const struct unit_type *putype)
Returns TRUE if the specified unit type is able to perform worker actions.
Definition: aiactions.cpp:67
static bool is_city_surrounded_by_our_spies(struct player *pplayer, struct city *pcity)
Check if we have a diplomat / spy near a given city.
Definition: aidiplomat.cpp:392
void dai_choose_diplomat_defensive(struct ai_type *ait, struct player *pplayer, struct city *pcity, struct adv_choice *choice, int def)
Calculates our need for diplomats as defensive units.
Definition: aidiplomat.cpp:108
static struct city * dai_diplomat_defend(struct ai_type *ait, struct player *pplayer, struct unit *punit, const struct unit_type *utype, struct pf_map *pfm)
Go to nearest/most threatened city (can be the current city too).
Definition: aidiplomat.cpp:501
void dai_manage_diplomat(struct ai_type *ait, struct player *pplayer, struct unit *punit)
If we are the only diplomat in a threatened city, defend against enemy actions.
Definition: aidiplomat.cpp:696
#define LOG_DIPLOMAT_BUILD
Definition: aidiplomat.cpp:66
static void dai_diplomat_city(struct ai_type *ait, struct unit *punit, struct city *ctarget)
Check if something is on our receiving end for some nasty diplomat business! Note that punit may die ...
Definition: aidiplomat.cpp:305
void dai_choose_diplomat_offensive(struct ai_type *ait, struct player *pplayer, struct city *pcity, struct adv_choice *choice)
Calculates our need for diplomats as offensive units.
Definition: aidiplomat.cpp:155
#define LOG_DIPLOMAT
Definition: aidiplomat.cpp:65
#define DIPLO_DEFENSE_WANT
Definition: aidiplomat.cpp:70
static bool dai_diplomat_bribe_nearby(struct ai_type *ait, struct player *pplayer, struct unit *punit, struct pf_map *pfm)
Find units that we can reach, and bribe them.
Definition: aidiplomat.cpp:570
static int count_stealable_techs(struct player *pplayer, struct player *tplayer)
Number of techs that we don't have and the enemy (tplayer) does.
Definition: aidiplomat.cpp:84
static void find_city_to_diplomat(struct player *pplayer, struct unit *punit, struct city **ctarget, int *move_dist, struct pf_map *pfm)
Returns (in ctarget) the closest city to send diplomats against, or nullptr if none available on this...
Definition: aidiplomat.cpp:420
void aiguard_request_guard(struct ai_type *ait, struct unit *punit)
Request a (new) bodyguard for the unit.
Definition: aiguard.cpp:218
void dai_calc_data(const struct player *pplayer, int *trade, int *expenses, int *income)
Returns the total amount of trade generated (trade) and total amount of gold needed as upkeep (expens...
Definition: aihand.cpp:111
#define TECH_LOG(ait, _, pplayer, padvance, msg,...)
Definition: ailog.h:32
static struct ai_plr * def_ai_player_data(const struct player *pplayer, struct ai_type *deftype)
Definition: aiplayer.h:47
static struct ai_city * def_ai_city_data(const struct city *pcity, struct ai_type *deftype)
Definition: aiplayer.h:35
static struct unit_ai * def_ai_unit_data(const struct unit *punit, struct ai_type *deftype)
Definition: aiplayer.h:41
void dai_unit_new_task(struct ai_type *ait, struct unit *punit, enum ai_unit_task task, struct tile *ptile)
Ensure unit sanity by telling charge that we won't bodyguard it anymore, tell bodyguard it can roam f...
Definition: aitools.cpp:648
int dai_gold_reserve(struct player *pplayer)
Credits the AI wants to have in reserves.
Definition: aitools.cpp:1120
int military_amortize(struct player *pplayer, struct city *pcity, int value, int delay, int build_cost)
Amortize a want modified by the shields (build_cost) we risk losing.
Definition: aitools.cpp:132
#define POTENTIALLY_HOSTILE_PLAYER(ait, pplayer, aplayer)
Definition: aiunit.h:77
ai_unit_task
Definition: aiunit.h:25
@ AIUNIT_NONE
Definition: aiunit.h:26
@ AIUNIT_ATTACK
Definition: aiunit.h:30
@ AIUNIT_DEFEND_HOME
Definition: aiunit.h:29
#define DEFENSE_POWER(ptype)
Definition: aiunit.h:71
#define ATTACK_POWER(ptype)
Definition: aiunit.h:73
struct player * city_owner(const struct city *pcity)
Return the owner of the city.
Definition: city.cpp:1083
struct tile * city_tile(const struct city *pcity)
Return the tile location of the city.
Definition: city.cpp:1095
int city_production_unit_veteran_level(struct city *pcity, const struct unit_type *punittype)
How many veteran levels will created unit of this type get?
Definition: city.cpp:768
const char * city_name_get(const struct city *pcity)
Return the name of the city.
Definition: city.cpp:1077
#define INCITE_IMPOSSIBLE_COST
Definition: city.h:69
struct city * find_closest_city(const struct tile *ptile, const struct city *pexclcity, const struct player *pplayer, bool only_ocean, bool only_continent, bool only_known, bool only_player, bool only_enemy, const struct unit_class *pclass)
Find the city closest to 'ptile'.
Definition: citytools.cpp:849
int city_incite_cost(struct player *pplayer, struct city *pcity)
Returns the cost to incite a city.
Definition: cityturn.cpp:3135
bool empty() const
int dai_action_choose_sub_tgt_unit_vs_city(struct action *paction, struct unit *actor_unit, struct city *target_city)
Returns the sub target id of the sub target chosen for the specified action performed by the specifie...
Definition: daiactions.cpp:298
adv_want dai_action_value_unit_vs_city(struct action *paction, struct unit *actor_unit, struct city *target_city, int sub_tgt_id, int count_tech)
Returns the utility of having the specified unit perform the specified action to the specified city t...
Definition: daiactions.cpp:90
int diplomats_unignored_tech_stealings(struct unit *pdiplomat, struct city *pcity)
Returns the amount of tech thefts from a city not ignored by the EFT_STEALINGS_IGNORE effect.
Definition: diplomats.cpp:764
int count_diplomats_on_tile(struct tile *ptile)
Return number of diplomats on this square.
Definition: diplomats.cpp:2149
float adv_want
Definition: fc_types.h:1144
@ O_SHIELD
Definition: fc_types.h:86
@ O_FOOD
Definition: fc_types.h:85
@ O_SCIENCE
Definition: fc_types.h:90
@ O_LUXURY
Definition: fc_types.h:89
@ O_GOLD
Definition: fc_types.h:88
struct unit * game_unit_by_number(int id)
Find unit out of all units in game: now uses fast idex method, instead of looking through all units o...
Definition: game.cpp:112
struct civ_game game
Definition: game.cpp:47
struct world wld
Definition: game.cpp:48
bool has_handicap(const struct player *pplayer, enum handicap_type htype)
AI players may have handicaps - allowing them to cheat or preventing them from using certain algorith...
Definition: handicaps.cpp:62
@ H_MAP
Definition: handicaps.h:27
@ H_DIPLOMAT
Definition: handicaps.h:17
@ H_NOBRIBE_WF
Definition: handicaps.h:33
@ H_FOG
Definition: handicaps.h:25
constexpr auto LOG_DEBUG
Definition: log.h:27
#define fc_assert_ret(condition)
Definition: log.h:112
constexpr auto LOG_ERROR
Definition: log.h:23
#define fc_assert(condition)
Definition: log.h:89
#define log_base(level, message,...)
Definition: log.h:41
bool same_pos(const struct tile *tile1, const struct tile *tile2)
Are (x1,y1) and (x2,y2) really the same when adjusted? This function might be necessary ALOT of place...
Definition: map.cpp:887
int real_map_distance(const struct tile *tile0, const struct tile *tile1)
Return real distance between two tiles.
Definition: map.cpp:599
struct tile * mapstep(const struct civ_map *nmap, const struct tile *ptile, enum direction8 dir)
Step from the given tile in the given direction.
Definition: map.cpp:342
#define adjc_iterate_end
Definition: map.h:358
#define adjc_iterate(nmap, center_tile, itr_tile)
Definition: map.h:351
#define DIR_REVERSE(dir)
Definition: map.h:487
bool map_is_known_and_seen(const struct tile *ptile, const struct player *pplayer, enum vision_layer vlayer)
Returns whether the layer 'vlayer' of the tile 'ptile' is known and seen by the player 'pplayer'.
Definition: maphand.cpp:894
int unit_move_rate(const struct unit *punit)
This function calculates the move rate of the unit.
Definition: movement.cpp:78
const char * nation_rule_name(const struct nation_type *pnation)
Return the (untranslated) rule name of the nation (adjective form).
Definition: nation.cpp:115
struct nation_type * nation_of_unit(const struct unit *punit)
Return the nation of the player who owns the unit.
Definition: nation.cpp:438
bool pf_map_position(struct pf_map *pfm, struct tile *ptile, struct pf_position *pos)
Get info about position at ptile and put it in pos.
struct pf_map * pf_map_new(const struct pf_parameter *parameter)
Factory function to create a new map according to the parameter.
PFPath pf_map_path(struct pf_map *pfm, struct tile *ptile)
CHECK DOCS AFTER FULL CONVERSTION OF pf_path to class PFPath Tries to find the best path in the given...
void pf_map_destroy(struct pf_map *pfm)
After usage the map must be destroyed.
#define pf_map_move_costs_iterate_end
Definition: path_finding.h:542
#define pf_map_positions_iterate_end
Definition: path_finding.h:564
#define pf_map_move_costs_iterate(ARG_pfm, NAME_tile, NAME_cost, COND_from_start)
Definition: path_finding.h:532
#define pf_map_positions_iterate(ARG_pfm, NAME_pos, COND_from_start)
Definition: path_finding.h:557
void pft_fill_unit_parameter(struct pf_parameter *parameter, const struct unit *punit)
Fill classic parameters for an unit.
Definition: pf_tools.cpp:822
enum tile_behavior no_intermediate_fights(const struct tile *ptile, enum known_type known, const struct pf_parameter *param)
PF callback to prohibit attacking anyone, except at the destination.
Definition: pf_tools.cpp:499
const char * player_name(const struct player *pplayer)
Return the leader name of the player.
Definition: player.cpp:816
bool pplayers_allied(const struct player *pplayer, const struct player *pplayer2)
Returns true iff players are allied.
Definition: player.cpp:1334
bool player_has_embassy(const struct player *pplayer, const struct player *pplayer2)
Check if pplayer has an embassy with pplayer2.
Definition: player.cpp:195
static bool is_barbarian(const struct player *pplayer)
Definition: player.h:474
#define is_ai(plr)
Definition: player.h:227
struct research * research_get(const struct player *pplayer)
Returns the research structure associated with the player.
Definition: research.cpp:110
int research_total_bulbs_required(const struct research *presearch, Tech_type_id tech, bool loss_value)
Function to determine cost for technology.
Definition: research.cpp:855
enum tech_state research_invention_state(const struct research *presearch, Tech_type_id tech)
Returns state of the tech for current research.
Definition: research.cpp:609
#define MAX(x, y)
Definition: shared.h:48
#define UNIT_LOG(_, punit, msg,...)
Definition: srv_log.h:95
enum act_tgt_compl target_complexity
Definition: actions.h:315
enum choice_type type
Definition: advchoice.h:32
adv_want want
Definition: advchoice.h:34
universals_u value
Definition: advchoice.h:33
bool need_boat
Definition: advchoice.h:35
int urgency
Definition: daicity.h:46
bool has_diplomat
Definition: daicity.h:56
bool diplomat_threat
Definition: daicity.h:55
Definition: aidata.h:63
adv_want tech_want[A_LAST+1]
Definition: aidata.h:95
QSet< int > diplomat_reservations
Definition: aidata.h:77
struct ai_plr::@155 stats
Definition: ai.h:42
Definition: city.h:291
int id
Definition: city.h:296
struct tile * tile
Definition: city.h:293
int prod[O_LAST]
Definition: city.h:327
struct civ_game::@28::@32 server
enum tile_behavior(* get_TB)(const struct tile *ptile, enum known_type known, const struct pf_parameter *param)
Definition: path_finding.h:380
bool(* get_zoc)(const struct player *pplayer, const struct tile *ptile, const struct civ_map *zmap)
Definition: path_finding.h:412
struct tile * start_tile
Definition: path_finding.h:341
Definition: player.h:231
struct player_economic economic
Definition: player.h:266
Tech_type_id researching
Definition: research.h:45
int techs_researched
Definition: research.h:35
Definition: tile.h:42
struct unit_list * units
Definition: tile.h:50
Definition: aiunit.h:39
bool done
Definition: aiunit.h:51
enum ai_unit_task task
Definition: aiunit.h:53
int move_rate
Definition: unittype.h:481
struct advance * require_advance
Definition: unittype.h:484
Definition: unit.h:134
int moves_left
Definition: unit.h:147
int id
Definition: unit.h:141
struct tile * goto_tile
Definition: unit.h:152
struct civ_map map
Definition: world_object.h:21
Tech_type_id advance_index(const struct advance *padvance)
Return the advance index.
Definition: tech.cpp:76
#define advance_index_iterate_end
Definition: tech.h:226
#define A_FIRST
Definition: tech.h:37
#define advance_index_iterate(_start, _index)
Definition: tech.h:221
struct city * tile_city(const struct tile *ptile)
Return the city on this tile (or nullptr), checking for city center.
Definition: tile.cpp:72
#define TILE_XY(ptile)
Definition: tile.h:36
const struct unit_type * utype
Definition: fc_types.h:585
struct unit * is_other_players_unit_tile(const struct tile *ptile, const struct player *pplayer)
Is there an unit belonging to another player on this tile?
Definition: unit.cpp:1269
int unit_bribe_cost(struct unit *punit, struct player *briber)
Calculate how expensive it is to bribe the unit.
Definition: unit.cpp:2061
bool unit_can_do_action_result(const struct unit *punit, enum action_result result)
Return TRUE iff this unit can do any enabler controlled action with the specified action result.
Definition: unit.cpp:318
void unit_virtual_destroy(struct unit *punit)
Free the memory used by virtual unit.
Definition: unit.cpp:1588
struct unit * unit_virtual_create(struct player *pplayer, struct city *pcity, const struct unit_type *punittype, int veteran_level)
Create a virtual unit skeleton.
Definition: unit.cpp:1490
#define unit_tile(_pu)
Definition: unit.h:371
#define CHECK_UNIT(punit)
Definition: unit.h:264
#define unit_owner(_pu)
Definition: unit.h:370
bool unit_activity_handling(struct unit *punit, enum unit_activity new_activity)
Handle request for changing activity.
Definition: unithand.cpp:5485
void unit_do_action(struct player *pplayer, const int actor_id, const int target_id, const int sub_tgt_id, const char *name, const action_id action_type)
Handle unit action.
Definition: unithand.cpp:2718
#define unit_list_iterate(unitlist, punit)
Definition: unitlist.h:25
#define unit_list_iterate_end
Definition: unitlist.h:27
const char * unit_rule_name(const struct unit *punit)
Return the (untranslated) rule name of the unit.
Definition: unittype.cpp:1283
const struct unit_type * unit_type_get(const struct unit *punit)
Return the unit type for this unit.
Definition: unittype.cpp:114
struct unit_type * best_role_unit(const struct city *pcity, int role)
Return "best" unit this city can build, with given role/flag.
Definition: unittype.cpp:1920
const char * utype_rule_name(const struct unit_type *punittype)
Return the (untranslated) rule name of the unit type.
Definition: unittype.cpp:1274
int utype_build_shield_cost(const struct city *pcity, const struct unit_type *punittype)
Returns the number of shields it takes to build this unit type.
Definition: unittype.cpp:1141
int num_role_units(int role)
How many unit types have specified role/flag.
Definition: unittype.cpp:1866
struct unit_type * get_role_unit(int role, int role_index)
Return index-th unit with specified role/flag.
Definition: unittype.cpp:1900
bool utype_can_do_action(const struct unit_type *putype, const action_id act_id)
Return TRUE iff units of the given type can do the specified generalized (ruleset defined) action ena...
Definition: unittype.cpp:386