]> git.pond.sub.org Git - empserver/blob - src/util/fairland.c
22a953929d24652ed8c5f29e1b5b65d28e8e2fb2
[empserver] / src / util / fairland.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2020, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  fairland.c: Create a nice, new world
28  *
29  *  Known contributors to this file:
30  *     Ken Stevens, 1995
31  *     Steve McClure, 1998
32  *     Markus Armbruster, 2004-2020
33  */
34
35 /*
36  * How fairland works
37  *
38  * 1. Place capitals
39  *
40  * Place the capitals on the torus in such a way so as to maximize
41  * their distances from one another.  This uses the perturbation
42  * technique of calculus of variations.
43  *
44  * 2. Grow start islands ("continents")
45  *
46  * For all continents, add the first sector at the capital's location,
47  * and the second right to it.  These are the capital sectors.  Then
48  * add one sector to each continent in turn, until they have the
49  * specified size.
50  *
51  * Growth uses weighted random sampling to pick one sector from the
52  * set of adjacent sea sectors that aren't too close to another
53  * continent.  Growth operates in spiking mode with a chance given by
54  * the spike percentage.  When "spiking", a sector's weight increases
55  * with number of adjacent sea sectors.  This directs the growth away
56  * from land, resulting in spikes.  When not spiking, the weight
57  * increases with the number of adjacent land sectors.  This makes the
58  * island more rounded.
59  *
60  * If growing fails due to lack of room, start over.  If it fails too
61  * many times, give up and terminate unsuccessfully.
62  *
63  * 3. Place and grow additional islands
64  *
65  * Each continent has a "sphere of influence": the set of sectors
66  * closer to it than to any other continent.  Each island is entirely
67  * in one such sphere, and each sphere contains the same number of
68  * islands with the same sizes.
69  *
70  * First, split the specified number of island sectors per continent
71  * randomly into the island sizes.  Sort by size so that larger
72  * islands are grown before smaller ones, to give the large ones the
73  * best chance to grow to their planned size.
74  *
75  * Then place one island's first sector into each sphere, using
76  * weighted random sampling with weights favoring sectors away from
77  * land and other spheres.  Add one sector to each island in turn,
78  * until they have the intended size.  Repeat until the specified
79  * number of islands has been grown.
80  *
81  * If placement fails due to lack of room, start over, just like for
82  * continents.
83  *
84  * Growing works as for continents, except the minimum distance for
85  * additional islands applies, and growing simply stops when any of
86  * the islands being grown lacks the room to grow further.  The number
87  * of sectors not grown carries over to the next island size.
88  *
89  * 4. Compute elevation
90  *
91  * First, use a simple random hill algorithm to assign raw elevations:
92  * initialize elevation to zero, then randomly raise circular hills on
93  * land / lower circular depressions at sea.  Their size and height
94  * depends on the distance to the coast.
95  *
96  * Then, elevate islands one after the other.
97  *
98  * Set the capitals' elevation to a fixed value.  Process the
99  * remaining sectors in order of increasing raw elevation, first
100  * non-mountains, then mountains.  Non-mountain elevation starts at 1,
101  * and increases linearly to just below "high" elevation.  Mountain
102  * elevation starts at "high" elevation, and increases linearly.
103  *
104  * This gives islands of the same size the same set of elevations.
105  * Larger islands get more and taller mountains.
106  *
107  * Finally, elevate sea: normalize the raw elevations to [-127:-1].
108  *
109  * 5. Set resources
110  *
111  * Sector resources are simple functions of elevation.  You can alter
112  * iron_conf[], gold_conf[], fert_conf[], oil_conf[], and uran_conf[]
113  * to customize them.
114  */
115
116 #include <config.h>
117
118 #include <assert.h>
119 #include <errno.h>
120 #include <limits.h>
121 #include <stdarg.h>
122 #include <stdio.h>
123 #include <unistd.h>
124 #include "chance.h"
125 #include "optlist.h"
126 #include "path.h"
127 #include "prototypes.h"
128 #include "sect.h"
129 #include "version.h"
130 #include "xy.h"
131
132 /*
133  * Number of retries when growing land fails
134  */
135 #define NUMTRIES 10
136
137 /* do not change these defines */
138 #define LANDMIN         1       /* plate altitude for normal land */
139 #define PLATMIN         36      /* plate altitude for plateau */
140 #define HIGHMIN         98      /* plate altitude for mountains */
141
142 /*
143  * Resource configuration
144
145  * Resources are determined by elevation.  The map from elevation to
146  * resource is defined as a linear interpolation of resource data
147  * points (elev, res) defined in the tables below.  Elevations range
148  * from -127 to 127, and resource values from 0 to 100.
149  */
150
151 struct resource_point {
152     int elev, res;
153 };
154
155 struct resource_point iron_conf[] = {
156     { -127, 0 },
157     { 21, 0 },
158     { 85, 100 },
159     { HIGHMIN - 1, 100 },
160     { HIGHMIN , 0 },
161     { 127, 0 } };
162
163 struct resource_point gold_conf[] = {
164     { -127, 0 },
165     { 35, 0 },
166     { HIGHMIN - 1, 80 },
167     { HIGHMIN, 80 },
168     { 127, 85 } };
169
170 struct resource_point fert_conf[] = {
171     { -127, 100 },
172     { -59, 100 },
173     { LANDMIN - 1, 41 },
174     { LANDMIN, 100 },
175     { 10, 100 },
176     { 56, 0 },
177     { 127, 0 } };
178
179 struct resource_point oil_conf[] = {
180     { -127, 100 },
181     { -49, 100 },
182     { LANDMIN - 1, 2 },
183     { LANDMIN, 100 },
184     { 6, 100 },
185     { 34, 0 },
186     { 127, 0 } };
187
188 struct resource_point uran_conf[] = {
189     { -127, 0 },
190     { 55, 0 },
191     { 90, 100 },
192     { 97, 100 },
193     { 98, 0 },
194     { 127, 0 } };
195
196 /*
197  * Program arguments and options
198  */
199 static char *program_name;
200 static int nc, sc;              /* number and size of continents */
201 static int ni, is;              /* number and size of islands */
202 #define DEFAULT_SPIKE 10
203 static int sp = DEFAULT_SPIKE;  /* spike percentage */
204 #define DEFAULT_MOUNTAIN 0
205 static int pm = DEFAULT_MOUNTAIN; /* mountain percentage */
206 #define DEFAULT_CONTDIST 2
207 static int di = DEFAULT_CONTDIST; /* min. distance between continents */
208 #define DEFAULT_ISLDIST 1
209 static int id = DEFAULT_ISLDIST;  /* ... continents and islands */
210 /* don't let the islands crash into each other.
211    1 = don't merge, 0 = merge. */
212 static int DISTINCT_ISLANDS = 1;
213 static int quiet;
214 #define DEFAULT_OUTFILE_NAME "newcap_script"
215 static const char *outfile = DEFAULT_OUTFILE_NAME;
216
217 #define STABLE_CYCLE 4          /* stability required for perterbed capitals */
218 #define DRIFT_BEFORE_CHECK ((WORLD_X + WORLD_Y)/2)
219 #define DRIFT_MAX ((WORLD_X + WORLD_Y)*2)
220
221 /* handy macros:
222 */
223
224 #define new_x(newx) (((newx) + WORLD_X) % WORLD_X)
225 #define new_y(newy) (((newy) + WORLD_Y) % WORLD_Y)
226
227 struct xy {
228     coord x, y;
229 };
230
231 /*
232  * Capital locations
233  * The i-th capital is at cap[i].
234  */
235 static struct xy *cap;
236
237 /*
238  * Island sizes
239  * isecs[i] is the size of the i-th island.
240  */
241 static int *isecs;
242
243 /*
244  * Island sectors
245  * The i-th island's j-th sector is at sect[i][j].
246  */
247 struct xy **sect;
248
249 /*
250  * Island at x, y
251  * own[XYOFFSET(x, y)] is x,y's island number, -1 if water.
252  */
253 static short *own;
254
255 /*
256  * Adjacent land sectors
257  * adj_land[XYOFFSET(x, y)] bit d is set exactly when the sector next
258  * to x, y in direction d is land.
259  */
260 static unsigned char *adj_land;
261
262 /*
263  * Elevation at x,y
264  * elev[XYOFFSET(x, y)] is x,y's elevation.
265  */
266 static short *elev;
267
268 /*
269  * Exclusive zones
270  * Each island is surrounded by an exclusive zone where only it may
271  * grow.  The width of the zone depends on minimum distances.
272  * While growing continents, it is @di sectors wide.
273  * While growing additional islands, it is @id sectors wide.
274  * DISTINCT_ISLANDS nullifies the exclusive zone then.
275  * xzone[XYOFFSET(x, y)] is -1 when the sector is in no exclusive
276  * zone, a (non-negative) island number when it is in that island's
277  * exclusive zone and no other, and -2 when it is in multiple
278  * exclusive zones.
279  */
280 static short *xzone;
281
282 /*
283  * Set of sectors seen already
284  * Increment @cur_seen to empty the set of sectors seen, set
285  * seen[XYOFFSET(x, y)] to @cur_seen to add x,y to the set.
286  */
287 static unsigned *seen;
288 static unsigned cur_seen;
289
290 /*
291  * Closest continent and "distance"
292  * closest[XYOFFSET(x, y)] is the closest continent's number.
293  * distance[] is complicated; see init_spheres_of_influence() and
294  * init_distance_to_coast().
295  */
296 static natid *closest;
297 static unsigned short *distance;
298
299 /*
300  * Queue for breadth-first search
301  */
302 static int *bfs_queue;
303 static int bfs_queue_head, bfs_queue_tail;
304
305 static const char *numletter =
306     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
307
308 static void print_vars(void);
309 static void qprint(const char * const fmt, ...)
310     ATTRIBUTE((format (printf, 1, 2)));
311 static void help(char *);
312 static void usage(void);
313 static void parse_args(int argc, char *argv[]);
314 static void allocate_memory(void);
315 static void init(void);
316 static int drift(void);
317 static int stable(int);
318 static void fl_move(int);
319 static int grow_continents(void);
320 static int grow_islands(void);
321 static void create_elevations(void);
322 static void elevate_prep(void);
323 static void elevate_land(void);
324 static void elevate_sea(void);
325 static void write_sects(void);
326 static void output(void);
327 static int write_newcap_script(void);
328
329 /* Debugging aids: */
330 void print_own_map(void);
331 void print_xzone_map(void);
332 void print_closest_map(void);
333 void print_distance_map(void);
334 void print_elev_map(void);
335
336 /****************************************************************************
337   MAIN
338 ****************************************************************************/
339
340 int
341 main(int argc, char *argv[])
342 {
343     int opt;
344     char *config_file = NULL;
345     int try, done;
346     unsigned rnd_seed = 0;
347     int seed_set = 0;
348
349     program_name = argv[0];
350
351     while ((opt = getopt(argc, argv, "e:hiqR:s:v")) != EOF) {
352         switch (opt) {
353         case 'e':
354             config_file = optarg;
355             break;
356         case 'i':
357             DISTINCT_ISLANDS = 0;
358             break;
359         case 'q':
360             quiet = 1;
361             break;
362         case 'R':
363             rnd_seed = strtoul(optarg, NULL, 10);
364             seed_set = 1;
365             break;
366         case 's':
367             outfile = optarg;
368             break;
369         case 'h':
370             usage();
371             exit(0);
372         case 'v':
373             printf("%s\n\n%s", version, legal);
374             exit(0);
375         default:
376             help(NULL);
377             exit(1);
378         }
379     }
380
381     if (!seed_set)
382         rnd_seed = pick_seed();
383     seed_prng(rnd_seed);
384     empfile_init();
385     if (emp_config(config_file) < 0)
386         exit(1);
387     empfile_fixup();
388
389     parse_args(argc - optind, argv + optind);
390
391     allocate_memory();
392     print_vars();
393
394     qprint("\n        #*# ...fairland rips open a rift in the datumplane... #*#\n\n");
395     qprint("seed is %u\n", rnd_seed);
396     try = 0;
397     do {
398         init();
399         if (try)
400             qprint("\ntry #%d (out of %d)...\n", try + 1, NUMTRIES);
401         qprint("placing capitals...\n");
402         if (!drift())
403             qprint("unstable drift\n");
404         qprint("growing continents...\n");
405         done = grow_continents();
406         if (!done)
407             continue;
408         qprint("growing islands:");
409         done = grow_islands();
410     } while (!done && ++try < NUMTRIES);
411     if (!done) {
412         fprintf(stderr, "%s: world not large enough for this much land\n",
413                 program_name);
414         exit(1);
415     }
416     qprint("elevating land...\n");
417     create_elevations();
418
419     qprint("writing to sectors file...\n");
420     if (!write_newcap_script())
421         exit(1);
422     if (chdir(gamedir)) {
423         fprintf(stderr, "%s: can't chdir to %s (%s)\n",
424                 program_name, gamedir, strerror(errno));
425         exit(1);
426     }
427     if (!ef_open(EF_SECTOR, EFF_MEM | EFF_NOTIME))
428         exit(1);
429     write_sects();
430     if (!ef_close(EF_SECTOR))
431         exit(1);
432
433     output();
434     qprint("\n\nA script for adding all the countries can be found in \"%s\".\n",
435            outfile);
436     exit(0);
437 }
438
439 static void
440 print_vars(void)
441 {
442     if (quiet)
443         return;
444     puts("Creating a planet with:\n");
445     printf("%d continents\n", nc);
446     printf("continent size: %d\n", sc);
447     printf("number of islands: %d\n", ni);
448     printf("average size of islands: %d\n", is);
449     printf("spike: %d%%\n", sp);
450     printf("%d%% of land is mountain (each continent will have %d mountains)\n",
451            pm, (pm * sc) / 100);
452     printf("minimum distance between continents: %d\n", di);
453     printf("minimum distance from islands to continents: %d\n", id);
454     printf("World dimensions: %dx%d\n", WORLD_X, WORLD_Y);
455 }
456
457 static void
458 qprint(const char *const fmt, ...)
459 {
460     va_list ap;
461
462     if (!quiet) {
463         va_start(ap, fmt);
464         vfprintf(stdout, fmt, ap);
465         va_end(ap);
466     }
467 }
468
469 static void
470 help(char *complaint)
471 {
472     if (complaint)
473         fprintf(stderr, "%s: %s\n", program_name, complaint);
474     fprintf(stderr, "Try -h for help.\n");
475 }
476
477 static void
478 usage(void)
479 {
480     printf("Usage: %s [OPTION]... NC SC [NI] [IS] [SP] [PM] [DI] [ID]\n"
481            "  -e CONFIG-FILE  configuration file\n"
482            "                  (default %s)\n"
483            "  -i              islands may merge\n"
484            "  -q              quiet\n"
485            "  -R SEED         seed for random number generator\n"
486            "  -s SCRIPT       name of script to create (default %s)\n"
487            "  -h              display this help and exit\n"
488            "  -v              display version information and exit\n"
489            "  NC              number of continents\n"
490            "  SC              continent size\n"
491            "  NI              number of islands (default NC)\n"
492            "  IS              average island size (default SC/2)\n"
493            "  SP              spike percentage: 0 = round, 100 = snake (default %d)\n"
494            "  PM              percentage of land that is mountain (default %d)\n"
495            "  DI              minimum distance between continents (default %d)\n"
496            "  ID              minimum distance from islands to continents (default %d)\n",
497            program_name, dflt_econfig, DEFAULT_OUTFILE_NAME,
498            DEFAULT_SPIKE, DEFAULT_MOUNTAIN, DEFAULT_CONTDIST, DEFAULT_ISLDIST);
499 }
500
501 static void
502 parse_args(int argc, char *argv[])
503 {
504     int dist_max = mapdist(0, 0, WORLD_X / 2, WORLD_Y / 2);
505
506     if (argc < 2) {
507         help("missing arguments");
508         exit(1);
509     }
510     if (argc > 8) {
511         help("too many arguments");
512         exit(1);
513     }
514     nc = atoi(argv[0]);
515     if (nc < 1) {
516         fprintf(stderr, "%s: number of continents must be > 0\n",
517                 program_name);
518         exit(1);
519     }
520
521     sc = atoi(argv[1]);
522     if (sc < 2) {
523         fprintf(stderr, "%s: size of continents must be > 1\n",
524                 program_name);
525         exit(1);
526     }
527
528     ni = nc;
529     is = sc / 2;
530
531     if (argc > 2)
532         ni = atoi(argv[2]);
533     if (ni < 0) {
534         fprintf(stderr, "%s: number of islands must be >= 0\n",
535                 program_name);
536         exit(1);
537     }
538     if (ni % nc) {
539         fprintf(stderr, "%s: number of islands must be a multiple of"
540                 " the number of continents\n",
541                 program_name);
542         exit(1);
543     }
544
545     if (argc > 3)
546         is = atoi(argv[3]);
547     if (is < 1) {
548         fprintf(stderr, "%s: size of islands must be > 0\n",
549                 program_name);
550         exit(1);
551     }
552
553     if (argc > 4)
554         sp = atoi(argv[4]);
555     if (sp < 0 || sp > 100) {
556         fprintf(stderr,
557                 "%s: spike percentage must be between 0 and 100\n",
558                 program_name);
559         exit(1);
560     }
561
562     if (argc > 5)
563         pm = atoi(argv[5]);
564     if (pm < 0 || pm > 100) {
565         fprintf(stderr,
566                 "%s: mountain percentage must be between 0 and 100\n",
567                 program_name);
568         exit(1);
569     }
570
571     if (argc > 6)
572         di = atoi(argv[6]);
573     if (di < 0) {
574         fprintf(stderr, "%s: distance between continents must be >= 0\n",
575                 program_name);
576         exit(1);
577     }
578     if (di > dist_max) {
579         fprintf(stderr, "%s: distance between continents too large\n",
580                 program_name);
581         exit(1);
582     }
583
584     if (argc > 7)
585         id = atoi(argv[7]);
586     if (id < 0) {
587         fprintf(stderr,
588                 "%s: distance from islands to continents must be >= 0\n",
589                 program_name);
590         exit(1);
591     }
592     if (id > dist_max) {
593         fprintf(stderr,
594                 "%s: distance from islands to continents too large\n",
595                 program_name);
596         exit(1);
597     }
598 }
599
600 /****************************************************************************
601   VARIABLE INITIALIZATION
602 ****************************************************************************/
603
604 static void
605 allocate_memory(void)
606 {
607     int i;
608
609     cap = malloc(nc * sizeof(*cap));
610     own = malloc(WORLD_SZ() * sizeof(*own));
611     adj_land = malloc(WORLD_SZ() * sizeof(*adj_land));
612     elev = calloc(WORLD_SZ(), sizeof(*elev));
613     xzone = malloc(WORLD_SZ() * sizeof(*xzone));
614     seen = calloc(WORLD_SZ(), sizeof(*seen));
615     closest = malloc(WORLD_SZ() * sizeof(*closest));
616     distance = malloc(WORLD_SZ() * sizeof(*distance));
617     bfs_queue = malloc(WORLD_SZ() * sizeof(*bfs_queue));
618     isecs = calloc(nc + ni, sizeof(int));
619     sect = malloc((nc + ni) * sizeof(*sect));
620     for (i = 0; i < nc; i++)
621         sect[i] = malloc(sc * sizeof(**sect));
622     for (i = nc; i < nc + ni; i++)
623         sect[i] = malloc(is * 2 * sizeof(**sect));
624 }
625
626 static void
627 init(void)
628 {
629     int i;
630
631     for (i = 0; i < WORLD_SZ(); i++)
632         own[i] = -1;
633     memset(adj_land, 0, WORLD_SZ() * sizeof(*adj_land));
634 }
635
636 /****************************************************************************
637   DRIFT THE CAPITALS UNTIL THEY ARE AS FAR AWAY FROM EACH OTHER AS POSSIBLE
638 ****************************************************************************/
639
640 /*
641  * How isolated is capital @j at @newx,@newy?
642  * Return the distance to the closest other capital.
643  */
644 static int
645 iso(int j, int newx, int newy)
646 {
647     int d = INT_MAX;
648     int i, md;
649
650     for (i = 0; i < nc; ++i) {
651         if (i == j)
652             continue;
653         md = mapdist(cap[i].x, cap[i].y, newx, newy);
654         if (md < d)
655             d = md;
656     }
657
658     return d;
659 }
660
661 /*
662  * Drift the capitals
663  * Return 1 for a stable drift, 0 for an unstable one.
664  */
665 static int
666 drift(void)
667 {
668     int turns, i;
669
670     for (i = 0; i < nc; i++) {
671         cap[i].y = (2 * i) / WORLD_X;
672         cap[i].x = (2 * i) % WORLD_X + cap[i].y % 2;
673         if (cap[i].y >= WORLD_Y) {
674             fprintf(stderr,
675                     "%s: world not big enough for all the continents\n",
676                     program_name);
677             exit(1);
678         }
679     }
680
681     for (turns = 0; turns < DRIFT_MAX; ++turns) {
682         if (stable(turns))
683             return 1;
684         for (i = 0; i < nc; ++i)
685             fl_move(i);
686     }
687     return 0;
688 }
689
690 /*
691  * Has the drift stabilized?
692  * @turns is the number of turns so far.
693  */
694 static int
695 stable(int turns)
696 {
697     static int mc[STABLE_CYCLE];
698     int i, isod, d = 0, stab = 1;
699
700     if (!turns) {
701         for (i = 0; i < STABLE_CYCLE; i++)
702             mc[i] = i;
703     }
704
705     if (turns <= DRIFT_BEFORE_CHECK)
706         return 0;
707
708     for (i = 0; i < nc; ++i) {
709         isod = iso(i, cap[i].x, cap[i].y);
710         if (isod > d)
711             d = isod;
712     }
713
714     for (i = 0; i < STABLE_CYCLE; ++i)
715         if (d != mc[i])
716             stab = 0;
717
718     mc[turns % STABLE_CYCLE] = d;
719     return stab;
720 }
721
722 /* This routine does the actual drifting
723 */
724
725 static void
726 fl_move(int j)
727 {
728     int dir, i, newx, newy;
729
730     dir = DIR_L + roll0(6);
731     for (i = 0; i < 6; i++) {
732         if (dir > DIR_LAST)
733             dir -= 6;
734         newx = new_x(cap[j].x + diroff[dir][0]);
735         newy = new_y(cap[j].y + diroff[dir][1]);
736         dir++;
737         if (iso(j, newx, newy) >= iso(j, cap[j].x, cap[j].y)) {
738             cap[j].x = newx;
739             cap[j].y = newy;
740             return;
741         }
742     }
743 }
744
745 /****************************************************************************
746   GROW THE CONTINENTS
747 ****************************************************************************/
748
749 static int
750 is_coastal(int x, int y)
751 {
752     return adj_land[XYOFFSET(x, y)]
753         != (1u << (DIR_LAST + 1)) - (1u << DIR_FIRST);
754 }
755
756 struct hexagon_iter {
757     int dir, i, n;
758 };
759
760 /*
761  * Start iterating around @x0,@y0 at distance @d.
762  * Set *x,*y to coordinates of the first sector.
763  */
764 static inline void
765 hexagon_first(struct hexagon_iter *iter, int x0, int y0, int n,
766               int *x, int *y)
767 {
768     *x = new_x(x0 - 2 * n);
769     *y = y0;
770     iter->dir = DIR_FIRST;
771     iter->i = 0;
772     iter->n = n;
773 }
774
775 /*
776  * Continue iteration started with hexagon_first().
777  * Set *x,*y to coordinates of the next sector.
778  * Return whether we're back at the first sector, i.e. iteration is
779  * complete.
780  */
781 static inline int
782 hexagon_next(struct hexagon_iter *iter, int *x, int *y)
783 {
784     *x = new_x(*x + diroff[iter->dir][0]);
785     *y = new_y(*y + diroff[iter->dir][1]);
786     iter->i++;
787     if (iter->i == iter->n) {
788         iter->i = 0;
789         iter->dir++;
790     }
791     return iter->dir <= DIR_LAST;
792 }
793
794 /*
795  * Is @x,@y in no exclusive zone other than perhaps @c's?
796  */
797 static int
798 xzone_ok(int c, int x, int y)
799 {
800     int off = XYOFFSET(x, y);
801
802     return xzone[off] == c || xzone[off] == -1;
803 }
804
805 /*
806  * Add sectors within distance @dist of @x,@y to @c's exclusive zone.
807  */
808 static void
809 xzone_around_sector(int c, int x, int y, int dist)
810 {
811     int d, x1, y1, off;
812     struct hexagon_iter hexit;
813
814     assert(xzone_ok(c, x, y));
815
816     xzone[XYOFFSET(x, y)] = c;
817     for (d = 1; d <= dist; d++) {
818         hexagon_first(&hexit, x, y, d, &x1, &y1);
819         do {
820             off = XYOFFSET(x1, y1);
821             if (xzone[off] == -1)
822                 xzone[off] = c;
823             else if (xzone[off] != c)
824                 xzone[off] = -2;
825         } while (hexagon_next(&hexit, &x1, &y1));
826     }
827 }
828
829 /*
830  * Add sectors within distance @dist to island @c's exclusive zone.
831  */
832 static void
833 xzone_around_island(int c, int dist)
834 {
835     int i;
836
837     for (i = 0; i < isecs[c]; i++)
838         xzone_around_sector(c, sect[c][i].x, sect[c][i].y, dist);
839 }
840
841 /*
842  * Initialize exclusive zones around @n islands.
843  */
844 static void
845 xzone_init(int n)
846 {
847     int i, c;
848
849     for (i = 0; i < WORLD_SZ(); i++)
850         xzone[i] = -1;
851
852     for (c = 0; c < n; c++)
853         xzone_around_island(c, id);
854 }
855
856 /*
857  * Initialize breadth-first search.
858  */
859 static void
860 bfs_init(void)
861 {
862     int i;
863
864     for (i = 0; i < WORLD_SZ(); i++) {
865         closest[i] = -1;
866         distance[i] = USHRT_MAX;
867     }
868
869     bfs_queue_head = bfs_queue_tail = 0;
870 }
871
872 /*
873  * Add sector @x,@y to the BFS queue.
874  * It's closest to @c, with distance @dist.
875  */
876 static void
877 bfs_enqueue(int c, int x, int y, int dist)
878 {
879     int off = XYOFFSET(x, y);
880
881     assert(dist < distance[off]);
882     closest[off] = c;
883     distance[off] = dist;
884     bfs_queue[bfs_queue_tail] = off;
885     bfs_queue_tail++;
886     if (bfs_queue_tail >= WORLD_SZ())
887         bfs_queue_tail = 0;
888     assert(bfs_queue_tail != bfs_queue_head);
889 }
890
891 /*
892  * Search breadth-first until the queue is empty.
893  */
894 static void
895 bfs_run_queue(void)
896 {
897     int off, dist, i, noff, nx, ny;
898     coord x, y;
899
900     while (bfs_queue_head != bfs_queue_tail) {
901         off = bfs_queue[bfs_queue_head];
902         bfs_queue_head++;
903         if (bfs_queue_head >= WORLD_SZ())
904             bfs_queue_head = 0;
905         dist = distance[off] + 1;
906         sctoff2xy(&x, &y, off);
907         for (i = DIR_FIRST; i <= DIR_LAST; i++) {
908             nx = new_x(x + diroff[i][0]);
909             ny = new_y(y + diroff[i][1]);
910             noff = XYOFFSET(nx, ny);
911             if (dist < distance[noff]) {
912                 bfs_enqueue(closest[off], nx, ny, dist);
913             } else if (distance[noff] == dist) {
914                 if (closest[off] != closest[noff])
915                     closest[noff] = (natid)-1;
916             } else
917                 assert(distance[noff] < dist);
918         }
919     }
920 }
921
922 /*
923  * Add island @c's coastal sectors to the BFS queue, with distance 0.
924  */
925 static void
926 bfs_enqueue_island(int c)
927 {
928     int i;
929
930     for (i = 0; i < isecs[c]; i++) {
931         if (is_coastal(sect[c][i].x, sect[c][i].y))
932             bfs_enqueue(c, sect[c][i].x, sect[c][i].y, 0);
933     }
934 }
935
936 /*
937  * Enqueue spheres of influence borders for breadth-first search.
938  */
939 static void
940 bfs_enqueue_border(void)
941 {
942     int x, y, off, dir, nx, ny, noff;
943
944     for (y = 0; y < WORLD_Y; y++) {
945         for (x = y % 2; x < WORLD_X; x += 2) {
946             off = XYOFFSET(x, y);
947             if (distance[off] <= id + 1)
948                 continue;
949             if (closest[off] == (natid)-1)
950                 continue;
951             for (dir = DIR_FIRST; dir <= DIR_LAST; dir++) {
952                 nx = new_x(x + diroff[dir][0]);
953                 ny = new_y(y + diroff[dir][1]);
954                 noff = XYOFFSET(nx, ny);
955                 if (closest[noff] != closest[off]) {
956                     bfs_enqueue(closest[off], x, y, id + 1);
957                     break;
958                 }
959             }
960         }
961     }
962 }
963
964 /*
965  * Compute spheres of influence
966  * A continent's sphere of influence is the set of sectors closer to
967  * it than to any other continent.
968  * Set closest[XYOFFSET(x, y)] to the closest continent's number,
969  * -1 if no single continent is closest.
970  * Set distance[XYOFFSET(x, y)] to the minimum of the distance to the
971  * closest coastal land sector and the distance to just outside the
972  * sphere of influence plus @id.  For sea sectors within a continent's
973  * sphere of influence, distance[off] - id is the distance to the
974  * border of the area where additional islands can be placed.
975  */
976 static void
977 init_spheres_of_influence(void)
978 {
979     int c;
980
981     bfs_init();
982     for (c = 0; c < nc; c++)
983         bfs_enqueue_island(c);
984     bfs_run_queue();
985     bfs_enqueue_border();
986     bfs_run_queue();
987 }
988
989 /*
990  * Precompute distance to coast
991  * Set distance[XYOFFSET(x, y)] to the distance to the closest coastal
992  * land sector.
993  * Set closest[XYOFFSET(x, y)] to the closest continent's number,
994  * -1 if no single continent is closest.
995  */
996 static void
997 init_distance_to_coast(void)
998 {
999     int c;
1000
1001     bfs_init();
1002     for (c = 0; c < nc + ni; c++)
1003         bfs_enqueue_island(c);
1004     bfs_run_queue();
1005 }
1006
1007 /*
1008  * Is @x,@y in the same sphere of influence as island @c?
1009  * Always true when @c is a continent.
1010  */
1011 static int
1012 is_in_sphere(int c, int x, int y)
1013 {
1014     return c < nc || closest[XYOFFSET(x, y)] == c % nc;
1015 }
1016
1017 /*
1018  * Can island @c grow at @x,@y?
1019  */
1020 static int
1021 can_grow_at(int c, int x, int y)
1022 {
1023     return own[XYOFFSET(x, y)] == -1 && xzone_ok(c, x, y)
1024         && is_in_sphere(c, x, y);
1025 }
1026
1027 static void
1028 adj_land_update(int x, int y)
1029 {
1030     int is_land = own[XYOFFSET(x, y)] != -1;
1031     int dir, nx, ny, noff;
1032
1033     for (dir = DIR_FIRST; dir <= DIR_LAST; dir++) {
1034         nx = new_x(x + diroff[dir][0]);
1035         ny = new_y(y + diroff[dir][1]);
1036         noff = XYOFFSET(nx, ny);
1037         if (is_land)
1038             adj_land[noff] |= 1u << DIR_BACK(dir);
1039         else
1040             adj_land[noff] &= ~(1u << DIR_BACK(dir));
1041     }
1042 }
1043
1044 static void
1045 add_sector(int c, int x, int y)
1046 {
1047     int off = XYOFFSET(x, y);
1048
1049     assert(own[off] == -1);
1050     xzone_around_sector(c, x, y, c < nc ? di : DISTINCT_ISLANDS ? id : 0);
1051     sect[c][isecs[c]].x = x;
1052     sect[c][isecs[c]].y = y;
1053     isecs[c]++;
1054     own[off] = c;
1055     adj_land_update(x, y);
1056 }
1057
1058 static int
1059 grow_weight(int c, int x, int y, int spike)
1060 {
1061     int n, b;
1062
1063     /*
1064      * #Land neighbors is #bits set in adj_land[].
1065      * Count them Brian Kernighan's way.
1066      */
1067     n = 0;
1068     for (b = adj_land[XYOFFSET(x, y)]; b; b &= b - 1)
1069         n++;
1070     assert(n > 0 && n < 7);
1071
1072     if (spike)
1073         return (6 - n) * (6 - n);
1074
1075     return n * n * n;
1076 }
1077
1078 static int
1079 grow_one_sector(int c)
1080 {
1081     int spike = roll0(100) < sp;
1082     int wsum, newx, newy, i, x, y, off, dir, nx, ny, noff, w;
1083
1084     assert(cur_seen < UINT_MAX);
1085     cur_seen++;
1086     wsum = 0;
1087     newx = newy = -1;
1088
1089     for (i = 0; i < isecs[c]; i++) {
1090         x = sect[c][i].x;
1091         y = sect[c][i].y;
1092         off = XYOFFSET(x, y);
1093
1094         for (dir = DIR_FIRST; dir <= DIR_LAST; dir++) {
1095             if (adj_land[off] & (1u << dir))
1096                 continue;
1097             nx = new_x(x + diroff[dir][0]);
1098             ny = new_y(y + diroff[dir][1]);
1099             noff = XYOFFSET(nx, ny);
1100             if (seen[noff] == cur_seen)
1101                 continue;
1102             assert(seen[noff] < cur_seen);
1103             seen[noff] = cur_seen;
1104             if (!can_grow_at(c, nx, ny))
1105                 continue;
1106             w = grow_weight(c, nx, ny, spike);
1107             assert(wsum < INT_MAX - w);
1108             wsum += w;
1109             if (roll0(wsum) < w) {
1110                 newx = nx;
1111                 newy = ny;
1112             }
1113         }
1114     }
1115
1116     if (!wsum)
1117         return 0;
1118
1119     add_sector(c, newx, newy);
1120     return 1;
1121 }
1122
1123 /*
1124  * Grow the continents.
1125  * Return 1 on success, 0 on error.
1126  */
1127 static int
1128 grow_continents(void)
1129 {
1130     int done = 1;
1131     int c, secs;
1132
1133     xzone_init(0);
1134
1135     for (c = 0; c < nc; ++c) {
1136         isecs[c] = 0;
1137         if (!can_grow_at(c, cap[c].x, cap[c].y)
1138             || !can_grow_at(c, new_x(cap[c].x + 2), cap[c].y)) {
1139             done = 0;
1140             continue;
1141         }
1142         add_sector(c, cap[c].x, cap[c].y);
1143         add_sector(c, new_x(cap[c].x + 2), cap[c].y);
1144     }
1145
1146     if (!done) {
1147         qprint("No room for continents\n");
1148         return 0;
1149     }
1150
1151     for (secs = 2; secs < sc && done; secs++) {
1152         for (c = 0; c < nc; ++c) {
1153             if (!grow_one_sector(c))
1154                 done = 0;
1155         }
1156     }
1157
1158     if (!done)
1159         qprint("Only managed to grow %d out of %d sectors.\n",
1160                secs - 1, sc);
1161     return done;
1162 }
1163
1164 /****************************************************************************
1165   GROW THE ISLANDS
1166 ****************************************************************************/
1167
1168 /*
1169  * Place additional island @c's first sector.
1170  * Return 1 on success, 0 on error.
1171  */
1172 static int
1173 place_island(int c, int isiz)
1174 {
1175     int n, x, y, d, w, newx, newy;
1176
1177     n = 0;
1178
1179     for (y = 0; y < WORLD_Y; y++) {
1180         for (x = y % 2; x < WORLD_X; x += 2) {
1181             if (can_grow_at(c, x, y)) {
1182                 d = distance[XYOFFSET(x, y)];
1183                 assert(d > id);
1184                 w = (d - id) * (d - id);
1185                 n += MIN(w, (isiz + 2) / 3);
1186                 if (roll0(n) < w) {
1187                     newx = x;
1188                     newy = y;
1189                 }
1190             }
1191         }
1192     }
1193
1194     if (n)
1195         add_sector(c, newx, newy);
1196     return n;
1197 }
1198
1199 static int
1200 int_cmp(const void *a, const void *b)
1201 {
1202     return *(int *)b - *(int *)a;
1203 }
1204
1205 static int *
1206 size_islands(void)
1207 {
1208     int n = ni / nc;
1209     int *isiz = malloc(n * sizeof(*isiz));
1210     int r0, r1, i;
1211
1212     isiz[0] = n * is;
1213     r1 = roll0(is);
1214     for (i = 1; i < n; i++) {
1215         r0 = r1;
1216         r1 = roll0(is);
1217         isiz[i] = is + r1 - r0;
1218         isiz[0] -= isiz[i];
1219     }
1220
1221     qsort(isiz, n, sizeof(*isiz), int_cmp);
1222     return isiz;
1223 }
1224
1225 /*
1226  * Grow the additional islands.
1227  * Return 1 on success, 0 on error.
1228  */
1229 static int
1230 grow_islands(void)
1231 {
1232     int *island_size = size_islands();
1233     int xzone_valid = 0;
1234     int carry = 0;
1235     int i, j, c, done, secs, isiz, x, y;
1236
1237     init_spheres_of_influence();
1238
1239     for (i = 0; i < ni / nc; i++) {
1240         c = nc + i * nc;
1241
1242         if (!xzone_valid)
1243             xzone_init(c);
1244
1245         carry += island_size[i];
1246         isiz = MIN(2 * is, carry);
1247
1248         for (j = 0; j < nc; j++) {
1249             isecs[c + j] = 0;
1250             if (!place_island(c + j, isiz)) {
1251                 qprint("\nNo room for island #%d\n", c - nc + j + 1);
1252                 free(island_size);
1253                 return 0;
1254             }
1255         }
1256
1257         done = 1;
1258         for (secs = 1; secs < isiz && done; secs++) {
1259             for (j = 0; j < nc; j++) {
1260                 if (!grow_one_sector(c + j))
1261                     done = 0;
1262             }
1263         }
1264
1265         if (!done) {
1266             secs--;
1267             for (j = 0; j < nc; j++) {
1268                 if (isecs[c + j] != secs) {
1269                     isecs[c + j]--;
1270                     assert(isecs[c + j] == secs);
1271                     x = sect[c + j][secs].x;
1272                     y = sect[c + j][secs].y;
1273                     own[XYOFFSET(x, y)] = -1;
1274                     adj_land_update(x, y);
1275                 }
1276             }
1277             xzone_valid = 0;
1278         }
1279
1280         for (j = 0; j < nc; j++)
1281             qprint(" %d(%d)", c - nc + j + 1, isecs[c + j]);
1282
1283         carry -= secs;
1284     }
1285
1286     free(island_size);
1287     qprint("\n");
1288
1289     if (carry)
1290         qprint("Only managed to grow %d out of %d island sectors.\n",
1291                is * ni - carry * nc, is * ni);
1292
1293     return 1;
1294 }
1295
1296 /****************************************************************************
1297   CREATE ELEVATIONS
1298 ****************************************************************************/
1299 static void
1300 create_elevations(void)
1301 {
1302     elevate_prep();
1303     elevate_land();
1304     elevate_sea();
1305 }
1306
1307 static int
1308 elev_cmp(const void *p, const void *q)
1309 {
1310     int a = *(int *)p;
1311     int b = *(int *)q;
1312     int delev = elev[a] - elev[b];
1313
1314     return delev ? delev : a - b;
1315 }
1316
1317 static void
1318 elevate_prep(void)
1319 {
1320     int n = WORLD_SZ() * 8;
1321     int off0, r, sign, elevation, d, x1, y1, off1;
1322     coord x0, y0;
1323     struct hexagon_iter hexit;
1324
1325     init_distance_to_coast();
1326
1327     while (n > 0) {
1328         off0 = roll0(WORLD_SZ());
1329         sctoff2xy(&x0, &y0, off0);
1330         if (own[off0] == -1) {
1331             r = roll(MIN(3, distance[off0]));
1332             sign = -1;
1333         } else {
1334             r = roll(MIN(3, distance[off0]) + 1);
1335             sign = 1;
1336         }
1337         elevation = elev[off0] + sign * r * r;
1338         elev[off0] = LIMIT_TO(elevation, SHRT_MIN, SHRT_MAX);
1339         n--;
1340         for (d = 1; d < r; d++) {
1341             hexagon_first(&hexit, x0, y0, d, &x1, &y1);
1342             do {
1343                 off1 = XYOFFSET(x1, y1);
1344                 elevation = elev[off1] + sign * (r * r - d * d);
1345                 elev[off1] = LIMIT_TO(elevation, SHRT_MIN, SHRT_MAX);
1346                 n--;
1347             } while (hexagon_next(&hexit, &x1, &y1));
1348         }
1349     }
1350 }
1351
1352 static void
1353 elevate_land(void)
1354 {
1355     int *off = malloc(MAX(sc, is * 2) * sizeof(*off));
1356     int max_nm = (pm * MAX(sc, is * 2)) / 100;
1357     int c, nm, i0, n, i;
1358     double elevation, delta;
1359
1360     for (c = 0; c < nc + ni; c++) {
1361         nm = (pm * isecs[c]) / 100;
1362         i0 = c < nc ? 2 : 0;
1363         n = isecs[c] - i0;
1364         for (i = 0; i < i0; i++)
1365             elev[XYOFFSET(sect[c][i].x, sect[c][i].y)] = PLATMIN;
1366         for (i = 0; i < n; i++)
1367             off[i] = XYOFFSET(sect[c][i0 + i].x, sect[c][i0 + i].y);
1368         qsort(off, n, sizeof(*off), elev_cmp);
1369         delta = (double)(HIGHMIN - LANDMIN - 1) / (n - nm - 1);
1370         elevation = LANDMIN;
1371         for (i = 0; i < n - nm; i++) {
1372             elev[off[i]] = (int)(elevation + 0.5);
1373             elevation += delta;
1374         }
1375         elevation = HIGHMIN;
1376         delta = (127.0 - HIGHMIN) / max_nm;
1377         for (; i < n; i++) {
1378             elevation += delta;
1379             elev[off[i]] = (int)(elevation + 0.5);
1380         }
1381     }
1382
1383     free(off);
1384 }
1385
1386 static void
1387 elevate_sea(void)
1388 {
1389     int i, min;
1390
1391     min = 0;
1392     for (i = 0; i < WORLD_SZ(); i++) {
1393         if (elev[i] < min)
1394             min = elev[i];
1395     }
1396
1397     for (i = 0; i < WORLD_SZ(); i++) {
1398         if (elev[i] < 0)
1399             elev[i] = -1 - 126 * elev[i] / min;
1400     }
1401 }
1402
1403 static int
1404 elev_to_sct_type(int elevation)
1405 {
1406     if (elevation < LANDMIN)
1407         return SCT_WATER;
1408     if (elevation < HIGHMIN)
1409         return SCT_RURAL;
1410     return SCT_MOUNT;
1411 }
1412
1413 /****************************************************************************
1414   ADD THE RESOURCES
1415 ****************************************************************************/
1416
1417 /*
1418  * Map elevation @elev to a resource value according to @conf.
1419  * This is a linear interpolation on the data points in @conf.
1420  */
1421 static int
1422 elev_to_resource(int elev, struct resource_point conf[])
1423 {
1424     int i, elev1, elev2, delev, res1, res2, dres;
1425
1426     for (i = 1; elev > conf[i].elev; i++) ;
1427     assert(conf[i - 1].elev <= elev);
1428
1429     elev1 = conf[i - 1].elev;
1430     elev2 = conf[i].elev;
1431     delev = elev2 - elev1;
1432     res1 = conf[i - 1].res;
1433     res2 = conf[i].res;
1434     dres = res2 - res1;
1435     return (int)(res1 + (double)((elev - elev1) * dres) / delev);
1436 }
1437
1438 static void
1439 add_resources(struct sctstr *sct)
1440 {
1441     sct->sct_min = elev_to_resource(sct->sct_elev, iron_conf);
1442     sct->sct_gmin = elev_to_resource(sct->sct_elev, gold_conf);
1443     sct->sct_fertil = elev_to_resource(sct->sct_elev, fert_conf);
1444     sct->sct_oil = elev_to_resource(sct->sct_elev, oil_conf);
1445     sct->sct_uran = elev_to_resource(sct->sct_elev, uran_conf);
1446 }
1447
1448 /****************************************************************************
1449   DESIGNATE THE SECTORS
1450 ****************************************************************************/
1451
1452 static void
1453 write_sects(void)
1454 {
1455     struct sctstr *sp;
1456     int i;
1457
1458     for (i = 0; i < WORLD_SZ(); i++) {
1459         sp = getsectid(i);
1460         sp->sct_elev = elev[i];
1461         sp->sct_type = elev_to_sct_type(sp->sct_elev);
1462         sp->sct_newtype = sp->sct_type;
1463         sp->sct_dterr = own[i] + 1;
1464         sp->sct_coastal = is_coastal(sp->sct_x, sp->sct_y);
1465         add_resources(sp);
1466     }
1467 }
1468
1469 /****************************************************************************
1470   PRINT A PICTURE OF THE MAP TO YOUR SCREEN
1471 ****************************************************************************/
1472 static void
1473 output(void)
1474 {
1475     int sx, sy, x, y, off, c, type;
1476
1477     if (quiet == 0) {
1478         for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1479             y = YNORM(sy);
1480             puts("");
1481             if (y % 2)
1482                 printf(" ");
1483             for (sx = -WORLD_X / 2 + y % 2; sx < WORLD_X / 2; sx += 2) {
1484                 x = XNORM(sx);
1485                 off = XYOFFSET(x, y);
1486                 c = own[off];
1487                 type = elev_to_sct_type(elev[off]);
1488                 if (type == SCT_WATER)
1489                     printf(". ");
1490                 else if (type == SCT_MOUNT)
1491                     printf("^ ");
1492                 else if (c >= nc)
1493                     printf("%% ");
1494                 else {
1495                     assert(0 <= c && c < nc);
1496                     if ((x == cap[c].x || x == new_x(cap[c].x + 2))
1497                         && y == cap[c].y)
1498                         printf("%c ", numletter[c % 62]);
1499                     else
1500                         printf("# ");
1501                 }
1502             }
1503         }
1504     }
1505 }
1506
1507 /*
1508  * Print a map to help visualize own[].
1509  * This is for debugging.
1510  */
1511 void
1512 print_own_map(void)
1513 {
1514     int sx, sy, x, y, off;
1515
1516     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1517         y = YNORM(sy);
1518         printf("%4d ", sy);
1519         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1520             x = XNORM(sx);
1521             off = XYOFFSET(x, y);
1522             if ((x + y) & 1)
1523                 putchar(' ');
1524             else if (own[off] == -1)
1525                 putchar('.');
1526             else
1527                 putchar(numletter[own[off] % 62]);
1528         }
1529         putchar('\n');
1530     }
1531 }
1532
1533 /*
1534  * Print a map to help visualize elev[].
1535  * This is for debugging.  It expects the terminal to understand
1536  * 24-bit color escape sequences \e[48;2;$red;$green;$blue;m.
1537  */
1538 void
1539 print_elev_map(void)
1540 {
1541     int sx, sy, x, y, off, sat;
1542
1543     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1544         y = YNORM(sy);
1545         printf("%4d ", sy);
1546         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1547             x = XNORM(sx);
1548             off = XYOFFSET(x, y);
1549             if ((x + y) & 1)
1550                 putchar(' ');
1551             else if (!elev[off])
1552                 putchar(' ');
1553             else if (elev[off] < 0) {
1554                 sat = 256 + elev[off] * 2;
1555                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, sat, 255);
1556             } else if (elev[off] < HIGHMIN / 2) {
1557                 sat = (HIGHMIN / 2 - elev[off]) * 4;
1558                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, 255, sat);
1559             } else if (elev[off] < HIGHMIN) {
1560                 sat = 128 + (HIGHMIN - elev[off]) * 2;
1561                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, sat / 2, sat / 4);
1562             } else {
1563                 sat = 128 + (elev[off] - HIGHMIN) * 2;
1564                 printf("\033[48;2;%d;%d;%dm^\033[0m", sat, sat, sat);
1565             }
1566         }
1567         putchar('\n');
1568     }
1569 }
1570
1571 /*
1572  * Print a map to help visualize xzone[].
1573  * This is for debugging.
1574  */
1575 void
1576 print_xzone_map(void)
1577 {
1578     int sx, sy, x, y, off;
1579
1580     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1581         y = YNORM(sy);
1582         printf("%4d ", sy);
1583         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1584             x = XNORM(sx);
1585             off = XYOFFSET(x, y);
1586             if ((x + y) & 1)
1587                 putchar(' ');
1588             else if (own[off] >= 0)
1589                 putchar('-');
1590             else if (xzone[off] >= 0)
1591                 putchar(numletter[xzone[off] % 62]);
1592             else {
1593                 assert(own[off] == -1);
1594                 putchar(xzone[off] == -1 ? '.' : '!');
1595             }
1596         }
1597         putchar('\n');
1598     }
1599 }
1600
1601 /*
1602  * Print a map to help visualize closest[].
1603  * This is for debugging.
1604  */
1605 void
1606 print_closest_map(void)
1607 {
1608     int sx, sy, x, y, off;
1609
1610     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1611         y = YNORM(sy);
1612         printf("%4d ", sy);
1613         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1614             x = XNORM(sx);
1615             off = XYOFFSET(x, y);
1616             if ((x + y) & 1)
1617                 putchar(' ');
1618             else if (closest[off] == (natid)-1)
1619                 putchar('.');
1620             else if (!distance[off]) {
1621                 assert(closest[off] == own[off]);
1622                 putchar('-');
1623             } else {
1624                 putchar(numletter[closest[off] % 62]);
1625             }
1626         }
1627         printf("\n");
1628     }
1629 }
1630
1631 void
1632 print_distance_map(void)
1633 {
1634     int sx, sy, x, y, off;
1635
1636     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1637         y = YNORM(sy);
1638         printf("%4d ", sy);
1639         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1640             x = XNORM(sx);
1641             off = XYOFFSET(x, y);
1642             if ((x + y) & 1)
1643                 putchar(' ');
1644             else if (closest[off] == (natid)-1)
1645                 putchar('.');
1646             else if (!distance[off]) {
1647                 assert(closest[off] == own[off]);
1648                 putchar('-');
1649             } else {
1650                 putchar(numletter[distance[off] % 62]);
1651             }
1652         }
1653         printf("\n");
1654     }
1655 }
1656
1657
1658 /***************************************************************************
1659   WRITE A SCRIPT FOR PLACING CAPITALS
1660 ****************************************************************************/
1661 static int
1662 write_newcap_script(void)
1663 {
1664     int c;
1665     FILE *script = fopen(outfile, "w");
1666
1667     if (!script) {
1668         fprintf(stderr, "%s: unable to write to %s (%s)\n",
1669                 program_name, outfile, strerror(errno));
1670         return 0;
1671     }
1672
1673     for (c = 0; c < nc; ++c) {
1674         fprintf(script, "add %d %d %d p\n", c + 1, c + 1, c + 1);
1675         fprintf(script, "newcap %d %d,%d\n", c + 1, cap[c].x, cap[c].y);
1676     }
1677     fprintf(script, "add %d visitor visitor v\n", c + 1);
1678     fclose(script);
1679     return 1;
1680 }