forked from jefetienne/daggerfall-unity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapsFile.cs
More file actions
1351 lines (1171 loc) · 55.9 KB
/
MapsFile.cs
File metadata and controls
1351 lines (1171 loc) · 55.9 KB
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
// Project: Daggerfall Tools For Unity
// Copyright: Copyright (C) 2009-2020 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
#region Using Statements
using System;
using System.IO;
using System.Collections.Generic;
using DaggerfallConnect.Utility;
using DaggerfallWorkshop.Utility.AssetInjection;
#endregion
namespace DaggerfallConnect.Arena2
{
/// <summary>
/// Connects to MAPS.BSA to enumerate locations within a specific region and extract their layouts.
/// </summary>
public class MapsFile
{
#region Class Variables
public const int WorldMapTerrainDim = 32768;
public const int WorldMapTileDim = 128;
public const int WorldMapRMBDim = 4096;
public const int MinWorldCoordX = 0;
public const int MinWorldCoordZ = 0;
public const int MaxWorldCoordX = 32768000;
public const int MaxWorldCoordZ = 16384000;
public const int MinWorldTileCoordX = 0;
public const int MaxWorldTileCoordX = 128000;
public const int MinWorldTileCoordZ = 0;
public const int MaxWorldTileCoordZ = 64000;
public const int MinMapPixelX = 0;
public const int MinMapPixelY = 0;
public const int MaxMapPixelX = 1000;
public const int MaxMapPixelY = 500;
/// <summary>
/// All region names.
/// </summary>
private static readonly string[] regionNames = {
"Alik'r Desert", "Dragontail Mountains", "Glenpoint Foothills", "Daggerfall Bluffs",
"Yeorth Burrowland", "Dwynnen", "Ravennian Forest", "Devilrock",
"Malekna Forest", "Isle of Balfiera", "Bantha", "Dak'fron",
"Islands in the Western Iliac Bay", "Tamarilyn Point", "Lainlyn Cliffs", "Bjoulsae River",
"Wrothgarian Mountains", "Daggerfall", "Glenpoint", "Betony", "Sentinel", "Anticlere", "Lainlyn", "Wayrest",
"Gen Tem High Rock village", "Gen Rai Hammerfell village", "Orsinium Area", "Skeffington Wood",
"Hammerfell bay coast", "Hammerfell sea coast", "High Rock bay coast", "High Rock sea coast",
"Northmoor", "Menevia", "Alcaire", "Koegria", "Bhoraine", "Kambria", "Phrygias", "Urvaius",
"Ykalon", "Daenia", "Shalgora", "Abibon-Gora", "Kairou", "Pothago", "Myrkwasa", "Ayasofya",
"Tigonus", "Kozanset", "Satakalaam", "Totambu", "Mournoth", "Ephesus", "Santaki", "Antiphyllos",
"Bergama", "Gavaudon", "Tulune", "Glenumbra Moors", "Ilessan Hills", "Cybiades"
};
/// <summary>
/// All region races, primarily used to generate townsfolk names. In the array extracted from FALL.EXE:
/// 0 = Breton, 1 = Redguard.
/// </summary>
private static readonly byte[] regionRaces = {
1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 1
};
/// <summary>
/// Block file prefixes.
/// </summary>
private readonly string[] rmbBlockPrefixes = {
"TVRN", "GENR", "RESI", "WEAP", "ARMR", "ALCH", "BANK", "BOOK",
"CLOT", "FURN", "GEMS", "LIBR", "PAWN", "TEMP", "TEMP", "PALA",
"FARM", "DUNG", "CAST", "MANR", "SHRI", "RUIN", "SHCK", "GRVE",
"FILL", "KRAV", "KDRA", "KOWL", "KMOO", "KCAN", "KFLA", "KHOR",
"KROS", "KWHE", "KSCA", "KHAW", "MAGE", "THIE", "DARK", "FIGH",
"CUST", "WALL", "MARK", "SHIP", "WITC"
};
/// <summary>
/// Letters that form the second part of an RMB block name.
/// </summary>
readonly string[] letter2Array = { "A", "L", "M", "S" };
/// <summary>
/// RDB block letters array.
/// </summary>
private readonly string[] rdbBlockLetters = { "N", "W", "L", "S", "B", "M" };
/// <summary>
/// Auto-discard behaviour enabled or disabled.
/// </summary>
private bool autoDiscardValue = true;
/// <summary>
/// The last region opened. Used by auto-discard logic.
/// </summary>
private int lastRegion = -1;
/// <summary>
/// The BsaFile representing MAPS.BSA.
/// </summary>
private readonly BsaFile bsaFile = new BsaFile();
/// <summary>
/// Array of decomposed region records.
/// </summary>
private RegionRecord[] regions;
/// <summary>
/// Climate PAK file.
/// </summary>
private PakFile climatePak;
/// <summary>
/// Politic PAK file.
/// </summary>
private PakFile politicPak;
/// <summary>
/// Flag set when class is loaded and ready.
/// </summary>
private bool isReady = false;
#endregion
#region Class Structures
/// <summary>
/// Represents a single region record.
/// </summary>
private struct RegionRecord
{
public string Name;
public FileProxy MapNames;
public FileProxy MapTable;
public FileProxy MapPItem;
public FileProxy MapDItem;
public DFRegion DFRegion;
}
/// <summary>
/// Offsets to dungeon records.
/// </summary>
private struct DungeonOffset
{
/// <summary>Offset in bytes relative to end of offset list.</summary>
public UInt32 Offset;
/// <summary>Is TRUE (0x0001) for all elements.</summary>
public UInt16 IsDungeon;
/// <summary>The exterior location this dungeon is paired with.</summary>
public UInt16 ExteriorLocationId;
}
#endregion
#region Static Properties
/// <summary>
/// Gets default MAPS.BSA filename.
/// </summary>
public static string Filename
{
get { return "MAPS.BSA"; }
}
#endregion
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public MapsFile()
{
}
/// <summary>
/// Load constructor.
/// </summary>
/// <param name="filePath">Absolute path to MAPS.BSA.</param>
/// <param name="usage">Determines if the BSA file will read from disk or memory.</param>
/// <param name="readOnly">File will be read-only if true, read-write if false.</param>
public MapsFile(string filePath, FileUsage usage, bool readOnly)
{
Load(filePath, usage, readOnly);
}
#endregion
#region Public Properties
/// <summary>
/// If true then decomposed regions will be destroyed every time a different region is fetched.
/// If false then decomposed regions will be maintained until DiscardRegion() or DiscardAllRegions() is called.
/// Turning off auto-discard will speed up region retrieval times at the expense of RAM. For best results, disable
/// auto-discard and impose your own caching scheme using LoadRecord() and DiscardRecord() based on your application
/// needs.
/// </summary>
public bool AutoDiscard
{
get { return autoDiscardValue; }
set { autoDiscardValue = value; }
}
/// <summary>
/// Number of regions in MAPS.BSA.
/// </summary>
public int RegionCount
{
get { return bsaFile.Count / 4; }
}
/// <summary>
/// Gets all region names as string array.
/// </summary>
public static string[] RegionNames
{
get { return regionNames; }
}
/// <summary>
/// Gets all region races as byte array.
/// </summary>
public static byte[] RegionRaces
{
get { return regionRaces; }
}
/// <summary>
/// Gets raw MAPS.BSA file.
/// </summary>
public BsaFile BsaFile
{
get { return bsaFile; }
}
/// <summary>
/// True when ready to load regions and locations, otherwise false.
/// </summary>
public bool Ready
{
get { return isReady; }
}
/// <summary>
/// Gets internal climate data.
/// </summary>
public PakFile ClimateFile
{
get { return climatePak; }
}
#endregion
#region Static Properties
public enum Climates
{
Ocean = 223,
Desert = 224,
Desert2 = 225, // seen in dak'fron
Mountain = 226,
Rainforest = 227,
Swamp = 228,
Subtropical = 229,
MountainWoods = 230,
Woodlands = 231,
HauntedWoodlands = 232 // not sure where this is?
}
/// <summary>
/// Gets default climate index.
/// </summary>
public static int DefaultClimate
{
get { return 231; }
}
/// <summary>
/// Gets default climate settings.
/// </summary>
public static DFLocation.ClimateSettings DefaultClimateSettings
{
get { return GetWorldClimateSettings(DefaultClimate); }
}
#endregion
#region Static Public Methods
/// <summary>
/// Converts longitude and latitude to map pixel coordinates.
/// The world is 1000x500 map pixels.
/// </summary>
/// <param name="longitude">Longitude position.</param>
/// <param name="latitude">Latitude position.</param>
/// <returns>Map pixel position.</returns>
public static DFPosition LongitudeLatitudeToMapPixel(int longitude, int latitude)
{
DFPosition pos = new DFPosition();
pos.X = longitude / 128;
pos.Y = 499 - (latitude / 128);
return pos;
}
/// <summary>
/// Converts map pixel coord to longitude and latitude.
/// </summary>
/// <param name="mapPixelX">Map pixel X.</param>
/// <param name="mapPixelY">Map pixel Y.</param>
/// <returns></returns>
public static DFPosition MapPixelToLongitudeLatitude(int mapPixelX, int mapPixelY)
{
DFPosition pos = new DFPosition();
pos.X = mapPixelX * 128;
pos.Y = (499 - mapPixelY) * 128;
return pos;
}
/// <summary>
/// Gets ID of map pixel.
/// This can be mapped to location IDs and quest IDs.
/// MapTableData.MapId & 0x000fffff = WorldPixelID.
/// </summary>
/// <param name="mapPixelX">Map pixel X.</param>
/// <param name="mapPixelY">Map pixel Y.</param>
/// <returns>Map pixel ID.</returns>
public static int GetMapPixelID(int mapPixelX, int mapPixelY)
{
return mapPixelY * 1000 + mapPixelX;
}
public static DFPosition GetPixelFromPixelID(int pixelID)
{
int x = pixelID % 1000;
int y = (pixelID - x) / 1000;
return new DFPosition(x, y);
}
/// <summary>
/// Gets ID of map pixel using latitude and longitude.
/// This can be mapped to location IDs and quest IDs.
/// MapTableData.MapId & 0x000fffff = WorldPixelID.
/// </summary>
/// <param name="longitude">Longitude position.</param>
/// <param name="latitude">Latitude position.</param>
/// <returns>Map pixel ID.</returns>
public static int GetMapPixelIDFromLongitudeLatitude(int longitude, int latitude)
{
DFPosition pos = LongitudeLatitudeToMapPixel(longitude, latitude);
return pos.Y * 1000 + pos.X;
}
/// <summary>
/// Converts map pixel to world coord.
/// </summary>
/// <param name="mapPixelX">Map pixel X.</param>
/// <param name="mapPixelY">Map pixel Y.</param>
/// <returns>World position.</returns>
public static DFPosition MapPixelToWorldCoord(int mapPixelX, int mapPixelY)
{
DFPosition pos = new DFPosition();
pos.X = mapPixelX * 32768;
pos.Y = (499 - mapPixelY) * 32768;
return pos;
}
/// <summary>
/// Converts world coord to nearest map pixel.
/// </summary>
/// <param name="worldX">World X position in native Daggerfall units.</param>
/// <param name="worldZ">World Z position in native Daggerfall units.</param>
/// <returns>Map pixel position.</returns>
public static DFPosition WorldCoordToMapPixel(int worldX, int worldZ)
{
DFPosition pos = new DFPosition();
pos.X = worldX / 32768;
pos.Y = 499 - (worldZ / 32768);
return pos;
}
/// <summary>
/// Converts world coord back to longitude and latitude.
/// </summary>
/// <param name="worldX">World X position in native Daggerfall units.</param>
/// <param name="worldZ">World Z position in native Daggerfall units.</param>
/// <returns>Longitude and latitude.</returns>
public static DFPosition WorldCoordToLongitudeLatitude(int worldX, int worldZ)
{
DFPosition mapPixel = WorldCoordToMapPixel(worldX, worldZ);
DFPosition pos = new DFPosition();
pos.X = mapPixel.X * 128;
pos.Y = (499 - mapPixel.Y) * 128;
return pos;
}
/// <summary>
/// Gets settings for specified map climate.
/// </summary>
/// <param name="worldClimate">Climate value from CLIMATE.PAK. Valid range is 223-232.</param>
/// <returns>Climate settings for specified world climate value.</returns>
public static DFLocation.ClimateSettings GetWorldClimateSettings(int worldClimate)
{
// Create settings struct
DFLocation.ClimateSettings settings = new DFLocation.ClimateSettings();
settings.WorldClimate = worldClimate;
// Set based on world climate
switch (worldClimate)
{
case (int)Climates.Ocean: // Ocean
settings.ClimateType = DFLocation.ClimateBaseType.Swamp;
settings.GroundArchive = 402;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_TemperateWoodland;
settings.SkyBase = 24;
settings.People = FactionFile.FactionRaces.Breton;
break;
case (int)Climates.Desert:
case (int)Climates.Desert2:
settings.ClimateType = DFLocation.ClimateBaseType.Desert;
settings.GroundArchive = 2;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_Desert;
settings.SkyBase = 8;
settings.People = FactionFile.FactionRaces.Redguard;
break;
case (int)Climates.Mountain:
settings.ClimateType = DFLocation.ClimateBaseType.Mountain;
settings.GroundArchive = 102;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_Mountains;
settings.SkyBase = 0;
settings.People = FactionFile.FactionRaces.Nord;
break;
case (int)Climates.Rainforest:
settings.ClimateType = DFLocation.ClimateBaseType.Swamp;
settings.GroundArchive = 402;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_RainForest;
settings.SkyBase = 24;
settings.People = FactionFile.FactionRaces.Redguard;
break;
case (int)Climates.Swamp:
settings.ClimateType = DFLocation.ClimateBaseType.Swamp;
settings.GroundArchive = 402;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_Swamp;
settings.SkyBase = 24;
settings.People = FactionFile.FactionRaces.Breton;
break;
case (int)Climates.Subtropical:
settings.ClimateType = DFLocation.ClimateBaseType.Desert;
settings.GroundArchive = 2;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_SubTropical;
settings.SkyBase = 24;
settings.People = FactionFile.FactionRaces.Breton;
break;
case (int)Climates.MountainWoods:
settings.ClimateType = DFLocation.ClimateBaseType.Temperate;
settings.GroundArchive = 102;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_TemperateWoodland;
settings.SkyBase = 16;
settings.People = FactionFile.FactionRaces.Breton;
break;
case (int)Climates.Woodlands:
settings.ClimateType = DFLocation.ClimateBaseType.Temperate;
settings.GroundArchive = 302;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_TemperateWoodland;
settings.SkyBase = 16;
settings.People = FactionFile.FactionRaces.Breton;
break;
case (int)Climates.HauntedWoodlands:
settings.ClimateType = DFLocation.ClimateBaseType.Temperate;
settings.GroundArchive = 302;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_HauntedWoodlands;
settings.SkyBase = 16;
settings.People = FactionFile.FactionRaces.Breton;
break;
default:
settings.ClimateType = DFLocation.ClimateBaseType.Temperate;
settings.GroundArchive = 302;
settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_TemperateWoodland;
settings.SkyBase = 16;
settings.People = FactionFile.FactionRaces.Breton;
break;
}
// Set nature set from nature archive index
settings.NatureSet = (DFLocation.ClimateTextureSet)settings.NatureArchive;
return settings;
}
#endregion
#region Public Methods
/// <summary>
/// Load MAPS.BSA file.
/// </summary>
/// <param name="filePath">Absolute path to MAPS.BSA file.</param>
/// <param name="usage">Specify if file will be accessed from disk, or loaded into RAM.</param>
/// <param name="readOnly">File will be read-only if true, read-write if false.</param>
/// <returns>True if successful, otherwise false.</returns>
public bool Load(string filePath, FileUsage usage, bool readOnly)
{
// Validate filename
if (!filePath.EndsWith("MAPS.BSA", StringComparison.InvariantCultureIgnoreCase))
return false;
// Load PAK files
string arena2Path = Path.GetDirectoryName(filePath);
climatePak = new PakFile(Path.Combine(arena2Path, "CLIMATE.PAK"));
politicPak = new PakFile(Path.Combine(arena2Path, "POLITIC.PAK"));
// Load file
isReady = false;
if (!bsaFile.Load(filePath, usage, readOnly))
return false;
// Create records array
regions = new RegionRecord[RegionCount];
// Set ready flag
isReady = true;
return true;
}
/// <summary>
/// Gets the name of specified region. Does not change the currently loaded region.
/// </summary>
/// <param name="region">Index of region.</param>
/// <returns>Name of the region.</returns>
public string GetRegionName(int region)
{
if (region < 0 || region >= RegionCount)
return string.Empty;
else
return regionNames[region];
}
/// <summary>
/// Gets index of region with specified name. Does not change the currently loaded region.
/// </summary>
/// <param name="name">Name of region.</param>
/// <returns>Index of found region, or -1 if not found.</returns>
public int GetRegionIndex(string name)
{
// Search for region name
for (int i = 0; i < RegionCount; i++)
{
if (regionNames[i] == name)
return i;
}
return -1;
}
/// <summary>
/// Load a region into memory by name and decompose it for use.
/// </summary>
/// <param name="name">Name of region.</param>
/// <returns>True if successful, otherwise false.</returns>
public bool LoadRegion(string name)
{
return LoadRegion(GetRegionIndex(name));
}
/// <summary>
/// Load a region into memory by index and decompose it for use.
/// </summary>
/// <param name="region">Index of region to load.</param>
/// <returns>True if successful, otherwise false.</returns>
public bool LoadRegion(int region)
{
// Validate
if (region < 0 || region >= RegionCount)
return false;
// Auto discard previous record
if (autoDiscardValue && lastRegion != -1)
DiscardRegion(lastRegion);
// Load record data
int record = region * 4;
regions[region].MapPItem = bsaFile.GetRecordProxy(record++);
regions[region].MapDItem = bsaFile.GetRecordProxy(record++);
regions[region].MapTable = bsaFile.GetRecordProxy(record++);
regions[region].MapNames = bsaFile.GetRecordProxy(record);
if (regions[region].MapNames.Length == 0 ||
regions[region].MapTable.Length == 0 ||
regions[region].MapPItem.Length == 0 ||
regions[region].MapDItem.Length == 0)
return false;
// Set region name
regions[region].Name = regionNames[region];
// Read region
if (!ReadRegion(region))
{
DiscardRegion(region);
return false;
}
// Set previous record
lastRegion = region;
return true;
}
/// <summary>
/// Discard a region from memory.
/// </summary>
/// <param name="region">Index of region to discard.</param>
public void DiscardRegion(int region)
{
// Validate
if (region >= RegionCount)
return;
// Discard memory files and other data
regions[region].Name = string.Empty;
regions[region].MapNames = null;
regions[region].MapTable = null;
regions[region].MapPItem = null;
regions[region].MapDItem = null;
regions[region].DFRegion = new DFRegion();
}
/// <summary>
/// Discard all regions.
/// </summary>
public void DiscardAllRegions()
{
for (int index = 0; index < RegionCount; index++)
{
DiscardRegion(index);
}
}
/// <summary>
/// Gets a DFRegion by index.
/// </summary>
/// <param name="region">Index of region.</param>
/// <returns>DFRegion.</returns>
public DFRegion GetRegion(int region)
{
// Load the region
if (!LoadRegion(region))
return new DFRegion();
return regions[region].DFRegion;
}
/// <summary>
/// Gets a DFRegion by name.
/// </summary>
/// <param name="name">Name of region.</param>
/// <returns>DFRegion.</returns>
public DFRegion GetRegion(string name)
{
int Region = GetRegionIndex(name);
if (-1 == Region)
return new DFRegion();
return GetRegion(Region);
}
/// <summary>
/// Gets a DFLocation representation of a location.
/// </summary>
/// <param name="region">Index of region.</param>
/// <param name="location">Index of location.</param>
/// <returns>DFLocation.</returns>
public DFLocation GetLocation(int region, int location)
{
// Load the region
if (!LoadRegion(region))
return new DFLocation();
// Read location
DFLocation dfLocation = new DFLocation();
if (!ReadLocation(region, location, ref dfLocation))
return new DFLocation();
// Store indices
dfLocation.RegionIndex = region;
dfLocation.LocationIndex = location;
// Generate smaller dungeon when enabled
if (dfLocation.HasDungeon &&
DaggerfallWorkshop.DaggerfallUnity.Settings.SmallerDungeons &&
!DaggerfallWorkshop.DaggerfallDungeon.IsMainStoryDungeon(dfLocation.MapTableData.MapId))
{
GenerateSmallerDungeon(ref dfLocation);
}
return dfLocation;
}
/// <summary>
/// Gets DFLocation representation of a location.
/// </summary>
/// <param name="regionName">Name of region.</param>
/// <param name="locationName">Name of location.</param>
/// <returns>DFLocation.</returns>
public DFLocation GetLocation(string regionName, string locationName)
{
// Load region
int Region = GetRegionIndex(regionName);
if (!LoadRegion(Region))
return new DFLocation();
// Check location exists
if (!regions[Region].DFRegion.MapNameLookup.ContainsKey(locationName))
return new DFLocation();
// Get location index
int Location = regions[Region].DFRegion.MapNameLookup[locationName];
return GetLocation(Region, Location);
}
/// <summary>
/// Lookup block name for exterior block from location data provided.
/// </summary>
/// <param name="dfLocation">DFLocation to read block name.</param>
/// <param name="x">Block X coordinate.</param>
/// <param name="y">Block Y coordinate.</param>
/// <returns>Block name.</returns>
public string GetRmbBlockName(ref DFLocation dfLocation, int x, int y)
{
int index = y * dfLocation.Exterior.ExteriorData.Width + x;
return dfLocation.Exterior.ExteriorData.BlockNames[index];
}
/// <summary>
/// Resolve block name for exterior block from X, Y coordinates.
/// </summary>
/// <param name="dfLocation">DFLocation to resolve block name.</param>
/// <param name="x">Block X coordinate.</param>
/// <param name="y">Block Y coordinate.</param>
/// <returns>Block name.</returns>
public string ResolveRmbBlockName(ref DFLocation dfLocation, int x, int y)
{
// Get indices
int offset = y * dfLocation.Exterior.ExteriorData.Width + x;
byte blockIndex = dfLocation.Exterior.ExteriorData.BlockIndex[offset];
byte blockNumber = dfLocation.Exterior.ExteriorData.BlockNumber[offset];
byte blockCharacter = dfLocation.Exterior.ExteriorData.BlockCharacter[offset];
return ResolveRmbBlockName(ref dfLocation, blockIndex, blockNumber, blockCharacter);
}
/// <summary>
/// Resolve block name from raw components.
/// </summary>
/// <param name="dfLocation">DFLocation to resolve block name.</param>
/// <param name="blockIndex">Block index.</param>
/// <param name="blockNumber">Block number.</param>
/// <param name="blockCharacter">Block character.</param>
/// <returns>Block name.</returns>
public string ResolveRmbBlockName(ref DFLocation dfLocation, byte blockIndex, byte blockNumber, byte blockCharacter)
{
string letter1 = string.Empty;
string letter2 = string.Empty;
string numbers = string.Empty;
// Get prefix
string prefix = rmbBlockPrefixes[blockIndex];
// Get letter 1
if ((blockCharacter & 0x10) != 0)
{
int asciiValue = dfLocation.Exterior.ExteriorData.Letter1ForRMBName;
letter1 = char.ConvertFromUtf32(asciiValue);
}
else
letter1 = "A";
// Get letter 2
letter2 = letter2Array[(byte)(2 * blockCharacter) >> 6];
// Get block number as a string
string blockNumberString = blockNumber.ToString();
if (blockIndex == 13 || blockIndex == 14)
{
// Handle temple numbers
int asciivalue = (blockCharacter & 0xF) + 65;
numbers = char.ConvertFromUtf32(asciivalue) + blockNumberString;
}
else
{
// Numbers are uniform in non-temple blocks
numbers = string.Format("{0:00}", blockNumber);
}
return prefix + letter1 + letter2 + numbers + ".RMB";
}
/// <summary>
/// Reads climate index from CLIMATE.PAK based on world pixel.
/// </summary>
/// <param name="mapPixelX">Map pixel X position.</param>
/// <param name="mapPixelY">Map pixel Y position.</param>
public int GetClimateIndex(int mapPixelX, int mapPixelY)
{
// Add +1 to X coordinate to line up with height map
mapPixelX += 1;
return climatePak.GetValue(mapPixelX, mapPixelY);
}
/// <summary>
/// Reads politic index from POLITIC.PAK based on world pixel.
/// </summary>
/// <param name="mapPixelX">Map pixel X position.</param>
/// <param name="mapPixelY">Map pixel Y position.</param>
public int GetPoliticIndex(int mapPixelX, int mapPixelY)
{
mapPixelX += 1;
return politicPak.GetValue(mapPixelX, mapPixelY);
}
/// <summary>
/// Sets climate index from CLIMATE.PAK based on world pixel.
/// Allows loaded climate data from Pak file to be modified by mods.
/// </summary>
/// <param name="mapPixelX">Map pixel X position.</param>
/// <param name="mapPixelY">Map pixel Y position.</param>
/// <param name="value">The climate to set for the specified map pixel.</param>
/// <returns>True if climate index was set, false otherwise.</returns>
public bool SetClimateIndex(int mapPixelX, int mapPixelY, Climates value)
{
mapPixelX += 1;
return climatePak.SetValue(mapPixelX, mapPixelY, (byte)value);
}
/// <summary>
/// Reads politic index from POLITIC.PAK based on world pixel.
/// Allows loaded region data from Pak file to be modified by mods.
/// </summary>
/// <param name="mapPixelX">Map pixel X position.</param>
/// <param name="mapPixelY">Map pixel Y position.</param>
/// <param name="value">The politic index to set for the specified map pixel.</param>
/// <returns>True if politic index was set, false otherwise.</returns>
public bool SetPoliticIndex(int mapPixelX, int mapPixelY, byte value)
{
mapPixelX += 1;
return politicPak.SetValue(mapPixelX, mapPixelY, value);
}
#endregion
#region Readers
/// <summary>
/// Read a region.
/// </summary>
/// <param name="region">The region index to read.</param>
/// <returns>True if successful, otherwise false.</returns>
private bool ReadRegion(int region)
{
try
{
// Store region name
regions[region].DFRegion.Name = regionNames[region];
// Read map names
BinaryReader reader = regions[region].MapNames.GetReader();
ReadMapNames(ref reader, region);
// Read map table
reader = regions[region].MapTable.GetReader();
ReadMapTable(ref reader, region);
}
catch (Exception e)
{
DiscardRegion(region);
Console.WriteLine(e.Message);
return false;
}
// Add any additional replacement location data to the region, assigning locationIndex
WorldDataReplacement.GetDFRegionAdditionalLocationData(region, ref regions[region].DFRegion);
return true;
}
/// <summary>
/// Read a location from the currently loaded region.
/// </summary>
/// <param name="region">Region index.</param>
/// <param name="location">Location index.</param>
/// <param name="dfLocation">DFLocation object to receive data.</param>
/// <returns>True if successful, otherwise false.</returns>
private bool ReadLocation(int region, int location, ref DFLocation dfLocation)
{
// Check for replacement location data and use it if found
if (WorldDataReplacement.GetDFLocationReplacementData(region, location, out dfLocation))
return true;
try
{
// Store parent region name
dfLocation.RegionName = RegionNames[region];
// Read MapPItem for this location
BinaryReader reader = regions[region].MapPItem.GetReader();
ReadMapPItem(ref reader, region, location, ref dfLocation);
// Read MapDItem for this location
reader = regions[region].MapDItem.GetReader();
ReadMapDItem(ref reader, region, ref dfLocation);
// Copy RegionMapTable data to this location
dfLocation.MapTableData = regions[region].DFRegion.MapTable[location];
// Read climate and politic data
ReadClimatePoliticData(ref dfLocation);
// Set loaded flag
dfLocation.Loaded = true;
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}
/// <summary>
/// Reads information from CLIMATE.PAK and POLITIC.PAK.
/// </summary>
/// <param name="dfLocation">DFLocation.</param>
private void ReadClimatePoliticData(ref DFLocation dfLocation)
{
DFPosition pos = LongitudeLatitudeToMapPixel(dfLocation.MapTableData.Longitude, dfLocation.MapTableData.Latitude);
// Read politic data. This should always equal region index + 128.
dfLocation.Politic = politicPak.GetValue(pos.X, pos.Y);
// Read climate data
int worldClimate = climatePak.GetValue(pos.X, pos.Y);
dfLocation.Climate = MapsFile.GetWorldClimateSettings(worldClimate);
}
/// <summary>
/// Read map names.
/// </summary>
/// <param name="reader">A binary reader to data.</param>
/// <param name="region">Destination region index.</param>
private void ReadMapNames(ref BinaryReader reader, int region)
{
// Location count
reader.BaseStream.Position = 0;
regions[region].DFRegion.LocationCount = reader.ReadUInt32();
// Read names
regions[region].DFRegion.MapNames = new String[regions[region].DFRegion.LocationCount];
regions[region].DFRegion.MapNameLookup = new System.Collections.Generic.Dictionary<string, int>();
for (int i = 0; i < regions[region].DFRegion.LocationCount; i++)
{
// Read map name data
regions[region].DFRegion.MapNames[i] = FileProxy.ReadCStringSkip(reader, 0, 32);
// Add to dictionary
if (!regions[region].DFRegion.MapNameLookup.ContainsKey(regions[region].DFRegion.MapNames[i]))
regions[region].DFRegion.MapNameLookup.Add(regions[region].DFRegion.MapNames[i], i);
}
}
/// <summary>
/// Read map table.
/// </summary>
/// <param name="reader">A binary reader to data.</param>
/// <param name="region">Destination region index.</param>
private void ReadMapTable(ref BinaryReader reader, int region)
{
// Read map table for each location
UInt32 bitfield;
reader.BaseStream.Position = 0;
regions[region].DFRegion.MapTable = new DFRegion.RegionMapTable[regions[region].DFRegion.LocationCount];
regions[region].DFRegion.MapIdLookup = new System.Collections.Generic.Dictionary<int, int>();
for (int i = 0; i < regions[region].DFRegion.LocationCount; i++)