webperimental: killstack decides stack protects.
[freeciv.git] / server / advisors / advdata.c
blob55c7c9b55c5e22ae0116509895f2b4caa0925c26
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.
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 ***********************************************************************/
14 #ifdef HAVE_CONFIG_H
15 #include <fc_config.h>
16 #endif
18 /* utility */
19 #include "log.h"
20 #include "mem.h"
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"
35 /* common/aicore */
36 #include "aisupport.h"
37 #include "path_finding.h"
38 #include "pf_tools.h"
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"
48 /* server/advisors */
49 #include "advbuilding.h"
50 #include "advcity.h"
51 #include "advtools.h"
52 #include "autosettlers.h"
54 /* ai */
55 #include "handicaps.h"
57 #include "advdata.h"
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);
66 /**************************************************************************
67 Precalculates some important data about the improvements in the game
68 that we use later in ai/aicity.c. We mark improvements as 'calculate'
69 if we want to run a full test on them, as 'estimate' if we just want
70 to do some guesses on them, or as 'unused' is they are useless to us.
71 Then we find the largest range of calculatable effects in the
72 improvement and record it for later use.
73 **************************************************************************/
74 static void adv_data_city_impr_calc(struct player *pplayer,
75 struct adv_data *adv)
77 int count[ADV_IMPR_LAST];
79 memset(count, 0, sizeof(count));
81 improvement_iterate(pimprove) {
82 struct universal source = {
83 .kind = VUT_IMPROVEMENT,
84 .value = {.building = pimprove}
87 adv->impr_calc[improvement_index(pimprove)] = ADV_IMPR_ESTIMATE;
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;
116 if (preq->range > adv->impr_range[improvement_index(pimprove)]) {
117 adv->impr_range[improvement_index(pimprove)] = preq->range;
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;
133 } requirement_vector_iterate_end;
134 break;
135 default:
136 /* Nothing! */
137 break;
139 } effect_list_iterate_end;
140 } improvement_iterate_end;
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 **************************************************************************/
148 static bool player_has_really_useful_tech_parasite(struct player* pplayer)
150 struct research *presearch, *aresearch;
151 int players_needed = get_player_bonus(pplayer, EFT_TECH_PARASITE);
153 if (players_needed == 0) {
154 return FALSE;
157 presearch = research_get(pplayer);
158 advance_index_iterate(A_FIRST, tech) {
159 int players_having;
161 if (!research_invention_gettable(presearch, tech,
162 game.info.tech_parasite_allow_holes)
163 || TECH_KNOWN == research_invention_state(presearch, tech)) {
164 continue;
167 players_having = 0;
169 players_iterate_alive(aplayer) {
170 if (aplayer == pplayer) {
171 continue;
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;
182 } players_iterate_alive_end;
183 } advance_index_iterate_end;
184 return FALSE;
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 **************************************************************************/
192 void adv_data_analyze_rulesets(struct player *pplayer)
194 struct adv_data *adv = pplayer->server.adv;
196 fc_assert_ret(adv != NULL);
198 adv_data_city_impr_calc(pplayer, adv);
201 /**************************************************************************
202 This function is called each turn to initialize pplayer->ai.stats.units.
203 **************************************************************************/
204 static void count_my_units(struct player *pplayer)
206 struct adv_data *adv = adv_data_get(pplayer, NULL);
208 memset(&adv->stats.units, 0, sizeof(adv->stats.units));
210 unit_list_iterate(pplayer->units, punit) {
211 struct unit_class *pclass = unit_class_get(punit);
213 adv->stats.units.byclass[uclass_index(pclass)]++;
215 if (unit_has_type_flag(punit, UTYF_COAST_STRICT)) {
216 adv->stats.units.coast_strict++;
218 if (uclass_has_flag(pclass, UCF_MISSILE)) {
219 adv->stats.units.missiles++;
221 if (unit_can_do_action(punit, ACTION_PARADROP)) {
222 adv->stats.units.paratroopers++;
224 if (utype_can_do_action(punit->utype, ACTION_AIRLIFT)) {
225 adv->stats.units.airliftable++;
227 if (can_upgrade_unittype(pplayer, unit_type_get(punit)) >= 0) {
228 adv->stats.units.upgradeable++;
230 } unit_list_iterate_end;
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 **************************************************************************/
237 bool is_adv_data_phase_open(struct player *pplayer)
239 struct adv_data *adv = pplayer->server.adv;
241 return adv->phase_is_initialized;
244 /**************************************************************************
245 Make and cache lots of calculations needed for other functions.
247 Returns TRUE if new data was created, FALSE if data existed already.
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.
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 **************************************************************************/
257 bool adv_data_phase_init(struct player *pplayer, bool is_new_phase)
259 struct adv_data *adv = pplayer->server.adv;
260 int i;
261 int nuke_units;
262 bool danger_of_nukes;
264 fc_assert_ret_val(adv != NULL, FALSE);
266 if (adv->phase_is_initialized) {
267 return FALSE;
269 adv->phase_is_initialized = TRUE;
271 TIMING_LOG(AIT_AIDATA, TIMER_START);
273 nuke_units = num_role_units(action_id_get_role(ACTION_NUKE));
274 danger_of_nukes = FALSE;
276 /*** Threats ***/
278 adv->num_continents = wld.map.num_continents;
279 adv->num_oceans = wld.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;
286 players_iterate(aplayer) {
287 if (!adv_is_player_dangerous(pplayer, aplayer)) {
288 continue;
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;
300 } city_list_iterate_end;
302 unit_list_iterate(aplayer->units, punit) {
303 const struct unit_class *pclass = unit_class_get(punit);
305 if (unit_type_get(punit)->adv.igwall) {
306 adv->threats.igwall = TRUE;
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;
323 } unit_class_iterate_end;
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));
332 adv->threats.ocean[-continent] = TRUE;
333 } else {
334 adjc_iterate(&(wld.map), unit_tile(punit), tile2) {
335 if (is_ocean_tile(tile2)) {
336 Continent_id continent = tile_continent(tile2);
338 adv->threats.ocean[-continent] = TRUE;
340 } adjc_iterate_end;
343 continue;
346 /* If our enemy builds missiles, worry about missile defence. */
347 if (uclass_has_flag(unit_class_get(punit), UCF_MISSILE)
348 && unit_type_get(punit)->attack_strength > 1) {
349 adv->threats.missile = TRUE;
352 /* If he builds nukes, worry a lot. */
353 if (unit_can_do_action(punit, ACTION_NUKE)) {
354 danger_of_nukes = TRUE;
356 } unit_list_iterate_end;
358 /* Check for nuke capability */
359 for (i = 0; i < nuke_units; i++) {
360 struct unit_type *nuke =
361 get_role_unit(action_id_get_role(ACTION_NUKE), i);
363 if (can_player_build_unit_direct(aplayer, nuke)) {
364 adv->threats.nuclear = 1;
367 } players_iterate_end;
369 /* Increase from fear to terror if opponent actually has nukes */
370 if (danger_of_nukes) {
371 adv->threats.nuclear++; /* sum of both fears */
374 /*** Exploration ***/
376 adv->explore.land_done = TRUE;
377 adv->explore.sea_done = TRUE;
378 adv->explore.continent = fc_calloc(adv->num_continents + 1, sizeof(bool));
379 adv->explore.ocean = fc_calloc(adv->num_oceans + 1, sizeof(bool));
381 whole_map_iterate(&(wld.map), ptile) {
382 Continent_id continent = tile_continent(ptile);
384 if (is_ocean_tile(ptile)) {
385 if (adv->explore.sea_done && has_handicap(pplayer, H_TARGETS)
386 && !map_is_known(ptile, pplayer)) {
387 /* We're not done there. */
388 adv->explore.sea_done = FALSE;
389 adv->explore.ocean[-continent] = TRUE;
391 /* skip rest, which is land only */
392 continue;
394 if (adv->explore.continent[tile_continent(ptile)]) {
395 /* we don't need more explaining, we got the point */
396 continue;
398 if (tile_has_cause_extra(ptile, EC_HUT)
399 && (!has_handicap(pplayer, H_HUTS)
400 || map_is_known(ptile, pplayer))) {
401 adv->explore.land_done = FALSE;
402 adv->explore.continent[continent] = TRUE;
403 continue;
405 if (has_handicap(pplayer, H_TARGETS) && !map_is_known(ptile, pplayer)) {
406 /* this AI must explore */
407 adv->explore.land_done = FALSE;
408 adv->explore.continent[continent] = TRUE;
410 } whole_map_iterate_end;
412 /*** Statistics ***/
414 adv->stats.cities = fc_calloc(adv->num_continents + 1, sizeof(int));
415 adv->stats.average_production = 0;
416 city_list_iterate(pplayer->cities, pcity) {
417 Continent_id continent = tile_continent(pcity->tile);
418 if (continent >= 0) {
419 adv->stats.cities[continent]++;
421 adv->stats.average_production += pcity->surplus[O_SHIELD];
422 } city_list_iterate_end;
423 adv->stats.average_production /= MAX(1, city_list_size(pplayer->cities));
425 /*** Diplomacy ***/
427 players_iterate(aplayer) {
428 struct adv_dipl *dip = adv_dipl_get(pplayer, aplayer);
430 dip->allied_with_enemy = FALSE;
431 players_iterate(check_pl) {
432 if (pplayers_allied(aplayer, check_pl)
433 && player_diplstate_get(pplayer, check_pl)->type == DS_WAR) {
434 dip->allied_with_enemy = TRUE;
436 } players_iterate_end;
437 } players_iterate_end;
439 adv->dipl.spacerace_leader = player_leading_spacerace();
441 adv->dipl.production_leader = NULL;
442 players_iterate(aplayer) {
443 if (adv->dipl.production_leader == NULL
444 || adv->dipl.production_leader->score.mfg < aplayer->score.mfg) {
445 adv->dipl.production_leader = aplayer;
447 } players_iterate_end;
449 /*** Priorities ***/
451 /* NEVER set these to zero! Weight values are usually multiplied by
452 * these values, so be careful with them. They are used in city
453 * and government calculations, and food and shields should be
454 * slightly bigger because we only look at surpluses there. They
455 * are all WAGs. */
456 adv->food_priority = FOOD_WEIGHTING;
457 adv->shield_priority = SHIELD_WEIGHTING;
458 if (adv_wants_science(pplayer)) {
459 adv->luxury_priority = 1;
460 adv->science_priority = TRADE_WEIGHTING;
461 } else {
462 adv->luxury_priority = TRADE_WEIGHTING;
463 adv->science_priority = 1;
465 adv->gold_priority = TRADE_WEIGHTING;
466 adv->happy_priority = 1;
467 adv->unhappy_priority = TRADE_WEIGHTING; /* danger */
468 adv->angry_priority = TRADE_WEIGHTING * 3; /* grave danger */
469 adv->pollution_priority = POLLUTION_WEIGHTING;
471 /* Research want */
472 if (is_future_tech(research_get(pplayer)->researching)
473 || player_has_really_useful_tech_parasite(pplayer)) {
474 adv->wants_science = FALSE;
475 } else {
476 adv->wants_science = TRUE;
479 /* max num cities
480 * The idea behind this code is that novice players don't understand that
481 * expansion is critical and find it very annoying.
482 * With the following code AI players will try to be only a bit better
483 * than the best human players. This should lead to more exciting games
484 * for the beginners.
486 if (has_handicap(pplayer, H_EXPANSION)) {
487 bool found_human = FALSE;
488 adv->max_num_cities = 3;
489 players_iterate_alive(aplayer) {
490 if (aplayer == pplayer || is_ai(aplayer)) {
491 continue;
493 adv->max_num_cities = MAX(adv->max_num_cities,
494 city_list_size(aplayer->cities) + 3);
495 found_human = TRUE;
496 } players_iterate_alive_end;
497 if (!found_human) {
498 adv->max_num_cities = MAP_INDEX_SIZE;
500 } else {
501 adv->max_num_cities = MAP_INDEX_SIZE;
504 count_my_units(pplayer);
506 TIMING_LOG(AIT_AIDATA, TIMER_STOP);
508 /* Government */
509 TIMING_LOG(AIT_GOVERNMENT, TIMER_START);
510 adv_best_government(pplayer);
511 TIMING_LOG(AIT_GOVERNMENT, TIMER_STOP);
513 return TRUE;
516 /**************************************************************************
517 Clean up our mess.
518 **************************************************************************/
519 void adv_data_phase_done(struct player *pplayer)
521 struct adv_data *adv = pplayer->server.adv;
523 fc_assert_ret(adv != NULL);
525 if (!adv->phase_is_initialized) {
526 return;
529 free(adv->explore.ocean);
530 adv->explore.ocean = NULL;
532 free(adv->explore.continent);
533 adv->explore.continent = NULL;
535 free(adv->threats.continent);
536 adv->threats.continent = NULL;
538 free(adv->threats.ocean);
539 adv->threats.ocean = NULL;
541 free(adv->stats.cities);
542 adv->stats.cities = NULL;
544 adv->num_continents = 0;
545 adv->num_oceans = 0;
547 adv->phase_is_initialized = FALSE;
550 /**************************************************************************
551 Return a pointer to our data.
552 If caller_closes is set, data phase will be opened even if it's
553 currently closed, and the boolean will be set accordingly to tell caller
554 that phase needs closing.
555 **************************************************************************/
556 struct adv_data *adv_data_get(struct player *pplayer, bool *caller_closes)
558 struct adv_data *adv = pplayer->server.adv;
560 fc_assert_ret_val(adv != NULL, NULL);
562 /* It's certainly indication of bug causing problems
563 if this adv_data_get() gets called between adv_data_phase_done() and
564 adv_data_phase_init(), since we may end up calling those
565 functions if number of known continents has changed.
567 Consider following case:
568 Correct call order would be:
569 a) adv_data_phase_init()
570 b) adv_data_get() -> adv_data_phase_done()
571 c) adv_data_get() -> adv_data_phase_init()
572 d) adv_data_phase_done()
573 e) do something
574 f) adv_data_phase_init()
576 In (e) data phase would be closed and data would be
577 correctly initialized at (f), which is probably beginning
578 next turn.
580 Buggy version where adv_data_get() (b&c) gets called after (d):
581 a) adv_data_phase_init()
582 d) adv_data_phase_done()
583 b) adv_data_get() -> adv_data_phase_done()
584 c) adv_data_get() -> adv_data_phase_init()
585 e) do something
586 f) adv_data_phase_init()
588 Now in (e) data phase would be open. When adv_data_phase_init()
589 then finally gets called and it really should recreate data
590 to match situation of new turn, it detects that data phase
591 is already initialized and does nothing.
593 So, this assertion is here for a reason!
595 Code below tries to fix the situation best it can if such a bug is
596 encountered. Since we are probably going to trust that to be enough
597 instead of making intrusive fixes for actual bug in stable branch,
598 do not assert for non-debug builds of stable versions. */
599 #if defined(FREECIV_DEBUG) || defined(IS_DEVEL_VERSION)
600 fc_assert(caller_closes != NULL || adv->phase_is_initialized);
601 #endif
603 if (caller_closes != NULL) {
604 *caller_closes = FALSE;
607 if (adv->num_continents != wld.map.num_continents
608 || adv->num_oceans != wld.map.num_oceans) {
609 /* we discovered more continents, recalculate! */
611 if (adv->phase_is_initialized) {
612 /* Only call these in this order if inside data phase.
613 This is blanket "fix" for all cases where adv_data_get() is called
614 at illegal time. This at least minimize bad effects of such calls. */
615 adv_data_phase_done(pplayer);
616 adv_data_phase_init(pplayer, FALSE);
617 } else {
618 /* Call them in "wrong" order so we return recalculated data to caller,
619 but leave data phase closed.
620 This is blanket "fix" for all cases where adv_data_get() is called
621 at illegal time. This at least minimize bad effects of such calls.
623 Arguably this is not buggy at all but works just as designed in
624 case of being called in alternate movement mode for players
625 other than currently moving one (for diplomacy between the two,
626 for example) */
627 log_debug("%s advisor data phase closed when adv_data_get() called",
628 player_name(pplayer));
629 adv_data_phase_init(pplayer, FALSE);
630 if (caller_closes != NULL) {
631 *caller_closes = TRUE;
632 } else {
633 adv_data_phase_done(pplayer);
636 } else {
637 if (!adv->phase_is_initialized && caller_closes != NULL) {
638 adv_data_phase_init(pplayer, FALSE);
639 *caller_closes = TRUE;
643 return adv;
646 /**************************************************************************
647 Allocate memory for advisor data. Save to call multiple times.
648 **************************************************************************/
649 void adv_data_init(struct player *pplayer)
651 struct adv_data *adv;
653 if (pplayer->server.adv == NULL) {
654 pplayer->server.adv = fc_calloc(1, sizeof(*pplayer->server.adv));
656 adv = pplayer->server.adv;
658 adv->government_want = NULL;
660 adv->dipl.adv_dipl_slots = fc_calloc(player_slot_count(),
661 sizeof(*adv->dipl.adv_dipl_slots));
662 player_slots_iterate(pslot) {
663 struct adv_dipl **dip_slot =
664 adv->dipl.adv_dipl_slots + player_slot_index(pslot);
665 *dip_slot = NULL;
666 } player_slots_iterate_end;
668 players_iterate(aplayer) {
669 adv_dipl_new(pplayer, aplayer);
670 if (aplayer != pplayer) {
671 adv_dipl_new(aplayer, pplayer);
673 } players_iterate_end;
675 adv_data_default(pplayer);
678 /**************************************************************************
679 Initialize with sane values.
680 **************************************************************************/
681 void adv_data_default(struct player *pplayer)
683 struct adv_data *adv = pplayer->server.adv;
685 fc_assert_ret(adv != NULL);
687 adv->govt_reeval = 0;
688 adv->government_want = fc_realloc(adv->government_want,
689 (government_count() + 1)
690 * sizeof(*adv->government_want));
691 memset(adv->government_want, 0,
692 (government_count() + 1) * sizeof(*adv->government_want));
694 adv->wonder_city = 0;
696 adv->wants_science = TRUE;
697 adv->celebrate = FALSE;
698 adv->max_num_cities = 10000;
701 /**************************************************************************
702 Free memory for advisor data.
703 **************************************************************************/
704 void adv_data_close(struct player *pplayer)
706 struct adv_data *adv = pplayer->server.adv;
708 fc_assert_ret(NULL != adv);
710 adv_data_phase_done(pplayer);
712 if (adv->government_want != NULL) {
713 free(adv->government_want);
716 if (adv->dipl.adv_dipl_slots != NULL) {
717 players_iterate(aplayer) {
718 adv_dipl_free(pplayer, aplayer);
719 if (aplayer != pplayer) {
720 adv_dipl_free(aplayer, pplayer);
722 } players_iterate_end;
723 FC_FREE(adv->dipl.adv_dipl_slots);
726 if (adv != NULL) {
727 free(adv);
730 pplayer->server.adv = NULL;
733 /****************************************************************************
734 Allocate new advisor diplomacy slot
735 ****************************************************************************/
736 static void adv_dipl_new(const struct player *plr1,
737 const struct player *plr2)
739 struct adv_dipl **dip_slot =
740 plr1->server.adv->dipl.adv_dipl_slots + player_index(plr2);
742 *dip_slot = fc_calloc(1, sizeof(struct adv_dipl));
745 /****************************************************************************
746 Free resources allocated for diplomacy information between two players.
747 ****************************************************************************/
748 static void adv_dipl_free(const struct player *plr1,
749 const struct player *plr2)
751 struct adv_dipl **dip_slot =
752 plr1->server.adv->dipl.adv_dipl_slots + player_index(plr2);
754 if (*dip_slot != NULL) {
755 FC_FREE(*dip_slot);
756 *dip_slot = NULL;
760 /**************************************************************************
761 Returns diplomatic state type between two players
762 **************************************************************************/
763 static struct adv_dipl *adv_dipl_get(const struct player *plr1,
764 const struct player *plr2)
766 struct adv_dipl **dip_slot =
767 plr1->server.adv->dipl.adv_dipl_slots + player_index(plr2);
769 return *dip_slot;
772 /**************************************************************************
773 Find best government to aim for.
774 We do it by setting our government to all possible values and calculating
775 our GDP (total ai_eval_calc_city) under this government. If the very
776 best of the governments is not available to us (it is not yet discovered),
777 we record it in the goal.gov structure with the aim of wanting the
778 necessary tech more. The best of the available governments is recorded
779 in goal.revolution. We record the want of each government, and only
780 recalculate this data every ai->govt_reeval_turns turns.
782 Note: Call this _before_ doing taxes!
783 **************************************************************************/
784 void adv_best_government(struct player *pplayer)
786 struct adv_data *adv = adv_data_get(pplayer, NULL);
787 int best_val = 0;
788 struct government *current_gov = government_of_player(pplayer);
790 adv->goal.govt.gov = current_gov;
791 adv->goal.govt.val = 0;
792 adv->goal.govt.req = A_UNSET;
793 adv->goal.revolution = current_gov;
795 if (has_handicap(pplayer, H_AWAY) || !pplayer->is_alive) {
796 return;
799 if (adv->govt_reeval == 0) {
800 const struct research *presearch = research_get(pplayer);
802 governments_iterate(gov) {
803 adv_want val = 0;
804 bool override = FALSE;
806 if (gov == game.government_during_revolution) {
807 continue; /* pointless */
809 if (gov->ai.better
810 && can_change_to_government(pplayer, gov->ai.better)) {
811 continue; /* we have better governments available */
814 CALL_PLR_AI_FUNC(gov_value, pplayer, pplayer, gov, &val, &override);
816 if (!override) {
817 int dist;
818 adv_want bonus = 0; /* in percentage */
819 int revolution_turns;
821 pplayer->government = gov;
822 /* Ideally we should change tax rates here, but since
823 * this is a rather big CPU operation, we'd rather not. */
824 check_player_max_rates(pplayer);
825 city_list_iterate(pplayer->cities, acity) {
826 auto_arrange_workers(acity);
827 } city_list_iterate_end;
828 city_list_iterate(pplayer->cities, pcity) {
829 val += adv_eval_calc_city(pcity, adv);
830 } city_list_iterate_end;
832 /* Bonuses for non-economic abilities. We increase val by
833 * a very small amount here to choose govt in cases where
834 * we have no cities yet. */
835 bonus += get_player_bonus(pplayer, EFT_VETERAN_BUILD) > 0 ? 3 : 0;
837 /* TODO: Individual and well balanced value. */
838 action_iterate(act) {
839 if (!action_immune_government(gov, act)) {
840 /* This government doesn't provide immunity againt this
841 * action. */
842 continue;
845 switch((enum gen_action)act) {
846 case ACTION_ATTACK:
847 case ACTION_SPY_INCITE_CITY:
848 case ACTION_SPY_INCITE_CITY_ESC:
849 case ACTION_CONQUER_CITY:
850 bonus += 4;
851 break;
852 case ACTION_SPY_BRIBE_UNIT:
853 bonus += 2;
854 break;
855 case ACTION_SPY_INVESTIGATE_CITY:
856 case ACTION_INV_CITY_SPEND:
857 case ACTION_SPY_POISON:
858 case ACTION_SPY_STEAL_GOLD:
859 case ACTION_SPY_SABOTAGE_CITY:
860 case ACTION_SPY_TARGETED_SABOTAGE_CITY:
861 case ACTION_SPY_STEAL_TECH:
862 case ACTION_SPY_TARGETED_STEAL_TECH:
863 case ACTION_SPY_SABOTAGE_UNIT:
864 case ACTION_CAPTURE_UNITS:
865 case ACTION_STEAL_MAPS:
866 case ACTION_BOMBARD:
867 case ACTION_SPY_NUKE:
868 case ACTION_SPY_NUKE_ESC:
869 case ACTION_NUKE:
870 case ACTION_DESTROY_CITY:
871 case ACTION_EXPEL_UNIT:
872 /* Being a target of this is usually undesireable */
873 /* TODO: Individual and well balanced values. */
874 bonus += 0.1;
875 break;
877 case ACTION_MARKETPLACE:
878 case ACTION_FOUND_CITY:
879 case ACTION_DISBAND_UNIT:
880 case ACTION_PARADROP:
881 /* Wants the ability to do this to it self. Don't want others
882 * to target it. Do nothing since action_immune_government()
883 * doesn't separate based on who the actor is. */
884 break;
886 case ACTION_ESTABLISH_EMBASSY:
887 case ACTION_ESTABLISH_EMBASSY_STAY:
888 case ACTION_TRADE_ROUTE:
889 case ACTION_JOIN_CITY:
890 case ACTION_HELP_WONDER:
891 case ACTION_RECYCLE_UNIT:
892 case ACTION_HOME_CITY:
893 case ACTION_UPGRADE_UNIT:
894 case ACTION_AIRLIFT:
895 case ACTION_HEAL_UNIT:
896 /* Could be good. An embassy gives permanent contact. A trade
897 * route gives gold per turn. Join city gives population. Help
898 * wonder gives shields. */
899 /* TODO: Individual and well balanced values. */
900 break;
902 case ACTION_COUNT:
903 /* Invalid */
904 fc_assert(act != ACTION_COUNT);
905 break;
907 } action_iterate_end;
909 bonus += get_player_bonus(pplayer, EFT_INSPIRE_PARTISANS) > 0 ? 3 : 0;
910 bonus += get_player_bonus(pplayer, EFT_RAPTURE_GROW) > 0 ? 2 : 0;
911 bonus += get_player_bonus(pplayer, EFT_FANATICS) > 0 ? 3 : 0;
912 bonus += get_player_bonus(pplayer, EFT_OUTPUT_INC_TILE) * 8;
914 revolution_turns = get_player_bonus(pplayer, EFT_REVOLUTION_UNHAPPINESS);
915 if (revolution_turns > 0) {
916 bonus -= 6 / revolution_turns;
919 val += (val * bonus) / 100;
921 /* FIXME: handle reqs other than technologies. */
922 dist = 0;
923 requirement_vector_iterate(&gov->reqs, preq) {
924 if (VUT_ADVANCE == preq->source.kind) {
925 dist += MAX(1, research_goal_unknown_techs(presearch,
926 advance_number(preq->source.value.advance)));
928 } requirement_vector_iterate_end;
929 val = amortize(val, dist);
932 adv->government_want[government_index(gov)] = val; /* Save want */
933 } governments_iterate_end;
934 /* Now reset our gov to it's real state. */
935 pplayer->government = current_gov;
936 city_list_iterate(pplayer->cities, acity) {
937 auto_arrange_workers(acity);
938 } city_list_iterate_end;
939 if (player_is_cpuhog(pplayer)) {
940 adv->govt_reeval = 1;
941 } else {
942 adv->govt_reeval = CLIP(5, city_list_size(pplayer->cities), 20);
945 adv->govt_reeval--;
947 /* Figure out which government is the best for us this turn. */
948 governments_iterate(gov) {
949 int gi = government_index(gov);
950 if (adv->government_want[gi] > best_val
951 && can_change_to_government(pplayer, gov)) {
952 best_val = adv->government_want[gi];
953 adv->goal.revolution = gov;
955 if (adv->government_want[gi] > adv->goal.govt.val) {
956 adv->goal.govt.gov = gov;
957 adv->goal.govt.val = adv->government_want[gi];
959 /* FIXME: handle reqs other than technologies. */
960 adv->goal.govt.req = A_NONE;
961 requirement_vector_iterate(&gov->reqs, preq) {
962 if (VUT_ADVANCE == preq->source.kind) {
963 adv->goal.govt.req = advance_number(preq->source.value.advance);
964 break;
966 } requirement_vector_iterate_end;
968 } governments_iterate_end;
969 /* Goodness of the ideal gov is calculated relative to the goodness of the
970 * best of the available ones. */
971 adv->goal.govt.val -= best_val;
974 /**************************************************************************
975 Return whether science would help us at all.
976 **************************************************************************/
977 bool adv_wants_science(struct player *pplayer)
979 return adv_data_get(pplayer, NULL)->wants_science;
983 /**********************************************************************
984 There are some signs that a player might be dangerous: We are at
985 war with him, he has done lots of ignoble things to us, he is an
986 ally of one of our enemies (a ticking bomb to be sure), we don't like him,
987 diplomatic state is neutral or we have cease fire.
988 ***********************************************************************/
989 bool adv_is_player_dangerous(struct player *pplayer,
990 struct player *aplayer)
992 struct adv_dipl *dip;
993 enum diplstate_type ds;
994 enum override_bool dang = NO_OVERRIDE;
996 if (is_ai(pplayer)) {
997 /* Give AI code possibility to decide itself */
998 CALL_PLR_AI_FUNC(consider_plr_dangerous, pplayer, pplayer, aplayer, &dang);
1001 if (dang == OVERRIDE_FALSE) {
1002 return FALSE;
1005 if (dang == OVERRIDE_TRUE) {
1006 return TRUE;
1009 if (pplayer == aplayer) {
1010 /* We always trust ourself */
1011 return FALSE;
1014 ds = player_diplstate_get(pplayer, aplayer)->type;
1016 if (ds == DS_WAR || ds == DS_CEASEFIRE) {
1017 /* It's already a war or aplayer can declare it soon */
1018 return TRUE;
1021 dip = adv_dipl_get(pplayer, aplayer);
1023 if (dip->allied_with_enemy) {
1024 /* Don't trust someone who will declare war on us soon */
1025 return TRUE;
1028 if (player_diplstate_get(pplayer, aplayer)->has_reason_to_cancel > 0) {
1029 return TRUE;
1032 if (pplayer->ai_common.love[player_index(aplayer)] < MAX_AI_LOVE / 10) {
1033 /* We don't trust players who we don't like. Note that
1034 * aplayer's units inside pplayer's borders decreases AI's love */
1035 return TRUE;
1038 return FALSE;