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)
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 ***********************************************************************/
15 #include <fc_config.h>
18 #include "fc_prehdrs.h"
29 #ifdef HAVE_SYS_IOCTL_H
30 #include <sys/ioctl.h>
32 #ifdef HAVE_SYS_TERMIO_H
33 #include <sys/termio.h>
35 #ifdef FREECIV_HAVE_SYS_TYPES_H
36 #include <sys/types.h>
47 #include "bitvector.h"
48 #include "capability.h"
49 #include "fc_cmdline.h"
64 #include "achievements.h"
72 #include "fc_interface.h"
73 #include "government.h"
89 #include "barbarian.h"
91 #include "citytools.h"
93 #include "connecthand.h"
106 #include "sanitycheck.h"
107 #include "savegame.h"
110 #include "settings.h"
111 #include "spacerace.h"
113 #include "stdinhand.h"
114 #include "techtools.h"
115 #include "unithand.h"
116 #include "unittools.h"
119 /* server/advisors */
121 #include "autosettlers.h"
122 #include "advbuilding.h"
123 #include "advspace.h"
124 #include "infracache.h"
126 /* server/scripting */
127 #include "script_server.h"
128 #include "luascript_types.h"
130 /* server/generator */
132 #include "mapgen_utils.h"
135 #include "aitraits.h"
136 #include "difficulty.h"
138 #include "srv_main.h"
140 static void end_turn(void);
141 static void announce_player(struct player
*pplayer
);
142 static void fc_interface_init_server(void);
144 static enum known_type
mapimg_server_tile_known(const struct tile
*ptile
,
145 const struct player
*pplayer
,
147 static struct terrain
148 *mapimg_server_tile_terrain(const struct tile
*ptile
,
149 const struct player
*pplayer
, bool knowledge
);
150 static struct player
*mapimg_server_tile_owner(const struct tile
*ptile
,
151 const struct player
*pplayer
,
153 static struct player
*mapimg_server_tile_city(const struct tile
*ptile
,
154 const struct player
*pplayer
,
156 static struct player
*mapimg_server_tile_unit(const struct tile
*ptile
,
157 const struct player
*pplayer
,
160 static int mapimg_server_plrcolor_count(void);
161 static struct rgbcolor
*mapimg_server_plrcolor_get(int i
);
163 static void handle_observer_ready(struct connection
*pconn
);
165 /* command-line arguments to server */
166 struct server_arguments srvarg
;
168 /* server aggregate information */
169 struct civserver server
;
171 /* server state information */
172 static enum server_states civserver_state
= S_S_INITIAL
;
174 /* this global is checked deep down the netcode.
175 packets handling functions can set it to none-zero, to
176 force end-of-tick asap
178 bool force_end_of_sniff
;
180 #define IDENTITY_NUMBER_SIZE 250000
181 BV_DEFINE(bv_identity_numbers
, IDENTITY_NUMBER_SIZE
);
182 bv_identity_numbers identity_numbers_used
;
184 /* server initialized flag */
185 static bool has_been_srv_init
= FALSE
;
187 /* time server processing at end-of-turn */
188 static struct timer
*eot_timer
= NULL
;
190 static struct timer
*between_turns
= NULL
;
192 /**************************************************************************
193 Initialize the game seed. This may safely be called multiple times.
194 **************************************************************************/
195 void init_game_seed(void)
197 if (game
.server
.seed_setting
== 0) {
198 /* We strip the high bit for now because neither game file nor
199 server options can handle unsigned ints yet. - Cedric */
200 game
.server
.seed
= time(NULL
) & (MAX_UINT32
>> 1);
201 #ifdef FREECIV_TESTMATIC
202 /* Log command to reproduce the gameseed */
203 log_testmatic("set gameseed %d", game
.server
.seed
);
204 #else /* FREECIV_TESTMATIC */
205 log_debug("Setting game.seed:%d", game
.server
.seed
);
206 #endif /* FREECIV_TESTMATIC */
208 game
.server
.seed
= game
.server
.seed_setting
;
211 if (!fc_rand_is_init()) {
212 fc_srand(game
.server
.seed
);
216 /**************************************************************************
217 Initialize freeciv server.
218 **************************************************************************/
221 i_am_server(); /* Tell to libfreeciv that we are server */
226 (void) bindtextdomain("freeciv-nations", get_locale_dir());
229 /* This is before ai module initializations so that if ai module
230 * wants to use registry files, it can. */
231 registry_module_init();
233 /* We want this before any AI stuff */
236 /* This must be before command line argument parsing.
237 This allocates default ai, and we want that to take place before
238 loading additional ai modules from command line. */
241 /* init server arguments... */
243 srvarg
.metaserver_no_send
= DEFAULT_META_SERVER_NO_SEND
;
244 sz_strlcpy(srvarg
.metaserver_addr
, DEFAULT_META_SERVER_ADDR
);
245 srvarg
.metaconnection_persistent
= FALSE
;
246 srvarg
.identity_name
[0] = '\0';
247 srvarg
.serverid
[0] = '\0';
249 srvarg
.bind_addr
= NULL
;
250 #ifdef FREECIV_JSON_CONNECTION
251 srvarg
.port
= FREECIV_JSON_PORT
;
252 #else /* FREECIV_JSON_CONNECTION */
253 srvarg
.port
= DEFAULT_SOCK_PORT
;
254 #endif /* FREECIV_JSON_CONNECTION */
256 srvarg
.bind_meta_addr
= NULL
;
258 srvarg
.loglevel
= LOG_NORMAL
;
260 srvarg
.log_filename
= NULL
;
261 srvarg
.fatal_assertions
= -1;
262 srvarg
.ranklog_filename
= NULL
;
263 srvarg
.load_filename
[0] = '\0';
264 srvarg
.script_filename
= NULL
;
265 srvarg
.saves_pathname
= "";
266 srvarg
.scenarios_pathname
= "";
267 srvarg
.ruleset
= NULL
;
271 srvarg
.fcdb_enabled
= FALSE
;
272 srvarg
.fcdb_conf
= NULL
;
273 srvarg
.auth_enabled
= FALSE
;
274 srvarg
.auth_allow_guests
= FALSE
;
275 srvarg
.auth_allow_newusers
= FALSE
;
277 /* mark as initialized */
278 has_been_srv_init
= TRUE
;
280 /* init character encodings. */
281 init_character_encodings(FC_DEFAULT_DATA_ENCODING
, FALSE
);
283 bind_textdomain_codeset("freeciv-nations", get_internal_encoding());
286 /* Initialize callbacks. */
287 game
.callbacks
.unit_deallocate
= identity_number_release
;
289 /* Initialize global mutexes */
290 fc_init_mutex(&game
.server
.mutexes
.city_list
);
296 /**************************************************************************
297 Handle client info packet
298 **************************************************************************/
299 void handle_client_info(struct connection
*pc
, enum gui_type gui
,
300 const char *distribution
)
302 pc
->client_gui
= gui
;
303 log_debug("%s's client has %s gui.", pc
->username
, gui_type_name(gui
));
304 if (strcmp(distribution
, "")) {
305 log_debug("It comes from %s distribution.", distribution
);
309 /**************************************************************************
310 Return current server state.
311 **************************************************************************/
312 enum server_states
server_state(void)
314 return civserver_state
;
317 /**************************************************************************
318 Set current server state.
319 **************************************************************************/
320 void set_server_state(enum server_states newstate
)
322 civserver_state
= newstate
;
325 /**************************************************************************
326 Returns iff the game was started once upon a time.
327 **************************************************************************/
328 bool game_was_started(void)
330 return (!game
.info
.is_new_game
|| S_S_INITIAL
!= server_state());
333 /****************************************************************************
334 Returns TRUE if any one game end condition is fulfilled, FALSE otherwise.
336 This function will notify players but will not set the server_state(). The
337 caller must set the server state to S_S_OVER if the function
339 ****************************************************************************/
340 bool check_for_game_over(void)
342 int candidates
, defeated
;
343 struct player
*victor
;
345 struct astring str
= ASTRING_INIT
;
347 /* Check for scenario victory; dead players can win if they are on a team
348 * with the winners. */
349 players_iterate(pplayer
) {
350 if (player_status_check(pplayer
, PSTATUS_WINNER
)
351 || get_player_bonus(pplayer
, EFT_VICTORY
) > 0) {
353 /* TRANS: Another entry in winners list (", the Tibetans") */
354 astr_add(&str
, Q_("?winners:, the %s"),
355 nation_plural_for_player(pplayer
));
357 /* TRANS: Beginning of the winners list ("the French") */
358 astr_add(&str
, Q_("?winners:the %s"),
359 nation_plural_for_player(pplayer
));
361 pplayer
->is_winner
= TRUE
;
364 } players_iterate_end
;
366 notify_conn(game
.est_connections
, NULL
, E_GAME_END
, ftc_server
,
367 /* TRANS: There can be several winners listed */
368 _("Scenario victory to %s."), astr_str(&str
));
374 /* Count candidates for the victory. */
378 /* Do not use player_iterate_alive here - dead player must be counted as
379 * defeated to end the game with a victory. */
380 players_iterate(pplayer
) {
381 if (is_barbarian(pplayer
)) {
385 if ((pplayer
)->is_alive
386 && !player_status_check((pplayer
), PSTATUS_SURRENDER
)) {
392 } players_iterate_end
;
394 if (0 == candidates
) {
395 notify_conn(game
.est_connections
, NULL
, E_GAME_END
, ftc_server
,
398 } else if (0 < defeated
) {
399 /* If nobody conceded the game, it mays be a solo game or a single team
401 fc_assert(NULL
!= victor
);
403 /* Quit if we have team victory. */
404 if (1 < team_count()) {
405 teams_iterate(pteam
) {
406 const struct player_list
*members
= team_members(pteam
);
407 int team_candidates
= 0, team_defeated
= 0;
409 if (1 == player_list_size(members
)) {
410 /* This is not really a team, single players are handled below. */
414 player_list_iterate(members
, pplayer
) {
415 if (pplayer
->is_alive
416 && !player_status_check((pplayer
), PSTATUS_SURRENDER
)) {
421 } player_list_iterate_end
;
423 fc_assert(team_candidates
+ team_defeated
424 == player_list_size(members
));
426 if (team_candidates
== candidates
&& team_defeated
< defeated
) {
427 /* We need a player in a other team to conced the game here. */
428 notify_conn(game
.est_connections
, NULL
, E_GAME_END
, ftc_server
,
429 _("Team victory to %s."),
430 team_name_translation(pteam
));
431 /* All players of the team win, even dead and surrended ones. */
432 player_list_iterate(members
, pplayer
) {
433 pplayer
->is_winner
= TRUE
;
434 } player_list_iterate_end
;
440 /* Check for allied victory. */
441 if (1 < candidates
&& victory_enabled(VC_ALLIED
)) {
442 struct player_list
*winner_list
= player_list_new();
444 /* Try to build a winner list. */
445 players_iterate_alive(pplayer
) {
446 if (is_barbarian(pplayer
)
447 || player_status_check((pplayer
), PSTATUS_SURRENDER
)) {
451 player_list_iterate(winner_list
, aplayer
) {
452 if (!pplayers_allied(aplayer
, pplayer
)) {
453 player_list_destroy(winner_list
);
457 } player_list_iterate_end
;
459 if (NULL
== winner_list
) {
462 player_list_append(winner_list
, pplayer
);
463 } players_iterate_alive_end
;
465 if (NULL
!= winner_list
) {
468 fc_assert(candidates
== player_list_size(winner_list
));
471 player_list_iterate(winner_list
, pplayer
) {
473 /* TRANS: Beginning of the winners list ("the French") */
474 astr_add(&str
, Q_("?winners:the %s"),
475 nation_plural_for_player(pplayer
));
478 /* TRANS: Another entry in winners list (", the Tibetans") */
479 astr_add(&str
, Q_("?winners:, the %s"),
480 nation_plural_for_player(pplayer
));
482 pplayer
->is_winner
= TRUE
;
483 } player_list_iterate_end
;
484 notify_conn(game
.est_connections
, NULL
, E_GAME_END
, ftc_server
,
485 /* TRANS: There can be several winners listed */
486 _("Allied victory to %s."), astr_str(&str
));
488 player_list_destroy(winner_list
);
493 /* Check for single player victory. */
494 if (1 == candidates
&& NULL
!= victor
) {
495 bool found
= FALSE
; /* We need at least one enemy defeated. */
497 players_iterate(pplayer
) {
498 if (pplayer
!= victor
499 && !is_barbarian(pplayer
)
500 && (!pplayer
->is_alive
501 || player_status_check((pplayer
), PSTATUS_SURRENDER
))
502 && pplayer
->team
!= victor
->team
503 && (!victory_enabled(VC_ALLIED
)
504 || !pplayers_allied(victor
, pplayer
))) {
508 } players_iterate_end
;
511 notify_conn(game
.est_connections
, NULL
, E_GAME_END
, ftc_server
,
512 _("Game ended in conquest victory for %s."), player_name(victor
));
513 victor
->is_winner
= TRUE
;
519 /* Check for culture victory */
520 if (victory_enabled(VC_CULTURE
)) {
521 struct player
*best
= NULL
;
523 int second_value
= -1;
525 players_iterate(pplayer
) {
526 if (is_barbarian(pplayer
) || !pplayer
->is_alive
) {
530 if (pplayer
->score
.culture
> best_value
) {
532 second_value
= best_value
;
533 best_value
= pplayer
->score
.culture
;
534 } else if (pplayer
->score
.culture
> second_value
) {
535 second_value
= pplayer
->score
.culture
;
537 } players_iterate_end
;
539 if (best
!= NULL
&& best_value
>= game
.info
.culture_vic_points
540 && best_value
> second_value
* (100 + game
.info
.culture_vic_lead
) / 100) {
541 notify_conn(game
.est_connections
, NULL
, E_GAME_END
, ftc_server
,
542 _("Game ended in cultural domination victory for %s."),
544 best
->is_winner
= TRUE
;
550 /* Quit if we are past the turn limit. */
551 if (game
.info
.turn
> game
.server
.end_turn
) {
552 notify_conn(game
.est_connections
, NULL
, E_GAME_END
, ftc_server
,
553 _("Game ended as the turn limit was exceeded."));
557 /* Check for a spacerace win. */
558 while ((victor
= check_spaceship_arrival())) {
559 const struct player_list
*members
;
562 notify_player(NULL
, NULL
, E_SPACESHIP
, ftc_server
,
563 _("The %s spaceship has arrived at Alpha Centauri."),
564 nation_adjective_for_player(victor
));
566 if (!game
.server
.endspaceship
) {
567 /* Games does not end on spaceship arrival. At least print all the
568 * arrival messages. */
572 /* This guy has won, now check if anybody else wins with him. */
573 members
= team_members(victor
->team
);
575 player_list_iterate(members
, pplayer
) {
576 if (pplayer
->is_alive
577 && !player_status_check((pplayer
), PSTATUS_SURRENDER
)) {
578 /* We need at least one player to be a winner candidate in the
583 } player_list_iterate_end
;
586 /* Let's try next arrival. */
590 if (1 < player_list_size(members
)) {
591 notify_conn(NULL
, NULL
, E_GAME_END
, ftc_server
,
592 _("Team victory to %s."),
593 team_name_translation(victor
->team
));
594 /* All players of the team win, even dead and surrended ones. */
595 player_list_iterate(members
, pplayer
) {
596 pplayer
->is_winner
= TRUE
;
597 } player_list_iterate_end
;
599 notify_conn(NULL
, NULL
, E_GAME_END
, ftc_server
,
600 _("Game ended in victory for %s."), player_name(victor
));
601 victor
->is_winner
= TRUE
;
609 /**************************************************************************
610 Send all information for when game starts or client reconnects.
611 Initial packets should have been sent before calling this function.
612 See comment in connecthand.c::establish_new_connection().
613 **************************************************************************/
614 void send_all_info(struct conn_list
*dest
)
616 conn_list_iterate(dest
, pconn
) {
617 if (conn_controls_player(pconn
)) {
618 send_attribute_block(pconn
->playing
, pconn
);
620 } conn_list_iterate_end
;
622 /* Resend player info because it could have more infos (e.g. embassy). */
623 send_player_all_c(NULL
, dest
);
624 researches_iterate(presearch
) {
625 send_research_info(presearch
, dest
);
626 } researches_iterate_end
;
628 send_all_known_tiles(dest
);
629 send_all_known_cities(dest
);
630 send_all_known_units(dest
);
631 send_spaceship_info(NULL
, dest
);
633 cities_iterate(pcity
) {
634 package_and_send_worker_tasks(pcity
);
635 } cities_iterate_end
;
638 /**************************************************************************
639 Give map information to players with EFT_REVEAL_CITIES or
640 EFT_REVEAL_MAP effects (traditionally from the Apollo Program).
641 **************************************************************************/
642 static void do_reveal_effects(void)
644 phase_players_iterate(pplayer
) {
645 if (get_player_bonus(pplayer
, EFT_REVEAL_CITIES
) > 0) {
646 players_iterate(other_player
) {
647 city_list_iterate(other_player
->cities
, pcity
) {
648 map_show_tile(pplayer
, pcity
->tile
);
649 } city_list_iterate_end
;
650 } players_iterate_end
;
652 if (get_player_bonus(pplayer
, EFT_REVEAL_MAP
) > 0) {
653 /* map_know_all will mark all unknown tiles as known and send
654 * tile, unit, and city updates as necessary. No other actions are
656 map_show_all(pplayer
);
658 } phase_players_iterate_end
;
661 /**************************************************************************
662 Give contact to players with the EFT_HAVE_CONTACTS effect (traditionally
663 from Marco Polo's Embassy).
664 **************************************************************************/
665 static void do_have_contacts_effect(void)
667 phase_players_iterate(pplayer
) {
668 if (get_player_bonus(pplayer
, EFT_HAVE_CONTACTS
) > 0) {
669 players_iterate(pother
) {
670 /* Note this gives pplayer contact with pother, but doesn't give
671 * pother contact with pplayer. This may cause problems in other
672 * parts of the code if we're not careful. */
673 make_contact(pplayer
, pother
, NULL
);
674 } players_iterate_end
;
676 } phase_players_iterate_end
;
679 /**************************************************************************
680 Handle the vision granting effect EFT_BORDER_VISION
681 **************************************************************************/
682 static void do_border_vision_effect(void)
684 if (game
.info
.borders
!= BORDERS_ENABLED
) {
685 /* Border_Vision is useless. If borders are disabled there are no
686 * borders to see inside. If borders are seen they are seen already.
687 * The borders setting can't change after the game has started. */
691 phase_players_iterate(plr
) {
692 bool new_border_vision
;
694 /* Check the Border_Vision effect for this player. */
695 new_border_vision
= (0 < get_player_bonus(plr
, EFT_BORDER_VISION
));
697 if (new_border_vision
!= plr
->server
.border_vision
) {
698 /* Border vision changed. */
701 map_set_border_vision(plr
, new_border_vision
);
703 } phase_players_iterate_end
;
706 /**************************************************************************
707 Handle environmental upsets, meaning currently pollution or fallout.
708 **************************************************************************/
709 static void update_environmental_upset(enum environment_upset_type type
,
710 int *current
, int *accum
, int *level
,
711 void (*upset_action_fn
)(int))
716 extra_type_iterate(cause
) {
717 if (extra_causes_env_upset(cause
, type
)) {
718 whole_map_iterate(&(wld
.map
), ptile
) {
719 if (tile_has_extra(ptile
, cause
)) {
722 } whole_map_iterate_end
;
724 } extra_type_iterate_end
;
728 if (*accum
< *level
) {
732 if (fc_rand((map_num_tiles() + 19) / 20) <= *accum
) {
733 upset_action_fn((wld
.map
.xsize
/ 10) + (wld
.map
.ysize
/ 10) + ((*accum
) * 5));
735 *level
+= (map_num_tiles() + 999) / 1000;
739 log_debug("environmental_upset: type=%-4d current=%-2d "
740 "level=%-2d accum=%-2d", type
, *current
, *level
, *accum
);
743 /**************************************************************************
744 Remove illegal units when armistice turns into peace treaty.
745 **************************************************************************/
746 static void remove_illegal_armistice_units(struct player
*plr1
,
749 /* Remove illegal units */
750 unit_list_iterate_safe(plr1
->units
, punit
) {
751 if (tile_owner(unit_tile(punit
)) == plr2
752 && is_military_unit(punit
)) {
753 notify_player(plr1
, unit_tile(punit
), E_DIPLOMACY
, ftc_server
,
754 _("Your %s was disbanded in accordance with "
755 "your peace treaty with the %s."),
756 unit_tile_link(punit
),
757 nation_plural_for_player(plr2
));
758 wipe_unit(punit
, ULR_ARMISTICE
, NULL
);
760 } unit_list_iterate_safe_end
;
761 unit_list_iterate_safe(plr2
->units
, punit
) {
762 if (tile_owner(unit_tile(punit
)) == plr1
763 && is_military_unit(punit
)) {
764 notify_player(plr2
, unit_tile(punit
), E_DIPLOMACY
, ftc_server
,
765 _("Your %s was disbanded in accordance with "
766 "your peace treaty with the %s."),
767 unit_tile_link(punit
),
768 nation_plural_for_player(plr1
));
769 wipe_unit(punit
, ULR_ARMISTICE
, NULL
);
771 } unit_list_iterate_safe_end
;
774 /**************************************************************************
775 Check for cease-fires and armistices running out; update cancelling
776 reasons and contact information.
777 **************************************************************************/
778 static void update_diplomatics(void)
780 players_iterate(plr1
) {
781 players_iterate(plr2
) {
782 struct player_diplstate
*state
= player_diplstate_get(plr1
, plr2
);
784 /* Players might just met when first of them was being handled
785 * (pact with third player changed and units got bounced next
786 * to second unit to form first contact)
787 * Do not decrease the counters for the other player yet in this turn */
788 if (state
->first_contact_turn
!= game
.info
.turn
) {
789 struct player_diplstate
*state2
= player_diplstate_get(plr2
, plr1
);
791 state
->has_reason_to_cancel
= MAX(state
->has_reason_to_cancel
- 1, 0);
792 state
->contact_turns_left
= MAX(state
->contact_turns_left
- 1, 0);
794 if (state
->type
== DS_ARMISTICE
795 /* Don't count down if auto canceled this turn. Auto canceling
796 * happens in this loop. */
797 && state
->auto_cancel_turn
!= game
.info
.turn
) {
799 if (state
->turns_left
<= 0) {
800 state
->type
= DS_PEACE
;
801 state2
->type
= DS_PEACE
;
802 state
->turns_left
= 0;
803 state2
->turns_left
= 0;
804 remove_illegal_armistice_units(plr1
, plr2
);
808 if (state
->type
== DS_CEASEFIRE
) {
810 switch(state
->turns_left
) {
812 notify_player(plr1
, NULL
, E_DIPLOMACY
, ftc_server
,
813 _("Concerned citizens point out that the cease-fire "
814 "with %s will run out soon."), player_name(plr2
));
815 /* Message to plr2 will be done when plr1 and plr2 will be swapped.
816 * Else, we will get a message duplication. Note the case is not
817 * the below, because the state will be changed for both players to
821 notify_player(plr1
, NULL
, E_DIPLOMACY
, ftc_server
,
822 _("The cease-fire with %s has run out. "
823 "You are now at war with the %s."),
825 nation_plural_for_player(plr2
));
826 notify_player(plr2
, NULL
, E_DIPLOMACY
, ftc_server
,
827 _("The cease-fire with %s has run out. "
828 "You are now at war with the %s."),
830 nation_plural_for_player(plr1
));
831 state
->type
= DS_WAR
;
832 state2
->type
= DS_WAR
;
833 state
->turns_left
= 0;
834 state2
->turns_left
= 0;
836 enter_war(plr1
, plr2
);
838 city_map_update_all_cities_for_player(plr1
);
839 city_map_update_all_cities_for_player(plr2
);
842 /* Avoid love-love-hate triangles */
843 players_iterate_alive(plr3
) {
844 if (plr3
!= plr1
&& plr3
!= plr2
845 && pplayers_allied(plr3
, plr1
)
846 && pplayers_allied(plr3
, plr2
)) {
847 struct player_diplstate
*to1
848 = player_diplstate_get(plr3
, plr1
);
849 struct player_diplstate
*from1
850 = player_diplstate_get(plr1
, plr3
);
851 struct player_diplstate
*to2
852 = player_diplstate_get(plr3
, plr2
);
853 struct player_diplstate
*from2
854 = player_diplstate_get(plr2
, plr3
);
856 notify_player(plr3
, NULL
, E_TREATY_BROKEN
, ftc_server
,
857 _("The cease-fire between %s and %s has run out. "
858 "They are at war. You cancel your alliance "
863 /* Cancel the alliance. */
864 to1
->has_reason_to_cancel
= TRUE
;
865 to2
->has_reason_to_cancel
= TRUE
;
866 handle_diplomacy_cancel_pact(plr3
, player_number(plr1
), CLAUSE_ALLIANCE
);
867 handle_diplomacy_cancel_pact(plr3
, player_number(plr2
), CLAUSE_ALLIANCE
);
869 /* Avoid asymmetric turns_left for the armistice. */
870 to1
->auto_cancel_turn
= game
.info
.turn
;
871 from1
->auto_cancel_turn
= game
.info
.turn
;
873 to2
->auto_cancel_turn
= game
.info
.turn
;
874 from2
->auto_cancel_turn
= game
.info
.turn
;
876 /* Count down for this turn. */
883 } players_iterate_alive_end
;
888 } players_iterate_end
;
889 } players_iterate_end
;
892 /****************************************************************************
893 Check all players to see whether they are dying.
895 WARNING: do not call this while doing any handling of players, units,
896 etc. If a player dies, all his units will be wiped and other data will
898 ****************************************************************************/
899 static void kill_dying_players(void)
901 bool voter_died
= FALSE
;
903 players_iterate_alive(pplayer
) {
904 /* cities or units remain? */
905 if (0 == city_list_size(pplayer
->cities
)
906 && 0 == unit_list_size(pplayer
->units
)) {
907 player_status_add(pplayer
, PSTATUS_DYING
);
909 /* also UTYF_GAMELOSS in unittools server_remove_unit() */
910 if (player_status_check(pplayer
, PSTATUS_DYING
)) {
911 /* Can't get more dead than this. */
912 voter_died
= voter_died
|| pplayer
->is_connected
;
913 kill_player(pplayer
);
915 } players_iterate_alive_end
;
918 send_updated_vote_totals(NULL
);
922 /**************************************************************************
923 Called at the start of each (new) phase to do AI activities.
924 **************************************************************************/
925 static void ai_start_phase(void)
927 phase_players_iterate(pplayer
) {
928 if (is_ai(pplayer
)) {
929 CALL_PLR_AI_FUNC(first_activities
, pplayer
, pplayer
);
931 } phase_players_iterate_end
;
932 kill_dying_players();
935 /**************************************************************************
936 Handle the beginning of each turn.
937 Note: This does not give "time" to any player;
938 it is solely for updating turn-dependent data.
939 **************************************************************************/
940 static void begin_turn(bool is_new_turn
)
942 log_debug("Begin turn");
944 event_cache_remove_old();
946 /* Reset this each turn. */
948 if (game
.info
.phase_mode
!= game
.server
.phase_mode_stored
) {
949 event_cache_phases_invalidate();
950 game
.info
.phase_mode
= game
.server
.phase_mode_stored
;
954 /* NB: Phase logic must match is_player_phase(). */
955 switch (game
.info
.phase_mode
) {
957 game
.server
.num_phases
= 1;
959 case PMT_PLAYERS_ALTERNATE
:
960 game
.server
.num_phases
= player_count();
962 case PMT_TEAMS_ALTERNATE
:
963 game
.server
.num_phases
= team_count();
966 log_error("Unrecognized phase mode %d in begin_turn().",
967 game
.info
.phase_mode
);
968 game
.server
.num_phases
= 1;
971 send_game_info(NULL
);
974 script_server_signal_emit("turn_begin", 2,
975 API_TYPE_INT
, game
.info
.turn
,
976 API_TYPE_INT
, game
.info
.year
);
977 script_server_signal_emit("turn_started", 2,
978 API_TYPE_INT
, game
.info
.turn
> 0 ? game
.info
.turn
- 1: game
.info
.turn
,
979 API_TYPE_INT
, game
.info
.year
);
981 /* We build scores at the beginning of every turn. We have to
982 * build them at the beginning so that the AI can use the data,
983 * and we are sure to have it when we need it. */
984 players_iterate(pplayer
) {
985 calc_civ_score(pplayer
);
986 } players_iterate_end
;
989 /* Retire useless barbarian units */
990 players_iterate(pplayer
) {
991 unit_list_iterate_safe(pplayer
->units
, punit
) {
992 struct tile
*ptile
= punit
->tile
;
994 if (unit_can_be_retired(punit
)
995 && fc_rand(100) < get_unit_bonus(punit
, EFT_RETIRE_PCT
)) {
996 notify_player(pplayer
, ptile
, E_UNIT_LOST_MISC
, ftc_server
,
997 /* TRANS: %s is a unit type */
998 _("%s retired!"), unit_tile_link(punit
));
999 wipe_unit(punit
, ULR_RETIRED
, NULL
);
1002 } unit_list_iterate_safe_end
;
1003 } players_iterate_end
;
1006 /* find out if users attached to players have been attached to those players
1007 * for long enough. The first user to do so becomes "associated" to that
1008 * player for ranking purposes. */
1009 players_iterate(pplayer
) {
1010 if (pplayer
->unassigned_ranked
1011 && pplayer
->user_turns
++ > TURNS_NEEDED_TO_RANK
1012 && pplayer
->is_alive
) {
1013 sz_strlcpy(pplayer
->ranked_username
, pplayer
->username
);
1014 pplayer
->unassigned_ranked
= pplayer
->unassigned_user
;
1016 } players_iterate_end
;
1019 /* See if the value of fog of war has changed */
1020 if (game
.info
.fogofwar
!= game
.server
.fogofwar_old
) {
1021 if (game
.info
.fogofwar
) {
1022 enable_fog_of_war();
1023 game
.server
.fogofwar_old
= TRUE
;
1025 disable_fog_of_war();
1026 game
.server
.fogofwar_old
= FALSE
;
1030 if (game
.info
.phase_mode
== PMT_CONCURRENT
) {
1031 log_debug("Shuffleplayers");
1035 game
.info
.phase
= 0;
1041 /**************************************************************************
1042 Begin a phase of movement. This handles all beginning-of-phase actions
1043 for one or more players.
1044 **************************************************************************/
1045 static void begin_phase(bool is_new_phase
)
1047 log_debug("Begin phase");
1049 conn_list_do_buffer(game
.est_connections
);
1051 phase_players_iterate(pplayer
) {
1052 if (is_new_phase
|| !game
.server
.turnblock
) {
1053 /* Otherwise respect what was loaded from the savegame. */
1054 pplayer
->phase_done
= FALSE
;
1056 pplayer
->ai_phase_done
= FALSE
;
1057 } phase_players_iterate_end
;
1058 send_player_all_c(NULL
, NULL
);
1060 dlsend_packet_start_phase(game
.est_connections
, game
.info
.phase
);
1062 if (!is_new_phase
) {
1063 conn_list_iterate(game
.est_connections
, pconn
) {
1064 send_diplomatic_meetings(pconn
);
1065 } conn_list_iterate_end
;
1068 /* Must be the first thing as it is needed for lots of functions below! */
1069 phase_players_iterate(pplayer
) {
1070 /* human players also need this for building advice */
1071 adv_data_phase_init(pplayer
, is_new_phase
);
1072 CALL_PLR_AI_FUNC(phase_begin
, pplayer
, pplayer
, is_new_phase
);
1073 } phase_players_iterate_end
;
1076 /* Unit "end of turn" activities - of course these actually go at
1077 * the start of the turn! */
1078 phase_players_iterate(pplayer
) {
1079 update_unit_activities(pplayer
);
1081 } phase_players_iterate_end
;
1082 /* Execute orders after activities have been completed (roads built,
1083 * pillage done, etc.). */
1084 phase_players_iterate(pplayer
) {
1085 execute_unit_orders(pplayer
);
1087 } phase_players_iterate_end
;
1088 phase_players_iterate(pplayer
) {
1089 finalize_unit_phase_beginning(pplayer
);
1090 } phase_players_iterate_end
;
1094 phase_players_iterate(pplayer
) {
1095 log_debug("beginning player turn for #%d (%s)",
1096 player_number(pplayer
), player_name(pplayer
));
1097 if (is_human(pplayer
)) {
1098 building_advisor(pplayer
);
1100 } phase_players_iterate_end
;
1102 phase_players_iterate(pplayer
) {
1103 send_player_cities(pplayer
);
1104 } phase_players_iterate_end
;
1106 flush_packets(); /* to curb major city spam */
1107 conn_list_do_unbuffer(game
.est_connections
);
1109 alive_phase_players_iterate(pplayer
) {
1110 update_revolution(pplayer
);
1111 } alive_phase_players_iterate_end
;
1114 /* Try to avoid hiding events under a diplomacy dialog */
1115 phase_players_iterate(pplayer
) {
1116 if (is_ai(pplayer
)) {
1117 CALL_PLR_AI_FUNC(diplomacy_actions
, pplayer
, pplayer
);
1119 } phase_players_iterate_end
;
1121 log_debug("Aistartturn");
1124 phase_players_iterate(pplayer
) {
1125 if (is_ai(pplayer
)) {
1126 CALL_PLR_AI_FUNC(restart_phase
, pplayer
, pplayer
);
1128 } phase_players_iterate_end
;
1133 game
.tinfo
.last_turn_change_time
= (float)game
.server
.turn_change_time
;
1134 game
.tinfo
.seconds_to_phasedone
= (double)current_turn_timeout();
1135 game
.server
.phase_timer
= timer_renew(game
.server
.phase_timer
,
1136 TIMER_USER
, TIMER_ACTIVE
);
1137 timer_start(game
.server
.phase_timer
);
1138 send_game_info(NULL
);
1140 if (game
.server
.num_phases
== 1) {
1141 /* All players in the same phase.
1142 * This means that AI has been handled above, and server
1143 * will be responsive again */
1144 lsend_packet_begin_turn(game
.est_connections
);
1148 /**************************************************************************
1149 End a phase of movement. This handles all end-of-phase actions
1150 for one or more players.
1151 **************************************************************************/
1152 static void end_phase(void)
1154 log_debug("Endphase");
1157 * This empties the client Messages window; put this before
1158 * everything else below, since otherwise any messages from the
1159 * following parts get wiped out before the user gets a chance to
1162 phase_players_iterate(pplayer
) {
1163 /* Unlike the start_phase packet we only send this one to the active
1165 lsend_packet_end_phase(pplayer
->connections
);
1166 } phase_players_iterate_end
;
1168 /* Enact any policy changes.
1169 * Do this first so that following end-phase activities take the
1170 * change into account. */
1171 phase_players_iterate(pplayer
) {
1172 multipliers_iterate(pmul
) {
1173 pplayer
->multipliers
[multiplier_index(pmul
)] =
1174 pplayer
->multipliers_target
[multiplier_index(pmul
)];
1175 } multipliers_iterate_end
;
1176 } phase_players_iterate_end
;
1178 phase_players_iterate(pplayer
) {
1179 struct research
*presearch
= research_get(pplayer
);
1181 if (A_UNSET
== presearch
->researching
) {
1182 Tech_type_id next_tech
= research_goal_step(presearch
,
1183 presearch
->tech_goal
);
1185 if (A_UNSET
!= next_tech
) {
1186 choose_tech(presearch
, next_tech
);
1188 choose_random_tech(presearch
);
1190 /* add the researched bulbs to the pool; do *NOT* checvk for finished
1192 update_bulbs(pplayer
, 0, FALSE
);
1194 } phase_players_iterate_end
;
1196 /* Freeze sending of cities. */
1197 send_city_suppression(TRUE
);
1199 /* AI end of turn activities */
1200 players_iterate(pplayer
) {
1201 unit_list_iterate(pplayer
->units
, punit
) {
1202 CALL_PLR_AI_FUNC(unit_turn_end
, pplayer
, punit
);
1203 } unit_list_iterate_end
;
1204 } players_iterate_end
;
1205 phase_players_iterate(pplayer
) {
1206 auto_settlers_player(pplayer
);
1207 if (is_ai(pplayer
)) {
1208 CALL_PLR_AI_FUNC(last_activities
, pplayer
, pplayer
);
1210 } phase_players_iterate_end
;
1212 /* Refresh cities */
1213 phase_players_iterate(pplayer
) {
1214 research_get(pplayer
)->got_tech
= FALSE
;
1215 } phase_players_iterate_end
;
1217 phase_players_iterate(pplayer
) {
1218 do_tech_parasite_effect(pplayer
);
1219 player_restore_units(pplayer
);
1221 /* If player finished spaceship parts last turn already, and didn't place them
1222 * during this entire turn, autoplace them. */
1223 if (adv_spaceship_autoplace(pplayer
, &pplayer
->spaceship
)) {
1224 notify_player(pplayer
, NULL
, E_SPACESHIP
, ftc_server
,
1225 _("Automatically placed spaceship parts that were still not placed."));
1228 update_city_activities(pplayer
);
1229 city_thaw_workers_queue();
1230 pplayer
->culture
+= nation_history_gain(pplayer
);
1231 research_get(pplayer
)->researching_saved
= A_UNKNOWN
;
1232 /* reduce the number of bulbs by the amount needed for tech upkeep and
1233 * check for finished research */
1234 update_bulbs(pplayer
, -player_tech_upkeep(pplayer
), TRUE
);
1236 } phase_players_iterate_end
;
1238 /* Some player/global effect may have changed cities' vision range */
1239 phase_players_iterate(pplayer
) {
1240 refresh_player_cities_vision(pplayer
);
1241 } phase_players_iterate_end
;
1243 kill_dying_players();
1245 /* Unfreeze sending of cities. */
1246 send_city_suppression(FALSE
);
1248 phase_players_iterate(pplayer
) {
1249 send_player_cities(pplayer
);
1250 } phase_players_iterate_end
;
1251 flush_packets(); /* to curb major city spam */
1253 do_reveal_effects();
1254 do_have_contacts_effect();
1255 do_border_vision_effect();
1257 phase_players_iterate(pplayer
) {
1258 CALL_PLR_AI_FUNC(phase_finished
, pplayer
, pplayer
);
1259 /* This has to be after all access to advisor data. */
1260 /* We used to run this for ai players only, but data phase
1261 is initialized for human players also. */
1262 adv_data_phase_done(pplayer
);
1263 } phase_players_iterate_end
;
1266 /**************************************************************************
1267 Handle the end of each turn.
1268 **************************************************************************/
1269 static void end_turn(void)
1271 int food
= 0, shields
= 0, trade
= 0, settlers
= 0;
1273 log_debug("Endturn");
1275 /* Hack: because observer players never get an end-phase packet we send
1277 conn_list_iterate(game
.est_connections
, pconn
) {
1278 if (NULL
== pconn
->playing
) {
1279 send_packet_end_phase(pconn
);
1281 } conn_list_iterate_end
;
1283 lsend_packet_end_turn(game
.est_connections
);
1285 map_calculate_borders();
1287 /* Output some AI measurement information */
1288 players_iterate(pplayer
) {
1289 if (!is_ai(pplayer
) || is_barbarian(pplayer
)) {
1292 unit_list_iterate(pplayer
->units
, punit
) {
1293 if (unit_is_cityfounder(punit
)) {
1296 } unit_list_iterate_end
;
1297 city_list_iterate(pplayer
->cities
, pcity
) {
1298 shields
+= pcity
->prod
[O_SHIELD
];
1299 food
+= pcity
->prod
[O_FOOD
];
1300 trade
+= pcity
->prod
[O_TRADE
];
1301 } city_list_iterate_end
;
1302 log_debug("%s T%d cities:%d pop:%d food:%d prod:%d "
1303 "trade:%d settlers:%d units:%d", player_name(pplayer
),
1304 game
.info
.turn
, city_list_size(pplayer
->cities
),
1305 total_player_citizens(pplayer
), food
, shields
, trade
,
1306 settlers
, unit_list_size(pplayer
->units
));
1307 } players_iterate_end
;
1309 log_debug("Season of native unrests");
1310 summon_barbarians(); /* wild guess really, no idea where to put it, but
1311 * I want to give them chance to move their units */
1313 if (game
.server
.migration
) {
1314 log_debug("Season of migrations");
1315 if (check_city_migrations()) {
1316 /* Make sure everyone has updated information about BOTH ends of the
1317 * migration movements. */
1318 players_iterate(plr
) {
1319 city_list_iterate(plr
->cities
, pcity
) {
1320 send_city_info(NULL
, pcity
);
1321 } city_list_iterate_end
;
1322 } players_iterate_end
;
1328 /* Check for new achievements during the turn.
1329 * This is not within phase, as multiple players may
1330 * achieve at the same turn and everyone deserves equal opportunity
1332 achievements_iterate(ach
) {
1333 struct player_list
*achievers
= player_list_new();
1334 struct player
*first
= achievement_plr(ach
, achievers
);
1335 struct packet_achievement_info pack
;
1337 pack
.id
= achievement_index(ach
);
1340 if (first
!= NULL
) {
1341 notify_player(first
, NULL
, E_ACHIEVEMENT
, ftc_server
,
1342 "%s", achievement_first_msg(ach
));
1346 lsend_packet_achievement_info(first
->connections
, &pack
);
1348 script_server_signal_emit("achievement_gained", 3,
1349 API_TYPE_ACHIEVEMENT
, ach
,
1350 API_TYPE_PLAYER
, first
,
1351 API_TYPE_BOOL
, TRUE
);
1358 player_list_iterate(achievers
, pplayer
) {
1359 /* Message already sent to first one */
1360 if (pplayer
!= first
) {
1361 notify_player(pplayer
, NULL
, E_ACHIEVEMENT
, ftc_server
,
1362 "%s", achievement_later_msg(ach
));
1364 lsend_packet_achievement_info(pplayer
->connections
, &pack
);
1366 script_server_signal_emit("achievement_gained", 3,
1367 API_TYPE_ACHIEVEMENT
, ach
,
1368 API_TYPE_PLAYER
, pplayer
,
1369 API_TYPE_BOOL
, FALSE
);
1371 } player_list_iterate_end
;
1374 player_list_destroy(achievers
);
1375 } achievements_iterate_end
;
1377 if (game
.info
.global_warming
) {
1378 update_environmental_upset(EUT_GLOBAL_WARMING
, &game
.info
.heating
,
1379 &game
.info
.globalwarming
,
1380 &game
.info
.warminglevel
, global_warming
);
1383 if (game
.info
.nuclear_winter
) {
1384 update_environmental_upset(EUT_NUCLEAR_WINTER
, &game
.info
.cooling
,
1385 &game
.info
.nuclearwinter
,
1386 &game
.info
.coolinglevel
, nuclear_winter
);
1389 /* Handle disappearing extras before appearing extras ->
1390 * Extra never appears only to disappear at the same turn,
1391 * but it can disappear and reappear. */
1392 extra_type_by_rmcause_iterate(ERM_DISAPPEARANCE
, pextra
) {
1393 whole_map_iterate(&(wld
.map
), ptile
) {
1394 if (tile_has_extra(ptile
, pextra
)
1395 && fc_rand(10000) < pextra
->disappearance_chance
1396 && can_extra_disappear(pextra
, ptile
)) {
1397 tile_extra_rm_apply(ptile
, pextra
);
1399 update_tile_knowledge(ptile
);
1401 if (tile_owner(ptile
) != NULL
) {
1402 /* TODO: Should notify players nearby even when borders disabled,
1403 * like in case of barbarian uprising */
1404 notify_player(tile_owner(ptile
), ptile
,
1405 E_SPONTANEOUS_EXTRA
, ftc_server
,
1406 /* TRANS: Small Fish disappears from (32, 72). */
1407 _("%s disappears from %s."),
1408 extra_name_translation(pextra
),
1412 /* Unit activities at the target tile and its neighbors may now
1413 * be illegal because of present reqs. */
1414 unit_activities_cancel_all_illegal(ptile
);
1415 adjc_iterate(ptile
, n_tile
) {
1416 unit_activities_cancel_all_illegal(n_tile
);
1419 } whole_map_iterate_end
;
1420 } extra_type_by_rmcause_iterate_end
;
1422 extra_type_by_cause_iterate(EC_APPEARANCE
, pextra
) {
1423 whole_map_iterate(&(wld
.map
), ptile
) {
1424 if (!tile_has_extra(ptile
, pextra
)
1425 && fc_rand(10000) < pextra
->appearance_chance
1426 && can_extra_appear(pextra
, ptile
)) {
1428 tile_extra_apply(ptile
, pextra
);
1430 update_tile_knowledge(ptile
);
1432 if (tile_owner(ptile
) != NULL
) {
1433 /* TODO: Should notify players nearby even when borders disabled,
1434 * like in case of barbarian uprising */
1435 notify_player(tile_owner(ptile
), ptile
,
1436 E_SPONTANEOUS_EXTRA
, ftc_server
,
1437 /* TRANS: Small Fish appears to (32, 72). */
1438 _("%s appears to %s."),
1439 extra_name_translation(pextra
),
1443 /* Unit activities at the target tile and its neighbors may now
1444 * be illegal because of !present reqs. */
1445 unit_activities_cancel_all_illegal(ptile
);
1446 adjc_iterate(ptile
, n_tile
) {
1447 unit_activities_cancel_all_illegal(n_tile
);
1450 } whole_map_iterate_end
;
1451 } extra_type_by_cause_iterate_end
;
1453 update_diplomatics();
1454 make_history_report();
1458 send_city_turn_notifications(NULL
);
1460 log_debug("Gamenextyear");
1461 game_advance_year();
1462 players_iterate_alive(pplayer
) {
1463 pplayer
->turns_alive
++;
1464 } players_iterate_alive_end
;
1466 log_debug("Updatetimeout");
1469 log_debug("Sendgameinfo");
1470 send_game_info(NULL
);
1472 log_debug("Sendplayerinfo");
1473 send_player_all_c(NULL
, NULL
);
1475 log_debug("Sendresearchinfo");
1476 researches_iterate(presearch
) {
1477 send_research_info(presearch
, NULL
);
1478 } researches_iterate_end
;
1480 log_debug("Sendyeartoclients");
1481 send_year_to_clients();
1484 /**************************************************************************
1485 Save game with autosave filename
1486 **************************************************************************/
1487 void save_game_auto(const char *save_reason
, enum autosave_type type
)
1490 const char *reason_filename
= NULL
;
1492 if (!(game
.server
.autosaves
& (1 << type
))) {
1498 reason_filename
= NULL
;
1501 reason_filename
= "final";
1504 reason_filename
= "quitidle";
1507 reason_filename
= "interrupted";
1510 reason_filename
= "timer";
1514 fc_assert(256 > strlen(game
.server
.save_name
));
1516 if (type
!= AS_TIMER
) {
1517 generate_save_name(game
.server
.save_name
, filename
, sizeof(filename
),
1520 fc_snprintf(filename
, sizeof(filename
), "%s-timer", game
.server
.save_name
);
1522 save_game(filename
, save_reason
, FALSE
);
1525 /**************************************************************************
1526 Start actual game. Everything has been set up already.
1527 **************************************************************************/
1528 void start_game(void)
1530 if (S_S_INITIAL
!= server_state()) {
1531 con_puts(C_SYNTAX
, _("The game is already running."));
1535 /* Remove ALLOW_CTRL from whoever has it (gotten from 'first'). */
1536 conn_list_iterate(game
.est_connections
, pconn
) {
1537 if (pconn
->access_level
== ALLOW_CTRL
) {
1538 notify_conn(NULL
, NULL
, E_SETTING
, ftc_server
,
1539 _("%s lost control cmdlevel on "
1540 "game start. Use voting from now on."),
1542 conn_set_access(pconn
, ALLOW_BASIC
, FALSE
);
1544 } conn_list_iterate_end
;
1545 set_running_game_access_level();
1547 con_puts(C_OK
, _("Starting game."));
1549 /* Prevent problems with commands that only make sense in pregame. */
1552 /* This value defines if the player data should be saved for a scenario. It
1553 * is only FALSE if the editor was used to set it to this value. For
1554 * such scenarios it has to be resetted at game start so that player data
1556 game
.scenario
.players
= TRUE
;
1558 force_end_of_sniff
= TRUE
;
1559 /* There's no stateful packet set to client until srv_ready(). */
1562 /**************************************************************************
1563 Quit the server and exit.
1564 **************************************************************************/
1565 void server_quit(void)
1567 if (server_state() == S_S_RUNNING
) {
1568 /* Quitting mid-game. */
1570 phase_players_iterate(pplayer
) {
1571 CALL_PLR_AI_FUNC(phase_finished
, pplayer
, pplayer
);
1572 /* This has to be after all access to advisor data. */
1573 /* We used to run this for ai players only, but data phase
1574 is initialized for human players also. */
1575 adv_data_phase_done(pplayer
);
1576 } phase_players_iterate_end
;
1579 if (game
.server
.save_timer
!= NULL
) {
1580 timer_destroy(game
.server
.save_timer
);
1581 game
.server
.save_timer
= NULL
;
1583 if (between_turns
!= NULL
) {
1584 timer_destroy(between_turns
);
1585 between_turns
= NULL
;
1587 if (eot_timer
!= NULL
) {
1588 timer_destroy(eot_timer
);
1590 set_server_state(S_S_OVER
);
1595 adv_settlers_free();
1597 if (game
.server
.phase_timer
!= NULL
) {
1598 timer_destroy(game
.server
.phase_timer
);
1599 game
.server
.phase_timer
= NULL
;
1601 if (game
.server
.save_timer
!= NULL
) {
1602 timer_destroy(game
.server
.save_timer
);
1603 game
.server
.save_timer
= NULL
;
1607 if (srvarg
.fcdb_enabled
) {
1608 /* If freeciv database has been initialized */
1611 #endif /* HAVE_FCDB */
1618 close_connections_and_socket();
1620 ruleset_choices_free();
1622 registry_module_close();
1623 fc_destroy_mutex(&game
.server
.mutexes
.city_list
);
1627 cmdline_option_values_free();
1631 /**************************************************************************
1632 Handle request asking report to be sent to client.
1633 **************************************************************************/
1634 void handle_report_req(struct connection
*pconn
, enum report_type type
)
1636 struct conn_list
*dest
= pconn
->self
;
1638 if (S_S_RUNNING
!= server_state() && S_S_OVER
!= server_state()) {
1639 log_error("Got a report request %d before game start", type
);
1643 if (NULL
== pconn
->playing
&& !pconn
->observer
) {
1644 log_error("Got a report request %d from detached connection", type
);
1649 case REPORT_WONDERS_OF_THE_WORLD
:
1650 report_wonders_of_the_world(dest
);
1652 case REPORT_TOP_5_CITIES
:
1653 report_top_five_cities(dest
);
1655 case REPORT_DEMOGRAPHIC
:
1656 report_demographics(pconn
);
1658 case REPORT_ACHIEVEMENTS
:
1659 report_achievements(pconn
);
1663 notify_conn(dest
, NULL
, E_BAD_COMMAND
, ftc_server
,
1664 _("request for unknown report (type %d)"), type
);
1667 /**************************************************************************
1668 Mark identity number free.
1669 **************************************************************************/
1670 void identity_number_release(int id
)
1672 BV_CLR(identity_numbers_used
, id
);
1675 /**************************************************************************
1676 Mark identity number allocated.
1677 **************************************************************************/
1678 void identity_number_reserve(int id
)
1680 BV_SET(identity_numbers_used
, id
);
1683 /**************************************************************************
1684 Check whether identity number is currently allocated.
1685 **************************************************************************/
1686 static bool identity_number_is_used(int id
)
1688 return BV_ISSET(identity_numbers_used
, id
);
1691 /**************************************************************************
1692 Increment identity_number and return result.
1693 **************************************************************************/
1694 static int increment_identity_number(void)
1696 server
.identity_number
= (server
.identity_number
+ 1) % IDENTITY_NUMBER_SIZE
;
1697 return server
.identity_number
;
1700 /**************************************************************************
1701 Identity ids wrap at IDENTITY_NUMBER_SIZE, skipping IDENTITY_NUMBER_ZERO
1702 Setup in server_game_init()
1703 **************************************************************************/
1704 int identity_number(void)
1708 while (identity_number_is_used(increment_identity_number())) {
1710 if (++retries
>= IDENTITY_NUMBER_SIZE
) {
1712 fc_assert_exit_msg(IDENTITY_NUMBER_SIZE
> retries
,
1713 "Exhausted city and unit numbers!");
1716 identity_number_reserve(server
.identity_number
);
1717 return server
.identity_number
;
1720 /**************************************************************************
1721 Returns TRUE if the packet type is an edit packet sent by the client.
1723 NB: The first and last client edit packets here must match those
1724 defined in common/packets.def.
1725 **************************************************************************/
1726 static bool is_client_edit_packet(int type
)
1728 return PACKET_EDIT_MODE
<= type
&& type
<= PACKET_EDIT_GAME
;
1731 /**************************************************************************
1732 Returns FALSE if connection should be closed (because the clients was
1733 rejected). Returns TRUE else.
1734 **************************************************************************/
1735 bool server_packet_input(struct connection
*pconn
, void *packet
, int type
)
1737 struct player
*pplayer
;
1739 /* a NULL packet can be returned from receive_packet_goto_route() */
1745 * Old pre-delta clients (before 2003-11-28) send a
1746 * PACKET_LOGIN_REQUEST (type 0) to the server. We catch this and
1747 * reply with an old reject packet. Since there is no struct for
1748 * this old packet anymore we build it by hand.
1751 unsigned char buffer
[4096];
1752 struct raw_data_out dout
;
1754 log_normal(_("Warning: rejecting old client %s"),
1755 conn_description(pconn
));
1757 dio_output_init(&dout
, buffer
, sizeof(buffer
));
1758 dio_put_uint16_raw(&dout
, 0);
1760 /* 1 == PACKET_LOGIN_REPLY in the old client */
1761 dio_put_uint8_raw(&dout
, 1);
1763 dio_put_bool32_raw(&dout
, FALSE
);
1764 dio_put_string_raw(&dout
,
1765 _("Your client is too old. To use this server, "
1766 "please upgrade your client to a "
1767 "Freeciv 2.2 or later."));
1768 dio_put_string_raw(&dout
, "");
1771 size_t size
= dio_output_used(&dout
);
1772 dio_output_rewind(&dout
);
1773 dio_put_uint16_raw(&dout
, size
);
1776 * Use send_connection_data instead of send_packet_data to avoid
1779 connection_send_data(pconn
, buffer
, size
);
1785 if (type
== PACKET_SERVER_JOIN_REQ
) {
1786 return handle_login_request(pconn
,
1787 (struct packet_server_join_req
*) packet
);
1790 /* May be received on a non-established connection. */
1791 if (type
== PACKET_AUTHENTICATION_REPLY
) {
1792 return auth_handle_reply(pconn
,
1793 ((struct packet_authentication_reply
*)
1797 if (type
== PACKET_CONN_PONG
) {
1798 handle_conn_pong(pconn
);
1802 if (!pconn
->established
) {
1803 log_error("Received game packet %s(%d) from unaccepted connection %s.",
1804 packet_name(type
), type
, conn_description(pconn
));
1808 /* valid packets from established connections but non-players */
1809 if (type
== PACKET_CHAT_MSG_REQ
1810 || type
== PACKET_SINGLE_WANT_HACK_REQ
1811 || type
== PACKET_NATION_SELECT_REQ
1812 || type
== PACKET_REPORT_REQ
1813 || type
== PACKET_CLIENT_INFO
1814 || type
== PACKET_CONN_PONG
1815 || type
== PACKET_CLIENT_HEARTBEAT
1816 || type
== PACKET_SAVE_SCENARIO
1817 || is_client_edit_packet(type
)) {
1819 /* Except for PACKET_EDIT_MODE (used to set edit mode), check
1820 * that the client is allowed to send the given edit packet. */
1821 if (is_client_edit_packet(type
) && type
!= PACKET_EDIT_MODE
1822 && !can_conn_edit(pconn
)) {
1823 notify_conn(pconn
->self
, NULL
, E_BAD_COMMAND
, ftc_editor
,
1824 _("You are not allowed to edit."));
1828 if (!server_handle_packet(type
, packet
, NULL
, pconn
)) {
1829 log_error("Received unknown packet %d from %s.",
1830 type
, conn_description(pconn
));
1835 pplayer
= pconn
->playing
;
1837 if (NULL
== pplayer
|| pconn
->observer
) {
1838 if (type
== PACKET_PLAYER_READY
&& pconn
->observer
) {
1839 handle_observer_ready(pconn
);
1842 /* don't support these yet */
1843 log_error("Received packet %s(%d) from non-player connection %s.",
1844 packet_name(type
), type
, conn_description(pconn
));
1848 if (S_S_RUNNING
!= server_state()
1849 && type
!= PACKET_NATION_SELECT_REQ
1850 && type
!= PACKET_PLAYER_READY
1851 && type
!= PACKET_VOTE_SUBMIT
) {
1852 if (S_S_OVER
== server_state()) {
1853 /* This can happen by accident, so we don't want to print
1854 * out lots of error messages. Ie, we use log_debug(). */
1855 log_debug("Got a packet of type %s(%d) in %s.",
1856 packet_name(type
), type
, server_states_name(S_S_OVER
));
1858 log_error("Got a packet of type %s(%d) outside %s.",
1859 packet_name(type
), type
, server_states_name(S_S_RUNNING
));
1864 pplayer
->nturns_idle
= 0;
1866 if (!pplayer
->is_alive
&& type
!= PACKET_REPORT_REQ
) {
1867 log_error("Got a packet of type %s(%d) from a dead player.",
1868 packet_name(type
), type
);
1872 /* Make sure to set this back to NULL before leaving this function: */
1873 pplayer
->current_conn
= pconn
;
1875 if (!server_handle_packet(type
, packet
, pplayer
, pconn
)) {
1876 log_error("Received unknown packet %d from %s.",
1877 type
, conn_description(pconn
));
1880 if (S_S_RUNNING
== server_state()
1881 && type
!= PACKET_PLAYER_READY
) {
1882 /* handle_player_ready() calls start_game(), but the game isn't started
1883 * until the main loop is re-entered, so kill_dying_players would think
1884 * all players are dead. This should be solved by adding a new
1885 * game state (now S_S_GENERATING_WAITING). */
1886 kill_dying_players();
1889 pplayer
->current_conn
= NULL
;
1893 /**************************************************************************
1894 Check if turn is really done. Returns nothing, but as a side effect sets
1895 force_end_of_sniff if no more input is expected this turn (i.e. turn done)
1896 **************************************************************************/
1897 void check_for_full_turn_done(void)
1899 bool connected
= FALSE
;
1901 if (S_S_RUNNING
!= server_state()) {
1902 /* Not in a running state, no turn done. */
1906 /* fixedlength is only applicable if we have a timeout set */
1907 if (game
.server
.fixedlength
&& current_turn_timeout() != 0) {
1911 /* If there are no connected players, don't automatically advance. This is
1912 * a hack to prevent all-AI games from running rampant. Note that if
1913 * timeout is set to -1 this function call is skipped entirely and the
1914 * server will run rampant. */
1915 players_iterate_alive(pplayer
) {
1916 if (pplayer
->is_connected
&& is_human(pplayer
)) {
1920 } players_iterate_alive_end
;
1926 phase_players_iterate(pplayer
) {
1927 if (!pplayer
->phase_done
&& pplayer
->is_alive
) {
1928 if (pplayer
->is_connected
) {
1929 /* In all cases, we wait for any connected players. */
1932 if (game
.server
.turnblock
&& is_human(pplayer
)) {
1933 /* If turnblock is enabled check for human players, connected
1937 if (is_ai(pplayer
) && !pplayer
->ai_phase_done
) {
1938 /* AI player has not finished */
1942 } phase_players_iterate_end
;
1944 force_end_of_sniff
= TRUE
;
1947 /****************************************************************************
1948 Update information about which nations have start positions on the map.
1950 Call this on server start, or when loading a scenario.
1951 ****************************************************************************/
1952 void update_nations_with_startpos(void)
1954 if (!game_was_started() && 0 < map_startpos_count()) {
1955 /* Restrict nations to those for which start positions are defined. */
1956 nations_iterate(pnation
) {
1957 fc_assert_action_msg(NULL
== pnation
->player
,
1958 if (pnation
->player
->nation
== pnation
) {
1959 /* At least assignment is consistent. Leave nation assigned,
1960 * and make sure that nation is also marked pickable. */
1961 pnation
->server
.no_startpos
= FALSE
;
1963 } else if (NULL
!= pnation
->player
->nation
) {
1964 /* Not consistent. Just initialize the pointer and hope for the
1966 pnation
->player
->nation
->player
= NULL
;
1967 pnation
->player
= NULL
;
1969 /* Not consistent. Just initialize the pointer and hope for the
1971 pnation
->player
= NULL
;
1972 }, "Player assigned to nation before %s()!", __FUNCTION__
);
1974 if (nation_barbarian_type(pnation
) != NOT_A_BARBARIAN
) {
1975 /* Always allow land and sea barbarians regardless of start
1977 pnation
->server
.no_startpos
= FALSE
;
1979 /* Restrict the set of nations offered to players, based on
1981 * If there are no start positions for a nation, remove it from the
1983 pnation
->server
.no_startpos
= TRUE
;
1984 map_startpos_iterate(psp
) {
1985 if (startpos_nation_allowed(psp
, pnation
)) {
1986 /* There is at least one start position that allows this nation,
1987 * so allow it to be picked.
1988 * (Depending on what nations players actually pick, it's not
1989 * guaranteed that the server can always find a match between
1990 * nations in this subset and start positions, in which case the
1991 * server may create mismatches.) */
1992 pnation
->server
.no_startpos
= FALSE
;
1995 } map_startpos_iterate_end
;
1997 } nations_iterate_end
;
1999 /* Not restricting nations by start positions. */
2000 nations_iterate(pnation
) {
2001 pnation
->server
.no_startpos
= FALSE
;
2002 } nations_iterate_end
;
2006 /**************************************************************************
2007 Handles a pick-nation packet from the client. These packets are
2008 handled by connection because ctrl users may edit anyone's nation in
2009 pregame, and editing is possible during a running game.
2010 **************************************************************************/
2011 void handle_nation_select_req(struct connection
*pc
, int player_no
,
2012 Nation_type_id nation_no
, bool is_male
,
2013 const char *name
, int style
)
2015 struct nation_type
*new_nation
;
2016 struct player
*pplayer
= player_by_number(player_no
);
2018 if (!pplayer
|| !can_conn_edit_players_nation(pc
, pplayer
)) {
2022 new_nation
= nation_by_number(nation_no
);
2024 if (new_nation
!= NO_NATION_SELECTED
) {
2027 /* check sanity of the packet sent by client */
2028 if (style
< 0 || style
>= game
.control
.num_styles
) {
2032 if (!client_can_pick_nation(new_nation
)) {
2033 notify_player(pplayer
, NULL
, E_NATION_SELECTED
, ftc_server
,
2034 _("%s nation is not available for user selection."),
2035 nation_adjective_translation(new_nation
));
2038 if (new_nation
->player
&& new_nation
->player
!= pplayer
) {
2039 notify_player(pplayer
, NULL
, E_NATION_SELECTED
, ftc_server
,
2040 _("%s nation is already in use."),
2041 nation_adjective_translation(new_nation
));
2045 if (!server_player_set_name_full(pc
, pplayer
, new_nation
, name
,
2046 message
, sizeof(message
))) {
2047 notify_player(pplayer
, NULL
, E_NATION_SELECTED
,
2048 ftc_server
, "%s", message
);
2052 /* Should be caught by is_nation_pickable() */
2053 fc_assert_ret(nation_is_in_current_set(new_nation
));
2055 notify_conn(NULL
, NULL
, E_NATION_SELECTED
, ftc_server
,
2056 _("%s is the %s ruler %s."),
2058 nation_adjective_translation(new_nation
),
2059 player_name(pplayer
));
2061 pplayer
->is_male
= is_male
;
2062 pplayer
->style
= style_by_number(style
);
2063 } else if (name
[0] == '\0') {
2066 server_player_set_name_full(pc
, pplayer
, NULL
, ANON_PLAYER_NAME
,
2067 message
, sizeof(message
));
2070 (void) player_set_nation(pplayer
, new_nation
);
2071 send_player_info_c(pplayer
, game
.est_connections
);
2074 /****************************************************************************
2075 Handle a player-ready packet from global observer.
2076 ****************************************************************************/
2077 static void handle_observer_ready(struct connection
*pconn
)
2079 if (pconn
->access_level
== ALLOW_HACK
) {
2080 players_iterate(plr
) {
2081 if (is_human(plr
)) {
2084 } players_iterate_end
;
2086 start_command(NULL
, FALSE
, TRUE
);
2090 /****************************************************************************
2091 Handle a player-ready packet.
2092 ****************************************************************************/
2093 void handle_player_ready(struct player
*requestor
,
2097 struct player
*pplayer
= player_by_number(player_no
);
2099 if (NULL
== pplayer
|| S_S_INITIAL
!= server_state()) {
2103 if (pplayer
!= requestor
) {
2104 /* Currently you can only change your own readiness. */
2108 pplayer
->is_ready
= is_ready
;
2109 send_player_info_c(pplayer
, NULL
);
2111 /* Note this is called even if the player has pressed /start once
2112 * before. For instance, when a player leaves everyone remaining
2113 * might have pressed /start already but the start won't happen
2114 * until someone presses it again. Also you can press start more
2115 * than once to remind other people to start (which is a good thing
2116 * until somebody does it too much and it gets labeled as spam). */
2118 int num_ready
= 0, num_unready
= 0;
2120 players_iterate(other_player
) {
2121 if (other_player
->is_connected
) {
2122 if (other_player
->is_ready
) {
2128 } players_iterate_end
;
2129 if (num_unready
> 0) {
2130 notify_conn(NULL
, NULL
, E_SETTING
, ftc_server
,
2131 _("Waiting to start game: %d out of %d players "
2132 "are ready to start."),
2133 num_ready
, num_ready
+ num_unready
);
2135 /* Check minplayers etc. and then start */
2136 start_command(NULL
, FALSE
, TRUE
);
2141 /****************************************************************************
2142 Fill or remove players to meet the given aifill.
2143 If return is non-NULL, points to a translated string explaining why
2144 the total number of players is less than 'amount'.
2145 ****************************************************************************/
2146 const char *aifill(int amount
)
2148 char *limitreason
= NULL
;
2151 if (game_was_started()) {
2155 limit
= MIN(amount
, game
.server
.max_players
);
2156 if (limit
< amount
) {
2157 limitreason
= _("requested more than 'maxplayers' setting");
2160 /* Limit to nations provided by ruleset */
2161 if (limit
> server
.playable_nations
) {
2162 limit
= server
.playable_nations
;
2163 if (nation_set_count() > 1) {
2164 limitreason
= _("not enough playable nations in this nation set "
2165 "(see 'nationset' setting)");
2167 limitreason
= _("not enough playable nations");
2171 if (limit
< player_count()) {
2172 int removal
= player_slot_count() - 1;
2174 while (limit
< player_count() && 0 <= removal
) {
2175 struct player
*pplayer
= player_by_number(removal
);
2182 if (!pplayer
->is_connected
&& !pplayer
->was_created
) {
2183 server_remove_player(pplayer
);
2187 /* 'limit' can be different from 'player_count()' at this point if
2188 * there are more human or created players than the 'limit'. */
2192 while (limit
> player_count()) {
2193 char leader_name
[MAX_LEN_NAME
];
2195 struct player
*pplayer
;
2197 pplayer
= server_create_player(-1, default_ai_type_name(),
2199 /* !game_was_started() so no need to assign_player_colors() */
2203 server_player_init(pplayer
, FALSE
, TRUE
);
2205 player_set_nation(pplayer
, NULL
);
2208 fc_snprintf(leader_name
, sizeof(leader_name
), "AI*%d", filled
++);
2209 } while (player_by_name(leader_name
));
2210 server_player_set_name(pplayer
, leader_name
);
2211 pplayer
->random_name
= TRUE
;
2212 sz_strlcpy(pplayer
->username
, _(ANON_USER_NAME
));
2213 pplayer
->unassigned_user
= TRUE
;
2215 pplayer
->ai_common
.skill_level
= game
.info
.skill_level
;
2217 set_ai_level_directer(pplayer
, game
.info
.skill_level
);
2219 CALL_PLR_AI_FUNC(gained_control
, pplayer
, pplayer
);
2221 log_normal(_("%s has been added as %s level AI-controlled player (%s)."),
2222 player_name(pplayer
),
2223 ai_level_translated_name(pplayer
->ai_common
.skill_level
),
2224 ai_name(pplayer
->ai
));
2225 notify_conn(NULL
, NULL
, E_SETTING
, ftc_server
,
2226 _("%s has been added as %s level AI-controlled player (%s)."),
2227 player_name(pplayer
),
2228 ai_level_translated_name(pplayer
->ai_common
.skill_level
),
2229 ai_name(pplayer
->ai
));
2231 send_player_info_c(pplayer
, NULL
);
2237 /****************************************************************************
2238 Tool for generate_players().
2239 ****************************************************************************/
2240 #define SPECHASH_TAG startpos
2241 #define SPECHASH_IKEY_TYPE struct startpos *
2242 #define SPECHASH_INT_DATA_TYPE
2243 #include "spechash.h"
2244 #define startpos_hash_iterate(hash, psp, c) \
2245 TYPED_HASH_ITERATE(struct startpos *, intptr_t, hash, psp, c)
2246 #define startpos_hash_iterate_end HASH_ITERATE_END
2248 /****************************************************************************
2249 Tool for generate_players().
2250 ****************************************************************************/
2251 static void player_set_nation_full(struct player
*pplayer
,
2252 struct nation_type
*pnation
)
2254 /* Don't change the name of a created player. */
2255 player_nation_defaults(pplayer
, pnation
, pplayer
->random_name
);
2258 /****************************************************************************
2259 Set nation for player with nation default values.
2260 ****************************************************************************/
2261 void player_nation_defaults(struct player
*pplayer
, struct nation_type
*pnation
,
2264 struct nation_leader
*pleader
;
2266 fc_assert(NO_NATION_SELECTED
!= pnation
);
2267 player_set_nation(pplayer
, pnation
);
2268 fc_assert(pnation
== pplayer
->nation
);
2270 pplayer
->style
= style_of_nation(pnation
);
2273 server_player_set_name(pplayer
, pick_random_player_name(pnation
));
2276 if ((pleader
= nation_leader_by_name(pnation
, player_name(pplayer
)))) {
2277 pplayer
->is_male
= nation_leader_is_male(pleader
);
2279 pplayer
->is_male
= (fc_rand(2) == 1);
2282 ai_traits_init(pplayer
);
2285 /****************************************************************************
2286 Assign random nations to players at game start. This includes human
2287 players, AI players created with "set aifill <X>", and players created
2288 with "create <PlayerName>".
2290 If a player's name matches one of the leader names for some nation, and
2291 that nation is available, choose that nation, and set the player sex
2292 appropriately. For example, when the Britons have not been chosen by
2293 anyone else, a player called Boudica whose nation has not been specified
2294 (for instance if they were created with "create Boudica") will become
2295 the Britons, and their sex will be female. Otherwise, the sex is chosen
2296 randomly, and the nation is chosen as below.
2298 If this is a scenario and the scenario has specific start positions for
2299 some nations, try to pick those nations, favouring those with start
2300 positions which already-assigned players can't use. (Note that it's
2301 possible that we can't find enough nations with available start positions,
2302 depending on what nations players have already picked; in this case,
2303 it's OK to pick nations without start positions, as init_new_game() will
2304 fall back to mismatched start positions.)
2306 Otherwise, pick available nations using pick_a_nation(), which tries to
2307 pick nations that look good with nations already in the game.
2309 For 'aifill' players, the player name/sex is then reset to that of a
2310 random leader for the chosen nation.
2311 ****************************************************************************/
2312 static void generate_players(void)
2314 int nations_to_assign
= 0;
2316 /* Announce players who already have nations, and select nations based
2317 * on player names. */
2318 players_iterate(pplayer
) {
2319 if (pplayer
->nation
!= NO_NATION_SELECTED
) {
2320 /* Traits are initialized here, and not already when nation gets picked,
2321 * as player may change his/her mind after picking one nation, and picks
2322 * another and we want to init traits only once, for the correct nation. */
2323 ai_traits_init(pplayer
);
2324 announce_player(pplayer
);
2328 /* See if the player name matches a known leader name.
2329 * If more than one nation has this leader name, pick one at random.
2330 * No attempt is made to avoid clashes to maximise the number of
2331 * nations that can be assigned in this way. */
2333 struct nation_list
*candidates
= nation_list_new();
2336 allowed_nations_iterate(pnation
) {
2337 if (is_nation_playable(pnation
)
2338 && client_can_pick_nation(pnation
)
2339 && NULL
== pnation
->player
2340 && (nation_leader_by_name(pnation
, player_name(pplayer
)))) {
2341 nation_list_append(candidates
, pnation
);
2344 } allowed_nations_iterate_end
;
2346 player_set_nation_full(pplayer
,
2347 nation_list_get(candidates
, fc_rand(n
)));
2349 nation_list_destroy(candidates
);
2351 if (pplayer
->nation
!= NO_NATION_SELECTED
) {
2352 announce_player(pplayer
);
2354 nations_to_assign
++;
2356 } players_iterate_end
;
2358 if (0 < nations_to_assign
&& 0 < map_startpos_count()) {
2359 /* We're running a scenario game with specified start positions.
2360 * Prefer nations assigned to those positions (but we can fall back
2361 * to others, even if game.scenario.startpos_nations is set). */
2362 struct startpos_hash
*hash
= startpos_hash_new();
2363 struct nation_type
*picked
;
2367 /* Initialization. */
2368 map_startpos_iterate(psp
) {
2369 if (startpos_allows_all(psp
)) {
2373 /* Count the already-assigned players whose nations can use this
2374 * start position. */
2376 players_iterate(pplayer
) {
2377 if (NO_NATION_SELECTED
!= pplayer
->nation
2378 && startpos_nation_allowed(psp
, pplayer
->nation
)) {
2381 } players_iterate_end
;
2383 startpos_hash_insert(hash
, psp
, c
);
2387 } map_startpos_iterate_end
;
2389 /* Try to assign nations with start positions to the unassigned
2390 * players, preferring nations whose start positions aren't usable
2391 * by already-assigned players. */
2392 players_iterate(pplayer
) {
2393 if (NO_NATION_SELECTED
!= pplayer
->nation
) {
2397 picked
= NO_NATION_SELECTED
;
2401 allowed_nations_iterate(pnation
) {
2402 if (!is_nation_playable(pnation
)
2403 || NULL
!= pnation
->player
) {
2404 /* Not available. */
2408 startpos_hash_iterate(hash
, psp
, val
) {
2409 if (!startpos_nation_allowed(psp
, pnation
)) {
2414 /* Pick this nation, as fewer nations already in the game
2415 * can use this start position. */
2419 } else if (val
== min
&& 0 == fc_rand(++i
)) {
2420 /* More than one nation is equally desirable. Pick one at
2424 } startpos_hash_iterate_end
;
2425 } allowed_nations_iterate_end
;
2427 if (NO_NATION_SELECTED
!= picked
) {
2428 player_set_nation_full(pplayer
, picked
);
2429 nations_to_assign
--;
2430 announce_player(pplayer
);
2431 /* Update the counts for the newly assigned nation. */
2432 startpos_hash_iterate(hash
, psp
, val
) {
2433 if (startpos_nation_allowed(psp
, picked
)) {
2434 startpos_hash_replace(hash
, psp
, val
+ 1);
2436 } startpos_hash_iterate_end
;
2438 /* No need to continue; we failed to pick a nation this time,
2439 * so we're not going to succeed next time. Fall back to
2440 * standard nation selection. */
2443 } players_iterate_end
;
2445 startpos_hash_destroy(hash
);
2448 if (0 < nations_to_assign
) {
2449 /* Pick random races. Try to select from the set permitted by
2450 * starting positions -- if we fell through here after failing to
2451 * match start positions, this will at least keep the picked
2452 * nations vaguely in keeping with the scenario.
2453 * However, even this may fail (if there are start positions that
2454 * can only be filled by nations outside the current nationset),
2455 * in which case we fall back to completely random nations. */
2456 bool needs_startpos
= TRUE
;
2457 players_iterate(pplayer
) {
2458 if (NO_NATION_SELECTED
== pplayer
->nation
) {
2459 struct nation_type
*pnation
= pick_a_nation(NULL
, FALSE
, needs_startpos
,
2461 if (pnation
== NO_NATION_SELECTED
&& needs_startpos
) {
2462 needs_startpos
= FALSE
;
2463 pnation
= pick_a_nation(NULL
, FALSE
, needs_startpos
, NOT_A_BARBARIAN
);
2465 fc_assert(pnation
!= NO_NATION_SELECTED
);
2466 player_set_nation_full(pplayer
, pnation
);
2467 nations_to_assign
--;
2468 announce_player(pplayer
);
2470 } players_iterate_end
;
2473 fc_assert(0 == nations_to_assign
);
2475 (void) send_server_info_to_metaserver(META_INFO
);
2478 /****************************************************************************
2479 Returns a random ruler name picked from given nation's ruler names
2480 that is not already in use.
2481 May return NULL if no unique name is available.
2482 ****************************************************************************/
2483 const char *pick_random_player_name(const struct nation_type
*pnation
)
2485 const char *choice
= NULL
;
2486 struct nation_leader_list
*candidates
= nation_leader_list_new();
2489 nation_leader_list_iterate(nation_leaders(pnation
), pleader
) {
2490 const char *name
= nation_leader_name(pleader
);
2492 if (NULL
== player_by_name(name
)
2493 && NULL
== player_by_user(name
)) {
2494 nation_leader_list_append(candidates
, pleader
);
2496 } nation_leader_list_iterate_end
;
2498 n
= nation_leader_list_size(candidates
);
2500 choice
= nation_leader_name(nation_leader_list_get(candidates
,
2503 nation_leader_list_destroy(candidates
);
2508 /*************************************************************************
2509 Announce what nation player rules to everyone.
2510 *************************************************************************/
2511 static void announce_player(struct player
*pplayer
)
2513 log_normal(_("%s rules the %s."),
2514 player_name(pplayer
), nation_plural_for_player(pplayer
));
2516 notify_conn(game
.est_connections
, NULL
, E_GAME_START
,
2517 ftc_server
, _("%s rules the %s."),
2518 player_name(pplayer
), nation_plural_for_player(pplayer
));
2520 /* Let the clients knows the nation of the players as soon as possible.
2521 * When a player's nation is server assigned its client will think of it
2522 * as NULL until informed about the assigned nation. */
2523 send_player_info_c(pplayer
, NULL
);
2526 /**************************************************************************
2527 Play the game! Returns when S_S_RUNNING != server_state().
2528 **************************************************************************/
2529 static void srv_running(void)
2532 bool is_new_turn
= game
.info
.is_new_game
;
2533 bool skip_mapimg
= !game
.info
.is_new_game
; /* Do not overwrite start-of-turn image */
2534 bool need_send_pending_events
= !game
.info
.is_new_game
;
2535 int save_counter
= game
.info
.is_new_game
? 1 : 0;
2537 /* We may as well reset is_new_game now. */
2538 game
.info
.is_new_game
= FALSE
;
2540 log_verbose("srv_running() mostly redundant send_server_settings()");
2541 send_server_settings(NULL
);
2543 timer_start(eot_timer
);
2545 if (game
.server
.autosaves
& (1 << AS_TIMER
)) {
2546 game
.server
.save_timer
= timer_renew(game
.server
.save_timer
,
2547 TIMER_USER
, TIMER_ACTIVE
);
2548 timer_start(game
.server
.save_timer
);
2552 * This will freeze the reports and agents at the client.
2554 * Do this before the body so that the PACKET_THAW_CLIENT packet is
2557 lsend_packet_freeze_client(game
.est_connections
);
2559 fc_assert(S_S_RUNNING
== server_state());
2560 while (S_S_RUNNING
== server_state()) {
2561 /* The beginning of a turn.
2563 * We have to initialize data as well as do some actions. However when
2564 * loading a game we don't want to do these actions (like AI unit
2565 * movement and AI diplomacy). */
2566 begin_turn(is_new_turn
);
2568 if (game
.server
.num_phases
!= 1) {
2569 /* We allow everyone to begin adjusting cities and such
2570 * from the beginning of the turn.
2571 * With simultaneous movement we send begin_turn packet in
2572 * begin_phase() only after AI players have finished their actions. */
2573 lsend_packet_begin_turn(game
.est_connections
);
2576 for (; game
.info
.phase
< game
.server
.num_phases
; game
.info
.phase
++) {
2577 log_debug("Starting phase %d/%d.", game
.info
.phase
,
2578 game
.server
.num_phases
);
2579 begin_phase(is_new_turn
);
2580 if (need_send_pending_events
) {
2581 /* When loading a savegame, we need to send loaded events, after
2582 * the clients switched to the game page (after the first
2583 * packet_start_phase is received). */
2584 conn_list_iterate(game
.est_connections
, pconn
) {
2585 send_pending_events(pconn
, TRUE
);
2586 } conn_list_iterate_end
;
2587 need_send_pending_events
= FALSE
;
2592 force_end_of_sniff
= FALSE
;
2595 * This will thaw the reports and agents at the client.
2597 lsend_packet_thaw_client(game
.est_connections
);
2600 /* Before sniff (human player activites), report time to now: */
2601 log_verbose("End/start-turn server/ai activities: %g seconds",
2602 timer_read_seconds(eot_timer
));
2605 /* Do auto-saves just before starting server_sniff_all_input(), so that
2606 * autosave happens effectively "at the same time" as manual
2607 * saves, from the point of view of restarting and AI players.
2608 * Post-increment so we don't count the first loop. */
2609 if (game
.info
.phase
== 0) {
2610 /* Create autosaves if requested. */
2611 if (save_counter
>= game
.server
.save_nturns
2612 && game
.server
.save_nturns
> 0) {
2614 save_game_auto("Autosave", AS_TURN
);
2619 /* Save map image(s). */
2620 for (i
= 0; i
< mapimg_count(); i
++) {
2621 struct mapdef
*pmapdef
= mapimg_isvalid(i
);
2622 if (pmapdef
!= NULL
) {
2623 mapimg_create(pmapdef
, FALSE
, game
.server
.save_name
,
2624 srvarg
.saves_pathname
);
2626 log_error("%s", mapimg_error());
2630 skip_mapimg
= FALSE
;
2634 log_debug("sniffingpackets");
2635 check_for_full_turn_done(); /* HACK: don't wait during AI phases */
2637 if (between_turns
!= NULL
) {
2638 game
.server
.turn_change_time
= timer_read_seconds(between_turns
);
2639 log_debug("Inresponsive between turns %g seconds", game
.server
.turn_change_time
);
2642 while (server_sniff_all_input() == S_E_OTHERWISE
) {
2646 between_turns
= timer_renew(between_turns
, TIMER_USER
, TIMER_ACTIVE
);
2647 timer_start(between_turns
);
2649 /* After sniff, re-zero the timer: (read-out above on next loop) */
2650 timer_clear(eot_timer
);
2651 timer_start(eot_timer
);
2653 conn_list_do_buffer(game
.est_connections
);
2658 * This will freeze the reports and agents at the client.
2660 lsend_packet_freeze_client(game
.est_connections
);
2664 conn_list_do_unbuffer(game
.est_connections
);
2666 if (S_S_OVER
== server_state()) {
2671 log_debug("Sendinfotometaserver");
2672 (void) send_server_info_to_metaserver(META_REFRESH
);
2674 if (S_S_OVER
!= server_state() && check_for_game_over()) {
2675 set_server_state(S_S_OVER
);
2676 if (game
.info
.turn
> game
.server
.end_turn
) {
2677 /* endturn was reached - rank users based on team scores */
2680 /* game ended for victory conditions - rank users based on survival */
2683 } else if ((check_for_game_over() && game
.info
.turn
> game
.server
.end_turn
)
2684 || S_S_OVER
== server_state()) {
2685 /* game terminated by /endgame command - calculate team scores */
2690 /* This will thaw the reports and agents at the client. */
2691 lsend_packet_thaw_client(game
.est_connections
);
2693 if (game
.server
.save_timer
!= NULL
) {
2694 timer_destroy(game
.server
.save_timer
);
2695 game
.server
.save_timer
= NULL
;
2697 if (between_turns
!= NULL
) {
2698 timer_destroy(between_turns
);
2699 between_turns
= NULL
;
2701 timer_clear(eot_timer
);
2704 /**************************************************************************
2705 Server initialization.
2706 **************************************************************************/
2707 static void srv_prepare(void)
2710 if (!srvarg
.auth_enabled
) {
2711 con_write(C_COMMENT
, _("This freeciv-server program has player "
2712 "authentication support, but it's currently not "
2715 #endif /* HAVE_FCDB */
2717 /* make sure it's initialized */
2718 if (!has_been_srv_init
) {
2724 /* must be before con_log_init() */
2726 con_log_init(srvarg
.log_filename
, srvarg
.loglevel
,
2727 srvarg
.fatal_assertions
);
2728 /* logging available after this point */
2730 server_open_socket();
2733 con_puts(C_COMMENT
, "");
2734 con_puts(C_COMMENT
, beta_message());
2735 con_puts(C_COMMENT
, "");
2740 settings_init(TRUE
);
2749 mapimg_init(mapimg_server_tile_known
, mapimg_server_tile_terrain
,
2750 mapimg_server_tile_owner
, mapimg_server_tile_city
,
2751 mapimg_server_tile_unit
, mapimg_server_plrcolor_count
,
2752 mapimg_server_plrcolor_get
);
2755 if (srvarg
.fcdb_enabled
) {
2758 success
= fcdb_init(srvarg
.fcdb_conf
);
2759 free(srvarg
.fcdb_conf
); /* Never needed again */
2760 srvarg
.fcdb_conf
= NULL
;
2765 #endif /* HAVE_FCDB */
2767 if (srvarg
.ruleset
!= NULL
) {
2768 const char *testfilename
;
2770 testfilename
= fileinfoname(get_data_dirs(), srvarg
.ruleset
);
2771 if (testfilename
== NULL
) {
2772 log_fatal(_("Ruleset directory \"%s\" not found"), srvarg
.ruleset
);
2775 sz_strlcpy(game
.server
.rulesetdir
, srvarg
.ruleset
);
2778 /* load a saved game */
2779 if ('\0' == srvarg
.load_filename
[0]
2780 || !load_command(NULL
, srvarg
.load_filename
, FALSE
, TRUE
)) {
2781 /* Rulesets are loaded on game initialization, but may be changed later
2782 * if /load or /rulesetdir is done. */
2783 load_rulesets(NULL
, FALSE
, TRUE
, FALSE
);
2786 maybe_automatic_meta_message(default_meta_message_string());
2788 if (!(srvarg
.metaserver_no_send
)) {
2789 log_normal(_("Sending info to metaserver <%s>."), meta_addr_port());
2790 /* Open socket for meta server */
2791 if (!server_open_meta(srvarg
.metaconnection_persistent
)
2792 || !send_server_info_to_metaserver(META_INFO
)) {
2793 con_write(C_FAIL
, _("Not starting without explicitly requested metaserver connection."));
2798 eot_timer
= timer_new(TIMER_CPU
, TIMER_ACTIVE
);
2801 /**************************************************************************
2803 **************************************************************************/
2804 static void srv_scores(void)
2806 /* Recalculate the scores in case of a spaceship victory */
2807 players_iterate(pplayer
) {
2808 calc_civ_score(pplayer
);
2809 } players_iterate_end
;
2811 log_civ_score_now();
2813 report_final_scores(NULL
);
2815 notify_player(NULL
, NULL
, E_GAME_END
, ftc_server
,
2816 _("The game is over..."));
2817 send_server_info_to_metaserver(META_INFO
);
2819 if (game
.server
.save_nturns
> 0
2820 && conn_list_size(game
.est_connections
) > 0) {
2821 /* Save game on game_over, but not when the gameover was caused by
2822 * the -q parameter. */
2823 save_game_auto("Game over", AS_GAME_OVER
);
2827 /**************************************************************************
2828 Apply some final adjustments from the ruleset on to the game state.
2829 We cannot do this during ruleset loading, since some players may be
2830 added later than that.
2831 **************************************************************************/
2832 static void final_ruleset_adjustments(void)
2834 players_iterate(pplayer
) {
2835 struct nation_type
*pnation
= nation_of_player(pplayer
);
2837 pplayer
->government
= init_government_of_nation(pnation
);
2839 if (pnation
->init_government
== game
.government_during_revolution
) {
2840 /* If we do not do this, an assertion will trigger. This enables us to
2841 * select a valid government on game start. */
2842 pplayer
->revolution_finishes
= 0;
2845 multipliers_iterate(pmul
) {
2846 pplayer
->multipliers
[multiplier_index(pmul
)]
2847 = pplayer
->multipliers_target
[multiplier_index(pmul
)]
2849 } multipliers_iterate_end
;
2850 } players_iterate_end
;
2853 /**************************************************************************
2855 **************************************************************************/
2856 static void srv_ready(void)
2858 (void) send_server_info_to_metaserver(META_INFO
);
2860 if (game
.server
.auto_ai_toggle
) {
2861 players_iterate(pplayer
) {
2862 if (!pplayer
->is_connected
&& is_human(pplayer
)) {
2863 toggle_ai_player_direct(NULL
, pplayer
);
2865 } players_iterate_end
;
2870 #ifdef TEST_RANDOM /* not defined anywhere, set it if you want it */
2873 test_random1(20000);
2874 test_random1(200000);
2877 if (game
.info
.is_new_game
) {
2878 game
.info
.turn
++; /* pregame T0 -> game T1 */
2879 fc_assert(game
.info
.turn
== 1);
2880 game
.info
.year
= game
.server
.start_year
;
2881 /* Must come before assign_player_colors() */
2883 final_ruleset_adjustments();
2886 /* If we have a tile map, and MAPGEN_SCENARIO == map.server.generator,
2887 * call map_fractal_generate anyway to make the specials, huts and
2888 * continent numbers. */
2890 || (MAPGEN_SCENARIO
== wld
.map
.server
.generator
2891 && game
.info
.is_new_game
)) {
2894 char value
[MAX_LEN_NAME
* 2];
2895 char pretty
[MAX_LEN_NAME
* 2];
2896 } mapgen_settings
[] = {
2899 { "teamplacement", }
2902 /* If a specific seed has been requested, there's no point retrying,
2903 * as the map will be the same every time. */
2904 bool retry_ok
= (wld
.map
.server
.seed_setting
== 0
2905 && wld
.map
.server
.generator
!= MAPGEN_SCENARIO
);
2906 int max
= retry_ok
? 3 : 1;
2907 bool created
= FALSE
;
2908 struct unit_type
*utype
= NULL
;
2909 int sucount
= strlen(game
.server
.start_units
);
2912 for (i
= 0; utype
== NULL
&& i
< sucount
; i
++) {
2913 utype
= crole_to_unit_type(game
.server
.start_units
[i
], NULL
);
2916 /* First unit the initial city might build. */
2917 utype
= get_role_unit(L_FIRSTBUILD
, 0);
2919 fc_assert(utype
!= NULL
);
2921 /* Register map generator setting main values. */
2922 for (i
= 0; i
< ARRAY_SIZE(mapgen_settings
); i
++) {
2923 const struct setting
*pset
= setting_by_name(mapgen_settings
[i
].name
);
2925 fc_assert_action(pset
!= NULL
, continue);
2926 (void) setting_value_name(pset
, FALSE
,
2927 mapgen_settings
[i
].value
,
2928 sizeof(mapgen_settings
[i
].value
));
2929 (void) setting_value_name(pset
, TRUE
,
2930 mapgen_settings
[i
].pretty
,
2931 sizeof(mapgen_settings
[i
].pretty
));
2934 for (i
= 0; !created
&& i
< max
; i
++) {
2935 created
= map_fractal_generate(TRUE
, utype
);
2936 if (!created
&& max
> 1) {
2939 /* If we're retrying, seed_setting == 0, which will yield a new map
2941 fc_assert(wld
.map
.server
.seed_setting
== 0);
2943 /* We will retry only if max attempts allow it */
2944 log_normal(_("Failed to create suitable map, retrying with another mapseed."));
2946 /* +1 - start human readable count from 1 and not from 0
2947 * +1 - refers to next round, not to one we just did
2950 log_normal(_("Attempt %d/%d"), i
+ 2, max
);
2952 wld
.map
.server
.have_resources
= FALSE
;
2954 /* Remove old information already present in tiles */
2955 map_free(&(wld
.map
));
2956 free_city_map_index();
2957 /* Restore the settings. */
2958 for (set
= 0; set
< ARRAY_SIZE(mapgen_settings
); set
++) {
2959 struct setting
*pset
= setting_by_name(mapgen_settings
[set
].name
);
2960 #ifdef FREECIV_NDEBUG
2961 setting_enum_set(pset
, mapgen_settings
[set
].value
, NULL
, NULL
, 0);
2962 #else /* FREECIV_NDEBUG */
2966 fc_assert_action(pset
!= NULL
, continue);
2967 success
= setting_enum_set(pset
, mapgen_settings
[set
].value
,
2968 NULL
, error
, sizeof(error
));
2969 fc_assert_msg(success
== TRUE
,
2970 "Failed to restore '%s': %s",
2971 mapgen_settings
[set
].name
,
2973 #endif /* FREECIV_NDEBUG */
2975 main_map_allocate(); /* NOT map_init() as that would overwrite settings */
2979 log_error(_("Cannot create suitable map with given settings."));
2980 /* TRANS: No full stop after the URL, could cause confusion. */
2981 log_error(_("Please report this message at %s"), BUG_URL
);
2985 if (wld
.map
.server
.generator
!= MAPGEN_SCENARIO
) {
2986 script_server_signal_emit("map_generated", 0);
2991 /* Test if main map generator settings have changed. */
2992 for (i
= 0; i
< ARRAY_SIZE(mapgen_settings
); i
++) {
2993 const struct setting
*pset
= setting_by_name(mapgen_settings
[i
].name
);
2994 char pretty
[sizeof(mapgen_settings
[i
].pretty
)];
2996 fc_assert_action(pset
!= NULL
, continue);
2997 if (0 == strcmp(setting_value_name(pset
, TRUE
, pretty
,
2999 mapgen_settings
[i
].pretty
)) {
3000 continue; /* Setting didn't change. */
3002 notify_conn(NULL
, NULL
, E_SETTING
, ftc_server
,
3003 _("Setting '%s' has been adjusted from %s to %s."),
3005 mapgen_settings
[i
].pretty
,
3007 log_normal(_("Setting '%s' has been adjusted from %s to %s."),
3009 mapgen_settings
[i
].pretty
,
3014 /* start the game */
3015 set_server_state(S_S_RUNNING
);
3016 (void) send_server_info_to_metaserver(META_INFO
);
3018 if (game
.info
.is_new_game
) {
3019 /* If we're starting a new game, reset the max_players to be at
3020 * least the number of players currently in the game. */
3021 game
.server
.max_players
= MAX(normal_player_count(), game
.server
.max_players
);
3023 /* Before the player map is allocated (and initialized)! */
3024 game
.server
.fogofwar_old
= game
.info
.fogofwar
;
3026 players_iterate(pplayer
) {
3027 player_map_init(pplayer
);
3028 pplayer
->economic
= player_limit_to_max_rates(pplayer
);
3029 pplayer
->economic
.gold
= game
.info
.gold
;
3030 } players_iterate_end
;
3032 /* Give initial technologies, as specified in the ruleset and the
3034 researches_iterate(presearch
) {
3035 init_tech(presearch
, TRUE
);
3036 give_initial_techs(presearch
, game
.info
.tech
);
3037 } researches_iterate_end
;
3039 /* Set up alliances based on team selections */
3040 players_iterate(pplayer
) {
3041 players_iterate(pdest
) {
3042 if (players_on_same_team(pplayer
, pdest
)
3043 && player_number(pplayer
) != player_number(pdest
)) {
3044 player_diplstate_get(pplayer
, pdest
)->type
= DS_TEAM
;
3045 give_shared_vision(pplayer
, pdest
);
3046 BV_SET(pplayer
->real_embassy
, player_index(pdest
));
3048 } players_iterate_end
;
3049 } players_iterate_end
;
3051 /* Assign colors from the ruleset for any players who weren't
3052 * explicitly assigned colors during the pregame.
3053 * This must come after generate_players() since it can depend on
3054 * assigned nations. */
3055 assign_player_colors();
3057 /* Save all settings for the 'reset game' command. */
3058 settings_game_start();
3061 /* FIXME: can this be moved? */
3062 players_iterate(pplayer
) {
3063 adv_data_analyze_rulesets(pplayer
);
3064 } players_iterate_end
;
3066 if (!game
.info
.is_new_game
) {
3067 players_iterate(pplayer
) {
3068 if (is_ai(pplayer
)) {
3069 set_ai_level_direct(pplayer
, pplayer
->ai_common
.skill_level
);
3071 } players_iterate_end
;
3073 players_iterate(pplayer
) {
3074 /* Initialize this again to be sure */
3075 adv_data_default(pplayer
);
3076 } players_iterate_end
;
3079 conn_list_compression_freeze(game
.est_connections
);
3080 send_all_info(game
.est_connections
);
3081 conn_list_compression_thaw(game
.est_connections
);
3083 if (game
.info
.is_new_game
) {
3084 /* Place players' initial units, etc */
3088 if (game
.server
.revealmap
& REVEAL_MAP_START
) {
3089 players_iterate(pplayer
) {
3090 map_show_all(pplayer
);
3091 } players_iterate_end
;
3095 if (game
.scenario
.is_scenario
&& game
.scenario
.players
) {
3096 /* This is a heavy scenario. It may include research. The sciencebox
3097 * setting may have been changed. A change to the sciencebox setting
3098 * may have caused the stored amount of bulbs to be enough to finish
3099 * the current research. */
3101 players_iterate(pplayer
) {
3102 /* Check for finished research. */
3103 update_bulbs(pplayer
, 0, TRUE
);
3104 } players_iterate_end
;
3107 CALL_FUNC_EACH_AI(game_start
);
3110 /**************************************************************************
3111 Initialize game data for the server (corresponds to server_game_free).
3112 **************************************************************************/
3113 void server_game_init(void)
3115 /* was redundantly in game_load() */
3116 server
.playable_nations
= 0;
3117 server
.nbarbarians
= 0;
3118 server
.identity_number
= IDENTITY_NUMBER_SKIP
;
3120 BV_CLR_ALL(identity_numbers_used
);
3121 identity_number_reserve(IDENTITY_NUMBER_ZERO
);
3125 /* game_init() set game.server.plr_colors to NULL. So we need to
3126 * initialize the colors after. */
3129 game
.server
.turn_change_time
= 0;
3132 /**************************************************************************
3133 Free game data that we reinitialize as part of a server soft restart.
3134 Bear in mind that this function is called when the 'load' command is
3136 **************************************************************************/
3137 void server_game_free(void)
3139 CALL_FUNC_EACH_AI(game_free
);
3141 /* Free all the treaties that were left open when game finished. */
3144 /* Free the vision data, without sending updates. */
3145 players_iterate(pplayer
) {
3146 unit_list_iterate(pplayer
->units
, punit
) {
3147 /* don't bother using vision_clear_sight() */
3148 vision_layer_iterate(v
) {
3149 punit
->server
.vision
->radius_sq
[v
] = -1;
3150 } vision_layer_iterate_end
;
3151 vision_free(punit
->server
.vision
);
3152 punit
->server
.vision
= NULL
;
3153 } unit_list_iterate_end
;
3155 city_list_iterate(pplayer
->cities
, pcity
) {
3156 /* don't bother using vision_clear_sight() */
3157 vision_layer_iterate(v
) {
3158 pcity
->server
.vision
->radius_sq
[v
] = -1;
3159 } vision_layer_iterate_end
;
3160 vision_free(pcity
->server
.vision
);
3161 pcity
->server
.vision
= NULL
;
3162 adv_city_free(pcity
);
3163 } city_list_iterate_end
;
3164 } players_iterate_end
;
3166 /* Destroy all players; with must be separate as the player information is
3167 * needed above. This also sends the information to the clients. */
3168 players_iterate(pplayer
) {
3169 server_remove_player(pplayer
);
3170 } players_iterate_end
;
3173 log_civ_score_free();
3179 /**************************************************************************
3181 **************************************************************************/
3184 fc_interface_init_server();
3189 /* Run server loop */
3191 set_server_state(S_S_INITIAL
);
3193 /* Load a script file. */
3194 if (NULL
!= srvarg
.script_filename
) {
3195 /* Adding an error message more here will duplicate them. */
3196 (void) read_init_script(NULL
, srvarg
.script_filename
, TRUE
, FALSE
);
3199 (void) aifill(game
.info
.aifill
);
3200 if (!game_was_started()) {
3201 event_cache_clear();
3204 log_normal(_("Now accepting new client connections on port %d."),
3206 /* Remain in S_S_INITIAL until all players are ready. */
3207 while (S_E_FORCE_END_OF_SNIFF
!= server_sniff_all_input()) {
3208 /* When force_end_of_sniff is used in pregame, it means that the server
3209 * is ready to start (usually set within start_game()). */
3212 if (S_S_RUNNING
> server_state()) {
3213 /* If restarting for lack of players, the state is S_S_OVER,
3214 * so don't try to start the game. */
3215 srv_ready(); /* srv_ready() sets server state to S_S_RUNNING. */
3220 /* Remain in S_S_OVER until players log out */
3221 while (conn_list_size(game
.est_connections
) > 0) {
3222 server_sniff_all_input();
3225 /* Close it even between games. */
3226 save_system_close();
3228 if (game
.info
.timeout
== -1 || srvarg
.exit_on_end
) {
3229 /* For autogames or if the -e option is specified, exit the server. */
3237 load_rulesets(NULL
, FALSE
, TRUE
, FALSE
);
3238 game
.info
.is_new_game
= TRUE
;
3241 /* Technically, we won't ever get here. We exit via server_quit. */
3244 /***************************************************************
3245 Initialize client specific functions.
3246 ***************************************************************/
3248 static inline void server_gui_color_free(struct color
*pcolor
)
3250 fc_assert_ret(pcolor
== NULL
);
3255 /***************************************************************************
3256 Returns the id of the city the player map of 'pplayer' has at 'ptile' or
3257 IDENTITY_NUMBER_ZERO if the player map don't have a city there.
3258 ***************************************************************************/
3259 static int server_plr_tile_city_id_get(const struct tile
*ptile
,
3260 const struct player
*pplayer
)
3262 const struct player_tile
*plrtile
= map_get_player_tile(ptile
, pplayer
);
3264 return plrtile
&& plrtile
->site
? plrtile
->site
->identity
3265 : IDENTITY_NUMBER_ZERO
;
3268 /***************************************************************************
3269 Returns the id of the server setting with the specified name.
3270 ***************************************************************************/
3271 server_setting_id
server_ss_by_name(const char *name
)
3273 struct setting
*pset
= setting_by_name(name
);
3276 return setting_number(pset
);
3278 log_error("No server setting named %s exists.", name
);
3279 return SERVER_SETTING_NONE
;
3283 /***************************************************************************
3284 Returns the name of the server setting with the specified id.
3285 ***************************************************************************/
3286 const char *server_ss_name_get(server_setting_id id
)
3288 struct setting
*pset
= setting_by_number(id
);
3291 return setting_name(pset
);
3293 log_error("No server setting with the id %d exists.", id
);
3298 /***************************************************************************
3299 Returns the type of the server setting with the specified id.
3300 ***************************************************************************/
3301 enum sset_type
server_ss_type_get(server_setting_id id
)
3303 struct setting
*pset
= setting_by_number(id
);
3306 return setting_type(pset
);
3308 log_error("No server setting with the id %d exists.", id
);
3309 return sset_type_invalid();
3313 /***************************************************************************
3314 Returns the value of the boolean server setting with the specified id.
3315 ***************************************************************************/
3316 bool server_ss_val_bool_get(server_setting_id id
)
3318 struct setting
*pset
= setting_by_number(id
);
3321 return setting_bool_get(pset
);
3323 log_error("No server setting with the id %d exists.", id
);
3328 /***************************************************************
3329 Initialize server specific functions.
3330 ***************************************************************/
3331 static void fc_interface_init_server(void)
3333 struct functions
*funcs
= fc_interface_funcs();
3335 funcs
->server_setting_by_name
= server_ss_by_name
;
3336 funcs
->server_setting_name_get
= server_ss_name_get
;
3337 funcs
->server_setting_type_get
= server_ss_type_get
;
3338 funcs
->server_setting_val_bool_get
= server_ss_val_bool_get
;
3339 funcs
->create_extra
= create_extra
;
3340 funcs
->destroy_extra
= destroy_extra
;
3341 funcs
->player_tile_vision_get
= map_is_known_and_seen
;
3342 funcs
->player_tile_city_id_get
= server_plr_tile_city_id_get
;
3343 funcs
->gui_color_free
= server_gui_color_free
;
3345 /* Keep this function call at the end. It checks if all required functions
3347 fc_interface_init();
3350 /***************************************************************************
3351 Helper function for the mapimg module - tile knowledge.
3352 ****************************************************************************/
3353 static enum known_type
mapimg_server_tile_known(const struct tile
*ptile
,
3354 const struct player
*pplayer
,
3357 if (knowledge
&& pplayer
) {
3358 return tile_get_known(ptile
, pplayer
);
3361 return TILE_KNOWN_SEEN
;
3364 /****************************************************************************
3365 Helper function for the mapimg module - tile terrain.
3366 ****************************************************************************/
3367 static struct terrain
3368 *mapimg_server_tile_terrain(const struct tile
*ptile
,
3369 const struct player
*pplayer
, bool knowledge
)
3371 if (knowledge
&& pplayer
) {
3372 struct player_tile
*plrtile
= map_get_player_tile(ptile
, pplayer
);
3373 return plrtile
->terrain
;
3376 return tile_terrain(ptile
);
3379 /****************************************************************************
3380 Helper function for the mapimg module - tile owner.
3381 ****************************************************************************/
3382 static struct player
*mapimg_server_tile_owner(const struct tile
*ptile
,
3383 const struct player
*pplayer
,
3386 if (knowledge
&& pplayer
3387 && tile_get_known(ptile
, pplayer
) != TILE_KNOWN_SEEN
) {
3388 struct player_tile
*plrtile
= map_get_player_tile(ptile
, pplayer
);
3389 return plrtile
->owner
;
3392 return tile_owner(ptile
);
3395 /****************************************************************************
3396 Helper function for the mapimg module - city owner.
3397 ****************************************************************************/
3398 static struct player
*mapimg_server_tile_city(const struct tile
*ptile
,
3399 const struct player
*pplayer
,
3402 struct city
*pcity
= tile_city(ptile
);
3408 if (knowledge
&& pplayer
) {
3409 struct vision_site
*pdcity
= map_get_player_city(ptile
, pplayer
);
3412 return pdcity
->owner
;
3418 return city_owner(tile_city(ptile
));
3421 /****************************************************************************
3422 Helper function for the mapimg module - unit owner.
3423 ****************************************************************************/
3424 static struct player
*mapimg_server_tile_unit(const struct tile
*ptile
,
3425 const struct player
*pplayer
,
3428 int unit_count
= unit_list_size(ptile
->units
);
3430 if (unit_count
== 0) {
3434 if (knowledge
&& pplayer
3435 && tile_get_known(ptile
, pplayer
) != TILE_KNOWN_SEEN
) {
3439 return unit_owner(unit_list_get(ptile
->units
, 0));
3442 /****************************************************************************
3443 Helper function for the mapimg module - number of player colors.
3444 ****************************************************************************/
3445 static int mapimg_server_plrcolor_count(void)
3447 return playercolor_count();
3450 /****************************************************************************
3451 Helper function for the mapimg module - one player color.
3452 ****************************************************************************/
3453 static struct rgbcolor
*mapimg_server_plrcolor_get(int i
)
3455 return playercolor_get(i
);