home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 September / PCWELT_9_2006.ISO / pcwsoft / Freeciv-2.0.8-win32-gtk2-setup.exe / doc / HACKING < prev    next >
Encoding:
Text File  |  2005-10-13  |  46.0 KB  |  1,048 lines

  1.                           Freeciv Hacker's Guide
  2.               
  3. This guide is intended to be a help for developers, wanting to mess with
  4. Freeciv program. 
  5.  
  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.
  9.  
  10. To read about the AI, see README.AI
  11.  
  12. ===========================================================================
  13. Basic
  14. ===========================================================================
  15. Freeciv is a client/server civilization style of game, written in C.
  16. The client is pretty dumb. Almost all calculations is performed on the
  17. server.
  18.  
  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]
  25.  
  26. The source code has the following important directories:
  27. common: data structures and code used by both the client and server.
  28. server: (duh)
  29. client: common client code
  30. client/* (fx gui-gtk): a specific gui implementation of the client.
  31. data: graphics, rulesets and stuff
  32. po: translations
  33. ai: the ai, later linked into the server.
  34.  
  35. ===========================================================================
  36. Server
  37. ===========================================================================
  38. General:
  39.  
  40. The server main loop basically looks like:
  41.  
  42.   while(server_state==RUN_GAME_STATE) { /* looped once per turn */
  43.     do_ai_stuff();   /* do the ai controlled players */
  44.     sniff_packets(); /* get player requests and handle them */
  45.     end_turn();      /* main turn update */
  46.     game_next_year();
  47.   }
  48.  
  49.  
  50. Most time is spend in the sniff_packets() function, where a select()
  51. call waits for packets or input on stdin(server-op commands).
  52.  
  53. ===========================================================================
  54. Server Autogame Testing
  55. ===========================================================================
  56. Code changes should always be tested before submission for inclusion
  57. into the CVS source tree. It is useful to run the client and server as
  58. autogames to verify either a particular savegame no longer shows a
  59. fixed bug, or as a random sequence of games in a while loop overnight.
  60.  
  61. To start a server game with all AI players, create a file (below named
  62. civ.serv) with lines such as the following:
  63.  
  64. # set gameseed 42       # repeat a particular game (random) sequence
  65. # set mapseed 42        # repeat a particular map generation sequence
  66. # set timeout 3         # run a client/server autogame
  67. set timeout -1          # run a server only autogame
  68. set aifill 7            # fill to 7 players
  69. hard                    # make the AI do complex things
  70. create Caesar           # first player (with known name) created and 
  71.                         # toggled to AI mode
  72. start
  73.  
  74. Note: After the start command the server prompt is unusable in
  75. autogame mode.
  76.  
  77. The commandline to run server-only games can be typed as variations
  78. of:
  79. $ while( time server/civserver -r civ.serv ); do date; done
  80.   ---  or  ---
  81. $ server/civserver -r civ.serv -f buggy1534.sav.gz
  82.  
  83. To attach one or more clients to an autogame, remove the "start"
  84. command, start the server program and attach clients to created AI
  85. players. Or type "aitoggle <player>" at the server command prompt for
  86. each player that connects. Finally, type "start" when you are ready to
  87. watch the show.
  88.  
  89. Note, that the server will eventually flood a client with updates
  90. faster than they can be drawn to the screen, thus it should always be
  91. throttled by setting a timeout value high enough to allow processing
  92. of the large update loads near the end of the game. 
  93.  
  94. The autogame mode with timeout -1 is only available in DEBUG versions
  95. and should not be used with clients as it removes virtually all the
  96. server gating controls.
  97.  
  98. ===========================================================================
  99. Data Structures
  100. ===========================================================================
  101. For variable length list of fx units and cities freeciv uses a genlist,
  102. which is implemented in common/genlist.c. By some macro magic type specific
  103. macros have been defined, avoiding much trouble.
  104. For example a tile struct (the pointer to it we call ptile) has a unit
  105. list, ptile->units; to iterate though all the units on the tile you would
  106. do the following:
  107.  
  108. unit_list_iterate(ptile->units, punit) {
  109. /* In here we could do something with punit, which is a pointer to a
  110.     unit struct */
  111. } unit_list_iterate_end;
  112.  
  113. Note that the macro itself declares the variable punit.
  114. Similarly there is a 
  115.  
  116. city_list_iterate(pplayer->cities, pcity) {
  117. /* Do something with pcity, the pointer to a city struct */
  118. } city_list_iterate_end;
  119.  
  120. There are other operations than iterating that can be performed on a list;
  121. inserting, deleting, sorting etc. See common/speclist.h
  122. Note that the way the *_list_iterate macro is implemented means you can use
  123. "continue" and "break" in the usual manner.
  124.  
  125. One thing you should keep in the back of your mind: Say you are iterating
  126. through a unit list, and then somewhere inside the iteration decide to
  127. disband a unit. In the server you would do this by calling
  128. wipe_unit(punit), which would then remove the unit node from all the
  129. relevant unit lists. But by the way unit_list_iterate works, if the removed
  130. unit was the following node unit_list_iterate will already have saved the
  131. pointer, and use it in a moment, with a segfault as the result. To avoid 
  132. this, use unit_list_iterate_safe instead.
  133.  
  134. You can also define your own lists with operations like iterating; read how
  135. in common/speclist.h.
  136.  
  137. =========================================================================
  138. Network and Packets
  139. =========================================================================
  140. The basic netcode is located in server/sernet.c and client/clinet.c.
  141.  
  142. All information passed between the server and clients, must be sent
  143. through the network as serialized packet structures.
  144. These are defined in common/packets.h.
  145.  
  146. For each 'foo' packet structure, there is one send and one receive function:
  147.  
  148. int            send_packet_foo    (struct connection *pc,
  149.                      struct packet_foo *packet);
  150. struct packet_foo * receive_packet_foo    (struct connection *pc);
  151.  
  152. The send_packet_foo() function serializes a structure into a bytestream
  153. and adds this to the send buffer in the connection struct.
  154. The receive_packet_foo() function de-serializes a bytestream into a
  155. structure and removes the bytestream from the input buffer in the
  156. connection struct.
  157. The connection struct is defined in common/connection.h.
  158.  
  159. Each structure field in a structure is serialized using architecture
  160. independent functions such as dio_put_uint32() and de-serialized with
  161. functions like dio_get_uint32().
  162.  
  163. A packet is constituted by header followed by the serialized structure
  164. data. The header contains the following fields:
  165.  
  166. uint16    :    length        (the length of the entire packet)
  167. uint8    :    type        (e.g. PACKET_TILE_INFO)
  168.  
  169. To demonstrate the route for a packet through the system, here's how
  170. a unit disband is performed:
  171.  
  172. 1)  A player disbands a unit.
  173. 2)  The client initializes a packet_unit_request structure, and calls the
  174.     packet layer function send_packet_unit_request() with this structure and
  175.     packet type: PACKET_UNIT_DISBAND.
  176. 3)  The packet layer serializes the structure, wraps it up in a packet
  177.     containing the packetlength, type and the serialized data. Finally 
  178.     the data is send to the server.
  179. 4)  On the server the packet is read. Based on the type, the corresponding
  180.     de-serialize function is called is called by get_packet_from_connection(). 
  181. 5)  A packet_unit_request is initialized with the bytestream.
  182. 6)  Since the incoming packet is a request (a request in this context 
  183.     is every packet sent from the client to the server) the server sends a 
  184.     PACKET_PROCESSING_STARTED packet to the client.
  185. 7)  Finally the corresponding packet-handler, handle_unit_disband() function,
  186.     is called with the newly constructed structure.
  187. 8)  The handler function checks if the disband request is legal (is the sender
  188.     really the owner of the unit) etc.
  189. 9)  The unit is disbanded => wipe_unit() => send_remove_unit().
  190. 10) Now an integer, containing the id of the disbanded unit is
  191.     wrapped into a packet along with the type PACKET_REMOVE_UNIT:
  192.     send_packet_generic_integer().
  193. 11) The packet is serialized and send across the network.
  194. 12) The packet-handler returns and the end of the processing is 
  195.     announced to the client with a PACKET_PROCESSING_FINISHED packet.
  196. 13) On the client the PACKET_REMOVE_UNIT packet is deserialized into 
  197.     a packet_generic_integer structure.
  198. 14) The corresponding client handler function is now called 
  199.     handle_remove_unit(), and finally the unit is disbanded.
  200.  
  201. Notice that the two packets (PACKET_UNIT_DISBAND and
  202. PACKET_REMOVE_UNIT) were generic packets.  That means the packet
  203. structures involved, are used by various requests.  The
  204. packet_unit_request() is for example also used for the packets
  205. PACKET_UNIT_BUILD_CITY and PACKET_UNIT_CHANGE_HOMECITY.
  206.  
  207. When adding a new packet type, check to see if you can reuse some of the
  208. existing packet types. This saves you the trouble of
  209. writing new serialize/deserialize functions.
  210.  
  211. The PACKET_PROCESSING_STARTED and PACKET_PROCESSING_FINISHED packets
  212. from above serve two main purposes:
  213.  
  214.  - they allow the client to identify what causes a certain packet the
  215.  client receives. If the packet is framed by PACKET_PROCESSING_STARTED
  216.  and PACKET_PROCESSING_FINISHED packets it is the causes of the
  217.  request. If not the received packet was not caused by this client
  218.  (server operator, other clients, server at a new turn)
  219.  
  220.  - after a PACKET_PROCESSING_FINISHED packet the client can test if
  221.  the requested action was performed by the server. If the server has
  222.  sent some updates the client data structure will now hold other
  223.  values.
  224.  
  225. The PACKET_FREEZE_HINT and PACKET_THAW_HINT packets serve two
  226. purposes:
  227.  
  228.  - Packets send between these two packets may contain multiple
  229.  information packets which may cause multiple updates of some GUI
  230.  items. PACKET_FREEZE_HINT and PACKET_THAW_HINT can now be used to
  231.  freeze the GUI at the time PACKET_FREEZE_HINT is received and only
  232.  update the GUI after the PACKET_THAW_HINT packet is received.
  233.  
  234.  - Packets send between these two packets may contain contradicting
  235.  information which may confuse a client-side AI (agents for
  236.  example). So any updates send between these two packets are only
  237.  processed after the PACKET_THAW_HINT packet is received.
  238.  
  239. The following areas are wrapped by PACKET_FREEZE_HINT and
  240. PACKET_THAW_HINT:
  241.  
  242.  - the data send if a new game starts
  243.  - the data send to a reconnecting player
  244.  - the end turn activities
  245.  
  246. The Xaw client uses XtAppAddInput() to tell Xt to call the callback
  247. functions, when something happens on the client socket.
  248. The GTK+ client uses a similar gdk_input_add() call.
  249.  
  250. =========================================================================
  251. Network Improvements
  252. =========================================================================
  253.  
  254. In previous versions when a connection send buffer in the server got full
  255. we emptied the buffer contents and continued processing. Unfortunately this
  256. caused incomplete packets to be sent to the client, which caused crashes
  257. in either the client or the server, since the client cannot detect this
  258. situation. This has been fixed by closing the client connection when the
  259. buffer is emptied.
  260.  
  261. We also had (and still have) several problems related to flow control.
  262. Basically the problem is the server can send packets much faster than the
  263. client can process them. This is especially true when in the end of the
  264. turn the AIs move all their units. Unit moves in particular take a long
  265. time for the client to process since by default smooth unit moves is on.
  266.  
  267. There are 3 ways to solve this problem:
  268. 1) We wait for the send buffers to drain before continuing processing.
  269. 2) We cut the player's connection and empty the send buffer.
  270. 3) We lose packets (this is similar to 2) but can cause an incoherent
  271.    state in the client).
  272.  
  273. We mitigated the problem by increasing the send buffer size on the server
  274. and making it dynamic. We also added in strategic places in the code calls
  275. to a new flush_packets() function that makes the server stall for some time
  276. draining the send buffers. Strategic places include whenever we send the
  277. whole map. The maximum amount of time spent per flush_packets() call is
  278. specified by the 'netwait' variable.
  279.  
  280. To disconnect unreachable clients we added two other features: the server
  281. terminates a client connection if it doesn't accept writes for a period
  282. of time (set using the 'tcptimeout' variable). It also pings the client
  283. after a certain time elapses (set using the 'pingtimeout' variable). If
  284. the client doesn't reply its connection is closed.
  285.  
  286. =========================================================================
  287. Graphics
  288. =========================================================================
  289. Currently the graphics is stored in the PNG file format (other formats
  290. may be readable by some clients).
  291.  
  292. If you alter the graphics, then make sure that the background remains
  293. transparent.  Failing to do this means the mask-pixmaps will not be
  294. generated properly, which will certainly not give any good results.
  295.  
  296. Each terrain tile is drawn in 16 versions, all the combinations with
  297. with a green border in one of the main directions. Hills, mountains,
  298. forests and rivers are treated in special cases.
  299.  
  300. The Xaw client requires that the graphics be stored in "paletted" PNGs,
  301. which for graphics with few colors is probably a good idea anyway. It also
  302. has a limited number of colors available, although it will try to match
  303. similar-looking colors after the existing supply has been exhausted.  Of
  304. course, not every tileset has to be usable by the Xaw client.
  305.  
  306. Isometric tilesets are drawn in a similar way to how civ2 draws (that's
  307. why civ2 graphics are compatible).  For each base terrain type there
  308. exists one tile sprite for that terrain.  The tile is blended with
  309. nearby tiles to get a nice-looking boundary.  This is erronously called
  310. "dither" in the code.
  311.  
  312. Non-isometric tilesets draw the tiles in the "original" freeciv way,
  313. which is both harder and less pretty.  There are multiple copies of
  314. each tile, so that a different copy can be drawn depending the terrain
  315. type of the adjacent tiles.  It may eventually be worthwhile to convert
  316. this to the civ2 system.
  317.  
  318. =========================================================================
  319. Diplomacy
  320. =========================================================================
  321. A few words about the diplomacy system. When a diplomacy meeting is
  322. established, a Treaty structure is created on both of the clients and
  323. on the server. All these structures are updated concurrently as clauses
  324. are added and removed.
  325.  
  326. =========================================================================
  327. Map structure
  328. =========================================================================
  329. The map is maintained in a pretty straightforward C array, containing
  330. X*Y tiles. You can use the function
  331. struct tile *map_get_tile(x, y)
  332. to find a pointer to a specific tile.
  333. A tile has various fields; see the struct in common/map.h
  334.  
  335. When operating on tiles you normally iterate over x and y and maybe use
  336. map_get_tile() to get the tile struct.
  337. When fx iterating in a square around a map position (x,y) the naive method
  338.  
  339. for (x1 = x-1; x1 <= x+1; x1++)
  340.   for (y1 = y-1; y1 <= y+1; y1++)
  341.     /* do something */
  342.  
  343. would sometimes, fx if (x,y) = (0,0) , give tiles like (-1,0) or (0,-1)
  344. Because the map wraps in the x direction the first position should be
  345. [assuming the map has the size (map.xsize,map.ysize)] (map.xsize-1, 0), while
  346. the second tile (0,-1) is not a real time at all!
  347. This could be solved by the following:
  348.  
  349. for (x1 = x-1; x1 <= x+1; x1++) {
  350.   for (y1 = y-1; y1 <= y+1; y1++) {
  351.     int abs_x = x1, abs_y = y1;
  352.     if (!normalize_map_pos(&abs_x, &abs_y))
  353.       continue;
  354.     /* do something with abs_x, abs_y */
  355.   }
  356. }
  357.  
  358. normalize_map_pos() will adjust the values of abs_x, abs_y to fix within
  359. the map, and if the original pos does not correspond to a tile, as (0, -1),
  360. it will return 0.
  361. Alternatively this could have all been done via the macro call
  362.  
  363. square_iterate(x, y, 1/*radius*/, x1, y1)  {
  364. /* do something */
  365. } square_iterate_end;
  366.  
  367. which automatically adjust the tile values. The defined macros should be
  368. used whenever possible, the example of a "manual" square iterate was only
  369. included to give people the knowledge of how things work.
  370.  
  371. Also available is the function real_map_distance(), which takes wrap and
  372. such things into account. It does not however take terrain and roads, etc.
  373. into account. For that you would use a move_cost_map, which is generated
  374. via the function generate_warmap(), and calculates the distances from a
  375. tile to all other tiles on the map. See server/gotohand.c.
  376.  
  377. Note that if all the code that operate on x and y values used macros, it
  378. would be very simple to convert these, to allow fx a flat world or a map
  379. structure like in civ2 for isometric view.
  380.  
  381. Almost all functions expect that any passed map positions are normal
  382. (is_normal_map_pos returns true). Currently there is no known
  383. exception of this rule. To assert this the CHECK_MAP_POS macro should
  384. be used.
  385.  
  386. =========================================================================
  387. Different types of map topology
  388. =========================================================================
  389.  
  390. Originally Freeciv supports only a simple rectangular map.  For instance
  391. a 5x3 map would be conceptualized as
  392.  
  393.   <- XXXXX ->
  394.   <- XXXXX ->
  395.   <- XXXXX ->
  396.  
  397. and it looks just like that under "overhead" (non-isometric) view (the
  398. arrows represent an east-west wrapping).  But under an isometric-view
  399. client, the same map will look like
  400.  
  401.      X
  402.     X X
  403.    X X X
  404.     X X X
  405.      X X X
  406.       X X
  407.        x
  408.  
  409. where "north" is to the upper-right and "south" to the lower-left.  This
  410. makes for a mediocre interface.
  411.  
  412. An isometric-view client will behave better with an isometric map.  This is
  413. what Civ2, SMAC, Civ3, etc. all use.  A rectangular isometric map can be
  414. conceptualized as
  415.  
  416.   <- X X X X X  ->
  417.   <-  X X X X X ->
  418.   <- X X X X X  ->
  419.   <-  X X X X X ->
  420.  
  421. (north is up) and it will look just like that under an isometric-view client.
  422. Of course under an overhead-view client it will again turn out badly.
  423.  
  424. Both types of maps can easily wrap in either direction: north-south or
  425. east-west.  Thus there are four types of wrapping: flat-earth, vertical
  426. cylinder, horizontal cylinder, and torus.  Traditionally Freeciv only wraps
  427. in the east-west direction.
  428.  
  429. =========================================================================
  430. Different coordinate systems
  431. =========================================================================
  432.  
  433. In Freeciv, we have the general concept of a "position" or "tile".  A tile
  434. can be referred to in any of several coordinate systems.  The distinction
  435. becomes important when we start to use non-standard maps (see above).
  436.  
  437.   Here is a diagram of coordinate conversions for a classical map.
  438.  
  439.       map        natural      native
  440.  
  441.       ABCD        ABCD         ABCD
  442.       EFGH  <=>   EFGH     <=> EFGH   <=> ABCDEFGHIJKL
  443.       IJKL        IJKL         IJKL
  444.  
  445.   Here is a diagram of coordinate conversions for an iso-map.
  446.  
  447.      map          natural     native       index
  448.  
  449.         CF        A B C         ABC     
  450.        BEIL  <=>   D E F   <=>  DEF   <=> ABCDEFGHIJKL
  451.       ADHK        G H I         GJI
  452.        GJ          J K L        JKL
  453.  
  454. Below each of the coordinate systems are explained in more detail.
  455.  
  456. - Map (or "standard") coordinates.
  457.  
  458.   All of the code examples above are in map coordinates.  These preserve
  459.   the local geometry of square tiles, but do not represent the global map
  460.   geometry well.  In map coordinates, you are guaranteed (so long as we use
  461.   square tiles) that the tile adjacency rules
  462.  
  463.       (map_x-1, map_y-1)    (map_x, map_y-1)   (map_x+1, map_y-1)
  464.       (map_x-1, map_y)      (map_x, map_y)     (map_x+1, map_y)
  465.       (map_x-1, map_y+1)    (map_x, map_y+1)   (map_x+1, map_y+1)
  466.  
  467.   are preserved, regardless of what the underlying map or drawing code
  468.   looks like.  This is the definition of the system.
  469.  
  470.   Map coordinates are easiest for local operations (like square_iterate
  471.   or adjc_iterate) but unwieldy for global operations.
  472.  
  473. - Natural coordinates.
  474.  
  475.   Natural coordinates preserve the geometry of map coordinates, but also have
  476.   the rectangular property of native coordinates.  They are unwieldy for
  477.   most operations because of their sparseness - they may not have the same
  478.   scale as map coordinates and, in the iso case, there are gaps in the
  479.   natural representation of a map.
  480.  
  481. - Native coordinates.
  482.  
  483.   With an iso-rectangular map, global operations are difficult using map
  484.   coordinates.  Imagine a simple iso-rectangular map.  Its "natural"
  485.   representation is
  486.  
  487.                  A B C        (0,0)   (2,0)   (4,0)
  488.                   D E F  <=>      (1,1)   (3,1)   (5,1)
  489.                  G H I        (0,2)   (2,2)   (4,2)
  490.  
  491.   while its representation in map coordinates would be
  492.  
  493.                      CF                   (2,0) (3,0)
  494.                     BEI  <=>        (1,1) (2,1) (3,1)
  495.                    ADH        (0,2) (1,2) (2,2)
  496.                     G               (1,3)
  497.  
  498.   Neither is particularly good for a global map operation such as
  499.   whole_map_iterate.  Something better is needed.
  500.  
  501.   Native coordinates compress the map into a continuous rectangle; the
  502.   dimensions are defined as map.xsize x map.ysize.  For instance the
  503.   above iso-rectangular map is represented in native coordinates by
  504.   compressing the natural representation in the X axis to get the
  505.   3x3 iso-rectangle of
  506.  
  507.                     ABC       (0,0) (1,0) (2,0)
  508.                     DEF  <=>  (0,1) (1,1) (2,1)
  509.                     GHI       (0,2) (1,2) (3,2)
  510.  
  511.   The resulting coordinate system is much easier to use than map
  512.   coordinates for some operations.  These include most internal topology
  513.   operations (e.g., normalize_map_pos, whole_map_iterate) as well as
  514.   storage (in map.tiles and savegames, for instance).
  515.  
  516.   In general, native coordinates can be defined based on this property:
  517.   the basic map becomes a continuous (gap-free) cardinally-oriented
  518.   rectangle when expressed in native coordinates.
  519.  
  520. - Index coordinates.
  521.  
  522.   Index coordinates simply reorder the map into a continous (filled-in)
  523.   one-dimensional system.  This coordinate system is closely tied to
  524.   the ordering of the tiles in native coordinates, and is slightly
  525.   easier to use for some operations (like storage) because it is
  526.   one-dimensional.  In general you can't assume anything about the ordering
  527.   of the positions within the system.
  528.  
  529. With a classical rectangular map, the first three coordinate systems are
  530. equivalent.  When we introduce isometric maps, the distinction becomes
  531. important, as demonstrated above.  Many places in the code have
  532. introduced "map_x/map_y" or "nat_x/nat_y" to help distinguish whether
  533. map or native coordinates are being used.  Other places are not yet
  534. rigorous in keeping them apart, and will often just name their variables
  535. "x" and "y".  The latter can usually be assumed to be map coordinates.
  536.  
  537. Note that map.xsize and map.ysize define the dimension of the map in
  538. _native_ coordinates.
  539.  
  540. Of course, if a future topology does not fit these rules for coordinate
  541. systems, they will have to be refined.
  542.  
  543. =========================================================================
  544. Native coordinates on an isometric map
  545. =========================================================================
  546.  
  547. An isometric map is defined by the operation that converts between map
  548. (user) coordinates and native (internal) ones.  In native coordinates, an
  549. isometric map behaves exactly the same way as a standard one.  (See
  550. "native coordinates", above.
  551.  
  552. Converting from map to native coordinates involves a pi/2 rotation (which
  553. scales in each dimension by sqrt(2)) followed by a compression in the X
  554. direction by a factor of 2.  Then a translation is required since the
  555. "normal set" of native coordinates is defined as
  556.   {(x, y) | x: [0..map.xsize) and y: [0..map.ysize)}
  557. while the normal set of map coordinates must satisfy x >= 0 and y >= 0.
  558.  
  559. Converting from native to map coordinates (a less cumbersome operation) is
  560. the opposite.
  561.                                         EJ
  562.            ABCDE     A B C D E         DIO
  563.   (native) FGHIJ <=>  F G H I J <=>   CHN  (map)
  564.            KLMNO     K L M N O       BGM
  565.                                     AFL
  566.                                      K
  567.  
  568. Note that
  569.  
  570.   native_to_map_pos(0, 0) == (0, map.xsize-1)
  571.   native_to_map_pos(map.xsize-1, 0) == (map.xsize-1, 0)
  572.   native_to_map_pos(x, y+2) = native_to_map_pos(x,y) + (1,1)
  573.   native_to_map_pos(x+1, y) = native_to_map_pos(x,y) + (1,-1)
  574.  
  575. The math then works out to
  576.  
  577.   map_x = ceiling(nat_y / 2) + nat_x
  578.   map_y = floor(nat_y / 2) - nat_x + map.xsize - 1
  579.  
  580.   nat_y = map_x + map_y - map.xsize
  581.   nat_x = floor(map_x - map_y + map.xsize / 2)
  582.  
  583. which leads to the macros native_to_map_pos, map_to_native_pos,
  584. map_pos_to_native_x, and map_pos_to_native_y that are defined in map.h.
  585.  
  586. =========================================================================
  587. Unknown tiles and Fog of War
  588. =========================================================================
  589.  
  590. In the tile struct there is a field
  591.  
  592. struct tile {
  593.   ...
  594.   unsigned int known;
  595.   ...
  596. };
  597.  
  598. On the server the known fields is considered to be a bitvector, one
  599. bit for each player, 0==tile unknown, 1==tile known.
  600. On the client this field contains one of the following 3 values:
  601.  
  602. enum known_type {
  603.  TILE_UNKNOWN, TILE_KNOWN_FOGGED, TILE_KNOWN
  604. };
  605.  
  606. The values TILE_UNKNOWN, TILE_KNOWN are straightforward. TILE_FOGGED
  607. is a tile of which the user knows the terrain (inclusive cities, roads,
  608. etc...).
  609.  
  610. TILE_UNKNOWN tiles are (or should be) never sent to the client.  In the past
  611. UNKNOWN tiles that were adjacent to FOGGED or KNOWN ones were sent to make
  612. the drawing process easier, but this has now been removed.  This means
  613. exploring new land may sometimes change the appearance of existing land (but
  614. this is not fundamentally different from what might happen when you
  615. transform land).  Sending the extra info, however, not only confused the
  616. goto code but allowed cheating.
  617.  
  618. Fog of war is the fact that even when you have seen a tile once you are
  619. not sent updates unless it is inside the sight range of one of your units
  620. or cities.
  621. We keep track of fog of war by counting the number of units and cities
  622. [and nifty future things like radar outposts] of each client that can
  623. see the tile. This requires a number per player, per tile, so each tile
  624. has a short[]. Every time a unit/city/miscellaneous can observe a tile
  625. 1 is added to its player's number at the tile, and when it can't observe
  626. any more (killed/moved/pillaged) 1 is subtracted. In addition to the
  627. initialization/loading of a game this array is manipulated with the
  628. void unfog_area(struct player *pplayer, int x, int y, int len)
  629. and
  630. void fog_area(struct player *pplayer, int x, int y, int len)
  631. functions. "int len" is the radius of the area that should be
  632. fogged/unfogged, i.e. a len of 1 is a normal unit. In addition to keeping
  633. track of fog of war, these functions also make sure to reveal TILE_UNKNOWN
  634. tiles you get near, and send info about TILE_UNKNOWN tiles near that the
  635. client needs for drawing. They then send the tiles to
  636. void send_tile_info(struct player *dest, int x, int y)
  637. which then sets the correct known_type and sends the tile to the client.
  638.  
  639. If you want to just show the terrain and cities of the square the
  640. function show_area does this. The tiles remain fogged.
  641. If you play without fog of war all the values of the seen arrays are
  642. initialized to 1. So you are using the exact same code, you just never
  643. get down to 0. As changes in the "fogginess" of the tiles are only sent
  644. to the client when the value shifts between zero and non-zero, no
  645. redundant packages are sent. You can even switch fog of war on/off
  646. in game just by adding/subtracting 1 to all the tiles.
  647.  
  648. We only send city and terrain updates to the players who can see the
  649. tile. So a city (or improvement) can exist in a square that is known and
  650. fogged and not be shown on the map. Likewise, you can see a city in a
  651. fogged square even if the city doesn't exist (it will be removed when
  652. you see the tile again). This is done by 1) only sending info to players
  653. who can see a tile 2) keeping track of what info has been sent so the
  654. game can be saved. For the purpose of 2) each player has a map on the
  655. server (consisting of player_tile's and dumb_city's) where the relevant
  656. information is kept.
  657.  
  658. The case where a player p1 gives map info to another player p2: This
  659. requires some extra info. Imagine a tile that neither player sees, but
  660. which p1 have the most recent info on. In that case the age of the players'
  661. info should be compared which is why the player tile has a last_updated
  662. field.
  663. This field is not kept up to date as long as the player can see the tile
  664. and it is unfogged, but when the tile gets fogged the date is updated.
  665.  
  666. [An alternative solution would be to give each tile a list
  667. of the units and cities that observe it. IMO this would not be any
  668. easier than just counting, and would have no benefits. The current
  669. solution also gives the possibility to reveal squares as you like,
  670. say near a radar tower tile special. Very flexible.]
  671.  
  672. [The barbarians and the ai take their map info directly from the server,
  673. so they can currently ignore fog of war, and they do so. I really think
  674. that the ideal AI wouldn't be cheating like this.]
  675.  
  676. There is now a shared vision feature, meaning that if p1 gives shared
  677. vision to p2, every time a function like show_area, fog_area, unfog_area
  678. or give_tile_info_from_player_to_player is called on p1 p2 also gets the
  679. info. Note that if p2 gives shared info to p3, p3 also gets the info.
  680. This is controlled by p1's really_gives_vision bitvector, where the
  681. dependencies will be kept.
  682.  
  683. If there is anything I have explained inadequately in this section you
  684. can ask me on <thue@diku.dk>.
  685. -Thue
  686.  
  687. =========================================================================
  688. National borders
  689. =========================================================================
  690. For the display of national borders (similar to those used in Sid Meier's
  691. Alpha Centauri) each map tile also has an "owner" field, to identify
  692. which nation lays claim to it. If game.borders is non-zero, each city
  693. claims a circle of tiles game.borders in radius (in the case of neighbouring
  694. enemy cities, tiles are divided equally, with the older city winning any
  695. ties). Cities claim all immediately adjacent tiles, plus any other tiles
  696. within the border radius on the same continent. Land cities also claim ocean
  697. tiles if they are surrounded by 5 land tiles on the same continent (this is
  698. a crude detection of inland seas or lakes, which should be improved upon).
  699.  
  700. Tile ownership is decided only by the server, and sent to the clients, which
  701. draw border lines between tiles of differing ownership. Owner information is
  702. sent for all tiles that are known by a client, whether or not they are fogged.
  703. A patch to convert this to "semi-fogged" behaviour, whereby clients receive
  704. limited information about non-neighbouring and unseen enemies, is available
  705. at http://freecivac.sf.net/.
  706.  
  707. =========================================================================
  708. Client GUI- Athena 
  709. =========================================================================
  710. One client GUI is written using athena-widgets. A few comments on this 
  711. could prove useful for anyone wishing to write new dialogs or improve
  712. on the current ones.
  713.  
  714. Widgets:
  715. --------
  716. When you create new widgets for a dialog, like:
  717.  
  718.   players_form = XtVaCreateManagedWidget("playersform", 
  719.                        formWidgetClass, 
  720.                        players_dialog_shell, NULL);
  721.  
  722. then put the widget properties in the app-default file 'Freeciv', instead
  723. of hardcoding them. For the widget created above, the following entries
  724. in the app-default file applies:
  725.  
  726. *playersform.background:          lightblue
  727. *playersform.resizable:           true
  728. *playersform.top:                 chainTop
  729. *playersform.bottom:              chainBottom
  730. *playersform.left:                chainLeft
  731. *playersform.right:               chainRight
  732.  
  733. Pixcomm and Canvas:
  734. -------------------
  735. The Pixcomm is a subclassed Command-widget, which can displays a Pixmap
  736. instead of a string, on top of a button(command). The Pixcomm widget
  737. should be used all places where this kind of high-level functionality
  738. is required. 
  739.  
  740. The Canvas widget is more low-level. One have to write an expose(redraw)
  741. event-handler for each widget. The widget generates events on resize
  742. and mousebuttons.
  743.  
  744. [Reading any Xt documentation, will tell you how powerful widget
  745. subclassing is. So I went trough great troubles subclassing the
  746. command widget. It was not before long I got mails from unhappy Xaw3d
  747. (and derives) users, that the client keeps crashing on them. Turns
  748. out that subclassing from any widgets but Core, chains the new
  749. widgets to libXaw. In hindsight I should just subclassed the Canvas
  750. widget and add more highlevel functionality. -PU]
  751.  
  752. ===========================================================================
  753. Misc - The idea trashcan 
  754. ===========================================================================
  755. [Currently all of the major entities - units, cities, players, contains
  756. an unique id. This id is really only required when a reference to an entity
  757. is to be serialized(saved or distributed over the net). However in the
  758. current code, the id is also used for comparing, looking up and in general
  759. referencing entities. This results in a lot of mess and unnecessary duplicate
  760. functions. Often when programming, one wonders if some function needs
  761. the id or a pointer when referring to an entity. -PU]
  762.  
  763. The paragraph above isn't true anymore for player, units and cities. -RF
  764.  
  765. ===========================================================================
  766.  
  767. Player-related entities in Freeciv - by Reinier Post <reinpost@win.tue.nl>
  768. + by dwp@mso.anu.edu.au
  769.  
  770. Freeciv is confused about the meaning of 'player'.  As a participant in
  771. Freeciv games, you'll notice that the participants are called 'players'.
  772. At the same time, players seem to be identified with civilizations.
  773. On the other hand, civilizations seem to be identified by 'nation':
  774. every player chooses a nation at the start of the game.
  775.  
  776. In the data structures, a 'player' identifies a civilization, not a user.
  777.  
  778. ----
  779.   THE PLAN:
  780.  
  781. There are four player-related entities:
  782.  
  783. + player
  784.   A civilization, with a capital, cities, units, an income, etc.
  785.  
  786. + nation
  787.   A type of civilization (except that very little actually depends on
  788.   nation, and the oddity exists that each player must be of different 
  789.   nation)
  790.  
  791. + user
  792.   Identifies 'someone out there', usually a human user running a civclient
  793.   (this is the plan; it is not yet implemented).
  794.  
  795. + connection
  796.   Records a client connection; like a user, but disappears when the user 
  797.   disconnects, whereas for real users we may want to remember them between 
  798.   connections.  See Connections section below.
  799.  
  800. Where do these entities exist?
  801.  
  802. Nations aren't actually used for annything that matters; for them,
  803. so the question isn't very interesting.
  804.  
  805. Players (more aptly named, 'civilizations'), exist in games.  Except in
  806. the context of a running game, the entity makes no sense.  Players and
  807. their status are part of savefiles.  A game can be saved and restarted
  808. on a different server; the players will be the same.  A new game will
  809. have new players.  Players exist in common/ (even games do) but a
  810. client only has one instantiated player.
  811.  
  812. The reason to introduce users is client-side server commands.  It must
  813. be possible to assign different levels of access to commands to different
  814. users.  Attaching it to players is not good enough: the information must
  815. survive the addition and removal of other players, the start or restart
  816. of a game, reconnections by the same user even from different computers,
  817. or transferral of the game to a different server.  However, a user
  818. may have different levels of access in different games.
  819.  
  820. While they last, connections are sufficient identification for users.
  821. The user entity will allow users to be identified when they reconnect.
  822.  
  823. Ideally, users would be identified with unique global ids, handed out
  824. by a 'registry service' similar to the metaserver, but this would be
  825. too cumbersome in practice.  So the plan is to make users persist in
  826. a server session (even whan a game is started, or restarted when that
  827. option is added) and make them persist across games (when a saved
  828. game is loaded in a different server session).
  829.  
  830. Users will be created when they first connect to a server, remembered by
  831. the running server and in savefiles.  Upon connecting, the client will
  832. be sent a unique session id, generated when the server started, plus a
  833. fresh user id; it will store them in a ~/.civcookie file, and send it
  834. back when trying to reconnect.  This will allow the identity of users
  835. to be protected.  'Protected' players will only allow the same user to
  836. reconnect; 'unprotected' ones allow anyone to connect; server commands
  837. and probably client options will be available to control this.
  838.  
  839. Player names will be assigned to users, not players.
  840.  
  841. The server maintains a default access level, which is used for new
  842. users and unprotected ones.
  843.  
  844. ----
  845.   THE PRESENT IMPLEMENTATION:
  846.  
  847. Currently access levels are stored in the connection struct.  This allows 
  848. access levels to be assigned to each individual connected player, which 
  849. would not be the case if they were directly assigned to the player struct 
  850. (due to the fact that the players array changes when players are added or 
  851. removed).
  852.  
  853. But that's it.
  854.  
  855. Players are still created before the game is started, and player names
  856. still belong to players.  Access levels exist in client and server, 
  857. but only the server uses them.  User ids are not yet implemented;
  858. Server ids do not exist at all.
  859.  
  860. Commands to protect/unprotect users do not yet exist; they would serve 
  861. no useful purpose.
  862.  
  863. Access levels can set for individual users, including AI players with 
  864. a connected observer, but only while someone is connected; they will not 
  865. be remembered when the user disconnects.
  866.  
  867. ===========================================================================
  868. Connections
  869. ===========================================================================
  870.  
  871. The code is currently transitioning from 1 or 0 connections per player
  872. only, to allowing multiple connections for each player (recall
  873. 'player' means a civilization, see above), where each connection may
  874. be either an "observer" or "controller".
  875.  
  876. This discussion is mostly about connection in the server.  The client
  877. only has one real connection: 'aconnection' - its connection to the
  878. server, though it does use some other connection structs (currently
  879. pplayer->conn) to store information about other connected clients
  880. (eg, capability strings).
  881.  
  882. In the old paradigm, server code would usually send information to a
  883. single player, or to all connected players (usually represented by
  884. destination being a NULL player pointer).  With multiple connections
  885. per player things become more complicated.  Sometimes information
  886. should be sent to a single connection, or to all connections for a
  887. single player, or to all (established) connections, etc.  To handle
  888. this, "destinations" should now be specified as a pointer to a struct
  889. conn_list (list of connections).  For convenience the following
  890. commonly applicable lists are maintained:
  891.    game.all_connections   -  all connections
  892.    game.est_connections   -  established connections
  893.    game.game_connections  -  connections observing and/or involved in game
  894.    pplayer->connections   -  connections for specific player
  895.    pconn->self            -  single connection (as list)
  896.  
  897. Connections can be classified as follows:  (first match applies)
  898.  
  899. 1. (pconn->used == 0) Not a real connection (closed/unused), should
  900.    not exist in any list of have any information sent to it.
  901.  
  902. (All following cases exist in game.all_connections.)
  903.  
  904. 2. (pconn->established == 0) TCP connection has been made, but initial
  905.    Freeciv packets have not yet been negotiated (join_game etc).
  906.    Exists in game.all_connections only.  Should not be sent any
  907.    information except directly as result of join_game etc packets, 
  908.    or server shutdown, or connection close, etc.
  909.  
  910. (All following cases exist in game.est_connections.)
  911.  
  912. 3. (pconn->player == NULL) Connection has been established, but is not
  913.    yet associated with a player.  Currently this is not possible, but
  914.    the plan is to allow this in future, so clients can connect and
  915.    then see list of players to choose from, or just control the server
  916.    or observe etc. Two subcases:
  917.  
  918.    3a. (pconn->observer == 0) Not observing the game.  Should receive
  919.        information about other clients, game status etc, but not map,
  920.        units, cities, etc.
  921.  
  922. (All following cases exist in game.game_connections.)
  923.  
  924.    3b. (pconn->observer == 1) Observing the game.  Exists in
  925.        game.game_connections.  Should receive game information about
  926.        map, units, cities, etc.
  927.  
  928. 4. (pconn->player != NULL) Connected to specific player, either as
  929.    "observer" or "controller".  (But observers not yet implemented.)
  930.    Exists in game.game_connections, and in pconn->player->connections.
  931.  
  932.  
  933. ===========================================================================
  934. Starting a Server from Within a Client
  935. ===========================================================================
  936.  
  937. After many years of complaints regarding the ease (or lack thereof) of
  938. starting a game of Freeciv [start a server, input settings on a command line,
  939. start a client, and connect, etc], a method has been developed for starting
  940. and playing a complete game using only the client. This has been called the
  941. "extended" or "new connect dialog". This is perhaps a misnomer, but there it 
  942. is. This win32 client has had this feature in some form for some time. 
  943.  
  944. It works by forking a server from within the client and then controlling that
  945. server via chatline messages. The guts of the machinery to do this can be
  946. found in these files:
  947.  
  948. client/connectdlg_common.[ch]
  949. client/gui-*/connectdlg.[ch]
  950. common/packets.def
  951. server/gamehand.[ch]
  952. server/stdinhand.[ch]
  953.  
  954. When a player starts a client, he is presents with several options: start
  955. a new game, continue a saved game and connect to a networked game. For the 
  956. latter option, connect_to_server() is called and login proceeeds as normal.
  957. The the first two options, connectdlg_common.c:client_start_server() is 
  958. called. Here, a server is spawned, standard input and outputs to that process
  959. are closed, and then connect_to_server() is called so the client connects to 
  960. that server.
  961.  
  962. At this point everything regarding the client/server connection is as usual;
  963. however, for the client to control the server, it must have access level HACK,
  964. so it must verify to the server that it is local (on the same machine or at
  965. least has access to the same disk as the server). The procedure is:
  966.  
  967. 1. the server creates a file using gamehand.c:create_challenge_filename() and
  968.    puts the name of this file in packet_server_join_reply that it sends back
  969.    to the client. The name of the file is semi-random.
  970. 2. The client, upon receiving confirmation that it can join the server,
  971.    creates a file using the name the server selected and places a random number
  972.    inside that file.
  973. 3. The client sends a packet [packet_single_want_hack_req] with that random 
  974.    number back to the server.
  975. 4. The server upon receiving the packet [packet_single_want_hack_req], opens
  976.    the file and compares the two numbers. If the file exists and the numbers
  977.    are equal the server grants that client HACK access level and sends a
  978.    packet [packet_single_want_hack_reply] informing the client of its elevated
  979.    access level.
  980.  
  981. Only one other packet is used --- packet_single_playerlist_req --- which asks
  982. the server to send a player list when a savegame is loaded. This list is used
  983. for player selection.
  984.  
  985.  
  986. ===========================================================================
  987. Macros and inline functions
  988. ===========================================================================
  989.  
  990. For a long time Freeciv had no inline functions, only macros.  With the
  991. use of other C99 features and some new requirements by the code, this has
  992. changed.  Now both macros and inline functions are used.
  993.  
  994. This causes problems because one coder may prefer to use a macro while
  995. another prefers an inline function.  Of course there was always some
  996. discretion to the author about whether to use a function or a macro; all
  997. we've done is add even more choices.
  998.  
  999. Therefore the following guidelines should be followed:
  1000.  
  1001. - Functions should only be put into header files when doing so makes a
  1002.   measurable impact on speed.  Functions should not be turned into macros or
  1003.   inlined unless there is a reason to do so.
  1004.  
  1005. - Macros that take function-like parameters should evaluate each parameter
  1006.   exactly once.  Any macro that doesn't follow this convention should be
  1007.   named in all upper-case letters as a MACRO.
  1008.  
  1009. - Iterator macros should respect "break".
  1010.  
  1011. - In header files macros are preferred to inline functions, but inline
  1012.   functions are better than MACROS.
  1013.  
  1014. - Functions or macros that are currently in one form do not have to be
  1015.   changed to the other form.
  1016.  
  1017. Note that many existing macros do not follow these guidelines.
  1018.  
  1019.  
  1020. ===========================================================================
  1021. Style Guide
  1022. ===========================================================================
  1023.  
  1024. See CodingStyle in this directory.
  1025.  
  1026. - If you send patches, use "diff -u" (or "diff -r -u").  For further
  1027.   information, see <http://www.freeciv.org/index.php/How_to_Contribute>.
  1028.   Also, name patch files descriptively (e.g. "fix-foo-bug-0.diff" is good,
  1029.   but "freeciv.diff" is not).
  1030.  
  1031. - When doing a "diff" for a patch, be sure to exclude unnecessary files
  1032.   by using the "-X" argument to "diff".  E.g.:
  1033.  
  1034.     % diff -ruN -Xdiff_ignore freeciv_cvs freeciv >/tmp/fix-foo-bug-0.diff
  1035.  
  1036.   A suggested "diff_ignore" file is included in the Freeciv distribution.
  1037.  
  1038. ===========================================================================
  1039. Internationalization (I18N)
  1040. ===========================================================================
  1041.  
  1042. Messages and text in general which are shown in the GUI should be
  1043. translated by using the "_()" macro. In addition freelog(LOG_NORMAL,
  1044. ...) messages should be translated. The other loglevels (LOG_FATAL,
  1045. LOG_ERROR,LOG_VERBOSE, LOG_DEBUG) should NOT be translated.
  1046.  
  1047. ===========================================================================
  1048.