3 This guide is intended to be a help for developers, wanting to mess with
6 Here and there, you'll see some comments marked as [...], containing more
7 personal thoughts on the design, why it looks like it does, and sometimes what
8 went wrong. I hope developers will find that interesting too.
10 To read about the AI, see README.AI
12 ===========================================================================
14 ===========================================================================
15 Freeciv is a client/server civilization style of game.
16 The client is pretty dumb. Almost all calculations are performed on the
19 [It wasn't like this always. Originally more code was placed in the
20 common/ dir, allowing the client to do some of the world updates itself.
21 The end_of_turn city-refresh was for example performed both on the server
22 and on the client. However things got quite complex, more and more info
23 was needed on the client-side(security problem). Little by little we moved
24 more code to the server, and as of 1.5 the client is quite dumb -PU]
26 The source code has the following important directories:
27 dependencies: code from upstream projects
28 utility: utility functionality that is not freeciv-specific
29 common: data structures and code used by both the client and server.
31 client: common client code
32 client/* (fx gui-gtk-3.0): a specific gui implementation of the client.
33 data: graphics, rulesets and stuff
34 translations: localization files
35 ai: the ai, later linked into the server
36 tools: freeciv support executables
38 Freeciv is written in C. Header files should be compatible with C++ so
39 that C++ add-ons (particularly new clients) are possible. See the
40 CodingStyle file for more.
42 ===========================================================================
44 ===========================================================================
47 The server main loop basically looks like:
49 while (server_state == RUN_GAME_STATE) { /* looped once per turn */
50 do_ai_stuff(); /* do the ai controlled players */
51 sniff_packets(); /* get player requests and handle them */
52 end_turn(); /* main turn update */
57 Most time is spend in the sniff_packets() function, where a select()
58 call waits for packets or input on stdin(server-op commands).
60 ===========================================================================
61 Server Autogame Testing
62 ===========================================================================
63 Code changes should always be tested before submission for inclusion
64 into the svn source tree. It is useful to run the client and server as
65 autogames to verify either a particular savegame no longer shows a
66 fixed bug, or as a random sequence of games in a while loop overnight.
68 To start a server game with all AI players, create a file (below named
69 civ.serv) with lines such as the following:
71 # set gameseed 42 # repeat a particular game (random) sequence
72 # set mapseed 42 # repeat a particular map generation sequence
73 # set timeout 3 # run a client/server autogame
74 set timeout -1 # run a server only autogame
75 set minplayers 0 # no human player needed
76 set ec_turns 0 # avoid timestamps in savegames
77 set aifill 7 # fill to 7 players
78 hard # make the AI do complex things
79 create Caesar # first player (with known name) created and
83 Note: The server prompt is unusable when game with timeout set to -1
84 is running. You can stop such game with single ctrl+c, and continue by
85 setting timeout to -1 again.
87 The commandline to run server-only games can be typed as variations
89 $ while( time server/freeciv-server -r civ.serv ); do date; done
91 $ server/freeciv-server -r civ.serv -f buggy1534.sav.gz
93 To attach one or more clients to an autogame, remove the "start"
94 command, start the server program and attach clients to created AI
95 players. Or type "aitoggle <player>" at the server command prompt for
96 each player that connects. Finally, type "start" when you are ready to
99 Note, that the server will eventually flood a client with updates
100 faster than they can be drawn to the screen, thus it should always be
101 throttled by setting a timeout value high enough to allow processing
102 of the large update loads near the end of the game.
104 The autogame mode with timeout -1 is only available in DEBUG versions
105 and should not be used with clients as it removes virtually all the
106 server gating controls.
108 If you plan to compare results of autogames the following changes can be
111 - define __FC_LINE__ to a constant value in ./utility/log.h
112 - undef LOG_TIMERS in ./utility/timing.h
113 - deactivation of the event cache (set ec_turns 0)
115 ===========================================================================
117 ===========================================================================
118 For variable length list of fx units and cities freeciv uses a genlist,
119 which is implemented in utility/genlist.c. By some macro magic type specific
120 macros have been defined, avoiding much trouble.
121 For example a tile struct (the pointer to it we call ptile) has a unit
122 list, ptile->units; to iterate though all the units on the tile you would
125 unit_list_iterate(ptile->units, punit) {
126 /* In here we could do something with punit, which is a pointer to a
128 } unit_list_iterate_end;
130 Note that the macro itself declares the variable punit.
133 city_list_iterate(pplayer->cities, pcity) {
134 /* Do something with pcity, the pointer to a city struct */
135 } city_list_iterate_end;
137 There are other operations than iterating that can be performed on a list;
138 inserting, deleting, sorting etc. See utility/speclist.h
139 Note that the way the *_list_iterate macro is implemented means you can use
140 "continue" and "break" in the usual manner.
142 One thing you should keep in the back of your mind: Say you are iterating
143 through a unit list, and then somewhere inside the iteration decide to
144 disband a unit. In the server you would do this by calling
145 wipe_unit(punit), which would then remove the unit node from all the
146 relevant unit lists. But by the way unit_list_iterate works, if the removed
147 unit was the following node unit_list_iterate will already have saved the
148 pointer, and use it in a moment, with a segfault as the result. To avoid
149 this, use unit_list_iterate_safe instead.
151 You can also define your own lists with operations like iterating; read how
152 in utility/speclist.h.
154 =========================================================================
156 =========================================================================
157 The basic netcode is located in server/sernet.c and client/clinet.c.
159 (FIXME: this section is a bit out of date. See also doc/README.delta.)
161 All information passed between the server and clients, must be sent
162 through the network as serialized packet structures.
163 These are defined in common/packets.h.
165 For each 'foo' packet structure, there is one send and one receive function:
167 int send_packet_foo (struct connection *pc,
168 struct packet_foo *packet);
169 struct packet_foo * receive_packet_foo (struct connection *pc);
171 The send_packet_foo() function serializes a structure into a bytestream
172 and adds this to the send buffer in the connection struct.
173 The receive_packet_foo() function de-serializes a bytestream into a
174 structure and removes the bytestream from the input buffer in the
176 The connection struct is defined in common/connection.h.
178 Each structure field in a structure is serialized using architecture
179 independent functions such as dio_put_uint32() and de-serialized with
180 functions like dio_get_uint32().
182 A packet is constituted by header followed by the serialized structure
183 data. The header contains the following fields (the sizes are defined in
184 common/packets.c:packet_header_set()). Currently this header is
185 identical to one used in initial handshake protocol, but this can
186 change in future versions.
188 uint16 : length (the length of the entire packet)
189 uint8 : type (e.g. PACKET_TILE_INFO)
191 For backward compatibility reasons, packets used for the initial protocol
192 (notably before checking the capabilities) have different header fields
193 sizes (defined in common/packets.c:packet_header_init()):
195 uint16 : length (the length of the entire packet)
196 uint8 : type (e.g. PACKET_SERVER_JOIN_REQ)
198 To demonstrate the route for a packet through the system, here's how
199 a unit disband is performed:
201 1) A player disbands a unit.
202 2) The client initializes a packet_unit_request structure, and calls the
203 packet layer function send_packet_unit_request() with this structure and
204 packet type: PACKET_UNIT_DISBAND.
205 3) The packet layer serializes the structure, wraps it up in a packet
206 containing the packetlength, type and the serialized data. Finally
207 the data is send to the server.
208 4) On the server the packet is read. Based on the type, the corresponding
209 de-serialize function is called is called by get_packet_from_connection().
210 5) A packet_unit_request is initialized with the bytestream.
211 6) Since the incoming packet is a request (a request in this context
212 is every packet sent from the client to the server) the server sends a
213 PACKET_PROCESSING_STARTED packet to the client.
214 7) Finally the corresponding packet-handler, handle_unit_disband() function,
215 is called with the newly constructed structure.
216 8) The handler function checks if the disband request is legal (is the sender
217 really the owner of the unit) etc.
218 9) The unit is disbanded => wipe_unit() => send_remove_unit().
219 10) Now an integer, containing the id of the disbanded unit is
220 wrapped into a packet along with the type PACKET_REMOVE_UNIT:
221 send_packet_generic_integer().
222 11) The packet is serialized and send across the network.
223 12) The packet-handler returns and the end of the processing is
224 announced to the client with a PACKET_PROCESSING_FINISHED packet.
225 13) On the client the PACKET_REMOVE_UNIT packet is deserialized into
226 a packet_generic_integer structure.
227 14) The corresponding client handler function is now called
228 handle_remove_unit(), and finally the unit is disbanded.
230 Notice that the two packets (PACKET_UNIT_DISBAND and
231 PACKET_REMOVE_UNIT) were generic packets. That means the packet
232 structures involved, are used by various requests. The
233 packet_unit_request() is for example also used for the packets
234 PACKET_UNIT_BUILD_CITY and PACKET_UNIT_CHANGE_HOMECITY.
236 When adding a new packet type, check to see if you can reuse some of the
237 existing packet types. This saves you the trouble of
238 writing new serialize/deserialize functions.
240 The PACKET_PROCESSING_STARTED and PACKET_PROCESSING_FINISHED packets
241 from above serve two main purposes:
243 - they allow the client to identify what causes a certain packet the
244 client receives. If the packet is framed by PACKET_PROCESSING_STARTED
245 and PACKET_PROCESSING_FINISHED packets it is the causes of the
246 request. If not the received packet was not caused by this client
247 (server operator, other clients, server at a new turn)
249 - after a PACKET_PROCESSING_FINISHED packet the client can test if
250 the requested action was performed by the server. If the server has
251 sent some updates the client data structure will now hold other
254 The PACKET_FREEZE_HINT and PACKET_THAW_HINT packets serve two
257 - Packets send between these two packets may contain multiple
258 information packets which may cause multiple updates of some GUI
259 items. PACKET_FREEZE_HINT and PACKET_THAW_HINT can now be used to
260 freeze the GUI at the time PACKET_FREEZE_HINT is received and only
261 update the GUI after the PACKET_THAW_HINT packet is received.
263 - Packets send between these two packets may contain contradicting
264 information which may confuse a client-side AI (agents for
265 example). So any updates send between these two packets are only
266 processed after the PACKET_THAW_HINT packet is received.
268 The following areas are wrapped by PACKET_FREEZE_HINT and
271 - the data send if a new game starts
272 - the data send to a reconnecting player
273 - the end turn activities
275 The Xaw client uses XtAppAddInput() to tell Xt to call the callback
276 functions, when something happens on the client socket.
277 The GTK+ client uses a similar gdk_input_add() call.
279 =========================================================================
281 =========================================================================
283 In previous versions when a connection send buffer in the server got full
284 we emptied the buffer contents and continued processing. Unfortunately this
285 caused incomplete packets to be sent to the client, which caused crashes
286 in either the client or the server, since the client cannot detect this
287 situation. This has been fixed by closing the client connection when the
290 We also had (and still have) several problems related to flow control.
291 Basically the problem is the server can send packets much faster than the
292 client can process them. This is especially true when in the end of the
293 turn the AIs move all their units. Unit moves in particular take a long
294 time for the client to process since by default smooth unit moves is on.
296 There are 3 ways to solve this problem:
297 1) We wait for the send buffers to drain before continuing processing.
298 2) We cut the player's connection and empty the send buffer.
299 3) We lose packets (this is similar to 2) but can cause an incoherent
300 state in the client).
302 We mitigated the problem by increasing the send buffer size on the server
303 and making it dynamic. We also added in strategic places in the code calls
304 to a new flush_packets() function that makes the server stall for some time
305 draining the send buffers. Strategic places include whenever we send the
306 whole map. The maximum amount of time spent per flush_packets() call is
307 specified by the 'netwait' variable.
309 To disconnect unreachable clients we added two other features: the server
310 terminates a client connection if it doesn't accept writes for a period
311 of time (set using the 'tcptimeout' variable). It also pings the client
312 after a certain time elapses (set using the 'pingtimeout' variable). If
313 the client doesn't reply its connection is closed.
315 =========================================================================
317 =========================================================================
318 Currently the graphics is stored in the PNG file format (other formats
319 may be readable by some clients).
321 If you alter the graphics, then make sure that the background remains
322 transparent. Failing to do this means the mask-pixmaps will not be
323 generated properly, which will certainly not give any good results.
325 Each terrain tile is drawn in 16 versions, all the combinations with
326 with a green border in one of the main directions. Hills, mountains,
327 forests and rivers are treated in special cases.
329 The Xaw client requires that the graphics be stored in "paletted" PNGs,
330 which for graphics with few colors is probably a good idea anyway. It also
331 has a limited number of colors available, although it will try to match
332 similar-looking colors after the existing supply has been exhausted. Of
333 course, not every tileset has to be usable by the Xaw client.
335 Isometric tilesets are drawn in a similar way to how civ2 draws (that's
336 why civ2 graphics are compatible). For each base terrain type there
337 exists one tile sprite for that terrain. The tile is blended with
338 nearby tiles to get a nice-looking boundary. This is erronously called
339 "dither" in the code.
341 Non-isometric tilesets draw the tiles in the "original" freeciv way,
342 which is both harder and less pretty. There are multiple copies of
343 each tile, so that a different copy can be drawn depending the terrain
344 type of the adjacent tiles. It may eventually be worthwhile to convert
345 this to the civ2 system.
347 =========================================================================
349 =========================================================================
350 A few words about the diplomacy system. When a diplomacy meeting is
351 established, a Treaty structure is created on both of the clients and
352 on the server. All these structures are updated concurrently as clauses
353 are added and removed.
355 =========================================================================
357 =========================================================================
358 The map is maintained in a pretty straightforward C array, containing
359 X*Y tiles. You can use the function
360 struct tile *map_pos_to_tile(x, y)
361 to find a pointer to a specific tile.
362 A tile has various fields; see the struct in "common/map.h"
364 You may iterate tiles, you may use the following methods:
366 whole_map_iterate(tile_itr) {
368 } whole_map_iterate_end;
369 for iterating all tiles of the map;
371 adjc_iterate(center_tile, tile_itr) {
374 for iterating all tiles close to 'center_tile', in all *valid* directions
375 for the current topology (see below);
377 cardinal_adjc_iterate(center_tile, tile_itr) {
379 } cardinal_adjc_iterate_end;
380 for iterating all tiles close to 'center_tile', in all *cardinal* directions
381 for the current topology (see below);
383 square_iterate(center_tile, radius, tile_itr) {
385 } square_iterate_end;
386 for iterating all tiles in the radius defined 'radius' (in real distance,
387 see below), beginning by 'center_tile';
389 circle_iterate(center_tile, radius, tile_itr) {
391 } square_iterate_end;
392 for iterating all tiles in the radius defined 'radius' (in square distance,
393 see below), beginning by 'center_tile';
395 iterate_outward(center_tile, real_dist, tile_itr) {
397 } iterate_outward_end;
398 for iterating all tiles in the radius defined 'radius' (in real distance,
399 see below), beginning by 'center_tile'. (Actually, this is the duplicate
402 or various tricky ones defined in "common/map.h", which automatically
403 adjust the tile values. The defined macros should be used whenever
404 possible, the examples above were only included to give people the
405 knowledge of how things work.
407 Note that the following
408 for (x1 = x-1; x1 <= x+1; x1++) {
409 for (y1 = y-1; y1 <= y+1; y1++) {
413 is not a reliable way to iterate all adjacent tiles for all topologies, so
414 such operations should be avoided.
417 Also available are the functions calculating distance between tiles. In
418 Freeciv, we are using 3 types of distance between tiles:
420 map_distance(ptile0, ptile1) returns the *Manhattan* distance between
421 tiles, i.e. the distance from 'ptile0' to 'ptile1', only using cardinal
422 directions, for example (abs(dx) + ads(dy)) for non-hexagonal topologies.
424 real_map_distance(ptile0, ptile1) returns the *normal* distance between
425 tiles, i.e. the minimal distance from 'ptile0' to 'ptile1' using all
426 valid directions for the current topology.
428 sq_map_distance(ptile0, ptile1) returns the *square* distance between
429 tiles. This is a simple way to make Pythagorean effects for making circles
430 on the map for example. For non-hexagonal topologies, it would be
431 (dx * dx + dy * dy). Only useless square root is missing.
433 =========================================================================
434 Different types of map topology
435 =========================================================================
437 Originally Freeciv supports only a simple rectangular map. For instance
438 a 5x3 map would be conceptualized as
444 and it looks just like that under "overhead" (non-isometric) view (the
445 arrows represent an east-west wrapping). But under an isometric-view
446 client, the same map will look like
456 where "north" is to the upper-right and "south" to the lower-left. This
457 makes for a mediocre interface.
459 An isometric-view client will behave better with an isometric map. This is
460 what Civ2, SMAC, Civ3, etc. all use. A rectangular isometric map can be
468 (north is up) and it will look just like that under an isometric-view client.
469 Of course under an overhead-view client it will again turn out badly.
471 Both types of maps can easily wrap in either direction: north-south or
472 east-west. Thus there are four types of wrapping: flat-earth, vertical
473 cylinder, horizontal cylinder, and torus. Traditionally Freeciv only wraps
474 in the east-west direction.
476 =========================================================================
477 Topology, cardinal directions and valid directions
478 =========================================================================
480 A *cardinal* direction connects tiles per a *side*.
481 Another *valid* direction connects tiles per a *corner*.
483 In non-hexagonal topologies, there are 4 cardinal directions, and 4 other
485 In hexagonal topologies, there are 6 cardinal directions, which matches
486 exactly the 6 valid directions.
488 Note that with isometric view, the direction named "North" (DIR8_NORTH)
489 is actually not from the top to the bottom of the screen view. All
490 directions are turned a step on the left (pi/4 rotation with square tiles,
491 pi/3 rotation for hexagonal tiles).
493 =========================================================================
494 Different coordinate systems
495 =========================================================================
497 In Freeciv, we have the general concept of a "position" or "tile". A tile
498 can be referred to in any of several coordinate systems. The distinction
499 becomes important when we start to use non-standard maps (see above).
501 Here is a diagram of coordinate conversions for a classical map.
503 map natural native index
506 EFGH <=> EFGH <=> EFGH <=> ABCDEFGHIJKL
509 Here is a diagram of coordinate conversions for an iso-map.
511 map natural native index
514 BEIL <=> D E F <=> DEF <=> ABCDEFGHIJKL
518 Below each of the coordinate systems are explained in more detail.
520 Note that hexagonal topologies are always considered as isometric.
522 - Map (or "standard") coordinates.
524 All of the code examples above are in map coordinates. These preserve
525 the local geometry of square tiles, but do not represent the global map
526 geometry well. In map coordinates, you are guaranteed (so long as we use
527 square tiles) that the tile adjacency rules
529 (map_x-1, map_y-1) (map_x, map_y-1) (map_x+1, map_y-1)
530 (map_x-1, map_y) (map_x, map_y) (map_x+1, map_y)
531 (map_x-1, map_y+1) (map_x, map_y+1) (map_x+1, map_y+1)
533 are preserved, regardless of what the underlying map or drawing code
534 looks like. This is the definition of the system.
536 With an isometric view, this looks like:
539 (map_x-1, map_y) (map_x, map_y-1)
540 (map_x-1, map_y+1) (map_x, map_y) (map_x+1, map_y-1)
541 (map_x, map_y+1) (map_x+1, map_y)
544 Map coordinates are easiest for local operations (like 'square_iterate'
545 and friends, translations, rotations and any other scalar operation)
546 but unwieldy for global operations.
548 When performing operations in map coordinates (like a translation
549 of tile (x, y) by (dx, dy) -> (x + dx, y + dy)), the new map coordinates
550 may be unsuitable for the current map. In case, you should use one of
551 the following functions/macros:
553 map_pos_to_tile(): return NULL if normalization is not possible;
555 normalize_map_pos(): return TRUE if normalization have been done (wrapping
556 X and Y coordinates if the current topology allows it);
558 is_normal_map_pos(): return TRUE if the map coordinates exist for the map;
560 is_real_map_pos(): return TRUE if the map coordinates may exist if we
561 perform normalization.
563 CHECK_MAP_POS(): assert whether the map coordinates exist for the map.
565 Map coordinates are quite central in the coordinate system, and they may
566 be easily converted to any other coordinates: MAP_TO_NATURAL_POS(),
567 MAP_TO_NATIVE_POS(), map_pos_to_index().
569 - Natural coordinates.
571 Natural coordinates preserve the geometry of map coordinates, but also have
572 the rectangular property of native coordinates. They are unwieldy for
573 most operations because of their sparseness - they may not have the same
574 scale as map coordinates and, in the iso case, there are gaps in the
575 natural representation of a map.
577 With classical view, this looks like:
579 (nat_x-1, nat_y-1) (nat_x, nat_y-1) (nat_x+1, nat_y-1)
580 (nat_x-1, nat_y) (nat_x, nat_y) (nat_x+1, nat_y)
581 (nat_x-1, nat_y+1) (nat_x, nat_y+1) (nat_x+1, nat_y+1)
583 With an isometric view, this looks like:
586 (nat_x-1, nat_y-1) (nat_x+1, nat_y-1)
587 (nat_x-2, nat_y) (nat_x, nat_y) (nat_x+2, nat_y)
588 (nat_x-1, nat_y+1) (nat_x+1, nat_y+1)
591 Natural coordinates are mostly used for operations which concern the user
592 view. It is the best way to determine the horizontal and the vertical
595 The only coordinates conversion is done using NATURAL_TO_MAP_POS().
597 - Native coordinates.
599 With classical view, this looks like:
601 (nat_x-1, nat_y-1) (nat_x, nat_y-1) (nat_x+1, nat_y-1)
602 (nat_x-1, nat_y) (nat_x, nat_y) (nat_x+1, nat_y)
603 (nat_x-1, nat_y+1) (nat_x, nat_y+1) (nat_x+1, nat_y+1)
605 With an isometric view, this looks like:
608 (nat_x-1, nat_y-1) (nat_x, nat_y-1)
609 (nat_x-1, nat_y) (nat_x, nat_y) (nat_x+1, nat_y)
610 (nat_x-1, nat_y+1) (nat_x, nat_y+1)
613 Neither is particularly good for a global map operation such as
614 map wrapping or conversions to/from map indexes, something better
617 Native coordinates compress the map into a continuous rectangle; the
618 dimensions are defined as map.xsize x map.ysize. For instance the
619 above iso-rectangular map is represented in native coordinates by
620 compressing the natural representation in the X axis to get the
623 ABC (0,0) (1,0) (2,0)
624 DEF <=> (0,1) (1,1) (2,1)
625 GHI (0,2) (1,2) (3,2)
627 The resulting coordinate system is much easier to use than map
628 coordinates for some operations. These include most internal topology
629 operations (e.g., normalize_map_pos, whole_map_iterate) as well as
630 storage (in map.tiles and savegames, for instance).
632 In general, native coordinates can be defined based on this property:
633 the basic map becomes a continuous (gap-free) cardinally-oriented
634 rectangle when expressed in native coordinates.
636 Native coordinates can be easily converted to map coordinates using
637 NATIVE_TO_MAP_POS(), to index using native_pos_to_index() and
638 to tile (shortcut) using native_pos_to_tile().
640 After operations, such as FC_WRAP(x, map.xsize), the result may be checked
641 with CHECK_NATIVE_POS().
645 Index coordinates simply reorder the map into a continuous (filled-in)
646 one-dimensional system. This coordinate system is closely tied to
647 the ordering of the tiles in native coordinates, and is slightly
648 easier to use for some operations (like storage) because it is
649 one-dimensional. In general you can't assume anything about the ordering
650 of the positions within the system.
652 Indexes can be easily converted to native coordinates using
653 index_to_native_pos() or to map positions (shortcut) using
656 An map index can tested using the CHECK_INDEX macro.
658 With a classical rectangular map, the first three coordinate systems are
659 equivalent. When we introduce isometric maps, the distinction becomes
660 important, as demonstrated above. Many places in the code have
661 introduced "map_x/map_y" or "nat_x/nat_y" to help distinguish whether
662 map or native coordinates are being used. Other places are not yet
663 rigorous in keeping them apart, and will often just name their variables
664 "x" and "y". The latter can usually be assumed to be map coordinates.
666 Note that if you don't need to do some abstract geometry exploit, you
667 will mostly use tile pointers, and give to map.[ch] tools the ability
668 to perform what you want.
670 Note that map.xsize and map.ysize define the dimension of the map in
671 _native_ coordinates.
673 Of course, if a future topology does not fit these rules for coordinate
674 systems, they will have to be refined.
676 =========================================================================
677 Native coordinates on an isometric map
678 =========================================================================
680 An isometric map is defined by the operation that converts between map
681 (user) coordinates and native (internal) ones. In native coordinates, an
682 isometric map behaves exactly the same way as a standard one. (See
683 "native coordinates", above.
685 Converting from map to native coordinates involves a pi/2 rotation (which
686 scales in each dimension by sqrt(2)) followed by a compression in the X
687 direction by a factor of 2. Then a translation is required since the
688 "normal set" of native coordinates is defined as
689 {(x, y) | x: [0..map.xsize) and y: [0..map.ysize)}
690 while the normal set of map coordinates must satisfy x >= 0 and y >= 0.
692 Converting from native to map coordinates (a less cumbersome operation) is
696 (native) FGHIJ <=> F G H I J <=> CHN (map)
703 native_to_map_pos(0, 0) == (0, map.xsize-1)
704 native_to_map_pos(map.xsize-1, 0) == (map.xsize-1, 0)
705 native_to_map_pos(x, y+2) = native_to_map_pos(x,y) + (1,1)
706 native_to_map_pos(x+1, y) = native_to_map_pos(x,y) + (1,-1)
708 The math then works out to
710 map_x = ceiling(nat_y / 2) + nat_x
711 map_y = floor(nat_y / 2) - nat_x + map.xsize - 1
713 nat_y = map_x + map_y - map.xsize
714 nat_x = floor(map_x - map_y + map.xsize / 2)
716 which leads to the macros NATIVE_TO_MAP_POS(), MAP_TO_NATIVE_POS() that are
719 =========================================================================
720 Unknown tiles and Fog of War
721 =========================================================================
723 In common/player.h, there are several fields:
727 struct dbv tile_known;
735 struct dbv tile_vision[V_COUNT];
740 While tile_get_known() returns:
742 /* network, order dependent */
745 TILE_KNOWN_UNSEEN = 1,
749 The values TILE_UNKNOWN, TILE_KNOWN_SEEN are straightforward.
750 TILE_KNOWN_UNSEEN is a tile of which the user knows the terrain,
751 but not recent cities, roads, etc.
753 TILE_UNKNOWN tiles never are (nor should be) sent to the client. In the
754 past, UNKNOWN tiles that were adjacent to UNSEEN or SEEN were sent to make
755 the drawing process easier, but this has now been removed. This means
756 exploring new land may sometimes change the appearance of existing land (but
757 this is not fundamentally different from what might happen when you
758 transform land). Sending the extra info, however, not only confused the
759 goto code but allowed cheating.
761 Fog of war is the fact that even when you have seen a tile once you are
762 not sent updates unless it is inside the sight range of one of your units
765 We keep track of fog of war by counting the number of units and cities
766 [and nifty future things like radar outposts] of each client that can
767 see the tile. This requires a number per player, per tile, so each player_tile
768 has a short[]. Every time a unit/city/miscellaneous can observe a tile
769 1 is added to its player's number at the tile, and when it can't observe
770 any more (killed/moved/pillaged) 1 is subtracted. In addition to the
771 initialization/loading of a game this array is manipulated with the
772 void unfog_area(struct player *pplayer, int x, int y, int len)
774 void fog_area(struct player *pplayer, int x, int y, int len)
775 functions. "int len" is the radius of the area that should be
776 fogged/unfogged, i.e. a len of 1 is a normal unit. In addition to keeping
777 track of fog of war, these functions also make sure to reveal TILE_UNKNOWN
778 tiles you get near, and send info about TILE_UNKNOWN tiles near that the
779 client needs for drawing. They then send the tiles to
780 void send_tile_info(struct player *dest, int x, int y)
781 which then sets the correct known_type and sends the tile to the client.
783 If you want to just show the terrain and cities of the square the
784 function show_area does this. The tiles remain fogged.
785 If you play without fog of war all the values of the seen arrays are
786 initialized to 1. So you are using the exact same code, you just never
787 get down to 0. As changes in the "fogginess" of the tiles are only sent
788 to the client when the value shifts between zero and non-zero, no
789 redundant packages are sent. You can even switch fog of war on/off
790 in game just by adding/subtracting 1 to all the tiles.
792 We only send city and terrain updates to the players who can see the
793 tile. So a city (or improvement) can exist in a square that is known and
794 fogged and not be shown on the map. Likewise, you can see a city in a
795 fogged square even if the city doesn't exist (it will be removed when
796 you see the tile again). This is done by 1) only sending info to players
797 who can see a tile 2) keeping track of what info has been sent so the
798 game can be saved. For the purpose of 2) each player has a map on the
799 server (consisting of player_tile's and dumb_city's) where the relevant
802 The case where a player p1 gives map info to another player p2: This
803 requires some extra info. Imagine a tile that neither player sees, but
804 which p1 have the most recent info on. In that case the age of the players'
805 info should be compared which is why the player tile has a last_updated
807 This field is not kept up to date as long as the player can see the tile
808 and it is unfogged, but when the tile gets fogged the date is updated.
810 [An alternative solution would be to give each tile a list
811 of the units and cities that observe it. IMO this would not be any
812 easier than just counting, and would have no benefits. The current
813 solution also gives the possibility to reveal squares as you like,
814 say near a radar tower tile special. Very flexible.]
816 [The barbarians and the ai take their map info directly from the server,
817 so they can currently ignore fog of war, and they do so. I really think
818 that the ideal AI wouldn't be cheating like this.]
820 There is now a shared vision feature, meaning that if p1 gives shared
821 vision to p2, every time a function like show_area, fog_area, unfog_area
822 or give_tile_info_from_player_to_player is called on p1 p2 also gets the
823 info. Note that if p2 gives shared info to p3, p3 also gets the info.
824 This is controlled by p1's really_gives_vision bitvector, where the
825 dependencies will be kept.
827 If there is anything I have explained inadequately in this section you
828 can ask me on <thue@diku.dk>.
831 =========================================================================
833 =========================================================================
834 For the display of national borders (similar to those used in Sid Meier's
835 Alpha Centauri) each map tile also has an "owner" field, to identify
836 which nation lays claim to it. If game.borders is non-zero, each city
837 claims a circle of tiles game.borders in radius (in the case of neighbouring
838 enemy cities, tiles are divided equally, with the older city winning any
839 ties). Cities claim all immediately adjacent tiles, plus any other tiles
840 within the border radius on the same continent. Land cities also claim ocean
841 tiles if they are surrounded by 5 land tiles on the same continent (this is
842 a crude detection of inland seas or lakes, which should be improved upon).
844 Tile ownership is decided only by the server, and sent to the clients, which
845 draw border lines between tiles of differing ownership. Owner information is
846 sent for all tiles that are known by a client, whether or not they are fogged.
847 A patch to convert this to "semi-fogged" behaviour, whereby clients receive
848 limited information about non-neighbouring and unseen enemies, is available
849 at http://freecivac.sf.net/.
851 =========================================================================
852 Xaw Client GUI- Athena
853 =========================================================================
854 The old freeciv-xaw client GUI is written using athena-widgets. A few
855 comments on this could prove useful for anyone wishing to write new
856 dialogs or improve on the current ones.
860 When you create new widgets for a dialog, like:
862 players_form = XtVaCreateManagedWidget("playersform",
864 players_dialog_shell, NULL);
866 then put the widget properties in the app-default file 'Freeciv', instead
867 of hardcoding them. For the widget created above, the following entries
868 in the app-default file applies:
870 *playersform.background: lightblue
871 *playersform.resizable: true
872 *playersform.top: chainTop
873 *playersform.bottom: chainBottom
874 *playersform.left: chainLeft
875 *playersform.right: chainRight
879 The Pixcomm is a subclassed Command-widget, which can displays a Pixmap
880 instead of a string, on top of a button(command). The Pixcomm widget
881 should be used all places where this kind of high-level functionality
884 The Canvas widget is more low-level. One have to write an expose(redraw)
885 event-handler for each widget. The widget generates events on resize
888 [Reading any Xt documentation, will tell you how powerful widget
889 subclassing is. So I went trough great troubles subclassing the
890 command widget. It was not before long I got mails from unhappy Xaw3d
891 (and derives) users, that the client keeps crashing on them. Turns
892 out that subclassing from any widgets but Core, chains the new
893 widgets to libXaw. In hindsight I should just subclassed the Canvas
894 widget and add more highlevel functionality. -PU]
896 ===========================================================================
897 Misc - The idea trashcan
898 ===========================================================================
899 [Currently all of the major entities - units, cities, players, contains
900 an unique id. This id is really only required when a reference to an entity
901 is to be serialized(saved or distributed over the net). However in the
902 current code, the id is also used for comparing, looking up and in general
903 referencing entities. This results in a lot of mess and unnecessary duplicate
904 functions. Often when programming, one wonders if some function needs
905 the id or a pointer when referring to an entity. -PU]
907 The paragraph above isn't true anymore for player, units and cities. -RF
909 ===========================================================================
911 Player-related entities in Freeciv - by Reinier Post <reinpost@win.tue.nl>
912 + by dwp@mso.anu.edu.au
914 Freeciv is confused about the meaning of 'player'. As a participant in
915 Freeciv games, you'll notice that the participants are called 'players'.
916 At the same time, players seem to be identified with civilizations.
917 On the other hand, civilizations seem to be identified by 'nation':
918 every player chooses a nation at the start of the game.
920 In the data structures, a 'player' identifies a civilization, not a user.
925 There are four player-related entities:
928 A civilization, with a capital, cities, units, an income, etc.
931 A type of civilization (except that very little actually depends on
932 nation, and the oddity exists that each player must be of different
936 Identifies 'someone out there', usually a human user running
940 Records a client connection; like a user, but disappears when the user
941 disconnects, whereas for real users we may want to remember them between
942 connections. See Connections section below.
944 Where do these entities exist?
946 Nations aren't actually used for annything that matters; for them,
947 so the question isn't very interesting.
949 Players (more aptly named, 'civilizations'), exist in games. Except in
950 the context of a running game, the entity makes no sense. Players and
951 their status are part of savefiles. A game can be saved and restarted
952 on a different server; the players will be the same. A new game will
953 have new players. Players exist in common/ (even games do) but a
954 client only has one instantiated player.
956 The reason to introduce users is client-side server commands. It must
957 be possible to assign different levels of access to commands to different
958 users. Attaching it to players is not good enough: the information must
959 survive the addition and removal of other players, the start or restart
960 of a game, reconnections by the same user even from different computers,
961 or transferral of the game to a different server. However, a user
962 may have different levels of access in different games.
964 While they last, connections are sufficient identification for users.
965 The user entity will allow users to be identified when they reconnect.
967 Ideally, users would be identified with unique global ids, handed out
968 by a 'registry service' similar to the metaserver, but this would be
969 too cumbersome in practice. So the plan is to make users persist in
970 a server session (even whan a game is started, or restarted when that
971 option is added) and make them persist across games (when a saved
972 game is loaded in a different server session).
974 Users will be created when they first connect to a server, remembered by
975 the running server and in savefiles. Upon connecting, the client will
976 be sent a unique session id, generated when the server started, plus a
977 fresh user id; it will store them in a ~/.civcookie file, and send it
978 back when trying to reconnect. This will allow the identity of users
979 to be protected. 'Protected' players will only allow the same user to
980 reconnect; 'unprotected' ones allow anyone to connect; server commands
981 and probably client options will be available to control this.
983 Player names will be assigned to users, not players.
985 The server maintains a default access level, which is used for new
986 users and unprotected ones.
989 THE PRESENT IMPLEMENTATION:
991 Currently access levels are stored in the connection struct. This allows
992 access levels to be assigned to each individual connected player, which
993 would not be the case if they were directly assigned to the player struct
994 (due to the fact that the players array changes when players are added or
999 Players are still created before the game is started, and player names
1000 still belong to players. Access levels exist in client and server,
1001 but only the server uses them. User ids are not yet implemented;
1002 Server ids do not exist at all.
1004 Commands to protect/unprotect users do not yet exist; they would serve
1007 Access levels can set for individual users, including AI players with
1008 a connected observer, but only while someone is connected; they will not
1009 be remembered when the user disconnects.
1011 ===========================================================================
1013 ===========================================================================
1015 The code is currently transitioning from 1 or 0 connections per player
1016 only, to allowing multiple connections for each player (recall
1017 'player' means a civilization, see above), where each connection may
1018 be either an "observer" or "controller".
1020 This discussion is mostly about connection in the server. The client
1021 only has one real connection (client.conn) -- its connection to the
1022 server -- though it does use some other connection structs (currently
1023 pplayer->conn) to store information about other connected clients
1024 (eg, capability strings).
1026 In the old paradigm, server code would usually send information to a
1027 single player, or to all connected players (usually represented by
1028 destination being a NULL player pointer). With multiple connections
1029 per player things become more complicated. Sometimes information
1030 should be sent to a single connection, or to all connections for a
1031 single player, or to all (established) connections, etc. To handle
1032 this, "destinations" should now be specified as a pointer to a struct
1033 conn_list (list of connections). For convenience the following
1034 commonly applicable lists are maintained:
1035 game.all_connections - all connections
1036 game.est_connections - established connections
1037 game.game_connections - connections observing and/or involved in game
1038 pplayer->connections - connections for specific player
1039 pconn->self - single connection (as list)
1041 Connections can be classified as follows: (first match applies)
1043 1. (pconn->used == 0) Not a real connection (closed/unused), should
1044 not exist in any list of have any information sent to it.
1046 (All following cases exist in game.all_connections.)
1048 2. (pconn->established == 0) TCP connection has been made, but initial
1049 Freeciv packets have not yet been negotiated (join_game etc).
1050 Exists in game.all_connections only. Should not be sent any
1051 information except directly as result of join_game etc packets,
1052 or server shutdown, or connection close, etc.
1054 (All following cases exist in game.est_connections.)
1056 3. (pconn->player == NULL) Connection has been established, but is not
1057 yet associated with a player. Currently this is not possible, but
1058 the plan is to allow this in future, so clients can connect and
1059 then see list of players to choose from, or just control the server
1060 or observe etc. Two subcases:
1062 3a. (pconn->observer == 0) Not observing the game. Should receive
1063 information about other clients, game status etc, but not map,
1066 (All following cases exist in game.game_connections.)
1068 3b. (pconn->observer == 1) Observing the game. Exists in
1069 game.game_connections. Should receive game information about
1070 map, units, cities, etc.
1072 4. (pconn->player != NULL) Connected to specific player, either as
1073 "observer" or "controller". (But observers not yet implemented.)
1074 Exists in game.game_connections, and in pconn->player->connections.
1077 ===========================================================================
1078 Starting a Server from Within a Client
1079 ===========================================================================
1081 After many years of complaints regarding the ease (or lack thereof) of
1082 starting a game of Freeciv [start a server, input settings on a command line,
1083 start a client, and connect, etc], a method has been developed for starting
1084 and playing a complete game using only the client. This has been called the
1085 "extended" or "new connect dialog". This is perhaps a misnomer, but there it
1086 is. This win32 client has had this feature in some form for some time.
1088 It works by forking a server from within the client and then controlling that
1089 server via chatline messages. The guts of the machinery to do this can be
1090 found in these files:
1092 client/connectdlg_common.[ch]
1093 client/gui-*/connectdlg.[ch]
1095 server/gamehand.[ch]
1096 server/stdinhand.[ch]
1098 When a player starts a client, he is presents with several options: start
1099 a new game, continue a saved game and connect to a networked game. For the
1100 latter option, connect_to_server() is called and login proceeeds as normal.
1101 The the first two options, connectdlg_common.c:client_start_server() is
1102 called. Here, a server is spawned, standard input and outputs to that process
1103 are closed, and then connect_to_server() is called so the client connects to
1106 At this point everything regarding the client/server connection is as usual;
1107 however, for the client to control the server, it must have access level HACK,
1108 so it must verify to the server that it is local (on the same machine or at
1109 least has access to the same disk as the server). The procedure is:
1111 1. the server creates a file using gamehand.c:create_challenge_filename() and
1112 puts the name of this file in packet_server_join_reply that it sends back
1113 to the client. The name of the file is semi-random.
1114 2. The client, upon receiving confirmation that it can join the server,
1115 creates a file using the name the server selected and places a random number
1117 3. The client sends a packet [packet_single_want_hack_req] with that random
1118 number back to the server.
1119 4. The server upon receiving the packet [packet_single_want_hack_req], opens
1120 the file and compares the two numbers. If the file exists and the numbers
1121 are equal the server grants that client HACK access level and sends a
1122 packet [packet_single_want_hack_reply] informing the client of its elevated
1125 Only one other packet is used --- packet_single_playerlist_req --- which asks
1126 the server to send a player list when a savegame is loaded. This list is used
1127 for player selection.
1130 ===========================================================================
1131 Macros and inline functions
1132 ===========================================================================
1134 For a long time Freeciv had no inline functions, only macros. With the
1135 use of other C99 features and some new requirements by the code, this has
1136 changed. Now both macros and inline functions are used.
1138 This causes problems because one coder may prefer to use a macro while
1139 another prefers an inline function. Of course there was always some
1140 discretion to the author about whether to use a function or a macro; all
1141 we've done is add even more choices.
1143 Therefore the following guidelines should be followed:
1145 - Functions should only be put into header files when doing so makes a
1146 measurable impact on speed. Functions should not be turned into macros or
1147 inlined unless there is a reason to do so.
1149 - Macros that take function-like parameters should evaluate each parameter
1150 exactly once. Any macro that doesn't follow this convention should be
1151 named in all upper-case letters as a MACRO.
1153 - Iterator macros should respect "break".
1155 - In header files macros are preferred to inline functions, but inline
1156 functions are better than MACROS.
1158 - Functions or macros that are currently in one form do not have to be
1159 changed to the other form.
1161 Note that many existing macros do not follow these guidelines.
1164 ===========================================================================
1166 ===========================================================================
1168 See CodingStyle in this directory.
1170 - If you send patches, use "diff -u" (or "diff -r -u"). For further
1171 information, see <http://www.freeciv.org/wiki/How_to_Contribute>.
1172 Also, name patch files descriptively (e.g. "fix-foo-bug-0.patch" is good,
1173 but "freeciv.patch" is not).
1175 - When doing a "diff" for a patch, be sure to exclude unnecessary files
1176 by using the "-X" argument to "diff". E.g.:
1178 % diff -ruN -Xdiff_ignore freeciv_svn freeciv >/tmp/fix-foo-bug-0.patch
1180 A suggested "diff_ignore" file is included in the Freeciv distribution.
1182 ===========================================================================
1183 Internationalization (I18N)
1184 ===========================================================================
1186 Messages and text in general which are shown in the GUI should be
1187 translated by using the "_()" macro. In addition log_normal() messages
1188 should be translated. In most cases, the other log levels (log_fatal(),
1189 log_error(), log_verbose(), log_debug()) should NOT be localised.
1191 See utility/fciconv.h for details of how Freeciv handles character sets
1192 and encodings. Briefly:
1194 The data_encoding is used in all data files and network transactions.
1197 The internal_encoding is used internally within freeciv. This is always
1198 UTF-8 at the server, but can be configured by the GUI client. (When your
1199 charset is the same as your GUI library, GUI writing is easier.)
1201 The local_encoding is the one supported on the command line. This is not
1202 under our control, and all output to the command line must be converted.
1204 ===========================================================================
1205 Debugging and Profiling
1206 ===========================================================================
1208 Debugging has to be activated on compile time by adding the option
1209 '--enable-debug=no/some/yes/checks' to the configure script. The different
1210 options have the following meaning:
1212 no: no debugging enabled(FREECIV_NDEBUG and NDEBUG are defined)
1213 additional compiler flags for optimisation (-O3 -fomit-frame-pointer)
1214 some: default build (neither FREECIV_NDEBUG nor FREECIV_DEBUG is defined)
1215 yes: debugging enable (FREECIV_DEBUG is defined)
1216 debugging log level available (4, log_debug())
1217 additional compiler flags:
1218 -Werror -Wmissing-prototypes -Wmissing-declarations
1219 -Wformat -Wformat-security -Wnested-externs
1221 checks: same as 'yes' but with one additional compiler check:
1223 This is OK for the server and most clients but in the case
1224 of the gtk client there is a problems in its main external library
1225 (gtk2) which prevent the compilation of the client using the
1226 extended flags. A fix is available but will not be applied due to
1227 compatibility issues. To compile freeciv with this option,
1228 temporary patch the file gtkitemfactory.h
1229 (see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=148766).
1231 Profiling is enabled by '--enable-gprof'. After the compilation run freeciv
1232 normally. It will be 5 to 10 times slower due to the added calls to the
1233 profiling functions. After freeciv quits normally (not after a crash) the
1234 file gmon.out is written. It can be analyzed by calling
1235 'gprof ./server/freeciv-server gmon.out > gprof.txt'. More information can
1236 be found at http://sourceware.org/binutils/docs/gprof/index.html.
1238 ===========================================================================