forked from plutoscarab/Rails
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRandomMap2.cs
1530 lines (1353 loc) · 43.2 KB
/
RandomMap2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// RandomMap2.cs
/*
* This class represents a randomly-generated map. The map can be recreated exactly by providing
* the same seed string. Only certain strings are allowed because the map algorithm version number
* is embedded in the seed, and only specific version numbers are recognized.
*
* This class differs from the RandomMap class in that it generates more realistic-looking
* terrain and attempts to simulate a satellite photo of the map. It also generates better
* mountain ranges.
*
*/
using System;
using System.Drawing;
using System.Collections;
using System.IO;
using System.Drawing.Imaging;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace Rails
{
struct RGB
{
public byte Red, Grn, Blu;
public RGB(int red, int grn, int blu)
{
Red = (byte) red;
Grn = (byte) grn;
Blu = (byte) blu;
}
public Color Color
{
get
{
return Color.FromArgb(Red, Grn, Blu);
}
}
}
public class RandomMap2 : Map
{
const int maxVersion = 2;
/*
* Version history:
*
* 0 Initial version
*
* 1 Valid port sites require only one or more adjacent seas
* instead of exactly 4
*
* 2 Added nationalized track to ensure three players can reach
* each non-capital city and two players can reach town
*
*/
public string Name;
int version;
Random rand;
Color waterColor;
Brush waterBrush;
// delegates for various path-finding algorithms
FloodMethod terrainCostMethod;
FloodMethod portsMethod;
// create a new map with a random seed
public RandomMap2(Size imageSize) : base(imageSize)
{
CreateRandomMap();
}
void CreateRandomMap()
{
int seed;
RandomNumberGenerator rng = new RNGCryptoServiceProvider();
byte[] s = new byte[4];
rng.GetBytes(s);
Random r = new Random(s[0] + 256 * (s[1] + 256 * (s[2] + 256 * s[3])));
#if DEBUG
foreach (string filename in Directory.GetFiles(".", "rejects*.bmp"))
File.Delete(filename);
int rejects = 0;
#endif
while(true)
{
Name = ChooseName(r);
GetVersionAndSeed(Name, out version, out seed);
if (version == maxVersion)
{
rand = new Random(seed);
CreateMap("Generating random map");
if (IsViableInternal())
break;
#if DEBUG
using (Graphics g = Graphics.FromImage(Background))
{
g.DrawImageUnscaled(base.Foreground, 0, 0);
}
Background.Save("rejects" + (rejects++).ToString() + ".bmp");
#endif
this.Dispose();
}
}
}
// create a new map with a given seed
public RandomMap2(Size imageSize, string name) : base(imageSize)
{
int seed;
Name = name;
GetVersionAndSeed(name, out version, out seed);
if (version > maxVersion)
{
string message = Resource.GetString("RandomMap2.UnsupportedMapName");
MessageBox.Show(message, Resource.GetString("Rails"), MessageBoxButtons.OK);
CreateRandomMap();
return;
}
rand = new Random(seed);
CreateMap("Loading map");
IsViableInternal(); // we already know it's viable, but we need to nationalize tracks
}
public new void Dispose()
{
if (waterBrush != null)
waterBrush.Dispose();
base.Dispose();
}
void GetVersionAndSeed(string name, out int version, out int seed)
{
HashAlgorithm hashAlg = MD5.Create();
Encoding enc = Encoding.UTF8;
byte[] hash = hashAlg.ComputeHash(enc.GetBytes(name.ToLower(System.Globalization.CultureInfo.InvariantCulture)));
version = hash[0];
seed = hash[1] + 256 * (hash[2] + 256 * (hash[3] + 256 * hash[4]));
}
// choose a random name
string ChooseName(Random r)
{
return NamePart(r) + "-" + NamePart(r);
}
Hashtable seenPart = new Hashtable();
string NamePart(Random r)
{
while(true)
{
string part = City.RandomName(2, r, seenPart);
if (part.Length >= 12)
return part;
}
}
// Save the map to disk. Since all we need is the seed to recreate the map, we
// save a lot of space by just storing the seed and a thumbnail image. The seed
// is stored in the image filename.
public override void Save()
{
try
{
Directory.CreateDirectory("maps");
string filename = "maps\\" + Name + ".ter";
int tw = 128;
int th = tw * ImageSize.Height / ImageSize.Width;
using (Bitmap thumb = new Bitmap(tw, th))
{
using (Image bg = this.Background.GetThumbnailImage(tw, th, null, IntPtr.Zero))
{
using (Graphics g = Graphics.FromImage(thumb))
{
g.DrawImage(bg, 0, 0, tw, th);
thumb.Save(filename);
}
}
}
}
catch(IOException)
{
System.Windows.Forms.MessageBox.Show("An error occurred while trying to save the map.");
}
}
void GenerateMilepostGrid(ZField field, int seaLevel, int hillLevel, int alpineLevel)
{
int xx, yy;
milepost = new Milepost[gridW, gridH];
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
{
if (GetCoord(x, y, out xx, out yy))
{
TerrainType t = TerrainType.Inaccessible;
if (field[xx, yy] < seaLevel)
t = TerrainType.Sea;
else if (xx > 0 && field[xx-1, yy] < seaLevel)
t = TerrainType.Sea;
else if (xx < width - 1 && field[xx+1, yy] < seaLevel)
t = TerrainType.Sea;
else if (yy > 0 && field[xx, yy-1] < seaLevel)
t = TerrainType.Sea;
else if (yy < height - 1 & field[xx, yy+1] < seaLevel)
t = TerrainType.Sea;
else if (field[xx, yy] >= hillLevel)
t = rand.Next(3) == 0 ? TerrainType.Mountain : TerrainType.Clear;
else
t = TerrainType.Clear;
milepost[x, y].Terrain = t;
milepost[x, y].CityIndex = -1;
milepost[x, y].SeaIndex = -1;
}
}
int i, j;
for (int y=0; y<height; y++)
for (int x=0; x<width; x++)
if (field[x, y] >= alpineLevel)
if (base.GetNearest(x, y, out i, out j))
milepost[i, j].Terrain = TerrainType.Alpine;
for (int y=0; y<gridH; y++)
for (int x=0; x<gridW; x++)
if (milepost[x, y].Terrain == TerrainType.Alpine)
if (rand.Next(3) > 0)
milepost[x, y].Terrain = TerrainType.Mountain;
}
void AnalyzeLandAndSeas()
{
// identify land masses separated by water
ResetFloodMap();
massIndex = 0;
Flood(0, 0, new FloodMethod(LandMassFloodMethod));
// count the land masses and seas and measure their size
Hashtable masses = new Hashtable(); // maps land/sea ID's to their size
Hashtable massId = new Hashtable(); // maps land/sea ID's to a contiguous value 0..n
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
{
massIndex = milepost[x, y].Value;
if (!masses.ContainsKey(massIndex))
{
massId[massIndex] = masses.Count;
masses[massIndex] = 1;
}
else
masses[massIndex] = (int) masses[massIndex] + 1;
}
// determine which landmasses are adjacent to which seas
int massCount = masses.Count;
ulong[] adjacent = new ulong[massCount];
int[] massIdx = new int[massCount]; // maps contiguous value 0..n to land/sea ID
Point[] massLocation = new Point[massCount];
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
{
int i, j;
for (int d=0; d<6; d++)
if (GetAdjacent(x, y, d, out i, out j))
if (milepost[x, y].Value != milepost[i, j].Value)
{
int v1 = milepost[x, y].Value;
int v2 = milepost[i, j].Value;
int m1 = (int) massId[v1];
int m2 = (int) massId[v2];
adjacent[m1] |= 1UL << m2;
massIdx[m1] = v1;
massIdx[m2] = v2;
}
massLocation[(int) massId[milepost[x, y].Value]] = new Point(x, y);
}
// keep track of which port and sea mileposts we have found to be useful
bool[,] useful = new bool[gridW, gridH];
// count the number of large land masses to see if ports are necessary
const int criticalMass = 13; // minimum size of each land mass
int ncontinents = 0;
for (int i=0; i<massCount; i++)
if (!IsSea(massLocation[i].X, massLocation[i].Y))
if ((int) masses[milepost[massLocation[i].X, massLocation[i].Y].Value] >= criticalMass)
ncontinents++;
// create ports if more than one large land mass
if (ncontinents > 1)
{
// create mapping of mass ID's to continent ID's
int[] continent = new int[massCount];
ncontinents = 0;
for (int i=0; i<massCount; i++)
{
int mx = massLocation[i].X;
int my = massLocation[i].Y;
if (!IsSea(mx, my))
{
massIndex = milepost[mx, my].Value;
if ((int) masses[massIndex] >= criticalMass)
continent[(int) massId[massIndex]] = ncontinents++;
}
}
// catalog all of the viable port locations
int nports = 0;
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
if ((int) masses[milepost[x, y].Value] >= criticalMass)
if (this.IsValidPortSite(x, y))
nports++;
Point[] portLocation = new Point[nports];
int[] portIndex = new int[nports];
nports = 0;
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
if ((int) masses[milepost[x, y].Value] >= criticalMass)
if (this.IsValidPortSite(x, y))
{
milepost[x, y].Terrain = TerrainType.Port;
portLocation[nports] = new Point(x, y);
portIndex[nports] = continent[(int) massId[milepost[x, y].Value]];
nports++;
}
// use ports to connect each continent to nearest neighboring continent
bool[] connected = new bool[ncontinents];
connected[0] = true;
for (int connectedCount=1; connectedCount<ncontinents; connectedCount++)
{
// calculate sea travel times from currently connected ports
this.ResetFloodMap();
for (int port=0; port<nports; port++)
if (connected[portIndex[port]])
milepost[portLocation[port].X, portLocation[port].Y].Value = 0;
this.Flood(portsMethod);
// find closest non-connected port
int min = int.MaxValue;
int closest = -1;
int px, py;
for (int port=0; port<nports; port++)
if (!connected[portIndex[port]])
{
px = portLocation[port].X;
py = portLocation[port].Y;
if (milepost[px, py].Value < min)
{
min = milepost[px, py].Value;
closest = port;
}
}
if (closest == -1)
break;
// mark the closest port's continent as connected
connected[portIndex[closest]] = true;
// make note of useful port connection
Point[] pts = new Point[min + 2];
int pt = 0;
px = portLocation[closest].X;
py = portLocation[closest].Y;
while (true)
{
// get dot location for drawing later
int ptx, pty;
base.GetCoord(px, py, out ptx, out pty);
pts[pt++] = new Point(ptx, pty);
useful[px, py] = true;
if (milepost[px, py].Value == 0)
break;
// trace path back to starting port
if (!base.GetAdjacent(px, py, (milepost[px, py].Gradient + 3) % 6, out px, out py))
break;
}
if (pt > 1) // should always happen
{
// create bezier end points and control points
Point[] bez = new Point[3 * pt - 2];
int bi = 0;
bez[bi++] = pts[0];
Point prev = new Point(2*pts[0].X - pts[1].X, 2*pts[0].Y - pts[1].Y);
Point next;
for (int i=1; i<pt; i++)
{
if (i < pt - 1)
next = pts[i + 1];
else
next = new Point(2*pts[pt-1].X - pts[pt-2].X, 2*pts[pt-1].Y - pts[pt-2].Y);
bez[bi++] = new Point(pts[i-1].X + (pts[i-1].X - prev.X)/3, pts[i-1].Y + (pts[i-1].Y - prev.Y)/3);
bez[bi++] = new Point(pts[i].X + (pts[i].X - next.X)/3, pts[i].Y + (pts[i].Y - next.Y)/3);
bez[bi++] = pts[i];
prev = pts[i-1];
}
// draw beziers
using (Graphics g = Graphics.FromImage(Background))
{
using (Pen p = new Pen(Color.FromArgb(75, Color.Blue), 5))
{
g.DrawBeziers(p, bez);
}
}
}
}
}
// record locations of large seas
int nseas = 0;
for (int i=0; i<massCount; i++)
if ((int) masses[massIdx[i]] > 50)
if (IsSea(massLocation[i].X, massLocation[i].Y))
nseas++;
Seas = new Point[nseas];
nseas = 0;
for (int i=0; i<massCount; i++)
if ((int) masses[massIdx[i]] > 50)
if (IsSea(massLocation[i].X, massLocation[i].Y))
{
Seas[nseas] = massLocation[i];
nseas++;
}
// initialize sea disasters before removing unviable sea travel mileposts
this.InitializeSeaDisasters();
// remove unusable port and sea mileposts
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
if (!useful[x, y])
{
if (milepost[x, y].Terrain == TerrainType.Port)
milepost[x, y].Terrain = TerrainType.Clear;
else if (milepost[x, y].Terrain == TerrainType.Sea)
milepost[x, y].Terrain = TerrainType.Inaccessible;
}
}
void GenerateCities()
{
// loop until good city arrangement is found, usually only once
while(true)
{
// reset city arrays and travel-distance data
Cities = new City[this.CityCount];
// initial test function is for major cities
IsValidSite isValidSite = new IsValidSite(IsValidCapitalSite);
// choose random spot for initial major city
int cx, cy;
while (true)
{
cx = rand.Next(gridW);
cy = rand.Next(gridH);
if (isValidSite(cx, cy))
break;
}
// clear the travel-distance data
ResetFloodMap();
// place all the cities and towns
Hashtable usedNames = new Hashtable();
for (int i=0; i<this.CityCount; i++)
{
// store the city location
milepost[cx, cy].CityIndex = i;
string name;
if (i < this.NumCapitals)
{
name = City.RandomName(i, rand, usedNames);
milepost[cx, cy].CityType = CityType.Capital;
int dx, dy;
for (int d=0; d<6; d++)
if (GetAdjacent(cx, cy, d, out dx, out dy))
{
milepost[dx, dy].CityType = CityType.CapitalCorner;
milepost[dx, dy].CityIndex = i;
}
}
else if (i < this.NumCapitals + this.NumCities)
{
name = City.RandomName(milepost[cx, cy].Capital, rand, usedNames);
milepost[cx, cy].CityType = CityType.City;
}
else
{
name = City.RandomName(milepost[cx, cy].Capital, rand, usedNames);
milepost[cx, cy].CityType = CityType.Town;
}
// after placing the major cities, switch to the city/town test function
if (i == this.NumCapitals)
isValidSite = new IsValidSite(IsValidCitySite);
else if (i == this.NumCapitals + this.NumCities)
isValidSite = new IsValidSite(IsValidTownSite);
Cities[i] = new City(cx, cy, name, new ArrayList(2));
// update travel-distance map to find furthest-distance site for next city
Flood(cx, cy, terrainCostMethod, isValidSite, i < this.NumCapitals ? i : -1, out cx, out cy);
}
usedNames = null;
// make sure all cities are accessible
bool allAccessible = true;
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
if (milepost[x, y].Value == int.MaxValue)
if (milepost[x, y].CityType != CityType.None)
allAccessible = false;
if (allAccessible)
break;
}
}
/*
void GenerateSeaLanes()
{
// for each remaining port, map out the sea lanes to other ports
bool[,] usefulSea = new bool[gridW, gridH];
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
if (milepost[x, y].Terrain == TerrainType.Port)
{
// get the physical location of the port
int x1, y1;
GetCoord(x, y, out x1, out y1);
// calculate distances to all other ports on same body of water
int mx, my;
ResetFloodMap();
Flood(x, y, portsMethod, null, out mx, out my);
// trace out the route back to this port from each other accessible port
for (int rx=0; rx<gridW; rx++)
for (int ry=0; ry<gridH; ry++)
if (milepost[rx, ry].Terrain == TerrainType.Port)
if (milepost[rx, ry].Value != int.MaxValue)
{
// follow distance map back to distance 0 (origin)
int px = rx, py = ry;
while (milepost[px, py].Value > 0)
{
// find the best direction to take
int bestDir = -1;
int qx, qy;
int min = int.MaxValue;
int minDist = int.MaxValue;
for (int d=0; d<6; d++)
if (GetAdjacent(px, py, d, out qx, out qy))
{
// get the physical location of the 2nd port
int x2, y2;
GetCoord(qx, qy, out x2, out y2);
// calculate the straight-line distance
int dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
// check if this is the best direction tried so far
int qvalue = milepost[qx, qy].Value;
if (qvalue < min || (qvalue == min && dist < minDist))
{
min = qvalue;
minDist = dist;
bestDir = d;
}
}
// move toward origin port and mark the sea-lane
GetAdjacent(px, py, bestDir, out px, out py);
usefulSea[px, py] = true;
}
}
}
// before we remove useless sea mileposts, calculate sea disaster areas
base.InitializeSeaDisasters();
// remove sea mileposts that aren't in sea lanes
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
if (milepost[x, y].Terrain == TerrainType.Sea && !usefulSea[x, y])
milepost[x, y].Terrain = TerrainType.Inaccessible;
}
*/
void GenerateRivers(ZField field, int seaLevel, Graphics g, bool[,] isWater)
{
// create rivers
int rivers = 0;
this.Rivers = new ArrayList();
Hashtable riverNames = new Hashtable();
while ((rivers < 15 || this.Rivers.Count < 3) && this.Rivers.Count < 7)
{
// pick a starting point near a city
int x, y;
City c = Cities[this.NumCapitals + (rivers % (this.CityCount - this.NumCapitals))];
while (true)
{
GetCoord(c.X, c.Y, out x, out y);
double a = Math.PI * 2 * rand.NextDouble();
x += (int) (50 * Math.Cos(a));
y += (int) (50 * Math.Sin(a));
if (x >= 0 && x < width && y >= 0 && y < height)
break;
}
// find the approximate nearest water
int x2 = -1, y2 = -1;
int min = int.MaxValue;
for (int p=0; p<200; p++)
{
int i = rand.Next(width);
int j = rand.Next(height);
if (field[i, j] < seaLevel)
{
int dist = (i-x)*(i-x) + (j-y)*(j-y);
if (dist < min)
{
min = dist;
x2 = i;
y2 = j;
}
}
}
// calculate a fractal line between the two points
ArrayList riverPoints = DrawFractalLine(g, waterBrush, x, y, x2, y2, 0.0, 1.0, isWater, field, seaLevel);
if (riverPoints.Count > 1)
{
// simplify the line into a manageable number of line segments
ArrayList riverLine = SimplifyPolyLine(riverPoints);
// throw out rivers that are too short
if (riverLine.Count > 30)
{
PointF[] points = (PointF[]) riverLine.ToArray(typeof(PointF));
// make sure we don't intersect other rivers
bool riversCross = false;
foreach (River r in this.Rivers)
if (Geometry.PolylinesIntersect(points, r.Path))
{
riversCross = true;
break;
}
if (riversCross)
continue;
// store the river data
River rv = new Rails.River(this.Rivers.Count, points, rand, riverNames);
this.Rivers.Add(rv);
// draw the river, thicker near the outlet
int np = riverPoints.Count * 2 / 3;
foreach (PointF p in riverPoints)
{
Background.SetPixel((int)p.X, (int)p.Y, waterColor);
isWater[(int)p.X, (int)p.Y] = true;
if (--np < 0)
{
if ((int)p.X<width-1)
{
Background.SetPixel((int)p.X+1, (int)p.Y, waterColor);
isWater[(int)p.X+1, (int)p.Y] = true;
if ((int)p.Y<height-1)
{
Background.SetPixel((int)p.X+1, (int)p.Y+1, waterColor);
isWater[(int)p.X+1, (int)p.Y+1] = true;
}
}
if ((int)p.Y<height-1)
{
Background.SetPixel((int)p.X, (int)p.Y+1, waterColor);
isWater[(int)p.X, (int)p.Y+1] = true;
}
}
}
}
}
rivers++;
}
riverNames = null;
LocateBridgeSites();
// outline the water
for (int x=1; x<width-1; x++)
for (int y=1; y<height-1; y++)
if (!isWater[x,y] && field[x,y]>=seaLevel)
if (isWater[x-1,y] || isWater[x+1,y] || isWater[x,y-1] || isWater[x,y+1])
Background.SetPixel(x, y, Color.Black);
isWater = null;
}
ZField GenerateTerrain(Progress progress)
{
int sc = 1;
int w = width;
int h = height;
int ss = sc * sc;
int sw = w * sc;
int sh = h * sc;
Rails.ZField z1 = new Rails.ZField(sw, sh, rand, 4);
if (progress != null) progress.SetProgress(15);
Rails.ZField z2 = new Rails.ZField(sw, sh, rand, 8);
if (progress != null) progress.SetProgress(30);
z2.Fold();
int[] pct = z1.GetPercentiles(30);
int sea1 = pct[0];
pct = z2.GetPercentiles(30);
int sea2 = pct[0];
double scaleLand = (256.0 - sea1) / (256.0 - sea2);
double scaleSea = 1.0 * sea1 / sea2;
byte[,] zz = new Byte[sw, sh];
for (int y=0; y<sh; y++)
for (int x=0; x<sw; x++)
{
if (z1[x, y] < sea1)
zz[x, y] = (byte) z1[x, y];
else
{
double mult = (z1[x, y] - sea1) / 10.0;
if (mult > 1.0) mult = 1.0;
zz[x, y] = (byte) (sea1 + (z2[x, y] * mult * (256 - sea1)) / 256);
}
}
Rails.ZField z = new Rails.ZField(zz);
z1 = null;
z2 = null;
int sea = sea1;
pct = z.GetPercentiles(90);
int hill = pct[0];
int[] red = {125, 143, 154, 164, 189, 212, 130, 152, 184, 208, 234, 230, 224, 220};
int[] grn = {153, 170, 182, 190, 208, 227, 162, 174, 190, 206, 225, 213, 199, 187};
int[] blu = {192, 207, 216, 213, 229, 238, 116, 129, 144, 160, 179, 160, 140, 122};
int colors = 13;
int landIdx = 6;
int hillIdx = 9;
double hillExp = Math.Log((hillIdx - landIdx) / (colors - landIdx - 1.0), (hill - sea) / (256.0 - sea));
int[] adj = new int[256];
for (int i=0; i<sea; i++)
adj[i] = i;
for (int i=sea; i<256; i++)
{
double alt = (i - sea) / (256.0 - sea);
alt = Math.Pow(alt, hillExp);
adj[i] = (int) (sea + alt * (256 - sea));
}
zz = new byte[w, h];
RGB[,] co = new RGB[w, h];
for (int y=0; y<h; y++)
{
for (int x=0; x<w; x++)
{
int tred = 0;
int tgrn = 0;
int tblu = 0;
int talt = 0;
int yy = y * sc;
for (int dy=0; dy<sc; dy++, yy++)
{
int xx = x * sc;
for (int dx=0; dx<sc; dx++, xx++)
{
int alt = z[xx, yy];
talt += adj[alt];
int rr, gg, bb;
if (alt >= sea && xx>0 && xx<sw-1 && yy>0 && yy<sh-1 && (z[xx-1,yy]<sea || z[xx+1,yy]<sea || z[xx,yy-1]<sea || z[xx,yy+1]<sea))
{
rr = gg = bb = 0; // black
}
else
{
float idx;
if (alt < sea)
{
idx = (alt * (landIdx - 1.0f)) / sea;
// idx = (float) Math.Ceiling(idx) + (float) Math.Floor(idx) - idx;
}
else
{
float a = (adj[alt] - sea) / (256.0f - sea);
idx = a * (colors - landIdx - 1) + landIdx;
}
int i = (int) idx;
int j = i + 1;
float q = idx - i;
// q = 0;
float p = 1 - q;
float fr = (red[i] * p + red[j] * q);
float fg = (grn[i] * p + grn[j] * q);
float fb = (blu[i] * p + blu[j] * q);
if (alt < sea)
{
rr = (int) fr;
gg = (int) fg;
bb = (int) fb;
}
else
{
int ds = 3;
int sdh = 0;
int sdd = 0;
for (int dl = -ds; dl<=+ds; dl++)
{
int xd = xx + dl;
if (xd >= 0 && xd < sw)
{
sdd += dl * dl;
sdh += dl * adj[z[xd, yy]];
}
}
double m = 1.0 * sdh / sdd;
double nx = -m / Math.Sqrt(1 + m * m);
sdh = sdd = 0;
for (int dl = -ds; dl<=+ds; dl++)
{
int yd = yy + dl;
if (yd >= 0 && yd < sh)
{
sdd += dl * dl;
sdh += dl * adj[z[xx, yd]];
}
}
m = 1.0 * sdh / sdd;
double ny = -m / Math.Sqrt(1 + m * m);
double nz = 5.0;
double nr = Math.Sqrt(3.0 * (nx * nx + ny * ny + nz * nz)) / 1.4;
double dot = (- nx - ny + nz) / nr;
if (dot < 0)
rr = gg = bb = 0;
else
{
rr = (int) (dot * fr); if (rr > 255) rr = 255;
gg = (int) (dot * fg); if (gg > 255) gg = 255;
bb = (int) (dot * fb); if (bb > 255) bb = 255;
}
}
}
tred += rr;
tgrn += gg;
tblu += bb;
}
}
tred /= ss; tgrn /= ss; tblu /= ss;
co[x, y] = new RGB(tred, tgrn, tblu);
zz[x, y] = (byte) (talt / ss);
}
if (progress != null) progress.SetProgress(30 + 70 * y / (h - 1));
}
for (int y=0; y<h; y++)
for (int x=0; x<w; x++)
Background.SetPixel(x, y, co[x, y].Color);
return new ZField(zz);
}
void CreateMap(string title)
{
using (Progress progress = new Progress(title))
{
CreateMap(progress);
}
}
// Create a new map. The random number generator has already been initialized appropriately.
void CreateMap(Progress progress)
{
waterColor = Color.FromArgb(212, 227, 239); // color of river/seas
waterBrush = new SolidBrush(waterColor);
// create the delegates for the path-finding algorithm
terrainCostMethod = new FloodMethod(TerrainCostMethod); // for positioning cities
portsMethod = new FloodMethod(PortsMethod); // for finding sea-lanes
Background = new Bitmap(width, height);
ZField field = GenerateTerrain(progress);
int[] pct = field.GetPercentiles(30, 60, 99);
if (pct[1] == pct[0])
pct[1]++;
GenerateMilepostGrid(field, pct[0], pct[1], pct[2]);
AnalyzeLandAndSeas();
GenerateCities();
// remove inaccessible mileposts from map
ResetFloodMap();
Flood(Cities[0].X, Cities[0].Y, terrainCostMethod);
for (int x=0; x<gridW; x++)
for (int y=0; y<gridH; y++)
if (milepost[x, y].Value == int.MaxValue)
milepost[x, y].Terrain = TerrainType.Inaccessible;
// GenerateSeaLanes();
int seaLevel = pct[0];
bool[,] isWater = new Boolean[width, height];
using (Graphics g = Graphics.FromImage(Background))
{
GenerateRivers(field, seaLevel, g, isWater);
}
for (int y=0; y<height; y++)
for (int x=0; x<width; x++)
isWater[x, y] = field[x, y] < seaLevel;
// locate causeway sites (track over inlets or lakes)
LocateWater(WaterMasks.InletMask, isWater);
DrawForeground();
Products.UseStandardProducts();
InitProductSources();
}
int massIndex;
// for area-finding algorithm, identify all mileposts in the same sea or landmass with
// the same value, and apply a new value at any land/sea transition
bool LandMassFloodMethod(int x, int y, int d, int i, int j, out int cost)
{
bool fromSea = IsSea(x, y);
bool toSea = IsSea(i, j);
if (fromSea == toSea)
cost = 0;
else
{
massIndex++;
cost = massIndex - milepost[x, y].Value;
}
return true;
}
// Generate a fractal line using a 2-D recursive midpoint displacement algorithm.
// Don't draw it yet--just store the points in a list.
ArrayList DrawFractalLine(Graphics g, Brush brush, float x1, float y1, float x2, float y2, double t1, double t2, bool[,] isWater, ZField field, int seaLevel)
{
ArrayList temp;
// don't subdivide further if endpoints closer than one pixel
if (Math.Abs(x1 - x2) <= 1 && Math.Abs(y1 - y2) <= 1)
{
return new ArrayList();
}
// find the midpoint
float xm = (x1 + x2) / 2;
float ym = (y1 + y2) / 2;
// offset the midpoint at right angles by a random amount proportional to the
// distance between the endpoints
float dx = x2 - x1;
float dy = y2 - y1;
double offset = (rand.NextDouble() - 0.5) / 1.5;
float x = xm + (float) (dy * offset);
float y = ym - (float) (dx * offset);
// do this recursively
double t = (t1 + t2) / 2.0;