webperimental: killstack decides stack protects.
[freeciv.git] / doc / HACKING
blob2986a501b3b3bf7851ac98b709c687b79e0c41e9
1                           Freeciv Hacker's Guide
2                           
3 This guide is intended to be a help for developers, wanting to mess with
4 Freeciv program. 
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 ===========================================================================
13 Basic
14 ===========================================================================
15 Freeciv is a client/server civilization style of game.
16 The client is pretty dumb. Almost all calculations are performed on the
17 server.
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.
30 server: (duh)
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 ===========================================================================
43 Server
44 ===========================================================================
45 General:
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 */
53     game_next_year();
54   }
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 
80                         # toggled to AI mode
81 start                   # start game
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
88 of:
89 $ while( time server/freeciv-server -r civ.serv ); do date; done
90   ---  or  ---
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
97 watch the show.
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
109 helpful:
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 ===========================================================================
116 Data Structures
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
123 do the following:
125 unit_list_iterate(ptile->units, punit) {
126 /* In here we could do something with punit, which is a pointer to a
127     unit struct */
128 } unit_list_iterate_end;
130 Note that the macro itself declares the variable punit.
131 Similarly there is a 
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 =========================================================================
155 Network and Packets
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
175 connection struct.
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()):
186 uint16  :       length          (the length of the entire packet)
187 uint16  :       type            (e.g. PACKET_TILE_INFO)
189 For backward compatibility reasons, packets used for the initial protocol
190 (notably before checking the capabilities) have different header fields
191 sizes (defined in common/packets.c:packet_header_init()):
193 uint16  :       length          (the length of the entire packet)
194 uint8   :       type            (e.g. PACKET_SERVER_JOIN_REQ)
196 To demonstrate the route for a packet through the system, here's how
197 a unit disband is performed:
199 1)  A player disbands a unit.
200 2)  The client initializes a packet_unit_request structure, and calls the
201     packet layer function send_packet_unit_request() with this structure and
202     packet type: PACKET_UNIT_DISBAND.
203 3)  The packet layer serializes the structure, wraps it up in a packet
204     containing the packetlength, type and the serialized data. Finally 
205     the data is send to the server.
206 4)  On the server the packet is read. Based on the type, the corresponding
207     de-serialize function is called is called by get_packet_from_connection(). 
208 5)  A packet_unit_request is initialized with the bytestream.
209 6)  Since the incoming packet is a request (a request in this context 
210     is every packet sent from the client to the server) the server sends a 
211     PACKET_PROCESSING_STARTED packet to the client.
212 7)  Finally the corresponding packet-handler, handle_unit_disband() function,
213     is called with the newly constructed structure.
214 8)  The handler function checks if the disband request is legal (is the sender
215     really the owner of the unit) etc.
216 9)  The unit is disbanded => wipe_unit() => send_remove_unit().
217 10) Now an integer, containing the id of the disbanded unit is
218     wrapped into a packet along with the type PACKET_REMOVE_UNIT:
219     send_packet_generic_integer().
220 11) The packet is serialized and send across the network.
221 12) The packet-handler returns and the end of the processing is 
222     announced to the client with a PACKET_PROCESSING_FINISHED packet.
223 13) On the client the PACKET_REMOVE_UNIT packet is deserialized into 
224     a packet_generic_integer structure.
225 14) The corresponding client handler function is now called 
226     handle_remove_unit(), and finally the unit is disbanded.
228 Notice that the two packets (PACKET_UNIT_DISBAND and
229 PACKET_REMOVE_UNIT) were generic packets.  That means the packet
230 structures involved, are used by various requests.  The
231 packet_unit_request() is for example also used for the packets
232 PACKET_UNIT_BUILD_CITY and PACKET_UNIT_CHANGE_HOMECITY.
234 When adding a new packet type, check to see if you can reuse some of the
235 existing packet types. This saves you the trouble of
236 writing new serialize/deserialize functions.
238 The PACKET_PROCESSING_STARTED and PACKET_PROCESSING_FINISHED packets
239 from above serve two main purposes:
241  - they allow the client to identify what causes a certain packet the
242  client receives. If the packet is framed by PACKET_PROCESSING_STARTED
243  and PACKET_PROCESSING_FINISHED packets it is the causes of the
244  request. If not the received packet was not caused by this client
245  (server operator, other clients, server at a new turn)
247  - after a PACKET_PROCESSING_FINISHED packet the client can test if
248  the requested action was performed by the server. If the server has
249  sent some updates the client data structure will now hold other
250  values.
252 The PACKET_FREEZE_HINT and PACKET_THAW_HINT packets serve two
253 purposes:
255  - Packets send between these two packets may contain multiple
256  information packets which may cause multiple updates of some GUI
257  items. PACKET_FREEZE_HINT and PACKET_THAW_HINT can now be used to
258  freeze the GUI at the time PACKET_FREEZE_HINT is received and only
259  update the GUI after the PACKET_THAW_HINT packet is received.
261  - Packets send between these two packets may contain contradicting
262  information which may confuse a client-side AI (agents for
263  example). So any updates send between these two packets are only
264  processed after the PACKET_THAW_HINT packet is received.
266 The following areas are wrapped by PACKET_FREEZE_HINT and
267 PACKET_THAW_HINT:
269  - the data send if a new game starts
270  - the data send to a reconnecting player
271  - the end turn activities
273 The GTK+ client uses gdk_input_add() to tell gtk to call the callback
274 functions, when something happens on the client socket.
276 =========================================================================
277 Network Improvements
278 =========================================================================
280 In previous versions when a connection send buffer in the server got full
281 we emptied the buffer contents and continued processing. Unfortunately this
282 caused incomplete packets to be sent to the client, which caused crashes
283 in either the client or the server, since the client cannot detect this
284 situation. This has been fixed by closing the client connection when the
285 buffer is emptied.
287 We also had (and still have) several problems related to flow control.
288 Basically the problem is the server can send packets much faster than the
289 client can process them. This is especially true when in the end of the
290 turn the AIs move all their units. Unit moves in particular take a long
291 time for the client to process since by default smooth unit moves is on.
293 There are 3 ways to solve this problem:
294 1) We wait for the send buffers to drain before continuing processing.
295 2) We cut the player's connection and empty the send buffer.
296 3) We lose packets (this is similar to 2) but can cause an incoherent
297    state in the client).
299 We mitigated the problem by increasing the send buffer size on the server
300 and making it dynamic. We also added in strategic places in the code calls
301 to a new flush_packets() function that makes the server stall for some time
302 draining the send buffers. Strategic places include whenever we send the
303 whole map. The maximum amount of time spent per flush_packets() call is
304 specified by the 'netwait' variable.
306 To disconnect unreachable clients we added two other features: the server
307 terminates a client connection if it doesn't accept writes for a period
308 of time (set using the 'tcptimeout' variable). It also pings the client
309 after a certain time elapses (set using the 'pingtimeout' variable). If
310 the client doesn't reply its connection is closed.
312 =========================================================================
313 Graphics
314 =========================================================================
315 Currently the graphics is stored in the PNG file format (other formats
316 may be readable by some clients).
318 If you alter the graphics, then make sure that the background remains
319 transparent.  Failing to do this means the mask-pixmaps will not be
320 generated properly, which will certainly not give any good results.
322 Each terrain tile is drawn in 16 versions, all the combinations with
323 with a green border in one of the main directions. Hills, mountains,
324 forests and rivers are treated in special cases.
326 Isometric tilesets are drawn in a similar way to how civ2 draws (that's
327 why civ2 graphics are compatible).  For each base terrain type there
328 exists one tile sprite for that terrain.  The tile is blended with
329 nearby tiles to get a nice-looking boundary.  This is erronously called
330 "dither" in the code.
332 Non-isometric tilesets draw the tiles in the "original" freeciv way,
333 which is both harder and less pretty.  There are multiple copies of
334 each tile, so that a different copy can be drawn depending the terrain
335 type of the adjacent tiles.  It may eventually be worthwhile to convert
336 this to the civ2 system.
338 =========================================================================
339 Diplomacy
340 =========================================================================
341 A few words about the diplomacy system. When a diplomacy meeting is
342 established, a Treaty structure is created on both of the clients and
343 on the server. All these structures are updated concurrently as clauses
344 are added and removed.
346 =========================================================================
347 Map structure
348 =========================================================================
349 The map is maintained in a pretty straightforward C array, containing
350 X*Y tiles. You can use the function
351 struct tile *map_pos_to_tile(x, y)
352 to find a pointer to a specific tile.
353 A tile has various fields; see the struct in "common/map.h"
355 You may iterate tiles, you may use the following methods:
357 whole_map_iterate(tile_itr) {
358   /* do something */
359 } whole_map_iterate_end;
360 for iterating all tiles of the map;
362 adjc_iterate(center_tile, tile_itr) {
363   /* do something */
364 } adjc_iterate_end;
365 for iterating all tiles close to 'center_tile', in all *valid* directions
366 for the current topology (see below);
368 cardinal_adjc_iterate(center_tile, tile_itr) {
369   /* do something */
370 } cardinal_adjc_iterate_end;
371 for iterating all tiles close to 'center_tile', in all *cardinal* directions
372 for the current topology (see below);
374 square_iterate(center_tile, radius, tile_itr) {
375   /* do something */
376 } square_iterate_end;
377 for iterating all tiles in the radius defined 'radius' (in real distance,
378 see below), beginning by 'center_tile';
380 circle_iterate(center_tile, radius, tile_itr) {
381   /* do something */
382 } square_iterate_end;
383 for iterating all tiles in the radius defined 'radius' (in square distance,
384 see below), beginning by 'center_tile';
386 iterate_outward(center_tile, real_dist, tile_itr) {
387   /* do something */
388 } iterate_outward_end;
389 for iterating all tiles in the radius defined 'radius' (in real distance,
390 see below), beginning by 'center_tile'. (Actually, this is the duplicate
391 of square_iterate);
393 or various tricky ones defined in "common/map.h", which automatically
394 adjust the tile values. The defined macros should be used whenever
395 possible, the examples above were only included to give people the
396 knowledge of how things work.
398 Note that the following
399 for (x1 = x-1; x1 <= x+1; x1++) {
400   for (y1 = y-1; y1 <= y+1; y1++) {
401     /* do something */
402   }
404 is not a reliable way to iterate all adjacent tiles for all topologies, so
405 such operations should be avoided.
408 Also available are the functions calculating distance between tiles. In
409 Freeciv, we are using 3 types of distance between tiles:
411 map_distance(ptile0, ptile1) returns the *Manhattan* distance between
412 tiles, i.e. the distance from 'ptile0' to 'ptile1', only using cardinal
413 directions, for example (abs(dx) + ads(dy)) for non-hexagonal topologies.
415 real_map_distance(ptile0, ptile1) returns the *normal* distance between
416 tiles, i.e. the minimal distance from 'ptile0' to 'ptile1' using all
417 valid directions for the current topology.
419 sq_map_distance(ptile0, ptile1) returns the *square* distance between
420 tiles. This is a simple way to make Pythagorean effects for making circles
421 on the map for example. For non-hexagonal topologies, it would be
422 (dx * dx + dy * dy). Only useless square root is missing.
424 =========================================================================
425 Different types of map topology
426 =========================================================================
428 Originally Freeciv supports only a simple rectangular map.  For instance
429 a 5x3 map would be conceptualized as
431   <- XXXXX ->
432   <- XXXXX ->
433   <- XXXXX ->
435 and it looks just like that under "overhead" (non-isometric) view (the
436 arrows represent an east-west wrapping).  But under an isometric-view
437 client, the same map will look like
439      X
440     X X
441    X X X
442     X X X
443      X X X
444       X X
445        x
447 where "north" is to the upper-right and "south" to the lower-left.  This
448 makes for a mediocre interface.
450 An isometric-view client will behave better with an isometric map.  This is
451 what Civ2, SMAC, Civ3, etc. all use.  A rectangular isometric map can be
452 conceptualized as
454   <- X X X X X  ->
455   <-  X X X X X ->
456   <- X X X X X  ->
457   <-  X X X X X ->
459 (north is up) and it will look just like that under an isometric-view client.
460 Of course under an overhead-view client it will again turn out badly.
462 Both types of maps can easily wrap in either direction: north-south or
463 east-west.  Thus there are four types of wrapping: flat-earth, vertical
464 cylinder, horizontal cylinder, and torus.  Traditionally Freeciv only wraps
465 in the east-west direction.
467 =========================================================================
468 Topology, cardinal directions and valid directions
469 =========================================================================
471 A *cardinal* direction connects tiles per a *side*.
472 Another *valid* direction connects tiles per a *corner*.
474 In non-hexagonal topologies, there are 4 cardinal directions, and 4 other
475 valid directions.
476 In hexagonal topologies, there are 6 cardinal directions, which matches
477 exactly the 6 valid directions.
479 Note that with isometric view, the direction named "North" (DIR8_NORTH)
480 is actually not from the top to the bottom of the screen view. All
481 directions are turned a step on the left (pi/4 rotation with square tiles,
482 pi/3 rotation for hexagonal tiles).
484 =========================================================================
485 Different coordinate systems
486 =========================================================================
488 In Freeciv, we have the general concept of a "position" or "tile".  A tile
489 can be referred to in any of several coordinate systems.  The distinction
490 becomes important when we start to use non-standard maps (see above).
492   Here is a diagram of coordinate conversions for a classical map.
494       map        natural      native       index
496       ABCD        ABCD         ABCD
497       EFGH  <=>   EFGH     <=> EFGH   <=> ABCDEFGHIJKL
498       IJKL        IJKL         IJKL
500   Here is a diagram of coordinate conversions for an iso-map.
502      map          natural     native       index
504         CF        A B C         ABC     
505        BEIL  <=>   D E F   <=>  DEF   <=> ABCDEFGHIJKL
506       ADHK        G H I         GJI
507        GJ          J K L        JKL
509 Below each of the coordinate systems are explained in more detail.
511 Note that hexagonal topologies are always considered as isometric.
513 - Map (or "standard") coordinates.
515   All of the code examples above are in map coordinates.  These preserve
516   the local geometry of square tiles, but do not represent the global map
517   geometry well.  In map coordinates, you are guaranteed (so long as we use
518   square tiles) that the tile adjacency rules
520       (map_x-1, map_y-1)    (map_x, map_y-1)   (map_x+1, map_y-1)
521       (map_x-1, map_y)      (map_x, map_y)     (map_x+1, map_y)
522       (map_x-1, map_y+1)    (map_x, map_y+1)   (map_x+1, map_y+1)
524   are preserved, regardless of what the underlying map or drawing code
525   looks like.  This is the definition of the system.
527   With an isometric view, this looks like:
529                               (map_x-1, map_y-1)
530                  (map_x-1, map_y)            (map_x, map_y-1)
531   (map_x-1, map_y+1)          (map_x, map_y)              (map_x+1, map_y-1)
532                  (map_x, map_y+1)            (map_x+1, map_y)
533                               (map_x+1, map_y+1)
535   Map coordinates are easiest for local operations (like 'square_iterate'
536   and friends, translations, rotations and any other scalar operation)
537   but unwieldy for global operations.
539   When performing operations in map coordinates (like a translation
540   of tile (x, y) by (dx, dy) -> (x + dx, y + dy)), the new map coordinates
541   may be unsuitable for the current map. In case, you should use one of
542   the following functions/macros:
544   map_pos_to_tile(): return NULL if normalization is not possible;
546   normalize_map_pos(): return TRUE if normalization have been done (wrapping
547   X and Y coordinates if the current topology allows it);
549   is_normal_map_pos(): return TRUE if the map coordinates exist for the map;
551   is_real_map_pos(): return TRUE if the map coordinates may exist if we
552   perform normalization.
554   CHECK_MAP_POS(): assert whether the map coordinates exist for the map.
556   Map coordinates are quite central in the coordinate system, and they may
557   be easily converted to any other coordinates: MAP_TO_NATURAL_POS(),
558   MAP_TO_NATIVE_POS(), map_pos_to_index().
560 - Natural coordinates.
562   Natural coordinates preserve the geometry of map coordinates, but also have
563   the rectangular property of native coordinates.  They are unwieldy for
564   most operations because of their sparseness - they may not have the same
565   scale as map coordinates and, in the iso case, there are gaps in the
566   natural representation of a map.
568   With classical view, this looks like:
570       (nat_x-1, nat_y-1)    (nat_x, nat_y-1)   (nat_x+1, nat_y-1)
571       (nat_x-1, nat_y)      (nat_x, nat_y)     (nat_x+1, nat_y)
572       (nat_x-1, nat_y+1)    (nat_x, nat_y+1)   (nat_x+1, nat_y+1)
574   With an isometric view, this looks like:
576                               (nat_x, nat_y-2)
577                (nat_x-1, nat_y-1)          (nat_x+1, nat_y-1)
578   (nat_x-2, nat_y)            (nat_x, nat_y)              (nat_x+2, nat_y)
579                (nat_x-1, nat_y+1)          (nat_x+1, nat_y+1)
580                               (nat_x, nat_y+2)
582   Natural coordinates are mostly used for operations which concern the user
583   view. It is the best way to determine the horizontal and the vertical
584   axis of the view.
586   The only coordinates conversion is done using NATURAL_TO_MAP_POS().
588 - Native coordinates.
590   With classical view, this looks like:
592       (nat_x-1, nat_y-1)    (nat_x, nat_y-1)   (nat_x+1, nat_y-1)
593       (nat_x-1, nat_y)      (nat_x, nat_y)     (nat_x+1, nat_y)
594       (nat_x-1, nat_y+1)    (nat_x, nat_y+1)   (nat_x+1, nat_y+1)
596   With an isometric view, this looks like:
598                               (nat_x, nat_y-2)
599                (nat_x-1, nat_y-1)          (nat_x, nat_y-1)
600   (nat_x-1, nat_y)            (nat_x, nat_y)            (nat_x+1, nat_y)
601                (nat_x-1, nat_y+1)          (nat_x, nat_y+1)
602                               (nat_x, nat_y+2)
604   Neither is particularly good for a global map operation such as
605   map wrapping or conversions to/from map indexes, something better
606   is needed.
608   Native coordinates compress the map into a continuous rectangle; the
609   dimensions are defined as map.xsize x map.ysize.  For instance the
610   above iso-rectangular map is represented in native coordinates by
611   compressing the natural representation in the X axis to get the
612   3x3 iso-rectangle of
614                     ABC       (0,0) (1,0) (2,0)
615                     DEF  <=>  (0,1) (1,1) (2,1)
616                     GHI       (0,2) (1,2) (3,2)
618   The resulting coordinate system is much easier to use than map
619   coordinates for some operations.  These include most internal topology
620   operations (e.g., normalize_map_pos, whole_map_iterate) as well as
621   storage (in map.tiles and savegames, for instance).
623   In general, native coordinates can be defined based on this property:
624   the basic map becomes a continuous (gap-free) cardinally-oriented
625   rectangle when expressed in native coordinates.
627   Native coordinates can be easily converted to map coordinates using
628   NATIVE_TO_MAP_POS(), to index using native_pos_to_index() and
629   to tile (shortcut) using native_pos_to_tile().
631   After operations, such as FC_WRAP(x, map.xsize), the result may be checked
632   with CHECK_NATIVE_POS().
634 - Index coordinates.
636   Index coordinates simply reorder the map into a continuous (filled-in)
637   one-dimensional system.  This coordinate system is closely tied to
638   the ordering of the tiles in native coordinates, and is slightly
639   easier to use for some operations (like storage) because it is
640   one-dimensional.  In general you can't assume anything about the ordering
641   of the positions within the system.
643   Indexes can be easily converted to native coordinates using
644   index_to_native_pos() or to map positions (shortcut) using
645   index_to_map_pos().
647   An map index can tested using the CHECK_INDEX macro.
649 With a classical rectangular map, the first three coordinate systems are
650 equivalent.  When we introduce isometric maps, the distinction becomes
651 important, as demonstrated above.  Many places in the code have
652 introduced "map_x/map_y" or "nat_x/nat_y" to help distinguish whether
653 map or native coordinates are being used.  Other places are not yet
654 rigorous in keeping them apart, and will often just name their variables
655 "x" and "y".  The latter can usually be assumed to be map coordinates.
657 Note that if you don't need to do some abstract geometry exploit, you
658 will mostly use tile pointers, and give to map.[ch] tools the ability
659 to perform what you want.
661 Note that map.xsize and map.ysize define the dimension of the map in
662 _native_ coordinates.
664 Of course, if a future topology does not fit these rules for coordinate
665 systems, they will have to be refined.
667 =========================================================================
668 Native coordinates on an isometric map
669 =========================================================================
671 An isometric map is defined by the operation that converts between map
672 (user) coordinates and native (internal) ones.  In native coordinates, an
673 isometric map behaves exactly the same way as a standard one.  (See
674 "native coordinates", above.
676 Converting from map to native coordinates involves a pi/2 rotation (which
677 scales in each dimension by sqrt(2)) followed by a compression in the X
678 direction by a factor of 2.  Then a translation is required since the
679 "normal set" of native coordinates is defined as
680   {(x, y) | x: [0..map.xsize) and y: [0..map.ysize)}
681 while the normal set of map coordinates must satisfy x >= 0 and y >= 0.
683 Converting from native to map coordinates (a less cumbersome operation) is
684 the opposite.
685                                         EJ
686            ABCDE     A B C D E         DIO
687   (native) FGHIJ <=>  F G H I J <=>   CHN  (map)
688            KLMNO     K L M N O       BGM
689                                     AFL
690                                      K
692 Note that
694   native_to_map_pos(0, 0) == (0, map.xsize-1)
695   native_to_map_pos(map.xsize-1, 0) == (map.xsize-1, 0)
696   native_to_map_pos(x, y+2) = native_to_map_pos(x,y) + (1,1)
697   native_to_map_pos(x+1, y) = native_to_map_pos(x,y) + (1,-1)
699 The math then works out to
701   map_x = ceiling(nat_y / 2) + nat_x
702   map_y = floor(nat_y / 2) - nat_x + map.xsize - 1
704   nat_y = map_x + map_y - map.xsize
705   nat_x = floor(map_x - map_y + map.xsize / 2)
707 which leads to the macros NATIVE_TO_MAP_POS(), MAP_TO_NATIVE_POS() that are
708 defined in map.h.
710 =========================================================================
711 Unknown tiles and Fog of War
712 =========================================================================
714 In common/player.h, there are several fields:
716 struct player {
717   ...
718   struct dbv tile_known;
720   union {
721     struct {
722       ...
723     } server;
725     struct {
726       struct dbv tile_vision[V_COUNT];
727     } client;
728   };
731 While tile_get_known() returns:
733 /* network, order dependent */
734 enum known_type {
735  TILE_UNKNOWN = 0,
736  TILE_KNOWN_UNSEEN = 1,
737  TILE_KNOWN_SEEN = 2,
740 The values TILE_UNKNOWN, TILE_KNOWN_SEEN are straightforward.
741 TILE_KNOWN_UNSEEN is a tile of which the user knows the terrain,
742 but not recent cities, roads, etc.
744 TILE_UNKNOWN tiles never are (nor should be) sent to the client.  In the
745 past, UNKNOWN tiles that were adjacent to UNSEEN or SEEN were sent to make
746 the drawing process easier, but this has now been removed.  This means
747 exploring new land may sometimes change the appearance of existing land (but
748 this is not fundamentally different from what might happen when you
749 transform land).  Sending the extra info, however, not only confused the
750 goto code but allowed cheating.
752 Fog of war is the fact that even when you have seen a tile once you are
753 not sent updates unless it is inside the sight range of one of your units
754 or cities.
756 We keep track of fog of war by counting the number of units and cities
757 [and nifty future things like radar outposts] of each client that can
758 see the tile. This requires a number per player, per tile, so each player_tile
759 has a short[]. Every time a unit/city/miscellaneous can observe a tile
760 1 is added to its player's number at the tile, and when it can't observe
761 any more (killed/moved/pillaged) 1 is subtracted. In addition to the
762 initialization/loading of a game this array is manipulated with the
763 void unfog_area(struct player *pplayer, int x, int y, int len)
765 void fog_area(struct player *pplayer, int x, int y, int len)
766 functions. "int len" is the radius of the area that should be
767 fogged/unfogged, i.e. a len of 1 is a normal unit. In addition to keeping
768 track of fog of war, these functions also make sure to reveal TILE_UNKNOWN
769 tiles you get near, and send info about TILE_UNKNOWN tiles near that the
770 client needs for drawing. They then send the tiles to
771 void send_tile_info(struct player *dest, int x, int y)
772 which then sets the correct known_type and sends the tile to the client.
774 If you want to just show the terrain and cities of the square the
775 function show_area does this. The tiles remain fogged.
776 If you play without fog of war all the values of the seen arrays are
777 initialized to 1. So you are using the exact same code, you just never
778 get down to 0. As changes in the "fogginess" of the tiles are only sent
779 to the client when the value shifts between zero and non-zero, no
780 redundant packages are sent. You can even switch fog of war on/off
781 in game just by adding/subtracting 1 to all the tiles.
783 We only send city and terrain updates to the players who can see the
784 tile. So a city (or improvement) can exist in a square that is known and
785 fogged and not be shown on the map. Likewise, you can see a city in a
786 fogged square even if the city doesn't exist (it will be removed when
787 you see the tile again). This is done by 1) only sending info to players
788 who can see a tile 2) keeping track of what info has been sent so the
789 game can be saved. For the purpose of 2) each player has a map on the
790 server (consisting of player_tile's and dumb_city's) where the relevant
791 information is kept.
793 The case where a player p1 gives map info to another player p2: This
794 requires some extra info. Imagine a tile that neither player sees, but
795 which p1 have the most recent info on. In that case the age of the players'
796 info should be compared which is why the player tile has a last_updated
797 field.
798 This field is not kept up to date as long as the player can see the tile
799 and it is unfogged, but when the tile gets fogged the date is updated.
801 [An alternative solution would be to give each tile a list
802 of the units and cities that observe it. IMO this would not be any
803 easier than just counting, and would have no benefits. The current
804 solution also gives the possibility to reveal squares as you like,
805 say near a radar tower tile special. Very flexible.]
807 [The barbarians and the ai take their map info directly from the server,
808 so they can currently ignore fog of war, and they do so. I really think
809 that the ideal AI wouldn't be cheating like this.]
811 There is now a shared vision feature, meaning that if p1 gives shared
812 vision to p2, every time a function like show_area, fog_area, unfog_area
813 or give_tile_info_from_player_to_player is called on p1 p2 also gets the
814 info. Note that if p2 gives shared info to p3, p3 also gets the info.
815 This is controlled by p1's really_gives_vision bitvector, where the
816 dependencies will be kept.
818 If there is anything I have explained inadequately in this section you
819 can ask me on <thue@diku.dk>.
820 -Thue
822 =========================================================================
823 National borders
824 =========================================================================
825 For the display of national borders (similar to those used in Sid Meier's
826 Alpha Centauri) each map tile also has an "owner" field, to identify
827 which nation lays claim to it. If game.borders is non-zero, each city
828 claims a circle of tiles game.borders in radius (in the case of neighbouring
829 enemy cities, tiles are divided equally, with the older city winning any
830 ties). Cities claim all immediately adjacent tiles, plus any other tiles
831 within the border radius on the same continent. Land cities also claim ocean
832 tiles if they are surrounded by 5 land tiles on the same continent (this is
833 a crude detection of inland seas or lakes, which should be improved upon).
835 Tile ownership is decided only by the server, and sent to the clients, which
836 draw border lines between tiles of differing ownership. Owner information is
837 sent for all tiles that are known by a client, whether or not they are fogged.
838 A patch to convert this to "semi-fogged" behaviour, whereby clients receive
839 limited information about non-neighbouring and unseen enemies, is available
840 at http://freecivac.sf.net/.
842 ===========================================================================
843 Misc - The idea trashcan
844 ===========================================================================
845 [Currently all of the major entities - units, cities, players, contains
846 an unique id. This id is really only required when a reference to an entity
847 is to be serialized(saved or distributed over the net). However in the
848 current code, the id is also used for comparing, looking up and in general
849 referencing entities. This results in a lot of mess and unnecessary duplicate
850 functions. Often when programming, one wonders if some function needs
851 the id or a pointer when referring to an entity. -PU]
853 The paragraph above isn't true anymore for player, units and cities. -RF
855 ===========================================================================
857 Player-related entities in Freeciv - by Reinier Post <reinpost@win.tue.nl>
858 + by dwp@mso.anu.edu.au
860 Freeciv is confused about the meaning of 'player'.  As a participant in
861 Freeciv games, you'll notice that the participants are called 'players'.
862 At the same time, players seem to be identified with civilizations.
863 On the other hand, civilizations seem to be identified by 'nation':
864 every player chooses a nation at the start of the game.
866 In the data structures, a 'player' identifies a civilization, not a user.
868 ----
869   THE PLAN:
871 There are four player-related entities:
873 + player
874   A civilization, with a capital, cities, units, an income, etc.
876 + nation
877   A type of civilization (except that very little actually depends on
878   nation, and the oddity exists that each player must be of different 
879   nation)
881 + user
882   Identifies 'someone out there', usually a human user running
883   freeciv client.
885 + connection
886   Records a client connection; like a user, but disappears when the user 
887   disconnects, whereas for real users we may want to remember them between 
888   connections.  See Connections section below.
890 Where do these entities exist?
892 Nations aren't actually used for annything that matters; for them,
893 so the question isn't very interesting.
895 Players (more aptly named, 'civilizations'), exist in games.  Except in
896 the context of a running game, the entity makes no sense.  Players and
897 their status are part of savefiles.  A game can be saved and restarted
898 on a different server; the players will be the same.  A new game will
899 have new players.  Players exist in common/ (even games do) but a
900 client only has one instantiated player.
902 The reason to introduce users is client-side server commands.  It must
903 be possible to assign different levels of access to commands to different
904 users.  Attaching it to players is not good enough: the information must
905 survive the addition and removal of other players, the start or restart
906 of a game, reconnections by the same user even from different computers,
907 or transferral of the game to a different server.  However, a user
908 may have different levels of access in different games.
910 While they last, connections are sufficient identification for users.
911 The user entity will allow users to be identified when they reconnect.
913 Ideally, users would be identified with unique global ids, handed out
914 by a 'registry service' similar to the metaserver, but this would be
915 too cumbersome in practice.  So the plan is to make users persist in
916 a server session (even whan a game is started, or restarted when that
917 option is added) and make them persist across games (when a saved
918 game is loaded in a different server session).
920 Users will be created when they first connect to a server, remembered by
921 the running server and in savefiles.  Upon connecting, the client will
922 be sent a unique session id, generated when the server started, plus a
923 fresh user id; it will store them in a ~/.civcookie file, and send it
924 back when trying to reconnect.  This will allow the identity of users
925 to be protected.  'Protected' players will only allow the same user to
926 reconnect; 'unprotected' ones allow anyone to connect; server commands
927 and probably client options will be available to control this.
929 Player names will be assigned to users, not players.
931 The server maintains a default access level, which is used for new
932 users and unprotected ones.
934 ----
935   THE PRESENT IMPLEMENTATION:
937 Currently access levels are stored in the connection struct.  This allows 
938 access levels to be assigned to each individual connected player, which 
939 would not be the case if they were directly assigned to the player struct 
940 (due to the fact that the players array changes when players are added or 
941 removed).
943 But that's it.
945 Players are still created before the game is started, and player names
946 still belong to players.  Access levels exist in client and server, 
947 but only the server uses them.  User ids are not yet implemented;
948 Server ids do not exist at all.
950 Commands to protect/unprotect users do not yet exist; they would serve 
951 no useful purpose.
953 Access levels can set for individual users, including AI players with 
954 a connected observer, but only while someone is connected; they will not 
955 be remembered when the user disconnects.
957 ===========================================================================
958 Connections
959 ===========================================================================
961 The code is currently transitioning from 1 or 0 connections per player
962 only, to allowing multiple connections for each player (recall
963 'player' means a civilization, see above), where each connection may
964 be either an "observer" or "controller".
966 This discussion is mostly about connection in the server.  The client
967 only has one real connection (client.conn) -- its connection to the
968 server -- though it does use some other connection structs (currently
969 pplayer->conn) to store information about other connected clients
970 (eg, capability strings).
972 In the old paradigm, server code would usually send information to a
973 single player, or to all connected players (usually represented by
974 destination being a NULL player pointer).  With multiple connections
975 per player things become more complicated.  Sometimes information
976 should be sent to a single connection, or to all connections for a
977 single player, or to all (established) connections, etc.  To handle
978 this, "destinations" should now be specified as a pointer to a struct
979 conn_list (list of connections).  For convenience the following
980 commonly applicable lists are maintained:
981    game.all_connections   -  all connections
982    game.est_connections   -  established connections
983    game.game_connections  -  connections observing and/or involved in game
984    pplayer->connections   -  connections for specific player
985    pconn->self            -  single connection (as list)
987 Connections can be classified as follows:  (first match applies)
989 1. (pconn->used == 0) Not a real connection (closed/unused), should
990    not exist in any list of have any information sent to it.
992 (All following cases exist in game.all_connections.)
994 2. (pconn->established == 0) TCP connection has been made, but initial
995    Freeciv packets have not yet been negotiated (join_game etc).
996    Exists in game.all_connections only.  Should not be sent any
997    information except directly as result of join_game etc packets, 
998    or server shutdown, or connection close, etc.
1000 (All following cases exist in game.est_connections.)
1002 3. (pconn->player == NULL) Connection has been established, but is not
1003    yet associated with a player.  Currently this is not possible, but
1004    the plan is to allow this in future, so clients can connect and
1005    then see list of players to choose from, or just control the server
1006    or observe etc. Two subcases:
1008    3a. (pconn->observer == 0) Not observing the game.  Should receive
1009        information about other clients, game status etc, but not map,
1010        units, cities, etc.
1012 (All following cases exist in game.game_connections.)
1014    3b. (pconn->observer == 1) Observing the game.  Exists in
1015        game.game_connections.  Should receive game information about
1016        map, units, cities, etc.
1018 4. (pconn->player != NULL) Connected to specific player, either as
1019    "observer" or "controller".  (But observers not yet implemented.)
1020    Exists in game.game_connections, and in pconn->player->connections.
1023 ===========================================================================
1024 Starting a Server from Within a Client
1025 ===========================================================================
1027 After many years of complaints regarding the ease (or lack thereof) of
1028 starting a game of Freeciv [start a server, input settings on a command line,
1029 start a client, and connect, etc], a method has been developed for starting
1030 and playing a complete game using only the client. This has been called the
1031 "extended" or "new connect dialog". This is perhaps a misnomer, but there it 
1032 is. This win32 client has had this feature in some form for some time. 
1034 It works by forking a server from within the client and then controlling that
1035 server via chatline messages. The guts of the machinery to do this can be
1036 found in these files:
1038 client/connectdlg_common.[ch]
1039 client/gui-*/connectdlg.[ch]
1040 common/packets.def
1041 server/gamehand.[ch]
1042 server/stdinhand.[ch]
1044 When a player starts a client, he is presents with several options: start
1045 a new game, continue a saved game and connect to a networked game. For the 
1046 latter option, connect_to_server() is called and login proceeeds as normal.
1047 The the first two options, connectdlg_common.c:client_start_server() is 
1048 called. Here, a server is spawned, standard input and outputs to that process
1049 are closed, and then connect_to_server() is called so the client connects to 
1050 that server.
1052 At this point everything regarding the client/server connection is as usual;
1053 however, for the client to control the server, it must have access level HACK,
1054 so it must verify to the server that it is local (on the same machine or at
1055 least has access to the same disk as the server). The procedure is:
1057 1. the server creates a file using gamehand.c:create_challenge_filename() and
1058    puts the name of this file in packet_server_join_reply that it sends back
1059    to the client. The name of the file is semi-random.
1060 2. The client, upon receiving confirmation that it can join the server,
1061    creates a file using the name the server selected and places a random number
1062    inside that file.
1063 3. The client sends a packet [packet_single_want_hack_req] with that random 
1064    number back to the server.
1065 4. The server upon receiving the packet [packet_single_want_hack_req], opens
1066    the file and compares the two numbers. If the file exists and the numbers
1067    are equal the server grants that client HACK access level and sends a
1068    packet [packet_single_want_hack_reply] informing the client of its elevated
1069    access level.
1071 Only one other packet is used --- packet_single_playerlist_req --- which asks
1072 the server to send a player list when a savegame is loaded. This list is used
1073 for player selection.
1076 ===========================================================================
1077 Macros and inline functions
1078 ===========================================================================
1080 For a long time Freeciv had no inline functions, only macros.  With the
1081 use of other C99 features and some new requirements by the code, this has
1082 changed.  Now both macros and inline functions are used.
1084 This causes problems because one coder may prefer to use a macro while
1085 another prefers an inline function.  Of course there was always some
1086 discretion to the author about whether to use a function or a macro; all
1087 we've done is add even more choices.
1089 Therefore the following guidelines should be followed:
1091 - Functions should only be put into header files when doing so makes a
1092   measurable impact on speed.  Functions should not be turned into macros or
1093   inlined unless there is a reason to do so.
1095 - Macros that take function-like parameters should evaluate each parameter
1096   exactly once.  Any macro that doesn't follow this convention should be
1097   named in all upper-case letters as a MACRO.
1099 - Iterator macros should respect "break".
1101 - In header files macros are preferred to inline functions, but inline
1102   functions are better than MACROS.
1104 - Functions or macros that are currently in one form do not have to be
1105   changed to the other form.
1107 Note that many existing macros do not follow these guidelines.
1110 ===========================================================================
1111 Style Guide
1112 ===========================================================================
1114 See CodingStyle in this directory.
1116 - If you send patches, use "diff -u" (or "diff -r -u").  For further
1117   information, see <http://www.freeciv.org/wiki/How_to_Contribute>.
1118   Also, name patch files descriptively (e.g. "fix-foo-bug-0.patch" is good,
1119   but "freeciv.patch" is not).
1121 - When doing a "diff" for a patch, be sure to exclude unnecessary files
1122   by using the "-X" argument to "diff".  E.g.:
1124     % diff -ruN -Xdiff_ignore freeciv_svn freeciv >/tmp/fix-foo-bug-0.patch
1126   A suggested "diff_ignore" file is included in the Freeciv distribution.
1128 ===========================================================================
1129 Internationalization (I18N)
1130 ===========================================================================
1132 Messages and text in general which are shown in the GUI should be
1133 translated by using the "_()" macro. In addition log_normal() messages
1134 should be translated. In most cases, the other log levels (log_fatal(),
1135 log_error(), log_verbose(), log_debug()) should NOT be localised.
1137 See utility/fciconv.h for details of how Freeciv handles character sets
1138 and encodings. Briefly:
1140 The data_encoding is used in all data files and network transactions.
1141 This is UTF-8.
1143 The internal_encoding is used internally within freeciv.  This is always
1144 UTF-8 at the server, but can be configured by the GUI client.  (When your
1145 charset is the same as your GUI library, GUI writing is easier.)
1147 The local_encoding is the one supported on the command line.  This is not
1148 under our control, and all output to the command line must be converted.
1150 ===========================================================================
1151 Debugging and Profiling
1152 ===========================================================================
1154 Debugging has to be activated on compile time by adding the option
1155 '--enable-debug=no/some/yes/checks' to the configure script. The different
1156 options have the following meaning:
1158   no:     no debugging enabled(FREECIV_NDEBUG and NDEBUG are defined)
1159           additional compiler flags for optimisation (-O3 -fomit-frame-pointer)
1160   some:   default build (neither FREECIV_NDEBUG nor FREECIV_DEBUG is defined)
1161   yes:    debugging enable (FREECIV_DEBUG is defined)
1162           debugging log level available (4, log_debug())
1163           additional compiler flags:
1164             -Werror -Wmissing-prototypes -Wmissing-declarations
1165             -Wformat -Wformat-security -Wnested-externs 
1166             -Wl,--no-add-needed
1167   checks: same as 'yes' but with one additional compiler check:
1168             -Wstrict-prototypes
1170 Profiling is enabled by '--enable-gprof'. After the compilation run freeciv
1171 normally. It will be 5 to 10 times slower due to the added calls to the
1172 profiling functions. After freeciv quits normally (not after a crash) the
1173 file gmon.out is written. It can be analyzed by calling
1174 'gprof ./server/freeciv-server gmon.out > gprof.txt'. More information can
1175 be found at http://sourceware.org/binutils/docs/gprof/index.html.
1177 ===========================================================================