]> git.pond.sub.org Git - empserver/blob - src/util/fairland.c
Update copyright notice
[empserver] / src / util / fairland.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2021, 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 static void qprint(const char * const fmt, ...)
197     ATTRIBUTE((format (printf, 1, 2)));
198
199 /*
200  * Program arguments and options
201  */
202 static char *program_name;
203 static int nc, sc;              /* number and size of continents */
204 static int ni, is;              /* number and size of islands */
205 #define DEFAULT_SPIKE 10
206 static int sp = DEFAULT_SPIKE;  /* spike percentage */
207 #define DEFAULT_MOUNTAIN 0
208 static int pm = DEFAULT_MOUNTAIN; /* mountain percentage */
209 #define DEFAULT_CONTDIST 2
210 static int di = DEFAULT_CONTDIST; /* min. distance between continents */
211 #define DEFAULT_ISLDIST 1
212 static int id = DEFAULT_ISLDIST;  /* ... continents and islands */
213 /* don't let the islands crash into each other.
214    1 = don't merge, 0 = merge. */
215 static int DISTINCT_ISLANDS = 1;
216 static int quiet;
217 #define DEFAULT_OUTFILE_NAME "newcap_script"
218 static const char *outfile = DEFAULT_OUTFILE_NAME;
219
220 #define STABLE_CYCLE 4          /* stability required for perturbed capitals */
221 #define DRIFT_BEFORE_CHECK ((WORLD_X + WORLD_Y)/2)
222 #define DRIFT_MAX ((WORLD_X + WORLD_Y)*2)
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 help(char *);
309 static void usage(void);
310 static void parse_args(int argc, char *argv[]);
311 static void allocate_memory(void);
312 static void init(void);
313 static int drift(void);
314 static int grow_continents(void);
315 static void create_elevations(void);
316 static void write_sects(void);
317 static void output(void);
318 static int write_newcap_script(void);
319 static int stable(int);
320 static void elevate_prep(void);
321 static void elevate_land(void);
322 static void elevate_sea(void);
323
324 static void print_vars(void);
325 static void drift_capital(int);
326 static int grow_islands(void);
327
328 /* Debugging aids: */
329 void print_own_map(void);
330 void print_xzone_map(void);
331 void print_closest_map(void);
332 void print_distance_map(void);
333 void print_elev_map(void);
334
335
336 int
337 main(int argc, char *argv[])
338 {
339     int opt;
340     char *config_file = NULL;
341     int try, done;
342     unsigned rnd_seed = 0;
343     int seed_set = 0;
344
345     program_name = argv[0];
346
347     while ((opt = getopt(argc, argv, "e:hiqR:s:v")) != EOF) {
348         switch (opt) {
349         case 'e':
350             config_file = optarg;
351             break;
352         case 'i':
353             DISTINCT_ISLANDS = 0;
354             break;
355         case 'q':
356             quiet = 1;
357             break;
358         case 'R':
359             rnd_seed = strtoul(optarg, NULL, 10);
360             seed_set = 1;
361             break;
362         case 's':
363             outfile = optarg;
364             break;
365         case 'h':
366             usage();
367             exit(0);
368         case 'v':
369             printf("%s\n\n%s", version, legal);
370             exit(0);
371         default:
372             help(NULL);
373             exit(1);
374         }
375     }
376
377     if (!seed_set)
378         rnd_seed = pick_seed();
379     seed_prng(rnd_seed);
380     empfile_init();
381     if (emp_config(config_file) < 0)
382         exit(1);
383     empfile_fixup();
384
385     parse_args(argc - optind, argv + optind);
386
387     allocate_memory();
388     print_vars();
389
390     qprint("\n        #*# ...fairland rips open a rift in the datumplane... #*#\n\n");
391     qprint("seed is %u\n", rnd_seed);
392     try = 0;
393     do {
394         init();
395         if (try)
396             qprint("\ntry #%d (out of %d)...\n", try + 1, NUMTRIES);
397         qprint("placing capitals...\n");
398         if (!drift())
399             qprint("unstable drift\n");
400         qprint("growing continents...\n");
401         done = grow_continents();
402         if (!done)
403             continue;
404         qprint("growing islands:");
405         done = grow_islands();
406     } while (!done && ++try < NUMTRIES);
407     if (!done) {
408         fprintf(stderr, "%s: world not large enough for this much land\n",
409                 program_name);
410         exit(1);
411     }
412     qprint("elevating land...\n");
413     create_elevations();
414
415     qprint("writing to sectors file...\n");
416     if (!write_newcap_script())
417         exit(1);
418     if (chdir(gamedir)) {
419         fprintf(stderr, "%s: can't chdir to %s (%s)\n",
420                 program_name, gamedir, strerror(errno));
421         exit(1);
422     }
423     if (!ef_open(EF_SECTOR, EFF_MEM | EFF_NOTIME))
424         exit(1);
425     write_sects();
426     if (!ef_close(EF_SECTOR))
427         exit(1);
428
429     output();
430     qprint("\n\nA script for adding all the countries can be found in \"%s\".\n",
431            outfile);
432     exit(0);
433 }
434
435 static void
436 print_vars(void)
437 {
438     if (quiet)
439         return;
440     puts("Creating a planet with:\n");
441     printf("%d continents\n", nc);
442     printf("continent size: %d\n", sc);
443     printf("number of islands: %d\n", ni);
444     printf("average size of islands: %d\n", is);
445     printf("spike: %d%%\n", sp);
446     printf("%d%% of land is mountain (each continent will have %d mountains)\n",
447            pm, (pm * sc) / 100);
448     printf("minimum distance between continents: %d\n", di);
449     printf("minimum distance from islands to continents: %d\n", id);
450     printf("World dimensions: %dx%d\n", WORLD_X, WORLD_Y);
451 }
452
453 static void
454 qprint(const char *const fmt, ...)
455 {
456     va_list ap;
457
458     if (!quiet) {
459         va_start(ap, fmt);
460         vfprintf(stdout, fmt, ap);
461         va_end(ap);
462     }
463 }
464
465 static void
466 help(char *complaint)
467 {
468     if (complaint)
469         fprintf(stderr, "%s: %s\n", program_name, complaint);
470     fprintf(stderr, "Try -h for help.\n");
471 }
472
473 static void
474 usage(void)
475 {
476     printf("Usage: %s [OPTION]... NC SC [NI] [IS] [SP] [PM] [DI] [ID]\n"
477            "  -e CONFIG-FILE  configuration file\n"
478            "                  (default %s)\n"
479            "  -i              islands may merge\n"
480            "  -q              quiet\n"
481            "  -R SEED         seed for random number generator\n"
482            "  -s SCRIPT       name of script to create (default %s)\n"
483            "  -h              display this help and exit\n"
484            "  -v              display version information and exit\n"
485            "  NC              number of continents\n"
486            "  SC              continent size\n"
487            "  NI              number of islands (default NC)\n"
488            "  IS              average island size (default SC/2)\n"
489            "  SP              spike percentage: 0 = round, 100 = snake (default %d)\n"
490            "  PM              percentage of land that is mountain (default %d)\n"
491            "  DI              minimum distance between continents (default %d)\n"
492            "  ID              minimum distance from islands to continents (default %d)\n",
493            program_name, dflt_econfig, DEFAULT_OUTFILE_NAME,
494            DEFAULT_SPIKE, DEFAULT_MOUNTAIN, DEFAULT_CONTDIST, DEFAULT_ISLDIST);
495 }
496
497 static void
498 parse_args(int argc, char *argv[])
499 {
500     int dist_max = mapdist(0, 0, WORLD_X / 2, WORLD_Y / 2);
501
502     if (argc < 2) {
503         help("missing arguments");
504         exit(1);
505     }
506     if (argc > 8) {
507         help("too many arguments");
508         exit(1);
509     }
510     nc = atoi(argv[0]);
511     if (nc < 1) {
512         fprintf(stderr, "%s: number of continents must be > 0\n",
513                 program_name);
514         exit(1);
515     }
516
517     sc = atoi(argv[1]);
518     if (sc < 2) {
519         fprintf(stderr, "%s: size of continents must be > 1\n",
520                 program_name);
521         exit(1);
522     }
523
524     ni = nc;
525     is = sc / 2;
526
527     if (argc > 2)
528         ni = atoi(argv[2]);
529     if (ni < 0) {
530         fprintf(stderr, "%s: number of islands must be >= 0\n",
531                 program_name);
532         exit(1);
533     }
534     if (ni % nc) {
535         fprintf(stderr, "%s: number of islands must be a multiple of"
536                 " the number of continents\n",
537                 program_name);
538         exit(1);
539     }
540
541     if (argc > 3)
542         is = atoi(argv[3]);
543     if (is < 1) {
544         fprintf(stderr, "%s: size of islands must be > 0\n",
545                 program_name);
546         exit(1);
547     }
548
549     if (argc > 4)
550         sp = atoi(argv[4]);
551     if (sp < 0 || sp > 100) {
552         fprintf(stderr,
553                 "%s: spike percentage must be between 0 and 100\n",
554                 program_name);
555         exit(1);
556     }
557
558     if (argc > 5)
559         pm = atoi(argv[5]);
560     if (pm < 0 || pm > 100) {
561         fprintf(stderr,
562                 "%s: mountain percentage must be between 0 and 100\n",
563                 program_name);
564         exit(1);
565     }
566
567     if (argc > 6)
568         di = atoi(argv[6]);
569     if (di < 0) {
570         fprintf(stderr, "%s: distance between continents must be >= 0\n",
571                 program_name);
572         exit(1);
573     }
574     if (di > dist_max) {
575         fprintf(stderr, "%s: distance between continents too large\n",
576                 program_name);
577         exit(1);
578     }
579
580     if (argc > 7)
581         id = atoi(argv[7]);
582     if (id < 0) {
583         fprintf(stderr,
584                 "%s: distance from islands to continents must be >= 0\n",
585                 program_name);
586         exit(1);
587     }
588     if (id > dist_max) {
589         fprintf(stderr,
590                 "%s: distance from islands to continents too large\n",
591                 program_name);
592         exit(1);
593     }
594 }
595
596
597 /*
598  * Variable initialization
599  */
600
601 static void
602 allocate_memory(void)
603 {
604     int i;
605
606     cap = malloc(nc * sizeof(*cap));
607     own = malloc(WORLD_SZ() * sizeof(*own));
608     adj_land = malloc(WORLD_SZ() * sizeof(*adj_land));
609     elev = calloc(WORLD_SZ(), sizeof(*elev));
610     xzone = malloc(WORLD_SZ() * sizeof(*xzone));
611     seen = calloc(WORLD_SZ(), sizeof(*seen));
612     closest = malloc(WORLD_SZ() * sizeof(*closest));
613     distance = malloc(WORLD_SZ() * sizeof(*distance));
614     bfs_queue = malloc(WORLD_SZ() * sizeof(*bfs_queue));
615     isecs = calloc(nc + ni, sizeof(int));
616     sect = malloc((nc + ni) * sizeof(*sect));
617     for (i = 0; i < nc; i++)
618         sect[i] = malloc(sc * sizeof(**sect));
619     for (i = nc; i < nc + ni; i++)
620         sect[i] = malloc(is * 2 * sizeof(**sect));
621 }
622
623 static void
624 init(void)
625 {
626     int i;
627
628     for (i = 0; i < WORLD_SZ(); i++)
629         own[i] = -1;
630     memset(adj_land, 0, WORLD_SZ() * sizeof(*adj_land));
631 }
632
633
634 /*
635  * Drift the capitals until they are as far away from each other as possible
636  */
637
638 /*
639  * How isolated is capital @j at @newx,@newy?
640  * Return the distance to the closest other capital.
641  */
642 static int
643 iso(int j, int newx, int newy)
644 {
645     int d = INT_MAX;
646     int i, md;
647
648     for (i = 0; i < nc; ++i) {
649         if (i == j)
650             continue;
651         md = mapdist(cap[i].x, cap[i].y, newx, newy);
652         if (md < d)
653             d = md;
654     }
655
656     return d;
657 }
658
659 /*
660  * Drift the capitals
661  * Return 1 for a stable drift, 0 for an unstable one.
662  */
663 static int
664 drift(void)
665 {
666     int turns, i;
667
668     for (i = 0; i < nc; i++) {
669         cap[i].y = (2 * i) / WORLD_X;
670         cap[i].x = (2 * i) % WORLD_X + cap[i].y % 2;
671         if (cap[i].y >= WORLD_Y) {
672             fprintf(stderr,
673                     "%s: world not big enough for all the continents\n",
674                     program_name);
675             exit(1);
676         }
677     }
678
679     for (turns = 0; turns < DRIFT_MAX; ++turns) {
680         if (stable(turns))
681             return 1;
682         for (i = 0; i < nc; ++i)
683             drift_capital(i);
684     }
685     return 0;
686 }
687
688 /*
689  * Has the drift stabilized?
690  * @turns is the number of turns so far.
691  */
692 static int
693 stable(int turns)
694 {
695     static int mc[STABLE_CYCLE];
696     int i, isod, d = 0, stab = 1;
697
698     if (!turns) {
699         for (i = 0; i < STABLE_CYCLE; i++)
700             mc[i] = i;
701     }
702
703     if (turns <= DRIFT_BEFORE_CHECK)
704         return 0;
705
706     for (i = 0; i < nc; ++i) {
707         isod = iso(i, cap[i].x, cap[i].y);
708         if (isod > d)
709             d = isod;
710     }
711
712     for (i = 0; i < STABLE_CYCLE; ++i)
713         if (d != mc[i])
714             stab = 0;
715
716     mc[turns % STABLE_CYCLE] = d;
717     return stab;
718 }
719
720 /*
721  * Drift capital @j.
722  * Move it to an adjacent sector where it is at least as isolated.
723 */
724 static void
725 drift_capital(int j)
726 {
727     int dir, i, newx, newy;
728
729     dir = DIR_L + roll0(6);
730     for (i = 0; i < 6; i++) {
731         if (dir > DIR_LAST)
732             dir -= 6;
733         newx = new_x(cap[j].x + diroff[dir][0]);
734         newy = new_y(cap[j].y + diroff[dir][1]);
735         dir++;
736         if (iso(j, newx, newy) >= iso(j, cap[j].x, cap[j].y)) {
737             cap[j].x = newx;
738             cap[j].y = newy;
739             return;
740         }
741     }
742 }
743
744
745 /*
746  * Grow land
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 grow_weight(int c, int x, int y, int spike)
1059 {
1060     int n, b;
1061
1062     /*
1063      * #Land neighbors is #bits set in adj_land[].
1064      * Count them Brian Kernighan's way.
1065      */
1066     n = 0;
1067     for (b = adj_land[XYOFFSET(x, y)]; b; b &= b - 1)
1068         n++;
1069     assert(n > 0 && n < 7);
1070
1071     if (spike)
1072         return (6 - n) * (6 - n);
1073
1074     return n * n * n;
1075 }
1076
1077 static int
1078 grow_one_sector(int c)
1079 {
1080     int spike = roll0(100) < sp;
1081     int wsum, newx, newy, i, x, y, off, dir, nx, ny, noff, w;
1082
1083     assert(cur_seen < UINT_MAX);
1084     cur_seen++;
1085     wsum = 0;
1086     newx = newy = -1;
1087
1088     for (i = 0; i < isecs[c]; i++) {
1089         x = sect[c][i].x;
1090         y = sect[c][i].y;
1091         off = XYOFFSET(x, y);
1092
1093         for (dir = DIR_FIRST; dir <= DIR_LAST; dir++) {
1094             if (adj_land[off] & (1u << dir))
1095                 continue;
1096             nx = new_x(x + diroff[dir][0]);
1097             ny = new_y(y + diroff[dir][1]);
1098             noff = XYOFFSET(nx, ny);
1099             if (seen[noff] == cur_seen)
1100                 continue;
1101             assert(seen[noff] < cur_seen);
1102             seen[noff] = cur_seen;
1103             if (!can_grow_at(c, nx, ny))
1104                 continue;
1105             w = grow_weight(c, nx, ny, spike);
1106             assert(wsum < INT_MAX - w);
1107             wsum += w;
1108             if (roll0(wsum) < w) {
1109                 newx = nx;
1110                 newy = ny;
1111             }
1112         }
1113     }
1114
1115     if (!wsum)
1116         return 0;
1117
1118     add_sector(c, newx, newy);
1119     return 1;
1120 }
1121
1122 /*
1123  * Grow the continents.
1124  * Return 1 on success, 0 on error.
1125  */
1126 static int
1127 grow_continents(void)
1128 {
1129     int done = 1;
1130     int c, secs;
1131
1132     xzone_init(0);
1133
1134     for (c = 0; c < nc; ++c) {
1135         isecs[c] = 0;
1136         if (!can_grow_at(c, cap[c].x, cap[c].y)
1137             || !can_grow_at(c, new_x(cap[c].x + 2), cap[c].y)) {
1138             done = 0;
1139             continue;
1140         }
1141         add_sector(c, cap[c].x, cap[c].y);
1142         add_sector(c, new_x(cap[c].x + 2), cap[c].y);
1143     }
1144
1145     if (!done) {
1146         qprint("No room for continents\n");
1147         return 0;
1148     }
1149
1150     for (secs = 2; secs < sc && done; secs++) {
1151         for (c = 0; c < nc; ++c) {
1152             if (!grow_one_sector(c))
1153                 done = 0;
1154         }
1155     }
1156
1157     if (!done)
1158         qprint("Only managed to grow %d out of %d sectors.\n",
1159                secs - 1, sc);
1160     return done;
1161 }
1162
1163 /*
1164  * Place additional island @c's first sector.
1165  * Return 1 on success, 0 on error.
1166  */
1167 static int
1168 place_island(int c, int isiz)
1169 {
1170     int n, x, y, d, w, newx, newy;
1171
1172     n = 0;
1173
1174     for (y = 0; y < WORLD_Y; y++) {
1175         for (x = y % 2; x < WORLD_X; x += 2) {
1176             if (can_grow_at(c, x, y)) {
1177                 d = distance[XYOFFSET(x, y)];
1178                 assert(d > id);
1179                 w = (d - id) * (d - id);
1180                 n += MIN(w, (isiz + 2) / 3);
1181                 if (roll0(n) < w) {
1182                     newx = x;
1183                     newy = y;
1184                 }
1185             }
1186         }
1187     }
1188
1189     if (n)
1190         add_sector(c, newx, newy);
1191     return n;
1192 }
1193
1194 static int
1195 int_cmp(const void *a, const void *b)
1196 {
1197     return *(int *)b - *(int *)a;
1198 }
1199
1200 static int *
1201 size_islands(void)
1202 {
1203     int n = ni / nc;
1204     int *isiz = malloc(n * sizeof(*isiz));
1205     int r0, r1, i;
1206
1207     isiz[0] = n * is;
1208     r1 = roll0(is);
1209     for (i = 1; i < n; i++) {
1210         r0 = r1;
1211         r1 = roll0(is);
1212         isiz[i] = is + r1 - r0;
1213         isiz[0] -= isiz[i];
1214     }
1215
1216     qsort(isiz, n, sizeof(*isiz), int_cmp);
1217     return isiz;
1218 }
1219
1220 /*
1221  * Grow the additional islands.
1222  * Return 1 on success, 0 on error.
1223  */
1224 static int
1225 grow_islands(void)
1226 {
1227     int *island_size = size_islands();
1228     int xzone_valid = 0;
1229     int carry = 0;
1230     int i, j, c, done, secs, isiz, x, y;
1231
1232     init_spheres_of_influence();
1233
1234     for (i = 0; i < ni / nc; i++) {
1235         c = nc + i * nc;
1236
1237         if (!xzone_valid)
1238             xzone_init(c);
1239
1240         carry += island_size[i];
1241         isiz = MIN(2 * is, carry);
1242
1243         for (j = 0; j < nc; j++) {
1244             isecs[c + j] = 0;
1245             if (!place_island(c + j, isiz)) {
1246                 qprint("\nNo room for island #%d\n", c - nc + j + 1);
1247                 free(island_size);
1248                 return 0;
1249             }
1250         }
1251
1252         done = 1;
1253         for (secs = 1; secs < isiz && done; secs++) {
1254             for (j = 0; j < nc; j++) {
1255                 if (!grow_one_sector(c + j))
1256                     done = 0;
1257             }
1258         }
1259
1260         if (!done) {
1261             secs--;
1262             for (j = 0; j < nc; j++) {
1263                 if (isecs[c + j] != secs) {
1264                     isecs[c + j]--;
1265                     assert(isecs[c + j] == secs);
1266                     x = sect[c + j][secs].x;
1267                     y = sect[c + j][secs].y;
1268                     own[XYOFFSET(x, y)] = -1;
1269                     adj_land_update(x, y);
1270                 }
1271             }
1272             xzone_valid = 0;
1273         }
1274
1275         for (j = 0; j < nc; j++)
1276             qprint(" %d(%d)", c - nc + j + 1, isecs[c + j]);
1277
1278         carry -= secs;
1279     }
1280
1281     free(island_size);
1282     qprint("\n");
1283
1284     if (carry)
1285         qprint("Only managed to grow %d out of %d island sectors.\n",
1286                is * ni - carry * nc, is * ni);
1287
1288     return 1;
1289 }
1290
1291
1292 /*
1293  * Create elevations
1294  */
1295
1296 static void
1297 create_elevations(void)
1298 {
1299     elevate_prep();
1300     elevate_land();
1301     elevate_sea();
1302 }
1303
1304 static int
1305 elev_cmp(const void *p, const void *q)
1306 {
1307     int a = *(int *)p;
1308     int b = *(int *)q;
1309     int delev = elev[a] - elev[b];
1310
1311     return delev ? delev : a - b;
1312 }
1313
1314 static void
1315 elevate_prep(void)
1316 {
1317     int n = WORLD_SZ() * 8;
1318     int off0, r, sign, elevation, d, x1, y1, off1;
1319     coord x0, y0;
1320     struct hexagon_iter hexit;
1321
1322     init_distance_to_coast();
1323
1324     while (n > 0) {
1325         off0 = roll0(WORLD_SZ());
1326         sctoff2xy(&x0, &y0, off0);
1327         if (own[off0] == -1) {
1328             r = roll(MIN(3, distance[off0]));
1329             sign = -1;
1330         } else {
1331             r = roll(MIN(3, distance[off0]) + 1);
1332             sign = 1;
1333         }
1334         elevation = elev[off0] + sign * r * r;
1335         elev[off0] = LIMIT_TO(elevation, SHRT_MIN, SHRT_MAX);
1336         n--;
1337         for (d = 1; d < r; d++) {
1338             hexagon_first(&hexit, x0, y0, d, &x1, &y1);
1339             do {
1340                 off1 = XYOFFSET(x1, y1);
1341                 elevation = elev[off1] + sign * (r * r - d * d);
1342                 elev[off1] = LIMIT_TO(elevation, SHRT_MIN, SHRT_MAX);
1343                 n--;
1344             } while (hexagon_next(&hexit, &x1, &y1));
1345         }
1346     }
1347 }
1348
1349 static void
1350 elevate_land(void)
1351 {
1352     int *off = malloc(MAX(sc, is * 2) * sizeof(*off));
1353     int max_nm = (pm * MAX(sc, is * 2)) / 100;
1354     int c, nm, i0, n, i;
1355     double elevation, delta;
1356
1357     for (c = 0; c < nc + ni; c++) {
1358         nm = (pm * isecs[c]) / 100;
1359         i0 = c < nc ? 2 : 0;
1360         n = isecs[c] - i0;
1361         for (i = 0; i < i0; i++)
1362             elev[XYOFFSET(sect[c][i].x, sect[c][i].y)] = PLATMIN;
1363         for (i = 0; i < n; i++)
1364             off[i] = XYOFFSET(sect[c][i0 + i].x, sect[c][i0 + i].y);
1365         qsort(off, n, sizeof(*off), elev_cmp);
1366         delta = (double)(HIGHMIN - LANDMIN - 1) / (n - nm - 1);
1367         elevation = LANDMIN;
1368         for (i = 0; i < n - nm; i++) {
1369             elev[off[i]] = (int)(elevation + 0.5);
1370             elevation += delta;
1371         }
1372         elevation = HIGHMIN;
1373         delta = (127.0 - HIGHMIN) / max_nm;
1374         for (; i < n; i++) {
1375             elevation += delta;
1376             elev[off[i]] = (int)(elevation + 0.5);
1377         }
1378     }
1379
1380     free(off);
1381 }
1382
1383 static void
1384 elevate_sea(void)
1385 {
1386     int i, min;
1387
1388     min = 0;
1389     for (i = 0; i < WORLD_SZ(); i++) {
1390         if (elev[i] < min)
1391             min = elev[i];
1392     }
1393
1394     for (i = 0; i < WORLD_SZ(); i++) {
1395         if (elev[i] < 0)
1396             elev[i] = -1 - 126 * elev[i] / min;
1397     }
1398 }
1399
1400 static int
1401 elev_to_sct_type(int elevation)
1402 {
1403     if (elevation < LANDMIN)
1404         return SCT_WATER;
1405     if (elevation < HIGHMIN)
1406         return SCT_RURAL;
1407     return SCT_MOUNT;
1408 }
1409
1410
1411 /*
1412  * Add resources
1413  */
1414
1415 /*
1416  * Map elevation @elev to a resource value according to @conf.
1417  * This is a linear interpolation on the data points in @conf.
1418  */
1419 static int
1420 elev_to_resource(int elev, struct resource_point conf[])
1421 {
1422     int i, elev1, elev2, delev, res1, res2, dres;
1423
1424     for (i = 1; elev > conf[i].elev; i++) ;
1425     assert(conf[i - 1].elev <= elev);
1426
1427     elev1 = conf[i - 1].elev;
1428     elev2 = conf[i].elev;
1429     delev = elev2 - elev1;
1430     res1 = conf[i - 1].res;
1431     res2 = conf[i].res;
1432     dres = res2 - res1;
1433     return (int)(res1 + (double)((elev - elev1) * dres) / delev);
1434 }
1435
1436 static void
1437 add_resources(struct sctstr *sct)
1438 {
1439     sct->sct_min = elev_to_resource(sct->sct_elev, iron_conf);
1440     sct->sct_gmin = elev_to_resource(sct->sct_elev, gold_conf);
1441     sct->sct_fertil = elev_to_resource(sct->sct_elev, fert_conf);
1442     sct->sct_oil = elev_to_resource(sct->sct_elev, oil_conf);
1443     sct->sct_uran = elev_to_resource(sct->sct_elev, uran_conf);
1444 }
1445
1446
1447 /*
1448  * Designate the sectors
1449  */
1450
1451 static void
1452 write_sects(void)
1453 {
1454     struct sctstr *sp;
1455     int i;
1456
1457     for (i = 0; i < WORLD_SZ(); i++) {
1458         sp = getsectid(i);
1459         sp->sct_elev = elev[i];
1460         sp->sct_type = elev_to_sct_type(sp->sct_elev);
1461         sp->sct_newtype = sp->sct_type;
1462         sp->sct_dterr = own[i] + 1;
1463         sp->sct_coastal = is_coastal(sp->sct_x, sp->sct_y);
1464         add_resources(sp);
1465     }
1466 }
1467
1468
1469 /*
1470  * Print a picture of the map
1471  */
1472
1473 static void
1474 output(void)
1475 {
1476     int sx, sy, x, y, off, c, type;
1477
1478     if (quiet == 0) {
1479         for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1480             y = YNORM(sy);
1481             puts("");
1482             if (y % 2)
1483                 printf(" ");
1484             for (sx = -WORLD_X / 2 + y % 2; sx < WORLD_X / 2; sx += 2) {
1485                 x = XNORM(sx);
1486                 off = XYOFFSET(x, y);
1487                 c = own[off];
1488                 type = elev_to_sct_type(elev[off]);
1489                 if (type == SCT_WATER)
1490                     printf(". ");
1491                 else if (type == SCT_MOUNT)
1492                     printf("^ ");
1493                 else if (c >= nc)
1494                     printf("%% ");
1495                 else {
1496                     assert(0 <= c && c < nc);
1497                     if ((x == cap[c].x || x == new_x(cap[c].x + 2))
1498                         && y == cap[c].y)
1499                         printf("%c ", numletter[c % 62]);
1500                     else
1501                         printf("# ");
1502                 }
1503             }
1504         }
1505     }
1506 }
1507
1508 /*
1509  * Print a map to help visualize own[].
1510  * This is for debugging.
1511  */
1512 void
1513 print_own_map(void)
1514 {
1515     int sx, sy, x, y, off;
1516
1517     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1518         y = YNORM(sy);
1519         printf("%4d ", sy);
1520         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1521             x = XNORM(sx);
1522             off = XYOFFSET(x, y);
1523             if ((x + y) & 1)
1524                 putchar(' ');
1525             else if (own[off] == -1)
1526                 putchar('.');
1527             else
1528                 putchar(numletter[own[off] % 62]);
1529         }
1530         putchar('\n');
1531     }
1532 }
1533
1534 /*
1535  * Print a map to help visualize elev[].
1536  * This is for debugging.  It expects the terminal to understand
1537  * 24-bit color escape sequences \e[48;2;$red;$green;$blue;m.
1538  */
1539 void
1540 print_elev_map(void)
1541 {
1542     int sx, sy, x, y, off, sat;
1543
1544     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1545         y = YNORM(sy);
1546         printf("%4d ", sy);
1547         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1548             x = XNORM(sx);
1549             off = XYOFFSET(x, y);
1550             if ((x + y) & 1)
1551                 putchar(' ');
1552             else if (!elev[off])
1553                 putchar(' ');
1554             else if (elev[off] < 0) {
1555                 sat = 256 + elev[off] * 2;
1556                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, sat, 255);
1557             } else if (elev[off] < HIGHMIN / 2) {
1558                 sat = (HIGHMIN / 2 - elev[off]) * 4;
1559                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, 255, sat);
1560             } else if (elev[off] < HIGHMIN) {
1561                 sat = 128 + (HIGHMIN - elev[off]) * 2;
1562                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, sat / 2, sat / 4);
1563             } else {
1564                 sat = 128 + (elev[off] - HIGHMIN) * 2;
1565                 printf("\033[48;2;%d;%d;%dm^\033[0m", sat, sat, sat);
1566             }
1567         }
1568         putchar('\n');
1569     }
1570 }
1571
1572 /*
1573  * Print a map to help visualize xzone[].
1574  * This is for debugging.
1575  */
1576 void
1577 print_xzone_map(void)
1578 {
1579     int sx, sy, x, y, off;
1580
1581     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1582         y = YNORM(sy);
1583         printf("%4d ", sy);
1584         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1585             x = XNORM(sx);
1586             off = XYOFFSET(x, y);
1587             if ((x + y) & 1)
1588                 putchar(' ');
1589             else if (own[off] >= 0)
1590                 putchar('-');
1591             else if (xzone[off] >= 0)
1592                 putchar(numletter[xzone[off] % 62]);
1593             else {
1594                 assert(own[off] == -1);
1595                 putchar(xzone[off] == -1 ? '.' : '!');
1596             }
1597         }
1598         putchar('\n');
1599     }
1600 }
1601
1602 /*
1603  * Print a map to help visualize closest[].
1604  * This is for debugging.
1605  */
1606 void
1607 print_closest_map(void)
1608 {
1609     int sx, sy, x, y, off;
1610
1611     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1612         y = YNORM(sy);
1613         printf("%4d ", sy);
1614         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1615             x = XNORM(sx);
1616             off = XYOFFSET(x, y);
1617             if ((x + y) & 1)
1618                 putchar(' ');
1619             else if (closest[off] == (natid)-1)
1620                 putchar('.');
1621             else if (!distance[off]) {
1622                 assert(closest[off] == own[off]);
1623                 putchar('-');
1624             } else {
1625                 putchar(numletter[closest[off] % 62]);
1626             }
1627         }
1628         printf("\n");
1629     }
1630 }
1631
1632 void
1633 print_distance_map(void)
1634 {
1635     int sx, sy, x, y, off;
1636
1637     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1638         y = YNORM(sy);
1639         printf("%4d ", sy);
1640         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1641             x = XNORM(sx);
1642             off = XYOFFSET(x, y);
1643             if ((x + y) & 1)
1644                 putchar(' ');
1645             else if (closest[off] == (natid)-1)
1646                 putchar('.');
1647             else if (!distance[off]) {
1648                 assert(closest[off] == own[off]);
1649                 putchar('-');
1650             } else {
1651                 putchar(numletter[distance[off] % 62]);
1652             }
1653         }
1654         printf("\n");
1655     }
1656 }
1657
1658
1659 /*
1660  * Write a script for placing capitals
1661  */
1662
1663 static int
1664 write_newcap_script(void)
1665 {
1666     int c;
1667     FILE *script = fopen(outfile, "w");
1668
1669     if (!script) {
1670         fprintf(stderr, "%s: unable to write to %s (%s)\n",
1671                 program_name, outfile, strerror(errno));
1672         return 0;
1673     }
1674
1675     for (c = 0; c < nc; ++c) {
1676         fprintf(script, "add %d %d %d p\n", c + 1, c + 1, c + 1);
1677         fprintf(script, "newcap %d %d,%d\n", c + 1, cap[c].x, cap[c].y);
1678     }
1679     fprintf(script, "add %d visitor visitor v\n", c + 1);
1680     fclose(script);
1681     return 1;
1682 }