OSDN Git Service

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