Lower default cmdlevel to basic on game start.
[freeciv.git] / server / unithand.c
blob55c82810bef37957f9e920fa0a74de950ce77704
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 <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
22 /* utility */
23 #include "astring.h"
24 #include "fcintl.h"
25 #include "mem.h"
26 #include "rand.h"
27 #include "shared.h"
29 /* common */
30 #include "actions.h"
31 #include "ai.h"
32 #include "city.h"
33 #include "combat.h"
34 #include "events.h"
35 #include "game.h"
36 #include "log.h"
37 #include "map.h"
38 #include "movement.h"
39 #include "packets.h"
40 #include "player.h"
41 #include "research.h"
42 #include "specialist.h"
43 #include "traderoutes.h"
44 #include "unit.h"
45 #include "unitlist.h"
47 /* common/scriptcore */
48 #include "luascript_types.h"
50 /* server */
51 #include "actiontools.h"
52 #include "barbarian.h"
53 #include "citizenshand.h"
54 #include "citytools.h"
55 #include "cityturn.h"
56 #include "diplomats.h"
57 #include "maphand.h"
58 #include "notify.h"
59 #include "plrhand.h"
60 #include "sanitycheck.h"
61 #include "spacerace.h"
62 #include "srv_main.h"
63 #include "techtools.h"
64 #include "unittools.h"
66 /* server/advisors */
67 #include "autoexplorer.h"
68 #include "autosettlers.h"
70 /* server/scripting */
71 #include "script_server.h"
73 #include "unithand.h"
75 /* A category of reasons why an action isn't enabled. */
76 enum ane_kind {
77 /* Explanation: bad actor terrain. */
78 ANEK_BAD_TERRAIN_ACT,
79 /* Explanation: bad target terrain. */
80 ANEK_BAD_TERRAIN_TGT,
81 /* Explanation: being transported. */
82 ANEK_IS_TRANSPORTED,
83 /* Explanation: not being transported. */
84 ANEK_IS_NOT_TRANSPORTED,
85 /* Explanation: must declare war first. */
86 ANEK_NO_WAR,
87 /* Explanation: this nation can't be targeted. */
88 ANEK_NATION_TGT,
89 /* Explanation: not enough MP left. */
90 ANEK_LOW_MP,
91 /* Explanation not detected. */
92 ANEK_UNKNOWN,
95 /* An explanation why an action isn't enabled. */
96 struct ane_expl {
97 /* The kind of reason why an action isn't enabled. */
98 enum ane_kind kind;
100 union {
101 /* The bad terrain in question. */
102 struct terrain *no_act_terrain;
104 /* The player to advice declaring war on. */
105 struct player *no_war_with;
107 /* The nation that can't be involved. */
108 struct nation_type *no_act_nation;
112 static void illegal_action(struct player *pplayer,
113 struct unit *actor,
114 enum gen_action stopped_action,
115 struct player *tgt_player,
116 const struct tile *target_tile,
117 const struct city *target_city,
118 const struct unit *target_unit);
119 static void city_add_unit(struct player *pplayer, struct unit *punit);
120 static void city_build(struct player *pplayer, struct unit *punit,
121 const char *name);
122 static bool do_unit_establish_trade(struct player *pplayer,
123 struct unit *punit,
124 struct city *pcity_dest,
125 bool est_if_able);
127 static void do_unit_help_build_wonder(struct player *pplayer,
128 struct unit *punit,
129 struct city *pcity_dest);
130 static bool unit_bombard(struct unit *punit, struct tile *ptile);
132 /**************************************************************************
133 Handle airlift request.
134 **************************************************************************/
135 void handle_unit_airlift(struct player *pplayer, int unit_id, int city_id)
137 struct unit *punit = player_unit_by_number(pplayer, unit_id);
138 struct city *pcity = game_city_by_number(city_id);
140 if (NULL == punit) {
141 /* Probably died or bribed. */
142 log_verbose("handle_unit_airlift() invalid unit %d", unit_id);
143 return;
146 if (NULL == pcity) {
147 /* Probably lost. */
148 log_verbose("handle_unit_airlift() invalid city %d", city_id);
149 return;
152 (void) do_airline(punit, pcity);
155 /**************************************************************************
156 Upgrade all units of a given type.
157 **************************************************************************/
158 void handle_unit_type_upgrade(struct player *pplayer, Unit_type_id uti)
160 struct unit_type *to_unittype;
161 struct unit_type *from_unittype = utype_by_number(uti);
162 int number_of_upgraded_units = 0;
164 if (NULL == from_unittype) {
165 /* Probably died or bribed. */
166 log_verbose("handle_unit_type_upgrade() invalid unit type %d", uti);
167 return;
170 to_unittype = can_upgrade_unittype(pplayer, from_unittype);
171 if (!to_unittype) {
172 notify_player(pplayer, NULL, E_BAD_COMMAND, ftc_server,
173 _("Illegal packet, can't upgrade %s (yet)."),
174 utype_name_translation(from_unittype));
175 return;
179 * Try to upgrade units. The order we upgrade in is arbitrary (if
180 * the player really cared they should have done it manually).
182 conn_list_do_buffer(pplayer->connections);
183 unit_list_iterate(pplayer->units, punit) {
184 if (unit_type_get(punit) == from_unittype) {
185 enum unit_upgrade_result result = unit_upgrade_test(punit, FALSE);
187 if (UU_OK == result) {
188 number_of_upgraded_units++;
189 transform_unit(punit, to_unittype, FALSE);
190 } else if (UU_NO_MONEY == result) {
191 break;
194 } unit_list_iterate_end;
195 conn_list_do_unbuffer(pplayer->connections);
197 /* Alert the player about what happened. */
198 if (number_of_upgraded_units > 0) {
199 const int cost = unit_upgrade_price(pplayer, from_unittype, to_unittype);
200 notify_player(pplayer, NULL, E_UNIT_UPGRADED, ftc_server,
201 /* FIXME: plurality of number_of_upgraded_units ignored!
202 * (Plurality of unit names is messed up anyway.) */
203 /* TRANS: "2 Musketeers upgraded to Riflemen for 100 gold."
204 * Plurality is in gold (second %d), not units. */
205 PL_("%d %s upgraded to %s for %d gold.",
206 "%d %s upgraded to %s for %d gold.",
207 cost * number_of_upgraded_units),
208 number_of_upgraded_units,
209 utype_name_translation(from_unittype),
210 utype_name_translation(to_unittype),
211 cost * number_of_upgraded_units);
212 send_player_info_c(pplayer, pplayer->connections);
213 } else {
214 notify_player(pplayer, NULL, E_UNIT_UPGRADED, ftc_server,
215 _("No units could be upgraded."));
219 /**************************************************************************
220 Upgrade a single unit.
221 **************************************************************************/
222 void handle_unit_upgrade(struct player *pplayer, int unit_id)
224 char buf[512];
225 struct unit *punit = player_unit_by_number(pplayer, unit_id);
227 if (NULL == punit) {
228 /* Probably died or bribed. */
229 log_verbose("handle_unit_upgrade() invalid unit %d", unit_id);
230 return;
233 if (UU_OK == unit_upgrade_info(punit, buf, sizeof(buf))) {
234 struct unit_type *from_unit = unit_type_get(punit);
235 struct unit_type *to_unit = can_upgrade_unittype(pplayer, from_unit);
236 int cost = unit_upgrade_price(pplayer, from_unit, to_unit);
238 transform_unit(punit, to_unit, FALSE);
239 send_player_info_c(pplayer, pplayer->connections);
240 notify_player(pplayer, unit_tile(punit), E_UNIT_UPGRADED, ftc_server,
241 PL_("%s upgraded to %s for %d gold.",
242 "%s upgraded to %s for %d gold.", cost),
243 utype_name_translation(from_unit),
244 unit_link(punit),
245 cost);
246 } else {
247 notify_player(pplayer, unit_tile(punit), E_UNIT_UPGRADED, ftc_server,
248 "%s", buf);
252 /**************************************************************************
253 Capture all the units at pdesttile using punit.
254 **************************************************************************/
255 static void do_capture_units(struct player *pplayer,
256 struct unit *punit,
257 struct tile *pdesttile)
259 char capturer_link[MAX_LEN_LINK];
260 const char *capturer_nation = nation_plural_for_player(pplayer);
261 bv_unit_types unique_on_tile;
263 /* Sanity check: make sure that the capture won't result in the actor
264 * ending up with more than one unit of each unique unit type. */
265 BV_CLR_ALL(unique_on_tile);
266 unit_list_iterate(pdesttile->units, to_capture) {
267 bool unique_conflict = FALSE;
269 /* Check what the player already has. */
270 if (utype_player_already_has_this_unique(pplayer,
271 unit_type_get(to_capture))) {
272 /* The player already has a unit of this kind. */
273 unique_conflict = TRUE;
276 if (utype_has_flag(unit_type_get(to_capture), UTYF_UNIQUE)) {
277 /* The type of the units at the tile must also be checked. Two allied
278 * players can both have their unique unit at the same tile.
279 * Capturing them both would give the actor two units of a kind that
280 * is supposed to be unique. */
282 if (BV_ISSET(unique_on_tile, utype_index(unit_type_get(to_capture)))) {
283 /* There is another unit of the same kind at this tile. */
284 unique_conflict = TRUE;
285 } else {
286 /* Remember the unit type in case another unit of the same kind is
287 * encountered later. */
288 BV_SET(unique_on_tile, utype_index(unit_type_get(to_capture)));
292 if (unique_conflict) {
293 log_debug("capture units: already got unique unit");
294 notify_player(pplayer, pdesttile, E_UNIT_ILLEGAL_ACTION, ftc_server,
295 /* TRANS: You can only have one Leader. */
296 _("You can only have one %s."),
297 unit_link(to_capture));
299 return;
301 } unit_list_iterate_end;
303 /* N.B: unit_link() always returns the same pointer. */
304 sz_strlcpy(capturer_link, unit_link(punit));
306 unit_list_iterate(pdesttile->units, to_capture) {
307 struct player *uplayer = unit_owner(to_capture);
308 const char *victim_link;
310 unit_owner(to_capture)->score.units_lost++;
311 to_capture = unit_change_owner(to_capture, pplayer,
312 (game.server.homecaughtunits
313 ? punit->homecity
314 : IDENTITY_NUMBER_ZERO),
315 ULR_CAPTURED);
316 /* As unit_change_owner() currently remove the old unit and
317 * replace by a new one (with a new id), we want to make link to
318 * the new unit. */
319 victim_link = unit_link(to_capture);
321 /* Notify players */
322 notify_player(pplayer, pdesttile, E_MY_DIPLOMAT_BRIBE, ftc_server,
323 /* TRANS: <unit> ... <unit> */
324 _("Your %s succeeded in capturing the %s %s."),
325 capturer_link, nation_adjective_for_player(uplayer),
326 victim_link);
327 notify_player(uplayer, pdesttile,
328 E_ENEMY_DIPLOMAT_BRIBE, ftc_server,
329 /* TRANS: <unit> ... <Poles> */
330 _("Your %s was captured by the %s."),
331 victim_link, capturer_nation);
332 } unit_list_iterate_end;
334 /* Subtract movement point from capturer */
335 punit->moves_left -= SINGLE_MOVE;
336 if (punit->moves_left < 0) {
337 punit->moves_left = 0;
340 send_unit_info(NULL, punit);
343 /**************************************************************************
344 Returns TRUE iff, from the point of view of the owner of the actor unit,
345 it looks like the actor unit may be able to perform a non action
346 enabler controlled action against a unit or city on the target_tile by
347 "moving" to it.
348 **************************************************************************/
349 static bool may_non_act_move(struct unit *actor_unit,
350 struct city *target_city,
351 struct tile *target_tile,
352 bool igzoc)
354 if (unit_can_move_to_tile(actor_unit, target_tile, igzoc)) {
355 /* Move. Includes occupying a foreign city. */
356 return TRUE;
359 if (can_unit_attack_tile(actor_unit, target_tile)) {
360 /* Attack. Includes nuking. */
361 return TRUE;
364 if (!is_ocean_tile(target_tile) && can_unit_bombard(actor_unit)) {
365 /* Bombard. May be possible even if regular attack isn't. */
366 return TRUE;
369 if (!target_city && unit_has_type_flag(actor_unit, UTYF_CAPTURER)) {
370 /* Capture. May be possible even if regular attack isn't. */
372 unit_list_iterate(target_tile->units, to_capture) {
373 if (!unit_has_type_flag(to_capture, UTYF_CAPTURABLE)) {
374 return FALSE;
376 } unit_list_iterate_end;
378 return TRUE;
381 return FALSE;
384 /**************************************************************************
385 Returns TRUE iff, from the point of view of the owner of the actor unit,
386 it looks like the actor unit may be able to do any action to the target
387 city.
389 If the owner of the actor unit don't have the knowledge needed to know
390 for sure if the unit can act TRUE will be returned.
391 **************************************************************************/
392 static bool may_unit_act_vs_city(struct unit *actor, struct city *target)
394 if (actor == NULL || target == NULL) {
395 /* Can't do any actions if actor or target are missing. */
396 return FALSE;
399 action_iterate(act) {
400 if (!(action_id_get_actor_kind(act) == AAK_UNIT
401 && action_id_get_target_kind(act) == ATK_CITY)) {
402 /* Not a relevant action. */
403 continue;
406 if (action_prob_possible(action_prob_vs_city(actor, act, target))) {
407 /* The actor unit may be able to do this action to the target
408 * city. */
409 return TRUE;
411 } action_iterate_end;
413 return FALSE;
416 /**************************************************************************
417 Returns TRUE iff, from the point of view of the owner of the actor unit,
418 it looks like the actor unit may be able to do any action to the target
419 unit.
421 If the owner of the actor unit don't have the knowledge needed to know
422 for sure if the unit can act TRUE will be returned.
423 **************************************************************************/
424 static bool may_unit_act_vs_unit(struct unit *actor, struct unit *target)
426 if (actor == NULL || target == NULL) {
427 /* Can't do any actions if actor or target are missing. */
428 return FALSE;
431 action_iterate(act) {
432 if (!(action_id_get_actor_kind(act) == AAK_UNIT
433 && action_id_get_target_kind(act) == ATK_UNIT)) {
434 /* Not a relevant action. */
435 continue;
438 if (action_prob_possible(action_prob_vs_unit(actor, act, target))) {
439 /* The actor unit may be able to do this action to the target
440 * unit. */
441 return TRUE;
443 } action_iterate_end;
445 return FALSE;
448 /**************************************************************************
449 Find a city to target for an action on the specified tile.
451 Returns NULL if no proper target is found.
452 **************************************************************************/
453 static struct city *tgt_city(struct unit *actor, struct tile *target_tile)
455 struct city *target = tile_city(target_tile);
457 if (target && may_unit_act_vs_city(actor, target)) {
458 /* It may be possible to act against this city. */
459 return target;
462 return NULL;
465 /**************************************************************************
466 Find a city to target for an action on the specified tile.
468 Returns NULL if no proper target is found.
469 **************************************************************************/
470 struct city *action_tgt_city(struct unit *actor, struct tile *target_tile)
472 return tgt_city(actor, target_tile);
475 /**************************************************************************
476 Find a unit to target for an action at the specified tile.
478 Returns the first unit found at the tile that the actor may act against
479 or NULL if no proper target is found.
480 **************************************************************************/
481 static struct unit *tgt_unit(struct unit *actor, struct tile *target_tile)
483 unit_list_iterate(target_tile->units, target) {
484 if (may_unit_act_vs_unit(actor, target)) {
485 return target;
487 } unit_list_iterate_end;
489 return NULL;
492 /**************************************************************************
493 Returns the first player that may enable the specified action if war is
494 declared.
496 Helper for need_war_player(). Use it in stead.
497 **************************************************************************/
498 static struct player *need_war_player_hlp(const struct unit *actor,
499 const int act,
500 const struct tile *target_tile,
501 const struct city *target_city,
502 const struct unit *target_unit)
504 if (action_id_get_actor_kind(act) != AAK_UNIT) {
505 /* No unit can ever do this action so it isn't relevant. */
506 return NULL;
509 if (!unit_can_do_action(actor, act)) {
510 /* The unit can't do the action no matter if there is war or not. */
511 return NULL;
514 if (can_utype_do_act_if_tgt_diplrel(unit_type_get(actor),
515 act, DS_WAR, FALSE)) {
516 /* The unit can do the action even if there isn't war. */
517 return NULL;
520 switch (action_id_get_target_kind(act)) {
521 case ATK_CITY:
522 if (target_city == NULL) {
523 /* No target city. */
524 return NULL;
527 if (player_diplstate_get(unit_owner(actor),
528 city_owner(target_city))->type != DS_WAR) {
529 return city_owner(target_city);
531 break;
532 case ATK_UNIT:
533 if (target_unit == NULL) {
534 /* No target unit. */
535 return NULL;
538 if (player_diplstate_get(unit_owner(actor),
539 unit_owner(target_unit))->type != DS_WAR) {
540 return unit_owner(target_unit);
542 break;
543 case ATK_COUNT:
544 /* Nothing to check. */
545 fc_assert(action_id_get_target_kind(act) != ATK_COUNT);
546 return NULL;
549 /* Declaring war won't enable the specified action. */
550 return NULL;
553 /**************************************************************************
554 Returns the first player that may enable the specified action if war is
555 declared. If the specified action is ACTION_ANY the first player that
556 may enable any action at all if war is declared will be returned.
557 **************************************************************************/
558 static struct player *need_war_player(const struct unit *actor,
559 const int action_id,
560 const struct tile *target_tile,
561 const struct city *target_city,
562 const struct unit *target_unit)
564 if (action_id == ACTION_ANY) {
565 /* Any action at all will do. */
566 action_iterate(act) {
567 struct player *war_player;
569 war_player = need_war_player_hlp(actor, act,
570 target_tile, target_city,
571 target_unit);
573 if (war_player != NULL) {
574 /* Declaring war on this player may enable this action. */
575 return war_player;
577 } action_iterate_end;
579 /* No action at all may be enabled by declaring war. */
580 return NULL;
581 } else {
582 /* Look for the specified action. */
583 return need_war_player_hlp(actor, action_id,
584 target_tile, target_city,
585 target_unit);
589 /**************************************************************************
590 Returns TRUE iff the specified terrain type blocks the specified action.
592 If the "action" is ACTION_ANY all actions are checked.
593 **************************************************************************/
594 static bool does_terrain_block_action(const int action_id,
595 bool is_target,
596 struct unit *actor_unit,
597 struct terrain *pterrain)
599 if (action_id == ACTION_ANY) {
600 /* Any action is OK. */
601 action_iterate(alt_act) {
602 if (utype_can_do_action(unit_type_get(actor_unit), alt_act)
603 && !does_terrain_block_action(alt_act, is_target,
604 actor_unit, pterrain)) {
605 /* Only one action has to be possible. */
606 return FALSE;
608 } action_iterate_end;
610 /* No action enabled. */
611 return TRUE;
614 /* ACTION_ANY is handled above. */
615 fc_assert_ret_val(action_id_is_valid(action_id), FALSE);
617 action_enabler_list_iterate(action_enablers_for_action(action_id),
618 enabler) {
619 if (requirement_fulfilled_by_terrain(pterrain,
620 (is_target ? &enabler->target_reqs : &enabler->actor_reqs))
621 && requirement_fulfilled_by_unit_type(unit_type_get(actor_unit),
622 &enabler->actor_reqs)) {
623 /* This terrain kind doesn't block this action enabler. */
624 return FALSE;
626 } action_enabler_list_iterate_end;
628 return TRUE;
631 /**************************************************************************
632 Returns TRUE iff the specified nation blocks the specified action.
634 If the "action" is ACTION_ANY all actions are checked.
635 **************************************************************************/
636 static bool does_nation_block_action(const int action_id,
637 bool is_target,
638 struct unit *actor_unit,
639 struct nation_type *pnation)
641 if (action_id == ACTION_ANY) {
642 /* Any action is OK. */
643 action_iterate(alt_act) {
644 if (utype_can_do_action(unit_type_get(actor_unit), alt_act)
645 && !does_nation_block_action(alt_act, is_target,
646 actor_unit, pnation)) {
647 /* Only one action has to be possible. */
648 return FALSE;
650 } action_iterate_end;
652 /* No action enabled. */
653 return TRUE;
656 /* ACTION_ANY is handled above. */
657 fc_assert_ret_val(action_id_is_valid(action_id), FALSE);
659 action_enabler_list_iterate(action_enablers_for_action(action_id),
660 enabler) {
661 if (requirement_fulfilled_by_nation(pnation,
662 (is_target ? &enabler->target_reqs
663 : &enabler->actor_reqs))
664 && requirement_fulfilled_by_unit_type(unit_type_get(actor_unit),
665 &enabler->actor_reqs)) {
666 /* This nation doesn't block this action enabler. */
667 return FALSE;
669 } action_enabler_list_iterate_end;
671 return TRUE;
674 /**************************************************************************
675 Returns an explaination why punit can't perform the specified action
676 based on the current game state.
677 **************************************************************************/
678 static struct ane_expl *expl_act_not_enabl(struct unit *punit,
679 const int action_id,
680 const struct tile *target_tile,
681 const struct city *target_city,
682 const struct unit *target_unit)
684 struct player *must_war_player;
685 struct player *tgt_player = NULL;
686 struct ane_expl *explnat = fc_malloc(sizeof(struct ane_expl));
687 bool can_exist = can_unit_exist_at_tile(punit, unit_tile(punit));
689 if (action_id == ACTION_ANY) {
690 /* Find the target player of some actions. */
691 if (target_city) {
692 /* Individual city targets have the highest priority. */
693 tgt_player = city_owner(target_city);
694 } else if (target_unit) {
695 /* Individual unit targets have the next priority. */
696 tgt_player = unit_owner(target_unit);
698 } else {
699 /* Find the target player of this action. */
700 switch (action_id_get_target_kind(action_id)) {
701 case ATK_CITY:
702 tgt_player = city_owner(target_city);
703 break;
704 case ATK_UNIT:
705 tgt_player = unit_owner(target_unit);
706 break;
707 case ATK_COUNT:
708 fc_assert(action_id_get_target_kind(action_id) != ATK_COUNT);
709 break;
713 if ((!can_exist
714 && !utype_can_do_act_when_ustate(unit_type_get(punit), action_id,
715 USP_LIVABLE_TILE, FALSE))
716 || (can_exist
717 && !utype_can_do_act_when_ustate(unit_type_get(punit), action_id,
718 USP_LIVABLE_TILE, TRUE))) {
719 explnat->kind = ANEK_BAD_TERRAIN_ACT;
720 explnat->no_act_terrain = tile_terrain(unit_tile(punit));
721 } else if (punit
722 && does_terrain_block_action(action_id, FALSE,
723 punit, tile_terrain(unit_tile(punit)))) {
724 /* No action enabler allows acting against this terrain kind. */
725 explnat->kind = ANEK_BAD_TERRAIN_ACT;
726 explnat->no_act_terrain = tile_terrain(unit_tile(punit));
727 } else if (target_tile
728 && does_terrain_block_action(action_id, TRUE,
729 punit, tile_terrain(target_tile))) {
730 /* No action enabler allows acting against this terrain kind. */
731 explnat->kind = ANEK_BAD_TERRAIN_TGT;
732 explnat->no_act_terrain = tile_terrain(target_tile);
733 } else if (unit_transported(punit)
734 && !utype_can_do_act_when_ustate(unit_type_get(punit), action_id,
735 USP_TRANSPORTED, TRUE)) {
736 explnat->kind = ANEK_IS_TRANSPORTED;
737 } else if (!unit_transported(punit)
738 && !utype_can_do_act_when_ustate(unit_type_get(punit), action_id,
739 USP_TRANSPORTED, FALSE)) {
740 explnat->kind = ANEK_IS_NOT_TRANSPORTED;
741 } else if ((must_war_player = need_war_player(punit,
742 action_id,
743 target_tile,
744 target_city,
745 target_unit))) {
746 explnat->kind = ANEK_NO_WAR;
747 explnat->no_war_with = must_war_player;
748 } else if (tgt_player
749 && does_nation_block_action(action_id, TRUE,
750 punit, tgt_player->nation)) {
751 explnat->kind = ANEK_NATION_TGT;
752 explnat->no_act_nation = tgt_player->nation;
753 } else if (action_mp_full_makes_legal(punit, action_id)) {
754 explnat->kind = ANEK_LOW_MP;
755 } else {
756 explnat->kind = ANEK_UNKNOWN;
759 return explnat;
762 /**************************************************************************
763 Explain why punit can't perform any action at all based on its current
764 game state.
765 **************************************************************************/
766 static void explain_why_no_action_enabled(struct unit *punit,
767 const struct tile *target_tile,
768 const struct city *target_city,
769 const struct unit *target_unit)
771 struct player *pplayer = unit_owner(punit);
772 struct ane_expl *explnat = expl_act_not_enabl(punit, ACTION_ANY,
773 target_tile,
774 target_city, target_unit);
776 switch (explnat->kind) {
777 case ANEK_BAD_TERRAIN_ACT:
778 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
779 _("Unit cannot act from %s."),
780 terrain_name_translation(explnat->no_act_terrain));
781 break;
782 case ANEK_BAD_TERRAIN_TGT:
783 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
784 _("Unit cannot act against %s."),
785 terrain_name_translation(explnat->no_act_terrain));
786 break;
787 case ANEK_IS_TRANSPORTED:
788 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
789 _("This unit is being transported, and"
790 " so cannot act."));
791 break;
792 case ANEK_IS_NOT_TRANSPORTED:
793 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
794 _("This unit cannot act when it isn't being "
795 "transported."));
796 break;
797 case ANEK_NO_WAR:
798 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
799 _("You must declare war on %s first. Try using "
800 "the Nations report (F3)."),
801 player_name(explnat->no_war_with));
802 break;
803 case ANEK_NATION_TGT:
804 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
805 /* TRANS: ... Pirate ... */
806 _("This unit cannot act against %s targets."),
807 nation_adjective_translation(explnat->no_act_nation));
808 break;
809 case ANEK_LOW_MP:
810 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
811 _("This unit has too few moves left to act."));
812 break;
813 case ANEK_UNKNOWN:
814 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
815 _("No action possible."));
816 break;
819 free(explnat);
822 /**************************************************************************
823 Handle a query for what actions a unit may do.
825 MUST always send a reply so the client can move on in the queue. This
826 includes when the client give invalid input. That the acting unit died
827 before the server received a request for what actions it could do should
828 not stop the client from processing the next unit in the queue.
829 **************************************************************************/
830 void handle_unit_get_actions(struct connection *pc,
831 const int actor_unit_id,
832 const int target_unit_id_client,
833 const int target_city_id_client,
834 const int target_tile_id,
835 const bool disturb_player)
837 struct player *actor_player;
838 struct unit *actor_unit;
839 struct tile *target_tile;
840 struct act_prob probabilities[ACTION_COUNT];
842 struct unit *target_unit;
843 struct city *target_city;
845 /* No potentially legal action is known yet. If none is found the player
846 * should get an explanation. */
847 bool at_least_one_action = FALSE;
849 /* A target should only be sent if it is possible to act against it */
850 int target_city_id = IDENTITY_NUMBER_ZERO;
851 int target_unit_id = IDENTITY_NUMBER_ZERO;
853 actor_player = pc->playing;
854 actor_unit = game_unit_by_number(actor_unit_id);
855 target_tile = index_to_tile(target_tile_id);
857 /* Check if the request is valid. */
858 if (!target_tile || !actor_unit || !actor_player
859 || actor_unit->owner != actor_player) {
860 action_iterate(act) {
861 /* No probability can exist when the request is invalid. */
862 probabilities[act] = ACTPROB_NA;
863 } action_iterate_end;
865 dsend_packet_unit_actions(pc, actor_unit_id,
866 IDENTITY_NUMBER_ZERO, IDENTITY_NUMBER_ZERO,
867 target_tile_id,
868 disturb_player,
869 probabilities);
870 return;
873 /* Select the targets. */
875 if (target_unit_id_client == IDENTITY_NUMBER_ZERO) {
876 /* Find a new target unit. */
877 target_unit = tgt_unit(actor_unit, target_tile);
878 } else {
879 /* Prepare the client selected target unit. */
880 target_unit = game_unit_by_number(target_unit_id_client);
883 if (target_city_id_client == IDENTITY_NUMBER_ZERO) {
884 /* Find a new target city. */
885 target_city = tgt_city(actor_unit, target_tile);
886 } else {
887 /* Prepare the client selected target city. */
888 target_city = game_city_by_number(target_city_id_client);
891 /* Find out what can be done to the targets. */
893 /* Set the probability for the actions. */
894 action_iterate(act) {
895 if (action_id_get_actor_kind(act) != AAK_UNIT) {
896 /* Not relevant. */
897 probabilities[act] = ACTPROB_NA;
898 continue;
901 if (target_city && action_id_get_target_kind(act) == ATK_CITY) {
902 probabilities[act] = action_prob_vs_city(actor_unit, act,
903 target_city);
904 } else if (target_unit && action_id_get_target_kind(act) == ATK_UNIT) {
905 probabilities[act] = action_prob_vs_unit(actor_unit, act,
906 target_unit);
907 } else {
908 probabilities[act] = ACTPROB_IMPOSSIBLE;
910 } action_iterate_end;
912 /* Analyze the probabilities. Decide what targets to send and if an
913 * explanation is needed. */
914 action_iterate(act) {
915 if (action_prob_possible(probabilities[act])) {
916 /* An action can be done. No need to explain why no action can be
917 * done. */
918 at_least_one_action = TRUE;
920 switch (action_id_get_target_kind(act)) {
921 case ATK_CITY:
922 /* The city should be sent as a target since it is possible to act
923 * against it. */
924 fc_assert(target_city != NULL);
925 target_city_id = target_city->id;
926 break;
927 case ATK_UNIT:
928 /* The unit should be sent as a target since it is possible to act
929 * against it. */
930 fc_assert(target_unit != NULL);
931 target_unit_id = target_unit->id;
932 break;
933 case ATK_COUNT:
934 fc_assert_msg(action_id_get_target_kind(act) != ATK_COUNT,
935 "Invalid action target kind.");
936 break;
939 if (target_city_id != IDENTITY_NUMBER_ZERO
940 && target_unit != IDENTITY_NUMBER_ZERO) {
941 /* No need to find out more. */
942 break;
945 } action_iterate_end;
947 /* Send possible actions and targets. */
948 dsend_packet_unit_actions(pc,
949 actor_unit_id, target_unit_id, target_city_id,
950 target_tile_id,
951 disturb_player,
952 probabilities);
954 if (disturb_player && !at_least_one_action) {
955 /* The user should get an explanation why no action is possible. */
956 explain_why_no_action_enabled(actor_unit,
957 target_tile, target_city, target_unit);
961 /**************************************************************************
962 Tell the client that the action it requested is illegal. This can be
963 caused by the player (and therefore the client) not knowing that some
964 condition of an action no longer is true.
965 **************************************************************************/
966 static void illegal_action(struct player *pplayer,
967 struct unit *actor,
968 enum gen_action stopped_action,
969 struct player *tgt_player,
970 const struct tile *target_tile,
971 const struct city *target_city,
972 const struct unit *target_unit)
974 struct ane_expl *explnat;
976 /* The mistake may have a cost. */
977 actor->moves_left = MAX(0, actor->moves_left
978 - get_target_bonus_effects(NULL,
979 unit_owner(actor),
980 tgt_player,
981 NULL,
982 NULL,
983 NULL,
984 actor,
985 unit_type_get(actor),
986 NULL,
987 NULL,
988 EFT_ILLEGAL_ACTION_MOVE_COST));
990 send_unit_info(NULL, actor);
992 /* Explain why the action was illegal. */
993 explnat = expl_act_not_enabl(actor, stopped_action,
994 target_tile, target_city, target_unit);
995 switch (explnat->kind) {
996 case ANEK_BAD_TERRAIN_ACT:
997 notify_player(pplayer, unit_tile(actor),
998 E_UNIT_ILLEGAL_ACTION, ftc_server,
999 _("Your %s can't do %s from %s."),
1000 unit_name_translation(actor),
1001 action_get_ui_name(stopped_action),
1002 terrain_name_translation(explnat->no_act_terrain));
1003 break;
1004 case ANEK_BAD_TERRAIN_TGT:
1005 notify_player(pplayer, unit_tile(actor),
1006 E_UNIT_ILLEGAL_ACTION, ftc_server,
1007 _("Your %s can't do %s to %s."),
1008 unit_name_translation(actor),
1009 action_get_ui_name(stopped_action),
1010 terrain_name_translation(explnat->no_act_terrain));
1011 break;
1012 case ANEK_IS_TRANSPORTED:
1013 notify_player(pplayer, unit_tile(actor),
1014 E_UNIT_ILLEGAL_ACTION, ftc_server,
1015 _("Your %s can't do %s while being transported."),
1016 unit_name_translation(actor),
1017 action_get_ui_name(stopped_action));
1018 break;
1019 case ANEK_IS_NOT_TRANSPORTED:
1020 notify_player(pplayer, unit_tile(actor),
1021 E_UNIT_ILLEGAL_ACTION, ftc_server,
1022 _("Your %s can't do %s while not being transported."),
1023 unit_name_translation(actor),
1024 action_get_ui_name(stopped_action));
1025 break;
1026 case ANEK_NO_WAR:
1027 notify_player(pplayer, unit_tile(actor),
1028 E_UNIT_ILLEGAL_ACTION, ftc_server,
1029 _("Your %s can't do %s while you"
1030 " aren't at war with %s."),
1031 unit_name_translation(actor),
1032 action_get_ui_name(stopped_action),
1033 player_name(explnat->no_war_with));
1034 break;
1035 case ANEK_NATION_TGT:
1036 notify_player(pplayer, unit_tile(actor),
1037 E_UNIT_ILLEGAL_ACTION, ftc_server,
1038 /* TRANS: Riflemen... Expel Unit... Pirate... Migrants */
1039 _("Your %s can't do %s to %s %s."),
1040 unit_name_translation(actor),
1041 action_get_ui_name(stopped_action),
1042 nation_adjective_translation(explnat->no_act_nation),
1043 action_target_kind_translated_name(
1044 action_id_get_target_kind(stopped_action)));
1045 break;
1046 case ANEK_LOW_MP:
1047 notify_player(pplayer, unit_tile(actor),
1048 E_UNIT_ILLEGAL_ACTION, ftc_server,
1049 _("Your %s has too few moves left to %s."),
1050 unit_name_translation(actor),
1051 action_get_ui_name(stopped_action));
1052 break;
1053 case ANEK_UNKNOWN:
1054 notify_player(pplayer, unit_tile(actor),
1055 E_UNIT_ILLEGAL_ACTION, ftc_server,
1056 _("Your %s was unable to %s."),
1057 unit_name_translation(actor),
1058 action_get_ui_name(stopped_action));
1059 break;
1062 free(explnat);
1065 /**************************************************************************
1066 Inform the client that something went wrong during a unit diplomat query
1067 **************************************************************************/
1068 static void unit_query_impossible(struct connection *pc,
1069 const int diplomat_id,
1070 const int target_id)
1072 dsend_packet_unit_action_answer(pc,
1073 diplomat_id, target_id,
1075 ACTION_COUNT);
1078 /**************************************************************************
1079 Tell the client the cost of bribing a unit, inciting a revolt, or
1080 any other parameters needed for action.
1082 Only send result back to the requesting connection, not all
1083 connections for that player.
1084 **************************************************************************/
1085 void handle_unit_action_query(struct connection *pc,
1086 const int actor_id,
1087 const int target_id,
1088 const enum gen_action action_type)
1090 struct player *pplayer = pc->playing;
1091 struct unit *pactor = player_unit_by_number(pplayer, actor_id);
1092 struct unit *punit = game_unit_by_number(target_id);
1093 struct city *pcity = game_city_by_number(target_id);
1095 if (!action_id_is_valid(action_type)) {
1096 /* Non existing action */
1097 log_error("handle_unit_action_query() the action %d doesn't exist.",
1098 action_type);
1100 unit_query_impossible(pc, actor_id, target_id);
1101 return;
1104 if (NULL == pactor) {
1105 /* Probably died or bribed. */
1106 log_verbose("handle_unit_action_query() invalid actor %d",
1107 actor_id);
1108 unit_query_impossible(pc, actor_id, target_id);
1109 return;
1112 if (!utype_may_act_at_all(unit_type_get(pactor))) {
1113 /* Shouldn't happen */
1114 log_error("handle_unit_action_query() %s (%d) is not an actor",
1115 unit_rule_name(pactor), actor_id);
1116 unit_query_impossible(pc, actor_id, target_id);
1117 return;
1120 switch (action_type) {
1121 case ACTION_SPY_BRIBE_UNIT:
1122 if (punit) {
1123 if (is_action_enabled_unit_on_unit(action_type,
1124 pactor, punit)) {
1125 dsend_packet_unit_action_answer(pc,
1126 actor_id, target_id,
1127 unit_bribe_cost(punit, pplayer),
1128 action_type);
1129 } else {
1130 illegal_action(pplayer, pactor, action_type, unit_owner(punit),
1131 NULL, NULL, punit);
1132 unit_query_impossible(pc, actor_id, target_id);
1133 return;
1136 break;
1137 case ACTION_SPY_INCITE_CITY:
1138 if (pcity) {
1139 if (is_action_enabled_unit_on_city(action_type,
1140 pactor, pcity)) {
1141 dsend_packet_unit_action_answer(pc,
1142 actor_id, target_id,
1143 city_incite_cost(pplayer, pcity),
1144 action_type);
1145 } else {
1146 illegal_action(pplayer, pactor, action_type, city_owner(pcity),
1147 NULL, pcity, NULL);
1148 unit_query_impossible(pc, actor_id, target_id);
1149 return;
1152 break;
1153 case ACTION_SPY_TARGETED_SABOTAGE_CITY:
1154 if (pcity) {
1155 if (is_action_enabled_unit_on_city(action_type,
1156 pactor, pcity)) {
1157 spy_send_sabotage_list(pc, pactor, pcity);
1158 } else {
1159 illegal_action(pplayer, pactor, action_type, city_owner(pcity),
1160 NULL, pcity, NULL);
1161 unit_query_impossible(pc, actor_id, target_id);
1162 return;
1165 break;
1166 default:
1167 unit_query_impossible(pc, actor_id, target_id);
1168 return;
1172 /**************************************************************************
1173 Handle a request to do an action.
1174 **************************************************************************/
1175 void handle_unit_do_action(struct player *pplayer,
1176 const int actor_id,
1177 const int target_id,
1178 const int value,
1179 const enum gen_action action_type)
1181 struct unit *actor_unit = player_unit_by_number(pplayer, actor_id);
1182 struct unit *punit = game_unit_by_number(target_id);
1183 struct city *pcity = game_city_by_number(target_id);
1184 struct tile *target_tile = index_to_tile(target_id);
1186 if (!(action_type == ACTION_COUNT
1187 || action_id_is_valid(action_type))) {
1188 /* Non existing action */
1189 log_error("unit_perform_action() the action %d doesn't exist.",
1190 action_type);
1192 return;
1195 if (NULL == actor_unit) {
1196 /* Being asked to unqueue a "spent" unit because the client haven't
1197 * been told that it's gone is expected. */
1198 if (!(action_type == ACTION_COUNT && value == ACTSIG_UNQUEUE)) {
1199 /* Probably died or bribed. */
1200 log_verbose("handle_unit_do_action() invalid actor %d",
1201 actor_id);
1204 return;
1207 if (!utype_may_act_at_all(unit_type_get(actor_unit))) {
1208 /* Shouldn't happen */
1209 log_error("handle_unit_do_action() %s (%d) is not an actor unit",
1210 unit_rule_name(actor_unit), actor_id);
1211 return;
1214 if (!unit_can_do_action_now(actor_unit)) {
1215 /* Action not possible due to unitwaittime setting. */
1216 return;
1219 #define ACTION_STARTED_UNIT_CITY(action, actor, target) \
1220 script_server_signal_emit("action_started_unit_city", 3, \
1221 API_TYPE_ACTION, action_by_number(action), \
1222 API_TYPE_UNIT, actor, \
1223 API_TYPE_CITY, target); \
1224 if (!actor || !unit_is_alive(actor_id)) { \
1225 /* Actor unit was destroyed during pre action Lua. */ \
1226 return; \
1228 if (!target || !city_exist(target_id)) { \
1229 /* Target city was destroyed during pre action Lua. */ \
1230 return; \
1233 #define ACTION_STARTED_UNIT_UNIT(action, actor, target) \
1234 script_server_signal_emit("action_started_unit_unit", 3, \
1235 API_TYPE_ACTION, action_by_number(action), \
1236 API_TYPE_UNIT, actor, \
1237 API_TYPE_UNIT, target); \
1238 if (!actor || !unit_is_alive(actor_id)) { \
1239 /* Actor unit was destroyed during pre action Lua. */ \
1240 return; \
1242 if (!target || !unit_is_alive(target_id)) { \
1243 /* Target unit was destroyed during pre action Lua. */ \
1244 return; \
1247 switch(action_type) {
1248 case ACTION_SPY_BRIBE_UNIT:
1249 if (punit) {
1250 if (is_action_enabled_unit_on_unit(action_type,
1251 actor_unit, punit)) {
1252 ACTION_STARTED_UNIT_UNIT(action_type, actor_unit, punit);
1254 diplomat_bribe(pplayer, actor_unit, punit);
1255 } else {
1256 illegal_action(pplayer, actor_unit, action_type,
1257 unit_owner(punit), NULL, NULL, punit);
1260 break;
1261 case ACTION_SPY_SABOTAGE_UNIT:
1262 if (punit) {
1263 if (is_action_enabled_unit_on_unit(action_type,
1264 actor_unit, punit)) {
1265 ACTION_STARTED_UNIT_UNIT(action_type, actor_unit, punit);
1267 spy_sabotage_unit(pplayer, actor_unit, punit);
1268 } else {
1269 illegal_action(pplayer, actor_unit, action_type,
1270 unit_owner(punit), NULL, NULL, punit);
1273 break;
1274 case ACTION_SPY_SABOTAGE_CITY:
1275 if (pcity) {
1276 if (is_action_enabled_unit_on_city(action_type, actor_unit, pcity)) {
1277 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1279 diplomat_sabotage(pplayer, actor_unit, pcity, B_LAST,
1280 action_type);
1281 } else {
1282 illegal_action(pplayer, actor_unit, action_type,
1283 city_owner(pcity), NULL, pcity, NULL);
1286 break;
1287 case ACTION_SPY_TARGETED_SABOTAGE_CITY:
1288 if (pcity) {
1289 if (is_action_enabled_unit_on_city(action_type, actor_unit, pcity)) {
1290 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1292 /* packet value is improvement ID + 1 (or some special codes) */
1293 diplomat_sabotage(pplayer, actor_unit, pcity, value - 1,
1294 action_type);
1295 } else {
1296 illegal_action(pplayer, actor_unit, action_type,
1297 city_owner(pcity), NULL, pcity, NULL);
1300 break;
1301 case ACTION_SPY_POISON:
1302 if (pcity) {
1303 if (is_action_enabled_unit_on_city(action_type,
1304 actor_unit, pcity)) {
1305 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1307 spy_poison(pplayer, actor_unit, pcity);
1308 } else {
1309 illegal_action(pplayer, actor_unit, action_type,
1310 city_owner(pcity), NULL, pcity, NULL);
1313 break;
1314 case ACTION_SPY_INVESTIGATE_CITY:
1315 if (pcity) {
1316 if (is_action_enabled_unit_on_city(action_type,
1317 actor_unit, pcity)) {
1318 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1320 diplomat_investigate(pplayer, actor_unit, pcity);
1321 } else {
1322 illegal_action(pplayer, actor_unit, action_type,
1323 city_owner(pcity), NULL, pcity, NULL);
1326 break;
1327 case ACTION_ESTABLISH_EMBASSY:
1328 if (pcity) {
1329 if (is_action_enabled_unit_on_city(action_type,
1330 actor_unit, pcity)) {
1331 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1333 diplomat_embassy(pplayer, actor_unit, pcity);
1334 } else {
1335 illegal_action(pplayer, actor_unit, action_type,
1336 city_owner(pcity), NULL, pcity, NULL);
1339 break;
1340 case ACTION_SPY_INCITE_CITY:
1341 if (pcity) {
1342 if (is_action_enabled_unit_on_city(action_type,
1343 actor_unit, pcity)) {
1344 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1346 diplomat_incite(pplayer, actor_unit, pcity);
1347 } else {
1348 illegal_action(pplayer, actor_unit, action_type,
1349 city_owner(pcity), NULL, pcity, NULL);
1352 break;
1353 case ACTION_SPY_STEAL_TECH:
1354 if (pcity) {
1355 if (is_action_enabled_unit_on_city(action_type,
1356 actor_unit, pcity)) {
1357 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1359 /* packet value is technology ID (or some special codes) */
1360 diplomat_get_tech(pplayer, actor_unit, pcity, A_UNSET,
1361 action_type);
1362 } else {
1363 illegal_action(pplayer, actor_unit, action_type,
1364 city_owner(pcity), NULL, pcity, NULL);
1367 break;
1368 case ACTION_SPY_TARGETED_STEAL_TECH:
1369 if (pcity) {
1370 if (is_action_enabled_unit_on_city(action_type,
1371 actor_unit, pcity)) {
1372 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1374 /* packet value is technology ID (or some special codes) */
1375 diplomat_get_tech(pplayer, actor_unit, pcity, value,
1376 action_type);
1377 } else {
1378 illegal_action(pplayer, actor_unit, action_type,
1379 city_owner(pcity), NULL, pcity, NULL);
1382 break;
1383 case ACTION_SPY_STEAL_GOLD:
1384 if (pcity) {
1385 if (is_action_enabled_unit_on_city(action_type,
1386 actor_unit, pcity)) {
1387 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1389 spy_steal_gold(pplayer, actor_unit, pcity);
1390 } else {
1391 illegal_action(pplayer, actor_unit, action_type,
1392 city_owner(pcity), NULL, pcity, NULL);
1395 break;
1396 case ACTION_TRADE_ROUTE:
1397 if (pcity) {
1398 if (is_action_enabled_unit_on_city(action_type,
1399 actor_unit, pcity)) {
1400 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1402 do_unit_establish_trade(pplayer, actor_unit, pcity,
1403 TRUE);
1404 } else {
1405 illegal_action(pplayer, actor_unit, action_type,
1406 city_owner(pcity), NULL, pcity, NULL);
1409 break;
1410 case ACTION_MARKETPLACE:
1411 if (pcity) {
1412 if (is_action_enabled_unit_on_city(action_type,
1413 actor_unit, pcity)) {
1414 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1416 do_unit_establish_trade(pplayer, actor_unit, pcity,
1417 FALSE);
1418 } else {
1419 illegal_action(pplayer, actor_unit, action_type,
1420 city_owner(pcity), NULL, pcity, NULL);
1423 break;
1424 case ACTION_HELP_WONDER:
1425 if (pcity) {
1426 if (is_action_enabled_unit_on_city(action_type,
1427 actor_unit, pcity)) {
1428 ACTION_STARTED_UNIT_CITY(action_type, actor_unit, pcity);
1430 do_unit_help_build_wonder(pplayer,
1431 actor_unit, pcity);
1432 } else {
1433 illegal_action(pplayer, actor_unit, action_type,
1434 city_owner(pcity), NULL, pcity, NULL);
1437 break;
1438 case ACTION_COUNT:
1439 switch ((enum action_proto_signal)value) {
1440 case ACTSIG_QUEUE:
1441 actor_unit->action_decision_want = ACT_DEC_ACTIVE;
1442 actor_unit->action_decision_tile = target_tile;
1444 /* Let the client know that this unit needs the player to decide
1445 * what to do. */
1446 send_unit_info(player_reply_dest(pplayer), actor_unit);
1448 break;
1449 case ACTSIG_UNQUEUE:
1450 /* Delete the reminder for the client to ask the server about what
1451 * actions the unit can perform against a certain target tile.
1452 * Action decision state can be set by the server it self too. */
1454 actor_unit->action_decision_want = ACT_DEC_NOTHING;
1455 actor_unit->action_decision_tile = NULL;
1457 /* Let the client know that this unit no longer needs the player to
1458 * decide what to do. */
1459 send_unit_info(player_reply_dest(pplayer), actor_unit);
1461 break;
1463 break;
1467 /**************************************************************************
1468 Transfer a unit from one city (and possibly player) to another.
1469 If 'rehome' is not set, only change the player which owns the unit
1470 (the new owner is new_pcity's owner). Otherwise the new unit will be
1471 given a homecity, even if it was homeless before.
1472 This new homecity must be valid for this unit.
1473 **************************************************************************/
1474 void unit_change_homecity_handling(struct unit *punit, struct city *new_pcity,
1475 bool rehome)
1477 struct city *old_pcity = game_city_by_number(punit->homecity);
1478 struct player *old_owner = unit_owner(punit);
1479 struct player *new_owner = city_owner(new_pcity);
1481 /* Calling this function when new_pcity is same as old_pcity should
1482 * be safe with current implementation, but it is not meant to
1483 * be used that way. */
1484 fc_assert_ret(new_pcity != old_pcity);
1486 /* If 'rehome' is not set, this function should only be used to change
1487 * which player owns the unit */
1488 fc_assert_ret(rehome || new_owner != old_owner);
1490 if (old_owner != new_owner) {
1491 struct city *pcity = tile_city(punit->tile);
1493 fc_assert(!utype_player_already_has_this_unique(new_owner,
1494 unit_type_get(punit)));
1496 vision_clear_sight(punit->server.vision);
1497 vision_free(punit->server.vision);
1499 if (pcity != NULL
1500 && !can_player_see_units_in_city(old_owner, pcity)) {
1501 /* Special case when city is being transferred. At this point city
1502 * itself has changed owner, so it's enemy city now that old owner
1503 * cannot see inside. All the normal methods of removing transferred
1504 * unit from previous owner's client think that there's no need to
1505 * remove unit as client shouldn't have it in first place. */
1506 unit_goes_out_of_sight(old_owner, punit);
1509 /* Remove AI control of the old owner. */
1510 CALL_PLR_AI_FUNC(unit_lost, old_owner, punit);
1512 unit_list_remove(old_owner->units, punit);
1513 unit_list_prepend(new_owner->units, punit);
1514 punit->owner = new_owner;
1516 /* Activate AI control of the new owner. */
1517 CALL_PLR_AI_FUNC(unit_got, new_owner, punit);
1519 punit->server.vision = vision_new(new_owner, unit_tile(punit));
1520 unit_refresh_vision(punit);
1523 if (rehome) {
1524 fc_assert(!unit_has_type_flag(punit, UTYF_NOHOME));
1526 /* Remove from old city first and add to new city only after that.
1527 * This is more robust in case old_city == new_city (currently
1528 * prohibited by fc_assert in the beginning of the function).
1530 if (old_pcity) {
1531 /* Even if unit is dead, we have to unlink unit pointer (punit). */
1532 unit_list_remove(old_pcity->units_supported, punit);
1533 /* update unit upkeep */
1534 city_units_upkeep(old_pcity);
1537 unit_list_prepend(new_pcity->units_supported, punit);
1539 /* update unit upkeep */
1540 city_units_upkeep(new_pcity);
1542 punit->homecity = new_pcity->id;
1545 if (!can_unit_continue_current_activity(punit)) {
1546 /* This is mainly for cases where unit owner changes to one not knowing
1547 * Railroad tech when unit is already building railroad. */
1548 set_unit_activity(punit, ACTIVITY_IDLE);
1551 /* Send info to players and observers. */
1552 send_unit_info(NULL, punit);
1554 city_refresh(new_pcity);
1555 send_city_info(new_owner, new_pcity);
1557 if (old_pcity) {
1558 fc_assert(city_owner(old_pcity) == old_owner);
1559 city_refresh(old_pcity);
1560 send_city_info(old_owner, old_pcity);
1563 fc_assert(unit_owner(punit) == city_owner(new_pcity));
1566 /**************************************************************************
1567 Change a unit's home city. The unit must be present in the city to
1568 be set as its new home city.
1569 **************************************************************************/
1570 void handle_unit_change_homecity(struct player *pplayer, int unit_id,
1571 int city_id)
1573 struct unit *punit = player_unit_by_number(pplayer, unit_id);
1574 struct city *pcity = player_city_by_number(pplayer, city_id);
1576 if (NULL == punit) {
1577 /* Probably died or bribed. */
1578 log_verbose("handle_unit_change_homecity() invalid unit %d", unit_id);
1579 return;
1582 if (pcity && can_unit_change_homecity_to(punit, pcity)) {
1583 unit_change_homecity_handling(punit, pcity, TRUE);
1587 /**************************************************************************
1588 Disband a unit. If its in a city, add 1/2 of the worth of the unit
1589 to the city's shield stock for the current production.
1590 **************************************************************************/
1591 void handle_unit_disband(struct player *pplayer, int unit_id)
1593 struct city *pcity;
1594 struct unit *punit = player_unit_by_number(pplayer, unit_id);
1596 if (NULL == punit) {
1597 /* Probably died or bribed. */
1598 log_verbose("handle_unit_disband() invalid unit %d", unit_id);
1599 return;
1602 if (unit_has_type_flag(punit, UTYF_UNDISBANDABLE)) {
1603 /* refuse to kill ourselves */
1604 notify_player(unit_owner(punit), unit_tile(punit),
1605 E_BAD_COMMAND, ftc_server,
1606 _("%s refuses to disband!"),
1607 unit_link(punit));
1608 return;
1611 pcity = tile_city(unit_tile(punit));
1612 if (pcity) {
1613 /* If you disband inside a city, it gives some shields to that city.
1615 * Note: Nowadays it's possible to disband unit in allied city and
1616 * your ally receives those shields. Should it be like this? Why not?
1617 * That's why we must use city_owner instead of pplayer -- Zamar */
1619 if (unit_can_do_action(punit, ACTION_HELP_WONDER)) {
1620 /* Count this just like a caravan that was added to a wonder.
1621 * However don't actually give the city the extra shields unless
1622 * they are building a wonder (but switching to a wonder later in
1623 * the turn will give the extra shields back). */
1624 pcity->caravan_shields += unit_build_shield_cost(punit);
1625 if (is_action_enabled_unit_on_city(ACTION_HELP_WONDER,
1626 punit, pcity)) {
1627 pcity->shield_stock += unit_build_shield_cost(punit);
1628 } else {
1629 pcity->shield_stock += unit_disband_shields(punit);
1631 } else {
1632 pcity->shield_stock += unit_disband_shields(punit);
1633 /* If we change production later at this turn. No penalty is added. */
1634 pcity->disbanded_shields += unit_disband_shields(punit);
1637 send_city_info(city_owner(pcity), pcity);
1640 wipe_unit(punit, ULR_DISBANDED, NULL);
1643 /**************************************************************************
1644 This function assumes that there is a valid city at punit->(x,y) for
1645 certain values of test_add_build_or_city. It should only be called
1646 after a call to unit_add_build_city_result, which does the
1647 consistency checking.
1648 **************************************************************************/
1649 void city_add_or_build_error(struct player *pplayer, struct unit *punit,
1650 enum unit_add_build_city_result res)
1652 /* Given that res came from unit_add_or_build_city_test(), pcity will
1653 * be non-null for all required status values. */
1654 struct tile *ptile = unit_tile(punit);
1655 struct city *pcity = tile_city(ptile);
1657 switch (res) {
1658 case UAB_BAD_CITY_TERRAIN:
1659 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1660 /* TRANS: <tile-terrain>. */
1661 _("Can't build a city on %s."),
1662 terrain_name_translation(tile_terrain(ptile)));
1663 break;
1664 case UAB_BAD_UNIT_TERRAIN:
1665 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1666 /* TRANS: <unit> ... <tile-terrain>. */
1667 _("%s can't build a city on %s."), unit_link(punit),
1668 terrain_name_translation(tile_terrain(ptile)));
1669 break;
1670 case UAB_BAD_BORDERS:
1671 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1672 _("Can't build a city inside foreign borders."));
1673 break;
1674 case UAB_NO_MIN_DIST:
1675 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1676 _("Can't place a city there because another city is too "
1677 "close."));
1678 break;
1679 case UAB_NOT_BUILD_UNIT:
1681 struct astring astr = ASTRING_INIT;
1683 if (game.scenario.prevent_new_cities) {
1684 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1685 _("Cities cannot be built in this scenario."));
1686 } else if (role_units_translations(&astr, UTYF_CITIES, TRUE)) {
1687 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1688 /* TRANS: %s is list of units separated by "or". */
1689 _("Only %s can build a city."), astr_str(&astr));
1690 astr_free(&astr);
1691 } else {
1692 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1693 _("Can't build a city."));
1696 break;
1697 case UAB_NOT_ADDABLE_UNIT:
1699 struct astring astr = ASTRING_INIT;
1701 if (role_units_translations(&astr, UTYF_ADD_TO_CITY, TRUE)) {
1702 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1703 /* TRANS: %s is list of units separated by "or". */
1704 _("Only %s can add to a city."), astr_str(&astr));
1705 astr_free(&astr);
1706 } else {
1707 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1708 _("Can't add to a city."));
1711 break;
1712 case UAB_NO_MOVES_ADD:
1713 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1714 _("%s unit has no moves left to add to %s."),
1715 unit_link(punit), city_link(pcity));
1716 break;
1717 case UAB_NO_MOVES_BUILD:
1718 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1719 _("%s unit has no moves left to build city."),
1720 unit_link(punit));
1721 break;
1722 case UAB_NOT_OWNER:
1723 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1724 /* TRANS: <city> is owned by <nation>, cannot add <unit>. */
1725 _("%s is owned by %s, cannot add %s."),
1726 city_link(pcity),
1727 nation_plural_for_player(city_owner(pcity)),
1728 unit_link(punit));
1729 break;
1730 case UAB_TOO_BIG:
1731 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1732 _("%s is too big to add %s."),
1733 city_link(pcity), unit_link(punit));
1734 break;
1735 case UAB_NO_SPACE:
1736 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1737 _("%s needs an improvement to grow, so "
1738 "you cannot add %s."),
1739 city_link(pcity), unit_link(punit));
1740 break;
1741 case UAB_BUILD_OK:
1742 case UAB_ADD_OK:
1743 /* Shouldn't happen */
1744 log_error("Cannot add %s to %s for unknown reason (%d)",
1745 unit_rule_name(punit), city_name_get(pcity), res);
1746 notify_player(pplayer, ptile, E_BAD_COMMAND, ftc_server,
1747 _("Can't add %s to %s."),
1748 unit_link(punit), city_link(pcity));
1749 break;
1753 /**************************************************************************
1754 This function assumes that there is a valid city at punit->(x,y) It
1755 should only be called after a call to a function like
1756 test_unit_add_or_build_city, which does the checking.
1757 **************************************************************************/
1758 static void city_add_unit(struct player *pplayer, struct unit *punit)
1760 struct city *pcity = tile_city(unit_tile(punit));
1761 int amount = unit_pop_value(punit);
1763 fc_assert_ret(amount > 0);
1765 script_server_signal_emit("city_size_change", 3,
1766 API_TYPE_CITY, pcity,
1767 API_TYPE_INT, amount,
1768 API_TYPE_STRING, "unit_added");
1769 city_size_add(pcity, amount);
1770 /* Make the new people something, otherwise city fails the checks */
1771 pcity->specialists[DEFAULT_SPECIALIST] += amount;
1772 citizens_update(pcity, unit_nationality(punit));
1773 /* Refresh the city data. */
1774 city_refresh(pcity);
1775 notify_player(pplayer, city_tile(pcity), E_CITY_BUILD, ftc_server,
1776 _("%s added to aid %s in growing."),
1777 unit_tile_link(punit),
1778 city_link(pcity));
1779 wipe_unit(punit, ULR_USED, NULL);
1781 sanity_check_city(pcity);
1783 send_city_info(NULL, pcity);
1786 /**************************************************************************
1787 This function assumes a certain level of consistency checking: There
1788 is no city under punit->(x,y), and that location is a valid one on
1789 which to build a city. It should only be called after a call to a
1790 function like test_unit_add_or_build_city(), which does the checking.
1791 **************************************************************************/
1792 static void city_build(struct player *pplayer, struct unit *punit,
1793 const char *name)
1795 char message[1024];
1796 int size;
1797 struct player *nationality;
1799 if (!is_allowed_city_name(pplayer, name, message, sizeof(message))) {
1800 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
1801 "%s", message);
1802 return;
1805 nationality = unit_nationality(punit);
1807 create_city(pplayer, unit_tile(punit), name, nationality);
1808 size = unit_type_get(punit)->city_size;
1809 if (size > 1) {
1810 struct city *pcity = tile_city(unit_tile(punit));
1812 fc_assert_ret(pcity != NULL);
1814 city_change_size(pcity, size, nationality, NULL);
1816 wipe_unit(punit, ULR_USED, NULL);
1819 /**************************************************************************
1820 Try to build city.
1821 Return value tells if request was sane. It can be TRUE even if city
1822 building failed, as long as the reason was not bad request.
1823 **************************************************************************/
1824 bool unit_build_city(struct player *pplayer, struct unit *punit,
1825 const char *name)
1827 enum unit_add_build_city_result res;
1829 if (NULL == punit) {
1830 /* Probably died or bribed. */
1831 log_verbose("unit_build_city() invalid unit.");
1832 return FALSE;
1835 if (!unit_can_do_action_now(punit)) {
1836 /* Building a city not possible due to unitwaittime setting. */
1837 return FALSE;
1840 res = unit_add_or_build_city_test(punit);
1842 if (UAB_BUILD_OK == res) {
1843 city_build(pplayer, punit, name);
1844 } else if (UAB_ADD_OK == res) {
1845 city_add_unit(pplayer, punit);
1846 } else {
1847 city_add_or_build_error(pplayer, punit, res);
1848 if (res != UAB_NO_MIN_DIST) {
1849 return FALSE;
1853 return TRUE;
1856 /**************************************************************************
1857 Handle city building request. Can result in adding to existing city
1858 also.
1859 **************************************************************************/
1860 void handle_unit_build_city(struct player *pplayer, int unit_id,
1861 const char *name)
1863 unit_build_city(pplayer, player_unit_by_number(pplayer, unit_id), name);
1866 /**************************************************************************
1867 Handle change in unit activity.
1868 **************************************************************************/
1869 static void handle_unit_change_activity_real(struct player *pplayer,
1870 int unit_id,
1871 enum unit_activity activity,
1872 struct extra_type *activity_target)
1874 struct unit *punit = player_unit_by_number(pplayer, unit_id);
1876 if (NULL == punit) {
1877 /* Probably died or bribed. */
1878 log_verbose("handle_unit_change_activity() invalid unit %d", unit_id);
1879 return;
1882 if (punit->activity == activity
1883 && punit->activity_target == activity_target
1884 && !punit->ai_controlled) {
1885 /* Treat change in ai.control as change in activity, so
1886 * idle autosettlers behave correctly when selected --dwp
1888 return;
1891 /* Remove city spot reservations for AI settlers on city founding
1892 * mission, before goto_tile reset. */
1893 if (punit->server.adv->task != AUT_NONE) {
1894 adv_unit_new_task(punit, AUT_NONE, NULL);
1897 punit->ai_controlled = FALSE;
1898 punit->goto_tile = NULL;
1900 if (activity == ACTIVITY_GOTO) {
1901 /* Don't permit a client to set a unit's activity to ACTIVITY_GOTO.
1902 * Setting ACTIVITY_GOTO from the client results in a unit indicating
1903 * it is going somewhere while it is standing still. The appearance of
1904 * the unit doing something can trick the user to not make use of it.
1906 * Handled here because adv_follow_path() uses unit_activity_handling()
1907 * to set a unit's activity to ACTIVITY_GOTO. */
1908 return;
1911 /* The activity can now be set. */
1912 unit_activity_handling_targeted(punit, activity, &activity_target);
1914 if (activity == ACTIVITY_EXPLORE) {
1915 /* Exploring is handled here explicitly, since the player expects to
1916 * see an immediate response from setting a unit to auto-explore.
1917 * Handling it deeper in the code leads to some tricky recursive loops -
1918 * see PR#2631. */
1919 if (punit->moves_left > 0) {
1920 do_explore(punit);
1925 /**************************************************************************
1926 Handle change in unit activity.
1927 **************************************************************************/
1928 void handle_unit_change_activity(struct player *pplayer, int unit_id,
1929 enum unit_activity activity,
1930 int target_id)
1932 struct extra_type *activity_target;
1934 if (target_id < 0 || target_id >= game.control.num_extra_types) {
1935 activity_target = NULL;
1936 } else {
1937 activity_target = extra_by_number(target_id);
1940 handle_unit_change_activity_real(pplayer, unit_id, activity, activity_target);
1943 /**************************************************************************
1944 Make sure everyone who can see combat does.
1945 **************************************************************************/
1946 static void see_combat(struct unit *pattacker, struct unit *pdefender)
1948 struct packet_unit_short_info unit_att_short_packet, unit_def_short_packet;
1949 struct packet_unit_info unit_att_packet, unit_def_packet;
1952 * Special case for attacking/defending:
1954 * Normally the player doesn't get the information about the units inside a
1955 * city. However for attacking/defending the player has to know the unit of
1956 * the other side. After the combat a remove_unit packet will be sent
1957 * to the client to tidy up.
1959 * Note these packets must be sent out before unit_versus_unit is called,
1960 * so that the original unit stats (HP) will be sent.
1962 package_short_unit(pattacker, &unit_att_short_packet,
1963 UNIT_INFO_IDENTITY, 0);
1964 package_short_unit(pdefender, &unit_def_short_packet,
1965 UNIT_INFO_IDENTITY, 0);
1966 package_unit(pattacker, &unit_att_packet);
1967 package_unit(pdefender, &unit_def_packet);
1969 conn_list_iterate(game.est_connections, pconn) {
1970 struct player *pplayer = pconn->playing;
1972 if (pplayer != NULL) {
1974 /* NOTE: this means the player can see combat between submarines even
1975 * if neither sub is visible. See similar comment in send_combat. */
1976 if (map_is_known_and_seen(unit_tile(pattacker), pplayer, V_MAIN)
1977 || map_is_known_and_seen(unit_tile(pdefender), pplayer,
1978 V_MAIN)) {
1980 /* Units are sent even if they were visible already. They may
1981 * have changed orientation for combat. */
1982 if (pplayer == unit_owner(pattacker)) {
1983 send_packet_unit_info(pconn, &unit_att_packet);
1984 } else {
1985 send_packet_unit_short_info(pconn, &unit_att_short_packet, FALSE);
1988 if (pplayer == unit_owner(pdefender)) {
1989 send_packet_unit_info(pconn, &unit_def_packet);
1990 } else {
1991 send_packet_unit_short_info(pconn, &unit_def_short_packet, FALSE);
1994 } else if (pconn->observer) {
1995 /* Global observer sees everything... */
1996 send_packet_unit_info(pconn, &unit_att_packet);
1997 send_packet_unit_info(pconn, &unit_def_packet);
1999 } conn_list_iterate_end;
2002 /**************************************************************************
2003 Send combat info to players.
2004 **************************************************************************/
2005 static void send_combat(struct unit *pattacker, struct unit *pdefender,
2006 int veteran, int bombard)
2008 struct packet_unit_combat_info combat;
2010 combat.attacker_unit_id=pattacker->id;
2011 combat.defender_unit_id=pdefender->id;
2012 combat.attacker_hp=pattacker->hp;
2013 combat.defender_hp=pdefender->hp;
2014 combat.make_winner_veteran=veteran;
2016 players_iterate(other_player) {
2017 /* NOTE: this means the player can see combat between submarines even
2018 * if neither sub is visible. See similar comment in see_combat. */
2019 if (map_is_known_and_seen(unit_tile(pattacker), other_player, V_MAIN)
2020 || map_is_known_and_seen(unit_tile(pdefender), other_player,
2021 V_MAIN)) {
2022 lsend_packet_unit_combat_info(other_player->connections, &combat);
2025 * Remove the client knowledge of the units. This corresponds to the
2026 * send_packet_unit_short_info calls up above.
2028 if (!can_player_see_unit(other_player, pattacker)) {
2029 unit_goes_out_of_sight(other_player, pattacker);
2031 if (!can_player_see_unit(other_player, pdefender)) {
2032 unit_goes_out_of_sight(other_player, pdefender);
2035 } players_iterate_end;
2037 /* Send combat info to non-player observers as well. They already know
2038 * about the unit so no unit_info is needed. */
2039 conn_list_iterate(game.est_connections, pconn) {
2040 if (NULL == pconn->playing && pconn->observer) {
2041 send_packet_unit_combat_info(pconn, &combat);
2043 } conn_list_iterate_end;
2046 /**************************************************************************
2047 This function assumes the bombard is legal. The calling function should
2048 have already made all necessary checks.
2049 **************************************************************************/
2050 static bool unit_bombard(struct unit *punit, struct tile *ptile)
2052 struct player *pplayer = unit_owner(punit);
2053 struct city *pcity = tile_city(ptile);
2055 log_debug("Start bombard: %s %s to %d, %d.",
2056 nation_rule_name(nation_of_player(pplayer)),
2057 unit_rule_name(punit), TILE_XY(ptile));
2059 unit_list_iterate_safe(ptile->units, pdefender) {
2061 /* Sanity checks */
2062 fc_assert_ret_val_msg(!pplayers_non_attack(unit_owner(punit),
2063 unit_owner(pdefender)), TRUE,
2064 "Trying to attack a unit with which you have "
2065 "peace or cease-fire at (%d, %d).",
2066 TILE_XY(unit_tile(pdefender)));
2067 fc_assert_ret_val_msg(!pplayers_allied(unit_owner(punit),
2068 unit_owner(pdefender)), TRUE,
2069 "Trying to attack a unit with which you have "
2070 "alliance at (%d, %d).",
2071 TILE_XY(unit_tile(pdefender)));
2073 if (is_unit_reachable_at(pdefender, punit, ptile)) {
2074 bool adj;
2075 enum direction8 facing;
2076 int att_hp, def_hp;
2078 adj = base_get_direction_for_step(punit->tile, pdefender->tile, &facing);
2080 fc_assert(adj);
2081 if (adj) {
2082 punit->facing = facing;
2084 /* Unlike with normal attack, we don't change orientation of
2085 * defenders when bombarding */
2088 unit_versus_unit(punit, pdefender, TRUE, &att_hp, &def_hp);
2090 see_combat(punit, pdefender);
2092 punit->hp = att_hp;
2093 pdefender->hp = def_hp;
2095 send_combat(punit, pdefender, 0, 1);
2097 send_unit_info(NULL, pdefender);
2100 } unit_list_iterate_safe_end;
2102 punit->moves_left = 0;
2104 unit_did_action(punit);
2105 unit_forget_last_activity(punit);
2107 if (pcity
2108 && city_size_get(pcity) > 1
2109 && get_city_bonus(pcity, EFT_UNIT_NO_LOSE_POP) <= 0
2110 && kills_citizen_after_attack(punit)) {
2111 city_reduce_size(pcity, 1, pplayer, "bombard");
2112 city_refresh(pcity);
2113 send_city_info(NULL, pcity);
2116 send_unit_info(NULL, punit);
2117 return TRUE;
2120 /**************************************************************************
2121 This function assumes the attack is legal. The calling function should have
2122 already made all necessary checks.
2123 **************************************************************************/
2124 static void unit_attack_handling(struct unit *punit, struct unit *pdefender)
2126 char loser_link[MAX_LEN_LINK], winner_link[MAX_LEN_LINK];
2127 struct unit *ploser, *pwinner;
2128 struct city *pcity;
2129 int moves_used, def_moves_used;
2130 int old_unit_vet, old_defender_vet, vet;
2131 int winner_id;
2132 struct tile *def_tile = unit_tile(pdefender);
2133 struct player *pplayer = unit_owner(punit);
2134 bool adj;
2135 enum direction8 facing;
2136 int att_hp, def_hp;
2138 log_debug("Start attack: %s %s against %s %s.",
2139 nation_rule_name(nation_of_player(pplayer)),
2140 unit_rule_name(punit),
2141 nation_rule_name(nation_of_unit(pdefender)),
2142 unit_rule_name(pdefender));
2144 /* Sanity checks */
2145 fc_assert_ret_msg(!pplayers_non_attack(pplayer, unit_owner(pdefender)),
2146 "Trying to attack a unit with which you have peace "
2147 "or cease-fire at (%d, %d).", TILE_XY(def_tile));
2148 fc_assert_ret_msg(!pplayers_allied(pplayer, unit_owner(pdefender))
2149 || (unit_has_type_flag(punit, UTYF_NUCLEAR)
2150 && punit == pdefender),
2151 "Trying to attack a unit with which you have alliance "
2152 "at (%d, %d).", TILE_XY(def_tile));
2154 if (unit_has_type_flag(punit, UTYF_NUCLEAR)) {
2155 if ((pcity = sdi_try_defend(pplayer, def_tile))) {
2156 /* FIXME: Remove the hard coded reference to SDI defense. */
2157 notify_player(pplayer, unit_tile(punit), E_UNIT_LOST_ATT, ftc_server,
2158 _("Your %s was shot down by "
2159 "SDI defenses, what a waste."), unit_tile_link(punit));
2160 notify_player(city_owner(pcity), def_tile, E_UNIT_WIN, ftc_server,
2161 _("The nuclear attack on %s was avoided by"
2162 " your SDI defense."), city_link(pcity));
2163 wipe_unit(punit, ULR_SDI, city_owner(pcity));
2164 return;
2167 dlsend_packet_nuke_tile_info(game.est_connections, tile_index(def_tile));
2169 wipe_unit(punit, ULR_DETONATED, NULL);
2170 do_nuclear_explosion(pplayer, def_tile);
2171 return;
2173 moves_used = unit_move_rate(punit) - punit->moves_left;
2174 def_moves_used = unit_move_rate(pdefender) - pdefender->moves_left;
2176 adj = base_get_direction_for_step(punit->tile, pdefender->tile, &facing);
2178 fc_assert(adj);
2179 if (adj) {
2180 punit->facing = facing;
2181 pdefender->facing = opposite_direction(facing);
2184 old_unit_vet = punit->veteran;
2185 old_defender_vet = pdefender->veteran;
2186 unit_versus_unit(punit, pdefender, FALSE, &att_hp, &def_hp);
2188 if ((att_hp <= 0 || uclass_has_flag(unit_class_get(punit), UCF_MISSILE))
2189 && unit_transported(punit)) {
2190 /* Dying attacker must be first unloaded so it doesn't die insider transport */
2191 unit_transport_unload_send(punit);
2194 see_combat(punit, pdefender);
2196 punit->hp = att_hp;
2197 pdefender->hp = def_hp;
2199 combat_veterans(punit, pdefender);
2201 /* Adjust attackers moves_left _after_ unit_versus_unit() so that
2202 * the movement attack modifier is correct! --dwp
2204 * For greater Civ2 compatibility (and game balance issues), we recompute
2205 * the new total MP based on the HP the unit has left after being damaged,
2206 * and subtract the MPs that had been used before the combat (plus the
2207 * points used in the attack itself, for the attacker). -GJW, Glip
2209 punit->moves_left = unit_move_rate(punit) - moves_used - SINGLE_MOVE;
2210 pdefender->moves_left = unit_move_rate(pdefender) - def_moves_used;
2212 if (punit->moves_left < 0) {
2213 punit->moves_left = 0;
2215 if (pdefender->moves_left < 0) {
2216 pdefender->moves_left = 0;
2218 unit_did_action(punit);
2219 unit_forget_last_activity(punit);
2221 if (punit->hp > 0
2222 && (pcity = tile_city(def_tile))
2223 && city_size_get(pcity) > 1
2224 && get_city_bonus(pcity, EFT_UNIT_NO_LOSE_POP) <= 0
2225 && kills_citizen_after_attack(punit)) {
2226 city_reduce_size(pcity, 1, pplayer, "attack");
2227 city_refresh(pcity);
2228 send_city_info(NULL, pcity);
2230 if (unit_has_type_flag(punit, UTYF_ONEATTACK)) {
2231 punit->moves_left = 0;
2233 pwinner = (punit->hp > 0) ? punit : pdefender;
2234 winner_id = pwinner->id;
2235 ploser = (pdefender->hp > 0) ? punit : pdefender;
2237 vet = (pwinner->veteran == ((punit->hp > 0) ? old_unit_vet :
2238 old_defender_vet)) ? 0 : 1;
2240 send_combat(punit, pdefender, vet, 0);
2242 /* N.B.: unit_link always returns the same pointer. */
2243 sz_strlcpy(loser_link, unit_tile_link(ploser));
2244 sz_strlcpy(winner_link, uclass_has_flag(unit_class_get(pwinner), UCF_MISSILE)
2245 ? unit_tile_link(pwinner) : unit_link(pwinner));
2247 if (punit == ploser) {
2248 /* The attacker lost */
2249 log_debug("Attacker lost: %s %s against %s %s.",
2250 nation_rule_name(nation_of_player(pplayer)),
2251 unit_rule_name(punit),
2252 nation_rule_name(nation_of_unit(pdefender)),
2253 unit_rule_name(pdefender));
2255 notify_player(unit_owner(pwinner), unit_tile(pwinner),
2256 E_UNIT_WIN, ftc_server,
2257 /* TRANS: "Your Cannon ... the Polish Destroyer." */
2258 _("Your %s survived the pathetic attack from the %s %s."),
2259 winner_link,
2260 nation_adjective_for_player(unit_owner(ploser)),
2261 loser_link);
2262 if (vet) {
2263 notify_unit_experience(pwinner);
2265 notify_player(unit_owner(ploser), def_tile,
2266 E_UNIT_LOST_ATT, ftc_server,
2267 /* TRANS: "... Cannon ... the Polish Destroyer." */
2268 _("Your attacking %s failed against the %s %s!"),
2269 loser_link,
2270 nation_adjective_for_player(unit_owner(pwinner)),
2271 winner_link);
2272 wipe_unit(ploser, ULR_KILLED, unit_owner(pwinner));
2273 } else {
2274 /* The defender lost, the attacker punit lives! */
2276 log_debug("Defender lost: %s %s against %s %s.",
2277 nation_rule_name(nation_of_player(pplayer)),
2278 unit_rule_name(punit),
2279 nation_rule_name(nation_of_unit(pdefender)),
2280 unit_rule_name(pdefender));
2282 punit->moved = TRUE; /* We moved */
2283 kill_unit(pwinner, ploser,
2284 vet && !uclass_has_flag(unit_class_get(punit), UCF_MISSILE));
2285 if (unit_is_alive(winner_id)) {
2286 if (uclass_has_flag(unit_class_get(pwinner), UCF_MISSILE)) {
2287 wipe_unit(pwinner, ULR_MISSILE, NULL);
2288 return;
2290 } else {
2291 return;
2295 /* If attacker wins, and occupychance > 0, it might move in. Don't move in
2296 * if there are enemy units in the tile (a fortress, city or air base with
2297 * multiple defenders and unstacked combat). Note that this could mean
2298 * capturing (or destroying) a city. */
2300 if (pwinner == punit && fc_rand(100) < game.server.occupychance &&
2301 !is_non_allied_unit_tile(def_tile, pplayer)) {
2303 /* Hack: make sure the unit has enough moves_left for the move to succeed,
2304 and adjust moves_left to afterward (if successful). */
2306 int old_moves = punit->moves_left;
2307 int full_moves = unit_move_rate(punit);
2309 punit->moves_left = full_moves;
2310 /* Post attack occupy move. */
2311 if (unit_move_handling(punit, def_tile, FALSE, TRUE, NULL)) {
2312 punit->moves_left = old_moves - (full_moves - punit->moves_left);
2313 if (punit->moves_left < 0) {
2314 punit->moves_left = 0;
2316 } else {
2317 punit->moves_left = old_moves;
2321 /* The attacker may have died for many reasons */
2322 if (game_unit_by_number(winner_id) != NULL) {
2323 send_unit_info(NULL, pwinner);
2327 /**************************************************************************
2328 see also aiunit could_unit_move_to_tile()
2329 **************************************************************************/
2330 static bool can_unit_move_to_tile_with_notify(struct unit *punit,
2331 struct tile *dest_tile,
2332 bool igzoc,
2333 struct unit *embark_to)
2335 struct tile *src_tile = unit_tile(punit);
2336 enum unit_move_result reason =
2337 unit_move_to_tile_test(punit, punit->activity,
2338 src_tile, dest_tile, igzoc, embark_to);
2340 switch (reason) {
2341 case MR_OK:
2342 return TRUE;
2344 case MR_BAD_TYPE_FOR_CITY_TAKE_OVER:
2345 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2346 _("This type of troops cannot take over a city."));
2347 break;
2349 case MR_BAD_TYPE_FOR_CITY_TAKE_OVER_FROM_NON_NATIVE:
2351 const char *types[utype_count()];
2352 int i = 0;
2354 unit_type_iterate(utype) {
2355 if (can_attack_from_non_native(utype)
2356 && utype_can_take_over(utype)) {
2357 types[i++] = utype_name_translation(utype);
2359 } unit_type_iterate_end;
2361 if (0 < i) {
2362 struct astring astr = ASTRING_INIT;
2364 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2365 /* TRANS: %s is a list of units separated by "or". */
2366 _("Only %s can conquer from a non-native tile."),
2367 astr_build_or_list(&astr, types, i));
2368 astr_free(&astr);
2369 } else {
2370 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2371 _("Cannot conquer from a non-native tile."));
2374 break;
2376 case MR_NO_WAR:
2377 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2378 _("Cannot attack unless you declare war first."));
2379 break;
2381 case MR_ZOC:
2382 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2383 _("%s can only move into your own zone of control."),
2384 unit_link(punit));
2385 break;
2387 case MR_TRIREME:
2388 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2389 _("%s cannot move that far from the coast line."),
2390 unit_link(punit));
2391 break;
2393 case MR_PEACE:
2394 if (tile_owner(dest_tile)) {
2395 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2396 _("Cannot invade unless you break peace with "
2397 "%s first."),
2398 player_name(tile_owner(dest_tile)));
2400 break;
2402 case MR_CANNOT_DISEMBARK:
2403 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2404 _("%s cannot disembark outside of a city or a native base "
2405 "for %s."),
2406 unit_link(punit),
2407 utype_name_translation(
2408 unit_type_get(unit_transport_get(punit))));
2409 break;
2411 case MR_NON_NATIVE_MOVE:
2412 notify_player(unit_owner(punit), src_tile, E_BAD_COMMAND, ftc_server,
2413 _("Terrain is unsuitable for %s units."),
2414 uclass_name_translation(unit_class_get(punit)));
2415 break;
2417 default:
2418 /* FIXME: need more explanations someday! */
2419 break;
2422 return FALSE;
2425 /**************************************************************************
2426 Will try to move to/attack the tile dest_x,dest_y. Returns TRUE if this
2427 was done, FALSE if it wasn't for some reason. Even if this returns TRUE,
2428 the unit may have died upon arrival to new tile.
2430 'igzoc' means ignore ZOC rules - not necessary for igzoc units etc, but
2431 done in some special cases (moving barbarians out of initial hut).
2432 Should normally be FALSE.
2434 'move_do_not_act' is another special case which should normally be
2435 FALSE. If TRUE any enabler controlled actions punit can perform to
2436 pdesttile it self or something located at it will be ignored. If FALSE
2437 the system will check if punit can perform any enabler controlled action
2438 to pdesttile. If it can the player will be asked to choose what to do. If
2439 it can't and punit is unable to move (or perform another non enabler
2440 controlled action) to pdesttile the game will try to explain why.
2442 FIXME: This function needs a good cleaning.
2443 **************************************************************************/
2444 bool unit_move_handling(struct unit *punit, struct tile *pdesttile,
2445 bool igzoc, bool move_do_not_act,
2446 struct unit *embark_to)
2448 struct player *pplayer = unit_owner(punit);
2449 struct city *pcity = tile_city(pdesttile);
2450 bool taking_over_city = FALSE;
2452 /*** Phase 1: Basic checks ***/
2454 /* this occurs often during lag, and to the AI due to some quirks -- Syela */
2455 if (!is_tiles_adjacent(unit_tile(punit), pdesttile)) {
2456 log_debug("tiles not adjacent in move request");
2457 return FALSE;
2461 if (punit->moves_left <= 0) {
2462 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
2463 _("This unit has no moves left."));
2464 return FALSE;
2467 if (!unit_can_do_action_now(punit)) {
2468 return FALSE;
2471 /*** Phase 2: Special abilities checks ***/
2473 /* Actors. Pop up an action selection dialog in the client.
2474 * If the AI has used a goto to send an actor to a target do not
2475 * pop up a dialog in the client.
2476 * For tiles occupied by allied cities or units, keep moving if
2477 * move_do_not_act tells us to, or if the unit is on goto and the tile
2478 * is not the final destination. */
2479 if (!move_do_not_act
2480 && utype_may_act_at_all(unit_type_get(punit))) {
2481 if ((0 < unit_list_size(pdesttile->units) || pcity)) {
2482 /* A target (unit or city) exists at the tile. If a target is an ally
2483 * it still looks like a target since move_do_not_act isn't set.
2484 * Assume that the intention is to do an action. */
2486 struct unit *tunit = tgt_unit(punit, pdesttile);
2487 struct city *tcity = tgt_city(punit, pdesttile);
2489 /* If a tcity or a tunit exists it must be possible to act against it
2490 * since tgt_city() or tgt_unit() wouldn't have targeted it
2491 * otherwise. */
2492 if (tcity || tunit) {
2493 if (pplayer->ai_controlled) {
2494 return FALSE;
2497 punit->action_decision_want = ACT_DEC_ACTIVE;
2498 punit->action_decision_tile = pdesttile;
2500 /* Let the client know that this unit needs the player to decide
2501 * what to do. */
2502 send_unit_info(player_reply_dest(pplayer), punit);
2504 /* The move wasn't done because the unit wanted the player to
2505 * decide what to do. */
2506 return FALSE;
2507 } else if (!may_non_act_move(punit, pcity, pdesttile, igzoc)) {
2508 /* No action can be done. No regular move can be done. Attack isn't
2509 * possible. Try to explain it to the player. */
2510 explain_why_no_action_enabled(punit, pdesttile, pcity,
2511 is_non_attack_unit_tile(pdesttile,
2512 pplayer));
2514 /* The move wasn't done because the unit couldn't do anything. */
2515 return FALSE;
2520 /*** Phase 3: Is it attack? ***/
2522 if (is_non_allied_unit_tile(pdesttile, pplayer)
2523 || is_non_allied_city_tile(pdesttile, pplayer)) {
2524 struct unit *victim = NULL;
2525 enum unit_attack_result ua_result;
2527 if (embark_to != NULL) {
2528 /* Can't both attack and embark. */
2529 return FALSE;
2532 /* We can attack ONLY in enemy cities */
2533 if ((pcity && !pplayers_at_war(city_owner(pcity), pplayer))
2534 || (victim = is_non_attack_unit_tile(pdesttile, pplayer))) {
2535 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
2536 _("You must declare war on %s first. Try using "
2537 "the Nations report (F3)."),
2538 victim == NULL
2539 ? player_name(city_owner(pcity))
2540 : player_name(unit_owner(victim)));
2541 return FALSE;
2544 if (unit_has_type_flag(punit, UTYF_CAPTURER) && pcity == NULL) {
2545 bool capture_possible = TRUE;
2547 unit_list_iterate(pdesttile->units, to_capture) {
2548 if (!unit_has_type_flag(to_capture, UTYF_CAPTURABLE)) {
2549 capture_possible = FALSE;
2550 break;
2552 } unit_list_iterate_end;
2554 if (capture_possible) {
2555 do_capture_units(pplayer, punit, pdesttile);
2557 return TRUE;
2561 /* Are we a bombarder? */
2562 if (unit_has_type_flag(punit, UTYF_BOMBARDER)) {
2563 /* Only land can be bombarded; if the target is on ocean (or is
2564 * an empty city), fall through to attack/conquer. */
2565 if (!is_ocean_tile(pdesttile) && unit_list_size(pdesttile->units) > 0) {
2566 if (can_unit_bombard(punit)) {
2567 unit_bombard(punit, pdesttile);
2568 return TRUE;
2569 } else {
2570 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
2571 _("This unit is being transported, and"
2572 " so cannot bombard."));
2573 return FALSE;
2578 /* Depending on 'unreachableprotects' setting, must be physically able
2579 * to attack EVERY unit there or must be physically able to attack SOME
2580 * unit there */
2581 ua_result = unit_attack_units_at_tile_result(punit, pdesttile);
2582 if (NULL == pcity && ua_result != ATT_OK) {
2583 struct tile *src_tile = unit_tile(punit);
2585 switch (ua_result) {
2586 case ATT_NON_ATTACK:
2587 notify_player(pplayer, src_tile, E_BAD_COMMAND, ftc_server,
2588 _("%s is not an attack unit."), unit_name_translation(punit));
2589 break;
2590 case ATT_UNREACHABLE:
2591 notify_player(pplayer, src_tile, E_BAD_COMMAND, ftc_server,
2592 _("You can't attack there since there's an unreachable unit."));
2593 break;
2594 case ATT_NONNATIVE_SRC:
2595 notify_player(pplayer, src_tile, E_BAD_COMMAND, ftc_server,
2596 _("%s can't launch attack from %s."),
2597 unit_name_translation(punit),
2598 terrain_name_translation(tile_terrain(src_tile)));
2599 break;
2600 case ATT_NONNATIVE_DST:
2601 notify_player(pplayer, src_tile, E_BAD_COMMAND, ftc_server,
2602 _("%s can't attack to %s."),
2603 unit_name_translation(punit),
2604 terrain_name_translation(tile_terrain(pdesttile)));
2605 break;
2606 case ATT_OK:
2607 fc_assert(ua_result != ATT_OK);
2608 break;
2611 return FALSE;
2614 /* The attack is legal wrt the alliances */
2615 victim = get_defender(punit, pdesttile);
2617 if (victim) {
2618 unit_attack_handling(punit, victim);
2619 return TRUE;
2620 } else {
2621 fc_assert_ret_val(is_enemy_city_tile(pdesttile, pplayer) != NULL,
2622 TRUE);
2624 if (unit_has_type_flag(punit, UTYF_NUCLEAR)) {
2625 if (unit_move(punit, pcity->tile, 0, NULL)) {
2626 /* Survived dangers of moving */
2627 unit_attack_handling(punit, punit); /* Boom! */
2629 return TRUE;
2632 taking_over_city = TRUE;
2633 /* Taking over a city is considered a move, so fall through */
2637 /*** Phase 4: OK now move the unit ***/
2639 /* We cannot move a transport into a tile that holds
2640 * units or cities not allied with all of our cargo. */
2641 if (get_transporter_capacity(punit) > 0) {
2642 unit_list_iterate(unit_tile(punit)->units, pcargo) {
2643 if (unit_contained_in(pcargo, punit)
2644 && (is_non_allied_unit_tile(pdesttile, unit_owner(pcargo))
2645 || (!taking_over_city
2646 && is_non_allied_city_tile(pdesttile,
2647 unit_owner(pcargo))))) {
2648 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
2649 _("A transported unit is not allied to all "
2650 "units or city on target tile."));
2651 return FALSE;
2653 } unit_list_iterate_end;
2656 if (can_unit_move_to_tile_with_notify(punit, pdesttile, igzoc,
2657 embark_to)) {
2658 int move_cost = map_move_cost_unit(punit, pdesttile);
2660 unit_move(punit, pdesttile, move_cost, embark_to);
2662 return TRUE;
2663 } else {
2664 return FALSE;
2668 /**************************************************************************
2669 Handle request to help in wonder building.
2670 **************************************************************************/
2671 static void do_unit_help_build_wonder(struct player *pplayer,
2672 struct unit *punit,
2673 struct city *pcity_dest)
2675 const char *work;
2677 /* Sanity check: The actor still exists. */
2678 fc_assert_ret(pplayer);
2679 fc_assert_ret(punit);
2681 /* Sanity check: The target city still exists. */
2682 fc_assert_ret(pcity_dest);
2684 pcity_dest->shield_stock += unit_build_shield_cost(punit);
2685 pcity_dest->caravan_shields += unit_build_shield_cost(punit);
2687 conn_list_do_buffer(pplayer->connections);
2689 if (build_points_left(pcity_dest) >= 0) {
2690 /* TRANS: Your Caravan helps build the Pyramids in Bergen (4
2691 * remaining). You can reorder '4' and 'remaining' in the actual
2692 * format string. */
2693 work = _("remaining");
2694 } else {
2695 /* TRANS: Your Caravan helps build the Pyramids in Bergen (4
2696 * surplus). You can reorder '4' and 'surplus' in the actual
2697 * format string. */
2698 work = _("surplus");
2701 /* Let the player that just donated shields to the wonder building know
2702 * the result of his donation. */
2703 notify_player(pplayer, city_tile(pcity_dest), E_CARAVAN_ACTION,
2704 ftc_server,
2705 /* TRANS: Your Caravan helps build the Pyramids in Bergen
2706 * (4 surplus). */
2707 _("Your %s helps build the %s in %s (%d %s)."),
2708 unit_link(punit),
2709 improvement_name_translation(
2710 pcity_dest->production.value.building),
2711 city_link(pcity_dest),
2712 abs(build_points_left(pcity_dest)),
2713 work);
2715 /* May cause an incident */
2716 action_consequence_success(ACTION_HELP_WONDER, pplayer,
2717 city_owner(pcity_dest),
2718 city_tile(pcity_dest), city_link(pcity_dest));
2720 if (city_owner(pcity_dest) != unit_owner(punit)) {
2721 /* Tell the city owner about the gift he just received. */
2723 notify_player(city_owner(pcity_dest), city_tile(pcity_dest),
2724 E_CARAVAN_ACTION, ftc_server,
2725 /* TRANS: Help building the Pyramids in Bergen received
2726 * from Persian Caravan (4 surplus). */
2727 _("Help building the %s in %s received from %s %s "
2728 "(%d %s)."),
2729 improvement_name_translation(
2730 pcity_dest->production.value.building),
2731 city_link(pcity_dest),
2732 nation_adjective_for_player(pplayer),
2733 unit_link(punit),
2734 abs(build_points_left(pcity_dest)),
2735 work);
2738 wipe_unit(punit, ULR_USED, NULL);
2739 send_player_info_c(pplayer, pplayer->connections);
2740 send_city_info(pplayer, pcity_dest);
2741 conn_list_do_unbuffer(pplayer->connections);
2744 /**************************************************************************
2745 Handle request to establish traderoute. If pcity_dest is NULL, assumes
2746 that unit is inside target city.
2747 **************************************************************************/
2748 static bool do_unit_establish_trade(struct player *pplayer,
2749 struct unit *punit,
2750 struct city *pcity_dest,
2751 bool est_if_able)
2753 char homecity_link[MAX_LEN_LINK], destcity_link[MAX_LEN_LINK];
2754 char punit_link[MAX_LEN_LINK];
2755 int revenue, i;
2756 bool can_establish;
2757 int home_overbooked = 0;
2758 int dest_overbooked = 0;
2759 int home_max;
2760 int dest_max;
2761 struct city *pcity_homecity;
2762 struct city_list *cities_out_of_home, *cities_out_of_dest;
2763 enum traderoute_bonus_type bonus_type;
2764 const char *bonus_str;
2766 /* Sanity check: The actor still exists. */
2767 fc_assert_ret_val(pplayer, FALSE);
2768 fc_assert_ret_val(punit, FALSE);
2770 /* Sanity check: The target city still exists. */
2771 fc_assert_ret_val(pcity_dest, FALSE);
2773 pcity_homecity = player_city_by_number(pplayer, punit->homecity);
2775 if (!pcity_homecity) {
2776 notify_player(pplayer, unit_tile(punit), E_BAD_COMMAND, ftc_server,
2777 _("Sorry, your %s cannot establish"
2778 " a trade route because it has no home city."),
2779 unit_link(punit));
2780 return FALSE;
2784 sz_strlcpy(homecity_link, city_link(pcity_homecity));
2785 sz_strlcpy(destcity_link, city_link(pcity_dest));
2787 if (!can_cities_trade(pcity_homecity, pcity_dest)) {
2788 notify_player(pplayer, city_tile(pcity_dest), E_BAD_COMMAND, ftc_server,
2789 _("Sorry, your %s cannot establish"
2790 " a trade route between %s and %s."),
2791 unit_link(punit),
2792 homecity_link,
2793 destcity_link);
2794 return FALSE;
2797 sz_strlcpy(punit_link, unit_tile_link(punit));
2798 cities_out_of_home = city_list_new();
2799 cities_out_of_dest = city_list_new();
2801 /* This part of code works like can_establish_trade_route, except
2802 * that we actually do the action of making the trade route. */
2804 /* If we can't make a new trade route we can still get the trade bonus. */
2805 can_establish = est_if_able
2806 && !have_cities_trade_route(pcity_homecity, pcity_dest);
2808 if (can_establish) {
2809 home_max = max_trade_routes(pcity_homecity);
2810 dest_max = max_trade_routes(pcity_dest);
2811 home_overbooked = city_num_trade_routes(pcity_homecity) - home_max;
2812 dest_overbooked = city_num_trade_routes(pcity_dest) - dest_max;
2815 if (can_establish && (home_overbooked >= 0 || dest_overbooked >= 0)) {
2816 int trade = trade_between_cities(pcity_homecity, pcity_dest);
2818 /* See if there's a trade route we can cancel at the home city. */
2819 if (home_overbooked >= 0) {
2820 if (home_max <= 0
2821 || (city_trade_removable(pcity_homecity, cities_out_of_home)
2822 >= trade)) {
2823 notify_player(pplayer, city_tile(pcity_dest),
2824 E_BAD_COMMAND, ftc_server,
2825 _("Sorry, your %s cannot establish"
2826 " a trade route here!"),
2827 punit_link);
2828 if (home_max > 0) {
2829 notify_player(pplayer, city_tile(pcity_dest),
2830 E_BAD_COMMAND, ftc_server,
2831 PL_(" The city of %s already has %d "
2832 "better trade route!",
2833 " The city of %s already has %d "
2834 "better trade routes!", home_max),
2835 homecity_link,
2836 home_max);
2838 can_establish = FALSE;
2842 /* See if there's a trade route we can cancel at the dest city. */
2843 if (can_establish && dest_overbooked >= 0) {
2844 if (dest_max <= 0
2845 || (city_trade_removable(pcity_dest, cities_out_of_dest)
2846 >= trade)) {
2847 notify_player(pplayer, city_tile(pcity_dest),
2848 E_BAD_COMMAND, ftc_server,
2849 _("Sorry, your %s cannot establish"
2850 " a trade route here!"),
2851 punit_link);
2852 if (dest_max > 0) {
2853 notify_player(pplayer, city_tile(pcity_dest),
2854 E_BAD_COMMAND, ftc_server,
2855 PL_(" The city of %s already has %d "
2856 "better trade route!",
2857 " The city of %s already has %d "
2858 "better trade routes!", dest_max),
2859 destcity_link,
2860 dest_max);
2862 can_establish = FALSE;
2867 /* We now know for sure whether we can establish a trade route. */
2869 /* Calculate and announce initial revenue. */
2870 revenue = get_caravan_enter_city_trade_bonus(pcity_homecity, pcity_dest,
2871 can_establish);
2873 bonus_type = trade_route_settings_by_type(cities_trade_route_type(pcity_homecity, pcity_dest))->bonus_type;
2874 bonus_str = NULL;
2876 switch (bonus_type) {
2877 case TBONUS_NONE:
2878 break;
2879 case TBONUS_GOLD:
2880 /* TRANS: used as part of caravan revenue sentence. */
2881 bonus_str = Q_("?tradebonustype:gold");
2882 break;
2883 case TBONUS_SCIENCE:
2884 /* TRANS: used as part of caravan revenue sentence. */
2885 bonus_str = Q_("?tradebonustype:research");
2886 break;
2887 case TBONUS_BOTH:
2888 /* TRANS: used as part of caravan revenue sentence. */
2889 bonus_str = Q_("?tradebonustype:gold and research");
2890 break;
2893 conn_list_do_buffer(pplayer->connections);
2895 if (bonus_str != NULL) {
2896 notify_player(pplayer, city_tile(pcity_dest),
2897 E_CARAVAN_ACTION, ftc_server,
2898 /* TRANS: ... Caravan ... Paris ... Stockholm, ... gold and research. */
2899 PL_("Your %s from %s has arrived in %s,"
2900 " and revenues amount to %d in %s.",
2901 "Your %s from %s has arrived in %s,"
2902 " and revenues amount to %d in %s.",
2903 revenue),
2904 punit_link,
2905 homecity_link,
2906 destcity_link,
2907 revenue,
2908 bonus_str);
2909 } else {
2910 notify_player(pplayer, city_tile(pcity_dest),
2911 E_CARAVAN_ACTION, ftc_server,
2912 /* TRANS: ... Caravan ... Paris ... Stockholm, ... */
2913 _("Your %s from %s has arrived in %s."),
2914 punit_link,
2915 homecity_link,
2916 destcity_link);
2918 wipe_unit(punit, ULR_USED, NULL);
2920 if (bonus_type == TBONUS_GOLD || bonus_type == TBONUS_BOTH) {
2921 pplayer->economic.gold += revenue;
2923 send_player_info_c(pplayer, pplayer->connections);
2926 if (bonus_type == TBONUS_SCIENCE || bonus_type == TBONUS_BOTH) {
2927 /* add bulbs and check for finished research */
2928 update_bulbs(pplayer, revenue, TRUE);
2930 /* Inform everyone about tech changes */
2931 send_research_info(research_get(pplayer), NULL);
2934 if (can_establish) {
2936 /* Announce creation of trade route (it's not actually created until
2937 * later in this function, as we have to cancel existing routes, but
2938 * it makes more sense to announce in this order) */
2940 /* Always tell the unit owner */
2941 notify_player(pplayer, NULL,
2942 E_CARAVAN_ACTION, ftc_server,
2943 _("New trade route established from %s to %s."),
2944 homecity_link,
2945 destcity_link);
2946 if (pplayer != city_owner(pcity_dest)) {
2947 notify_player(city_owner(pcity_dest), city_tile(pcity_dest),
2948 E_CARAVAN_ACTION, ftc_server,
2949 _("The %s established a trade route between their "
2950 "city %s and %s."),
2951 nation_plural_for_player(pplayer),
2952 homecity_link,
2953 destcity_link);
2956 /* Now cancel any less profitable trade route from the home city. */
2957 city_list_iterate(cities_out_of_home, pcity) {
2958 remove_trade_route(pcity_homecity, pcity, TRUE, FALSE);
2959 } city_list_iterate_end;
2961 /* And the same for the dest city. */
2962 city_list_iterate(cities_out_of_dest, pcity) {
2963 remove_trade_route(pcity_dest, pcity, TRUE, FALSE);
2964 } city_list_iterate_end;
2966 /* Actually create the new trade route */
2967 for (i = 0; i < MAX_TRADE_ROUTES; i++) {
2968 if (pcity_homecity->trade[i] == 0) {
2969 pcity_homecity->trade[i] = pcity_dest->id;
2970 break;
2973 fc_assert(i < MAX_TRADE_ROUTES);
2975 for (i = 0; i < MAX_TRADE_ROUTES; i++) {
2976 if (pcity_dest->trade[i] == 0) {
2977 pcity_dest->trade[i] = pcity_homecity->id;
2978 break;
2981 fc_assert(i < MAX_TRADE_ROUTES);
2983 /* Refresh the cities. */
2984 city_refresh(pcity_homecity);
2985 city_refresh(pcity_dest);
2986 city_list_iterate(cities_out_of_home, pcity) {
2987 city_refresh(pcity);
2988 } city_list_iterate_end;
2989 city_list_iterate(cities_out_of_dest, pcity) {
2990 city_refresh(pcity);
2991 } city_list_iterate_end;
2993 /* Notify the owners of the cities. */
2994 send_city_info(pplayer, pcity_homecity);
2995 send_city_info(city_owner(pcity_dest), pcity_dest);
2996 city_list_iterate(cities_out_of_home, pcity) {
2997 send_city_info(city_owner(pcity), pcity);
2998 } city_list_iterate_end;
2999 city_list_iterate(cities_out_of_dest, pcity) {
3000 send_city_info(city_owner(pcity), pcity);
3001 } city_list_iterate_end;
3003 /* Notify each player about the other cities so that they know about
3004 * its size for the trade calculation . */
3005 if (pplayer != city_owner(pcity_dest)) {
3006 send_city_info(city_owner(pcity_dest), pcity_homecity);
3007 send_city_info(pplayer, pcity_dest);
3010 city_list_iterate(cities_out_of_home, pcity) {
3011 if (city_owner(pcity_dest) != city_owner(pcity)) {
3012 send_city_info(city_owner(pcity_dest), pcity);
3013 send_city_info(city_owner(pcity), pcity_dest);
3015 if (pplayer != city_owner(pcity)) {
3016 send_city_info(pplayer, pcity);
3017 send_city_info(city_owner(pcity), pcity_homecity);
3019 } city_list_iterate_end;
3021 city_list_iterate(cities_out_of_dest, pcity) {
3022 if (city_owner(pcity_dest) != city_owner(pcity)) {
3023 send_city_info(city_owner(pcity_dest), pcity);
3024 send_city_info(city_owner(pcity), pcity_dest);
3026 if (pplayer != city_owner(pcity)) {
3027 send_city_info(pplayer, pcity);
3028 send_city_info(city_owner(pcity), pcity_homecity);
3030 } city_list_iterate_end;
3033 /* May cause an incident */
3034 action_consequence_success(est_if_able ?
3035 ACTION_TRADE_ROUTE :
3036 ACTION_MARKETPLACE,
3037 pplayer, city_owner(pcity_dest),
3038 city_tile(pcity_dest),
3039 city_link(pcity_dest));
3041 conn_list_do_unbuffer(pplayer->connections);
3043 /* Free data. */
3044 city_list_destroy(cities_out_of_home);
3045 city_list_destroy(cities_out_of_dest);
3047 return TRUE;
3050 /**************************************************************************
3051 Assign the unit to the battlegroup.
3053 Battlegroups are handled entirely by the client, so all we have to
3054 do here is save the battlegroup ID so that it'll be persistent.
3055 **************************************************************************/
3056 void handle_unit_battlegroup(struct player *pplayer,
3057 int unit_id, int battlegroup)
3059 struct unit *punit = player_unit_by_number(pplayer, unit_id);
3061 if (NULL == punit) {
3062 /* Probably died or bribed. */
3063 log_verbose("handle_unit_battlegroup() invalid unit %d", unit_id);
3064 return;
3067 punit->battlegroup = CLIP(-1, battlegroup, MAX_NUM_BATTLEGROUPS);
3070 /**************************************************************************
3071 Handle request to set unit to autosettler mode.
3072 **************************************************************************/
3073 void handle_unit_autosettlers(struct player *pplayer, int unit_id)
3075 struct unit *punit = player_unit_by_number(pplayer, unit_id);
3077 if (NULL == punit) {
3078 /* Probably died or bribed. */
3079 log_verbose("handle_unit_autosettlers() invalid unit %d", unit_id);
3080 return;
3083 if (!can_unit_do_autosettlers(punit))
3084 return;
3086 punit->ai_controlled = TRUE;
3087 send_unit_info(NULL, punit);
3090 /**************************************************************************
3091 Update everything that needs changing when unit activity changes from
3092 old activity to new one.
3093 **************************************************************************/
3094 static void unit_activity_dependencies(struct unit *punit,
3095 enum unit_activity old_activity,
3096 struct extra_type *old_target)
3098 switch (punit->activity) {
3099 case ACTIVITY_IDLE:
3100 switch (old_activity) {
3101 case ACTIVITY_PILLAGE:
3103 if (old_target != NULL) {
3104 unit_list_iterate_safe(unit_tile(punit)->units, punit2) {
3105 if (punit2->activity == ACTIVITY_PILLAGE) {
3106 extra_deps_iterate(&(punit2->activity_target->reqs), pdep) {
3107 if (pdep == old_target) {
3108 set_unit_activity(punit2, ACTIVITY_IDLE);
3109 send_unit_info(NULL, punit2);
3110 break;
3112 } extra_deps_iterate_end;
3114 } unit_list_iterate_safe_end;
3116 break;
3118 case ACTIVITY_EXPLORE:
3119 /* Restore unit's control status */
3120 punit->ai_controlled = FALSE;
3121 break;
3122 default:
3123 ; /* do nothing */
3125 break;
3126 case ACTIVITY_EXPLORE:
3127 punit->ai_controlled = TRUE;
3128 set_unit_activity(punit, ACTIVITY_EXPLORE);
3129 send_unit_info(NULL, punit);
3130 break;
3131 default:
3132 /* do nothing */
3133 break;
3137 /**************************************************************************
3138 Handle request for changing activity.
3139 **************************************************************************/
3140 void unit_activity_handling(struct unit *punit,
3141 enum unit_activity new_activity)
3143 /* Must specify target for ACTIVITY_BASE */
3144 fc_assert_ret(new_activity != ACTIVITY_BASE
3145 && new_activity != ACTIVITY_GEN_ROAD);
3147 if (new_activity == ACTIVITY_PILLAGE) {
3148 struct extra_type *target = NULL;
3150 /* Assume untargeted pillaging if no target specified */
3151 unit_activity_handling_targeted(punit, new_activity, &target);
3152 } else if (can_unit_do_activity(punit, new_activity)) {
3153 enum unit_activity old_activity = punit->activity;
3154 struct extra_type *old_target = punit->activity_target;
3156 free_unit_orders(punit);
3157 set_unit_activity(punit, new_activity);
3158 send_unit_info(NULL, punit);
3159 unit_activity_dependencies(punit, old_activity, old_target);
3163 /**************************************************************************
3164 Handle request for targeted activity.
3165 **************************************************************************/
3166 void unit_activity_handling_targeted(struct unit *punit,
3167 enum unit_activity new_activity,
3168 struct extra_type **new_target)
3170 if (!activity_requires_target(new_activity)) {
3171 unit_activity_handling(punit, new_activity);
3172 } else if (can_unit_do_activity_targeted(punit, new_activity, *new_target)) {
3173 enum unit_activity old_activity = punit->activity;
3174 struct extra_type *old_target = punit->activity_target;
3175 enum unit_activity stored_activity = new_activity;
3177 free_unit_orders(punit);
3178 unit_assign_specific_activity_target(punit,
3179 &new_activity, new_target);
3180 if (new_activity != stored_activity
3181 && !activity_requires_target(new_activity)) {
3182 /* unit_assign_specific_activity_target() changed our target activity
3183 * (to ACTIVITY_IDLE in practice) */
3184 unit_activity_handling(punit, new_activity);
3185 } else {
3186 set_unit_activity_targeted(punit, new_activity, *new_target);
3187 send_unit_info(NULL, punit);
3188 unit_activity_dependencies(punit, old_activity, old_target);
3193 /****************************************************************************
3194 Handle a client request to load the given unit into the given transporter.
3195 ****************************************************************************/
3196 void handle_unit_load(struct player *pplayer, int cargo_id, int trans_id,
3197 int ttile_idx)
3199 struct unit *pcargo = player_unit_by_number(pplayer, cargo_id);
3200 struct unit *ptrans = game_unit_by_number(trans_id);
3201 struct tile *ptile = index_to_tile(ttile_idx);
3202 struct tile *ctile;
3203 struct tile *ttile;
3204 bool moves = FALSE;
3205 bool leave = FALSE;
3207 if (NULL == pcargo) {
3208 /* Probably died or bribed. */
3209 log_verbose("handle_unit_load() invalid cargo %d", cargo_id);
3210 return;
3213 if (NULL == ptrans) {
3214 /* Probably died or bribed. */
3215 log_verbose("handle_unit_load() invalid transport %d", trans_id);
3216 return;
3219 ttile = unit_tile(ptrans);
3220 if (!same_pos(ttile, ptile)) {
3221 /* Transport no longer in where client assumed it to be. */
3222 return;
3225 ctile = unit_tile(pcargo);
3227 if (!same_pos(ctile, ttile)) {
3228 if (pcargo->moves_left <= 0 || !unit_can_move_to_tile(pcargo, ttile, FALSE)) {
3229 return;
3232 moves = TRUE;
3235 if (unit_transported(pcargo)) {
3236 if (!can_unit_unload(pcargo, ptrans)) {
3237 /* Can't leave current transport */
3238 return;
3241 leave = TRUE;
3244 /* A player may only load their units, but they may be loaded into
3245 * other player's transporters, depending on the rules in
3246 * could_unit_load(). */
3247 if (!could_unit_load(pcargo, ptrans)) {
3248 return;
3251 /* It's possible. Let's make all the necessary steps. */
3252 if (leave) {
3253 unit_transport_unload(pcargo);
3256 if (moves) {
3257 /* Pre load move. */
3258 unit_move_handling(pcargo, ttile, FALSE, TRUE, ptrans);
3259 return;
3262 /* Load the unit and send out info to clients. */
3263 unit_transport_load_send(pcargo, ptrans);
3266 /****************************************************************************
3267 Handle a client request to unload the given unit from the given
3268 transporter.
3269 ****************************************************************************/
3270 void handle_unit_unload(struct player *pplayer, int cargo_id, int trans_id)
3272 struct unit *pcargo = game_unit_by_number(cargo_id);
3273 struct unit *ptrans = game_unit_by_number(trans_id);
3275 if (NULL == pcargo) {
3276 /* Probably died or bribed. */
3277 log_verbose("handle_unit_unload() invalid cargo %d", cargo_id);
3278 return;
3281 if (NULL == ptrans) {
3282 /* Probably died or bribed. */
3283 log_verbose("handle_unit_unload() invalid transport %d", trans_id);
3284 return;
3287 /* You are allowed to unload a unit if it is yours or if the transporter
3288 * is yours. */
3289 if (unit_owner(pcargo) != pplayer && unit_owner(ptrans) != pplayer) {
3290 return;
3293 if (!can_unit_unload(pcargo, ptrans)) {
3294 return;
3297 if (!can_unit_survive_at_tile(pcargo, unit_tile(pcargo))) {
3298 return;
3301 /* Unload the unit and send out info to clients. */
3302 unit_transport_unload_send(pcargo);
3305 /**************************************************************************
3306 Explode nuclear at a tile without enemy units
3307 **************************************************************************/
3308 void handle_unit_nuke(struct player *pplayer, int unit_id)
3310 struct unit *punit = player_unit_by_number(pplayer, unit_id);
3312 if (NULL == punit) {
3313 /* Probably died or bribed. */
3314 log_verbose("handle_unit_nuke() invalid unit %d", unit_id);
3315 return;
3318 if (!unit_can_do_action_now(punit)) {
3319 /* Exploding nuke not possible due to unitwaittime setting. */
3320 return;
3323 unit_attack_handling(punit, punit);
3326 /**************************************************************************
3327 Handle paradrop request.
3328 **************************************************************************/
3329 void handle_unit_paradrop_to(struct player *pplayer, int unit_id, int tile)
3331 struct unit *punit = player_unit_by_number(pplayer, unit_id);
3332 struct tile *ptile = index_to_tile(tile);
3334 if (NULL == punit) {
3335 /* Probably died or bribed. */
3336 log_verbose("handle_unit_paradrop_to() invalid unit %d", unit_id);
3337 return;
3340 if (NULL == ptile) {
3341 /* Shouldn't happen */
3342 log_error("handle_unit_paradrop_to() invalid tile index (%d) for %s (%d)",
3343 tile, unit_rule_name(punit), unit_id);
3344 return;
3347 (void) do_paradrop(punit, ptile);
3350 /****************************************************************************
3351 Receives route packages.
3352 ****************************************************************************/
3353 void handle_unit_orders(struct player *pplayer,
3354 const struct packet_unit_orders *packet)
3356 int length = packet->length, i;
3357 struct unit *punit = player_unit_by_number(pplayer, packet->unit_id);
3358 struct tile *src_tile = index_to_tile(packet->src_tile);
3360 if (NULL == punit) {
3361 /* Probably died or bribed. */
3362 log_verbose("handle_unit_orders() invalid unit %d", packet->unit_id);
3363 return;
3366 if (0 > length || MAX_LEN_ROUTE < length) {
3367 /* Shouldn't happen */
3368 log_error("handle_unit_orders() invalid %s (%d) "
3369 "packet length %d (max %d)", unit_rule_name(punit),
3370 packet->unit_id, length, MAX_LEN_ROUTE);
3371 return;
3374 if (src_tile != unit_tile(punit)) {
3375 /* Failed sanity check. Usually this happens if the orders were sent
3376 * in the previous turn, and the client thought the unit was in a
3377 * different position than it's actually in. The easy solution is to
3378 * discard the packet. We don't send an error message to the client
3379 * here (though maybe we should?). */
3380 log_verbose("handle_unit_orders() invalid %s (%d) tile (%d, %d) "
3381 "!= (%d, %d)", unit_rule_name(punit), punit->id,
3382 TILE_XY(src_tile), TILE_XY(unit_tile(punit)));
3383 return;
3386 if (ACTIVITY_IDLE != punit->activity) {
3387 /* New orders implicitly abandon current activity */
3388 unit_activity_handling(punit, ACTIVITY_IDLE);
3391 for (i = 0; i < length; i++) {
3392 if (packet->orders[i] < 0 || packet->orders[i] > ORDER_LAST) {
3393 log_error("%s() %s (player nb %d) has sent an invalid order %d "
3394 "at index %d, truncating", __FUNCTION__,
3395 player_name(pplayer), player_number(pplayer),
3396 packet->orders[i], i);
3397 length = i;
3398 break;
3400 switch (packet->orders[i]) {
3401 case ORDER_MOVE:
3402 case ORDER_ACTION_MOVE:
3403 if (!map_untrusted_dir_is_valid(packet->dir[i])) {
3404 log_error("handle_unit_orders() %d isn't a valid move direction. "
3405 "Sent in order number %d from %s to unit number %d.",
3406 packet->dir[i], i,
3407 player_name(pplayer), packet->unit_id);
3409 return;
3411 break;
3412 case ORDER_ACTIVITY:
3413 switch (packet->activity[i]) {
3414 case ACTIVITY_FALLOUT:
3415 case ACTIVITY_POLLUTION:
3416 case ACTIVITY_PILLAGE:
3417 case ACTIVITY_MINE:
3418 case ACTIVITY_IRRIGATE:
3419 case ACTIVITY_TRANSFORM:
3420 case ACTIVITY_CONVERT:
3421 /* Simple activities. */
3422 break;
3423 case ACTIVITY_FORTIFYING:
3424 case ACTIVITY_SENTRY:
3425 if (i != length - 1) {
3426 /* Only allowed as the last order. */
3427 log_error("handle_unit_orders() activity %d is only allowed in "
3428 "the last order. "
3429 "Sent in order number %d from %s to unit number %d.",
3430 packet->activity[i], i,
3431 player_name(pplayer), packet->unit_id);
3433 return;
3435 break;
3436 case ACTIVITY_BASE:
3437 if (!is_extra_caused_by(extra_by_number(packet->target[i]), EC_BASE)) {
3438 log_error("handle_unit_orders() %s isn't a base. "
3439 "Sent in order number %d from %s to unit number %d.",
3440 extra_rule_name(extra_by_number(packet->target[i])), i,
3441 player_name(pplayer), packet->unit_id);
3443 return;
3445 break;
3446 case ACTIVITY_GEN_ROAD:
3447 if (!is_extra_caused_by(extra_by_number(packet->target[i]), EC_ROAD)) {
3448 log_error("handle_unit_orders() %s isn't a road. "
3449 "Sent in order number %d from %s to unit number %d.",
3450 extra_rule_name(extra_by_number(packet->target[i])), i,
3451 player_name(pplayer), packet->unit_id);
3453 return;
3455 break;
3456 /* Not supported yet. */
3457 case ACTIVITY_EXPLORE:
3458 case ACTIVITY_IDLE:
3459 /* Not set from the client. */
3460 case ACTIVITY_GOTO:
3461 case ACTIVITY_FORTIFIED:
3462 /* Compatiblity, used in savegames. */
3463 case ACTIVITY_OLD_ROAD:
3464 case ACTIVITY_OLD_RAILROAD:
3465 case ACTIVITY_FORTRESS:
3466 case ACTIVITY_AIRBASE:
3467 /* Unused. */
3468 case ACTIVITY_PATROL_UNUSED:
3469 case ACTIVITY_LAST:
3470 case ACTIVITY_UNKNOWN:
3471 log_error("handle_unit_orders() unsupported activity %d. "
3472 "Sent in order number %d from %s to unit number %d.",
3473 packet->activity[i], i,
3474 player_name(pplayer), packet->unit_id);
3476 return;
3479 if (packet->target[i] == EXTRA_NONE
3480 && unit_activity_needs_target_from_client(packet->activity[i])) {
3481 /* The orders system can't do server side target assignment for
3482 * this activity. */
3483 log_error("handle_unit_orders() can't assign target for %d. "
3484 "Sent in order number %d from %s to unit number %d.",
3485 packet->activity[i], i,
3486 player_name(pplayer), packet->unit_id);
3488 return;
3491 break;
3492 case ORDER_FULL_MP:
3493 case ORDER_BUILD_CITY:
3494 case ORDER_DISBAND:
3495 case ORDER_BUILD_WONDER:
3496 case ORDER_TRADE_ROUTE:
3497 case ORDER_HOMECITY:
3498 break;
3499 case ORDER_LAST:
3500 /* An invalid order. This is handled in execute_orders. */
3501 break;
3505 /* This must be before old orders are freed. If this is is
3506 * settlers on city founding mission, city spot reservation
3507 * from goto_tile must be freed, and free_unit_orders() loses
3508 * goto_tile information */
3509 adv_unit_new_task(punit, AUT_NONE, NULL);
3511 free_unit_orders(punit);
3512 /* If we waited on a tile, reset punit->done_moving */
3513 punit->done_moving = (punit->moves_left <= 0);
3515 /* Make sure that the unit won't keep its old ai_controlled state after
3516 * it has recieved new orders from the client. */
3517 punit->ai_controlled = FALSE;
3519 if (length == 0) {
3520 fc_assert(!unit_has_orders(punit));
3521 send_unit_info(NULL, punit);
3522 return;
3525 punit->has_orders = TRUE;
3526 punit->orders.length = length;
3527 punit->orders.index = 0;
3528 punit->orders.repeat = packet->repeat;
3529 punit->orders.vigilant = packet->vigilant;
3530 punit->orders.list
3531 = fc_malloc(length * sizeof(*(punit->orders.list)));
3532 for (i = 0; i < length; i++) {
3533 punit->orders.list[i].order = packet->orders[i];
3534 punit->orders.list[i].dir = packet->dir[i];
3535 punit->orders.list[i].activity = packet->activity[i];
3536 punit->orders.list[i].target = packet->target[i];
3539 if (!packet->repeat) {
3540 punit->goto_tile = index_to_tile(packet->dest_tile);
3541 } else {
3542 /* Make sure that no old goto_tile remains. */
3543 punit->goto_tile = NULL;
3546 #ifdef DEBUG
3547 log_debug("Orders for unit %d: length:%d", packet->unit_id, length);
3548 for (i = 0; i < length; i++) {
3549 log_debug(" %d,%s", packet->orders[i], dir_get_name(packet->dir[i]));
3551 #endif
3553 if (!is_player_phase(unit_owner(punit), game.info.phase)
3554 || execute_orders(punit, TRUE)) {
3555 /* Looks like the unit survived. */
3556 send_unit_info(NULL, punit);
3560 /**************************************************************************
3561 Handle worker task assigned to the city
3562 **************************************************************************/
3563 void handle_worker_task(struct player *pplayer,
3564 const struct packet_worker_task *packet)
3566 struct city *pcity = game_city_by_number(packet->city_id);
3567 struct worker_task *ptask = NULL;
3568 struct tile *ptile = index_to_tile(packet->tile_id);
3570 if (pcity == NULL || pcity->owner != pplayer || ptile == NULL) {
3571 return;
3574 worker_task_list_iterate(pcity->task_reqs, ptask_old) {
3575 if (tile_index(ptask_old->ptile) == packet->tile_id) {
3576 ptask = ptask_old;
3578 } worker_task_list_iterate_end;
3580 if (ptask == NULL) {
3581 if (packet->activity == ACTIVITY_LAST) {
3582 return;
3585 ptask = fc_malloc(sizeof(struct worker_task));
3586 worker_task_init(ptask);
3587 worker_task_list_append(pcity->task_reqs, ptask);
3588 } else {
3589 if (packet->activity == ACTIVITY_LAST) {
3590 worker_task_list_remove(pcity->task_reqs, ptask);
3591 free(ptask);
3592 ptask = NULL;
3596 if (ptask != NULL) {
3597 ptask->ptile = ptile;
3598 ptask->act = packet->activity;
3599 if (packet->tgt >= 0) {
3600 if (packet->tgt < MAX_EXTRA_TYPES) {
3601 ptask->tgt = extra_by_number(packet->tgt);
3602 } else {
3603 log_debug("Illegal worker task target %d", packet->tgt);
3604 ptask->tgt = NULL;
3606 } else {
3607 ptask->tgt = NULL;
3609 ptask->want = packet->want;
3612 lsend_packet_worker_task(pplayer->connections, packet);