Use linear-gradient instead of gtk css extension in gtk3.22-client theme
[freeciv.git] / common / unit.c
blob78d3230f02c1008bd4b3ba2482700655c4944461
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 /* utility */
19 #include "astring.h"
20 #include "bitvector.h"
21 #include "fcintl.h"
22 #include "mem.h"
23 #include "shared.h"
24 #include "support.h"
26 /* common */
27 #include "ai.h"
28 #include "actions.h"
29 #include "base.h"
30 #include "city.h"
31 #include "game.h"
32 #include "log.h"
33 #include "map.h"
34 #include "movement.h"
35 #include "packets.h"
36 #include "player.h"
37 #include "road.h"
38 #include "tech.h"
39 #include "traderoutes.h"
40 #include "unitlist.h"
42 #include "unit.h"
44 static bool is_real_activity(enum unit_activity activity);
46 Activity_type_id real_activities[ACTIVITY_LAST];
48 struct cargo_iter {
49 struct iterator vtable;
50 const struct unit_list_link *links[GAME_TRANSPORT_MAX_RECURSIVE];
51 int depth;
53 #define CARGO_ITER(iter) ((struct cargo_iter *) (iter))
55 /****************************************************************************
56 Determines if punit can be airlifted to dest_city now! So punit needs
57 to be in a city now.
58 If pdest_city is NULL, just indicate whether it's possible for the unit
59 to be airlifted at all from its current position.
60 The 'restriction' parameter specifies which player's knowledge this is
61 based on -- one player can't see whether another's cities are currently
62 able to airlift. (Clients other than global observers should only call
63 this with a non-NULL 'restriction'.)
64 ****************************************************************************/
65 enum unit_airlift_result
66 test_unit_can_airlift_to(const struct player *restriction,
67 const struct unit *punit,
68 const struct city *pdest_city)
70 const struct city *psrc_city = tile_city(unit_tile(punit));
71 const struct player *punit_owner;
72 enum unit_airlift_result ok_result = AR_OK;
74 if (0 == punit->moves_left) {
75 /* No moves left. */
76 return AR_NO_MOVES;
79 if (!uclass_has_flag(unit_class_get(punit), UCF_AIRLIFTABLE)) {
80 return AR_WRONG_UNITTYPE;
83 if (0 < get_transporter_occupancy(punit)) {
84 /* Units with occupants can't be airlifted currently. */
85 return AR_OCCUPIED;
88 if (NULL == psrc_city) {
89 /* No city there. */
90 return AR_NOT_IN_CITY;
93 if (psrc_city == pdest_city) {
94 /* Airlifting to our current position doesn't make sense. */
95 return AR_BAD_DST_CITY;
98 if (pdest_city
99 && (NULL == restriction
100 || (tile_get_known(city_tile(pdest_city), restriction)
101 == TILE_KNOWN_SEEN))
102 && !can_unit_exist_at_tile(punit, city_tile(pdest_city))) {
103 /* Can't exist at the destination tile. */
104 return AR_BAD_DST_CITY;
107 punit_owner = unit_owner(punit);
109 /* Check validity of both source and destination before checking capacity,
110 * to avoid misleadingly optimistic returns. */
112 if (punit_owner != city_owner(psrc_city)
113 && !(game.info.airlifting_style & AIRLIFTING_ALLIED_SRC
114 && pplayers_allied(punit_owner, city_owner(psrc_city)))) {
115 /* Not allowed to airlift from this source. */
116 return AR_BAD_SRC_CITY;
119 if (pdest_city &&
120 punit_owner != city_owner(pdest_city)
121 && !(game.info.airlifting_style & AIRLIFTING_ALLIED_DEST
122 && pplayers_allied(punit_owner, city_owner(pdest_city)))) {
123 /* Not allowed to airlift to this destination. */
124 return AR_BAD_DST_CITY;
127 if (NULL == restriction || city_owner(psrc_city) == restriction) {
128 /* We know for sure whether or not src can airlift this turn. */
129 if (0 >= psrc_city->airlift) {
130 /* The source cannot airlift for this turn (maybe already airlifted
131 * or no airport).
133 * Note that (game.info.airlifting_style & AIRLIFTING_UNLIMITED_SRC)
134 * is not handled here because it always needs an airport to airlift.
135 * See also do_airline() in server/unittools.h. */
136 return AR_SRC_NO_FLIGHTS;
137 } /* else, there is capacity; continue to other checks */
138 } else {
139 /* We don't have access to the 'airlift' field. Assume it's OK; can
140 * only find out for sure by trying it. */
141 ok_result = AR_OK_SRC_UNKNOWN;
144 if (pdest_city) {
145 if (NULL == restriction || city_owner(pdest_city) == restriction) {
146 if (0 >= pdest_city->airlift
147 && !(game.info.airlifting_style & AIRLIFTING_UNLIMITED_DEST)) {
148 /* The destination cannot support airlifted units for this turn
149 * (maybe already airlifed or no airport).
150 * See also do_airline() in server/unittools.h. */
151 return AR_DST_NO_FLIGHTS;
152 } /* else continue */
153 } else {
154 ok_result = AR_OK_DST_UNKNOWN;
158 return ok_result;
161 /****************************************************************************
162 Encapsulates whether a return from test_unit_can_airlift_to() should be
163 treated as a successful result.
164 ****************************************************************************/
165 bool is_successful_airlift_result(enum unit_airlift_result result)
167 switch (result) {
168 case AR_OK:
169 case AR_OK_SRC_UNKNOWN:
170 case AR_OK_DST_UNKNOWN:
171 return TRUE;
172 default: /* everything else is failure */
173 return FALSE;
177 /****************************************************************************
178 Determines if punit can be airlifted to dest_city now! So punit needs
179 to be in a city now.
180 On the server this gives correct information; on the client it errs on the
181 side of saying airlifting is possible even if it's not certain given
182 player knowledge.
183 ****************************************************************************/
184 bool unit_can_airlift_to(const struct unit *punit,
185 const struct city *pdest_city)
187 /* FIXME: really we want client_player(), not unit_owner(). */
188 struct player *restriction = is_server() ? NULL : unit_owner(punit);
189 fc_assert_ret_val(pdest_city, FALSE);
190 return is_successful_airlift_result(
191 test_unit_can_airlift_to(restriction, punit, pdest_city));
194 /****************************************************************************
195 Return TRUE iff the unit is following client-side orders.
196 ****************************************************************************/
197 bool unit_has_orders(const struct unit *punit)
199 return punit->has_orders;
202 /**************************************************************************
203 Return TRUE unless it is known to be imposible to disband this unit at
204 its current position to get full shields for building a wonder.
205 **************************************************************************/
206 bool unit_can_help_build_wonder_here(const struct unit *punit)
208 struct city *pcity = tile_city(unit_tile(punit));
210 if (!pcity) {
211 /* No city to help at this tile. */
212 return FALSE;
215 if (!utype_can_do_action(unit_type_get(punit), ACTION_HELP_WONDER)) {
216 /* This unit can never do help wonder. */
217 return FALSE;
220 /* Evaluate all action enablers for extra accuracy. */
221 /* TODO: Is it worth it? */
222 return action_prob_possible(action_prob_vs_city(punit,
223 ACTION_HELP_WONDER,
224 pcity));
227 /**************************************************************************
228 Return TRUE iff this unit can be disbanded at its current location to
229 provide a trade route from the homecity to the target city.
230 **************************************************************************/
231 bool unit_can_est_trade_route_here(const struct unit *punit)
233 struct city *phomecity, *pdestcity;
235 return (utype_can_do_action(unit_type_get(punit), ACTION_TRADE_ROUTE)
236 && (pdestcity = tile_city(unit_tile(punit)))
237 && (phomecity = game_city_by_number(punit->homecity))
238 && can_cities_trade(phomecity, pdestcity));
241 /**************************************************************************
242 Return the number of units the transporter can hold (or 0).
243 **************************************************************************/
244 int get_transporter_capacity(const struct unit *punit)
246 return unit_type_get(punit)->transport_capacity;
249 /**************************************************************************
250 Is the unit capable of attacking?
251 **************************************************************************/
252 bool is_attack_unit(const struct unit *punit)
254 return (unit_type_get(punit)->attack_strength > 0);
257 /**************************************************************************
258 Military units are capable of enforcing martial law. Military ground
259 and heli units can occupy empty cities -- see unit_can_take_over(punit).
260 Some military units, like the Galleon, have no attack strength.
261 **************************************************************************/
262 bool is_military_unit(const struct unit *punit)
264 return !unit_has_type_flag(punit, UTYF_CIVILIAN);
267 /**************************************************************************
268 Return TRUE iff this unit is a diplomat (spy) unit. Diplomatic units
269 can do diplomatic actions (not to be confused with diplomacy).
270 **************************************************************************/
271 bool is_diplomat_unit(const struct unit *punit)
273 return (unit_has_type_flag(punit, UTYF_DIPLOMAT));
276 /**************************************************************************
277 Return TRUE iff this unit can do the specified generalized (ruleset
278 defined) action enabler controlled action.
279 **************************************************************************/
280 bool unit_can_do_action(const struct unit *punit,
281 const int action_id)
283 return utype_can_do_action(unit_type_get(punit), action_id);
286 /**************************************************************************
287 Return TRUE iff this tile is threatened from any unit within 2 tiles.
288 **************************************************************************/
289 bool is_square_threatened(const struct player *pplayer,
290 const struct tile *ptile, bool omniscient)
292 square_iterate(ptile, 2, ptile1) {
293 unit_list_iterate(ptile1->units, punit) {
294 if ((omniscient
295 || can_player_see_unit(pplayer, punit))
296 && pplayers_at_war(pplayer, unit_owner(punit))
297 && (utype_acts_hostile(unit_type_get(punit))
298 || (is_military_unit(punit) && is_attack_unit(punit)))
299 && (is_native_tile(unit_type_get(punit), ptile)
300 || (can_attack_non_native(unit_type_get(punit))
301 && is_native_near_tile(unit_class_get(punit), ptile)))) {
302 return TRUE;
304 } unit_list_iterate_end;
305 } square_iterate_end;
307 return FALSE;
310 /**************************************************************************
311 This checks the "field unit" flag on the unit. Field units cause
312 unhappiness (under certain governments) even when they aren't abroad.
313 **************************************************************************/
314 bool is_field_unit(const struct unit *punit)
316 return unit_has_type_flag(punit, UTYF_FIELDUNIT);
320 /**************************************************************************
321 Is the unit one that is invisible on the map. A unit is invisible if
322 it has the UTYF_PARTIAL_INVIS flag or if it transported by a unit with
323 this flag.
324 **************************************************************************/
325 bool is_hiding_unit(const struct unit *punit)
327 return (unit_has_type_flag(punit, UTYF_PARTIAL_INVIS)
328 || (unit_transported(punit)
329 && unit_has_type_flag(unit_transport_get(punit),
330 UTYF_PARTIAL_INVIS)));
333 /**************************************************************************
334 Return TRUE iff an attack from this unit would kill a citizen in a city
335 (city walls protect against this).
336 **************************************************************************/
337 bool kills_citizen_after_attack(const struct unit *punit)
339 return game.info.killcitizen
340 && uclass_has_flag(unit_class_get(punit), UCF_KILLCITIZEN);
343 /****************************************************************************
344 Return TRUE iff this unit may be disbanded to add its pop_cost to a
345 city at its current location.
346 ****************************************************************************/
347 bool unit_can_add_to_city(const struct unit *punit)
349 return (UAB_ADD_OK == unit_add_or_build_city_test(punit));
352 /****************************************************************************
353 Return TRUE iff this unit is capable of building a new city at its
354 current location.
355 ****************************************************************************/
356 bool unit_can_build_city(const struct unit *punit)
358 return (UAB_BUILD_OK == unit_add_or_build_city_test(punit));
361 /****************************************************************************
362 Return TRUE iff this unit can add to a current city or build a new city
363 at its current location.
364 ****************************************************************************/
365 bool unit_can_add_or_build_city(const struct unit *punit)
367 enum unit_add_build_city_result res = unit_add_or_build_city_test(punit);
369 return (UAB_BUILD_OK == res || UAB_ADD_OK == res);
372 /****************************************************************************
373 See if the unit can add to an existing city or build a new city at
374 its current location, and return a 'result' value telling what is
375 allowed.
376 ****************************************************************************/
377 enum unit_add_build_city_result
378 unit_add_or_build_city_test(const struct unit *punit)
380 struct tile *ptile = unit_tile(punit);
381 struct city *pcity = tile_city(ptile);
382 bool is_build = unit_is_cityfounder(punit);
383 bool is_add = unit_has_type_flag(punit, UTYF_ADD_TO_CITY);
384 int new_pop;
386 /* Test if we can build. */
387 if (NULL == pcity) {
388 if (!is_build) {
389 return UAB_NOT_BUILD_UNIT;
391 if (punit->moves_left == 0) {
392 return UAB_NO_MOVES_BUILD;
394 switch (city_build_here_test(ptile, punit)) {
395 case CB_OK:
396 return UAB_BUILD_OK;
397 case CB_BAD_CITY_TERRAIN:
398 return UAB_BAD_CITY_TERRAIN;
399 case CB_BAD_UNIT_TERRAIN:
400 return UAB_BAD_UNIT_TERRAIN;
401 case CB_BAD_BORDERS:
402 return UAB_BAD_BORDERS;
403 case CB_NO_MIN_DIST:
404 return UAB_NO_MIN_DIST;
406 log_error("%s(): Internal error.", __FUNCTION__);
407 return UAB_NO_MOVES_BUILD; /* Returns something prohibitive. */
410 /* Test if we can add. */
411 if (!is_add) {
412 return UAB_NOT_ADDABLE_UNIT;
414 if (punit->moves_left == 0) {
415 return UAB_NO_MOVES_ADD;
418 fc_assert(unit_pop_value(punit) > 0);
419 new_pop = city_size_get(pcity) + unit_pop_value(punit);
421 if (new_pop > game.info.add_to_size_limit) {
422 return UAB_TOO_BIG;
424 if (city_owner(pcity) != unit_owner(punit)) {
425 return UAB_NOT_OWNER;
427 if (!city_can_grow_to(pcity, new_pop)) {
428 return UAB_NO_SPACE;
430 return UAB_ADD_OK;
433 /**************************************************************************
434 Return TRUE iff the unit can change homecity to the given city.
435 **************************************************************************/
436 bool can_unit_change_homecity_to(const struct unit *punit,
437 const struct city *pcity)
439 struct city *acity = tile_city(unit_tile(punit));
441 /* Requirements to change homecity:
443 * 1. Homeless units can't change homecity (this is a feature since
444 * being homeless is a big benefit).
445 * 2. The unit must be inside the city it is rehoming to.
446 * 3. Of course you can only have your own cities as homecity.
447 * 4. You can't rehome to the current homecity. */
448 return (punit && pcity
449 && punit->homecity > 0
450 && acity
451 && city_owner(acity) == unit_owner(punit)
452 && punit->homecity != acity->id);
455 /**************************************************************************
456 Return TRUE iff the unit can change homecity at its current location.
457 **************************************************************************/
458 bool can_unit_change_homecity(const struct unit *punit)
460 return can_unit_change_homecity_to(punit, tile_city(unit_tile(punit)));
463 /**************************************************************************
464 Returns the speed of a unit doing an activity. This depends on the
465 veteran level and the base move_rate of the unit (regardless of HP or
466 effects). Usually this is just used for settlers but the value is also
467 used for military units doing fortify/pillage activities.
469 The speed is multiplied by ACTIVITY_FACTOR.
470 **************************************************************************/
471 int get_activity_rate(const struct unit *punit)
473 const struct veteran_level *vlevel;
475 fc_assert_ret_val(punit != NULL, 0);
477 vlevel = utype_veteran_level(unit_type_get(punit), punit->veteran);
478 fc_assert_ret_val(vlevel != NULL, 0);
480 /* The speed of the settler depends on its base move_rate, not on
481 * the number of moves actually remaining or the adjusted move rate.
482 * This means sea formers won't have their activity rate increased by
483 * Magellan's, and it means injured units work just as fast as
484 * uninjured ones. Note the value is never less than SINGLE_MOVE. */
485 int move_rate = unit_type_get(punit)->move_rate;
487 /* All settler actions are multiplied by ACTIVITY_FACTOR. */
488 return ACTIVITY_FACTOR
489 * (float)vlevel->power_fact / 100
490 * move_rate / SINGLE_MOVE;
493 /**************************************************************************
494 Returns the amount of work a unit does (will do) on an activity this
495 turn. Units that have no MP do no work.
497 The speed is multiplied by ACTIVITY_FACTOR.
498 **************************************************************************/
499 int get_activity_rate_this_turn(const struct unit *punit)
501 /* This logic is also coded in client/goto.c. */
502 if (punit->moves_left > 0) {
503 return get_activity_rate(punit);
504 } else {
505 return 0;
509 /**************************************************************************
510 Return the estimated number of turns for the worker unit to start and
511 complete the activity at the given location. This assumes no other
512 worker units are helping out, and doesn't take account of any work
513 already done by this unit.
514 **************************************************************************/
515 int get_turns_for_activity_at(const struct unit *punit,
516 enum unit_activity activity,
517 const struct tile *ptile,
518 struct extra_type *tgt)
520 /* FIXME: This is just an approximation since we don't account for
521 * get_activity_rate_this_turn. */
522 int speed = get_activity_rate(punit);
523 int points_needed = tile_activity_time(activity, ptile, tgt);
525 if (points_needed >= 0 && speed >= 0) {
526 return (points_needed - 1) / speed + 1; /* round up */
527 } else {
528 return FC_INFINITY;
532 /**************************************************************************
533 Return TRUE if activity requires some sort of target to be specified.
534 **************************************************************************/
535 bool activity_requires_target(enum unit_activity activity)
537 switch (activity) {
538 case ACTIVITY_PILLAGE:
539 case ACTIVITY_BASE:
540 case ACTIVITY_GEN_ROAD:
541 case ACTIVITY_IRRIGATE:
542 case ACTIVITY_MINE:
543 case ACTIVITY_POLLUTION:
544 case ACTIVITY_FALLOUT:
545 return TRUE;
546 case ACTIVITY_IDLE:
547 case ACTIVITY_FORTIFIED:
548 case ACTIVITY_SENTRY:
549 case ACTIVITY_GOTO:
550 case ACTIVITY_EXPLORE:
551 case ACTIVITY_TRANSFORM:
552 case ACTIVITY_FORTIFYING:
553 case ACTIVITY_CONVERT:
554 return FALSE;
555 /* These shouldn't be kicking around internally. */
556 case ACTIVITY_FORTRESS:
557 case ACTIVITY_AIRBASE:
558 case ACTIVITY_PATROL_UNUSED:
559 default:
560 fc_assert_ret_val(FALSE, FALSE);
563 return FALSE;
566 /**************************************************************************
567 Return whether the unit can be put in auto-settler mode.
569 NOTE: we used to have "auto" mode including autosettlers and auto-attack.
570 This was bad because the two were indestinguishable even though they
571 are very different. Now auto-attack is done differently so we just have
572 auto-settlers. If any new auto modes are introduced they should be
573 handled separately.
574 **************************************************************************/
575 bool can_unit_do_autosettlers(const struct unit *punit)
577 return unit_has_type_flag(punit, UTYF_SETTLERS);
580 /**************************************************************************
581 Setup array of real activities
582 **************************************************************************/
583 void setup_real_activities_array(void)
585 Activity_type_id act;
586 int i = 0;
588 for (act = 0; act < ACTIVITY_LAST; act++) {
589 if (is_real_activity(act)) {
590 real_activities[i++] = act;
594 real_activities[i] = ACTIVITY_LAST;
597 /**************************************************************************
598 Return if given activity really is in game. For savegame compatibility
599 activity enum cannot be reordered and there is holes in it.
600 **************************************************************************/
601 static bool is_real_activity(enum unit_activity activity)
603 /* ACTIVITY_FORTRESS, ACTIVITY_AIRBASE, ACTIVITY_OLD_ROAD, and
604 * ACTIVITY_OLD_RAILROAD are deprecated */
605 return (0 <= activity && activity < ACTIVITY_LAST)
606 && activity != ACTIVITY_FORTRESS
607 && activity != ACTIVITY_AIRBASE
608 && activity != ACTIVITY_OLD_ROAD
609 && activity != ACTIVITY_OLD_RAILROAD
610 && activity != ACTIVITY_UNKNOWN
611 && activity != ACTIVITY_PATROL_UNUSED;
614 /**************************************************************************
615 Return the name of the activity in a static buffer.
616 **************************************************************************/
617 const char *get_activity_text(enum unit_activity activity)
619 /* The switch statement has just the activities listed with no "default"
620 * handling. This enables the compiler to detect missing entries
621 * automatically, and still handles everything correctly. */
622 switch (activity) {
623 case ACTIVITY_IDLE:
624 return _("Idle");
625 case ACTIVITY_POLLUTION:
626 return _("Pollution");
627 case ACTIVITY_MINE:
628 /* TRANS: Activity name, verb in English */
629 return _("Plant");
630 case ACTIVITY_IRRIGATE:
631 return _("Irrigate");
632 case ACTIVITY_FORTIFYING:
633 return _("Fortifying");
634 case ACTIVITY_FORTIFIED:
635 return _("Fortified");
636 case ACTIVITY_SENTRY:
637 return _("Sentry");
638 case ACTIVITY_PILLAGE:
639 return _("Pillage");
640 case ACTIVITY_GOTO:
641 return _("Goto");
642 case ACTIVITY_EXPLORE:
643 return _("Explore");
644 case ACTIVITY_TRANSFORM:
645 return _("Transform");
646 case ACTIVITY_FALLOUT:
647 return _("Fallout");
648 case ACTIVITY_BASE:
649 return _("Base");
650 case ACTIVITY_GEN_ROAD:
651 return _("Road");
652 case ACTIVITY_CONVERT:
653 return _("Convert");
654 case ACTIVITY_OLD_ROAD:
655 case ACTIVITY_OLD_RAILROAD:
656 case ACTIVITY_FORTRESS:
657 case ACTIVITY_AIRBASE:
658 case ACTIVITY_UNKNOWN:
659 case ACTIVITY_PATROL_UNUSED:
660 case ACTIVITY_LAST:
661 break;
664 fc_assert(FALSE);
665 return _("Unknown");
668 /****************************************************************************
669 Return TRUE iff the given unit could be loaded into the transporter
670 if we moved there.
671 ****************************************************************************/
672 bool could_unit_load(const struct unit *pcargo, const struct unit *ptrans)
674 if (!pcargo || !ptrans || pcargo == ptrans) {
675 return FALSE;
678 /* Double-check ownership of the units: you can load into an allied unit
679 * (of course only allied units can be on the same tile). */
680 if (!pplayers_allied(unit_owner(pcargo), unit_owner(ptrans))) {
681 return FALSE;
684 /* Make sure this transporter can carry this type of unit. */
685 if (!can_unit_transport(ptrans, pcargo)) {
686 return FALSE;
689 /* Un-embarkable transport must be in city or base to load cargo. */
690 if (!utype_can_freely_load(unit_type_get(pcargo), unit_type_get(ptrans))
691 && !tile_city(unit_tile(ptrans))
692 && !tile_has_native_base(unit_tile(ptrans), unit_type_get(ptrans))) {
693 return FALSE;
696 /* Make sure there's room in the transporter. */
697 if (get_transporter_occupancy(ptrans)
698 >= get_transporter_capacity(ptrans)) {
699 return FALSE;
702 /* Check iff this is a valid transport. */
703 if (!unit_transport_check(pcargo, ptrans)) {
704 return FALSE;
707 /* Check transport depth. */
708 if (GAME_TRANSPORT_MAX_RECURSIVE
709 < 1 + unit_transport_depth(ptrans) + unit_cargo_depth(pcargo)) {
710 return FALSE;
713 return TRUE;
716 /****************************************************************************
717 Return TRUE iff the given unit can be loaded into the transporter.
718 ****************************************************************************/
719 bool can_unit_load(const struct unit *pcargo, const struct unit *ptrans)
721 /* This function needs to check EVERYTHING. */
723 /* Check positions of the units. Of course you can't load a unit onto
724 * a transporter on a different tile... */
725 if (!same_pos(unit_tile(pcargo), unit_tile(ptrans))) {
726 return FALSE;
729 /* Cannot load if cargo is already loaded onto something else. */
730 if (unit_transported(pcargo)) {
731 return FALSE;
734 return could_unit_load(pcargo, ptrans);
737 /****************************************************************************
738 Return TRUE iff the given unit can be unloaded from its current
739 transporter.
741 This function checks everything *except* the legality of the position
742 after the unloading. The caller may also want to call
743 can_unit_exist_at_tile() to check this, unless the unit is unloading and
744 moving at the same time.
745 ****************************************************************************/
746 bool can_unit_unload(const struct unit *pcargo, const struct unit *ptrans)
748 if (!pcargo || !ptrans) {
749 return FALSE;
752 /* Make sure the unit's transporter exists and is known. */
753 if (unit_transport_get(pcargo) != ptrans) {
754 return FALSE;
757 /* Un-disembarkable transport must be in city or base to unload cargo. */
758 if (!utype_can_freely_unload(unit_type_get(pcargo), unit_type_get(ptrans))
759 && !tile_city(unit_tile(ptrans))
760 && !tile_has_native_base(unit_tile(ptrans), unit_type_get(ptrans))) {
761 return FALSE;
764 return TRUE;
767 /**************************************************************************
768 Return whether the unit can be paradropped - that is, if the unit is in
769 a friendly city or on an airbase special, has enough movepoints left, and
770 has not paradropped yet this turn.
771 **************************************************************************/
772 bool can_unit_paradrop(const struct unit *punit)
774 struct unit_type *utype;
776 if (!unit_has_type_flag(punit, UTYF_PARATROOPERS))
777 return FALSE;
779 if(punit->paradropped)
780 return FALSE;
782 utype = unit_type_get(punit);
784 if(punit->moves_left < utype->paratroopers_mr_req)
785 return FALSE;
787 if (tile_has_base_flag(unit_tile(punit), BF_PARADROP_FROM)) {
788 /* Paradrop has to be possible from non-native base.
789 * Paratroopers are "Land" units, but they can paradrom from Airbase. */
790 return TRUE;
793 if (!tile_city(unit_tile(punit))) {
794 return FALSE;
797 return TRUE;
800 /**************************************************************************
801 Return whether the unit can bombard.
802 Basically if it is a bombarder, isn't being transported, and hasn't
803 moved this turn.
804 **************************************************************************/
805 bool can_unit_bombard(const struct unit *punit)
807 if (!unit_has_type_flag(punit, UTYF_BOMBARDER)) {
808 return FALSE;
811 if (unit_transported(punit)) {
812 return FALSE;
815 return TRUE;
818 /**************************************************************************
819 Check if the unit's current activity is actually legal.
820 **************************************************************************/
821 bool can_unit_continue_current_activity(struct unit *punit)
823 enum unit_activity current = punit->activity;
824 struct extra_type *target = punit->activity_target;
825 enum unit_activity current2 =
826 (current == ACTIVITY_FORTIFIED) ? ACTIVITY_FORTIFYING : current;
827 bool result;
829 punit->activity = ACTIVITY_IDLE;
830 punit->activity_target = NULL;
832 result = can_unit_do_activity_targeted(punit, current2, target);
834 punit->activity = current;
835 punit->activity_target = target;
837 return result;
840 /**************************************************************************
841 Return TRUE iff the unit can do the given untargeted activity at its
842 current location.
844 Note that some activities must be targeted; see
845 can_unit_do_activity_targeted.
846 **************************************************************************/
847 bool can_unit_do_activity(const struct unit *punit,
848 enum unit_activity activity)
850 struct extra_type *target = NULL;
852 /* FIXME: lots of callers (usually client real_menus_update()) rely on
853 * being able to find out whether an activity is in general possible.
854 * Find one for them, but when they come to do the activity, they will
855 * have to determine the target themselves */
857 struct tile *ptile = unit_tile(punit);
858 struct terrain *pterrain = tile_terrain(ptile);
860 if (activity == ACTIVITY_IRRIGATE
861 && pterrain->irrigation_result == pterrain) {
862 target = next_extra_for_tile(ptile,
863 EC_IRRIGATION,
864 unit_owner(punit),
865 punit);
866 if (NULL == target) {
867 return FALSE; /* No more irrigation extras available. */
869 } else if (activity == ACTIVITY_MINE
870 && pterrain->mining_result == pterrain) {
871 target = next_extra_for_tile(ptile,
872 EC_MINE,
873 unit_owner(punit),
874 punit);
875 if (NULL == target) {
876 return FALSE; /* No more mine extras available. */
881 return can_unit_do_activity_targeted(punit, activity, target);
884 /**************************************************************************
885 Return whether the unit can do the targeted activity at its current
886 location.
887 **************************************************************************/
888 bool can_unit_do_activity_targeted(const struct unit *punit,
889 enum unit_activity activity,
890 struct extra_type *target)
892 return can_unit_do_activity_targeted_at(punit, activity, target,
893 unit_tile(punit));
896 /**************************************************************************
897 Return TRUE if the unit can do the targeted activity at the given
898 location.
899 **************************************************************************/
900 bool can_unit_do_activity_targeted_at(const struct unit *punit,
901 enum unit_activity activity,
902 struct extra_type *target,
903 const struct tile *ptile)
905 struct terrain *pterrain = tile_terrain(ptile);
906 struct unit_class *pclass = unit_class_get(punit);
908 /* Check that no build activity conflicting with one already in progress
909 * gets executed. */
910 /* FIXME: Should check also the cases where one of the activities is terrain
911 * change that destroys the target of the other activity */
912 if (target != NULL && is_build_activity(activity, ptile)) {
913 unit_list_iterate(ptile->units, tunit) {
914 if (is_build_activity(tunit->activity, ptile)
915 && !can_extras_coexist(target, tunit->activity_target)) {
916 return FALSE;
918 } unit_list_iterate_end;
921 switch(activity) {
922 case ACTIVITY_IDLE:
923 case ACTIVITY_GOTO:
924 return TRUE;
926 case ACTIVITY_POLLUTION:
928 struct extra_type *pextra;
930 if (pterrain->clean_pollution_time == 0) {
931 return FALSE;
934 if (target != NULL) {
935 pextra = target;
936 } else {
937 /* TODO: Make sure that all callers set target so that
938 * we don't need this fallback. */
939 pextra = prev_extra_in_tile(ptile,
940 ERM_CLEANPOLLUTION,
941 unit_owner(punit),
942 punit);
943 if (pextra == NULL) {
944 /* No available pollution extras */
945 return FALSE;
949 if (!is_extra_removed_by(pextra, ERM_CLEANPOLLUTION)) {
950 return FALSE;
953 if (!unit_has_type_flag(punit, UTYF_SETTLERS)
954 || !can_remove_extra(pextra, punit, ptile)) {
955 return FALSE;
958 if (tile_has_extra(ptile, pextra)) {
959 return TRUE;
962 return FALSE;
965 case ACTIVITY_FALLOUT:
967 struct extra_type *pextra;
969 if (pterrain->clean_fallout_time == 0) {
970 return FALSE;
973 if (target != NULL) {
974 pextra = target;
975 } else {
976 /* TODO: Make sure that all callers set target so that
977 * we don't need this fallback. */
978 pextra = prev_extra_in_tile(ptile,
979 ERM_CLEANFALLOUT,
980 unit_owner(punit),
981 punit);
982 if (pextra == NULL) {
983 /* No available pollution extras */
984 return FALSE;
988 if (!is_extra_removed_by(pextra, ERM_CLEANFALLOUT)) {
989 return FALSE;
992 if (!unit_has_type_flag(punit, UTYF_SETTLERS)
993 || !can_remove_extra(pextra, punit, ptile)) {
994 return FALSE;
997 if (tile_has_extra(ptile, pextra)) {
998 return TRUE;
1001 return FALSE;
1004 case ACTIVITY_MINE:
1005 if (pterrain->mining_result == pterrain) {
1006 if (target == NULL) {
1007 return FALSE;
1010 if (pterrain->mining_time == 0) {
1011 return FALSE;
1014 if (!is_extra_caused_by(target, EC_MINE)) {
1015 return FALSE;
1019 if (unit_has_type_flag(punit, UTYF_SETTLERS)
1020 && ((pterrain == pterrain->mining_result
1021 && can_build_extra(target, punit, ptile)
1022 && get_tile_bonus(ptile, punit, EFT_MINING_POSSIBLE) > 0)
1023 || (pterrain != pterrain->mining_result
1024 && pterrain->mining_result != T_NONE
1025 && get_tile_bonus(ptile, punit, EFT_MINING_TF_POSSIBLE) > 0
1026 && target == NULL
1027 && terrain_surroundings_allow_change(ptile,
1028 pterrain->mining_result)
1029 && (!terrain_has_flag(pterrain->mining_result, TER_NO_CITIES)
1030 || !tile_city(ptile))))) {
1031 return TRUE;
1032 } else {
1033 return FALSE;
1036 case ACTIVITY_IRRIGATE:
1037 if (pterrain->irrigation_result == pterrain) {
1038 if (target == NULL) {
1039 return FALSE;
1042 if (pterrain->irrigation_time == 0) {
1043 return FALSE;
1046 if (!is_extra_caused_by(target, EC_IRRIGATION)) {
1047 return FALSE;
1051 if (unit_has_type_flag(punit, UTYF_SETTLERS)
1052 && ((pterrain == pterrain->irrigation_result
1053 && can_build_extra(target, punit, ptile)
1054 && can_be_irrigated(ptile, punit))
1055 || (pterrain != pterrain->irrigation_result
1056 && pterrain->irrigation_result != T_NONE
1057 && get_tile_bonus(ptile, punit, EFT_IRRIG_TF_POSSIBLE) > 0
1058 && target == NULL
1059 && terrain_surroundings_allow_change(ptile,
1060 pterrain->irrigation_result)
1061 && (!terrain_has_flag(pterrain->irrigation_result, TER_NO_CITIES)
1062 || !tile_city(ptile))))) {
1063 return TRUE;
1064 } else {
1065 return FALSE;
1068 case ACTIVITY_FORTIFYING:
1069 return (uclass_has_flag(pclass, UCF_CAN_FORTIFY)
1070 && !unit_has_type_flag(punit, UTYF_CANT_FORTIFY)
1071 && punit->activity != ACTIVITY_FORTIFIED
1072 && (!terrain_has_flag(pterrain, TER_NO_FORTIFY) || tile_city(ptile)));
1074 case ACTIVITY_FORTIFIED:
1075 return FALSE;
1077 case ACTIVITY_BASE:
1078 if (target == NULL) {
1079 return FALSE;
1081 return can_build_base(punit, extra_base_get(target), ptile);
1083 case ACTIVITY_GEN_ROAD:
1084 if (target == NULL) {
1085 return FALSE;
1087 return can_build_road(extra_road_get(target), punit, ptile);
1089 case ACTIVITY_SENTRY:
1090 if (!can_unit_survive_at_tile(punit, unit_tile(punit))
1091 && !unit_transported(punit)) {
1092 /* Don't let units sentry on tiles they will die on. */
1093 return FALSE;
1095 return TRUE;
1097 case ACTIVITY_PILLAGE:
1099 if (pterrain->pillage_time == 0) {
1100 return FALSE;
1103 if (uclass_has_flag(pclass, UCF_CAN_PILLAGE)) {
1104 bv_extras pspresent = get_tile_infrastructure_set(ptile, NULL);
1105 bv_extras psworking = get_unit_tile_pillage_set(ptile);
1107 bv_extras pspossible;
1109 BV_CLR_ALL(pspossible);
1110 extra_type_iterate(pextra) {
1111 int idx = extra_index(pextra);
1113 /* Only one unit can pillage a given improvement at a time */
1114 if (BV_ISSET(pspresent, idx) && !BV_ISSET(psworking, idx)
1115 && can_remove_extra(pextra, punit, ptile)) {
1116 bool required = FALSE;
1118 extra_type_iterate(pdepending) {
1119 if (BV_ISSET(pspresent, extra_index(pdepending))) {
1120 extra_deps_iterate(&(pdepending->reqs), pdep) {
1121 if (pdep == pextra) {
1122 required = TRUE;
1123 break;
1125 } extra_deps_iterate_end;
1127 if (required) {
1128 break;
1130 } extra_type_iterate_end;
1132 if (!required) {
1133 BV_SET(pspossible, idx);
1136 } extra_type_iterate_end;
1138 if (!BV_ISSET_ANY(pspossible)) {
1139 /* Nothing available to pillage */
1140 return FALSE;
1143 if (target == NULL) {
1144 /* Undirected pillaging. If we've got this far, then there's
1145 * *something* we can pillage; work out what when we come to it */
1146 return TRUE;
1147 } else {
1148 if (!game.info.pillage_select) {
1149 /* Hobson's choice (this case mostly exists for old clients) */
1150 /* Needs to match what unit_activity_assign_target chooses */
1151 struct extra_type *tgt;
1153 tgt = get_preferred_pillage(pspossible);
1155 if (tgt != target) {
1156 /* Only one target allowed, which wasn't the requested one */
1157 return FALSE;
1161 return BV_ISSET(pspossible, extra_index(target));
1163 } else {
1164 /* Unit is not a type that can pillage at all */
1165 return FALSE;
1169 case ACTIVITY_EXPLORE:
1170 return (!unit_type_get(punit)->fuel && !is_losing_hp(punit));
1172 case ACTIVITY_TRANSFORM:
1173 return (pterrain->transform_result != T_NONE
1174 && pterrain != pterrain->transform_result
1175 && terrain_surroundings_allow_change(ptile,
1176 pterrain->transform_result)
1177 && (!terrain_has_flag(pterrain->transform_result, TER_NO_CITIES)
1178 || !(tile_city(ptile)))
1179 && get_tile_bonus(ptile, punit, EFT_TRANSFORM_POSSIBLE) > 0);
1181 case ACTIVITY_CONVERT:
1182 return unit_can_convert(punit);
1184 case ACTIVITY_OLD_ROAD:
1185 case ACTIVITY_OLD_RAILROAD:
1186 case ACTIVITY_FORTRESS:
1187 case ACTIVITY_AIRBASE:
1188 case ACTIVITY_PATROL_UNUSED:
1189 case ACTIVITY_LAST:
1190 case ACTIVITY_UNKNOWN:
1191 break;
1193 log_error("can_unit_do_activity_targeted_at() unknown activity %d",
1194 activity);
1195 return FALSE;
1198 /**************************************************************************
1199 Assign a new task to a unit. Doesn't account for changed_from.
1200 **************************************************************************/
1201 static void set_unit_activity_internal(struct unit *punit,
1202 enum unit_activity new_activity)
1204 fc_assert_ret(new_activity != ACTIVITY_FORTRESS
1205 && new_activity != ACTIVITY_AIRBASE);
1207 punit->activity = new_activity;
1208 punit->activity_count = 0;
1209 punit->activity_target = NULL;
1210 if (new_activity == ACTIVITY_IDLE && punit->moves_left > 0) {
1211 /* No longer done. */
1212 punit->done_moving = FALSE;
1216 /**************************************************************************
1217 assign a new untargeted task to a unit.
1218 **************************************************************************/
1219 void set_unit_activity(struct unit *punit, enum unit_activity new_activity)
1221 fc_assert_ret(!activity_requires_target(new_activity));
1223 if (new_activity == ACTIVITY_FORTIFYING
1224 && punit->changed_from == ACTIVITY_FORTIFIED) {
1225 new_activity = ACTIVITY_FORTIFIED;
1227 set_unit_activity_internal(punit, new_activity);
1228 if (new_activity == punit->changed_from) {
1229 punit->activity_count = punit->changed_from_count;
1233 /**************************************************************************
1234 assign a new targeted task to a unit.
1235 **************************************************************************/
1236 void set_unit_activity_targeted(struct unit *punit,
1237 enum unit_activity new_activity,
1238 struct extra_type *new_target)
1240 fc_assert_ret(activity_requires_target(new_activity)
1241 || new_target == NULL);
1243 set_unit_activity_internal(punit, new_activity);
1244 punit->activity_target = new_target;
1245 if (new_activity == punit->changed_from
1246 && new_target == punit->changed_from_target) {
1247 punit->activity_count = punit->changed_from_count;
1251 /**************************************************************************
1252 Assign a new base building task to unit
1253 **************************************************************************/
1254 void set_unit_activity_base(struct unit *punit,
1255 Base_type_id base)
1257 set_unit_activity_internal(punit, ACTIVITY_BASE);
1258 punit->activity_target = base_extra_get(base_by_number(base));
1259 if (ACTIVITY_BASE == punit->changed_from
1260 && punit->activity_target == punit->changed_from_target) {
1261 punit->activity_count = punit->changed_from_count;
1265 /**************************************************************************
1266 Assign a new road building task to unit
1267 **************************************************************************/
1268 void set_unit_activity_road(struct unit *punit,
1269 Road_type_id road)
1271 set_unit_activity_internal(punit, ACTIVITY_GEN_ROAD);
1272 punit->activity_target = road_extra_get(road_by_number(road));
1273 if (ACTIVITY_GEN_ROAD == punit->changed_from
1274 && punit->activity_target == punit->changed_from_target) {
1275 punit->activity_count = punit->changed_from_count;
1279 /**************************************************************************
1280 Return whether any units on the tile are doing this activity.
1281 **************************************************************************/
1282 bool is_unit_activity_on_tile(enum unit_activity activity,
1283 const struct tile *ptile)
1285 unit_list_iterate(ptile->units, punit) {
1286 if (punit->activity == activity) {
1287 return TRUE;
1289 } unit_list_iterate_end;
1290 return FALSE;
1293 /****************************************************************************
1294 Return a mask of the extras which are actively (currently) being
1295 pillaged on the given tile.
1296 ****************************************************************************/
1297 bv_extras get_unit_tile_pillage_set(const struct tile *ptile)
1299 bv_extras tgt_ret;
1301 BV_CLR_ALL(tgt_ret);
1302 unit_list_iterate(ptile->units, punit) {
1303 if (punit->activity == ACTIVITY_PILLAGE) {
1304 BV_SET(tgt_ret, extra_index(punit->activity_target));
1306 } unit_list_iterate_end;
1308 return tgt_ret;
1311 /**************************************************************************
1312 Return text describing the unit's current activity as a static string.
1314 FIXME: Convert all callers of this function to unit_activity_astr()
1315 because this function is not re-entrant.
1316 **************************************************************************/
1317 const char *unit_activity_text(const struct unit *punit) {
1318 static struct astring str = ASTRING_INIT;
1320 astr_clear(&str);
1321 unit_activity_astr(punit, &str);
1323 return astr_str(&str);
1326 /**************************************************************************
1327 Append text describing the unit's current activity to the given astring.
1328 **************************************************************************/
1329 void unit_activity_astr(const struct unit *punit, struct astring *astr)
1331 if (!punit || !astr) {
1332 return;
1335 switch (punit->activity) {
1336 case ACTIVITY_IDLE:
1337 if (utype_fuel(unit_type_get(punit))) {
1338 int rate, f;
1340 rate = unit_type_get(punit)->move_rate;
1341 f = ((punit->fuel) - 1);
1343 /* Add in two parts as move_points_text() returns ptr to static
1344 * End result: "Moves: (fuel)moves_left" */
1345 astr_add_line(astr, "%s: (%s)", _("Moves"),
1346 move_points_text((rate * f) + punit->moves_left, FALSE));
1347 astr_add(astr, "%s",
1348 move_points_text(punit->moves_left, FALSE));
1349 } else {
1350 astr_add_line(astr, "%s: %s", _("Moves"),
1351 move_points_text(punit->moves_left, FALSE));
1353 return;
1354 case ACTIVITY_POLLUTION:
1355 case ACTIVITY_FALLOUT:
1356 case ACTIVITY_OLD_ROAD:
1357 case ACTIVITY_OLD_RAILROAD:
1358 case ACTIVITY_TRANSFORM:
1359 case ACTIVITY_FORTIFYING:
1360 case ACTIVITY_FORTIFIED:
1361 case ACTIVITY_AIRBASE:
1362 case ACTIVITY_FORTRESS:
1363 case ACTIVITY_SENTRY:
1364 case ACTIVITY_GOTO:
1365 case ACTIVITY_EXPLORE:
1366 case ACTIVITY_CONVERT:
1367 astr_add_line(astr, "%s", get_activity_text(punit->activity));
1368 return;
1369 case ACTIVITY_MINE:
1370 case ACTIVITY_IRRIGATE:
1371 if (punit->activity_target == NULL) {
1372 astr_add_line(astr, "%s", get_activity_text(punit->activity));
1373 } else {
1374 astr_add_line(astr, "Building %s",
1375 extra_name_translation(punit->activity_target));
1377 return;
1378 case ACTIVITY_PILLAGE:
1379 if (punit->activity_target != NULL) {
1380 astr_add_line(astr, "%s: %s", get_activity_text(punit->activity),
1381 extra_name_translation(punit->activity_target));
1382 } else {
1383 astr_add_line(astr, "%s", get_activity_text(punit->activity));
1385 return;
1386 case ACTIVITY_BASE:
1387 astr_add_line(astr, "%s: %s", get_activity_text(punit->activity),
1388 extra_name_translation(punit->activity_target));
1389 return;
1390 case ACTIVITY_GEN_ROAD:
1391 astr_add_line(astr, "%s: %s", get_activity_text(punit->activity),
1392 extra_name_translation(punit->activity_target));
1393 return;
1394 case ACTIVITY_UNKNOWN:
1395 case ACTIVITY_PATROL_UNUSED:
1396 case ACTIVITY_LAST:
1397 break;
1400 log_error("Unknown unit activity %d for %s (nb %d) in %s()",
1401 punit->activity, unit_rule_name(punit), punit->id, __FUNCTION__);
1404 /**************************************************************************
1405 Append a line of text describing the unit's upkeep to the astring.
1407 NB: In the client it is assumed that this information is only available
1408 for units owned by the client's player; the caller must check this.
1409 **************************************************************************/
1410 void unit_upkeep_astr(const struct unit *punit, struct astring *astr)
1412 if (!punit || !astr) {
1413 return;
1416 astr_add_line(astr, "%s %d/%d/%d", _("Food/Shield/Gold:"),
1417 punit->upkeep[O_FOOD], punit->upkeep[O_SHIELD],
1418 punit->upkeep[O_GOLD]);
1421 /**************************************************************************
1422 Return the nationality of the unit.
1423 **************************************************************************/
1424 struct player *unit_nationality(const struct unit *punit)
1426 fc_assert_ret_val(NULL != punit, NULL);
1427 return punit->nationality;
1430 /*****************************************************************************
1431 Set the tile location of the unit. Tile can be NULL (for transported units.
1432 *****************************************************************************/
1433 void unit_tile_set(struct unit *punit, struct tile *ptile)
1435 fc_assert_ret(NULL != punit);
1436 punit->tile = ptile;
1439 /**************************************************************************
1440 Returns true if the tile contains an allied unit and only allied units.
1441 (ie, if your nation A is allied with B, and B is allied with C, a tile
1442 containing units from B and C will return false)
1443 **************************************************************************/
1444 struct unit *is_allied_unit_tile(const struct tile *ptile,
1445 const struct player *pplayer)
1447 struct unit *punit = NULL;
1449 unit_list_iterate(ptile->units, cunit) {
1450 if (pplayers_allied(pplayer, unit_owner(cunit)))
1451 punit = cunit;
1452 else
1453 return NULL;
1455 unit_list_iterate_end;
1457 return punit;
1460 /****************************************************************************
1461 Is there an enemy unit on this tile? Returns the unit or NULL if none.
1463 This function is likely to fail if used at the client because the client
1464 doesn't see all units. (Maybe it should be moved into the server code.)
1465 ****************************************************************************/
1466 struct unit *is_enemy_unit_tile(const struct tile *ptile,
1467 const struct player *pplayer)
1469 unit_list_iterate(ptile->units, punit) {
1470 if (pplayers_at_war(unit_owner(punit), pplayer))
1471 return punit;
1472 } unit_list_iterate_end;
1474 return NULL;
1477 /**************************************************************************
1478 is there an non-allied unit on this tile?
1479 **************************************************************************/
1480 struct unit *is_non_allied_unit_tile(const struct tile *ptile,
1481 const struct player *pplayer)
1483 unit_list_iterate(ptile->units, punit) {
1484 if (!pplayers_allied(unit_owner(punit), pplayer))
1485 return punit;
1487 unit_list_iterate_end;
1489 return NULL;
1492 /**************************************************************************
1493 is there an unit belonging to another player on this tile?
1494 **************************************************************************/
1495 struct unit *is_other_players_unit_tile(const struct tile *ptile,
1496 const struct player *pplayer)
1498 unit_list_iterate(ptile->units, punit) {
1499 if (unit_owner(punit) != pplayer) {
1500 return punit;
1502 } unit_list_iterate_end;
1504 return NULL;
1507 /**************************************************************************
1508 is there an unit we have peace or ceasefire with on this tile?
1509 **************************************************************************/
1510 struct unit *is_non_attack_unit_tile(const struct tile *ptile,
1511 const struct player *pplayer)
1513 unit_list_iterate(ptile->units, punit) {
1514 if (pplayers_non_attack(unit_owner(punit), pplayer))
1515 return punit;
1517 unit_list_iterate_end;
1519 return NULL;
1522 /****************************************************************************
1523 Is there an occupying unit on this tile?
1525 Intended for both client and server; assumes that hiding units are not
1526 sent to client. First check tile for known and seen.
1528 called by city_can_work_tile().
1529 ****************************************************************************/
1530 struct unit *unit_occupies_tile(const struct tile *ptile,
1531 const struct player *pplayer)
1533 unit_list_iterate(ptile->units, punit) {
1534 if (!is_military_unit(punit)) {
1535 continue;
1538 if (uclass_has_flag(unit_class_get(punit), UCF_DOESNT_OCCUPY_TILE)) {
1539 continue;
1542 if (pplayers_at_war(unit_owner(punit), pplayer)) {
1543 return punit;
1545 } unit_list_iterate_end;
1547 return NULL;
1550 /**************************************************************************
1551 Is this square controlled by the pplayer?
1553 Here "is_my_zoc" means essentially a square which is *not* adjacent to an
1554 enemy unit (that has a ZOC) on a terrain that has zoc rules.
1556 Since this function is also used in the client, it has to deal with some
1557 client-specific features, like FoW and the fact that the client cannot
1558 see units inside enemy cities.
1559 **************************************************************************/
1560 bool is_my_zoc(const struct player *pplayer, const struct tile *ptile0)
1562 struct terrain *pterrain;
1564 square_iterate(ptile0, 1, ptile) {
1565 pterrain = tile_terrain(ptile);
1566 if (T_UNKNOWN == pterrain
1567 || terrain_has_flag(pterrain, TER_NO_ZOC)) {
1568 continue;
1571 /* Note: in the client, this loop will not check units
1572 inside city that might be there. */
1573 unit_list_iterate(ptile->units, punit) {
1574 if (!pplayers_allied(unit_owner(punit), pplayer)
1575 && !unit_has_type_flag(punit, UTYF_NOZOC)) {
1576 return FALSE;
1578 } unit_list_iterate_end;
1580 if (!is_server()) {
1581 struct city *pcity = is_non_allied_city_tile(ptile, pplayer);
1583 if (pcity
1584 && (pcity->client.occupied
1585 || TILE_KNOWN_UNSEEN == tile_get_known(ptile, pplayer))) {
1586 /* If the city is fogged, we assume it's occupied */
1587 return FALSE;
1590 } square_iterate_end;
1592 return TRUE;
1595 /**************************************************************************
1596 Takes into account unit class flag UCF_ZOC as well as IGZOC
1597 **************************************************************************/
1598 bool unit_type_really_ignores_zoc(const struct unit_type *punittype)
1600 return (!uclass_has_flag(utype_class(punittype), UCF_ZOC)
1601 || utype_has_flag(punittype, UTYF_IGZOC));
1604 /**************************************************************************
1605 An "aggressive" unit is a unit which may cause unhappiness
1606 under a Republic or Democracy.
1607 A unit is *not* aggressive if one or more of following is true:
1608 - zero attack strength
1609 - inside a city
1610 - ground unit inside a fortress within 3 squares of a friendly city
1611 **************************************************************************/
1612 bool unit_being_aggressive(const struct unit *punit)
1614 if (!is_attack_unit(punit)) {
1615 return FALSE;
1617 if (tile_city(unit_tile(punit))) {
1618 return FALSE;
1620 if (BORDERS_DISABLED != game.info.borders) {
1621 switch (game.info.happyborders) {
1622 case HB_DISABLED:
1623 break;
1624 case HB_NATIONAL:
1625 if (tile_owner(unit_tile(punit)) == unit_owner(punit)) {
1626 return FALSE;
1628 break;
1629 case HB_ALLIANCE:
1630 if (pplayers_allied(tile_owner(unit_tile(punit)), unit_owner(punit))) {
1631 return FALSE;
1633 break;
1636 if (tile_has_base_flag_for_unit(unit_tile(punit),
1637 unit_type_get(punit),
1638 BF_NOT_AGGRESSIVE)) {
1639 return !is_unit_near_a_friendly_city(punit);
1642 return TRUE;
1645 /**************************************************************************
1646 Returns true if given activity is some kind of building.
1647 **************************************************************************/
1648 bool is_build_activity(enum unit_activity activity, const struct tile *ptile)
1650 struct terrain *pterr = NULL;
1652 if (ptile != NULL) {
1653 pterr = tile_terrain(ptile);
1656 switch (activity) {
1657 case ACTIVITY_MINE:
1658 if (pterr != NULL && pterr->mining_result != pterr) {
1659 return FALSE;
1661 return TRUE;
1662 case ACTIVITY_IRRIGATE:
1663 if (pterr != NULL && pterr->irrigation_result != pterr) {
1664 return FALSE;
1666 return TRUE;
1667 case ACTIVITY_BASE:
1668 case ACTIVITY_GEN_ROAD:
1669 return TRUE;
1670 default:
1671 return FALSE;
1675 /**************************************************************************
1676 Returns true if given activity is some kind of cleaning.
1677 **************************************************************************/
1678 bool is_clean_activity(enum unit_activity activity)
1680 switch (activity) {
1681 case ACTIVITY_PILLAGE:
1682 case ACTIVITY_POLLUTION:
1683 case ACTIVITY_FALLOUT:
1684 return TRUE;
1685 default:
1686 return FALSE;
1690 /**************************************************************************
1691 Returns true if given activity affects tile.
1692 **************************************************************************/
1693 bool is_tile_activity(enum unit_activity activity)
1695 return is_build_activity(activity, NULL)
1696 || is_clean_activity(activity)
1697 || activity == ACTIVITY_TRANSFORM;
1700 /**************************************************************************
1701 Create a virtual unit skeleton. pcity can be NULL, but then you need
1702 to set tile and homecity yourself.
1703 **************************************************************************/
1704 struct unit *unit_virtual_create(struct player *pplayer, struct city *pcity,
1705 struct unit_type *punittype,
1706 int veteran_level)
1708 /* Make sure that contents of unit structure are correctly initialized,
1709 * if you ever allocate it by some other mean than fc_calloc() */
1710 struct unit *punit = fc_calloc(1, sizeof(*punit));
1711 int max_vet_lvl;
1713 /* It does not register the unit so the id is set to 0. */
1714 punit->id = IDENTITY_NUMBER_ZERO;
1716 fc_assert_ret_val(NULL != punittype, NULL); /* No untyped units! */
1717 punit->utype = punittype;
1719 fc_assert_ret_val(NULL != pplayer, NULL); /* No unowned units! */
1720 punit->owner = pplayer;
1721 punit->nationality = pplayer;
1723 punit->facing = rand_direction();
1725 if (pcity) {
1726 unit_tile_set(punit, pcity->tile);
1727 punit->homecity = pcity->id;
1728 } else {
1729 unit_tile_set(punit, NULL);
1730 punit->homecity = IDENTITY_NUMBER_ZERO;
1733 memset(punit->upkeep, 0, O_LAST * sizeof(*punit->upkeep));
1734 punit->goto_tile = NULL;
1735 max_vet_lvl = utype_veteran_levels(punittype) - 1;
1736 punit->veteran = MIN(veteran_level, max_vet_lvl);
1737 /* A unit new and fresh ... */
1738 punit->fuel = utype_fuel(unit_type_get(punit));
1739 punit->hp = unit_type_get(punit)->hp;
1740 punit->moves_left = unit_move_rate(punit);
1741 punit->moved = FALSE;
1743 punit->ai_controlled = FALSE;
1744 punit->paradropped = FALSE;
1745 punit->done_moving = FALSE;
1747 punit->transporter = NULL;
1748 punit->transporting = unit_list_new();
1750 set_unit_activity(punit, ACTIVITY_IDLE);
1751 punit->battlegroup = BATTLEGROUP_NONE;
1752 punit->has_orders = FALSE;
1754 punit->action_decision_want = ACT_DEC_NOTHING;
1755 punit->action_decision_tile = NULL;
1757 if (is_server()) {
1758 punit->server.debug = FALSE;
1759 punit->server.birth_turn = game.info.turn;
1761 punit->server.dying = FALSE;
1763 punit->server.ord_map = 0;
1764 punit->server.ord_city = 0;
1766 punit->server.vision = NULL; /* No vision. */
1767 punit->server.action_timestamp = 0;
1768 /* Must be an invalid turn number, and an invalid previous turn
1769 * number. */
1770 punit->server.action_turn = -2;
1771 /* punit->server.moving = NULL; set by fc_calloc(). */
1773 punit->server.adv = fc_calloc(1, sizeof(*punit->server.adv));
1775 CALL_FUNC_EACH_AI(unit_alloc, punit);
1776 } else {
1777 punit->client.focus_status = FOCUS_AVAIL;
1778 punit->client.transported_by = -1;
1779 punit->client.colored = FALSE;
1780 punit->client.act_prob_cache = NULL;
1783 return punit;
1786 /**************************************************************************
1787 Free the memory used by virtual unit. By the time this function is
1788 called, you should already have unregistered it everywhere.
1789 **************************************************************************/
1790 void unit_virtual_destroy(struct unit *punit)
1792 free_unit_orders(punit);
1794 /* Unload unit if transported. */
1795 unit_transport_unload(punit);
1796 fc_assert(!unit_transported(punit));
1798 /* Check for transported units. Use direct access to the list. */
1799 if (unit_list_size(punit->transporting) != 0) {
1800 /* Unload all units. */
1801 unit_list_iterate_safe(punit->transporting, pcargo) {
1802 unit_transport_unload(pcargo);
1803 } unit_list_iterate_safe_end;
1805 fc_assert(unit_list_size(punit->transporting) == 0);
1807 if (punit->transporting) {
1808 unit_list_destroy(punit->transporting);
1811 CALL_FUNC_EACH_AI(unit_free, punit);
1813 if (is_server() && punit->server.adv) {
1814 FC_FREE(punit->server.adv);
1815 } else {
1816 if (punit->client.act_prob_cache) {
1817 FC_FREE(punit->client.act_prob_cache);
1821 FC_FREE(punit);
1824 /**************************************************************************
1825 Free and reset the unit's goto route (punit->pgr). Only used by the
1826 server.
1827 **************************************************************************/
1828 void free_unit_orders(struct unit *punit)
1830 if (punit->has_orders) {
1831 punit->goto_tile = NULL;
1832 free(punit->orders.list);
1833 punit->orders.list = NULL;
1835 punit->has_orders = FALSE;
1838 /****************************************************************************
1839 Return how many units are in the transport.
1840 ****************************************************************************/
1841 int get_transporter_occupancy(const struct unit *ptrans)
1843 fc_assert_ret_val(ptrans, -1);
1845 return unit_list_size(ptrans->transporting);
1848 /****************************************************************************
1849 Helper for transporter_for_unit() and transporter_for_unit_at()
1850 ****************************************************************************/
1851 static struct unit *base_transporter_for_unit(const struct unit *pcargo,
1852 const struct tile *ptile,
1853 bool (*unit_load_test)
1854 (const struct unit *pc,
1855 const struct unit *pt))
1857 struct unit *best_trans = NULL;
1858 struct {
1859 bool has_orders, is_idle, can_freely_unload;
1860 int depth, outermost_moves_left, total_moves;
1861 } cur, best = { FALSE };
1863 unit_list_iterate(ptile->units, ptrans) {
1864 if (!unit_load_test(pcargo, ptrans)) {
1865 continue;
1866 } else if (best_trans == NULL) {
1867 best_trans = ptrans;
1870 /* Gather data from transport stack in a single pass, for use in
1871 * various conditions below. */
1872 cur.has_orders = unit_has_orders(ptrans);
1873 cur.outermost_moves_left = ptrans->moves_left;
1874 cur.total_moves = ptrans->moves_left + unit_move_rate(ptrans);
1875 unit_transports_iterate(ptrans, ptranstrans) {
1876 if (unit_has_orders(ptranstrans)) {
1877 cur.has_orders = TRUE;
1879 cur.outermost_moves_left = ptranstrans->moves_left;
1880 cur.total_moves += ptranstrans->moves_left + unit_move_rate(ptranstrans);
1881 } unit_transports_iterate_end;
1883 /* Criteria for deciding the 'best' transport to load onto.
1884 * The following tests are applied in order; earlier ones have
1885 * lexicographically greater significance than later ones. */
1887 /* Transports which have orders, or are on transports with orders,
1888 * are less preferable to transport stacks without orders (to
1889 * avoid loading on units that are just passing through). */
1890 if (best_trans != ptrans) {
1891 if (!cur.has_orders && best.has_orders) {
1892 best_trans = ptrans;
1893 } else if (cur.has_orders && !best.has_orders) {
1894 continue;
1898 /* Else, transports which are idle are preferable (giving players
1899 * some control over loading) -- this does not check transports
1900 * of transports. */
1901 cur.is_idle = (ptrans->activity == ACTIVITY_IDLE);
1902 if (best_trans != ptrans) {
1903 if (cur.is_idle && !best.is_idle) {
1904 best_trans = ptrans;
1905 } else if (!cur.is_idle && best.is_idle) {
1906 continue;
1910 /* Else, transports from which the cargo could unload at any time
1911 * are preferable to those where the cargo can only disembark in
1912 * cities/bases. */
1913 cur.can_freely_unload = utype_can_freely_unload(unit_type_get(pcargo),
1914 unit_type_get(ptrans));
1915 if (best_trans != ptrans) {
1916 if (cur.can_freely_unload && !best.can_freely_unload) {
1917 best_trans = ptrans;
1918 } else if (!cur.can_freely_unload && best.can_freely_unload) {
1919 continue;
1923 /* Else, transports which are less deeply nested are preferable. */
1924 cur.depth = unit_transport_depth(ptrans);
1925 if (best_trans != ptrans) {
1926 if (cur.depth < best.depth) {
1927 best_trans = ptrans;
1928 } else if (cur.depth > best.depth) {
1929 continue;
1933 /* Else, transport stacks where the outermost transport has more
1934 * moves left are preferable (on the assumption that it's the
1935 * outermost transport that's about to move). */
1936 if (best_trans != ptrans) {
1937 if (cur.outermost_moves_left > best.outermost_moves_left) {
1938 best_trans = ptrans;
1939 } else if (cur.outermost_moves_left < best.outermost_moves_left) {
1940 continue;
1944 /* All other things being equal, as a tie-breaker, compare the total
1945 * moves left (this turn) and move rate (future turns) for the whole
1946 * stack, to take into account total potential movement for both
1947 * short and long journeys (we don't know which the cargo intends to
1948 * make). Doesn't try to account for whether transports can unload,
1949 * etc. */
1950 if (best_trans != ptrans) {
1951 if (cur.total_moves > best.total_moves) {
1952 best_trans = ptrans;
1953 } else {
1954 continue;
1958 fc_assert(best_trans == ptrans);
1959 best = cur;
1960 } unit_list_iterate_end;
1962 return best_trans;
1965 /****************************************************************************
1966 Find the best transporter at the given location for the unit. See also
1967 unit_can_load() to test if there will be transport might be suitable
1968 for 'pcargo'.
1969 ****************************************************************************/
1970 struct unit *transporter_for_unit(const struct unit *pcargo)
1972 return base_transporter_for_unit(pcargo, unit_tile(pcargo), can_unit_load);
1975 /****************************************************************************
1976 Find the best transporter at the given location for the unit. See also
1977 unit_could_load_at() to test if there will be transport might be suitable
1978 for 'pcargo'.
1979 ****************************************************************************/
1980 struct unit *transporter_for_unit_at(const struct unit *pcargo,
1981 const struct tile *ptile)
1983 return base_transporter_for_unit(pcargo, ptile, could_unit_load);
1986 /****************************************************************************
1987 Check if unit of given type would be able to transport all of transport's
1988 cargo.
1989 ****************************************************************************/
1990 static bool can_type_transport_units_cargo(const struct unit_type *utype,
1991 const struct unit *punit)
1993 if (get_transporter_occupancy(punit) > utype->transport_capacity) {
1994 return FALSE;
1997 unit_list_iterate(punit->transporting, pcargo) {
1998 if (!can_unit_type_transport(utype, unit_class_get(pcargo))) {
1999 return FALSE;
2001 } unit_list_iterate_end;
2003 return TRUE;
2006 /****************************************************************************
2007 Tests if the unit could be updated. Returns UU_OK if is this is
2008 possible.
2010 is_free should be set if the unit upgrade is "free" (e.g., Leonardo's).
2011 Otherwise money is needed and the unit must be in an owned city.
2013 Note that this function is strongly tied to unittools.c:upgrade_unit().
2014 ****************************************************************************/
2015 enum unit_upgrade_result unit_upgrade_test(const struct unit *punit,
2016 bool is_free)
2018 struct player *pplayer = unit_owner(punit);
2019 struct unit_type *to_unittype = can_upgrade_unittype(pplayer,
2020 unit_type_get(punit));
2021 struct city *pcity;
2022 int cost;
2024 if (!to_unittype) {
2025 return UU_NO_UNITTYPE;
2028 if (!is_free) {
2029 cost = unit_upgrade_price(pplayer, unit_type_get(punit), to_unittype);
2030 if (pplayer->economic.gold < cost) {
2031 return UU_NO_MONEY;
2034 pcity = tile_city(unit_tile(punit));
2035 if (!pcity) {
2036 return UU_NOT_IN_CITY;
2038 if (city_owner(pcity) != pplayer) {
2039 /* TODO: should upgrades in allied cities be possible? */
2040 return UU_NOT_CITY_OWNER;
2044 if (!can_type_transport_units_cargo(to_unittype, punit)) {
2045 /* TODO: allow transported units to be reassigned. Check here
2046 * and make changes to upgrade_unit. */
2047 return UU_NOT_ENOUGH_ROOM;
2050 if (punit->transporter != NULL) {
2051 if (!can_unit_type_transport(unit_type_get(punit->transporter),
2052 unit_class_get(punit))) {
2053 return UU_UNSUITABLE_TRANSPORT;
2055 } else if (!can_exist_at_tile(to_unittype, unit_tile(punit))) {
2056 /* The new unit type can't survive on this terrain. */
2057 return UU_NOT_TERRAIN;
2060 return UU_OK;
2063 /**************************************************************************
2064 Tests if unit can be converted to another type.
2065 **************************************************************************/
2066 bool unit_can_convert(const struct unit *punit)
2068 struct unit_type *tgt = unit_type_get(punit)->converted_to;
2070 if (tgt == NULL) {
2071 return FALSE;
2074 if (!can_type_transport_units_cargo(tgt, punit)) {
2075 return FALSE;
2078 if (!can_exist_at_tile(tgt, unit_tile(punit))) {
2079 return FALSE;
2082 return TRUE;
2085 /**************************************************************************
2086 Find the result of trying to upgrade the unit, and a message that
2087 most callers can use directly.
2088 **************************************************************************/
2089 enum unit_upgrade_result unit_upgrade_info(const struct unit *punit,
2090 char *buf, size_t bufsz)
2092 struct player *pplayer = unit_owner(punit);
2093 enum unit_upgrade_result result = unit_upgrade_test(punit, FALSE);
2094 int upgrade_cost;
2095 struct unit_type *from_unittype = unit_type_get(punit);
2096 struct unit_type *to_unittype = can_upgrade_unittype(pplayer,
2097 unit_type_get(punit));
2098 char tbuf[MAX_LEN_MSG];
2100 fc_snprintf(tbuf, ARRAY_SIZE(tbuf), PL_("Treasury contains %d gold.",
2101 "Treasury contains %d gold.",
2102 pplayer->economic.gold),
2103 pplayer->economic.gold);
2105 switch (result) {
2106 case UU_OK:
2107 upgrade_cost = unit_upgrade_price(pplayer, from_unittype, to_unittype);
2108 /* This message is targeted toward the GUI callers. */
2109 /* TRANS: Last %s is pre-pluralised "Treasury contains %d gold." */
2110 fc_snprintf(buf, bufsz, PL_("Upgrade %s to %s for %d gold?\n%s",
2111 "Upgrade %s to %s for %d gold?\n%s",
2112 upgrade_cost),
2113 utype_name_translation(from_unittype),
2114 utype_name_translation(to_unittype),
2115 upgrade_cost, tbuf);
2116 break;
2117 case UU_NO_UNITTYPE:
2118 fc_snprintf(buf, bufsz,
2119 _("Sorry, cannot upgrade %s (yet)."),
2120 utype_name_translation(from_unittype));
2121 break;
2122 case UU_NO_MONEY:
2123 upgrade_cost = unit_upgrade_price(pplayer, from_unittype, to_unittype);
2124 /* TRANS: Last %s is pre-pluralised "Treasury contains %d gold." */
2125 fc_snprintf(buf, bufsz, PL_("Upgrading %s to %s costs %d gold.\n%s",
2126 "Upgrading %s to %s costs %d gold.\n%s",
2127 upgrade_cost),
2128 utype_name_translation(from_unittype),
2129 utype_name_translation(to_unittype),
2130 upgrade_cost, tbuf);
2131 break;
2132 case UU_NOT_IN_CITY:
2133 case UU_NOT_CITY_OWNER:
2134 fc_snprintf(buf, bufsz,
2135 _("You can only upgrade units in your cities."));
2136 break;
2137 case UU_NOT_ENOUGH_ROOM:
2138 fc_snprintf(buf, bufsz,
2139 _("Upgrading this %s would strand units it transports."),
2140 utype_name_translation(from_unittype));
2141 break;
2142 case UU_NOT_TERRAIN:
2143 fc_snprintf(buf, bufsz,
2144 _("Upgrading this %s would result in a %s which can not "
2145 "survive at this place."),
2146 utype_name_translation(from_unittype),
2147 utype_name_translation(to_unittype));
2148 break;
2149 case UU_UNSUITABLE_TRANSPORT:
2150 fc_snprintf(buf, bufsz,
2151 _("Upgrading this %s would result in a %s which its "
2152 "current transport, %s, could not transport."),
2153 utype_name_translation(from_unittype),
2154 utype_name_translation(to_unittype),
2155 unit_name_translation(punit->transporter));
2156 break;
2159 return result;
2162 /**************************************************************************
2163 Does unit lose hitpoints each turn?
2164 **************************************************************************/
2165 bool is_losing_hp(const struct unit *punit)
2167 struct unit_type *punittype = unit_type_get(punit);
2169 return get_unit_bonus(punit, EFT_UNIT_RECOVER)
2170 < (punittype->hp *
2171 utype_class(punittype)->hp_loss_pct / 100);
2174 /**************************************************************************
2175 Does unit lose hitpoints each turn?
2176 **************************************************************************/
2177 bool unit_type_is_losing_hp(const struct player *pplayer,
2178 const struct unit_type *punittype)
2180 return get_unittype_bonus(pplayer, NULL, punittype, EFT_UNIT_RECOVER)
2181 < (punittype->hp *
2182 utype_class(punittype)->hp_loss_pct / 100);
2185 /**************************************************************************
2186 Check if unit with given id is still alive. Use this before using
2187 old unit pointers when unit might have died.
2188 **************************************************************************/
2189 bool unit_is_alive(int id)
2191 /* Check if unit exist in game */
2192 if (game_unit_by_number(id)) {
2193 return TRUE;
2196 return FALSE;
2199 /**************************************************************************
2200 Return TRUE if this is a valid unit pointer but does not correspond to
2201 any unit that exists in the game.
2203 NB: A return value of FALSE implies that either the pointer is NULL or
2204 that the unit exists in the game.
2205 **************************************************************************/
2206 bool unit_is_virtual(const struct unit *punit)
2208 if (!punit) {
2209 return FALSE;
2212 return punit != game_unit_by_number(punit->id);
2215 /**************************************************************************
2216 Return pointer to ai data of given unit and ai type.
2217 **************************************************************************/
2218 void *unit_ai_data(const struct unit *punit, const struct ai_type *ai)
2220 return punit->server.ais[ai_type_number(ai)];
2223 /**************************************************************************
2224 Attach ai data to unit
2225 **************************************************************************/
2226 void unit_set_ai_data(struct unit *punit, const struct ai_type *ai,
2227 void *data)
2229 punit->server.ais[ai_type_number(ai)] = data;
2232 /*****************************************************************************
2233 Calculate how expensive it is to bribe the unit. The cost depends on the
2234 distance to the capital, the owner's treasury, and the build cost of the
2235 unit. For a damaged unit the price is reduced. For a veteran unit, it is
2236 increased.
2238 The bribe cost for settlers are halved.
2239 **************************************************************************/
2240 int unit_bribe_cost(struct unit *punit, struct player *briber)
2242 int cost, default_hp, dist = 0;
2243 struct city *capital;
2245 fc_assert_ret_val(punit != NULL, 0);
2247 default_hp = unit_type_get(punit)->hp;
2248 cost = unit_owner(punit)->economic.gold + game.info.base_bribe_cost;
2249 capital = player_capital(unit_owner(punit));
2251 /* Consider the distance to the capital. */
2252 if (capital != NULL) {
2253 dist = MIN(GAME_UNIT_BRIBE_DIST_MAX,
2254 map_distance(capital->tile, unit_tile(punit)));
2255 } else {
2256 dist = GAME_UNIT_BRIBE_DIST_MAX;
2258 cost /= dist + 2;
2260 /* Consider the build cost. */
2261 cost *= unit_build_shield_cost(punit) / 10;
2263 /* Rule set specific cost modification */
2264 cost += (cost
2265 * get_target_bonus_effects(NULL, unit_owner(punit), briber,
2266 game_city_by_number(punit->homecity),
2267 NULL, unit_tile(punit),
2268 punit, unit_type_get(punit), NULL, NULL,
2269 EFT_UNIT_BRIBE_COST_PCT))
2270 / 100;
2272 /* Veterans are not cheap. */
2274 struct unit_type *ptype = unit_type_get(punit);
2275 const struct veteran_level *vlevel
2276 = utype_veteran_level(ptype, punit->veteran);
2278 fc_assert_ret_val(vlevel != NULL, 0);
2279 cost = cost * vlevel->power_fact / 100;
2280 if (ptype->move_rate > 0) {
2281 cost += cost * vlevel->move_bonus / ptype->move_rate;
2282 } else {
2283 cost += cost * vlevel->move_bonus / SINGLE_MOVE;
2287 /* Cost now contains the basic bribe cost. We now reduce it by:
2288 * bribecost = cost/2 + cost/2 * damage/hp
2289 * = cost/2 * (1 + damage/hp) */
2290 return ((float)cost / 2 * (1.0 + punit->hp / default_hp));
2293 /*****************************************************************************
2294 Load pcargo onto ptrans. Returns TRUE on success.
2295 *****************************************************************************/
2296 bool unit_transport_load(struct unit *pcargo, struct unit *ptrans, bool force)
2298 fc_assert_ret_val(ptrans != NULL, FALSE);
2299 fc_assert_ret_val(pcargo != NULL, FALSE);
2301 fc_assert_ret_val(!unit_list_search(ptrans->transporting, pcargo), FALSE);
2303 if (force || can_unit_load(pcargo, ptrans)) {
2304 pcargo->transporter = ptrans;
2305 unit_list_append(ptrans->transporting, pcargo);
2307 return TRUE;
2310 return FALSE;
2313 /*****************************************************************************
2314 Unload pcargo from ptrans. Returns TRUE on success.
2315 *****************************************************************************/
2316 bool unit_transport_unload(struct unit *pcargo)
2318 struct unit *ptrans;
2320 fc_assert_ret_val(pcargo != NULL, FALSE);
2322 if (!unit_transported(pcargo)) {
2323 /* 'pcargo' is not transported. */
2324 return FALSE;
2327 /* Get the transporter; must not be defined on the client! */
2328 ptrans = unit_transport_get(pcargo);
2329 if (ptrans) {
2330 bool success;
2332 /* 'pcargo' and 'ptrans' should be on the same tile. */
2333 fc_assert(same_pos(unit_tile(pcargo), unit_tile(ptrans)));
2334 /* It is an error if 'pcargo' can not be removed from the 'ptrans'. */
2335 success = unit_list_remove(ptrans->transporting, pcargo);
2336 fc_assert(success);
2339 /* For the server (also safe for the client). */
2340 pcargo->transporter = NULL;
2342 return TRUE;
2345 /*****************************************************************************
2346 Returns TRUE iff the unit is transported.
2347 *****************************************************************************/
2348 bool unit_transported(const struct unit *pcargo)
2350 fc_assert_ret_val(pcargo != NULL, FALSE);
2352 /* The unit is transported if a transporter unit is set or, (for the client)
2353 * if the transported_by field is set. */
2354 if (pcargo->transporter != NULL
2355 || (!is_server() && pcargo->client.transported_by != -1)) {
2356 return TRUE;
2359 return FALSE;
2362 /*****************************************************************************
2363 Returns the transporter of the unit or NULL if it is not transported.
2364 *****************************************************************************/
2365 struct unit *unit_transport_get(const struct unit *pcargo)
2367 fc_assert_ret_val(pcargo != NULL, NULL);
2369 return pcargo->transporter;
2372 /*****************************************************************************
2373 Returns the list of cargo units.
2374 *****************************************************************************/
2375 struct unit_list *unit_transport_cargo(const struct unit *ptrans)
2377 fc_assert_ret_val(ptrans != NULL, NULL);
2378 fc_assert_ret_val(ptrans->transporting != NULL, NULL);
2380 return ptrans->transporting;
2383 /****************************************************************************
2384 Helper for unit_transport_check().
2385 ****************************************************************************/
2386 static inline bool
2387 unit_transport_check_one(const struct unit_type *cargo_utype,
2388 const struct unit_type *trans_utype)
2390 return (trans_utype != cargo_utype
2391 && !can_unit_type_transport(cargo_utype,
2392 utype_class(trans_utype)));
2395 /****************************************************************************
2396 Returns whether 'pcargo' in 'ptrans' is a valid transport. Note that
2397 'pcargo' can already be (but doesn't need) loaded into 'ptrans'.
2399 It may fail if one of the cargo unit has the same type of one of the
2400 transporter unit or if one of the cargo unit can transport one of
2401 the transporters.
2402 ****************************************************************************/
2403 bool unit_transport_check(const struct unit *pcargo,
2404 const struct unit *ptrans)
2406 const struct unit_type *cargo_utype = unit_type_get(pcargo);
2408 /* Check 'pcargo' against 'ptrans'. */
2409 if (!unit_transport_check_one(cargo_utype, unit_type_get(ptrans))) {
2410 return FALSE;
2413 /* Check 'pcargo' against 'ptrans' parents. */
2414 unit_transports_iterate(ptrans, pparent) {
2415 if (!unit_transport_check_one(cargo_utype, unit_type_get(pparent))) {
2416 return FALSE;
2418 } unit_transports_iterate_end;
2420 /* Check cargo children... */
2421 unit_cargo_iterate(pcargo, pchild) {
2422 cargo_utype = unit_type_get(pchild);
2424 /* ...against 'ptrans'. */
2425 if (!unit_transport_check_one(cargo_utype, unit_type_get(ptrans))) {
2426 return FALSE;
2429 /* ...and against 'ptrans' parents. */
2430 unit_transports_iterate(ptrans, pparent) {
2431 if (!unit_transport_check_one(cargo_utype, unit_type_get(pparent))) {
2432 return FALSE;
2434 } unit_transports_iterate_end;
2435 } unit_cargo_iterate_end;
2437 return TRUE;
2440 /****************************************************************************
2441 Returns whether 'pcargo' is transported by 'ptrans', either directly
2442 or indirectly.
2443 ****************************************************************************/
2444 bool unit_contained_in(const struct unit *pcargo, const struct unit *ptrans)
2446 unit_transports_iterate(pcargo, plevel) {
2447 if (ptrans == plevel) {
2448 return TRUE;
2450 } unit_transports_iterate_end;
2451 return FALSE;
2454 /****************************************************************************
2455 Returns the number of unit cargo layers within transport 'ptrans'.
2456 ****************************************************************************/
2457 int unit_cargo_depth(const struct unit *ptrans)
2459 struct cargo_iter iter;
2460 struct iterator *it;
2461 int depth = 0;
2463 for (it = cargo_iter_init(&iter, ptrans); iterator_valid(it);
2464 iterator_next(it)) {
2465 if (iter.depth > depth) {
2466 depth = iter.depth;
2469 return depth;
2472 /****************************************************************************
2473 Returns the number of unit transport layers which carry unit 'pcargo'.
2474 ****************************************************************************/
2475 int unit_transport_depth(const struct unit *pcargo)
2477 int level = 0;
2479 unit_transports_iterate(pcargo, plevel) {
2480 level++;
2481 } unit_transports_iterate_end;
2482 return level;
2485 /****************************************************************************
2486 Returns the size of the unit cargo iterator.
2487 ****************************************************************************/
2488 size_t cargo_iter_sizeof(void)
2490 return sizeof(struct cargo_iter);
2493 /****************************************************************************
2494 Get the unit of the cargo iterator.
2495 ****************************************************************************/
2496 static void *cargo_iter_get(const struct iterator *it)
2498 const struct cargo_iter *iter = CARGO_ITER(it);
2500 return unit_list_link_data(iter->links[iter->depth - 1]);
2503 /****************************************************************************
2504 Try to find next unit for the cargo iterator.
2505 ****************************************************************************/
2506 static void cargo_iter_next(struct iterator *it)
2508 struct cargo_iter *iter = CARGO_ITER(it);
2509 const struct unit_list_link *piter = iter->links[iter->depth - 1];
2510 const struct unit_list_link *pnext;
2512 /* Variant 1: unit has cargo. */
2513 pnext = unit_list_head(unit_transport_cargo(unit_list_link_data(piter)));
2514 if (NULL != pnext) {
2515 fc_assert(iter->depth < ARRAY_SIZE(iter->links));
2516 iter->links[iter->depth++] = pnext;
2517 return;
2520 do {
2521 /* Variant 2: there are other cargo units at same level. */
2522 pnext = unit_list_link_next(piter);
2523 if (NULL != pnext) {
2524 iter->links[iter->depth - 1] = pnext;
2525 return;
2528 /* Variant 3: return to previous level, and do same tests. */
2529 piter = iter->links[iter->depth-- - 2];
2530 } while (0 < iter->depth);
2533 /****************************************************************************
2534 Return whether the iterator is still valid.
2535 ****************************************************************************/
2536 static bool cargo_iter_valid(const struct iterator *it)
2538 return (0 < CARGO_ITER(it)->depth);
2541 /****************************************************************************
2542 Initialize the cargo iterator.
2543 ****************************************************************************/
2544 struct iterator *cargo_iter_init(struct cargo_iter *iter,
2545 const struct unit *ptrans)
2547 struct iterator *it = ITERATOR(iter);
2549 it->get = cargo_iter_get;
2550 it->next = cargo_iter_next;
2551 it->valid = cargo_iter_valid;
2552 iter->links[0] = unit_list_head(unit_transport_cargo(ptrans));
2553 iter->depth = (NULL != iter->links[0] ? 1 : 0);
2555 return it;
2558 /****************************************************************************
2559 Is a cityfounder unit?
2560 ****************************************************************************/
2561 bool unit_is_cityfounder(const struct unit *punit)
2563 return utype_is_cityfounder(unit_type_get(punit));