OSDN Git Service

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