using System.Runtime.Serialization.Formatters.Binary; using OSMDatastructure; using OSMDatastructure.Graph; namespace Server; public class RegionLoader { private string path { get; } private Dictionary regionIdsDict; public RegionLoader(string path) { this.path = path; this.regionIdsDict = new(); } public HashSet GetNodes(ulong regionHash) { Region r = GetRegion(regionHash); return r.nodes; } public HashSet GetWays(ulong regionHash) { Region r = GetRegion(regionHash); return r.ways; } public Region GetRegion(ulong regionHash) { if (regionIdsDict.ContainsKey(regionHash)) return regionIdsDict[regionHash]; else return LoadRegion(regionHash); } private Region LoadRegion(ulong regionHash) { Region newRegion = new Region(regionHash); BinaryFormatter bFormatter = new BinaryFormatter(); if (regionIdsDict.ContainsKey(regionHash)) throw new Exception("Region already loaded"); if (!Directory.Exists(Path.Join(path, regionHash.ToString()))) throw new FileNotFoundException("Region does not exist"); #pragma warning disable SYSLIB0011 using (FileStream wayFileStream = new FileStream(Path.Join(path, regionHash.ToString(), RegionConverter.WaysFileName), FileMode.Open)) { while (wayFileStream.Position < wayFileStream.Length) { OsmWay deserializedWay = (OsmWay)bFormatter.Deserialize(wayFileStream); newRegion.ways.Add(deserializedWay); } } using (FileStream nodeFileStream = new FileStream(Path.Join(path, regionHash.ToString(), RegionConverter.NodesFileName), FileMode.Open)) { while (nodeFileStream.Position < nodeFileStream.Length) { OsmNode deserializedNode = (OsmNode)bFormatter.Deserialize(nodeFileStream); newRegion.nodes.Add(deserializedNode); } } #pragma warning restore SYSLIB0011 regionIdsDict.Add(regionHash, newRegion); return newRegion; } }