OSDN Git Service

Additional Map metadata
[automap/automap.git] / Automap / Subsystems / AutomapSystem.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
5 using System.IO;
6 using System.Linq;
7 using System.Text;
8 using System.Text.RegularExpressions;
9 using System.Threading;
10
11 using Hjg.Pngcs;
12
13 using ProtoBuf;
14
15 using Vintagestory.API.Client;
16 using Vintagestory.API.Common;
17 using Vintagestory.API.Config;
18 using Vintagestory.API.Datastructures;
19 using Vintagestory.API.MathTools;
20 using Vintagestory.Common;
21
22 namespace Automap
23 {
24         public class AutomapSystem
25         {
26                 private Thread cartographer_thread;
27                 private Thread snapshotThread;
28                 private Snapshotter snapshot;
29                 private ICoreClientAPI ClientAPI { get; set; }
30                 private ILogger Logger { get; set; }
31                 private AChunkRenderer ChunkRenderer { get; set; }
32                 private JsonGenerator JsonGenerator { get; set; }
33
34                 internal const string _mapPath = @"Maps";
35                 internal const string _chunkPath = @"Chunks";
36                 internal const uint editThreshold = 1;
37                 private const string _domain = @"automap";
38                 private const string chunkFile_filter = @"*_*.png";
39                 private const string poiFileName = @"poi_binary";
40                 private const string eoiFileName = @"eoi_binary";
41                 private const string pointsTsvFileName = @"points_of_interest.tsv";
42                 private const string plainMetadataFileName = @"map_metadata.txt";
43                 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
44
45                 private ConcurrentDictionary<Vec2i, ColumnCounter> columnCounters = new ConcurrentDictionary<Vec2i, ColumnCounter>(3, 150);
46                 private ColumnsMetadata chunkTopMetadata;
47                 private PointsOfInterest POIs = new PointsOfInterest();
48                 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
49
50                 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
51                 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
52                 internal Dictionary<int, string> RockIdCodes { get; private set; }
53                 internal Dictionary<int, string> AiryIdCodes { get; private set; }
54
55                 internal CommandType CurrentState { get; set; }
56                 //Run status, Chunks processed, stats, center of map....
57                 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
58                 private Vec2i startChunkColumn;
59
60                 private readonly int chunkSize;
61                 private string path;
62                 private IAsset staticMap;
63                 private PersistedConfiguration configuration;
64
65
66                 public static string AutomapStatusEventKey = @"AutomapStatus";
67                 public static string AutomapCommandEventKey = @"AutomapCommand";
68
69                 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
70                 {
71                         this.ClientAPI = clientAPI;
72                         this.Logger = logger;
73                         chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
74
75                         configuration = config;
76                         ClientAPI.Event.LevelFinalize += EngageAutomap;
77
78                         this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
79
80                         //Listen on bus for commands
81                         ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
82
83
84                         if (configuration.Autostart)
85                         {
86                                 CurrentState = CommandType.Run;
87                                 Logger.Debug("Autostart is Enabled.");
88                         }
89
90                 }
91
92
93                 #region Internals
94                 private void EngageAutomap()
95                 {
96                         path = ClientAPI.GetOrCreateDataPath(_mapPath);
97                         path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
98                         ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
99                                                   
100                         JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
101
102                         string mapFilename = Path.Combine(path, "automap.html");
103                         StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
104
105                         staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
106                         outputText.Write(staticMap.ToText());
107                         outputText.Flush();
108
109                         Prefill_POI_Designators();
110                         startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
111                         chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
112                         Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
113                         Reload_Metadata();
114
115                         ClientAPI.Event.ChunkDirty += ChunkAChanging;
116
117                         cartographer_thread = new Thread(Cartographer)
118                         {
119                                 Name = "Cartographer",
120                                 Priority = ThreadPriority.Lowest,
121                                 IsBackground = true
122                         };
123
124                         snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize,ClientAPI.World.Seed );
125                         snapshotThread = new Thread(Snap)
126                         {
127                                 Name = "Snapshot",
128                                 Priority = ThreadPriority.Lowest,
129                                 IsBackground = true
130                         };
131
132                         ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
133                 }
134
135                 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
136                 {
137                 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);              
138                 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
139                 
140                 columnCounters.AddOrUpdate(topPosition, 
141                                               new ColumnCounter(chunkSize, newOrEdit, chunkCoord), 
142                                               (chkPos, chkChng) => chkChng.Update(chunkCoord, chunkSize, newOrEdit)
143                                              );
144                 
145                 }
146
147                 private void AwakenCartographer(float delayed)
148                 {
149
150                         if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
151                         {
152 #if DEBUG
153                                 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
154 #endif
155
156                                 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
157                                 {
158                                         cartographer_thread.Start();
159                                 }
160                                 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
161                                 {
162                                         //Time to (re)write chunk shards
163                                         cartographer_thread.Interrupt();
164                                 }
165                                 //#if DEBUG
166                                 //ClientAPI.TriggerChatMessage($"Automap {updatedChunksTotal} Updates - MAX (N:{chunkTopMetadata.North_mostChunk},S:{chunkTopMetadata.South_mostChunk},E:{chunkTopMetadata.East_mostChunk}, W:{chunkTopMetadata.West_mostChunk} - TOTAL: {chunkTopMetadata.Count})");
167                                 //#endif
168                         }
169                         else if (CurrentState == CommandType.Snapshot)
170                         {
171                                 if (snapshotThread.ThreadState.HasFlag(ThreadState.Unstarted))
172                                 {
173                                         snapshotThread.Start();
174                                 } else if (snapshotThread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
175                                 {
176                                         snapshotThread.Interrupt();
177                                 }
178                         }
179
180                 }
181
182
183                 private void Cartographer()
184                 {
185                         wake:
186                         Logger.VerboseDebug("Cartographer thread awoken");
187
188                         try
189                         {
190                                 ColumnCounter ejectedItem ;
191                                 uint updatedChunks = 0;
192                                 uint updatedPixels = 0;
193
194                                 //-- Should dodge enumerator changing underfoot....at a cost.
195                                 if (!columnCounters.IsEmpty)
196                                 {
197                                         var tempSet = columnCounters.ToArray().Where(cks => cks.Value.WeightedSum > editThreshold) .OrderByDescending(kvp => kvp.Value.WeightedSum);
198                                         UpdateEntityMetadata();
199
200                                         foreach (var mostActiveCol in tempSet)
201                                         {
202                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
203
204                                                 if (mapChunk == null)
205                                                 {
206                                                         //TODO: REVISIT THIS CHUNK!
207                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
208                                                         nullMapCount++;
209                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
210                                                         continue;
211                                                 }
212
213                                                 ColumnMeta chunkMeta;
214                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key))
215                                                 {
216                                                         chunkMeta = chunkTopMetadata[mostActiveCol.Key];
217                                                         #if DEBUG
218                                                         Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
219                                                         #endif
220                                                 }
221                                                 else
222                                                 {
223                                                         chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
224                                                         #if DEBUG
225                                                         Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
226                                                         #endif
227                                                 }
228                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
229
230                                                 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
231                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
232
233                                                 if (updatedPixels > 0)
234                                                 {
235                                                         #if DEBUG
236                                                         Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
237                                                         #endif
238                                                         updatedChunks++;
239                                                         chunkTopMetadata.Update(chunkMeta);
240                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
241                                                 }
242                                                 else
243                                                 {
244                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
245                                                         #if DEBUG
246                                                         Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
247                                                         #endif
248                                                 }
249                                         }
250                                 }
251
252                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
253
254                                 if (updatedChunks > 0)
255                                 {
256                                         //What about chunk updates themselves; a update bitmap isn't kept...
257                                         updatedChunksTotal += updatedChunks;
258                                         JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
259                                         updatedChunks = 0;
260
261                                         //Cleanup in-memory Metadata...
262                                         chunkTopMetadata.ClearMetadata( );
263                                 }
264
265                                 #if DEBUG
266                                 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
267                                 #endif
268
269                                 columnCounters.Clear( );
270
271                                 //Then sleep until interupted again, and repeat
272 #if DEBUG
273                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
274 #endif
275                                 Thread.Sleep(Timeout.Infinite);
276
277                         }
278                         catch (ThreadInterruptedException)
279                         {
280
281 #if DEBUG
282                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
283 #endif
284                                 goto wake;
285
286                         }
287                         catch (ThreadAbortException)
288                         {
289 #if DEBUG
290                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
291 #endif
292                         }
293                         finally
294                         {
295 #if DEBUG
296                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
297 #endif
298                                 PersistPointsData();
299                                 Write_PlainMetadata( );
300                         }
301                 }
302
303                 private void Snap()
304                 {
305                         snapshotTake:
306 #if DEBUG
307                         Logger.VerboseDebug("Snapshot started");
308 #endif
309                         try
310                         {
311                                 snapshot.Take();
312 #if DEBUG
313                                 Logger.VerboseDebug("Snapshot sleeping");
314 #endif
315                                 CurrentState = CommandType.Run;
316                                 Thread.Sleep(Timeout.Infinite);
317                         }
318                         catch (ThreadInterruptedException)
319                         {
320 #if DEBUG
321                                 Logger.VerboseDebug("Snapshot intertupted");
322 #endif
323                                 goto snapshotTake;
324                         }
325                 }
326
327                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
328                 {
329                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
330
331                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
332                 }
333
334                 private void Prefill_POI_Designators()
335                 {
336
337                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
338                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
339                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
340
341                         var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
342                                                          where airyBlock.MatterState == EnumMatterState.Solid
343                                                          where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
344                                                          where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0
345                                                          select airyBlock;                      
346                         //^^ 'Solid' phase - 'Plant' Blocks without any boundg box ? Except water...
347                         this.AiryIdCodes = airBlocksQuery.ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
348
349                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
350                         Reload_POI_Designators();
351                 }
352
353                 private void Reload_POI_Designators()
354                 {
355                         Logger.VerboseDebug("Connecting {0} Configured Block-Designators", configuration.BlockDesignators.Count);
356                         foreach (var designator in configuration.BlockDesignators)
357                         {
358                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
359                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
360                                 foreach (var entry in blockIDs)
361                                 {
362                                         BlockID_Designators.Add(entry.Key, designator);
363                                 }
364                         }
365                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
366
367
368                         Logger.VerboseDebug("Connecting {0} Configured Entity-Designators", configuration.EntityDesignators.Count);
369                         foreach (var designator in configuration.EntityDesignators)
370                         {
371                                 //Get Variants first, from EntityTypes...better be populated!
372                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
373
374                                 foreach (var match in matched)
375                                 {
376                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
377                                         this.Entity_Designators.Add(match.Code, designator);
378                                 }
379
380                                 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
381                         }
382
383
384                 }
385
386
387
388                 /// <summary>
389                 /// Store Points/Entity of Interest
390                 /// </summary>
391                 private void PersistPointsData()
392                 {
393                         //POI and EOI raw dump files ~ WRITE em!
394                         //var poiRawFile = File.
395                         string poiPath = Path.Combine(path, poiFileName);
396                         string eoiPath = Path.Combine(path, eoiFileName);
397
398                         if (this.POIs.Count > 0)
399                         {
400                                 using (var poiFile = File.OpenWrite(poiPath))
401                                 {
402                                         Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
403                                 }
404                         }
405
406                         if (this.EOIs.Count > 0)
407                         {
408                                 using (var eoiFile = File.OpenWrite(eoiPath))
409                                 {
410                                         Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
411                                 }
412                         }
413
414                         //Create Easy to Parse TSV file for tool/human use....
415                         string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
416
417                         using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
418                         {
419                                 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination");
420                                 foreach (var point in this.POIs)
421                                 {
422                                         tsvWriter.Write(point.Name + "\t");
423                                         var notes = point.Notes
424                                                 .Replace("\n", "\\n")
425                                                 .Replace("\t", "\\t")
426                                                 .Replace("\\", "\\\\");
427                                         tsvWriter.Write(notes + "\t");
428                                         tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
429                                         tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
430                                         tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
431                                         tsvWriter.WriteLine();
432                                 }
433                                 foreach (var entity in this.EOIs)
434                                 {
435                                         tsvWriter.Write(entity.Name + "\t");
436                                         var notes = entity.Notes
437                                                 .Replace("\n", "\\n")
438                                                 .Replace("\t", "\\t")
439                                                 .Replace("\\", "\\\\");
440                                         tsvWriter.Write(notes + "\t");
441                                         tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
442                                         tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
443                                         tsvWriter.Write("n/a\t");
444                                         tsvWriter.WriteLine();
445                                 }
446                                 tsvWriter.WriteLine();
447                                 tsvWriter.Flush();
448                         }
449
450                 }
451
452                 private void Write_PlainMetadata( )
453                 { 
454                 string metaPath = Path.Combine(path, plainMetadataFileName);
455
456                 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
457                 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII)) 
458                         {
459                                 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
460                                 mdWriter.WriteLine("PlayerCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
461                                 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
462                                 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
463                                 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
464                                 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
465                                 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
466                                 mdWriter.WriteLine("Version '{0}'", ClientAPI.Self().Info.Version);
467                                 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
468                                 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
469                                 mdWriter.Flush( );
470                         }
471                 }
472                 }
473                         
474
475                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
476                 {
477                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
478                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
479                                                                                         mapChunk.YMax,
480                                                                                         mostActiveCol.Key.Y * chunkSize);
481
482                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
483                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
484
485                         return data;
486                 }
487
488                 /// <summary>
489                 /// Reload chunk bounds from chunk shards
490                 /// </summary>
491                 /// <returns>The metadata.</returns>
492                 private void Reload_Metadata()
493                 {
494                         var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
495
496                         if (!shardsDir.Exists)
497                         {
498                                 #if DEBUG
499                                 Logger.VerboseDebug("Could not open world map (shards) directory");
500                                 #endif
501                                 return;
502                         }
503                         var shardFiles = shardsDir.GetFiles(chunkFile_filter);
504
505                         if (shardFiles.Length > 0)
506                         {
507                                 #if DEBUG
508                                 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
509                                 #endif
510
511                                 foreach (var shardFile in shardFiles)
512                                 {
513
514                                         if (shardFile.Length < 1024) continue;
515                                         var result = chunkShardRegex.Match(shardFile.Name);
516                                         if (!result.Success) continue;
517
518                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
519                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
520
521                                         try
522                                         {
523                                                 using (var fileStream = shardFile.OpenRead())
524                                                 {
525
526                                                         PngReader pngRead = new PngReader(fileStream);
527                                                         pngRead.ReadSkippingAllRows();
528                                                         pngRead.End();
529                                                         //Parse PNG chunks for METADATA in shard
530                                                         PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
531                                                         var column = metadataFromPng.ChunkMetadata;
532                                                         if (column.PrettyLocation == null)
533                                                                 column = column.Reload(ClientAPI);
534                                                         chunkTopMetadata.Add(column);
535                                                 }
536
537                                         }
538                                         catch (PngjException someEx)
539                                         {
540                                                 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
541                                                 continue;
542                                         }
543                                         catch (ProtoException protoEx) 
544                                         {
545                                                 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
546                                                 continue;
547                                         }
548                                 }
549                         }
550
551                         //POI and EOI raw dump files ~ reload em!
552                         //var poiRawFile = File.
553                         string poiPath = Path.Combine(path, poiFileName);
554                         string eoiPath = Path.Combine(path, eoiFileName);
555
556                         if (File.Exists(poiPath))
557                         {
558                                 using (var poiFile = File.OpenRead(poiPath))
559                                 {
560                                         this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
561                                         Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
562                                 }
563                         }
564
565                         if (File.Exists(eoiPath))
566                         {
567                                 using (var eoiFile = File.OpenRead(eoiPath))
568                                 {
569                                         this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
570                                         Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
571                                 }
572                         }
573
574                 }
575
576
577
578                 /// <summary>
579                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
580                 /// </summary>
581                 /// <param name="key">Chunk Coordinate</param>
582                 /// <param name="mapChunk">Map chunk.</param>
583                 /// <param name="chunkMeta">Chunk metadata</param>
584                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
585                 {
586                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish... 
587                         byte chunkTally = 0;
588
589                 #if DEBUG
590                 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
591                 #endif
592
593                 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
594
595                 for (; targetChunkY > 0; targetChunkY--)
596                         {
597                                 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
598
599                                 if (worldChunk == null || worldChunk.BlockEntities == null)
600                                 {
601                                         #if DEBUG
602                                         Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
603                                         #endif
604                                         nullChunkCount++;
605                                         continue;
606                                 }
607
608                                 if (worldChunk.IsPacked()) 
609                                 {
610                                 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
611                                 worldChunk.Unpack( );//RESEARCH: Thread Unsafe? 
612                                 }
613
614                                 /*************** Chunk Entities Scanning *********************/
615                                 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
616                                 {
617                                         #if DEBUG
618                                         Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
619                                         #endif
620
621                                         foreach (var blockEnt in worldChunk.BlockEntities)
622                                         {
623                                                 if (blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
624                                                 {
625                                                         var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
626                                                         designator.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
627                                                 }
628                                         }
629                                 }
630
631                                 /********************* Chunk/Column BLOCKs scanning ****************/
632                                 //Heightmap, Stats, block tally
633
634                                 int X_index, Y_index, Z_index;
635
636                                 //First Chance fail-safe;
637                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
638                                 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
639                                 nullChunkCount++;
640                                 continue;
641                                 }               
642
643                                 chunkMeta.ColumnPresense[targetChunkY] = true;
644                                 chunkTally++;
645                                 for (Y_index = 0; Y_index < chunkSize; Y_index++)
646                                 {
647                                         for (Z_index = 0; Z_index < chunkSize; Z_index++)
648                                         {
649                                                 for (X_index = 0; X_index < chunkSize; X_index++) 
650                                                 {
651                                                 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
652
653                                                 //'Last' Chance fail-safe;
654                                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
655                                                 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
656                                                 nullChunkCount++;
657                                                 goto loop_bustout; ;
658                                                 }
659
660                                                 int aBlockId = worldChunk.Blocks[indicie];
661
662                                                 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
663                                                 chunkMeta.AirBlocks++;
664                                                 continue;
665                                                 }
666
667                                                 if (RockIdCodes.ContainsKey(aBlockId)) {
668                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
669                                                         chunkMeta.RockRatio[aBlockId]++;
670                                                 else
671                                                         chunkMeta.RockRatio.Add(aBlockId, 1);
672                                                 }
673
674                                                 chunkMeta.NonAirBlocks++;
675
676                                                 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
677                                                 //Heightmap - Need to ignore Grass & Snow
678                                                 if (localHeight > chunkMeta.HeightMap[X_index, Z_index]) 
679                                                         {
680                                                         chunkMeta.HeightMap[X_index, Z_index] = localHeight;
681                                                         if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
682                                                         }
683                                                 }
684                                         }
685                                 }
686                                 loop_bustout:;
687                         }
688                         Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
689                 }
690
691                 private void UpdateEntityMetadata()
692                 {
693                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
694                         //Mabey scan only for 'new' entities by tracking ID in set?
695                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
696                         {
697
698                                 #if DEBUG
699                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
700                                 #endif
701
702                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
703                                 if (dMatch.Value != null)
704                                 {
705                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.Pos.AsBlockPos.Copy(), loadedEntity.Value);
706                                 }
707
708                         }
709
710
711                 }
712
713                 private void AddNote(string notation)
714                 {
715                         var playerNodePoi = new PointOfInterest()
716                         {
717                                 Name = "Note",
718                                 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
719                                 Notes = notation,
720                                 Timestamp = DateTime.UtcNow,
721                         };
722
723                         this.POIs.AddReplace(playerNodePoi);
724                 }
725
726
727
728                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
729                 {
730                         //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
731
732                         CommandData cmdData = data as CommandData;
733
734                         switch (cmdData.State)
735                         {
736                                 case CommandType.Run:
737                                 case CommandType.Stop:
738                                 case CommandType.Snapshot:
739                                         if (CurrentState != cmdData.State)
740                                         {
741                                                 CurrentState = cmdData.State;
742                                                 AwakenCartographer(0.0f);
743                                         }
744                                         break;
745
746                                 case CommandType.Notation:
747                                         //Add to POI list where player location
748                                         AddNote(cmdData.Notation);
749                                         break;
750                         }
751                         #if DEBUG
752                         ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
753                         #endif
754                 }
755                 #endregion
756
757                 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
758                 {
759                 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
760                 switch (rendererName) 
761                 {                               
762                 case StandardRenderer.Name:
763                         return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
764                 
765                 case AlternateRenderer.Name:
766                         return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
767         
768                 case FlatRenderer.Name:
769                         return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);  
770
771                 default:
772                         throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");
773                 }
774
775                 return null;
776                 }
777         }
778
779 }