OSDN Git Service

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