File: maphand.c

package info (click to toggle)
freeciv 2.1.5-2
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 95,924 kB
  • ctags: 20,829
  • sloc: ansic: 231,256; sh: 4,872; makefile: 2,867; python: 1,259; yacc: 318
file content (1815 lines) | stat: -rw-r--r-- 61,981 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
/********************************************************************** 
 Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
***********************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <assert.h>

#include "fcintl.h"
#include "log.h"
#include "mem.h"
#include "rand.h"
#include "support.h"

#include "events.h"
#include "game.h"
#include "map.h"
#include "movement.h"
#include "nation.h"
#include "packets.h"
#include "unit.h"
#include "unitlist.h"

#include "citytools.h"
#include "cityturn.h"
#include "maphand.h"
#include "plrhand.h"           /* notify_player */
#include "sernet.h"
#include "srv_main.h"
#include "unithand.h"
#include "unittools.h"

#define MAXIMUM_CLAIMED_OCEAN_SIZE (20)

/* These arrays are indexed by continent number (or negative of the
 * ocean number) so the 0th element is unused and the array is 1 element
 * larger than you'd expect.
 *
 * The lake surrounders array tells how many land continents surround each
 * ocean (or -1 if the ocean touches more than one continent).
 *
 * The _sizes arrays give the sizes (in tiles) of each continent and
 * ocean.
 */
static Continent_id *lake_surrounders;
static int *continent_sizes, *ocean_sizes;

/**************************************************************************
  Number this tile and nearby tiles (recursively) with the specified
  continent number nr, using a flood-fill algorithm.

  is_land tells us whether we are assigning continent numbers or ocean 
  numbers.

  if skip_unsafe is specified then "unsafe" terrains are skipped.  This
  is useful for mapgen algorithms.
**************************************************************************/
static void assign_continent_flood(struct tile *ptile, bool is_land,
				   int nr, bool skip_unsafe)
{
  if (tile_get_continent(ptile) != 0) {
    return;
  }

  if (ptile->terrain == T_UNKNOWN) {
    return;
  }

  if (skip_unsafe && terrain_has_flag(tile_get_terrain(ptile), TER_UNSAFE)) {
    /* FIXME: This should check a specialized flag, not the TER_UNSAFE
     * flag which may not even be present. */
    return;
  }

  if (!XOR(is_land, is_ocean(tile_get_terrain(ptile)))) {
    return;
  }

  tile_set_continent(ptile, nr);
  
  /* count the tile */
  if (nr < 0) {
    ocean_sizes[-nr]++;
  } else {
    continent_sizes[nr]++;
  }

  adjc_iterate(ptile, tile1) {
    assign_continent_flood(tile1, is_land, nr, skip_unsafe);
  } adjc_iterate_end;
}

/**************************************************************************
  Calculate lake_surrounders[] array
**************************************************************************/
static void recalculate_lake_surrounders(void)
{
  const size_t size = (map.num_oceans + 1) * sizeof(*lake_surrounders);

  lake_surrounders = fc_realloc(lake_surrounders, size);
  memset(lake_surrounders, 0, size);
  
  whole_map_iterate(ptile) {
    Continent_id cont = tile_get_continent(ptile);
    if (ptile->terrain != T_UNKNOWN && !is_ocean(tile_get_terrain(ptile))) {
      adjc_iterate(ptile, tile2) {
        Continent_id cont2 = tile_get_continent(tile2);
	if (is_ocean(tile_get_terrain(tile2))) {
	  if (lake_surrounders[-cont2] == 0) {
	    lake_surrounders[-cont2] = cont;
	  } else if (lake_surrounders[-cont2] != cont) {
	    lake_surrounders[-cont2] = -1;
	  }
	}
      } adjc_iterate_end;
    }
  } whole_map_iterate_end;
}

/**************************************************************************
  Assigns continent and ocean numbers to all tiles, and set
  map.num_continents and map.num_oceans.  Recalculates continent and
  ocean sizes, and lake_surrounders[] arrays.

  Continents have numbers 1 to map.num_continents _inclusive_.
  Oceans have (negative) numbers -1 to -map.num_oceans _inclusive_.

  If skip_unsafe is specified then unsafe terrains are not used to
  connect continents.  This is useful for generator code so that polar
  regions don't connect landmasses.
**************************************************************************/
void assign_continent_numbers(bool skip_unsafe)
{
  
  /* Initialize */
  map.num_continents = 0;
  map.num_oceans = 0;

  whole_map_iterate(ptile) {
    tile_set_continent(ptile, 0);
  } whole_map_iterate_end;

  /* Assign new numbers */
  whole_map_iterate(ptile) {
    const struct terrain *pterrain = tile_get_terrain(ptile);

    if (tile_get_continent(ptile) != 0) {
      /* Already assigned. */
      continue;
    }

    if (ptile->terrain == T_UNKNOWN) {
      continue; /* Can't assign this. */
    }

    if (!skip_unsafe || !terrain_has_flag(pterrain, TER_UNSAFE)) {
      if (!is_ocean(pterrain)) {
	map.num_continents++;
	continent_sizes
	  = fc_realloc(continent_sizes,
		       (map.num_continents + 1) * sizeof(*continent_sizes));
	continent_sizes[map.num_continents] = 0;
	assign_continent_flood(ptile, TRUE, map.num_continents, skip_unsafe);
      } else {
	map.num_oceans++;
	ocean_sizes
	  = fc_realloc(ocean_sizes,
		       (map.num_oceans + 1) * sizeof(*ocean_sizes));
	ocean_sizes[map.num_oceans] = 0;
	assign_continent_flood(ptile, FALSE, -map.num_oceans, skip_unsafe);
      }
    }
  } whole_map_iterate_end;

  recalculate_lake_surrounders();

  freelog(LOG_VERBOSE, "Map has %d continents and %d oceans", 
	  map.num_continents, map.num_oceans);
}

static void player_tile_init(struct tile *ptile, struct player *pplayer);
static void give_tile_info_from_player_to_player(struct player *pfrom,
						 struct player *pdest,
						 struct tile *ptile);
static void shared_vision_change_seen(struct tile *ptile,
				      struct player *pplayer, int change,
				      enum vision_layer vlayer);
static int map_get_seen(const struct tile *ptile,
			const struct player *pplayer,
			enum vision_layer vlayer);
static void map_change_own_seen(struct tile *ptile, struct player *pplayer,
				int change, enum vision_layer vlayer);

/**************************************************************************
Used only in global_warming() and nuclear_winter() below.
**************************************************************************/
static bool is_terrain_ecologically_wet(struct tile *ptile)
{
  return (tile_has_special(ptile, S_RIVER)
	  || is_ocean_near_tile(ptile)
	  || is_special_near_tile(ptile, S_RIVER));
}

/**************************************************************************
...
**************************************************************************/
void global_warming(int effect)
{
  int k;

  freelog(LOG_VERBOSE, "Global warming: %d", game.info.heating);

  k = map_num_tiles();
  while(effect > 0 && (k--) > 0) {
    struct terrain *old, *new;
    struct tile *ptile;

    ptile = rand_map_pos();
    old = tile_get_terrain(ptile);
    if (is_terrain_ecologically_wet(ptile)) {
      new = old->warmer_wetter_result;
    } else {
      new = old->warmer_drier_result;
    }
    if (new != T_NONE && old != new) {
      effect--;
      tile_change_terrain(ptile, new);
      check_terrain_change(ptile, old);
      update_tile_knowledge(ptile);
      unit_list_iterate(ptile->units, punit) {
	if (!can_unit_continue_current_activity(punit)) {
	  handle_unit_activity_request(punit, ACTIVITY_IDLE);
	}
      } unit_list_iterate_end;
    } else if (old == new) {
      /* This counts toward warming although nothing is changed. */
      effect--;
    }
  }

  notify_player(NULL, NULL, E_GLOBAL_ECO,
		   _("Global warming has occurred!"));
  notify_player(NULL, NULL, E_GLOBAL_ECO,
		_("Coastlines have been flooded and vast "
		  "ranges of grassland have become deserts."));
}

/**************************************************************************
...
**************************************************************************/
void nuclear_winter(int effect)
{
  int k;

  freelog(LOG_VERBOSE, "Nuclear winter: %d", game.info.cooling);

  k = map_num_tiles();
  while(effect > 0 && (k--) > 0) {
    struct terrain *old, *new;
    struct tile *ptile;

    ptile = rand_map_pos();
    old = tile_get_terrain(ptile);
    if (is_terrain_ecologically_wet(ptile)) {
      new = old->cooler_wetter_result;
    } else {
      new = old->cooler_drier_result;
    }
    if (new != T_NONE && old != new) {
      effect--;
      tile_change_terrain(ptile, new);
      check_terrain_change(ptile, old);
      update_tile_knowledge(ptile);
      unit_list_iterate(ptile->units, punit) {
	if (!can_unit_continue_current_activity(punit)) {
	  handle_unit_activity_request(punit, ACTIVITY_IDLE);
	}
      } unit_list_iterate_end;
    } else if (old == new) {
      /* This counts toward winter although nothing is changed. */
      effect--;
    }
  }

  notify_player(NULL, NULL, E_GLOBAL_ECO,
		   _("Nuclear winter has occurred!"));
  notify_player(NULL, NULL, E_GLOBAL_ECO,
		_("Wetlands have dried up and vast "
		  "ranges of grassland have become tundra."));
}

/***************************************************************
To be called when a player gains the Railroad tech for the first
time.  Sends a message, and then upgrade all city squares to
railroads.  "discovery" just affects the message: set to
   1 if the tech is a "discovery",
   0 if otherwise acquired (conquer/trade/GLib).        --dwp
***************************************************************/
void upgrade_city_rails(struct player *pplayer, bool discovery)
{
  if (!(terrain_control.may_road)) {
    return;
  }

  conn_list_do_buffer(pplayer->connections);

  if (discovery) {
    notify_player(pplayer, NULL, E_TECH_GAIN,
		  _("New hope sweeps like fire through the country as "
		    "the discovery of railroad is announced.\n"
		    "      Workers spontaneously gather and upgrade all "
		    "cities with railroads."));
  } else {
    notify_player(pplayer, NULL, E_TECH_GAIN,
		  _("The people are pleased to hear that your "
		    "scientists finally know about railroads.\n"
		    "      Workers spontaneously gather and upgrade all "
		    "cities with railroads."));
  }
  
  city_list_iterate(pplayer->cities, pcity) {
    tile_set_special(pcity->tile, S_RAILROAD);
    update_tile_knowledge(pcity->tile);
  }
  city_list_iterate_end;

  conn_list_do_unbuffer(pplayer->connections);
}

/**************************************************************************
Return TRUE iff the player me really gives shared vision to player them.
**************************************************************************/
static bool really_gives_vision(struct player *me, struct player *them)
{
  return TEST_BIT(me->really_gives_vision, player_index(them));
}

/**************************************************************************
...
**************************************************************************/
static void buffer_shared_vision(struct player *pplayer)
{
  players_iterate(pplayer2) {
    if (really_gives_vision(pplayer, pplayer2))
      conn_list_do_buffer(pplayer2->connections);
  } players_iterate_end;
  conn_list_do_buffer(pplayer->connections);
}

/**************************************************************************
...
**************************************************************************/
static void unbuffer_shared_vision(struct player *pplayer)
{
  players_iterate(pplayer2) {
    if (really_gives_vision(pplayer, pplayer2))
      conn_list_do_unbuffer(pplayer2->connections);
  } players_iterate_end;
  conn_list_do_unbuffer(pplayer->connections);
}

/**************************************************************************
...
**************************************************************************/
void give_map_from_player_to_player(struct player *pfrom, struct player *pdest)
{
  buffer_shared_vision(pdest);
  whole_map_iterate(ptile) {
    give_tile_info_from_player_to_player(pfrom, pdest, ptile);
  } whole_map_iterate_end;
  unbuffer_shared_vision(pdest);
}

/**************************************************************************
...
**************************************************************************/
void give_seamap_from_player_to_player(struct player *pfrom, struct player *pdest)
{
  buffer_shared_vision(pdest);
  whole_map_iterate(ptile) {
    if (is_ocean(tile_get_terrain(ptile))) {
      give_tile_info_from_player_to_player(pfrom, pdest, ptile);
    }
  } whole_map_iterate_end;
  unbuffer_shared_vision(pdest);
}

/**************************************************************************
...
**************************************************************************/
void give_citymap_from_player_to_player(struct city *pcity,
					struct player *pfrom, struct player *pdest)
{
  buffer_shared_vision(pdest);
  map_city_radius_iterate(pcity->tile, ptile) {
    give_tile_info_from_player_to_player(pfrom, pdest, ptile);
  } map_city_radius_iterate_end;
  unbuffer_shared_vision(pdest);
}

/**************************************************************************
  Send all tiles known to specified clients.
  If dest is NULL means game.est_connections.
  
  Note for multiple connections this may change "sent" multiple times
  for single player.  This is ok, because "sent" data is just optimised
  calculations, so it will be correct before this, for each connection
  during this, and at end.
**************************************************************************/
void send_all_known_tiles(struct conn_list *dest)
{
  int tiles_sent;

  if (!dest) {
    dest = game.est_connections;
  }

  /* send whole map piece by piece to each player to balance the load
     of the send buffers better */
  tiles_sent = 0;
  conn_list_do_buffer(dest);

  whole_map_iterate(ptile) {
    tiles_sent++;
    if ((tiles_sent % map.xsize) == 0) {
      conn_list_do_unbuffer(dest);
      flush_packets();
      conn_list_do_buffer(dest);
    }

    send_tile_info(dest, ptile);
  } whole_map_iterate_end;

  conn_list_do_unbuffer(dest);
  flush_packets();
}

/**************************************************************************
  Send tile information to all the clients in dest which know and see
  the tile. If dest is NULL, sends to all clients (game.est_connections)
  which know and see tile.

  Note that this function does not update the playermap.  For that call
  update_tile_knowledge().
**************************************************************************/
void send_tile_info(struct conn_list *dest, struct tile *ptile)
{
  struct packet_tile_info info;

  if (!dest) {
    dest = game.est_connections;
  }

  info.x = ptile->x;
  info.y = ptile->y;
  info.owner = tile_owner(ptile) ? player_number(tile_owner(ptile)) : MAP_TILE_OWNER_NULL;
  if (ptile->spec_sprite) {
    sz_strlcpy(info.spec_sprite, ptile->spec_sprite);
  } else {
    info.spec_sprite[0] = '\0';
  }

  conn_list_iterate(dest, pconn) {
    struct player *pplayer = pconn->player;

    if (!pplayer && !pconn->observer) {
      continue;
    }
    if (!pplayer || map_is_known_and_seen(ptile, pplayer, V_MAIN)) {
      info.known = TILE_KNOWN;
      info.type = ptile->terrain ? ptile->terrain->index : -1;

      tile_special_type_iterate(spe) {
	info.special[spe] = BV_ISSET(ptile->special, spe);
      } tile_special_type_iterate_end;

      info.resource = ptile->resource ? ptile->resource->index : -1;
      info.continent = ptile->continent;
      send_packet_tile_info(pconn, &info);
    } else if (pplayer && map_is_known(ptile, pplayer)
	       && map_get_seen(ptile, pplayer, V_MAIN) == 0) {
      struct player_tile *plrtile = map_get_player_tile(ptile, pplayer);

      info.known = TILE_KNOWN_FOGGED;
      info.type = plrtile->terrain ? plrtile->terrain->index : -1;

      tile_special_type_iterate(spe) {
	info.special[spe] = BV_ISSET(plrtile->special, spe);
      } tile_special_type_iterate_end;

      info.resource = plrtile->resource ? plrtile->resource->index : -1;
      info.continent = ptile->continent;
      send_packet_tile_info(pconn, &info);
    }
  }
  conn_list_iterate_end;
}

/****************************************************************************
  Assumption: Each unit type is visible on only one layer.
****************************************************************************/
static bool unit_is_visible_on_layer(const struct unit *punit,
				     enum vision_layer vlayer)
{
  return XOR(vlayer == V_MAIN, is_hiding_unit(punit));
}

/****************************************************************************
  This is a backend function that marks a tile as unfogged.  Call this when
  map_unfog_tile adds the first point of visibility to the tile, or when
  shared vision changes cause a tile to become unfogged.
****************************************************************************/
static void really_unfog_tile(struct player *pplayer, struct tile *ptile,
			      enum vision_layer vlayer)
{
  struct city *pcity;
  bool old_known = map_is_known(ptile, pplayer);

  freelog(LOG_DEBUG, "really unfogging %d,%d\n", TILE_XY(ptile));

  map_set_known(ptile, pplayer);

  if (vlayer == V_MAIN) {
    /* send info about the tile itself 
     * It has to be sent first because the client needs correct
     * continent number before it can handle following packets
     */
    update_player_tile_knowledge(pplayer, ptile);
    send_tile_info(pplayer->connections, ptile);
    /* NOTE: because the V_INVIS case doesn't fall into this if statement,
     * changes to V_INVIS fogging won't send a new info packet to the client
     * and the client's tile_seen[V_INVIS] bitfield may end up being out
     * of date. */
  }

  /* discover units */
  unit_list_iterate(ptile->units, punit) {
    if (unit_is_visible_on_layer(punit, vlayer)) {
      send_unit_info(pplayer, punit);
    }
  } unit_list_iterate_end;

  if (vlayer == V_MAIN) {
    /* discover cities */ 
    reality_check_city(pplayer, ptile);
    if ((pcity=tile_get_city(ptile)))
      send_city_info(pplayer, pcity);

    /* If the tile was not known before we need to refresh the cities that
       can use the tile. */
    if (!old_known) {
      map_city_radius_iterate(ptile, tile1) {
	pcity = tile_get_city(tile1);
	if (pcity && city_owner(pcity) == pplayer) {
	  update_city_tile_status_map(pcity, ptile);
	}
      } map_city_radius_iterate_end;
      sync_cities();
    }
  }
}

/****************************************************************************
  Add an extra point of visibility to the given tile.  pplayer may not be
  NULL.  The caller may wish to buffer_shared_vision if calling this
  function multiple times.
****************************************************************************/
static void map_unfog_tile(struct player *pplayer, struct tile *ptile,
			   bool can_reveal_tiles,
			   enum vision_layer vlayer)
{
  /* Increase seen count. */
  shared_vision_change_seen(ptile, pplayer, +1, vlayer);

  /* And then give the vision.  Did the tile just become visible?
   * Then send info about units and cities and the tile itself. */
  players_iterate(pplayer2) {
    if (pplayer2 == pplayer || really_gives_vision(pplayer, pplayer2)) {
      bool known = map_is_known(ptile, pplayer2);

      if ((!known && can_reveal_tiles)
	  || (known && map_get_seen(ptile, pplayer2, vlayer) == 1)) {
	really_unfog_tile(pplayer2, ptile, vlayer);
      }
    }
  } players_iterate_end;
}

/****************************************************************************
  This is a backend function that marks a tile as fogged.  Call this when
  map_fog_tile removes the last point of visibility from the tile, or when
  shared vision changes cause a tile to become fogged.
****************************************************************************/
static void really_fog_tile(struct player *pplayer, struct tile *ptile,
			    enum vision_layer vlayer)
{
  freelog(LOG_DEBUG, "Fogging %i,%i. Previous fog: %i.",
	  TILE_XY(ptile), map_get_seen(ptile, pplayer, vlayer));
 
  assert(map_get_seen(ptile, pplayer, vlayer) == 0);

  unit_list_iterate(ptile->units, punit)
    if (unit_is_visible_on_layer(punit, vlayer)) {
      unit_goes_out_of_sight(pplayer,punit);
    }
  unit_list_iterate_end;  

  if (vlayer == V_MAIN) {
    update_player_tile_last_seen(pplayer, ptile);
    send_tile_info(pplayer->connections, ptile);
  }
}

/**************************************************************************
  Remove a point of visibility from the given tile.  pplayer may not be
  NULL.  The caller may wish to buffer_shared_vision if calling this
  function multiple times.
**************************************************************************/
static void map_fog_tile(struct player *pplayer, struct tile *ptile,
			 enum vision_layer vlayer)
{
  shared_vision_change_seen(ptile, pplayer, -1, vlayer);

  if (map_is_known(ptile, pplayer)) {
    players_iterate(pplayer2) {
      if (pplayer2 == pplayer || really_gives_vision(pplayer, pplayer2)) {
	if (map_get_seen(ptile, pplayer2, vlayer) == 0) {
	  really_fog_tile(pplayer2, ptile, vlayer);
	}
      }
    } players_iterate_end;
  }
}

/**************************************************************************
  Send basic map information: map size, topology, and is_earth.
**************************************************************************/
void send_map_info(struct conn_list *dest)
{
  struct packet_map_info minfo;

  minfo.xsize=map.xsize;
  minfo.ysize=map.ysize;
  minfo.topology_id = map.topology_id;
 
  lsend_packet_map_info(dest, &minfo);
}

/**************************************************************************
...
**************************************************************************/
static void shared_vision_change_seen(struct tile *ptile,
				      struct player *pplayer, int change,
				      enum vision_layer vlayer)
{
  map_change_seen(ptile, pplayer, change, vlayer);
  map_change_own_seen(ptile, pplayer, change, vlayer);

  players_iterate(pplayer2) {
    if (really_gives_vision(pplayer, pplayer2))
      map_change_seen(ptile, pplayer2, change, vlayer);
  } players_iterate_end;
}

/**************************************************************************
There doesn't have to be a city.
**************************************************************************/
static void map_refog_circle(struct player *pplayer, struct tile *ptile,
			     int old_radius_sq, int new_radius_sq,
			     bool can_reveal_tiles,
			     enum vision_layer vlayer)
{
  if (old_radius_sq != new_radius_sq) {
    int max_radius = MAX(old_radius_sq, new_radius_sq);

    freelog(LOG_DEBUG, "Refogging circle at %d,%d from %d to %d",
	    TILE_XY(ptile), old_radius_sq, new_radius_sq);

    buffer_shared_vision(pplayer);
    circle_dxyr_iterate(ptile, max_radius, tile1, dx, dy, dr) {
      if (dr > old_radius_sq && dr <= new_radius_sq) {
	map_unfog_tile(pplayer, tile1, can_reveal_tiles, vlayer);
      } else if (dr > new_radius_sq && dr <= old_radius_sq) {
	map_fog_tile(pplayer, tile1, vlayer);
      }
    } circle_dxyr_iterate_end;
    unbuffer_shared_vision(pplayer);
  }
}

/****************************************************************************
  Shows the area to the player.  Unless the tile is "seen", it will remain
  fogged and units will be hidden.

  Callers may wish to buffer_shared_vision before calling this function.
****************************************************************************/
void map_show_tile(struct player *src_player, struct tile *ptile)
{
  static int recurse = 0;
  freelog(LOG_DEBUG, "Showing %i,%i to %s",
	  TILE_XY(ptile), player_name(src_player));

  assert(recurse == 0);
  recurse++;

  players_iterate(pplayer) {
    if (pplayer == src_player || really_gives_vision(pplayer, src_player)) {
      struct city *pcity;
      bool old_known = map_is_known(ptile, pplayer);

      if (!map_is_known_and_seen(ptile, pplayer, V_MAIN)) {
	map_set_known(ptile, pplayer);

	/* as the tile may be fogged send_tile_info won't always do this for us */
	update_player_tile_knowledge(pplayer, ptile);
	update_player_tile_last_seen(pplayer, ptile);

	send_tile_info(pplayer->connections, ptile);

	/* remove old cities that exist no more */
	reality_check_city(pplayer, ptile);
	if ((pcity = tile_get_city(ptile))) {
	  /* as the tile may be fogged send_city_info won't do this for us */
	  update_dumb_city(pplayer, pcity);
	  send_city_info(pplayer, pcity);
	}

	vision_layer_iterate(v) {
	  if (map_get_seen(ptile, pplayer, v) != 0) {
	    unit_list_iterate(ptile->units, punit)
	      if (unit_is_visible_on_layer(punit, v)) {
		send_unit_info(pplayer, punit);
	      }
	    unit_list_iterate_end;
	  }
	} vision_layer_iterate_end;

	/* If the tile was not known before we need to refresh the cities that
	   can use the tile. */
	if (!old_known) {
	  map_city_radius_iterate(ptile, tile1) {
	    pcity = tile_get_city(tile1);
	    if (pcity && city_owner(pcity) == pplayer) {
	      update_city_tile_status_map(pcity, ptile);
	    }
	  } map_city_radius_iterate_end;
	  sync_cities();
	}
      }
    }
  } players_iterate_end;

  recurse--;
}

/****************************************************************************
  Shows the area to the player.  Unless the tile is "seen", it will remain
  fogged and units will be hidden.
****************************************************************************/
void map_show_circle(struct player *pplayer, struct tile *ptile, int radius_sq)
{
  buffer_shared_vision(pplayer);

  circle_iterate(ptile, radius_sq, tile1) {
    map_show_tile(pplayer, tile1);
  } circle_iterate_end;

  unbuffer_shared_vision(pplayer);
}

/****************************************************************************
  Shows the area to the player.  Unless the tile is "seen", it will remain
  fogged and units will be hidden.
****************************************************************************/
void map_show_all(struct player *pplayer)
{
  buffer_shared_vision(pplayer);

  whole_map_iterate(ptile) {
    map_show_tile(pplayer, ptile);
  } whole_map_iterate_end;

  unbuffer_shared_vision(pplayer);
}

/****************************************************************************
  Return whether the player knows the tile.  Knowing a tile means you've
  seen it once (as opposed to seeing a tile which means you can see it now).
****************************************************************************/
bool map_is_known(const struct tile *ptile, const struct player *pplayer)
{
  return BV_ISSET(ptile->tile_known, player_index(pplayer));
}

/***************************************************************
...
***************************************************************/
bool map_is_known_and_seen(const struct tile *ptile, struct player *pplayer,
			   enum vision_layer vlayer)
{
  assert(!game.info.fogofwar
	 || (BV_ISSET(ptile->tile_seen[vlayer], player_index(pplayer))
	     == (map_get_player_tile(ptile, pplayer)->seen_count[vlayer]
		 > 0)));
  return (BV_ISSET(ptile->tile_known, player_index(pplayer))
	  && BV_ISSET(ptile->tile_seen[vlayer], player_index(pplayer)));
}

/****************************************************************************
  Return whether the player can see the tile.  Seeing a tile means you have
  vision of it now (as opposed to knowing a tile which means you've seen it
  before).  Note that a tile can be seen but not known (currently this only
  happens when a city is founded with some unknown tiles in its radius); in
  this case the tile is unknown (but map_get_seen will still return TRUE).
****************************************************************************/
static int map_get_seen(const struct tile *ptile,
			const struct player *pplayer,
			enum vision_layer vlayer)
{
  assert(!game.info.fogofwar
	 || (BV_ISSET(ptile->tile_seen[vlayer], player_index(pplayer))
	     == (map_get_player_tile(ptile, pplayer)->seen_count[vlayer]
		 > 0)));
  return map_get_player_tile(ptile, pplayer)->seen_count[vlayer];
}

/***************************************************************
...
***************************************************************/
void map_change_seen(struct tile *ptile, struct player *pplayer, int change,
		     enum vision_layer vlayer)
{
  struct player_tile *plrtile = map_get_player_tile(ptile, pplayer);

  /* assert to avoid underflow */
  assert(0 <= change || -change <= plrtile->seen_count[vlayer]);

  plrtile->seen_count[vlayer] += change;
  if (plrtile->seen_count[vlayer] != 0) {
    BV_SET(ptile->tile_seen[vlayer], player_index(pplayer));
  } else {
    BV_CLR(ptile->tile_seen[vlayer], player_index(pplayer));
  }
  freelog(LOG_DEBUG, "%d,%d, p: %d, change %d, result %d\n", TILE_XY(ptile),
	  player_number(pplayer), change, plrtile->seen_count[vlayer]);
}

/***************************************************************
...
***************************************************************/
static int map_get_own_seen(struct tile *ptile, struct player *pplayer,
			    enum vision_layer vlayer)
{
  return map_get_player_tile(ptile, pplayer)->own_seen[vlayer];
}

/***************************************************************
...
***************************************************************/
static void map_change_own_seen(struct tile *ptile, struct player *pplayer,
				int change,
				enum vision_layer vlayer)
{
  map_get_player_tile(ptile, pplayer)->own_seen[vlayer] += change;
}

/***************************************************************
...
***************************************************************/
void map_set_known(struct tile *ptile, struct player *pplayer)
{
  BV_SET(ptile->tile_known, player_index(pplayer));
  vision_layer_iterate(v) {
    if (map_get_player_tile(ptile, pplayer)->seen_count[v] > 0) {
      BV_SET(ptile->tile_seen[v], player_index(pplayer));
    }
  } vision_layer_iterate_end;
}

/***************************************************************
...
***************************************************************/
void map_clear_known(struct tile *ptile, struct player *pplayer)
{
  BV_CLR(ptile->tile_known, player_index(pplayer));
}

/****************************************************************************
  Call this function to unfog all tiles.  This should only be called when
  a player dies or at the end of the game as it will result in permanent
  vision of the whole map.
****************************************************************************/
void map_know_and_see_all(struct player *pplayer)
{
  buffer_shared_vision(pplayer);

  whole_map_iterate(ptile) {
    vision_layer_iterate(v) {
      map_unfog_tile(pplayer, ptile, TRUE, v);
    } vision_layer_iterate_end;
  } whole_map_iterate_end;

  unbuffer_shared_vision(pplayer);
}

/**************************************************************************
  Unfogs all tiles for all players.  See map_know_and_see_all.
**************************************************************************/
void show_map_to_all(void)
{
  players_iterate(pplayer) {
    map_know_and_see_all(pplayer);
  } players_iterate_end;
}

/***************************************************************
  Allocate space for map, and initialise the tiles.
  Uses current map.xsize and map.ysize.
****************************************************************/
void player_map_allocate(struct player *pplayer)
{
  pplayer->private_map
    = fc_malloc(MAP_INDEX_SIZE * sizeof(*pplayer->private_map));

  whole_map_iterate(ptile) {
    player_tile_init(ptile, pplayer);
  } whole_map_iterate_end;
}

/***************************************************************
 frees a player's private map.
***************************************************************/
void player_map_free(struct player *pplayer)
{
  if (!pplayer->private_map) {
    return;
  }

  whole_map_iterate(ptile) {
    struct player_tile *plrtile = map_get_player_tile(ptile, pplayer);

    if (plrtile->vision_source) {
      free(plrtile->vision_source);
    }
  } whole_map_iterate_end;

  free(pplayer->private_map);
  pplayer->private_map = NULL;
}

/***************************************************************
  We need to use fogofwar_old here, so the player's tiles get
  in the same state as the other players' tiles.
***************************************************************/
static void player_tile_init(struct tile *ptile, struct player *pplayer)
{
  struct player_tile *plrtile = map_get_player_tile(ptile, pplayer);

  plrtile->terrain = T_UNKNOWN;
  clear_all_specials(&plrtile->special);
  plrtile->resource = NULL;
  plrtile->vision_source = NULL;

  vision_layer_iterate(v) {
    plrtile->seen_count[v] = 0;
    BV_CLR(ptile->tile_seen[v], player_index(pplayer));
  } vision_layer_iterate_end;

  if (!game.fogofwar_old) {
    plrtile->seen_count[V_MAIN] = 1;
    if (map_is_known(ptile, pplayer)) {
      BV_SET(ptile->tile_seen[V_MAIN], player_index(pplayer));
    }
  }

  plrtile->last_updated = GAME_START_YEAR;
  vision_layer_iterate(v) {
    plrtile->own_seen[v] = plrtile->seen_count[v];
  } vision_layer_iterate_end;
}

/****************************************************************************
  ...
****************************************************************************/
struct vision_base *map_get_player_base(const struct tile *ptile,
					const struct player *pplayer)
{
  return map_get_player_tile(ptile, pplayer)->vision_source;
}

/****************************************************************************
  ...
****************************************************************************/
struct vision_base *map_get_player_city(const struct tile *ptile,
					const struct player *pplayer)
{
  struct player_tile *playtile = map_get_player_tile(ptile, pplayer);
  struct vision_base *vision_source = playtile->vision_source;

  if (vision_source && ptile == vision_source->location) {
    return vision_source;
  }
  return NULL;
}

/****************************************************************************
  Players' information of tiles is tracked so that fogged area can be kept
  consistent even when the client disconnects.  This function returns the
  player tile information for the given tile and player.
****************************************************************************/
struct player_tile *map_get_player_tile(const struct tile *ptile,
					const struct player *pplayer)
{
  return pplayer->private_map + ptile->index;
}

/****************************************************************************
  Give pplayer the correct knowledge about tile; return TRUE iff
  knowledge changed.

  Note that unlike update_tile_knowledge, this function will not send any
  packets to the client.  Callers may want to call send_tile_info() if this
  function returns TRUE.
****************************************************************************/
bool update_player_tile_knowledge(struct player *pplayer, struct tile *ptile)
{
  struct player_tile *plrtile = map_get_player_tile(ptile, pplayer);

  if (plrtile->terrain != ptile->terrain
      || !BV_ARE_EQUAL(plrtile->special, ptile->special)
      || plrtile->resource != ptile->resource) {
    plrtile->terrain = ptile->terrain;
    plrtile->special = ptile->special;
    plrtile->resource = ptile->resource;
    return TRUE;
  }
  return FALSE;
}

/****************************************************************************
  Update playermap knowledge for everybody who sees the tile, and send a
  packet to everyone whose info is changed.

  Note this only checks for changing of the terrain, special, or resource
  for the tile, since these are the only values held in the playermap.

  A tile's owner always can see terrain changes in his or her territory.
****************************************************************************/
void update_tile_knowledge(struct tile *ptile)
{
  /* Players */
  players_iterate(pplayer) {
    if (map_is_known_and_seen(ptile, pplayer, V_MAIN)) {
      if (update_player_tile_knowledge(pplayer, ptile)) {
        send_tile_info(pplayer->connections, ptile);
      }
    }
  } players_iterate_end;

  /* Global observers */
  conn_list_iterate(game.est_connections, pconn) {
    struct player *pplayer = pconn->player;
    if (!pplayer && pconn->observer) {
      send_tile_info(pconn->self, ptile);
    }
  } conn_list_iterate_end;
}

/***************************************************************
...
***************************************************************/
void update_player_tile_last_seen(struct player *pplayer, struct tile *ptile)
{
  map_get_player_tile(ptile, pplayer)->last_updated = game.info.year;
}

/***************************************************************
...
***************************************************************/
static void really_give_tile_info_from_player_to_player(struct player *pfrom,
							struct player *pdest,
							struct tile *ptile)
{
  struct player_tile *from_tile, *dest_tile;
  if (!map_is_known_and_seen(ptile, pdest, V_MAIN)) {
    /* I can just hear people scream as they try to comprehend this if :).
     * Let me try in words:
     * 1) if the tile is seen by pfrom the info is sent to pdest
     *  OR
     * 2) if the tile is known by pfrom AND (he has more recent info
     *     OR it is not known by pdest)
     */
    if (map_is_known_and_seen(ptile, pfrom, V_MAIN)
	|| (map_is_known(ptile, pfrom)
	    && (((map_get_player_tile(ptile, pfrom)->last_updated
		 > map_get_player_tile(ptile, pdest)->last_updated))
	        || !map_is_known(ptile, pdest)))) {
      from_tile = map_get_player_tile(ptile, pfrom);
      dest_tile = map_get_player_tile(ptile, pdest);
      /* Update and send tile knowledge */
      map_set_known(ptile, pdest);
      dest_tile->terrain = from_tile->terrain;
      dest_tile->special = from_tile->special;
      dest_tile->resource = from_tile->resource;
      dest_tile->last_updated = from_tile->last_updated;
      send_tile_info(pdest->connections, ptile);
	
      /* update and send city knowledge */
      /* remove outdated cities */
      if (dest_tile->vision_source) {
	if (!from_tile->vision_source) {
	  /* As the city was gone on the newer from_tile
	     it will be removed by this function */
	  reality_check_city(pdest, ptile);
	} else /* We have a dest_city. update */
	  if (from_tile->vision_source->identity
	   != dest_tile->vision_source->identity)
	    /* As the city was gone on the newer from_tile
	       it will be removed by this function */
	    reality_check_city(pdest, ptile);
      }
      /* Set and send new city info */
      if (from_tile->vision_source) {
	if (!dest_tile->vision_source) {
	  dest_tile->vision_source = fc_calloc(1, sizeof(*dest_tile->vision_source));
	}
	/* struct assignment copy */
	*dest_tile->vision_source = *from_tile->vision_source;
	send_city_info_at_tile(pdest, pdest->connections, NULL, ptile);
      }

      map_city_radius_iterate(ptile, tile1) {
	struct city *pcity = tile_get_city(tile1);
	if (pcity && city_owner(pcity) == pdest) {
	  update_city_tile_status_map(pcity, ptile);
	}
      } map_city_radius_iterate_end;
      sync_cities();
    }
  }
}

/***************************************************************
...
***************************************************************/
static void give_tile_info_from_player_to_player(struct player *pfrom,
						 struct player *pdest,
						 struct tile *ptile)
{
  really_give_tile_info_from_player_to_player(pfrom, pdest, ptile);

  players_iterate(pplayer2) {
    if (!really_gives_vision(pdest, pplayer2))
      continue;
    really_give_tile_info_from_player_to_player(pfrom, pplayer2, ptile);
  } players_iterate_end;
}

/***************************************************************
This updates all players' really_gives_vision field.
If p1 gives p2 shared vision and p2 gives p3 shared vision p1
should also give p3 shared vision.
***************************************************************/
static void create_vision_dependencies(void)
{
  int added;

  players_iterate(pplayer) {
    pplayer->really_gives_vision = pplayer->gives_shared_vision;
  } players_iterate_end;

  /* In words: This terminates when it has run a round without adding
     a dependency. One loop only propagates dependencies one level deep,
     which is why we keep doing it as long as changes occur. */
  do {
    added = 0;
    players_iterate(pplayer) {
      players_iterate(pplayer2) {
	if (really_gives_vision(pplayer, pplayer2)
	    && pplayer != pplayer2) {
	  players_iterate(pplayer3) {
	    if (really_gives_vision(pplayer2, pplayer3)
		&& !really_gives_vision(pplayer, pplayer3)
		&& pplayer != pplayer3) {
	      pplayer->really_gives_vision |= (1<<player_index(pplayer3));
	      added++;
	    }
	  } players_iterate_end;
	}
      } players_iterate_end;
    } players_iterate_end;
  } while (added > 0);
}

/***************************************************************
...
***************************************************************/
void give_shared_vision(struct player *pfrom, struct player *pto)
{
  int save_vision[MAX_NUM_PLAYERS+MAX_NUM_BARBARIANS];
  if (pfrom == pto) return;
  if (gives_shared_vision(pfrom, pto)) {
    freelog(LOG_ERROR, "Trying to give shared vision from %s to %s, "
	    "but that vision is already given!",
	    player_name(pfrom),
	    player_name(pto));
    return;
  }

  players_iterate(pplayer) {
    save_vision[player_index(pplayer)] = pplayer->really_gives_vision;
  } players_iterate_end;

  pfrom->gives_shared_vision |= 1<<player_index(pto);
  create_vision_dependencies();
  freelog(LOG_DEBUG, "giving shared vision from %s to %s\n",
	  player_name(pfrom),
	  player_name(pto));

  players_iterate(pplayer) {
    buffer_shared_vision(pplayer);
    players_iterate(pplayer2) {
      if (really_gives_vision(pplayer, pplayer2)
	  && !TEST_BIT(save_vision[player_index(pplayer)], player_index(pplayer2))) {
	freelog(LOG_DEBUG, "really giving shared vision from %s to %s\n",
	       player_name(pplayer),
	       player_name(pplayer2));
	whole_map_iterate(ptile) {
	  vision_layer_iterate(v) {
	    int change = map_get_own_seen(ptile, pplayer, v);

	    if (change != 0) {
	      map_change_seen(ptile, pplayer2, change, v);
	      if (map_get_seen(ptile, pplayer2, v) == change
		  && map_is_known(ptile, pplayer)) {
		really_unfog_tile(pplayer2, ptile, v);
	      }
	    }
	  } vision_layer_iterate_end;
	} whole_map_iterate_end;

	/* squares that are not seen, but which pfrom may have more recent
	   knowledge of */
	give_map_from_player_to_player(pplayer, pplayer2);
      }
    } players_iterate_end;
    unbuffer_shared_vision(pplayer);
  } players_iterate_end;

  if (S_S_RUNNING == server_state()) {
    send_player_info(pfrom, NULL);
  }
}

/***************************************************************
...
***************************************************************/
void remove_shared_vision(struct player *pfrom, struct player *pto)
{
  int save_vision[MAX_NUM_PLAYERS+MAX_NUM_BARBARIANS];
  assert(pfrom != pto);
  if (!gives_shared_vision(pfrom, pto)) {
    freelog(LOG_ERROR, "Tried removing the shared vision from %s to %s, "
	    "but it did not exist in the first place!",
	    player_name(pfrom),
	    player_name(pto));
    return;
  }

  players_iterate(pplayer) {
    save_vision[player_index(pplayer)] = pplayer->really_gives_vision;
  } players_iterate_end;

  freelog(LOG_DEBUG, "removing shared vision from %s to %s\n",
	  player_name(pfrom),
	  player_name(pto));

  pfrom->gives_shared_vision &= ~(1<<player_index(pto));
  create_vision_dependencies();

  players_iterate(pplayer) {
    buffer_shared_vision(pplayer);
    players_iterate(pplayer2) {
      if (!really_gives_vision(pplayer, pplayer2)
	  && TEST_BIT(save_vision[player_index(pplayer)], player_index(pplayer2))) {
	freelog(LOG_DEBUG, "really removing shared vision from %s to %s\n",
	       player_name(pplayer),
	       player_name(pplayer2));
	whole_map_iterate(ptile) {
	  vision_layer_iterate(v) {
	    int change = map_get_own_seen(ptile, pplayer, v);

	    if (change > 0) {
	      map_change_seen(ptile, pplayer2, -change, v);
	      if (map_get_seen(ptile, pplayer2, v) == 0)
		really_fog_tile(pplayer2, ptile, v);
	    }
	  } vision_layer_iterate_end;
	} whole_map_iterate_end;
      }
    } players_iterate_end;
    unbuffer_shared_vision(pplayer);
  } players_iterate_end;

  if (S_S_RUNNING == server_state()) {
    send_player_info(pfrom, NULL);
  }
}

/*************************************************************************
...
*************************************************************************/
static void enable_fog_of_war_player(struct player *pplayer)
{
  buffer_shared_vision(pplayer);
  whole_map_iterate(ptile) {
    map_fog_tile(pplayer, ptile, V_MAIN);
  } whole_map_iterate_end;
  unbuffer_shared_vision(pplayer);
}

/*************************************************************************
...
*************************************************************************/
void enable_fog_of_war(void)
{
  players_iterate(pplayer) {
    enable_fog_of_war_player(pplayer);
  } players_iterate_end;
}

/*************************************************************************
...
*************************************************************************/
static void disable_fog_of_war_player(struct player *pplayer)
{
  buffer_shared_vision(pplayer);
  whole_map_iterate(ptile) {
    map_unfog_tile(pplayer, ptile, FALSE, V_MAIN);
  } whole_map_iterate_end;
  unbuffer_shared_vision(pplayer);
}

/*************************************************************************
...
*************************************************************************/
void disable_fog_of_war(void)
{
  players_iterate(pplayer) {
    disable_fog_of_war_player(pplayer);
  } players_iterate_end;
}

/**************************************************************************
  Set the tile to be a river if required.
  It's required if one of the tiles nearby would otherwise be part of a
  river to nowhere.
  For simplicity, I'm assuming that this is the only exit of the river,
  so I don't need to trace it across the continent.  --CJM
  Also, note that this only works for R_AS_SPECIAL type rivers.  --jjm
**************************************************************************/
static void ocean_to_land_fix_rivers(struct tile *ptile)
{
  /* clear the river if it exists */
  tile_clear_special(ptile, S_RIVER);

  cardinal_adjc_iterate(ptile, tile1) {
    if (tile_has_special(tile1, S_RIVER)) {
      bool ocean_near = FALSE;
      cardinal_adjc_iterate(tile1, tile2) {
        if (is_ocean(tile_get_terrain(tile2)))
          ocean_near = TRUE;
      } cardinal_adjc_iterate_end;
      if (!ocean_near) {
        tile_set_special(ptile, S_RIVER);
        return;
      }
    }
  } cardinal_adjc_iterate_end;
}

/****************************************************************************
  A helper function for check_terrain_change that moves units off of invalid
  terrain after it's been changed.
****************************************************************************/
static void bounce_units_on_terrain_change(struct tile *ptile)
{
  unit_list_iterate_safe(ptile->units, punit) {
    bool unit_alive = TRUE;

    if (punit->tile == ptile
	&& punit->transported_by == -1
	&& !can_unit_exist_at_tile(punit, ptile)) {
      /* look for a nearby safe tile */
      adjc_iterate(ptile, ptile2) {
	if (can_unit_exist_at_tile(punit, ptile2)
	    && !is_non_allied_unit_tile(ptile2, unit_owner(punit))) {
	  freelog(LOG_VERBOSE,
		  "Moved %s %s due to changing terrain at (%d,%d).",
		  nation_rule_name(nation_of_unit(punit)),
		  unit_rule_name(punit),
		  TILE_XY(punit->tile));
	  notify_player(unit_owner(punit),
			   punit->tile, E_UNIT_RELOCATED,
			   _("Moved your %s due to changing terrain."),
			   unit_name_translation(punit));
	  unit_alive = move_unit(punit, ptile2, 0);
	  if (unit_alive && punit->activity == ACTIVITY_SENTRY) {
	    handle_unit_activity_request(punit, ACTIVITY_IDLE);
	  }
	  break;
	}
      } adjc_iterate_end;
      if (unit_alive && punit->tile == ptile) {
	/* if we get here we could not move punit */
	freelog(LOG_VERBOSE,
		"Disbanded %s %s due to changing land to sea at (%d,%d).",
		nation_rule_name(nation_of_unit(punit)),
		unit_rule_name(punit),
		TILE_XY(punit->tile));
	notify_player(unit_owner(punit),
			 punit->tile, E_UNIT_LOST,
			 _("Disbanded your %s due to changing terrain."),
			 unit_name_translation(punit));
	wipe_unit(punit);
      }
    }
  } unit_list_iterate_safe_end;
}

/****************************************************************************
  Handles global side effects for a terrain change.  Call this in the
  server immediately after calling tile_change_terrain.
****************************************************************************/
void check_terrain_change(struct tile *ptile, struct terrain *oldter)
{
  struct terrain *newter = tile_get_terrain(ptile);
  bool ocean_toggled = FALSE;

  if (is_ocean(oldter) && !is_ocean(newter)) {
    /* ocean to land ... */
    ocean_to_land_fix_rivers(ptile);
    city_landlocked_sell_coastal_improvements(ptile);
    ocean_toggled = TRUE;
  } else if (!is_ocean(oldter) && is_ocean(newter)) {
    /* land to ocean ... */
    ocean_toggled = TRUE;
  }

  if (ocean_toggled) {
    bounce_units_on_terrain_change(ptile);
    assign_continent_numbers(FALSE);

    /* New continent numbers for all tiles to all players */
    send_all_known_tiles(NULL);
  }
}

/*************************************************************************
  Ocean tile can be claimed iff one of the following conditions stands:
  a) it is an inland lake not larger than MAXIMUM_OCEAN_SIZE
  b) it is adjacent to only one continent and not more than two ocean tiles
  c) It is one tile away from a city
  The source which claims the ocean has to be placed on the correct continent.
  in case a) The continent which surrounds the inland lake
  in case b) The only continent which is adjacent to the tile
  The correct continent is returned in *contp.
*************************************************************************/
static bool is_claimable_ocean(struct tile *ptile, struct tile *source)
{
  Continent_id cont = tile_get_continent(ptile);
  Continent_id source_cont = tile_get_continent(source);
  Continent_id cont2;
  int ocean_tiles;

  if (get_ocean_size(-cont) <= MAXIMUM_CLAIMED_OCEAN_SIZE
      && lake_surrounders[-cont] == source_cont) {
    return TRUE;
  }
  
  ocean_tiles = 0;
  adjc_iterate(ptile, tile2) {
    cont2 = tile_get_continent(tile2);
    if (tile2 == source) {
      return TRUE;
    }
    if (cont2 == cont) {
      ocean_tiles++;
    } else if (cont2 != source_cont) {
      return FALSE; /* two land continents adjacent, punt! */
    }
  } adjc_iterate_end;
  if (ocean_tiles <= 2) {
    return TRUE;
  } else {
    return FALSE;
  }
}

/*************************************************************************
  Update tile worker states for all cities that have the given map tile
  within their radius. Does not sync with client.

  This function is inefficient and so should only be called when the
  owner actually changes.
*************************************************************************/
static void tile_update_owner(struct tile *ptile)
{
  /* This implementation is horribly inefficient, but this doesn't cause
   * problems since it's not called often. */
  cities_iterate(pcity) {
    update_city_tile_status_map(pcity, ptile);
  } cities_iterate_end;
}

/*************************************************************************
  Add any unique home city not found in list but found on tile to the 
  list.
*************************************************************************/
static void add_unique_homecities(struct city_list *cities_to_refresh, 
                           struct tile *tile1)
{
  /* Update happiness */
 unit_list_iterate(tile1->units, unit) {
   struct city* homecity = game_find_city_by_number(unit->homecity);
   bool already_listed = FALSE;

    if (!homecity) {
      continue;
    }
    city_list_iterate(cities_to_refresh, city2) {
      if (city2 == homecity) {
        already_listed = TRUE;
        break;
      }
      if (!already_listed) {
        city_list_prepend(cities_to_refresh, homecity);
      }
    } city_list_iterate_end;
  } unit_list_iterate_end;
}

/*************************************************************************
  Claim ownership of a single tile.  This does no checks.
*************************************************************************/
void map_claim_ownership(struct tile *ptile, struct player *owner,
                         struct tile *source)
{
  ptile->owner_source = source;
  tile_set_owner(ptile, owner);
  send_tile_info(NULL, ptile);
  tile_update_owner(ptile);
}

/*************************************************************************
  Establish range of a border source.
*************************************************************************/
static int tile_border_range(struct tile *ptile)
{
  int range;

  if (ptile->city) {
    range = MIN(ptile->city->size + 1, game.info.borders);
    if (ptile->city->size > game.info.borders) {
      range += (ptile->city->size - game.info.borders) / 2;
    }
  } else {
    range = game.info.borders;
  }
  return range;
}

/*************************************************************************
  Update borders for all sources.  Call this on turn end.

  We will remove claim to land whose source is gone, and claim
  more land to sources in range, unless there are enemy units within
  this range.
*************************************************************************/
void map_calculate_borders(void)
{
  struct city_list *cities_to_refresh = NULL;

  if (game.info.borders == 0) {
    return;
  }

  if (game.info.happyborders > 0) {
    cities_to_refresh = city_list_new();
  }

  /* First transfer ownership for sources that have changed hands. */
  whole_map_iterate(ptile) {
    if (tile_owner(ptile) 
        && ptile->owner_source
        && ptile->owner_source->owner != tile_owner(ptile)
        && (ptile->owner_source->city
            || tile_has_special(ptile->owner_source, S_FORTRESS))) {
      /* Claim ownership of tiles previously owned by someone else */
      map_claim_ownership(ptile, ptile->owner_source->owner, 
                          ptile->owner_source);
    }
  } whole_map_iterate_end;

  /* Second transfer ownership to city closer than current source 
   * but with the same owner. */
  whole_map_iterate(ptile) {
    if (tile_owner(ptile)) {
      city_list_iterate(tile_owner(ptile)->cities, pcity) {
        int r_curr, r_city = sq_map_distance(ptile, pcity->tile);
        int max_range = tile_border_range(pcity->tile);

        /* Repair tile ownership */
        if (!ptile->owner_source) {
          assert(FALSE);
          ptile->owner_source = pcity->tile;
        }
        r_curr = sq_map_distance(ptile, ptile->owner_source);
        max_range *= max_range; /* we are dealing with square distances */
        /* Transfer tile to city if closer than current source */
        if (r_curr > r_city && max_range >= r_city) {
          freelog(LOG_DEBUG, "%s %s(%d,%d) acquired tile (%d,%d) from "
                  "(%d,%d)",
                  nation_rule_name(nation_of_player(tile_owner(ptile))),
                  city_name(pcity),
                  TILE_XY(pcity->tile),
                  TILE_XY(ptile),
                  TILE_XY(ptile->owner_source));
          ptile->owner_source = pcity->tile;
        }
      } city_list_iterate_end;
    }
  } whole_map_iterate_end;

  /* Third remove undue ownership. */
  whole_map_iterate(ptile) {
    if (tile_owner(ptile)
        && (tile_owner(ptile) != ptile->owner_source->owner
            || (!ptile->owner_source->city
                && !tile_has_special(ptile->owner_source, S_FORTRESS)))) {
      /* Ownership source gone */
      map_claim_ownership(ptile, NULL, NULL);
    }
  } whole_map_iterate_end;

  /* Now claim ownership of unclaimed tiles for all sources; we
   * grab one circle each turn as long as we have range left
   * to better visually display expansion. */
  whole_map_iterate(ptile) {
    if (tile_owner(ptile)
        && (ptile->city || tile_has_special(ptile, S_FORTRESS))) {
      /* We have an ownership source */
      int expand_range = 99;
      int found_unclaimed = 99;
      int range = tile_border_range(ptile);

      freelog(LOG_DEBUG, "source at %d,%d", ptile->x, ptile->y);
      range *= range; /* due to sq dist */
      freelog(LOG_DEBUG, "borders range for source is %d", range);

      circle_dxyr_iterate(ptile, range, atile, dx, dy, dist) {
        if (expand_range > dist) {
          unit_list_iterate(atile->units, punit) {
            if (!pplayers_allied(unit_owner(punit), tile_owner(ptile))) {
              /* We cannot expand borders further when enemy units are
               * standing in the way. */
              expand_range = dist - 1;
            }
          } unit_list_iterate_end;
        }
        if (found_unclaimed > dist
            && tile_owner(atile) == NULL
            && map_is_known(atile, tile_owner(ptile))
            && (!is_ocean(atile->terrain)
                || is_claimable_ocean(atile, ptile))) {
          found_unclaimed = dist;
        }
      } circle_dxyr_iterate_end;
      freelog(LOG_DEBUG, "expand_range=%d found_unclaimed=%d", expand_range,
              found_unclaimed);

      circle_dxyr_iterate(ptile, range, atile, dx, dy, dist) {
        if (dist > expand_range || dist > found_unclaimed) {
          continue; /* only expand one extra circle radius each turn */
        }
        if (map_is_known(atile, tile_owner(ptile))
            && tile_owner(atile) == NULL
            && ((!is_ocean(atile->terrain) 
                 && atile->continent == ptile->continent)
                || (is_ocean(atile->terrain)
                    && is_claimable_ocean(atile, ptile)))) {
          map_claim_ownership(atile, tile_owner(ptile), ptile);
          atile->owner_source = ptile;
          if (game.info.happyborders > 0) {
            add_unique_homecities(cities_to_refresh, atile);
          }
        }
      } circle_dxyr_iterate_end;
    }
  } whole_map_iterate_end;

  /* Update happiness in all homecities we have collected */ 
  if (game.info.happyborders > 0) {
    city_list_iterate(cities_to_refresh, to_refresh) {
      city_refresh(to_refresh);
      send_city_info(city_owner(to_refresh), to_refresh);
    } city_list_iterate_end;
    
    city_list_unlink_all(cities_to_refresh);
    city_list_free(cities_to_refresh);
  }
}

/*************************************************************************
  Return size in tiles of the given continent(not ocean)
*************************************************************************/
int get_continent_size(Continent_id id)
{
  assert(id > 0);
  return continent_sizes[id];
}

/*************************************************************************
  Return size in tiles of the given ocean. You should use positive ocean
  number.
*************************************************************************/
int get_ocean_size(Continent_id id) 
{
  assert(id > 0);
  return ocean_sizes[id];
}

/* Vision structure - see documentation in maphand.h */


/****************************************************************************
  Create a new vision source.

  See documentation in maphand.h.
****************************************************************************/
struct vision *vision_new(struct player *pplayer, struct tile *ptile,
			  bool can_reveal_tiles)
{
  struct vision *vision = fc_malloc(sizeof(*vision));

  vision->player = pplayer;
  vision->tile = ptile;
  vision->can_reveal_tiles = can_reveal_tiles;
  vision_layer_iterate(v) {
    vision->radius_sq[v] = -1;
  } vision_layer_iterate_end;

  return vision;
}

/****************************************************************************
  Returns the sight points (radius_sq) that this vision source has.

  See documentation in maphand.h.
****************************************************************************/
int vision_get_sight(const struct vision *vision, enum vision_layer vlayer)
{
  return vision->radius_sq[vlayer];
}

/****************************************************************************
  Change the sight points for the vision source, fogging or unfogging tiles
  as needed.

  See documentation in maphand.h.
****************************************************************************/
void vision_change_sight(struct vision *vision, enum vision_layer vlayer,
			 int radius_sq)
{
  map_refog_circle(vision->player, vision->tile,
		   vision->radius_sq[vlayer], radius_sq,
		   vision->can_reveal_tiles, vlayer);
  vision->radius_sq[vlayer] = radius_sq;
}

/****************************************************************************
  Clear all sight points from this vision source.

  See documentation in maphand.h.
****************************************************************************/
void vision_clear_sight(struct vision *vision)
{
  /* We don't use vision_layer_iterate because we have to go in reverse
   * order. */
  vision_change_sight(vision, V_INVIS, -1);
  vision_change_sight(vision, V_MAIN, -1);
}

/****************************************************************************
  Free the vision source.

  See documentation in maphand.h.
****************************************************************************/
void vision_free(struct vision *vision)
{
  assert(S_S_RUNNING != server_state() || vision->radius_sq[V_MAIN] < 0);
  assert(S_S_RUNNING != server_state() || vision->radius_sq[V_INVIS] < 0);
  free(vision);
}