-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
2141 lines (1890 loc) · 56.1 KB
/
main.go
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
package main
import (
"bufio"
"errors"
"fmt"
"image"
"image/color"
"image/png"
"io/ioutil"
"math"
"math/rand"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/golang/freetype"
bmp "github.com/jsummers/gobmp"
"golang.org/x/image/draw"
"golang.org/x/image/font"
)
var modPath = "c:/Users/admin/Documents/Paradox Interactive/Hearts of Iron IV/mod/oldworldblues"
// var modPath = "d:/Games/SteamApps/common/Hearts of Iron IV"
var definitionsPath = modPath + "/map/definition.csv"
var adjacenciesPath = modPath + "/map/adjacencies.csv"
var provincesPath = modPath + "/map/provinces.bmp"
var terrainPath = modPath + "/map/terrain.bmp"
var heightmapPath = modPath + "/map/heightmap.bmp"
var statesPath = modPath + "/history/states"
var strategicRegionPath = modPath + "/map/strategicregions"
var provincesIDMap = make(map[int]*Province)
var provincesRGBMap = make(map[color.Color]*Province)
var statesMap = make(map[int]*State)
var strategicRegionMap = make(map[int]*StrategicRegion)
var rStateID = regexp.MustCompile(`(?:id[ \n\t]*?=[ \n\t]*?(\d+))`)
var rStateName = regexp.MustCompile(`(?:name[ \n\t]*?=[ \n\t]*?\"(.+?)\")`)
var rStateManpower = regexp.MustCompile(`(?:manpower[ \n\t]*?=[ \n\t]*?(\d+))`)
var rStateProvinces = regexp.MustCompile(`(?s:provinces[ \n\t]*?=[ \n\t]*?{.*?([0-9 ]+).*?})`)
var rStateInfrastructure = regexp.MustCompile(`(?:infrastructure[ \n\t]*?=[ \n\t]*?(\d+))`)
var rStateImpassable = regexp.MustCompile(`(?:impassable[ \n\t]*?=[ \n\t]*?yes)`)
var rSpace = regexp.MustCompile(`\s+`)
var mapScalePixelToKm = 7.114
var provincesImageSize image.Rectangle
var waterColor = color.RGBA{68, 107, 163, 255}
var charWidth = 4
var charHeight = 5
var startTime time.Time
var utf8bom = []byte{0xEF, 0xBB, 0xBF}
// Province represents an in-game province with all parsed data in it.
type Province struct {
ID int
RGB color.RGBA
Type string // "land", "sea" or "lake"
IsCoastal bool
Terrain string
Continent int
State *State
StrategicRegion *StrategicRegion
PixelCoords []image.Point
PixelCoordsMap map[image.Point]bool
CenterPoint image.Point
AdjacentTo map[int]*Province
ConnectedTo map[int]*Province
ImpassableTo map[int]*Province
RenderColor color.RGBA
}
// State represents an in-game state with all parsed data in it.
type State struct {
ID int
Name string
Manpower int
Infrastructure int
IsCoastal bool
IsImpassable bool
Continent int
PixelCoords []image.Point
PixelCoordsMap map[image.Point]bool
CenterPoint image.Point
Provinces map[int]*Province
DistanceTo map[int]int // Distance to other states.
AdjacentTo map[int]*State
ConnectedTo map[int]*State
ImpassableTo map[int]*State
RenderColor color.RGBA
}
// StrategicRegion represents an in-game strategic_region with all parsed data in it.
type StrategicRegion struct {
ID int
Name string
Provinces map[int]*Province
PixelCoords []image.Point
PixelCoordsMap map[image.Point]bool
CenterPoint image.Point
}
func main() {
// Track start time for benchmarking.
startTime = time.Now()
// Parse definition.csv for provinces.
err := parseDefinitions()
if err != nil {
panic(err)
}
// Parse adjacencies.csv for province connections and impassable borders.
err = parseAdjacencies()
if err != nil {
panic(err)
}
// Parse provinces.bmp for province adjacency.
err = parseProvinces()
if err != nil {
panic(err)
}
// Find the center points of each province.
findProvincesCenterPoints()
// Parse state files.
err = parseStateFiles()
if err != nil {
panic(err)
}
// Parse states provinces.
parseStatesProvinces()
// Parse states distance to other states.
parseStatesDistanceToOtherStates()
// Parse state files.
err = parseStrategicRegionFiles()
if err != nil {
panic(err)
}
// Parse strategic regions provinces.
parseStrategicRegionsProvinces()
// Write the output file.
err = saveGeoData()
if err != nil {
panic(err)
}
// // Generate state ID map.
// err = generateSateMap()
// if err != nil {
// panic(err)
// }
// // Generate state ID map.
// err = generateColoredSateMap()
// if err != nil {
// panic(err)
// }
// // Generate state ID map.
// err = generateSateIDMap()
// if err != nil {
// panic(err)
// }
// // Generate province map.
// err = generateProvinceMap()
// if err != nil {
// panic(err)
// }
// // Generate province ID map.
// err = generateProvinceIDMap()
// if err != nil {
// panic(err)
// }
// // Generate manpower map.
// err = generateManpowerMap()
// if err != nil {
// panic(err)
// }
// // Generate sea province map.
// err = generateSeaProvinceMap()
// if err != nil {
// panic(err)
// }
// // Generate province-based terrain map.
// err = generateProvinceBasedTerrainMap()
// if err != nil {
// panic(err)
// }
// // Generate province-based heightmap threshold map.
// err = generateProvinceBasedHeightmapThresholdMap()
// if err != nil {
// panic(err)
// }
// // Generate infrastructure map.
// err = generateInfrastructureMap()
// if err != nil {
// panic(err)
// }
// // Generate infrastructure map.
// err = generateSmallProvincesMap(32)
// if err != nil {
// panic(err)
// }
// // Generate color shuffled province map.
// err = generateColorShuffledProvinceMap()
// if err != nil {
// panic(err)
// }
// // Generate state ID map.
// err = generateProvinceContinentValues("continents.png")
// if err != nil {
// panic(err)
// }
// // Generate impassable terrain map.
// err = generateImpassableMap()
// if err != nil {
// panic(err)
// }
// Print out elapsed time.
elapsedTime := time.Since(startTime)
fmt.Printf("Elapsed time: %s\n", elapsedTime)
}
// ReadLines reads a whole file
// and returns a slice of its lines.
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
// Remove utf-8 bom if found.
if len(lines) > 0 {
utf8bomString := string(utf8bom)
if strings.HasPrefix(lines[0], utf8bomString) {
lines[0] = strings.TrimPrefix(lines[0], utf8bomString)
}
}
return lines, scanner.Err()
}
func parseDefinitions() error {
fmt.Printf("%s: Parsing definition.csv...\n", time.Since(startTime))
definitions, err := readLines(filepath.FromSlash(definitionsPath))
if err != nil {
return err
}
for _, s := range definitions {
province, err := parseDefinitionsProvince(s)
if err != nil {
return err
}
provincesIDMap[province.ID] = &province
provincesRGBMap[province.RGB] = &province
}
return nil
}
func parseDefinitionsProvince(s string) (p Province, err error) {
pStrings := strings.Split(s, ";")
if len(pStrings) != 8 {
return p, errors.New("\"" + definitionsPath + "\": " + s + ": must contain 8 fields")
}
p.ID, err = strconv.Atoi(pStrings[0])
if err != nil {
return p, err
}
r, err := strconv.Atoi(pStrings[1])
if err != nil {
return p, err
}
g, err := strconv.Atoi(pStrings[2])
if err != nil {
return p, err
}
b, err := strconv.Atoi(pStrings[3])
if err != nil {
return p, err
}
p.RGB = color.RGBA{uint8(r), uint8(g), uint8(b), 255}
p.Type = pStrings[4]
p.IsCoastal, err = strconv.ParseBool(pStrings[5])
if err != nil {
return p, err
}
p.Terrain = pStrings[6]
p.Continent, err = strconv.Atoi(pStrings[7])
if err != nil {
return p, err
}
p.PixelCoordsMap = make(map[image.Point]bool)
p.AdjacentTo = make(map[int]*Province)
p.ConnectedTo = make(map[int]*Province)
p.ImpassableTo = make(map[int]*Province)
return p, nil
}
func parseAdjacencies() error {
fmt.Printf("%s: Parsing adjacencies.csv...\n", time.Since(startTime))
adjacencies, err := readLines(filepath.FromSlash(adjacenciesPath))
if err != nil {
return err
}
// Skip first and last lines.
for _, s := range adjacencies[1 : len(adjacencies)-1] {
err := parseAdjacenciesState(s)
if err != nil {
return err
}
}
return nil
}
func parseAdjacenciesState(s string) error {
// Skip commented and empty lines.
if strings.HasPrefix(s, "#") || len(s) == 0 {
return nil
}
a := strings.Split(s, ";")
if len(a) != 10 {
return errors.New("\"" + adjacenciesPath + "\": " + s + ": must contain 10 fields")
}
id1, err := strconv.Atoi(a[0])
if err != nil {
return err
}
id2, err := strconv.Atoi(a[1])
if err != nil {
return err
}
if a[2] == "sea" || a[2] == "" {
provincesIDMap[id1].ConnectedTo[id2] = provincesIDMap[id2]
provincesIDMap[id2].ConnectedTo[id1] = provincesIDMap[id1]
}
if a[2] == "impassable" {
provincesIDMap[id1].ImpassableTo[id2] = provincesIDMap[id2]
provincesIDMap[id2].ImpassableTo[id1] = provincesIDMap[id1]
}
return nil
}
func parseProvinces() error {
fmt.Printf("%s: Parsing provinces.bmp...\n", time.Since(startTime))
provincesFile, err := os.Open(filepath.FromSlash(provincesPath))
if err != nil {
return err
}
defer provincesFile.Close()
provincesImage, err := bmp.Decode(provincesFile)
if err != nil {
return err
}
provincesImageSize.Max = image.Point{provincesImage.Bounds().Max.X, provincesImage.Bounds().Max.Y}
// Parse each pixel in scanline order.
for y := 0; y < provincesImage.Bounds().Max.Y; y++ {
for x := 0; x < provincesImage.Bounds().Max.X; x++ {
var e, s color.Color
// Get the color of the current pixel.
c := provincesImage.At(x, y)
r, g, b, a := c.RGBA()
c = color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}
// Add pixel coordinates to the province that has this RGB value.
provincesRGBMap[c].PixelCoordsMap[image.Point{x, y}] = true
provincesRGBMap[c].PixelCoords = append(provincesRGBMap[c].PixelCoords, image.Point{x, y})
// Find out the color of the adjacent right and bottom pixels.
if x < provincesImage.Bounds().Max.X-1 {
e = provincesImage.At(x+1, y)
r, g, b, a := e.RGBA()
e = color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}
}
if y < provincesImage.Bounds().Max.Y-1 {
s = provincesImage.At(x, y+1)
r, g, b, a := s.RGBA()
s = color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}
}
// If color is different then this two provinces are adjacent.
if (c != e) && (e != nil) {
provincesRGBMap[c].AdjacentTo[provincesRGBMap[e].ID] = provincesRGBMap[e]
provincesRGBMap[e].AdjacentTo[provincesRGBMap[c].ID] = provincesRGBMap[c]
}
if (c != s) && (s != nil) {
provincesRGBMap[c].AdjacentTo[provincesRGBMap[s].ID] = provincesRGBMap[s]
provincesRGBMap[s].AdjacentTo[provincesRGBMap[c].ID] = provincesRGBMap[c]
}
}
}
return nil
}
func findProvincesCenterPoints() {
fmt.Printf("%s: Calculating provinces center point coordinates...\n", time.Since(startTime))
for _, p := range provincesIDMap {
p.CenterPoint = findCenterPoint(p.PixelCoords)
}
}
func findCenterPoint(coords []image.Point) image.Point {
// Fast centerpoint calculation.
x := 0
y := 0
for _, c := range coords {
x += c.X
y += c.Y
}
return image.Point{int(math.Round(float64(x) / float64(len(coords)))), int(math.Round(float64(y) / float64(len(coords))))}
// // Long largest rects centerpoint calculation.
// l := math.MaxInt64
// r := math.MinInt64
// t := math.MaxInt64
// b := math.MinInt64
// for _, c := range coords {
// if c.X < l {
// l = c.X
// }
// if c.X > r {
// r = c.X
// }
// if c.Y < t {
// t = c.Y
// }
// if c.Y > b {
// b = c.Y
// }
// }
// maxRectSize := -1
// var maxRect image.Rectangle
// line := make([]int, r-l+1)
// for y := t; y <= b; y++ {
// i := 0
// for x := l; x <= r; x++ {
// if containsPoint(coords, image.Point{x, y}) {
// line[i]++
// } else {
// line[i] = 0
// }
// i++
// }
// // fmt.Println(line)
// rectSize, xStart, xEnd, yStart := findLargestRectangle(line)
// if maxRectSize < rectSize {
// maxRectSize = rectSize
// maxRect.Min = image.Point{l + xStart, y - yStart + 1}
// maxRect.Max = image.Point{l + xEnd - 1, y - 1}
// }
// }
// // fmt.Println("> ", l, t, r, b, maxRectSize, maxRect, image.Point{int(math.Round(float64(maxRect.Min.X+maxRect.Max.X) / 2)), int(math.Round(float64(maxRect.Min.Y+maxRect.Max.Y) / 2))})
// return image.Point{int(math.Round(float64(maxRect.Min.X+maxRect.Max.X) / 2)), int(math.Round(float64(maxRect.Min.Y+maxRect.Max.Y) / 2))}
}
func findLargestRectangle(hist []int) (int, int, int, int) {
var h, pos, tempH, tempPos int
var xStart, xEnd, yStart int
var hStack, posStack []int
maxSize := -1
tempSize := -1
for pos = 0; pos < len(hist); pos++ {
h = hist[pos]
if len(hStack) == 0 || h > hStack[len(hStack)-1] {
hStack = append(hStack, h)
posStack = append(posStack, pos)
} else if h < hStack[len(hStack)-1] {
for len(hStack) > 0 && h < hStack[len(hStack)-1] {
hStack, posStack, tempH, tempPos, tempSize = popStack(hStack, posStack, pos, maxSize)
if maxSize < tempSize {
maxSize = tempSize
xStart = tempPos
xEnd = pos
yStart = tempH
}
}
hStack = append(hStack, h)
posStack = append(posStack, tempPos)
}
}
return maxSize, xStart, xEnd, yStart
}
func popStack(hStack, posStack []int, pos, maxSize int) ([]int, []int, int, int, int) {
tempH, hStack := hStack[len(hStack)-1], hStack[:len(hStack)-1]
tempPos, posStack := posStack[len(posStack)-1], posStack[:len(posStack)-1]
tempSize := tempH * (pos - tempPos)
return hStack, posStack, tempH, tempPos, tempSize
}
func maxInt(x, y int) int {
if x > y {
return x
}
return y
}
func parseStateFiles() error {
fmt.Printf("%s: Parsing state files...\n", time.Since(startTime))
stateFiles, err := filepath.Glob(filepath.FromSlash(statesPath) + string(os.PathSeparator) + "*.txt")
if err != nil {
return err
}
for _, s := range stateFiles {
state, err := parseState(s)
if err != nil {
return err
}
statesMap[state.ID] = &state
}
return nil
}
func parseState(path string) (state State, err error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return state, err
}
s := strings.Replace(string(b), "\r\n", "\n", -1)
state.ID, err = strconv.Atoi(rStateID.FindStringSubmatch(s)[1])
if err != nil {
return state, err
}
r := rStateName.FindStringSubmatch(s)
if r != nil {
state.Name = r[1]
}
r = rStateManpower.FindStringSubmatch(s)
if r != nil {
state.Manpower, err = strconv.Atoi(r[1])
if err != nil {
return state, err
}
}
r = rStateInfrastructure.FindStringSubmatch(s)
if r != nil {
state.Infrastructure, err = strconv.Atoi(r[1])
if err != nil {
return state, err
}
}
r = rStateImpassable.FindStringSubmatch(s)
if r != nil {
state.IsImpassable = true
}
state.Provinces = make(map[int]*Province)
provinces := strings.Split(strings.TrimSpace(rSpace.ReplaceAllString(rStateProvinces.FindStringSubmatch(s)[1], " ")), " ")
for _, p := range provinces {
pID, err := strconv.Atoi(p)
if err != nil {
return state, err
}
state.Provinces[pID] = provincesIDMap[pID]
}
state.Continent = -1
state.PixelCoordsMap = make(map[image.Point]bool)
state.DistanceTo = make(map[int]int)
state.AdjacentTo = make(map[int]*State)
state.ConnectedTo = make(map[int]*State)
state.ImpassableTo = make(map[int]*State)
return state, nil
}
func parseStatesProvinces() {
fmt.Printf("%s: Parsing provinces in each state...\n", time.Since(startTime))
for _, s1 := range statesMap {
for _, p1 := range s1.Provinces {
// All provinces in a state should have the same continent number.
// Save the first province continent as states continent.
if s1.Continent == -1 {
s1.Continent = p1.Continent
}
// If there is at least one coastal province in a state, mark state as coastal.
if p1.IsCoastal {
s1.IsCoastal = true
}
// Fill in each states pixel coordinates.
for _, pc := range p1.PixelCoords {
s1.PixelCoordsMap[pc] = true
s1.PixelCoords = append(s1.PixelCoords, pc)
}
// Fill up adjacentTo and connectedTo fields in all states
// based on the provinces in those states
for _, s2 := range statesMap {
for _, p2 := range s2.Provinces {
for _, a1 := range p1.AdjacentTo {
if a1.ID == p2.ID && s1.ID != s2.ID {
s1.AdjacentTo[s2.ID] = s2
}
}
for _, c1 := range p1.ConnectedTo {
if c1.ID == p2.ID && s1.ID != s2.ID {
s1.ConnectedTo[s2.ID] = s2
}
}
}
}
// Add state to the province.
p1.State = s1
}
}
for _, s1 := range statesMap {
// Find the center point of the state.
// fmt.Printf("%s: Calculating states center point coordinates...\n", time.Since(startTime))
s1.CenterPoint = findCenterPoint(s1.PixelCoords)
// If state has provinces with non-empty impassableTo field.
// Check if all provinces adjacent to another state are impassable to it.
// If that's the case, then add this state to impassableTo filed of the first sate.
impassableProvincesCount := 0
for _, p1 := range s1.Provinces {
if len(p1.ImpassableTo) > 0 {
impassableProvincesCount++
}
}
if impassableProvincesCount > 0 {
for _, s2 := range s1.AdjacentTo {
adjacentProvinces := make(map[int]struct{})
adjacentProvincesCount := 0
impassableProvincesCount = 0
for _, p1 := range s1.Provinces {
for _, ap1 := range p1.AdjacentTo {
for _, p2 := range s2.Provinces {
if ap1.ID == p2.ID {
adjacentProvinces[ap1.ID] = struct{}{}
adjacentProvincesCount++
}
}
}
for _, i1 := range p1.ImpassableTo {
if _, ok := adjacentProvinces[i1.ID]; ok {
impassableProvincesCount++
}
}
}
if impassableProvincesCount > 0 && impassableProvincesCount == adjacentProvincesCount {
s1.ImpassableTo[s2.ID] = s2
}
}
}
}
}
func parseStatesDistanceToOtherStates() {
fmt.Printf("%s: Calculating distance between each state...\n", time.Since(startTime))
for _, s1 := range statesMap {
for _, s2 := range statesMap {
s1.DistanceTo[s2.ID] = distance(s1.CenterPoint, s2.CenterPoint)
}
}
}
// Distance returns rounded distance between two coordinates.
func distance(c1, c2 image.Point) int {
return int(math.Round(math.Sqrt(math.Pow(float64(c2.X-c1.X), 2)+math.Pow(float64(c2.Y-c1.Y), 2)) * mapScalePixelToKm))
}
func parseStrategicRegionFiles() error {
fmt.Printf("%s: Parsing strategic region files...\n", time.Since(startTime))
strategicRegionFiles, err := filepath.Glob(filepath.FromSlash(strategicRegionPath) + string(os.PathSeparator) + "*.txt")
if err != nil {
return err
}
for _, r := range strategicRegionFiles {
strategicRegion, err := parseStrategicRegion(r)
if err != nil {
return err
}
strategicRegionMap[strategicRegion.ID] = &strategicRegion
}
return nil
}
func parseStrategicRegion(path string) (strategicRegion StrategicRegion, err error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return strategicRegion, err
}
s := strings.Replace(string(b), "\r\n", "\n", -1)
strategicRegion.ID, err = strconv.Atoi(rStateID.FindStringSubmatch(s)[1])
if err != nil {
return strategicRegion, err
}
r := rStateName.FindStringSubmatch(s)
if r != nil {
strategicRegion.Name = r[1]
}
strategicRegion.Provinces = make(map[int]*Province)
provinces := strings.Split(strings.TrimSpace(rSpace.ReplaceAllString(rStateProvinces.FindStringSubmatch(s)[1], " ")), " ")
for _, p := range provinces {
pID, err := strconv.Atoi(p)
if err != nil {
return strategicRegion, err
}
strategicRegion.Provinces[pID] = provincesIDMap[pID]
}
strategicRegion.PixelCoordsMap = make(map[image.Point]bool)
return strategicRegion, nil
}
func parseStrategicRegionsProvinces() {
fmt.Printf("%s: Parsing provinces in each strategic region...\n", time.Since(startTime))
for _, r := range strategicRegionMap {
for _, p := range r.Provinces {
// Fill in each strategic regions pixel coordinates.
for _, pc := range p.PixelCoords {
r.PixelCoordsMap[pc] = true
r.PixelCoords = append(r.PixelCoords, pc)
}
// Add strategic region to the province.
p.StrategicRegion = r
}
// // Find the center point of the strategic region.
// // fmt.Printf("%s: Calculating strategic regions center point coordinates...\n", time.Since(startTime))
// r.CenterPoint = findCenterPoint(r.PixelCoords)
}
}
func saveGeoData() error {
fmt.Printf("%s: Writing the output file...\n", time.Since(startTime))
// Create new file.
f, err := os.Create("hoi4geoparser_data.txt")
if err != nil {
return err
}
defer f.Close()
// Write on_actions header into the output file.
_, err = f.WriteString("# Autogenerated by hoi4geoparser. Do not mess with the data.\n# evil_c0okie (https://github.com/malashin/hoi4geoparser)\n\non_actions = {\n\ton_startup = {\n\t\teffect = {\n")
if err != nil {
return err
}
// Sort the state ids.
statesIDs := sortedKeySliceFromStateMap(statesMap)
// Iterate over all states in ID sorted order.
for _, sID := range statesIDs {
// if len(statesMap[sID].ConnectedTo) == 0 && len(statesMap[sID].ImpassableTo) == 0 {
// continue
// }
if len(statesMap[sID].ImpassableTo) == 0 && !statesMap[sID].IsImpassable {
continue
}
// Write the state id into the output file.
_, err = f.WriteString("\t\t\t" + strconv.Itoa(sID) + " = {\n")
if err != nil {
return err
}
// if len(statesMap[sID].ConnectedTo) > 0 {
// // Sort the map.
// statesConnectedToIDs := sortedKeySliceFromStateMap(statesMap[sID].ConnectedTo)
// // Iterate over all states from ConnectedTo map in ID sorted order.
// for _, cID := range statesConnectedToIDs {
// // Write the connected_to@STATE variables.
// _, err = f.WriteString("\t\t\t\tset_variable = { connected_to@" + strconv.Itoa(cID) + " = 1 }\n")
// if err != nil {
// return err
// }
// }
// }
if len(statesMap[sID].ImpassableTo) > 0 {
// Sort the map.
statesImpassableToIDs := sortedKeySliceFromStateMap(statesMap[sID].ImpassableTo)
// Iterate over all states from ImpassableTo map in ID sorted order.
for _, aID := range statesImpassableToIDs {
// Write the impassable_to@STATE variables.
_, err = f.WriteString("\t\t\t\tset_variable = { impassable_to@" + strconv.Itoa(aID) + " = 1 }\n")
if err != nil {
return err
}
}
}
if statesMap[sID].IsImpassable {
// Write the is_impassable state flag.
_, err = f.WriteString("\t\t\t\tset_state_flag = is_impassable\n")
if err != nil {
return err
}
}
// // Sort the map.
// statesDistanceToIDs := sortedKeySliceFromIntMap(statesMap[sID].DistanceTo)
// // Iterate over all states from DistanceTO map in ID sorted order.
// for _, dID := range statesDistanceToIDs {
// // Write the distance_to@STATE variables.
// _, err = f.WriteString("\t\t\t\tset_variable = { distance_to@" + strconv.Itoa(dID) + " = " + strconv.Itoa(statesMap[sID].DistanceTo[dID]) + " }\n")
// if err != nil {
// return err
// }
// }
// Write the state closing brackets into the output file.
_, err = f.WriteString("\t\t\t}\n")
if err != nil {
return err
}
}
// Write the on_startup and effect closing brackets into the output file.
_, err = f.WriteString("\t\t}\n\t}\n}\n")
if err != nil {
return err
}
return nil
}
func sortedKeySliceFromStateMap(m map[int]*State) (slice []int) {
for k := range m {
slice = append(slice, k)
}
sort.Ints(slice)
return slice
}
func sortedKeySliceFromIntMap(m map[int]int) (slice []int) {
for k := range m {
slice = append(slice, k)
}
sort.Ints(slice)
return slice
}
func generateRandomLightColor() color.RGBA {
max := 255
min := 128
c := color.RGBA{uint8(rand.Intn(max-min) + min), uint8(rand.Intn(max-min) + min), uint8(rand.Intn(max-min) + min), 255}
// if isColorClose(c, waterColor) {
// c = generateRandomLightColor()
// }
return c
}
func isColorClose(a color.RGBA, b color.RGBA) bool {
d := math.Sqrt(2*math.Exp2(float64(b.R-a.R)) + 4*math.Exp2(float64(b.G-a.G)) + 3*math.Exp2(float64(b.B-a.B)))
// fmt.Printf("%v %v | %e %f %v\n", a, b, d, d, d < 10000000000000000000000000000000000)
return d < 10000000000000000000000000000000000
}
func generateRandomStateColor(s *State, i int) {
b := false
col := generateRandomLightColor()
for _, a := range s.AdjacentTo {
// fmt.Println(s.ID, col, a.ID, a.RenderColor)
if (a.RenderColor != color.RGBA{0, 0, 0, 0}) && (isColorClose(col, a.RenderColor)) {
b = true
continue
}
}
if b && (i < 500) {
generateRandomStateColor(s, i+1)
}
s.RenderColor = col
}
func addLabel(img *image.RGBA, c *freetype.Context, x, y int, size float64, label string) error {
pt := freetype.Pt(x, y)
if _, err := c.DrawString(label, pt); err != nil {
return err
}
return nil
}
func generateSateMap() error {
fmt.Printf("%s: Generating state map...\n", time.Since(startTime))
// Create empty image and fill it with blue color (water).
img := image.NewRGBA(provincesImageSize)
draw.Draw(img, img.Bounds(), &image.Uniform{waterColor}, image.ZP, draw.Src)
// // Draw state shapes.
// for _, s := range statesMap {
// generateRandomStateColor(s, 0)
// for _, p := range s.PixelCoords {
// img.Set(p.X, p.Y, s.RenderColor)
// }
// }
// Draw land province shapes.
fillCol := color.RGBA{255, 255, 255, 255}
for _, prov := range provincesIDMap {
if prov.Type == "land" {
for _, p := range prov.PixelCoords {
img.Set(p.X, p.Y, fillCol)
}
}
}
// Draw state borders.
stateBorderColor := color.RGBA{158, 158, 158, 255}
for _, s := range statesMap {
for _, p := range s.PixelCoords {
_, exists := s.PixelCoordsMap[image.Point{p.X + 1, p.Y}]
if !exists {
img.Set(p.X+1, p.Y, stateBorderColor)
}
_, exists = s.PixelCoordsMap[image.Point{p.X, p.Y + 1}]
if !exists {
img.Set(p.X, p.Y+1, stateBorderColor)
}
_, exists = s.PixelCoordsMap[image.Point{p.X - 1, p.Y}]
if !exists {
img.Set(p.X, p.Y, stateBorderColor)
}
_, exists = s.PixelCoordsMap[image.Point{p.X, p.Y - 1}]
if !exists {
img.Set(p.X, p.Y, stateBorderColor)
}
}
}
// Draw strategic region borders.
strategicRegionBorderColor := color.RGBA{158, 158, 158, 255}
for _, r := range strategicRegionMap {
for _, p := range r.PixelCoords {
_, exists := r.PixelCoordsMap[image.Point{p.X + 1, p.Y}]
if !exists {
img.Set(p.X+1, p.Y, strategicRegionBorderColor)
}
_, exists = r.PixelCoordsMap[image.Point{p.X, p.Y + 1}]
if !exists {
img.Set(p.X, p.Y+1, strategicRegionBorderColor)
}
_, exists = r.PixelCoordsMap[image.Point{p.X - 1, p.Y}]
if !exists {
img.Set(p.X, p.Y, strategicRegionBorderColor)
}
_, exists = r.PixelCoordsMap[image.Point{p.X, p.Y - 1}]
if !exists {