webperimental: killstack decides stack protects.
[freeciv.git] / server / barbarian.c
blobe71211ec39f70ff08c0a97a008fb322df4036247
1 /***********************************************************************
2 Freeciv - Copyright (C) 2003 - 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 /***********************************************************************
15 Functions for creating barbarians in huts, land and sea
16 Started by Jerzy Klek <jekl@altavista.net>
17 with more ideas from Falk Hueffner
18 ***********************************************************************/
20 #ifdef HAVE_CONFIG_H
21 #include <fc_config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
28 /* utility */
29 #include "fcintl.h"
30 #include "log.h"
31 #include "rand.h"
32 #include "support.h"
34 /* common */
35 #include "effects.h"
36 #include "events.h"
37 #include "game.h"
38 #include "government.h"
39 #include "map.h"
40 #include "movement.h"
41 #include "nation.h"
42 #include "research.h"
43 #include "tech.h"
44 #include "terrain.h"
45 #include "unitlist.h"
47 /* server */
48 #include "aiiface.h"
49 #include "citytools.h"
50 #include "gamehand.h"
51 #include "maphand.h"
52 #include "notify.h"
53 #include "plrhand.h"
54 #include "srv_main.h"
55 #include "stdinhand.h"
56 #include "techtools.h"
57 #include "unithand.h"
58 #include "unittools.h"
60 /* server/advisors */
61 #include "advdata.h"
63 /* ai */
64 #include "difficulty.h"
66 #include "barbarian.h"
68 #define BARBARIAN_INITIAL_VISION_RADIUS 3
69 #define BARBARIAN_INITIAL_VISION_RADIUS_SQ 9
71 /**************************************************************************
72 Is player a land barbarian?
73 **************************************************************************/
74 bool is_land_barbarian(struct player *pplayer)
76 return (pplayer->ai_common.barbarian_type == LAND_BARBARIAN
77 || pplayer->ai_common.barbarian_type == LAND_AND_SEA_BARBARIAN);
80 /**************************************************************************
81 Is player a sea barbarian?
82 **************************************************************************/
83 bool is_sea_barbarian(struct player *pplayer)
85 return (pplayer->ai_common.barbarian_type == SEA_BARBARIAN
86 || pplayer->ai_common.barbarian_type == LAND_AND_SEA_BARBARIAN);
89 /**************************************************************************
90 Creates the land/sea barbarian player and inits some stuff. If
91 barbarian player already exists, return player pointer. If barbarians
92 are dead, revive them with a new leader :-)
94 Dead barbarians forget the map and lose the money.
95 **************************************************************************/
96 struct player *create_barbarian_player(enum barbarian_type type)
98 struct player *barbarians;
99 struct nation_type *nation = NULL;
100 struct research *presearch;
102 players_iterate(old_barbs) {
103 if ((type == LAND_BARBARIAN && is_land_barbarian(old_barbs))
104 || (type == SEA_BARBARIAN && is_sea_barbarian(old_barbs))) {
105 if (!old_barbs->is_alive) {
106 old_barbs->economic.gold = 0;
107 old_barbs->is_alive = TRUE;
108 player_status_reset(old_barbs);
110 /* Free old name so pick_random_player_name() can select it again.
111 * This is needed in case ruleset defines just one leader for
112 * barbarian nation. */
113 old_barbs->name[0] = '\0';
114 server_player_set_name(old_barbs,
115 pick_random_player_name(nation_of_player(old_barbs)));
116 sz_strlcpy(old_barbs->username, _(ANON_USER_NAME));
117 old_barbs->unassigned_user = TRUE;
118 /* I need to make them to forget the map, I think */
119 whole_map_iterate(&(wld.map), ptile) {
120 map_clear_known(ptile, old_barbs);
121 } whole_map_iterate_end;
123 old_barbs->economic.gold += 100; /* New leader, new money */
125 return old_barbs;
127 } players_iterate_end;
129 /* make a new player, or not */
130 barbarians = server_create_player(-1, default_ai_type_name(), NULL, FALSE);
131 if (!barbarians) {
132 return NULL;
134 server_player_init(barbarians, TRUE, TRUE);
136 if (type == LAND_BARBARIAN || type == SEA_BARBARIAN) {
137 /* Try LAND_AND_SEA *FIRST*, so that we don't end up
138 * with one of the Land/Sea barbarians created first and
139 * then LAND_AND_SEA created instead of the second. */
140 nation = pick_a_nation(NULL, FALSE, FALSE, LAND_AND_SEA_BARBARIAN);
141 if (nation != NULL) {
142 type = LAND_AND_SEA_BARBARIAN;
146 if (nation == NULL) {
147 nation = pick_a_nation(NULL, FALSE, FALSE, type);
150 /* Ruleset loading time checks should guarantee that there always is
151 suitable nation available */
152 fc_assert(nation != NULL);
154 player_nation_defaults(barbarians, nation, TRUE);
155 if (game_was_started()) {
156 /* Find a color for the new player. */
157 assign_player_colors();
160 server.nbarbarians++;
162 sz_strlcpy(barbarians->username, _(ANON_USER_NAME));
163 barbarians->unassigned_user = TRUE;
164 barbarians->is_connected = FALSE;
165 barbarians->government = init_government_of_nation(nation);
166 fc_assert(barbarians->revolution_finishes < 0);
167 barbarians->server.got_first_city = FALSE;
168 barbarians->economic.gold = 100;
170 barbarians->phase_done = TRUE;
172 /* Do the ai */
173 set_as_ai(barbarians);
174 barbarians->ai_common.barbarian_type = type;
175 set_ai_level_directer(barbarians, game.info.skill_level);
177 presearch = research_get(barbarians);
178 init_tech(presearch, TRUE);
179 give_initial_techs(presearch, 0);
181 /* Ensure that we are at war with everyone else */
182 players_iterate(pplayer) {
183 if (pplayer != barbarians) {
184 player_diplstate_get(pplayer, barbarians)->type = DS_WAR;
185 player_diplstate_get(barbarians, pplayer)->type = DS_WAR;
187 } players_iterate_end;
189 CALL_PLR_AI_FUNC(gained_control, barbarians, barbarians);
191 log_verbose("Created barbarian %s, player %d", player_name(barbarians),
192 player_number(barbarians));
193 notify_player(NULL, NULL, E_UPRISING, ftc_server,
194 _("%s gain a leader by the name %s. Dangerous "
195 "times may lie ahead."),
196 nation_plural_for_player(barbarians),
197 player_name(barbarians));
199 send_player_all_c(barbarians, NULL);
200 /* Send research info after player info, else the client will complain
201 * about invalid team. */
202 send_research_info(presearch, NULL);
204 return barbarians;
207 /**************************************************************************
208 (Re)initialize direction checked status array based on terrain class.
209 **************************************************************************/
210 static void init_dir_checked_status(bool *checked,
211 enum terrain_class *terrainc,
212 enum terrain_class tclass)
214 int dir;
216 for (dir = 0; dir < 8; dir++) {
217 if (terrainc[dir] == tclass) {
218 checked[dir] = FALSE;
219 } else {
220 checked[dir] = TRUE;
225 /**************************************************************************
226 Return random directory from not yet checked ones.
227 **************************************************************************/
228 static int random_unchecked_direction(int possibilities, const bool *checked)
230 int j = -1;
231 int i;
233 int num = fc_rand(possibilities);
234 for (i = 0; i <= num; i++) {
235 j++;
236 while (checked[j]) {
237 j++;
238 fc_assert(j < 8);
242 return j;
245 /**************************************************************************
246 Unleash barbarians means give barbarian player some units and move them
247 out of the hut, unless there's no place to go.
249 Barbarian unit deployment algorithm: If enough free land around, deploy
250 on land, if not enough land but some sea free, load some of them on
251 boats, otherwise (not much land and no sea) kill enemy unit and stay in
252 a village. The return value indicates if the explorer survived entering
253 the vilage.
254 **************************************************************************/
255 bool unleash_barbarians(struct tile *ptile)
257 struct player *barbarians;
258 int unit_cnt;
259 int i;
260 bool alive = TRUE; /* explorer survived */
261 enum terrain_class terrainc[8];
262 struct tile *dir_tiles[8];
263 int land_tiles = 0;
264 int ocean_tiles = 0;
265 bool checked[8];
266 int checked_count;
267 int dir;
268 bool barbarian_stays = FALSE;
270 /* FIXME: When there is no L_BARBARIAN unit,
271 * but L_BARBARIAN_TECH is already available,
272 * we should unleash those.
273 * Doesn't affect any ruleset I'm aware of. */
274 if (BARBS_DISABLED == game.server.barbarianrate
275 || game.info.turn < game.server.onsetbarbarian
276 || num_role_units(L_BARBARIAN) == 0) {
277 unit_list_iterate_safe((ptile)->units, punit) {
278 wipe_unit(punit, ULR_BARB_UNLEASH, NULL);
279 } unit_list_iterate_safe_end;
280 return FALSE;
283 barbarians = create_barbarian_player(LAND_BARBARIAN);
284 if (!barbarians) {
285 return FALSE;
288 adv_data_phase_init(barbarians, TRUE);
289 CALL_PLR_AI_FUNC(phase_begin, barbarians, barbarians, TRUE);
291 unit_cnt = 3 + fc_rand(4);
292 for (i = 0; i < unit_cnt; i++) {
293 struct unit_type *punittype
294 = find_a_unit_type(L_BARBARIAN, L_BARBARIAN_TECH);
296 /* If unit cannot live on this tile, we just don't create one.
297 * Maybe find_a_unit_type() should take tile parameter, so
298 * we could get suitable unit if one exist. */
299 if (is_native_tile(punittype, ptile)) {
300 struct unit *barb_unit;
302 barb_unit = create_unit(barbarians, ptile, punittype, 0, 0, -1);
303 log_debug("Created barbarian unit %s", utype_rule_name(punittype));
304 send_unit_info(NULL, barb_unit);
308 /* Get information about surrounding terrains in terrain class level.
309 * Only needed if we consider moving units away to random directions. */
310 for (dir = 0; dir < 8; dir++) {
311 dir_tiles[dir] = mapstep(&(wld.map), ptile, dir);
312 if (dir_tiles[dir] == NULL) {
313 terrainc[dir] = terrain_class_invalid();
314 } else if (!is_non_allied_unit_tile(dir_tiles[dir], barbarians)) {
315 if (is_ocean_tile(dir_tiles[dir])) {
316 terrainc[dir] = TC_OCEAN;
317 ocean_tiles++;
318 } else {
319 terrainc[dir] = TC_LAND;
320 land_tiles++;
322 } else {
323 terrainc[dir] = terrain_class_invalid();
327 if (land_tiles >= 3) {
328 /* Enough land, scatter guys around */
329 unit_list_iterate_safe((ptile)->units, punit2) {
330 if (unit_owner(punit2) == barbarians) {
331 bool dest_found = FALSE;
333 /* Initialize checked status for checking free land tiles */
334 init_dir_checked_status(checked, terrainc, TC_LAND);
336 /* Search tile to move to */
337 for (checked_count = 0; !dest_found && checked_count < land_tiles;
338 checked_count++) {
339 int rdir = random_unchecked_direction(land_tiles - checked_count, checked);
341 if (unit_can_move_to_tile(&(wld.map), punit2, dir_tiles[rdir],
342 TRUE, FALSE)) {
343 /* Move */
344 (void) unit_move_handling(punit2, dir_tiles[rdir],
345 TRUE, TRUE, NULL);
346 log_debug("Moved barbarian unit from (%d, %d) to (%d, %d)",
347 TILE_XY(ptile), TILE_XY(dir_tiles[rdir]));
348 dest_found = TRUE;
351 checked[rdir] = TRUE;
353 if (!dest_found) {
354 /* This barbarian failed to move out of hut tile. */
355 barbarian_stays = TRUE;
358 } unit_list_iterate_safe_end;
360 } else {
361 if (ocean_tiles > 0) {
362 /* maybe it's an island, try to get on boats */
363 struct tile *btile = NULL; /* Boat tile */
365 /* Initialize checked status for checking Ocean tiles */
366 init_dir_checked_status(checked, terrainc, TC_OCEAN);
368 /* Search tile for boat. We always create just one boat. */
369 for (checked_count = 0; btile == NULL && checked_count < ocean_tiles;
370 checked_count++) {
371 struct unit_type *boat;
372 int rdir = random_unchecked_direction(ocean_tiles - checked_count, checked);
374 boat = find_a_unit_type(L_BARBARIAN_BOAT, -1);
375 if (is_native_tile(boat, dir_tiles[rdir])) {
376 (void) create_unit(barbarians, dir_tiles[rdir], boat, 0, 0, -1);
377 btile = dir_tiles[rdir];
380 checked[rdir] = TRUE;
383 if (btile) {
384 /* We do have a boat. Try to get everybody in */
385 unit_list_iterate_safe((ptile)->units, punit2) {
386 if (unit_owner(punit2) == barbarians) {
387 if (unit_can_move_to_tile(&(wld.map), punit2, btile, TRUE, FALSE)) {
388 /* Load */
389 (void) unit_move_handling(punit2, btile, TRUE, TRUE, NULL);
392 } unit_list_iterate_safe_end;
395 /* Move rest of the barbarians to random land tiles */
396 unit_list_iterate_safe((ptile)->units, punit2) {
397 if (unit_owner(punit2) == barbarians) {
398 bool dest_found = FALSE;
400 /* Initialize checked status for checking Land tiles */
401 init_dir_checked_status(checked, terrainc, TC_LAND);
403 /* Search tile to move to */
404 for (checked_count = 0; !dest_found && checked_count < land_tiles;
405 checked_count++) {
406 int rdir;
407 rdir = random_unchecked_direction(land_tiles - checked_count, checked);
409 if (unit_can_move_to_tile(&(wld.map), punit2, dir_tiles[rdir],
410 TRUE, FALSE)) {
411 /* Move */
412 (void) unit_move_handling(punit2, dir_tiles[rdir],
413 TRUE, TRUE, NULL);
414 dest_found = TRUE;
417 checked[rdir] = TRUE;
419 if (!dest_found) {
420 /* This barbarian failed to move out of hut tile. */
421 barbarian_stays = TRUE;
424 } unit_list_iterate_safe_end;
425 } else {
426 /* The village is surrounded! Barbarians cannot leave. */
427 barbarian_stays = TRUE;
431 if (barbarian_stays) {
432 /* There's barbarian in this village! Kill the explorer. */
433 unit_list_iterate_safe((ptile)->units, punit2) {
434 if (unit_owner(punit2) != barbarians) {
435 wipe_unit(punit2, ULR_BARB_UNLEASH, NULL);
436 alive = FALSE;
437 } else {
438 send_unit_info(NULL, punit2);
440 } unit_list_iterate_safe_end;
443 /* FIXME: I don't know if this is needed */
444 if (ptile) {
445 map_show_circle(barbarians, ptile, BARBARIAN_INITIAL_VISION_RADIUS_SQ);
448 return alive;
451 /**************************************************************************
452 Is sea not further than a couple of tiles away from land?
453 **************************************************************************/
454 static bool is_near_land(struct tile *tile0)
456 square_iterate(&(wld.map), tile0, 4, ptile) {
457 if (!is_ocean_tile(ptile)) {
458 return TRUE;
460 } square_iterate_end;
462 return FALSE;
465 /**************************************************************************
466 Return this or a neighbouring tile that is free of any units
467 **************************************************************************/
468 static struct tile *find_empty_tile_nearby(struct tile *ptile)
470 square_iterate(&(wld.map), ptile, 1, tile1) {
471 if (unit_list_size(tile1->units) == 0) {
472 return tile1;
474 } square_iterate_end;
476 return NULL;
479 /**************************************************************************
480 The barbarians are summoned at a randomly chosen place if:
481 1. It's not closer than MIN_UNREST_DIST and not further than
482 MAX_UNREST_DIST from the nearest city. City owner is called 'victim'
483 here.
484 2. The place or a neighbouring tile must be empty to deploy the units.
485 3. If it's the sea it shouldn't be far from the land. (questionable)
486 4. Place must be known to the victim
487 5. The uprising chance depends also on the victim empire size, its
488 government (civil_war_chance) and barbarian difficulty level.
489 6. The number of land units also depends slightly on victim's empire
490 size and barbarian difficulty level.
491 Q: The empire size is used so there are no uprisings in the beginning
492 of the game (year is not good as it can be customized), but it seems
493 a bit unjust if someone is always small. So maybe it should rather
494 be an average number of cities (all cities/player num)? Depending
495 on the victim government type is also questionable.
496 **************************************************************************/
497 static void try_summon_barbarians(void)
499 struct tile *ptile, *utile;
500 int i, dist;
501 int uprise;
502 struct city *pc;
503 struct player *barbarians, *victim;
504 struct unit_type *leader_type;
505 int barb_count, really_created = 0;
506 bool hut_present = FALSE;
507 int city_count;
508 int city_max;
510 /* We attempt the summons on a particular, random position. If this is
511 * an invalid position then the summons simply fails this time. This means
512 * that a particular tile's chance of being summoned on is independent of
513 * all the other tiles on the map - which is essential for balanced
514 * gameplay. */
515 ptile = rand_map_pos(&(wld.map));
517 if (terrain_has_flag(tile_terrain(ptile), TER_NO_BARBS)) {
518 return;
521 if (!(pc = find_closest_city(ptile, NULL, NULL, FALSE, FALSE, FALSE, FALSE,
522 FALSE, NULL))) {
523 /* any city */
524 return;
527 victim = city_owner(pc);
529 dist = real_map_distance(ptile, pc->tile);
530 log_debug("Closest city (to %d,%d) is %s (at %d,%d) distance %d.",
531 TILE_XY(ptile), city_name_get(pc), TILE_XY(pc->tile), dist);
532 if (dist > MAX_UNREST_DIST || dist < MIN_UNREST_DIST) {
533 return;
536 /* I think Sea Raiders can come out of unknown sea territory */
537 if (!(utile = find_empty_tile_nearby(ptile))
538 || (!map_is_known(utile, victim)
539 && !is_ocean_tile(utile))
540 || !is_near_land(utile)) {
541 return;
544 fc_assert(1 < game.server.barbarianrate);
546 /* do not harass small civs - in practice: do not uprise at the beginning */
547 if ((int)fc_rand(30) + 1 >
548 (int)city_list_size(victim->cities) * (game.server.barbarianrate - 1)
549 || fc_rand(100) > get_player_bonus(victim, EFT_CIVIL_WAR_CHANCE)) {
550 return;
552 log_debug("Barbarians are willing to fight");
554 /* Remove huts in place of uprising */
555 extra_type_by_cause_iterate(EC_HUT, pextra) {
556 if (tile_has_extra(utile, pextra)) {
557 tile_extra_rm_apply(utile, pextra);
558 hut_present = TRUE;
560 } extra_type_by_cause_iterate_end;
562 if (hut_present) {
563 update_tile_knowledge(utile);
566 city_count = city_list_size(victim->cities);
567 city_max = UPRISE_CIV_SIZE;
568 uprise = 1;
570 while (city_max <= city_count) {
571 uprise++;
572 city_max *= 1.2 + UPRISE_CIV_SIZE;
575 barb_count = fc_rand(3) + uprise * game.server.barbarianrate;
576 leader_type = get_role_unit(L_BARBARIAN_LEADER, 0);
578 if (!is_ocean_tile(utile)) {
579 /* land (disembark) barbarians */
580 barbarians = create_barbarian_player(LAND_BARBARIAN);
581 if (!barbarians) {
582 return;
584 for (i = 0; i < barb_count; i++) {
585 struct unit_type *punittype
586 = find_a_unit_type(L_BARBARIAN, L_BARBARIAN_TECH);
588 /* If unit cannot live on this tile, we just don't create one.
589 * Maybe find_a_unit_type() should take tile parameter, so
590 * we could get suitable unit if one exist. */
591 if (is_native_tile(punittype, utile)) {
592 (void) create_unit(barbarians, utile, punittype, 0, 0, -1);
593 really_created++;
594 log_debug("Created barbarian unit %s",utype_rule_name(punittype));
598 if (is_native_tile(leader_type, utile)) {
599 (void) create_unit(barbarians, utile,
600 leader_type, 0, 0, -1);
601 really_created++;
603 } else { /* sea raiders - their units will be veteran */
604 struct unit *ptrans;
605 struct unit_type *boat;
606 bool miniphase;
608 barbarians = create_barbarian_player(SEA_BARBARIAN);
609 if (!barbarians) {
610 return;
612 /* Setup data phase if it's not already set up. Created ferries may
613 need that data.
614 We don't know if create_barbarian_player() above created completely
615 new player or did it just return existing one. If it was existing
616 one, phase has already been set up at turn begin and will be closed
617 at turn end. If this is completely new player, we have to take care
618 of both opening and closing the data phase. Return value of
619 adv_data_phase_init() tells us if data phase was already initialized
620 at turn beginning. */
621 miniphase = adv_data_phase_init(barbarians, TRUE);
622 if (miniphase) {
623 CALL_PLR_AI_FUNC(phase_begin, barbarians, barbarians, TRUE);
626 boat = find_a_unit_type(L_BARBARIAN_BOAT,-1);
628 if (is_native_tile(boat, utile)
629 && (is_safe_ocean(&(wld.map), utile)
630 || (!utype_has_flag(boat, UTYF_COAST_STRICT)
631 && !utype_has_flag(boat, UTYF_COAST)))) {
632 int cap;
634 ptrans = create_unit(barbarians, utile, boat, 0, 0, -1);
635 really_created++;
636 cap = get_transporter_capacity(ptrans);
638 /* Fill boat with barb_count barbarians at max, leave space for leader */
639 for (i = 0; i < cap - 1 && i < barb_count; i++) {
640 struct unit_type *barb
641 = find_a_unit_type(L_BARBARIAN_SEA, L_BARBARIAN_SEA_TECH);
643 if (can_unit_type_transport(boat, utype_class(barb))) {
644 (void) create_unit_full(barbarians, utile, barb, 0, 0, -1, -1,
645 ptrans);
646 really_created++;
647 log_debug("Created barbarian unit %s", utype_rule_name(barb));
651 if (can_unit_type_transport(boat, utype_class(leader_type))) {
652 (void) create_unit_full(barbarians, utile, leader_type, 0, 0,
653 -1, -1, ptrans);
654 really_created++;
658 if (miniphase) {
659 CALL_PLR_AI_FUNC(phase_finished, barbarians, barbarians);
660 adv_data_phase_done(barbarians);
664 if (really_created == 0) {
665 /* No barbarians found suitable spot */
666 return;
669 /* Is this necessary? create_unit_full already sends unit info. */
670 unit_list_iterate(utile->units, punit2) {
671 send_unit_info(NULL, punit2);
672 } unit_list_iterate_end;
674 /* to let them know where to get you */
675 map_show_circle(barbarians, utile, BARBARIAN_INITIAL_VISION_RADIUS_SQ);
676 map_show_circle(barbarians, pc->tile, BARBARIAN_INITIAL_VISION_RADIUS_SQ);
678 /* There should probably be a different message about Sea Raiders */
679 if (is_land_barbarian(barbarians)) {
680 notify_player(victim, utile, E_UPRISING, ftc_server,
681 _("Native unrest near %s led by %s."),
682 city_link(pc),
683 player_name(barbarians));
684 } else if (map_is_known_and_seen(utile, victim, V_MAIN)) {
685 notify_player(victim, utile, E_UPRISING, ftc_server,
686 _("Sea raiders seen near %s!"),
687 city_link(pc));
691 /**************************************************************************
692 Summon barbarians out of the blue. Try more times for more difficult
693 levels - which means there can be more than one uprising in one year!
694 **************************************************************************/
695 void summon_barbarians(void)
697 int i, n;
699 if (BARBS_DISABLED == game.server.barbarianrate
700 || BARBS_HUTS_ONLY == game.server.barbarianrate) {
701 return;
704 if (game.info.turn < game.server.onsetbarbarian) {
705 return;
708 n = map_num_tiles() / MAP_FACTOR;
709 if (n == 0) {
710 /* Allow barbarians on maps smaller than MAP_FACTOR */
711 n = 1;
714 for (i = 0; i < n * (game.server.barbarianrate - 1); i++) {
715 try_summon_barbarians();