1 /***********************************************************************
2  Freeciv - Copyright (C) 2002 - The Freeciv Project
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 "log.h"
20 #include "mem.h"
21 
22 /* common */
23 #include "actions.h"
24 #include "ai.h"
25 #include "city.h"
26 #include "effects.h"
27 #include "game.h"
28 #include "government.h"
29 #include "map.h"
30 #include "movement.h"
31 #include "research.h"
32 #include "unit.h"
33 #include "unitlist.h"
34 
35 /* common/aicore */
36 #include "aisupport.h"
37 #include "path_finding.h"
38 #include "pf_tools.h"
39 
40 /* server */
41 #include "cityturn.h"
42 #include "diplhand.h"
43 #include "maphand.h"
44 #include "plrhand.h"
45 #include "srv_log.h"
46 #include "unittools.h"
47 
48 /* server/advisors */
49 #include "advbuilding.h"
50 #include "advcity.h"
51 #include "advtools.h"
52 #include "autosettlers.h"
53 
54 /* ai */
55 #include "handicaps.h"
56 
57 #include "advdata.h"
58 
59 static void adv_dipl_new(const struct player *plr1,
60                          const struct player *plr2);
61 static void adv_dipl_free(const struct player *plr1,
62                           const struct player *plr2);
63 static struct adv_dipl *adv_dipl_get(const struct player *plr1,
64                                      const struct player *plr2);
65 
66 /**************************************************************************
67   Precalculates some important data about the improvements in the game
68   that we use later in ai/default/aicity.c. We mark improvements as
69   'calculate' if we want to run a full test on them, as 'estimate' if
70   we just want to do some guesses on them, or as 'unused' is they are
71   useless to us. Then we find the largest range of calculatable effects
72   in the improvement and record it for later use.
73 **************************************************************************/
adv_data_city_impr_calc(struct player * pplayer,struct adv_data * adv)74 static void adv_data_city_impr_calc(struct player *pplayer,
75 				    struct adv_data *adv)
76 {
77   int count[ADV_IMPR_LAST];
78 
79   memset(count, 0, sizeof(count));
80 
81   improvement_iterate(pimprove) {
82     struct universal source = {
83       .kind = VUT_IMPROVEMENT,
84       .value = {.building = pimprove}
85     };
86 
87     adv->impr_calc[improvement_index(pimprove)] = ADV_IMPR_ESTIMATE;
88 
89     /* Find largest extension */
90     effect_list_iterate(get_req_source_effects(&source), peffect) {
91       switch (peffect->type) {
92 #if 0
93       /* TODO */
94       case EFT_FORCE_CONTENT:
95       case EFT_FORCE_CONTENT_PCT:
96       case EFT_MAKE_CONTENT:
97       case EFT_MAKE_CONTENT_MIL:
98       case EFT_MAKE_CONTENT_MIL_PER:
99       case EFT_MAKE_CONTENT_PCT:
100       case EFT_MAKE_HAPPY:
101 #endif
102       case EFT_CAPITAL_CITY:
103       case EFT_POLLU_POP_PCT:
104       case EFT_POLLU_POP_PCT_2:
105       case EFT_POLLU_PROD_PCT:
106       case EFT_OUTPUT_BONUS:
107       case EFT_OUTPUT_BONUS_2:
108       case EFT_OUTPUT_WASTE_PCT:
109       case EFT_UPKEEP_FREE:
110 	requirement_vector_iterate(&peffect->reqs, preq) {
111 	  if (VUT_IMPROVEMENT == preq->source.kind
112 	      && preq->source.value.building == pimprove) {
113             if (adv->impr_calc[improvement_index(pimprove)] != ADV_IMPR_CALCULATE_FULL) {
114 	      adv->impr_calc[improvement_index(pimprove)] = ADV_IMPR_CALCULATE;
115             }
116 	    if (preq->range > adv->impr_range[improvement_index(pimprove)]) {
117 	      adv->impr_range[improvement_index(pimprove)] = preq->range;
118 	    }
119 	  }
120 	} requirement_vector_iterate_end;
121         break;
122       case EFT_OUTPUT_ADD_TILE:
123       case EFT_OUTPUT_PER_TILE:
124       case EFT_OUTPUT_INC_TILE:
125 	requirement_vector_iterate(&peffect->reqs, preq) {
126 	  if (VUT_IMPROVEMENT == preq->source.kind
127 	      && preq->source.value.building == pimprove) {
128 	    adv->impr_calc[improvement_index(pimprove)] = ADV_IMPR_CALCULATE_FULL;
129 	    if (preq->range > adv->impr_range[improvement_index(pimprove)]) {
130 	      adv->impr_range[improvement_index(pimprove)] = preq->range;
131 	    }
132 	  }
133 	} requirement_vector_iterate_end;
134       break;
135       default:
136       /* Nothing! */
137       break;
138       }
139     } effect_list_iterate_end;
140   } improvement_iterate_end;
141 }
142 
143 /**************************************************************************
144   Check if the player still takes advantage of EFT_TECH_PARASITE.
145   Research is useless if there are still techs which may be given to the
146   player for free.
147 **************************************************************************/
player_has_really_useful_tech_parasite(struct player * pplayer)148 static bool player_has_really_useful_tech_parasite(struct player* pplayer)
149 {
150   struct research *presearch, *aresearch;
151   int players_needed = get_player_bonus(pplayer, EFT_TECH_PARASITE);
152 
153   if (players_needed == 0) {
154     return FALSE;
155   }
156 
157   presearch = research_get(pplayer);
158   advance_index_iterate(A_FIRST, tech) {
159     int players_having;
160 
161     if (!research_invention_gettable(presearch, tech,
162                                      game.info.tech_parasite_allow_holes)
163         || TECH_KNOWN == research_invention_state(presearch, tech)) {
164       continue;
165     }
166 
167     players_having = 0;
168 
169     players_iterate_alive(aplayer) {
170       if (aplayer == pplayer) {
171         continue;
172       }
173 
174       aresearch = research_get(aplayer);
175       if (TECH_KNOWN == research_invention_state(aresearch, tech)
176           || aresearch->researching == tech) {
177 	players_having++;
178 	if (players_having >= players_needed) {
179 	  return TRUE;
180 	}
181       }
182     } players_iterate_alive_end;
183   } advance_index_iterate_end;
184   return FALSE;
185 }
186 
187 /**************************************************************************
188   Analyze rulesets. Must be run after rulesets are loaded, unlike
189   _init, which must be run before savegames are loaded, which is usually
190   before rulesets.
191 **************************************************************************/
adv_data_analyze_rulesets(struct player * pplayer)192 void adv_data_analyze_rulesets(struct player *pplayer)
193 {
194   struct adv_data *adv = pplayer->server.adv;
195 
196   fc_assert_ret(adv != NULL);
197 
198   adv_data_city_impr_calc(pplayer, adv);
199 }
200 
201 /**************************************************************************
202   This function is called each turn to initialize pplayer->ai.stats.units.
203 **************************************************************************/
count_my_units(struct player * pplayer)204 static void count_my_units(struct player *pplayer)
205 {
206   struct adv_data *adv = adv_data_get(pplayer, NULL);
207 
208   memset(&adv->stats.units, 0, sizeof(adv->stats.units));
209 
210   unit_list_iterate(pplayer->units, punit) {
211     struct unit_class *pclass = unit_class_get(punit);
212 
213     adv->stats.units.byclass[uclass_index(pclass)]++;
214 
215     if (unit_has_type_flag(punit, UTYF_TRIREME)) {
216       adv->stats.units.triremes++;
217     }
218     if (uclass_has_flag(pclass, UCF_MISSILE)) {
219       adv->stats.units.missiles++;
220     }
221     if (unit_has_type_flag(punit, UTYF_PARATROOPERS)) {
222       adv->stats.units.paratroopers++;
223     }
224     if (uclass_has_flag(pclass, UCF_AIRLIFTABLE)) {
225       adv->stats.units.airliftable++;
226     }
227     if (can_upgrade_unittype(pplayer, unit_type_get(punit)) >= 0) {
228       adv->stats.units.upgradeable++;
229     }
230   } unit_list_iterate_end;
231 }
232 
233 /**************************************************************************
234   Return whether data phase is currently open. Data phase is open
235   between adv_data_phase_init() and adv_data_phase_done() calls.
236 **************************************************************************/
is_adv_data_phase_open(struct player * pplayer)237 bool is_adv_data_phase_open(struct player *pplayer)
238 {
239   struct adv_data *adv = pplayer->server.adv;
240 
241   return adv->phase_is_initialized;
242 }
243 
244 /**************************************************************************
245   Make and cache lots of calculations needed for other functions.
246 
247   Returns TRUE if new data was created, FALSE if data existed already.
248 
249   Note: We use map.num_continents here rather than pplayer->num_continents
250   because we are omniscient and don't care about such trivialities as who
251   can see what.
252 
253   FIXME: We should try to find the lowest common defence strength of our
254   defending units, and ignore enemy units that are incapable of harming
255   us, instead of just checking attack strength > 1.
256 **************************************************************************/
adv_data_phase_init(struct player * pplayer,bool is_new_phase)257 bool adv_data_phase_init(struct player *pplayer, bool is_new_phase)
258 {
259   struct adv_data *adv = pplayer->server.adv;
260   int i;
261   int nuke_units;
262   bool danger_of_nukes;
263 
264   fc_assert_ret_val(adv != NULL, FALSE);
265 
266   if (adv->phase_is_initialized) {
267     return FALSE;
268   }
269   adv->phase_is_initialized = TRUE;
270 
271   TIMING_LOG(AIT_AIDATA, TIMER_START);
272 
273   nuke_units = num_role_units(UTYF_NUCLEAR);
274   danger_of_nukes = FALSE;
275 
276   /*** Threats ***/
277 
278   adv->num_continents    = game.map.num_continents;
279   adv->num_oceans        = game.map.num_oceans;
280   adv->threats.continent = fc_calloc(adv->num_continents + 1, sizeof(bool));
281   adv->threats.invasions = FALSE;
282   adv->threats.nuclear   = 0; /* none */
283   adv->threats.ocean     = fc_calloc(adv->num_oceans + 1, sizeof(bool));
284   adv->threats.igwall    = FALSE;
285 
286   players_iterate(aplayer) {
287     if (!adv_is_player_dangerous(pplayer, aplayer)) {
288       continue;
289     }
290 
291     /* The idea is that if there aren't any hostile cities on
292      * our continent, the danger of land attacks is not big
293      * enough to warrant city walls. Concentrate instead on
294      * coastal fortresses and hunting down enemy transports. */
295     city_list_iterate(aplayer->cities, acity) {
296       Continent_id continent = tile_continent(acity->tile);
297       if (continent >= 0) {
298         adv->threats.continent[continent] = TRUE;
299       }
300     } city_list_iterate_end;
301 
302     unit_list_iterate(aplayer->units, punit) {
303       const struct unit_class *pclass = unit_class_get(punit);
304 
305       if (unit_type_get(punit)->adv.igwall) {
306         adv->threats.igwall = TRUE;
307       }
308 
309       if (pclass->adv.sea_move != MOVE_NONE) {
310         /* If the enemy has not started sailing yet, or we have total
311          * control over the seas, don't worry, keep attacking. */
312         if (uclass_has_flag(pclass, UCF_CAN_OCCUPY_CITY)) {
313           /* Enemy represents a cross-continental threat! */
314           adv->threats.invasions = TRUE;
315         } else if (get_transporter_capacity(punit) > 0) {
316           unit_class_iterate(cargoclass) {
317             if (uclass_has_flag(cargoclass, UCF_CAN_OCCUPY_CITY)
318                 && can_unit_type_transport(unit_type_get(punit), cargoclass)) {
319               /* Enemy can transport some threatening units! */
320               adv->threats.invasions = TRUE;
321               break;
322             }
323           } unit_class_iterate_end;
324         }
325 
326         /* The idea is that while our enemies don't have any offensive
327          * seaborne units, we don't have to worry. Go on the offensive! */
328         if (unit_type_get(punit)->attack_strength > 1) {
329 	  if (is_ocean_tile(unit_tile(punit))) {
330 	    Continent_id continent = tile_continent(unit_tile(punit));
331 	    adv->threats.ocean[-continent] = TRUE;
332 	  } else {
333 	    adjc_iterate(unit_tile(punit), tile2) {
334 	      if (is_ocean_tile(tile2)) {
335 	        Continent_id continent = tile_continent(tile2);
336 	        adv->threats.ocean[-continent] = TRUE;
337 	      }
338 	    } adjc_iterate_end;
339 	  }
340         }
341         continue;
342       }
343 
344       /* If our enemy builds missiles, worry about missile defence. */
345       if (uclass_has_flag(unit_class_get(punit), UCF_MISSILE)
346           && unit_type_get(punit)->attack_strength > 1) {
347         adv->threats.missile = TRUE;
348       }
349 
350       /* If he builds nukes, worry a lot. */
351       if (unit_has_type_flag(punit, UTYF_NUCLEAR)) {
352         danger_of_nukes = TRUE;
353       }
354     } unit_list_iterate_end;
355 
356     /* Check for nuke capability */
357     for (i = 0; i < nuke_units; i++) {
358       struct unit_type *nuke = get_role_unit(UTYF_NUCLEAR, i);
359 
360       if (can_player_build_unit_direct(aplayer, nuke)) {
361         adv->threats.nuclear = 1;
362       }
363     }
364   } players_iterate_end;
365 
366   /* Increase from fear to terror if opponent actually has nukes */
367   if (danger_of_nukes) {
368     adv->threats.nuclear++; /* sum of both fears */
369   }
370 
371   /*** Exploration ***/
372 
373   adv->explore.land_done = TRUE;
374   adv->explore.sea_done = TRUE;
375   adv->explore.continent = fc_calloc(adv->num_continents + 1, sizeof(bool));
376   adv->explore.ocean = fc_calloc(adv->num_oceans + 1, sizeof(bool));
377   whole_map_iterate(ptile) {
378     Continent_id continent = tile_continent(ptile);
379 
380     if (is_ocean_tile(ptile)) {
381       if (adv->explore.sea_done && has_handicap(pplayer, H_TARGETS)
382           && !map_is_known(ptile, pplayer)) {
383 	/* We're not done there. */
384         adv->explore.sea_done = FALSE;
385         adv->explore.ocean[-continent] = TRUE;
386       }
387       /* skip rest, which is land only */
388       continue;
389     }
390     if (adv->explore.continent[tile_continent(ptile)]) {
391       /* we don't need more explaining, we got the point */
392       continue;
393     }
394     if (tile_has_cause_extra(ptile, EC_HUT)
395         && (!has_handicap(pplayer, H_HUTS)
396              || map_is_known(ptile, pplayer))) {
397       adv->explore.land_done = FALSE;
398       adv->explore.continent[continent] = TRUE;
399       continue;
400     }
401     if (has_handicap(pplayer, H_TARGETS) && !map_is_known(ptile, pplayer)) {
402       /* this AI must explore */
403       adv->explore.land_done = FALSE;
404       adv->explore.continent[continent] = TRUE;
405     }
406   } whole_map_iterate_end;
407 
408   /*** Statistics ***/
409 
410   adv->stats.cities = fc_calloc(adv->num_continents + 1, sizeof(int));
411   adv->stats.average_production = 0;
412   city_list_iterate(pplayer->cities, pcity) {
413     Continent_id continent = tile_continent(pcity->tile);
414     if (continent >= 0) {
415       adv->stats.cities[continent]++;
416     }
417     adv->stats.average_production += pcity->surplus[O_SHIELD];
418   } city_list_iterate_end;
419   adv->stats.average_production /= MAX(1, city_list_size(pplayer->cities));
420 
421   /*** Diplomacy ***/
422 
423   players_iterate(aplayer) {
424     struct adv_dipl *dip = adv_dipl_get(pplayer, aplayer);
425 
426     dip->allied_with_enemy = FALSE;
427     players_iterate(check_pl) {
428       if (pplayers_allied(aplayer, check_pl)
429           && player_diplstate_get(pplayer, check_pl)->type == DS_WAR) {
430         dip->allied_with_enemy = TRUE;
431       }
432     } players_iterate_end;
433   } players_iterate_end;
434 
435   adv->dipl.spacerace_leader = player_leading_spacerace();
436 
437   adv->dipl.production_leader = NULL;
438   players_iterate(aplayer) {
439     if (adv->dipl.production_leader == NULL
440         || adv->dipl.production_leader->score.mfg < aplayer->score.mfg) {
441       adv->dipl.production_leader = aplayer;
442     }
443   } players_iterate_end;
444 
445   adv->dipl.tech_leader = NULL;
446   players_iterate(aplayer) {
447     if (adv->dipl.tech_leader == NULL
448         || adv->dipl.tech_leader->score.techs < aplayer->score.techs) {
449       adv->dipl.tech_leader = aplayer;
450     }
451   } players_iterate_end;
452 
453   /*** Priorities ***/
454 
455   /* NEVER set these to zero! Weight values are usually multiplied by
456    * these values, so be careful with them. They are used in city
457    * and government calculations, and food and shields should be
458    * slightly bigger because we only look at surpluses there. They
459    * are all WAGs. */
460   adv->food_priority = FOOD_WEIGHTING;
461   adv->shield_priority = SHIELD_WEIGHTING;
462   if (adv_wants_science(pplayer)) {
463     adv->luxury_priority = 1;
464     adv->science_priority = TRADE_WEIGHTING * 1.2;
465   } else {
466     adv->luxury_priority = TRADE_WEIGHTING;
467     adv->science_priority = 1;
468   }
469   adv->gold_priority = TRADE_WEIGHTING;
470   adv->happy_priority = 1;
471   adv->unhappy_priority = TRADE_WEIGHTING; /* danger */
472   adv->angry_priority = TRADE_WEIGHTING * 3; /* grave danger */
473   adv->pollution_priority = POLLUTION_WEIGHTING;
474 
475   /* Research want */
476   if (is_future_tech(research_get(pplayer)->researching)
477       || player_has_really_useful_tech_parasite(pplayer)) {
478     adv->wants_science = FALSE;
479   } else {
480     adv->wants_science = TRUE;
481   }
482 
483   /* max num cities
484    * The idea behind this code is that novice players don't understand that
485    * expansion is critical and find it very annoying.
486    * With the following code AI players will try to be only a bit better
487    * than the best human players. This should lead to more exciting games
488    * for the beginners.
489    */
490   if (has_handicap(pplayer, H_EXPANSION)) {
491     bool found_human = FALSE;
492     adv->max_num_cities = 3;
493     players_iterate_alive(aplayer) {
494       if (aplayer == pplayer || aplayer->ai_controlled) {
495         continue;
496       }
497       adv->max_num_cities = MAX(adv->max_num_cities,
498 				city_list_size(aplayer->cities) + 3);
499       found_human = TRUE;
500     } players_iterate_alive_end;
501     if (!found_human) {
502       adv->max_num_cities = MAP_INDEX_SIZE;
503     }
504   } else {
505     adv->max_num_cities = MAP_INDEX_SIZE;
506   }
507 
508   count_my_units(pplayer);
509 
510   TIMING_LOG(AIT_AIDATA, TIMER_STOP);
511 
512   /* Government */
513   TIMING_LOG(AIT_GOVERNMENT, TIMER_START);
514   adv_best_government(pplayer);
515   TIMING_LOG(AIT_GOVERNMENT, TIMER_STOP);
516 
517   return TRUE;
518 }
519 
520 /**************************************************************************
521   Clean up our mess.
522 **************************************************************************/
adv_data_phase_done(struct player * pplayer)523 void adv_data_phase_done(struct player *pplayer)
524 {
525   struct adv_data *adv = pplayer->server.adv;
526 
527   fc_assert_ret(adv != NULL);
528 
529   if (!adv->phase_is_initialized) {
530     return;
531   }
532 
533   free(adv->explore.ocean);
534   adv->explore.ocean = NULL;
535 
536   free(adv->explore.continent);
537   adv->explore.continent = NULL;
538 
539   free(adv->threats.continent);
540   adv->threats.continent = NULL;
541 
542   free(adv->threats.ocean);
543   adv->threats.ocean = NULL;
544 
545   free(adv->stats.cities);
546   adv->stats.cities = NULL;
547 
548   adv->num_continents = 0;
549   adv->num_oceans     = 0;
550 
551   adv->phase_is_initialized = FALSE;
552 }
553 
554 /**************************************************************************
555   Return a pointer to our data.
556   If caller_closes is set, data phase will be opened even if it's
557   currently closed, and the boolean will be set accordingly to tell caller
558   that phase needs closing.
559 **************************************************************************/
adv_data_get(struct player * pplayer,bool * caller_closes)560 struct adv_data *adv_data_get(struct player *pplayer, bool *caller_closes)
561 {
562   struct adv_data *adv = pplayer->server.adv;
563 
564   fc_assert_ret_val(adv != NULL, NULL);
565 
566   /* It's certainly indication of bug causing problems
567      if this adv_data_get() gets called between adv_data_phase_done() and
568      adv_data_phase_init(), since we may end up calling those
569      functions if number of known continents has changed.
570 
571      Consider following case:
572        Correct call order would be:
573        a) adv_data_phase_init()
574        b)   adv_data_get() -> adv_data_phase_done()
575        c)   adv_data_get() -> adv_data_phase_init()
576        d) adv_data_phase_done()
577        e) do something
578        f) adv_data_phase_init()
579 
580        In (e) data phase would be closed and data would be
581        correctly initialized at (f), which is probably beginning
582        next turn.
583 
584        Buggy version where adv_data_get() (b&c) gets called after (d):
585        a) adv_data_phase_init()
586        d) adv_data_phase_done()
587        b)   adv_data_get() -> adv_data_phase_done()
588        c)   adv_data_get() -> adv_data_phase_init()
589        e) do something
590        f) adv_data_phase_init()
591 
592        Now in (e) data phase would be open. When adv_data_phase_init()
593        then finally gets called and it really should recreate data
594        to match situation of new turn, it detects that data phase
595        is already initialized and does nothing.
596 
597        So, this assertion is here for a reason!
598 
599        Code below tries to fix the situation best it can if such a bug is
600        encountered. Since we are probably going to trust that to be enough
601        instead of making intrusive fixes for actual bug in stable branch,
602        do not assert for non-debug builds of stable versions. */
603 #if defined(DEBUG) || defined(IS_DEVEL_VERSION)
604   fc_assert(caller_closes != NULL || adv->phase_is_initialized);
605 #endif
606 
607   if (caller_closes != NULL) {
608     *caller_closes = FALSE;
609   }
610 
611   if (adv->num_continents != game.map.num_continents
612       || adv->num_oceans != game.map.num_oceans) {
613     /* we discovered more continents, recalculate! */
614 
615     if (adv->phase_is_initialized) {
616       /* Only call these in this order if inside data phase.
617          This is blanket "fix" for all cases where adv_data_get() is called
618          at illegal time. This at least minimize bad effects of such calls. */
619       adv_data_phase_done(pplayer);
620       adv_data_phase_init(pplayer, FALSE);
621     } else {
622       /* Call them in "wrong" order so we return recalculated data to caller,
623          but leave data phase closed.
624          This is blanket "fix" for all cases where adv_data_get() is called
625          at illegal time. This at least minimize bad effects of such calls.
626 
627          Arguably this is not buggy at all but works just as designed in
628          case of being called in alternate movement mode for players
629          other than currently moving one (for diplomacy between the two,
630          for example) */
631       log_debug("%s advisor data phase closed when adv_data_get() called",
632                 player_name(pplayer));
633       adv_data_phase_init(pplayer, FALSE);
634       if (caller_closes != NULL) {
635         *caller_closes = TRUE;
636       } else {
637         adv_data_phase_done(pplayer);
638       }
639     }
640   } else {
641     if (!adv->phase_is_initialized && caller_closes != NULL) {
642       adv_data_phase_init(pplayer, FALSE);
643       *caller_closes = TRUE;
644     }
645   }
646 
647   return adv;
648 }
649 
650 /**************************************************************************
651   Allocate memory for advisor data. Save to call multiple times.
652 **************************************************************************/
adv_data_init(struct player * pplayer)653 void adv_data_init(struct player *pplayer)
654 {
655   struct adv_data *adv;
656 
657   if (pplayer->server.adv == NULL) {
658     pplayer->server.adv = fc_calloc(1, sizeof(*pplayer->server.adv));
659   }
660   adv = pplayer->server.adv;
661 
662   adv->government_want = NULL;
663 
664   adv->dipl.adv_dipl_slots = fc_calloc(player_slot_count(),
665                                        sizeof(*adv->dipl.adv_dipl_slots));
666   player_slots_iterate(pslot) {
667     struct adv_dipl **dip_slot =
668       adv->dipl.adv_dipl_slots + player_slot_index(pslot);
669     *dip_slot = NULL;
670   } player_slots_iterate_end;
671 
672   players_iterate(aplayer) {
673     adv_dipl_new(pplayer, aplayer);
674     if (aplayer != pplayer) {
675       adv_dipl_new(aplayer, pplayer);
676     }
677   } players_iterate_end;
678 
679   adv_data_default(pplayer);
680 }
681 
682 /**************************************************************************
683   Initialize with sane values.
684 **************************************************************************/
adv_data_default(struct player * pplayer)685 void adv_data_default(struct player *pplayer)
686 {
687   struct adv_data *adv = pplayer->server.adv;
688 
689   fc_assert_ret(adv != NULL);
690 
691   adv->govt_reeval = 0;
692   adv->government_want = fc_realloc(adv->government_want,
693                                    (government_count() + 1)
694                                     * sizeof(*adv->government_want));
695   memset(adv->government_want, 0,
696          (government_count() + 1) * sizeof(*adv->government_want));
697 
698   adv->wonder_city = 0;
699 
700   adv->wants_science = TRUE;
701   adv->celebrate = FALSE;
702   adv->max_num_cities = 10000;
703 }
704 
705 /**************************************************************************
706   Free memory for advisor data.
707 **************************************************************************/
adv_data_close(struct player * pplayer)708 void adv_data_close(struct player *pplayer)
709 {
710   struct adv_data *adv = pplayer->server.adv;
711 
712   fc_assert_ret(NULL != adv);
713 
714   adv_data_phase_done(pplayer);
715 
716   if (adv->government_want != NULL) {
717     free(adv->government_want);
718   }
719 
720   if (adv->dipl.adv_dipl_slots != NULL) {
721     players_iterate(aplayer) {
722       adv_dipl_free(pplayer, aplayer);
723       if (aplayer != pplayer) {
724         adv_dipl_free(aplayer, pplayer);
725       }
726     } players_iterate_end;
727     FC_FREE(adv->dipl.adv_dipl_slots);
728   }
729 
730   if (adv != NULL) {
731     free(adv);
732   }
733 
734   pplayer->server.adv = NULL;
735 }
736 
737 /****************************************************************************
738   Allocate new advisor diplomacy slot
739 ****************************************************************************/
adv_dipl_new(const struct player * plr1,const struct player * plr2)740 static void adv_dipl_new(const struct player *plr1,
741                          const struct player *plr2)
742 {
743   struct adv_dipl **dip_slot =
744     plr1->server.adv->dipl.adv_dipl_slots + player_index(plr2);
745 
746   *dip_slot = fc_calloc(1, sizeof(struct adv_dipl));
747 }
748 
749 /****************************************************************************
750   Free resources allocated for diplomacy information between two players.
751 ****************************************************************************/
adv_dipl_free(const struct player * plr1,const struct player * plr2)752 static void adv_dipl_free(const struct player *plr1,
753                           const struct player *plr2)
754 {
755   struct adv_dipl **dip_slot =
756     plr1->server.adv->dipl.adv_dipl_slots + player_index(plr2);
757 
758   if (*dip_slot != NULL) {
759     FC_FREE(*dip_slot);
760     *dip_slot = NULL;
761   }
762 }
763 
764 /**************************************************************************
765   Returns diplomatic state type between two players
766 **************************************************************************/
adv_dipl_get(const struct player * plr1,const struct player * plr2)767 static struct adv_dipl *adv_dipl_get(const struct player *plr1,
768                                      const struct player *plr2)
769 {
770   struct adv_dipl **dip_slot =
771     plr1->server.adv->dipl.adv_dipl_slots + player_index(plr2);
772 
773   return *dip_slot;
774 }
775 
776 /**************************************************************************
777   Get value of government provided action immunities.
778 **************************************************************************/
adv_gov_action_immunity_want(struct government * gov)779 adv_want adv_gov_action_immunity_want(struct government *gov)
780 {
781   adv_want bonus = 0;
782 
783   if (action_immune_government(gov, ACTION_SPY_INCITE_CITY)) {
784     bonus += 4;
785   }
786   if (action_immune_government(gov, ACTION_SPY_BRIBE_UNIT)) {
787     bonus += 2;
788   }
789 
790   return bonus;
791 }
792 
793 /**************************************************************************
794   Get value of currently set government provided misc player bonuses.
795 
796   Caller can set player's government temporarily to another one to
797   evaluate that government instead of the one player actually have.
798 **************************************************************************/
adv_gov_player_bonus_want(struct player * pplayer)799 adv_want adv_gov_player_bonus_want(struct player *pplayer)
800 {
801   adv_want bonus = 0;
802 
803   /* Bonuses for non-economic abilities. We increase val by
804    * a very small amount here to choose govt in cases where
805    * we have no cities yet. */
806   bonus += get_player_bonus(pplayer, EFT_VETERAN_BUILD) > 0 ? 3 : 0;
807   bonus += get_player_bonus(pplayer, EFT_INSPIRE_PARTISANS) > 0 ? 3 : 0;
808   bonus += get_player_bonus(pplayer, EFT_RAPTURE_GROW) > 0 ? 2 : 0;
809   bonus += get_player_bonus(pplayer, EFT_FANATICS) > 0 ? 3 : 0;
810   bonus += get_player_bonus(pplayer, EFT_OUTPUT_INC_TILE) * 8;
811 
812   return bonus;
813 }
814 
815 /**************************************************************************
816   Find best government to aim for.
817   We do it by setting our government to all possible values and calculating
818   our GDP (total ai_eval_calc_city) under this government.  If the very
819   best of the governments is not available to us (it is not yet discovered),
820   we record it in the goal.gov structure with the aim of wanting the
821   necessary tech more.  The best of the available governments is recorded
822   in goal.revolution.  We record the want of each government, and only
823   recalculate this data every ai->govt_reeval_turns turns.
824 
825   Note: Call this _before_ doing taxes!
826 **************************************************************************/
adv_best_government(struct player * pplayer)827 void adv_best_government(struct player *pplayer)
828 {
829   struct adv_data *adv = adv_data_get(pplayer, NULL);
830   int best_val = 0;
831   struct government *current_gov = government_of_player(pplayer);
832 
833   adv->goal.govt.gov = current_gov;
834   adv->goal.govt.val = 0;
835   adv->goal.govt.req = A_UNSET;
836   adv->goal.revolution = current_gov;
837 
838   if (has_handicap(pplayer, H_AWAY) || !pplayer->is_alive) {
839     return;
840   }
841 
842   if (adv->govt_reeval == 0) {
843     const struct research *presearch = research_get(pplayer);
844 
845     governments_iterate(gov) {
846       adv_want val = 0;
847       bool override = FALSE;
848 
849       if (gov == game.government_during_revolution) {
850         continue; /* pointless */
851       }
852       if (gov->ai.better
853           && can_change_to_government(pplayer, gov->ai.better)) {
854         continue; /* we have better governments available */
855       }
856 
857       CALL_PLR_AI_FUNC(gov_value, pplayer, pplayer, gov, &val, &override);
858 
859       if (!override) {
860         int dist;
861         int bonus = 0; /* in percentage */
862         int revolution_turns;
863 
864         pplayer->government = gov;
865         /* Ideally we should change tax rates here, but since
866          * this is a rather big CPU operation, we'd rather not. */
867         check_player_max_rates(pplayer);
868         city_list_iterate(pplayer->cities, acity) {
869           auto_arrange_workers(acity);
870         } city_list_iterate_end;
871         city_list_iterate(pplayer->cities, pcity) {
872           val += adv_eval_calc_city(pcity, adv);
873         } city_list_iterate_end;
874 
875         bonus += adv_gov_action_immunity_want(gov);
876         bonus += adv_gov_player_bonus_want(pplayer);
877 
878         revolution_turns = get_player_bonus(pplayer, EFT_REVOLUTION_UNHAPPINESS);
879         if (revolution_turns > 0) {
880           bonus -= 6 / revolution_turns;
881         }
882 
883         val += (val * bonus) / 100;
884 
885         /* FIXME: handle reqs other than technologies. */
886         dist = 0;
887         requirement_vector_iterate(&gov->reqs, preq) {
888           if (VUT_ADVANCE == preq->source.kind) {
889             dist += MAX(1, research_goal_unknown_techs(presearch,
890                                                        advance_number(preq->source.value.advance)));
891           }
892         } requirement_vector_iterate_end;
893         val = amortize(val, dist);
894       }
895 
896       adv->government_want[government_index(gov)] = val; /* Save want */
897     } governments_iterate_end;
898     /* Now reset our gov to it's real state. */
899     pplayer->government = current_gov;
900     city_list_iterate(pplayer->cities, acity) {
901       auto_arrange_workers(acity);
902     } city_list_iterate_end;
903     if (player_is_cpuhog(pplayer)) {
904       adv->govt_reeval = 1;
905     } else {
906       adv->govt_reeval = CLIP(5, city_list_size(pplayer->cities), 20);
907     }
908   }
909   adv->govt_reeval--;
910 
911   /* Figure out which government is the best for us this turn. */
912   governments_iterate(gov) {
913     int gi = government_index(gov);
914     if (adv->government_want[gi] > best_val
915         && can_change_to_government(pplayer, gov)) {
916       best_val = adv->government_want[gi];
917       adv->goal.revolution = gov;
918     }
919     if (adv->government_want[gi] > adv->goal.govt.val) {
920       adv->goal.govt.gov = gov;
921       adv->goal.govt.val = adv->government_want[gi];
922 
923       /* FIXME: handle reqs other than technologies. */
924       adv->goal.govt.req = A_NONE;
925       requirement_vector_iterate(&gov->reqs, preq) {
926 	if (VUT_ADVANCE == preq->source.kind) {
927 	  adv->goal.govt.req = advance_number(preq->source.value.advance);
928 	  break;
929 	}
930       } requirement_vector_iterate_end;
931     }
932   } governments_iterate_end;
933   /* Goodness of the ideal gov is calculated relative to the goodness of the
934    * best of the available ones. */
935   adv->goal.govt.val -= best_val;
936 }
937 
938 /**************************************************************************
939   Return whether science would help us at all.
940 **************************************************************************/
adv_wants_science(struct player * pplayer)941 bool adv_wants_science(struct player *pplayer)
942 {
943   return adv_data_get(pplayer, NULL)->wants_science;
944 }
945 
946 
947 /**********************************************************************
948   There are some signs that a player might be dangerous: We are at
949   war with him, he has done lots of ignoble things to us, he is an
950   ally of one of our enemies (a ticking bomb to be sure), we don't like him,
951   diplomatic state is neutral or we have cease fire.
952 ***********************************************************************/
adv_is_player_dangerous(struct player * pplayer,struct player * aplayer)953 bool adv_is_player_dangerous(struct player *pplayer,
954                              struct player *aplayer)
955 {
956   struct adv_dipl *dip;
957   enum diplstate_type ds;
958   enum override_bool dang = NO_OVERRIDE;
959 
960   if (pplayer->ai_controlled) {
961     /* Give AI code possibility to decide itself */
962     CALL_PLR_AI_FUNC(consider_plr_dangerous, pplayer, pplayer, aplayer, &dang);
963   }
964 
965   if (dang == OVERRIDE_FALSE) {
966     return FALSE;
967   }
968 
969   if (dang == OVERRIDE_TRUE) {
970     return TRUE;
971   }
972 
973   if (pplayer == aplayer) {
974     /* We always trust ourself */
975     return FALSE;
976   }
977 
978   ds = player_diplstate_get(pplayer, aplayer)->type;
979 
980   if (ds == DS_WAR || ds == DS_CEASEFIRE) {
981     /* It's already a war or aplayer can declare it soon */
982     return TRUE;
983   }
984 
985   dip = adv_dipl_get(pplayer, aplayer);
986 
987   if (dip->allied_with_enemy) {
988     /* Don't trust someone who will declare war on us soon */
989     return TRUE;
990   }
991 
992   if (player_diplstate_get(pplayer, aplayer)->has_reason_to_cancel > 0) {
993     return TRUE;
994   }
995 
996   if (pplayer->ai_common.love[player_index(aplayer)] < MAX_AI_LOVE / 10) {
997     /* We don't trust players who we don't like. Note that
998      * aplayer's units inside pplayer's borders decreases AI's love */
999     return TRUE;
1000   }
1001 
1002   return FALSE;
1003 }
1004