webperimental: killstack decides stack protects.
[freeciv.git] / ai / default / aicity.c
blobbf1c55ed90ec494d76f4d44cd62573119e36bd76
1 /***********************************************************************
2 Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2, or (at your option)
6 any later version.
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 #include <string.h>
19 #include <math.h> /* pow */
21 /* utility */
22 #include "rand.h"
23 #include "registry.h"
25 /* common */
26 #include "actions.h"
27 #include "game.h"
28 #include "government.h"
29 #include "research.h"
30 #include "specialist.h"
32 /* server */
33 #include "cityhand.h"
34 #include "citytools.h"
35 #include "cityturn.h"
36 #include "notify.h"
37 #include "plrhand.h"
38 #include "srv_log.h"
39 #include "unithand.h"
40 #include "unittools.h"
42 /* server/advisors */
43 #include "advdata.h"
44 #include "advtools.h"
45 #include "autosettlers.h"
46 #include "advbuilding.h"
47 #include "infracache.h"
49 /* ai */
50 #include "aitraits.h"
51 #include "difficulty.h"
52 #include "handicaps.h"
54 /* ai/default */
55 #include "aidata.h"
56 #include "aihand.h"
57 #include "ailog.h"
58 #include "aiplayer.h"
59 #include "aisettler.h"
60 #include "aitools.h"
61 #include "aiunit.h"
62 #include "daidiplomacy.h"
63 #include "daidomestic.h"
64 #include "daimilitary.h"
65 #include "daieffects.h"
67 #include "aicity.h"
69 #define LOG_BUY LOG_DEBUG
70 #define LOG_EMERGENCY LOG_VERBOSE
71 #define LOG_WANT LOG_VERBOSE
73 /* TODO: AI_CITY_RECALC_SPEED should be configurable to ai difficulty.
74 -kauf */
75 #define AI_CITY_RECALC_SPEED 5
77 #define AI_BA_RECALC_SPEED 5
79 #define SPECVEC_TAG tech
80 #define SPECVEC_TYPE struct advance *
81 #include "specvec.h"
83 #define SPECVEC_TAG impr
84 #define SPECVEC_TYPE struct impr_type *
85 #include "specvec.h"
87 /* Iterate over cities within a certain range around a given city
88 * (city_here) that exist within a given city list. */
89 #define city_range_iterate(city_here, list, range, city) \
90 { \
91 city_list_iterate(list, city) { \
92 if (range == REQ_RANGE_PLAYER \
93 || range == REQ_RANGE_TEAM \
94 || range == REQ_RANGE_ALLIANCE \
95 || (range == REQ_RANGE_TRADEROUTE \
96 && (city == city_here \
97 || have_cities_trade_route(city, city_here))) \
98 || ((range == REQ_RANGE_CITY || range == REQ_RANGE_LOCAL) \
99 && city == city_here) \
100 || (range == REQ_RANGE_CONTINENT \
101 && tile_continent(city->tile) == \
102 tile_continent(city_here->tile))) {
104 #define city_range_iterate_end \
106 } city_list_iterate_end; \
109 #define CITY_EMERGENCY(pcity) \
110 (pcity->surplus[O_SHIELD] < 0 || city_unhappy(pcity) \
111 || pcity->food_stock + pcity->surplus[O_FOOD] < 0)
113 static void dai_city_sell_noncritical(struct city *pcity, bool redundant_only);
114 static void resolve_city_emergency(struct ai_type *ait, struct player *pplayer,
115 struct city *pcity);
117 /**************************************************************************
118 Increase want for a technology because of the value of that technology
119 in providing an improvement effect.
121 The input building_want gives the desire for the improvement;
122 the value may be negative for technologies that produce undesirable
123 effects.
125 This function must convert from units of 'building want' to 'tech want'.
126 We put this conversion in a function because the 'want' scales are
127 unclear and kludged. Consequently, this conversion might require tweaking.
128 **************************************************************************/
129 static void want_tech_for_improvement_effect(struct ai_type *ait,
130 struct player *pplayer,
131 const struct city *pcity,
132 const struct impr_type *pimprove,
133 const struct advance *tech,
134 adv_want building_want)
136 /* The conversion factor was determined by experiment,
137 * and might need adjustment. See also dai_tech_effect_values()
139 const adv_want tech_want = building_want * def_ai_city_data(pcity, ait)->building_wait
140 * 14 / 8;
141 #if 0
142 /* This logging is relatively expensive,
143 * so activate it only while necessary. */
144 TECH_LOG(LOG_DEBUG, pplayer, tech,
145 "wanted by %s for building: %d -> %d",
146 city_name_get(pcity), improvement_rule_name(pimprove),
147 building_want, tech_want);
148 #endif /* 0 */
149 if (tech) {
150 def_ai_player_data(pplayer, ait)->tech_want[advance_index(tech)] += tech_want;
154 /**************************************************************************
155 Increase want for a technologies because of the value of that technology
156 in providing an improvement effect.
157 **************************************************************************/
158 void want_techs_for_improvement_effect(struct ai_type *ait,
159 struct player *pplayer,
160 const struct city *pcity,
161 const struct impr_type *pimprove,
162 struct tech_vector *needed_techs,
163 adv_want building_want)
165 int t;
166 int n_needed_techs = tech_vector_size(needed_techs);
168 for (t = 0; t < n_needed_techs; t++) {
169 want_tech_for_improvement_effect(ait, pplayer, pcity, pimprove,
170 *tech_vector_get(needed_techs, t),
171 building_want);
175 /**************************************************************************
176 Decrease want for a technology because of the value of that technology
177 in obsoleting an improvement effect.
178 **************************************************************************/
179 void dont_want_tech_obsoleting_impr(struct ai_type *ait,
180 struct player *pplayer,
181 const struct city *pcity,
182 const struct impr_type *pimprove,
183 adv_want building_want)
185 requirement_vector_iterate(&pimprove->obsolete_by, pobs) {
186 if (pobs->source.kind == VUT_ADVANCE && pobs->present) {
187 want_tech_for_improvement_effect(ait, pplayer, pcity, pimprove,
188 pobs->source.value.advance,
189 -building_want);
191 } requirement_vector_iterate_end;
194 /**************************************************************************
195 Choose a build for the barbarian player.
197 TODO: Move this into daimilitary.c
198 TODO: It will be called for each city but doesn't depend on the city,
199 maybe cache it? Although barbarians don't normally have many cities,
200 so can be a bigger bother to cache it.
201 **************************************************************************/
202 static void dai_barbarian_choose_build(struct player *pplayer,
203 struct city *pcity,
204 struct adv_choice *choice)
206 struct unit_type *bestunit = NULL;
207 int i, bestattack = 0;
209 /* Choose the best unit among the basic ones */
210 for (i = 0; i < num_role_units(L_BARBARIAN_BUILD); i++) {
211 struct unit_type *iunit = get_role_unit(L_BARBARIAN_BUILD, i);
213 if (iunit->attack_strength > bestattack
214 && can_city_build_unit_now(pcity, iunit)) {
215 bestunit = iunit;
216 bestattack = iunit->attack_strength;
220 /* Choose among those made available through other civ's research */
221 for (i = 0; i < num_role_units(L_BARBARIAN_BUILD_TECH); i++) {
222 struct unit_type *iunit = get_role_unit(L_BARBARIAN_BUILD_TECH, i);
224 if (iunit->attack_strength > bestattack
225 && can_city_build_unit_now(pcity, iunit)) {
226 bestunit = iunit;
227 bestattack = iunit->attack_strength;
231 /* If found anything, put it into the choice */
232 if (bestunit) {
233 choice->value.utype = bestunit;
234 /* FIXME: 101 is the "overriding military emergency" indicator */
235 choice->want = 101;
236 choice->type = CT_ATTACKER;
237 adv_choice_set_use(choice, "barbarian");
238 } else {
239 log_base(LOG_WANT, "Barbarians don't know what to build!");
243 /**************************************************************************
244 Chooses what the city will build. Is called after the military advisor
245 put it's choice into pcity->server.ai.choice and "settler advisor" put
246 settler want into pcity->founder_*.
248 Note that AI cheats -- it suffers no penalty for switching from unit to
249 improvement, etc.
250 **************************************************************************/
251 static void dai_city_choose_build(struct ai_type *ait, struct player *pplayer,
252 struct city *pcity)
254 struct adv_choice *newchoice;
255 struct adv_data *adv = adv_data_get(pplayer, NULL);
256 struct ai_city *city_data = def_ai_city_data(pcity, ait);
258 if (has_handicap(pplayer, H_AWAY)
259 && city_built_last_turn(pcity)
260 && city_data->urgency == 0) {
261 /* Don't change existing productions unless we have to. */
262 return;
265 if (is_barbarian(pplayer)) {
266 dai_barbarian_choose_build(pplayer, pcity, &(city_data->choice));
267 } else {
268 /* FIXME: 101 is the "overriding military emergency" indicator */
269 if ((city_data->choice.want <= 100
270 || city_data->urgency == 0)
271 && !(dai_on_war_footing(ait, pplayer) && city_data->choice.want > 0
272 && pcity->id != adv->wonder_city)) {
273 newchoice = domestic_advisor_choose_build(ait, pplayer, pcity);
274 adv_choice_copy(&(city_data->choice), adv_better_choice(&(city_data->choice), newchoice));
275 adv_free_choice(newchoice);
279 /* Fallbacks */
280 if (city_data->choice.want == 0) {
281 /* Fallbacks do happen with techlevel 0, which is now default. -- Per */
282 CITY_LOG(LOG_WANT, pcity, "Falling back - didn't want to build soldiers,"
283 " workers, caravans, settlers, or buildings!");
284 city_data->choice.want = 1;
285 if (best_role_unit(pcity, action_id_get_role(ACTION_TRADE_ROUTE))) {
286 city_data->choice.value.utype
287 = best_role_unit(pcity, action_id_get_role(ACTION_TRADE_ROUTE));
288 city_data->choice.type = CT_CIVILIAN;
289 adv_choice_set_use(&(city_data->choice), "fallback trade route");
290 } else {
291 unsigned int our_def = assess_defense_quadratic(ait, pcity);
293 if (our_def == 0
294 && dai_process_defender_want(ait, pplayer, pcity, 1, &(city_data->choice))) {
295 adv_choice_set_use(&(city_data->choice), "fallback defender");
296 CITY_LOG(LOG_DEBUG, pcity, "Building fallback defender");
297 } else if (best_role_unit(pcity, UTYF_SETTLERS)) {
298 city_data->choice.value.utype
299 = dai_role_utype_for_terrain_class(pcity, UTYF_SETTLERS, TC_LAND);
300 city_data->choice.type = CT_CIVILIAN;
301 adv_choice_set_use(&(city_data->choice), "fallback worker");
302 } else {
303 CITY_LOG(LOG_ERROR, pcity, "Cannot even build a fallback "
304 "(caravan/coinage/settlers). Fix the ruleset!");
305 city_data->choice.want = 0;
310 if (city_data->choice.want != 0) {
311 struct universal build_new;
313 ADV_CHOICE_ASSERT(city_data->choice);
315 CITY_LOG(LOG_DEBUG, pcity, "wants %s with desire " ADV_WANT_PRINTF ".",
316 dai_choice_rule_name(&city_data->choice),
317 city_data->choice.want);
319 switch (city_data->choice.type) {
320 case CT_CIVILIAN:
321 case CT_ATTACKER:
322 case CT_DEFENDER:
323 build_new.kind = VUT_UTYPE;
324 build_new.value.utype = city_data->choice.value.utype;
325 break;
326 case CT_BUILDING:
327 build_new.kind = VUT_IMPROVEMENT;
328 build_new.value.building = city_data->choice.value.building;
329 break;
330 case CT_NONE:
331 build_new.kind = VUT_NONE;
332 break;
333 case CT_LAST:
334 build_new.kind = universals_n_invalid();
335 break;
338 change_build_target(pplayer, pcity, &build_new, E_CITY_PRODUCTION_CHANGED);
342 /**************************************************************************
343 Sell building from city
344 **************************************************************************/
345 static void try_to_sell_stuff(struct player *pplayer, struct city *pcity)
347 improvement_iterate(pimprove) {
348 if (can_city_sell_building(pcity, pimprove)
349 && !building_has_effect(pimprove, EFT_DEFEND_BONUS)) {
350 /* selling walls to buy defenders is counterproductive -- Syela */
351 really_handle_city_sell(pplayer, pcity, pimprove);
352 break;
354 } improvement_iterate_end;
357 /**************************************************************************
358 Increase maxbuycost. This variable indicates (via ai_gold_reserve) to
359 the tax selection code how much money do we need for buying stuff.
360 **************************************************************************/
361 static void increase_maxbuycost(struct player *pplayer, int new_value)
363 pplayer->ai_common.maxbuycost = MAX(pplayer->ai_common.maxbuycost, new_value);
366 /**************************************************************************
367 Try to upgrade a city's units. limit is the last amount of gold we can
368 end up with after the upgrade. military is if we want to upgrade non-
369 military or military units.
370 **************************************************************************/
371 static void dai_upgrade_units(struct city *pcity, int limit, bool military)
373 struct player *pplayer = city_owner(pcity);
374 int expenses;
376 dai_calc_data(pplayer, NULL, &expenses, NULL);
378 unit_list_iterate(pcity->tile->units, punit) {
379 if (pcity->owner == punit->owner) {
380 struct unit_type *old_type = unit_type_get(punit);
382 /* Only upgrade units you own, not allied ones */
383 struct unit_type *punittype = can_upgrade_unittype(pplayer, old_type);
385 if (military && !IS_ATTACKER(old_type)) {
386 /* Only upgrade military units this round */
387 continue;
388 } else if (!military && IS_ATTACKER(old_type)) {
389 /* Only civilians or tranports this round */
390 continue;
393 if (punittype) {
394 int cost = unit_upgrade_price(pplayer, old_type, punittype);
395 int real_limit = limit;
397 /* Sinking Triremes are DANGEROUS!! We'll do anything to upgrade 'em. */
398 /* FIXME: This assumes rules to be quite close to civ/2.
399 * Of the supplied rulesets those are the only ones with
400 * UTYF_COAST unit, but... */
401 if (unit_has_type_flag(punit, UTYF_COAST)) {
402 real_limit = expenses;
404 if (pplayer->economic.gold - cost > real_limit) {
405 CITY_LOG(LOG_BUY, pcity, "Upgraded %s to %s for %d (%s)",
406 unit_rule_name(punit),
407 utype_rule_name(punittype),
408 cost,
409 military ? "military" : "civilian");
410 handle_unit_do_action(city_owner(pcity), punit->id,
411 pcity->id, 0, "", ACTION_UPGRADE_UNIT);
412 } else {
413 increase_maxbuycost(pplayer, cost);
417 } unit_list_iterate_end;
420 /**************************************************************************
421 Try to disband punit in the traditional way.
423 Try to disband the specified unit. Match the old behavior in what kind
424 of disbanding is tried and who benefits from it.
425 **************************************************************************/
426 static void unit_do_disband_trad(struct player *owner, struct unit *punit,
427 const enum action_requester requester)
429 const int punit_id_stored = punit->id;
431 fc_assert_ret(owner == unit_owner(punit));
433 /* Help Wonder gives 100% of the shields used to produce the unit to the
434 * city where it is located. */
435 if (unit_can_do_action(punit, ACTION_HELP_WONDER)) {
436 struct city *tgt_city;
438 /* Only a city at the same tile as the unit can benefit. */
439 tgt_city = tile_city(unit_tile(punit));
441 if (tgt_city
442 && is_action_enabled_unit_on_city(ACTION_HELP_WONDER,
443 punit, tgt_city)) {
444 if (unit_perform_action(owner, punit->id, tgt_city->id,
445 0, NULL, ACTION_HELP_WONDER, requester)) {
446 /* No shields wasted. The unit did Help Wonder. */
447 return;
452 if (!unit_is_alive(punit_id_stored)) {
453 /* The unit is gone. Maybe it was killed in Lua? */
454 return;
457 /* Disbanding a unit inside a city gives it 50% of the shields used to
458 * produce the unit. */
459 if (unit_can_do_action(punit, ACTION_RECYCLE_UNIT)) {
460 struct city *tgt_city;
462 /* Only a city at the same tile as the unit can benefit. */
463 tgt_city = tile_city(unit_tile(punit));
465 if (tgt_city
466 && is_action_enabled_unit_on_city(ACTION_RECYCLE_UNIT,
467 punit, tgt_city)) {
468 if (unit_perform_action(owner, punit->id, tgt_city->id,
469 0, NULL, ACTION_RECYCLE_UNIT, requester)) {
470 /* The unit did Recycle Unit. 50% of the shields wasted. */
471 return;
476 if (!unit_is_alive(punit_id_stored)) {
477 /* The unit is gone. Maybe it was killed in Lua? */
478 return;
481 /* Try to disband even if all shields will be wasted. */
482 if (unit_can_do_action(punit, ACTION_DISBAND_UNIT)) {
483 if (is_action_enabled_unit_on_self(ACTION_DISBAND_UNIT, punit)) {
484 if (unit_perform_action(owner, punit->id, punit->id,
485 0, NULL, ACTION_DISBAND_UNIT, requester)) {
486 /* All shields wasted. The unit did Disband Unit. */
487 return;
493 /**************************************************************************
494 Buy and upgrade stuff!
495 **************************************************************************/
496 static void dai_spend_gold(struct ai_type *ait, struct player *pplayer)
498 struct adv_choice bestchoice;
499 int cached_limit = dai_gold_reserve(pplayer);
500 int expenses;
501 bool war_footing = dai_on_war_footing(ait, pplayer);
503 /* Disband explorers that are at home but don't serve a purpose.
504 * FIXME: This is a hack, and should be removed once we
505 * learn how to ferry explorers to new land. */
506 city_list_iterate(pplayer->cities, pcity) {
507 struct tile *ptile = pcity->tile;
508 unit_list_iterate_safe(ptile->units, punit) {
509 if (unit_has_type_role(punit, L_EXPLORER)
510 && pcity->id == punit->homecity
511 && def_ai_city_data(pcity, ait)->urgency == 0) {
512 CITY_LOG(LOG_BUY, pcity, "disbanding %s to increase production",
513 unit_rule_name(punit));
514 unit_do_disband_trad(pplayer, punit, ACT_REQ_PLAYER);
516 } unit_list_iterate_safe_end;
517 } city_list_iterate_end;
519 dai_calc_data(pplayer, NULL, &expenses, NULL);
521 do {
522 bool expensive; /* don't buy when it costs x2 unless we must */
523 int buycost;
524 int limit = cached_limit; /* cached_limit is our gold reserve */
525 struct city *pcity = NULL;
526 struct ai_city *city_data;
528 /* Find highest wanted item on the buy list */
529 adv_init_choice(&bestchoice);
530 city_list_iterate(pplayer->cities, acity) {
531 struct ai_city *acity_data = def_ai_city_data(acity, ait);
533 if (acity_data->choice.want
534 > bestchoice.want && ai_fuzzy(pplayer, TRUE)) {
535 bestchoice.value = acity_data->choice.value;
536 bestchoice.want = acity_data->choice.want;
537 bestchoice.type = acity_data->choice.type;
538 pcity = acity;
540 } city_list_iterate_end;
542 /* We found nothing, so we're done */
543 if (bestchoice.want == 0) {
544 break;
547 city_data = def_ai_city_data(pcity, ait);
549 /* Not dealing with this city a second time */
550 city_data->choice.want = 0;
552 ADV_CHOICE_ASSERT(bestchoice);
554 /* Try upgrade units at danger location (high want is usually danger) */
555 if (city_data->urgency > 1) {
556 if (bestchoice.type == CT_BUILDING
557 && is_wonder(bestchoice.value.building)) {
558 CITY_LOG(LOG_BUY, pcity, "Wonder being built in dangerous position!");
559 } else {
560 /* If we have urgent want, spend more */
561 int upgrade_limit = limit;
563 if (city_data->urgency > 1) {
564 upgrade_limit = expenses;
566 /* Upgrade only military units now */
567 dai_upgrade_units(pcity, upgrade_limit, TRUE);
571 if (pcity->anarchy != 0 && bestchoice.type != CT_BUILDING) {
572 continue; /* Nothing we can do */
575 /* Cost to complete production */
576 buycost = city_production_buy_gold_cost(pcity);
578 if (buycost <= 0) {
579 continue; /* Already completed */
582 if (is_unit_choice_type(bestchoice.type)
583 && utype_is_cityfounder(bestchoice.value.utype)) {
584 if (get_city_bonus(pcity, EFT_GROWTH_FOOD) == 0
585 && bestchoice.value.utype->pop_cost > 0
586 && city_size_get(pcity) <= bestchoice.value.utype->pop_cost) {
587 /* Don't buy settlers in cities that cannot afford the population cost. */
588 /* This used to check also if city is about to grow to required size
589 * next turn and allow buying of settlers in that case, but current
590 * order of end/start turn activities is such that settler building
591 * fails already before city grows. */
592 continue;
593 } else if (city_list_size(pplayer->cities) > 6) {
594 /* Don't waste precious money buying settlers late game
595 * since this raises taxes, and we want science. Adjust this
596 * again when our tax algorithm is smarter. */
597 continue;
598 } else if (war_footing) {
599 continue;
601 } else {
602 /* We are not a settler. Therefore we increase the cash need we
603 * balance our buy desire with to keep cash at hand for emergencies
604 * and for upgrades */
605 limit *= 2;
608 /* It costs x2 to buy something with no shields contributed */
609 expensive = (pcity->shield_stock == 0)
610 || (pplayer->economic.gold - buycost < limit);
612 if (bestchoice.type == CT_ATTACKER
613 && buycost
614 > utype_build_shield_cost(bestchoice.value.utype) * 2
615 && !war_footing) {
616 /* Too expensive for an offensive unit */
617 continue;
620 /* FIXME: Here Syela wanted some code to check if
621 * pcity was doomed, and we should therefore attempt
622 * to sell everything in it of non-military value */
624 if (pplayer->economic.gold - expenses >= buycost
625 && (!expensive
626 || (city_data->grave_danger != 0
627 && assess_defense(ait, pcity) == 0)
628 || (bestchoice.want > 200 && city_data->urgency > 1))) {
629 /* Buy stuff */
630 CITY_LOG(LOG_BUY, pcity, "Crash buy of %s for %d (want " ADV_WANT_PRINTF ")",
631 dai_choice_rule_name(&bestchoice),
632 buycost,
633 bestchoice.want);
634 really_handle_city_buy(pplayer, pcity);
635 } else if (city_data->grave_danger != 0
636 && bestchoice.type == CT_DEFENDER
637 && assess_defense(ait, pcity) == 0) {
638 /* We have no gold but MUST have a defender */
639 CITY_LOG(LOG_BUY, pcity, "must have %s but can't afford it (%d < %d)!",
640 dai_choice_rule_name(&bestchoice),
641 pplayer->economic.gold,
642 buycost);
643 try_to_sell_stuff(pplayer, pcity);
644 if (pplayer->economic.gold - expenses >= buycost) {
645 CITY_LOG(LOG_BUY, pcity, "now we can afford it (sold something)");
646 really_handle_city_buy(pplayer, pcity);
648 increase_maxbuycost(pplayer, buycost);
650 } while (TRUE);
652 if (!war_footing) {
653 /* Civilian upgrades now */
654 city_list_iterate(pplayer->cities, pcity) {
655 dai_upgrade_units(pcity, cached_limit, FALSE);
656 } city_list_iterate_end;
659 log_base(LOG_BUY, "%s wants to keep %d in reserve (tax factor %d)",
660 player_name(pplayer), cached_limit, pplayer->ai_common.maxbuycost);
663 /**************************************************************************
664 Calculates a unit's food upkeep (per turn).
665 **************************************************************************/
666 static int unit_food_upkeep(struct unit *punit)
668 struct player *pplayer = unit_owner(punit);
669 int upkeep = utype_upkeep_cost(unit_type_get(punit), pplayer, O_FOOD);
671 if (punit->id != 0 && punit->homecity == 0)
672 upkeep = 0; /* thanks, Peter */
674 return upkeep;
678 /**************************************************************************
679 Returns how much food a settler will consume out of the city's foodbox
680 when created. If unit has id zero it is assumed to be a virtual unit
681 inside a city.
683 FIXME: This function should be generalised and then moved into
684 common/unittype.c - Per
685 **************************************************************************/
686 static int unit_foodbox_cost(struct unit *punit)
688 int pop_cost = unit_type_get(punit)->pop_cost;
690 if (pop_cost <= 0) {
691 return 0;
694 if (punit->id == 0) {
695 /* It is a virtual unit, so must start in a city... */
696 struct city *pcity = tile_city(unit_tile(punit));
697 int size = city_size_get(pcity);
698 int cost = 0;
699 int i;
701 /* The default is to lose 100%. The growth bonus reduces this. */
702 int foodloss_pct = 100 - get_city_bonus(pcity, EFT_GROWTH_FOOD);
704 foodloss_pct = CLIP(0, foodloss_pct, 100);
705 fc_assert_ret_val(pcity != NULL, -1);
706 fc_assert(size >= pop_cost);
708 for (i = pop_cost; i > 0 ; i--) {
709 cost += city_granary_size(size--);
711 cost = cost * foodloss_pct / 100;
713 return cost;
716 return 30;
719 /**************************************************************************
720 Estimates the want for a terrain improver (aka worker) by creating a
721 virtual unit and feeding it to settler_evaluate_improvements.
723 TODO: AI does not ship UTYF_SETTLERS around, only UTYF_CITIES - Per
724 **************************************************************************/
725 static void contemplate_terrain_improvements(struct ai_type *ait,
726 struct city *pcity)
728 struct unit *virtualunit;
729 int want;
730 enum unit_activity best_act;
731 struct extra_type *best_target;
732 struct tile *best_tile = NULL; /* May be accessed by log_*() calls. */
733 struct tile *pcenter = city_tile(pcity);
734 struct player *pplayer = city_owner(pcity);
735 struct adv_data *adv = adv_data_get(pplayer, NULL);
736 struct ai_plr *ai = dai_plr_data_get(ait, pplayer, NULL);
737 struct unit_type *utype;
738 Continent_id place = tile_continent(pcenter);
739 struct ai_city *city_data = def_ai_city_data(pcity, ait);
740 struct dai_private_data *private = (struct dai_private_data *)ait->private;
742 if (!private->contemplace_workers) {
743 /* AI type uses custom method to set worker want and type. */
744 return;
747 city_data->worker_want = 0; /* Make sure old want does not stay if we don't want now */
749 utype = dai_role_utype_for_terrain_class(pcity, UTYF_SETTLERS, TC_LAND);
751 if (utype == NULL) {
752 log_debug("No UTYF_SETTLERS role unit available");
753 return;
756 /* Create a localized "virtual" unit to do operations with. */
757 virtualunit = unit_virtual_create(pplayer, pcity, utype, 0);
758 /* Advisors data space not allocated as it's not needed in the
759 lifetime of the virtualunit. */
760 unit_tile_set(virtualunit, pcenter);
761 want = settler_evaluate_improvements(virtualunit, &best_act, &best_target,
762 &best_tile,
763 NULL, NULL);
764 if (unit_type_get(virtualunit)->pop_cost >= city_size_get(pcity)) {
765 /* We don't like disbanding the city as a side effect */
766 unit_virtual_destroy(virtualunit);
768 return;
770 /* We consider unit_food_upkeep with only half FOOD_WEIGHTING to
771 * balance the fact that unit can improve many tiles during its
772 * lifetime, and want is calculated for just one of them.
773 * Having full FOOD_WEIGHT here would mean that tile improvement of
774 * +1 food would give just zero want for settler. Other weights
775 * are lower, so +1 shield - unit food upkeep would be negative. */
776 want = (want - unit_food_upkeep(virtualunit) * FOOD_WEIGHTING / 2) * 100
777 / (40 + unit_foodbox_cost(virtualunit));
778 unit_virtual_destroy(virtualunit);
780 /* Massage our desire based on available statistics to prevent
781 * overflooding with worker type units if they come cheap in
782 * the ruleset */
783 if (place >= 0) {
784 want /= MAX(1, ai->stats.workers[place] / (adv->stats.cities[place] + 1));
785 want -= ai->stats.workers[place];
786 } else {
787 /* TODO: Handle Oceans with cities sensibly */
789 want = MAX(want, 0);
791 if (place >= 0) {
792 CITY_LOG(LOG_DEBUG, pcity, "wants %s with want %d to do %s at (%d,%d), "
793 "we have %d workers and %d cities on the continent",
794 utype_rule_name(utype),
795 want,
796 get_activity_text(best_act),
797 TILE_XY(best_tile),
798 ai->stats.workers[place],
799 adv->stats.cities[place]);
800 } else {
801 CITY_LOG(LOG_DEBUG, pcity, "wants %s with want %d to do %s at (%d,%d)",
802 utype_rule_name(utype),
803 want,
804 get_activity_text(best_act),
805 TILE_XY(best_tile));
808 fc_assert(want >= 0);
810 city_data->worker_want = want;
811 city_data->worker_type = dai_role_utype_for_terrain_class(pcity, UTYF_SETTLERS,
812 TC_LAND);
815 /**************************************************************************
816 One of the top level AI functions. It does (by calling other functions):
817 worker allocations,
818 build choices,
819 extra gold spending.
820 **************************************************************************/
821 void dai_manage_cities(struct ai_type *ait, struct player *pplayer)
823 pplayer->ai_common.maxbuycost = 0;
825 TIMING_LOG(AIT_EMERGENCY, TIMER_START);
826 city_list_iterate(pplayer->cities, pcity) {
827 if (CITY_EMERGENCY(pcity)
828 || city_granary_size(city_size_get(pcity)) == pcity->food_stock) {
829 /* Having a full granary isn't an emergency, but we want to rearrange */
830 auto_arrange_workers(pcity); /* this usually helps */
832 if (CITY_EMERGENCY(pcity)) {
833 /* Fix critical shortages or unhappiness */
834 resolve_city_emergency(ait, pplayer, pcity);
836 dai_city_sell_noncritical(pcity, TRUE);
837 sync_cities();
838 } city_list_iterate_end;
839 if (pplayer->economic.tax >= 30 /* Otherwise expect it to increase tax */
840 && player_get_expected_income(pplayer) < -(pplayer->economic.gold)) {
841 int count = city_list_size(pplayer->cities);
842 struct city *sellers[count + 1];
843 int i;
845 /* Randomized order */
846 i = 0;
847 city_list_iterate(pplayer->cities, pcity) {
848 sellers[i++] = pcity;
849 } city_list_iterate_end;
850 for (i = 0; i < count; i++) {
851 int replace = fc_rand(count);
852 struct city *tmp;
854 tmp = sellers[i];
855 sellers[i] = sellers[replace];
856 sellers[replace] = tmp;
859 i = 0;
860 while (player_get_expected_income(pplayer) < -(pplayer->economic.gold)
861 && i < count) {
862 dai_city_sell_noncritical(sellers[i++], FALSE);
865 TIMING_LOG(AIT_EMERGENCY, TIMER_STOP);
867 TIMING_LOG(AIT_BUILDINGS, TIMER_START);
868 building_advisor(pplayer);
869 TIMING_LOG(AIT_BUILDINGS, TIMER_STOP);
871 /* Initialize the infrastructure cache, which is used shortly. */
872 initialize_infrastructure_cache(pplayer);
873 city_list_iterate(pplayer->cities, pcity) {
874 struct ai_city *city_data = def_ai_city_data(pcity, ait);
875 struct adv_choice *choice;
877 /* Note that this function mungs the seamap, but we don't care */
878 TIMING_LOG(AIT_CITY_MILITARY, TIMER_START);
879 choice = military_advisor_choose_build(ait, pplayer, pcity);
880 adv_choice_copy(&(city_data->choice), choice);
881 adv_free_choice(choice);
882 TIMING_LOG(AIT_CITY_MILITARY, TIMER_STOP);
883 if (dai_on_war_footing(ait, pplayer) && city_data->choice.want > 0) {
884 city_data->worker_want = 0;
885 city_data->founder_want = 0;
886 city_data->founder_turn = game.info.turn; /* Do not consider zero we set here
887 * valid value, if real want is needed.
888 * Recalculate immediately in such situation. */
889 continue; /* Go, soldiers! */
891 /* Will record its findings in pcity->worker_want */
892 TIMING_LOG(AIT_CITY_TERRAIN, TIMER_START);
893 contemplate_terrain_improvements(ait, pcity);
894 TIMING_LOG(AIT_CITY_TERRAIN, TIMER_STOP);
896 TIMING_LOG(AIT_CITY_SETTLERS, TIMER_START);
897 if (city_data->founder_turn <= game.info.turn) {
898 /* Will record its findings in pcity->founder_want */
899 contemplate_new_city(ait, pcity);
900 /* Avoid recalculating all the time.. */
901 /* This means AI is not very opportunistic if there happens to open up spot for
902 * a new city. */
903 city_data->founder_turn =
904 game.info.turn + fc_rand(AI_CITY_RECALC_SPEED) + AI_CITY_RECALC_SPEED;
905 } else if (pcity->server.debug) {
906 /* recalculate every turn */
907 contemplate_new_city(ait, pcity);
909 TIMING_LOG(AIT_CITY_SETTLERS, TIMER_STOP);
910 ADV_CHOICE_ASSERT(city_data->choice);
911 } city_list_iterate_end;
912 /* Reset auto settler state for the next run. */
913 dai_auto_settler_reset(ait, pplayer);
915 city_list_iterate(pplayer->cities, pcity) {
916 dai_city_choose_build(ait, pplayer, pcity);
917 } city_list_iterate_end;
919 dai_spend_gold(ait, pplayer);
922 /**************************************************************************
923 Are effects provided by this building not needed?
925 If this function is called for a building that has not yet been
926 constructed, side effect benefits may not be accurately calculated
927 (see improvement.c for details).
928 **************************************************************************/
929 static bool building_crucial(const struct player *plr,
930 struct impr_type *pimprove,
931 const struct city *pcity)
933 #if 0 /* This check will become more complicated now. */
934 if (ai_wants_no_science(plr)
935 && building_has_effect(pimprove, EFT_SCIENCE_BONUS)) {
936 return FALSE;
938 #endif
939 if (building_has_effect(pimprove, EFT_DEFEND_BONUS)
940 /* selling city walls is really, really dumb -- Syela */
941 || is_improvement_productive(pcity, pimprove)) {
942 return TRUE;
945 return FALSE;
948 /**************************************************************************
949 Sell an noncritical building if there are any in the city.
950 **************************************************************************/
951 static void dai_city_sell_noncritical(struct city *pcity,
952 bool redundant_only)
954 struct player *pplayer = city_owner(pcity);
956 city_built_iterate(pcity, pimprove) {
957 if (can_city_sell_building(pcity, pimprove)
958 && !building_crucial(pplayer, pimprove, pcity)
959 && (!redundant_only || is_improvement_redundant(pcity, pimprove))) {
960 do_sell_building(pplayer, pcity, pimprove);
961 notify_player(pplayer, pcity->tile, E_IMP_SOLD, ftc_server,
962 _("%s is selling %s for %d."),
963 city_link(pcity),
964 improvement_name_translation(pimprove),
965 impr_sell_gold(pimprove));
966 return; /* max 1 building each turn */
968 } city_built_iterate_end;
971 /**************************************************************************
972 This function tries desperately to save a city from going under by
973 revolt or starvation of food or resources. We do this by taking
974 over resources held by nearby cities and disbanding units.
976 TODO: Try to move units into friendly cities to reduce unhappiness
977 instead of disbanding. Also rather starve city than keep it in
978 revolt, as long as we don't lose settlers.
980 TODO: Make function that tries to save units by moving them into
981 cities that can upkeep them and change homecity rather than just
982 disband. This means we'll have to move this function to beginning
983 of AI turn sequence (before moving units).
985 "I don't care how slow this is; it will very rarely be used." -- Syela
987 Syela is wrong. It happens quite too often, mostly due to unhappiness.
988 Also, most of the time we are unable to resolve the situation.
989 **************************************************************************/
990 static void resolve_city_emergency(struct ai_type *ait, struct player *pplayer,
991 struct city *pcity)
993 struct tile *pcenter = city_tile(pcity);
995 log_base(LOG_EMERGENCY,
996 "Emergency in %s (%s, angry%d, unhap%d food%d, prod%d)",
997 city_name_get(pcity),
998 city_unhappy(pcity) ? "unhappy" : "content",
999 pcity->feel[CITIZEN_ANGRY][FEELING_FINAL],
1000 pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL],
1001 pcity->surplus[O_FOOD],
1002 pcity->surplus[O_SHIELD]);
1004 city_tile_iterate(city_map_radius_sq_get(pcity), pcenter, atile) {
1005 struct city *acity = tile_worked(atile);
1007 if (acity && acity != pcity && city_owner(acity) == city_owner(pcity)) {
1008 log_base(LOG_EMERGENCY, "%s taking over %s square in (%d, %d)",
1009 city_name_get(pcity), city_name_get(acity), TILE_XY(atile));
1011 int ax, ay;
1012 fc_assert_action(city_base_to_city_map(&ax, &ay, acity, atile),
1013 continue);
1015 if (is_free_worked(acity, atile)) {
1016 /* Can't remove a worker here. */
1017 continue;
1020 city_map_update_empty(acity, atile);
1021 acity->specialists[DEFAULT_SPECIALIST]++;
1022 city_freeze_workers_queue(acity);
1024 } city_tile_iterate_end;
1026 auto_arrange_workers(pcity);
1028 if (!CITY_EMERGENCY(pcity)) {
1029 log_base(LOG_EMERGENCY, "Emergency in %s resolved", city_name_get(pcity));
1030 goto cleanup;
1033 unit_list_iterate_safe(pcity->units_supported, punit) {
1034 if (city_unhappy(pcity)
1035 && (utype_happy_cost(unit_type_get(punit), pplayer) > 0
1036 && (unit_being_aggressive(punit) || is_field_unit(punit)))
1037 && def_ai_unit_data(punit, ait)->passenger == 0) {
1038 UNIT_LOG(LOG_EMERGENCY, punit, "is causing unrest, disbanded");
1039 /* TODO: if Help Wonder stops blocking Disband Unit there may be
1040 * cases where Disband Unit should be selected. Example: Field unit
1041 * in allied city that is building a wonder that makes the ally win
1042 * without sharing the victory. */
1043 /* TODO: Should the unit try to find legal targets at adjacent tiles?
1044 * Should it consider other self eliminating actions than the
1045 * components of the traditional disband? */
1046 unit_do_disband_trad(pplayer, punit, ACT_REQ_PLAYER);
1047 city_refresh(pcity);
1049 } unit_list_iterate_safe_end;
1051 if (CITY_EMERGENCY(pcity)) {
1052 log_base(LOG_EMERGENCY, "Emergency in %s remains unresolved",
1053 city_name_get(pcity));
1054 } else {
1055 log_base(LOG_EMERGENCY,
1056 "Emergency in %s resolved by disbanding unit(s)",
1057 city_name_get(pcity));
1060 cleanup:
1061 city_thaw_workers_queue();
1062 sync_cities();
1065 /**************************************************************************
1066 Initialize city for use with default AI.
1067 **************************************************************************/
1068 void dai_city_alloc(struct ai_type *ait, struct city *pcity)
1070 struct ai_city *city_data = fc_calloc(1, sizeof(struct ai_city));
1072 city_data->building_wait = BUILDING_WAIT_MINIMUM;
1073 adv_init_choice(&(city_data->choice));
1075 city_set_ai_data(pcity, ait, city_data);
1078 /**************************************************************************
1079 Free city from use with default AI.
1080 **************************************************************************/
1081 void dai_city_free(struct ai_type *ait, struct city *pcity)
1083 struct ai_city *city_data = def_ai_city_data(pcity, ait);
1085 if (city_data != NULL) {
1086 adv_deinit_choice(&(city_data->choice));
1087 city_set_ai_data(pcity, ait, NULL);
1088 FC_FREE(city_data);
1092 /**************************************************************************
1093 Write ai city segments to savefile
1094 **************************************************************************/
1095 void dai_city_save(struct ai_type *ait, const char *aitstr,
1096 struct section_file *file, const struct city *pcity,
1097 const char *citystr)
1099 struct ai_city *city_data = def_ai_city_data(pcity, ait);
1101 /* FIXME: remove this when the urgency is properly recalculated. */
1102 secfile_insert_int(file, city_data->urgency, "%s.%s.urgency", citystr, aitstr);
1104 /* avoid fc_rand recalculations on subsequent reload. */
1105 secfile_insert_int(file, city_data->building_turn, "%s.%s.building_turn",
1106 citystr, aitstr);
1107 secfile_insert_int(file, city_data->building_wait, "%s.%s.building_wait",
1108 citystr, aitstr);
1110 /* avoid fc_rand and expensive recalculations on subsequent reload. */
1111 secfile_insert_int(file, city_data->founder_turn, "%s.%s.founder_turn",
1112 citystr, aitstr);
1113 secfile_insert_int(file, city_data->founder_want, "%s.%s.founder_want",
1114 citystr, aitstr);
1115 secfile_insert_bool(file, city_data->founder_boat, "%s.%s.founder_boat",
1116 citystr, aitstr);
1119 /**************************************************************************
1120 Load ai city segment from savefile
1121 **************************************************************************/
1122 void dai_city_load(struct ai_type *ait, const char *aitstr,
1123 const struct section_file *file,
1124 struct city *pcity, const char *citystr)
1126 struct ai_city *city_data = def_ai_city_data(pcity, ait);
1128 /* FIXME: remove this when the urgency is properly recalculated. */
1129 city_data->urgency
1130 = secfile_lookup_int_default(file, 0, "%s.%s.urgency", citystr, aitstr);
1132 /* avoid fc_rand recalculations on subsequent reload. */
1133 city_data->building_turn
1134 = secfile_lookup_int_default(file, 0, "%s.%s.building_turn", citystr,
1135 aitstr);
1136 city_data->building_wait
1137 = secfile_lookup_int_default(file, BUILDING_WAIT_MINIMUM,
1138 "%s.%s.building_wait", citystr, aitstr);
1140 /* avoid fc_rand and expensive recalculations on subsequent reload. */
1141 city_data->founder_turn
1142 = secfile_lookup_int_default(file, 0, "%s.%s.founder_turn", citystr,
1143 aitstr);
1144 city_data->founder_want
1145 = secfile_lookup_int_default(file, 0, "%s.%s.founder_want", citystr,
1146 aitstr);
1147 city_data->founder_boat
1148 = secfile_lookup_bool_default(file, (city_data->founder_want < 0),
1149 "%s.%s.founder_boat", citystr, aitstr);
1152 /**************************************************************************
1153 How undesirable for the owner of a particular city is the fact that it
1154 can be a target of a particular action?
1156 The negative utility (how undesirable it is) is given as a positive
1157 number. If it is desirable to be the target of an action make the
1158 negative utility a negative number since double negative is positive.
1160 Examples:
1161 * action_target_neg_util(Add to population) = -50
1162 * action_target_neg_util(Subtract from population) = 50
1163 **************************************************************************/
1164 static int action_target_neg_util(int action_id,
1165 const struct city *pcity)
1167 switch ((enum gen_action)action_id) {
1168 case ACTION_SPY_INCITE_CITY:
1169 case ACTION_SPY_INCITE_CITY_ESC:
1170 /* Copied from the evaluation of the No_Incite effect */
1171 return MAX((game.server.diplchance * 2
1172 - game.server.incite_total_factor) / 2
1173 - game.server.incite_improvement_factor * 5
1174 - game.server.incite_unit_factor * 5, 0);
1176 /* Really bad for the city owner. */
1177 case ACTION_SPY_NUKE:
1178 case ACTION_SPY_NUKE_ESC:
1179 case ACTION_CONQUER_CITY:
1180 /* The ai will never destroy his own city to keep it out of enemy
1181 * hands. If it starts supporting it this value should change. */
1182 case ACTION_DESTROY_CITY:
1183 return 20;
1185 /* Bad for the city owner. */
1186 case ACTION_SPY_POISON:
1187 case ACTION_SPY_SABOTAGE_CITY:
1188 case ACTION_SPY_TARGETED_SABOTAGE_CITY:
1189 case ACTION_SPY_STEAL_GOLD:
1190 /* TODO: Individual and well balanced values */
1191 return 10;
1193 /* Good for an enemy */
1194 case ACTION_SPY_STEAL_TECH:
1195 case ACTION_SPY_TARGETED_STEAL_TECH:
1196 case ACTION_STEAL_MAPS:
1197 /* TODO: Individual and well balanced values */
1198 return 8;
1200 /* Could be worse */
1201 case ACTION_ESTABLISH_EMBASSY:
1202 case ACTION_ESTABLISH_EMBASSY_STAY:
1203 case ACTION_SPY_INVESTIGATE_CITY:
1204 case ACTION_INV_CITY_SPEND:
1205 case ACTION_MARKETPLACE:
1206 /* TODO: Individual and well balanced values */
1207 return 1;
1209 /* Good for the ciy owner in most cases. */
1210 case ACTION_TRADE_ROUTE:
1211 case ACTION_HELP_WONDER:
1212 case ACTION_JOIN_CITY:
1213 case ACTION_RECYCLE_UNIT:
1214 case ACTION_HOME_CITY:
1215 case ACTION_UPGRADE_UNIT:
1216 case ACTION_AIRLIFT:
1217 /* TODO: Individual and well balanced values */
1218 return -1;
1220 /* Shouldn't happen. */
1221 case ACTION_SPY_BRIBE_UNIT:
1222 case ACTION_SPY_SABOTAGE_UNIT:
1223 case ACTION_EXPEL_UNIT:
1224 case ACTION_DISBAND_UNIT:
1225 case ACTION_CAPTURE_UNITS:
1226 case ACTION_BOMBARD:
1227 case ACTION_FOUND_CITY:
1228 case ACTION_NUKE:
1229 case ACTION_PARADROP:
1230 case ACTION_ATTACK:
1231 case ACTION_HEAL_UNIT:
1232 case ACTION_COUNT:
1233 fc_assert_msg(action_id_get_target_kind(action_id) == ATK_CITY,
1234 "Action not aimed at cities");
1237 fc_assert_msg(action_id_exists(action_id),
1238 "Action %d don't exist.", action_id);
1240 /* Wrong action. Ignore it. */
1241 return 0;
1244 /**************************************************************************
1245 Increase the degree to which we want to meet a set of requirements,
1246 because they will enable construction of an improvement
1247 with desirable effects.
1249 v is the desire for the improvement.
1251 Returns whether all the requirements are met.
1252 **************************************************************************/
1253 static bool adjust_wants_for_reqs(struct ai_type *ait,
1254 struct player *pplayer,
1255 struct city *pcity,
1256 struct impr_type *pimprove,
1257 const adv_want v)
1259 bool all_met = TRUE;
1260 int n_needed_techs = 0;
1261 int n_needed_improvements = 0;
1262 struct tech_vector needed_techs;
1263 struct impr_vector needed_improvements;
1265 tech_vector_init(&needed_techs);
1266 impr_vector_init(&needed_improvements);
1268 requirement_vector_iterate(&pimprove->reqs, preq) {
1269 const bool active = is_req_active(pplayer, NULL, pcity, pimprove,
1270 pcity->tile, NULL, NULL, NULL, NULL,
1271 NULL,
1272 preq, RPT_POSSIBLE);
1274 if (VUT_ADVANCE == preq->source.kind && preq->present && !active) {
1275 /* Found a missing technology requirement for this improvement. */
1276 tech_vector_append(&needed_techs, preq->source.value.advance);
1277 } else if (VUT_IMPROVEMENT == preq->source.kind && preq->present && !active) {
1278 /* Found a missing improvement requirement for this improvement.
1279 * For example, in the default ruleset a city must have a Library
1280 * before it can have a University. */
1281 impr_vector_append(&needed_improvements, preq->source.value.building);
1283 all_met = all_met && active;
1284 } requirement_vector_iterate_end;
1286 /* If v is negative, the improvement is not worth building,
1287 * but there is no need to punish research of the technologies
1288 * that would make it available.
1290 n_needed_techs = tech_vector_size(&needed_techs);
1291 if (0 < v && 0 < n_needed_techs) {
1292 /* Tell AI module how much we want this improvement and what techs are
1293 * required to get it. */
1294 const adv_want dv = v / n_needed_techs;
1296 want_techs_for_improvement_effect(ait, pplayer, pcity, pimprove,
1297 &needed_techs, dv);
1300 /* If v is negative, the improvement is not worth building,
1301 * but there is no need to punish building the improvements
1302 * that would make it available.
1304 n_needed_improvements = impr_vector_size(&needed_improvements);
1305 if (0 < v && 0 < n_needed_improvements) {
1306 /* Because we want this improvement,
1307 * we want the improvements that will make it possible */
1308 const adv_want dv = v / (n_needed_improvements * 4); /* WAG */
1309 int i;
1311 for (i = 0; i < n_needed_improvements; i++) {
1312 struct impr_type *needed_impr = *impr_vector_get(&needed_improvements, i);
1313 /* TODO: increase the want for the needed_impr,
1314 * if we can build it now */
1315 /* Recurse */
1316 (void) adjust_wants_for_reqs(ait, pplayer, pcity, needed_impr, dv);
1320 /* TODO: use a similar method to increase wants for governments
1321 * that will make this improvement possible? */
1323 tech_vector_free(&needed_techs);
1324 impr_vector_free(&needed_improvements);
1326 return all_met;
1329 /**************************************************************************
1330 Calculates city want from some input values. Set pimprove to NULL when
1331 nothing in the city has changed, and you just want to know the
1332 base want of a city.
1333 **************************************************************************/
1334 adv_want dai_city_want(struct player *pplayer, struct city *acity,
1335 struct adv_data *adv, struct impr_type *pimprove)
1337 adv_want want = 0;
1338 int prod[O_LAST], bonus[O_LAST], waste[O_LAST];
1340 memset(prod, 0, O_LAST * sizeof(*prod));
1341 if (NULL != pimprove
1342 && adv->impr_calc[improvement_index(pimprove)] == ADV_IMPR_CALCULATE_FULL) {
1343 struct tile *acenter = city_tile(acity);
1344 bool celebrating = base_city_celebrating(acity);
1346 /* The below calculation mostly duplicates get_worked_tile_output().
1347 * We do this only for buildings that we know may change tile
1348 * outputs. */
1349 city_tile_iterate(city_map_radius_sq_get(acity), acenter, ptile) {
1350 if (tile_worked(ptile) == acity) {
1351 output_type_iterate(o) {
1352 prod[o] += city_tile_output(acity, ptile, celebrating, o);
1353 } output_type_iterate_end;
1355 } city_tile_iterate_end;
1357 add_specialist_output(acity, prod);
1358 } else {
1359 fc_assert(sizeof(*prod) == sizeof(*acity->citizen_base));
1360 memcpy(prod, acity->citizen_base, O_LAST * sizeof(*prod));
1363 trade_routes_iterate(acity, proute) {
1364 prod[O_TRADE] += proute->value;
1365 } trade_routes_iterate_end;
1366 prod[O_GOLD] += get_city_tithes_bonus(acity);
1367 output_type_iterate(o) {
1368 bonus[o] = get_final_city_output_bonus(acity, o);
1369 waste[o] = city_waste(acity, o, prod[o] * bonus[o] / 100, NULL);
1370 } output_type_iterate_end;
1371 add_tax_income(pplayer,
1372 prod[O_TRADE] * bonus[O_TRADE] / 100 - waste[O_TRADE],
1373 prod);
1374 output_type_iterate(o) {
1375 prod[o] = prod[o] * bonus[o] / 100 - waste[o];
1376 } output_type_iterate_end;
1378 city_built_iterate(acity, upkept) {
1379 prod[O_GOLD] -= city_improvement_upkeep(acity, upkept);
1380 } city_built_iterate_end;
1381 /* Unit upkeep isn't handled here. Unless we do a full city_refresh it
1382 * won't be changed anyway. */
1384 want += prod[O_FOOD] * adv->food_priority;
1385 if (prod[O_SHIELD] != 0) {
1386 want += prod[O_SHIELD] * adv->shield_priority;
1387 want -= city_pollution(acity, prod[O_SHIELD]) * adv->pollution_priority;
1389 want += prod[O_LUXURY] * adv->luxury_priority;
1390 want += prod[O_SCIENCE] * adv->science_priority;
1391 want += prod[O_GOLD] * adv->gold_priority;
1393 return want;
1396 /**************************************************************************
1397 Calculates want for some buildings by actually adding the building and
1398 measuring the effect.
1399 **************************************************************************/
1400 static adv_want base_want(struct ai_type *ait, struct player *pplayer,
1401 struct city *pcity, struct impr_type *pimprove)
1403 struct adv_data *adv = adv_data_get(pplayer, NULL);
1404 adv_want final_want = 0;
1405 int wonder_player_id = WONDER_NOT_OWNED;
1406 int wonder_city_id = WONDER_NOT_BUILT;
1408 if (adv->impr_calc[improvement_index(pimprove)] == ADV_IMPR_ESTIMATE) {
1409 return 0; /* Nothing to calculate here. */
1412 if (!can_city_build_improvement_now(pcity, pimprove)
1413 || (is_small_wonder(pimprove)
1414 && NULL != city_from_small_wonder(pplayer, pimprove))) {
1415 return 0;
1418 if (is_wonder(pimprove)) {
1419 if (is_great_wonder(pimprove)) {
1420 wonder_player_id =
1421 game.info.great_wonder_owners[improvement_index(pimprove)];
1423 wonder_city_id = pplayer->wonders[improvement_index(pimprove)];
1425 /* Add the improvement */
1426 city_add_improvement(pcity, pimprove);
1428 /* Stir, then compare notes */
1429 city_range_iterate(pcity, pplayer->cities,
1430 adv->impr_range[improvement_index(pimprove)], acity) {
1431 final_want += dai_city_want(pplayer, acity, adv, pimprove)
1432 - def_ai_city_data(acity, ait)->worth;
1433 } city_range_iterate_end;
1435 /* Restore */
1436 city_remove_improvement(pcity, pimprove);
1437 if (is_wonder(pimprove)) {
1438 if (is_great_wonder(pimprove)) {
1439 game.info.great_wonder_owners[improvement_index(pimprove)] =
1440 wonder_player_id;
1443 pplayer->wonders[improvement_index(pimprove)] = wonder_city_id;
1446 return final_want;
1449 /**************************************************************************
1450 Calculate effects of possible improvements and extra effects of existing
1451 improvements. Consequently adjust the desirability of those improvements
1452 or the technologies that would make them possible.
1454 This function may (indeed, should) be called even for improvements that a city
1455 already has, or can not (yet) build. For existing improvements,
1456 it will discourage research of technologies that would make the improvement
1457 obsolete or reduce its effectiveness, and encourages technologies that would
1458 improve its effectiveness. For improvements that the city can not yet build
1459 it will encourage research of the techs and building of the improvements
1460 that will make the improvement possible.
1462 A complexity is that there are two sets of requirements to consider:
1463 the requirements for the building itself, and the requirements for
1464 the effects for the building.
1466 A few base variables:
1467 c - number of cities we have in current range
1468 u - units we have of currently affected type
1469 v - the want for the improvement we are considering
1471 This function contains a whole lot of WAGs. We ignore cond_* for now,
1472 thinking that one day we may fulfil the cond_s anyway. In general, we
1473 first add bonus for city improvements, then for wonders.
1475 IDEA: Calculate per-continent aggregates of various data, and use this
1476 for wonders below for better wonder placements.
1477 **************************************************************************/
1478 static void adjust_improvement_wants_by_effects(struct ai_type *ait,
1479 struct player *pplayer,
1480 struct city *pcity,
1481 struct impr_type *pimprove,
1482 const bool already)
1484 adv_want v = 0;
1485 int cities[REQ_RANGE_COUNT];
1486 int nplayers = normal_player_count();
1487 struct adv_data *ai = adv_data_get(pplayer, NULL);
1488 bool capital = is_capital(pcity);
1489 bool can_build = TRUE;
1490 struct government *gov = government_of_player(pplayer);
1491 struct universal source = {
1492 .kind = VUT_IMPROVEMENT,
1493 .value = {.building = pimprove}
1495 const bool is_coinage = improvement_has_flag(pimprove, IF_GOLD);
1496 int turns = 9999;
1497 int place = tile_continent(pcity->tile);
1499 /* Remove team members from the equation */
1500 players_iterate(aplayer) {
1501 if (aplayer->team
1502 && aplayer->team == pplayer->team
1503 && aplayer != pplayer) {
1504 nplayers--;
1506 } players_iterate_end;
1508 if (is_coinage) {
1509 /* Since coinage contains some entirely spurious ruleset values,
1510 * we need to hard-code a sensible want.
1511 * We must otherwise handle the special IF_GOLD improvement
1512 * like the others, so the AI will research techs that make it available,
1513 * for rulesets that do not provide it from the start.
1515 v += TRADE_WEIGHTING / 10;
1516 } else {
1517 /* Base want is calculated above using a more direct approach. */
1518 v += base_want(ait, pplayer, pcity, pimprove);
1519 if (v != 0) {
1520 CITY_LOG(LOG_DEBUG, pcity, "%s base_want is " ADV_WANT_PRINTF " (range=%d)",
1521 improvement_rule_name(pimprove),
1523 ai->impr_range[improvement_index(pimprove)]);
1527 if (!is_coinage) {
1528 /* Adjust by building cost */
1529 /* FIXME: ought to reduce by upkeep cost and amortise by building cost */
1530 v -= (impr_build_shield_cost(pimprove)
1531 / (pcity->surplus[O_SHIELD] * 10 + 1));
1534 /* Find number of cities per range. */
1535 cities[REQ_RANGE_PLAYER] = city_list_size(pplayer->cities);
1536 /* kludge -- Number of *our* cities in these ranges. */
1537 cities[REQ_RANGE_WORLD] = cities[REQ_RANGE_ALLIANCE] = cities[REQ_RANGE_TEAM]
1538 = cities[REQ_RANGE_PLAYER];
1540 if (place < 0) {
1541 cities[REQ_RANGE_CONTINENT] = 1;
1542 } else {
1543 cities[REQ_RANGE_CONTINENT] = ai->stats.cities[place];
1546 /* All the trade partners and the city being considered. */
1547 cities[REQ_RANGE_TRADEROUTE] = city_num_trade_routes(pcity)+1;
1549 cities[REQ_RANGE_CITY] = cities[REQ_RANGE_LOCAL] = 1;
1551 /* Invalid building range */
1552 cities[REQ_RANGE_ADJACENT] = cities[REQ_RANGE_CADJACENT] = 0;
1554 players_iterate(aplayer) {
1555 int potential = (aplayer->server.bulbs_last_turn
1556 + city_list_size(aplayer->cities) + 1);
1558 if (potential > 0) {
1559 requirement_vector_iterate(&pimprove->obsolete_by, pobs) {
1560 if (pobs->source.kind == VUT_ADVANCE && pobs->present) {
1561 turns = MIN(turns,
1562 research_goal_bulbs_required(research_get(aplayer),
1563 advance_number(pobs->source.value.advance))
1564 / (potential + 1));
1566 } requirement_vector_iterate_end;
1568 } players_iterate_end;
1570 effect_list_iterate(get_req_source_effects(&source), peffect) {
1571 struct requirement *mypreq = NULL;
1572 bool active = TRUE;
1573 int n_needed_techs = 0;
1574 struct tech_vector needed_techs;
1575 bool present = TRUE;
1576 bool impossible_to_get = FALSE;
1578 tech_vector_init(&needed_techs);
1580 requirement_vector_iterate(&peffect->reqs, preq) {
1581 /* Check if all the requirements for the currently evaluated effect
1582 * are met, except for having the building that we are evaluating. */
1583 if (VUT_IMPROVEMENT == preq->source.kind
1584 && preq->source.value.building == pimprove) {
1585 mypreq = preq;
1586 present = preq->present;
1587 continue;
1589 if (!is_req_active(pplayer, NULL, pcity, pimprove, NULL, NULL, NULL,
1590 NULL, NULL, NULL, preq, RPT_POSSIBLE)) {
1591 active = FALSE;
1592 if (VUT_ADVANCE == preq->source.kind && preq->present) {
1593 /* This missing requirement is a missing tech requirement.
1594 * This will be for some additional effect
1595 * (For example, in the default ruleset, Mysticism increases
1596 * the effect of Temples). */
1597 tech_vector_append(&needed_techs, preq->source.value.advance);
1598 } else if (!dai_can_requirement_be_met_in_city(preq, pplayer, pcity)) {
1599 impossible_to_get = TRUE;
1602 } requirement_vector_iterate_end;
1604 n_needed_techs = tech_vector_size(&needed_techs);
1605 if ((active || n_needed_techs) && !impossible_to_get) {
1606 adv_want v1 = dai_effect_value(pplayer, gov, ai, pcity, capital,
1607 turns, peffect, cities[mypreq->range],
1608 nplayers);
1609 /* v1 could be negative (the effect could be undesirable),
1610 * although it is usually positive.
1611 * For example, in the default ruleset, Communism decreases the
1612 * effectiveness of a Cathedral. */
1614 if (!present) {
1615 /* Building removes the effect */
1616 /* Currently v1 is (v + delta). Make it (v - delta) instead */
1617 v1 = -v1;
1620 if (active) {
1621 v += v1;
1622 } else if (v1 > 0) {
1623 /* If value of the effect is negative, do not hold it against
1624 * the tech - having the tech wont force one to build the
1625 * building. */
1627 /* We might want the technology that will enable this
1628 * (additional) effect.
1629 * The better the effect, the more we want the technology.
1630 * We are more interested in (additional) effects that enhance
1631 * buildings we already have.
1633 const int a = already? 5: 4; /* WAG */
1634 const adv_want dv = v1 * a / (4 * n_needed_techs);
1636 want_techs_for_improvement_effect(ait, pplayer, pcity, pimprove,
1637 &needed_techs, dv);
1641 tech_vector_free(&needed_techs);
1642 } effect_list_iterate_end;
1644 /* Can the city be the target of an action? */
1645 action_iterate (action_id) {
1646 bool is_possible;
1647 bool will_be_possible = FALSE;
1648 enum req_range max_range;
1649 int act_neg_util;
1651 /* Is the action relevant? */
1652 if (action_id_get_target_kind(action_id) != ATK_CITY) {
1653 continue;
1656 /* No range found yet. Local is the most narrow range. */
1657 max_range = REQ_RANGE_LOCAL;
1659 /* Is is possible to do the action to the city right now?
1661 * (DiplRel requirements are ignored since actor_player is NULL) */
1662 is_possible = is_action_possible_on_city(action_id, NULL, pcity);
1664 /* Will it be possible to do the action to the city if the building is
1665 * built? */
1666 action_enabler_list_iterate(action_enablers_for_action(action_id),
1667 enabler) {
1668 bool active = TRUE;
1669 enum req_range range = REQ_RANGE_LOCAL;
1671 requirement_vector_iterate(&(enabler->target_reqs), preq) {
1672 if (VUT_IMPROVEMENT == preq->source.kind
1673 && preq->source.value.building == pimprove) {
1674 /* Pretend the building is there */
1675 if (preq->present) {
1676 range = preq->range; /* Assumption: Max one pr vector */
1677 continue;
1678 } else {
1679 active = FALSE;
1680 break;
1684 if (!is_req_active(pplayer, NULL, pcity, pimprove,
1685 city_tile(pcity), NULL, NULL, NULL, NULL,
1686 NULL,
1687 preq, RPT_POSSIBLE)) {
1688 active = FALSE;
1689 break;
1691 } requirement_vector_iterate_end;
1693 if (active) {
1694 will_be_possible = TRUE;
1696 /* Store the widest range that enables the action. */
1697 if (max_range < range) {
1698 max_range = range;
1701 /* Don't break the iteration even if the action is enabled. There
1702 * could be a wider range in an active action enabler not yet seen.
1705 } action_enabler_list_iterate_end;
1707 /* Will the building significantly change the ability to target
1708 * the city? */
1709 if (is_possible == will_be_possible) {
1710 continue;
1713 /* How undersireable is it that the city may be a target? */
1714 act_neg_util = action_target_neg_util(action_id, pcity);
1716 /* Multiply the desire by number of cities in range.
1717 * Note: This is a simplification. If the action can be done or not
1718 * _may_ be uncanged or changed in the opposite direction in the other
1719 * cities in the range. */
1720 act_neg_util = cities[max_range] * act_neg_util;
1722 /* Consider the utility of being a potential target.
1723 * Remember: act_util is the negative utility of being a target. */
1724 if (will_be_possible) {
1725 v -= act_neg_util;
1726 } else {
1727 v += act_neg_util;
1729 } action_iterate_end;
1731 if (already) {
1732 /* Discourage research of the technology that would make this building
1733 * obsolete. The bigger the desire for this building, the more
1734 * we want to discourage the technology. */
1735 dont_want_tech_obsoleting_impr(ait, pplayer, pcity, pimprove, v);
1736 } else {
1737 /* Increase the want for technologies that will enable
1738 * construction of this improvement, if necessary.
1740 const bool all_met = adjust_wants_for_reqs(ait, pplayer, pcity, pimprove, v);
1741 can_build = can_build && all_met;
1744 if (is_coinage && can_build) {
1745 /* Could have a negative want for coinage,
1746 * if we have some stock in a building already. */
1747 pcity->server.adv->building_want[improvement_index(pimprove)] += v;
1748 } else if (!already && can_build) {
1749 const struct research *presearch = research_get(pplayer);
1751 /* Convert the base 'want' into a building want
1752 * by applying various adjustments */
1754 /* Would it mean losing shields? */
1755 if ((VUT_UTYPE == pcity->production.kind
1756 || (is_wonder(pcity->production.value.building)
1757 && !is_wonder(pimprove))
1758 || (!is_wonder(pcity->production.value.building)
1759 && is_wonder(pimprove)))
1760 && pcity->turn_last_built != game.info.turn) {
1761 if (has_handicap(pplayer, H_PRODCHGPEN)) {
1762 v -= pcity->shield_stock * SHIELD_WEIGHTING / 4;
1763 } else {
1764 v -= pcity->shield_stock * SHIELD_WEIGHTING / 15;
1768 /* Reduce want if building gets obsoleted soon */
1769 requirement_vector_iterate(&pimprove->obsolete_by, pobs) {
1770 if (pobs->source.kind == VUT_ADVANCE && pobs->present) {
1771 v -= v / MAX(1, research_goal_unknown_techs(presearch,
1772 advance_number(pobs->source.value.advance)));
1774 } requirement_vector_iterate_end;
1776 /* Are we wonder city? Try to avoid building non-wonders very much. */
1777 if (pcity->id == ai->wonder_city && !is_wonder(pimprove)) {
1778 v /= 5;
1781 /* Set */
1782 pcity->server.adv->building_want[improvement_index(pimprove)] += v;
1784 /* Else we either have the improvement already,
1785 * or we can not build it (yet) */
1788 /**************************************************************************
1789 Whether the AI should calculate the building wants for this city
1790 this turn, ahead of schedule.
1792 Always recalculate if the city just finished building,
1793 so we can make a sensible choice for the next thing to build.
1794 Perhaps the improvement we were building has become obsolete,
1795 or a different player built the Great Wonder we were building.
1796 **************************************************************************/
1797 static bool should_force_recalc(struct city *pcity)
1799 return city_built_last_turn(pcity)
1800 || (VUT_IMPROVEMENT == pcity->production.kind
1801 && !improvement_has_flag(pcity->production.value.building, IF_GOLD)
1802 && !can_city_build_improvement_later(pcity, pcity->production.value.building));
1805 /**************************************************************************
1806 Initialize building advisor. Calculates data of all players, not
1807 only of those controlled by current ai type.
1808 **************************************************************************/
1809 void dai_build_adv_init(struct ai_type *ait, struct player *pplayer)
1811 struct adv_data *ai = adv_data_get(pplayer, NULL);
1813 /* Find current worth of cities and cache this. */
1814 city_list_iterate(pplayer->cities, pcity) {
1815 def_ai_city_data(pcity, ait)->worth = dai_city_want(pplayer, pcity, ai, NULL);
1816 } city_list_iterate_end;
1819 /**************************************************************************
1820 Calculate how much an AI player should want to build particular
1821 improvements, because of the effects of those improvements, and
1822 increase the want for technologies that will enable buildings with
1823 desirable effects.
1824 **************************************************************************/
1825 void dai_build_adv_adjust(struct ai_type *ait, struct player *pplayer,
1826 struct city *wonder_city)
1828 /* Clear old building wants.
1829 * Do this separately from the iteration over improvement types
1830 * because each iteration could actually update more than one improvement,
1831 * if improvements have improvements as requirements.
1833 city_list_iterate(pplayer->cities, pcity) {
1834 struct ai_city *city_data = def_ai_city_data(pcity, ait);
1836 if (city_data->building_turn <= game.info.turn) {
1837 /* Do a scheduled recalculation this turn */
1838 improvement_iterate(pimprove) {
1839 pcity->server.adv->building_want[improvement_index(pimprove)] = 0;
1840 } improvement_iterate_end;
1841 } else if (should_force_recalc(pcity)) {
1842 /* Do an emergency recalculation this turn. */
1843 city_data->building_wait = city_data->building_turn
1844 - game.info.turn;
1845 city_data->building_turn = game.info.turn;
1847 improvement_iterate(pimprove) {
1848 pcity->server.adv->building_want[improvement_index(pimprove)] = 0;
1849 } improvement_iterate_end;
1851 } city_list_iterate_end;
1853 improvement_iterate(pimprove) {
1854 const bool is_coinage = improvement_has_flag(pimprove, IF_GOLD);
1856 /* Handle coinage specially because you can never complete coinage */
1857 if (is_coinage
1858 || can_player_build_improvement_later(pplayer, pimprove)) {
1859 city_list_iterate(pplayer->cities, pcity) {
1860 struct ai_city *city_data = def_ai_city_data(pcity, ait);
1862 if (pcity != wonder_city && is_wonder(pimprove)) {
1863 /* Only wonder city should build wonders! */
1864 pcity->server.adv->building_want[improvement_index(pimprove)] = 0;
1865 } else if (city_data->building_turn <= game.info.turn) {
1866 /* Building wants vary relatively slowly, so not worthwhile
1867 * recalculating them every turn.
1868 * We DO want to calculate (tech) wants because of buildings
1869 * we already have. */
1870 const bool already = city_has_building(pcity, pimprove);
1871 int idx = improvement_index(pimprove);
1873 adjust_improvement_wants_by_effects(ait, pplayer, pcity,
1874 pimprove, already);
1876 fc_assert(!(already
1877 && 0 < pcity->server.adv->building_want[idx]));
1879 if (is_great_wonder(pimprove)) {
1880 /* Not only would we get the wonder, but we would also prevent
1881 * opponents from getting it. */
1882 pcity->server.adv->building_want[idx] *= 1.5;
1884 if (pcity->production.kind == VUT_IMPROVEMENT
1885 && is_great_wonder(pcity->production.value.building)) {
1886 /* If we already are building a great wonder, prefer continuing
1887 * to do so over stopping it */
1888 pcity->server.adv->building_want[idx] *= 1.25;
1892 /* If I am not an expansionist, I want buildings more than units */
1893 if (pcity->server.adv->building_want[idx] > 0) {
1894 pcity->server.adv->building_want[idx]
1895 = pcity->server.adv->building_want[idx]
1896 * TRAIT_DEFAULT_VALUE
1897 / ai_trait_get_value(TRAIT_EXPANSIONIST, pplayer);
1900 /* else wait until a later turn */
1901 } city_list_iterate_end;
1902 } else {
1903 /* An impossible improvement */
1904 city_list_iterate(pplayer->cities, pcity) {
1905 pcity->server.adv->building_want[improvement_index(pimprove)] = 0;
1906 } city_list_iterate_end;
1908 } improvement_iterate_end;
1910 #ifdef FREECIV_DEBUG
1911 /* This logging is relatively expensive, so activate only if necessary */
1912 city_list_iterate(pplayer->cities, pcity) {
1913 improvement_iterate(pimprove) {
1914 if (pcity->server.adv->building_want[improvement_index(pimprove)] != 0) {
1915 CITY_LOG(LOG_DEBUG, pcity, "want to build %s with " ADV_WANT_PRINTF,
1916 improvement_rule_name(pimprove),
1917 pcity->server.adv->building_want[improvement_index(pimprove)]);
1919 } improvement_iterate_end;
1920 } city_list_iterate_end;
1921 #endif /* FREECIV_DEBUG */
1923 /* Reset recalc counter */
1924 city_list_iterate(pplayer->cities, pcity) {
1925 struct ai_city *city_data = def_ai_city_data(pcity, ait);
1927 if (city_data->building_turn <= game.info.turn) {
1928 /* This will spread recalcs out so that no one turn end is
1929 * much longer than others */
1930 city_data->building_wait = fc_rand(AI_BA_RECALC_SPEED) + AI_BA_RECALC_SPEED;
1931 city_data->building_turn = game.info.turn
1932 + city_data->building_wait;
1934 } city_list_iterate_end;
1937 /**************************************************************************
1938 Is it ok for advisor code to consider given city as wonder city?
1939 **************************************************************************/
1940 void dai_consider_wonder_city(struct ai_type *ait, struct city *pcity, bool *result)
1942 if (def_ai_city_data(pcity, ait)->grave_danger > 0) {
1943 *result = FALSE;
1944 } else {
1945 *result = TRUE;
1949 /**************************************************************************
1950 Returns a buildable, non-obsolete building that can provide the effect.
1952 Note: this function is an inefficient hack to be used by the old AI. It
1953 will never find wonders, since that's not what the AI wants.
1954 **************************************************************************/
1955 Impr_type_id dai_find_source_building(struct city *pcity,
1956 enum effect_type effect_type,
1957 struct unit_type *utype)
1959 int greatest_value = 0;
1960 struct impr_type *best_building = NULL;
1962 effect_list_iterate(get_effects(effect_type), peffect) {
1963 if (peffect->value > greatest_value) {
1964 struct impr_type *building = NULL;
1965 bool wrong_unit = FALSE;
1967 requirement_vector_iterate(&peffect->reqs, preq) {
1968 if (VUT_IMPROVEMENT == preq->source.kind && preq->present) {
1969 building = preq->source.value.building;
1971 if (!can_city_build_improvement_now(pcity, building)
1972 || !is_improvement(building)) {
1973 building = NULL;
1974 break;
1976 } else if (utype != NULL
1977 && !is_req_active(city_owner(pcity), NULL, pcity, NULL, city_tile(pcity),
1978 NULL, utype, NULL, NULL, NULL, preq, RPT_POSSIBLE)) {
1979 /* Effect requires other kind of unit than what we are interested about */
1980 wrong_unit = TRUE;
1981 break;
1983 } requirement_vector_iterate_end;
1984 if (!wrong_unit && building != NULL) {
1985 best_building = building;
1986 greatest_value = peffect->value;
1989 } effect_list_iterate_end;
1991 if (best_building) {
1992 return improvement_number(best_building);
1994 return B_LAST;