OSDN Git Service

Potential fix for Memory leak - Clear (some) Metadata post persist
[automap/automap.git] / Automap / Subsystems / AutomapSystem.cs
1 using System;
2 using System.Collections.Concurrent;
3 using System.Collections.Generic;
4 using System.IO;
5 using System.Linq;
6 using System.Reflection;
7 using System.Text;
8 using System.Text.RegularExpressions;
9 using System.Threading;
10
11 using Hjg.Pngcs;
12 using Hjg.Pngcs.Chunks;
13
14 using Newtonsoft.Json;
15
16 using ProtoBuf;
17
18 using Vintagestory.API.Client;
19 using Vintagestory.API.Common;
20 using Vintagestory.API.Config;
21 using Vintagestory.API.Datastructures;
22 using Vintagestory.API.MathTools;
23 using Vintagestory.Common;
24
25 namespace Automap
26 {
27         public class AutomapSystem
28         {
29                 private Thread cartographer_thread;
30                 private ICoreClientAPI ClientAPI { get; set; }
31                 private ILogger Logger { get; set; }
32                 private IChunkRenderer ChunkRenderer { get; set; }
33                 private JsonGenerator JsonGenerator { get; set; }
34
35                 private const string _mapPath = @"Maps";
36                 private const string _chunkPath = @"Chunks";
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 static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+).png", RegexOptions.Singleline);
43
44                 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
45                 private ColumnsMetadata chunkTopMetadata;
46                 private PointsOfInterest POIs = new PointsOfInterest();
47                 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
48                 private string jsonPreBuilt;
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
54                 internal CommandType CurrentState { get; set; }
55                 //Run status, Chunks processed, stats, center of map....
56                 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
57                 private Vec2i startChunkColumn;
58
59                 private readonly int chunkSize;
60                 private string path;
61                 private IAsset staticMap;
62                 private PersistedConfiguration configuration;
63
64
65                 public static string AutomapStatusEventKey = @"AutomapStatus";
66                 public static string AutomapCommandEventKey = @"AutomapCommand";
67                 PersistedConfiguration cachedConfiguration;
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                         ClientAPI.Event.LevelFinalize += EngageAutomap;
75                         configuration = config;
76
77
78                         //TODO:Choose which one from GUI 
79                         this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
80
81                         //Listen on bus for commands
82                         ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
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                         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.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / chunkSize));
109                         chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
110
111                         Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
112                         Reload_Metadata();
113
114                         ClientAPI.Event.ChunkDirty += ChunkAChanging;
115
116                         cartographer_thread = new Thread(Cartographer)
117                         {
118                                 Name = "Cartographer",
119                                 Priority = ThreadPriority.Lowest,
120                                 IsBackground = true
121                         };
122
123                         ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
124                 }
125
126                 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
127                 {
128                         Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
129
130                         columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
131                 }
132
133                 private void AwakenCartographer(float delayed)
134                 {
135
136                         if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
137                         {
138                                 #if DEBUG
139                                 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
140                                 #endif
141
142                                 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
143                                 {
144                                         cartographer_thread.Start();
145                                 }
146                                 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
147                                 {
148                                         //Time to (re)write chunk shards
149                                         cartographer_thread.Interrupt();
150                                 }
151                                 //#if DEBUG
152                                 //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})");
153                                 //#endif
154                         }
155                         else if (CurrentState == CommandType.Snapshot)
156                         {
157                                 //TODO: Snapshot generator second thread...
158                         }
159
160                 }
161
162
163                 private void Cartographer()
164                 {
165                         wake:
166                         Logger.VerboseDebug("Cartographer thread awoken");
167
168                         try
169                         {
170                                 uint ejectedItem = 0;
171                                 uint updatedChunks = 0;
172                                 uint updatedPixels = 0;
173
174                                 //-- Should dodge enumerator changing underfoot....at a cost.
175                                 if (!columnCounter.IsEmpty)
176                                 {
177                                         var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
178                                         UpdateEntityMetadata();
179
180                                         foreach (var mostActiveCol in tempSet)
181                                         {
182                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
183
184                                                 if (mapChunk == null)
185                                                 {
186                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
187                                                         nullMapCount++;
188                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
189                                                         continue;
190                                                 }
191
192                                                 ColumnMeta chunkMeta;
193                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key))
194                                                 {
195                                                         chunkMeta = chunkTopMetadata[mostActiveCol.Key];
196                                                 }
197                                                 else
198                                                 {
199                                                         chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
200                                                 }
201
202                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
203
204                                                 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
205                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
206
207                                                 if (updatedPixels > 0)
208                                                 {
209
210                                                         #if DEBUG
211                                                         Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
212                                                         #endif
213                                                         updatedChunks++;
214                                                         chunkTopMetadata.Update(chunkMeta);
215                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
216                                                 }
217                                                 else
218                                                 {
219                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
220                                                         Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
221                                                 }
222                                         }
223                                 //Cleanup persisted Metadata...
224                                 chunkTopMetadata.ClearMetadata( );
225                                 }
226
227                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
228
229                                 if (updatedChunks > 0)
230                                 {
231                                         //What about chunk updates themselves; a update bitmap isn't kept...
232                                         updatedChunksTotal += updatedChunks;
233                                         JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
234                                         updatedChunks = 0;
235                                 }
236
237                                 //Then sleep until interupted again, and repeat
238
239                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
240
241                                 Thread.Sleep(Timeout.Infinite);
242
243                         }
244                         catch (ThreadInterruptedException)
245                         {
246
247                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
248                                 goto wake;
249
250                         }
251                         catch (ThreadAbortException)
252                         {
253                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
254
255                         }
256                         finally
257                         {
258                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
259                                 PersistPointsData( );
260                         }
261                 }
262
263                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
264                 {
265                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
266
267                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
268                 }
269
270                 private void Prefill_POI_Designators()
271                 {
272
273                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
274                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
275                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
276
277                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
278
279                         Reload_POI_Designators();
280                 }
281
282                 private void Reload_POI_Designators()
283                 {
284                         Logger.VerboseDebug("Connecting {0} Configured Block-Designators", configuration.BlockDesignators.Count);
285                         foreach (var designator in configuration.BlockDesignators)
286                         {
287                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
288                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
289                                 foreach (var entry in blockIDs)
290                                 {
291                                         BlockID_Designators.Add(entry.Key, designator);
292                                 }
293                         }
294                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
295
296
297                         Logger.VerboseDebug("Connecting {0} Configured Entity-Designators", configuration.EntityDesignators.Count);
298                         foreach (var designator in configuration.EntityDesignators)
299                         {
300                                 //Get Variants first, from EntityTypes...better be populated!
301                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
302
303                                 foreach (var match in matched)
304                                 {
305                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
306                                         this.Entity_Designators.Add(match.Code, designator);
307                                 }
308
309
310
311                                 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
312                         }
313
314
315                 }
316
317
318
319                 /// <summary>
320                 /// Store Points/Entity of Interest
321                 /// </summary>
322                 private void PersistPointsData( )
323                 {
324                 //POI and EOI raw dump files ~ WRITE em!
325                 //var poiRawFile = File.
326                 string poiPath = Path.Combine(path, poiFileName);
327                 string eoiPath = Path.Combine(path, eoiFileName);
328
329                 if (this.POIs.Count > 0) {
330                 using (var poiFile = File.OpenWrite(poiPath)) {
331                         Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
332                 }
333                 }
334
335                 if (this.EOIs.Count > 0) {
336                 using (var eoiFile = File.OpenWrite(eoiPath)) {
337                         Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
338                 }
339                 }
340
341                 //Create Easy to Parse TSV file for tool/human use....
342                 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
343
344                 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
345                 {
346                 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\t");
347                         foreach (var point in this.POIs) {
348                                         tsvWriter.Write(point.Name + "\t");
349                                         tsvWriter.Write(point.Notes + "\t");
350                                         tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
351                                         tsvWriter.Write(point.Timestamp.ToString("u")+"\t");
352                                         tsvWriter.WriteLine();
353                         }
354                         foreach (var entity in this.EOIs) {
355                                         tsvWriter.Write(entity.Name + "\t");
356                                         tsvWriter.Write(entity.Notes + "\t");
357                                         tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
358                                         tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
359                                         tsvWriter.WriteLine( );
360                         }
361                 tsvWriter.WriteLine();
362                 tsvWriter.Flush( );
363                 }
364
365                 }
366
367                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
368                 {
369                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), (byte) chunkSize);
370                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
371                                                                                         mapChunk.YMax,
372                                                                                         mostActiveCol.Key.Y * chunkSize);
373
374                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
375                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
376
377                         return data;
378                 }
379
380                 /// <summary>
381                 /// Reload chunk bounds from chunk shards
382                 /// </summary>
383                 /// <returns>The metadata.</returns>
384                 private void Reload_Metadata()
385                 {
386                         var worldmapDir = new DirectoryInfo(path);
387
388                         if (worldmapDir.Exists)
389                         {
390
391                                 var shardFiles = worldmapDir.GetFiles(chunkFile_filter);
392
393                                 if (shardFiles.Length > 0)
394                                 {
395                                         #if DEBUG
396                                         Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
397                                         #endif
398                                          
399                                         foreach (var shardFile in shardFiles) {
400
401                                         if (shardFile.Length < 1024) continue;
402                                         var result = chunkShardRegex.Match(shardFile.Name);
403                                         if (result.Success) {
404                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
405                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
406
407                                         try 
408                                                 {
409                                                 using (var fileStream = shardFile.OpenRead( )) {
410
411                                                 PngReader pngRead = new PngReader(fileStream);
412                                                 pngRead.ReadSkippingAllRows( );
413                                                 pngRead.End( );
414                                                 //Parse PNG chunks for METADATA in shard
415                                                 PngMetadataChunk metadataFromPng = pngRead.GetChunksList( ).GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
416
417                                                 chunkTopMetadata.Add(metadataFromPng.ChunkMetadata);
418                                                 }
419
420                                                 }
421                                                 catch (PngjException someEx)
422                                                 {
423                                                         Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
424                                                         continue;
425                                                 }
426                                                 }
427
428                                         }
429                                 }
430
431                                 //POI and EOI raw dump files ~ reload em!
432                                 //var poiRawFile = File.
433                                 string poiPath = Path.Combine(path, poiFileName);
434                                 string eoiPath = Path.Combine(path, eoiFileName);
435
436                                 if (File.Exists(poiPath)) {
437                                         using (var poiFile = File.OpenRead(poiPath)) {
438                                         this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
439                                         Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
440                                         }
441                                 }
442
443                                 if (File.Exists(eoiPath)) {
444                                         using (var eoiFile = File.OpenRead(eoiPath)) {
445                                         this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
446                                         Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
447                                         }
448                                 }
449
450                         }
451                         else
452                         {
453                                 #if DEBUG
454                                 Logger.VerboseDebug("Could not open world map directory");
455                                 #endif
456                         }
457
458
459
460                 }
461
462                 private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
463                 {
464                         ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
465
466                         string filename = $"{coord.X}_{coord.Y}.png";
467                         filename = Path.Combine(path, filename);
468
469                         PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
470                         PngMetadata meta = pngWriter.GetMetadata();
471                         meta.SetTimeNow();
472                         meta.SetText("Chunk_X", coord.X.ToString("D"));
473                         meta.SetText("Chunk_Y", coord.Y.ToString("D"));
474                         //Setup specialized meta-data PNG chunks here...
475                         PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
476                         {
477                                 ChunkMetadata = metadata
478                         };
479                         pngWriter.GetChunksList().Queue(pngChunkMeta);
480                         pngWriter.CompLevel = 9;// 9 is the maximum compression
481                         pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
482
483                         return pngWriter;
484                 }
485
486                 /// <summary>
487                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
488                 /// </summary>
489                 /// <param name="key">Chunk Coordinate</param>
490                 /// <param name="mapChunk">Map chunk.</param>
491                 /// <param name="chunkMeta">Chunk metadata</param>
492                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
493                 {
494
495                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ... 
496                         for (; targetChunkY > 0; targetChunkY--)
497                         {
498                         WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
499
500                         if (chunkData == null || chunkData.BlockEntities == null) {
501                         #if DEBUG
502                         Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
503                         #endif
504                         nullChunkCount++;
505                         continue;
506                         }
507
508                                 /*************** Chunk Entities Scanning *********************/
509                                 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
510                                 {
511                                 #if DEBUG
512                                         Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
513                                 #endif
514
515                                         foreach (var blockEnt in chunkData.BlockEntities)
516                                         {
517                                                 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
518                                                 {
519                                                         var designator = BlockID_Designators[blockEnt.Block.BlockId];
520                                                         designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
521                                                 }
522                                         }
523                                 }
524                                 /********************* Chunk/Column BLOCKs scanning ****************/
525                                 //Heightmap, Stats, block tally
526                                 chunkData.Unpack();
527
528                                 int X_index, Y_index, Z_index;
529                                 X_index = Y_index = Z_index = 0;
530
531                                 //Ensure ChunkData Metadata fields arn't null...due to being tossed out
532                                 if (chunkMeta.HeightMap == null) { chunkMeta.HeightMap = new ushort[chunkSize, chunkSize]; }
533                                 if (chunkMeta.RockRatio == null) { chunkMeta.RockRatio = new Dictionary<int, uint>(10); }
534
535                                 do
536                                 {
537                                         do
538                                         {
539                                                 do
540                                                 {
541                                                         /* Encode packed indicie
542                                                         (y * chunksize + z) * chunksize + x
543                                                         */
544                                                         var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
545                                                         int aBlockId = chunkData.Blocks[indicie];
546
547                                                         if (aBlockId == 0)
548                                                         {//Air
549                                                                 chunkMeta.AirBlocks++;
550                                                                 continue;
551                                                         }
552
553                                                         if (RockIdCodes.ContainsKey(aBlockId))
554                                                         {
555                                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
556                                                         }
557
558                                                         chunkMeta.NonAirBlocks++;
559
560                                                         //Heightmap 
561                                                         if (chunkMeta.HeightMap[X_index, Z_index] == 0)
562                                                         { chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize)); }
563
564                                                 }
565                                                 while (X_index++ < (chunkSize - 1));
566                                                 X_index = 0;
567                                         }
568                                         while (Z_index++ < (chunkSize - 1));
569                                         Z_index = 0;
570                                 }
571                                 while (Y_index++ < (chunkSize - 1));
572
573                         }
574                 }
575
576                 private void UpdateEntityMetadata()
577                 {
578                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
579                         //Mabey scan only for 'new' entities by tracking ID in set?
580                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
581                         {
582
583                                 #if DEBUG
584                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
585                                 #endif
586
587                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
588                                 if (dMatch.Value != null)
589                                 {
590                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
591                                 }
592
593                         }
594
595
596                 }
597
598                 private void AddNote(string notation)
599                 {
600                         var playerNodePoi = new PointOfInterest()
601                         {
602                                 Name = "Note",
603                                 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
604                                 Notes = notation,
605                                 Timestamp = DateTime.UtcNow,
606                         };
607
608                         this.POIs.AddReplace(playerNodePoi);
609                 }
610
611
612
613                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
614                 {
615                         Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
616
617                         CommandData cmdData = data as CommandData;
618
619
620                         if (CurrentState != CommandType.Snapshot)
621                         {
622                                 switch (cmdData.State)
623                                 {
624                                         case CommandType.Run:                                                                                           
625                                         case CommandType.Stop:
626                                                 if (CurrentState != cmdData.State) {
627                                                 CurrentState = cmdData.State;
628                                                 AwakenCartographer(0.0f);
629                                                 }
630                                                 break;
631
632                                         case CommandType.Snapshot:
633                                                 CurrentState = CommandType.Stop;
634                                                 //Snapshot starts a second thread/process...
635
636                                                 break;
637
638                                         case CommandType.Notation:
639                                                 //Add to POI list where player location
640                                                 AddNote(cmdData.Notation);
641                                                 break;
642                                 }
643                         }
644
645
646
647 #if DEBUG
648                         ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
649 #endif
650
651                 }
652
653
654
655
656                 #endregion
657
658         }
659
660 }