OSDN Git Service

chat message -> verbose debug
[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.Text;
7 using System.Text.RegularExpressions;
8 using System.Threading;
9
10 using Hjg.Pngcs;
11 using Hjg.Pngcs.Chunks;
12
13 using Vintagestory.API.Client;
14 using Vintagestory.API.Common;
15 using Vintagestory.API.Config;
16 using Vintagestory.API.Datastructures;
17 using Vintagestory.API.MathTools;
18 using Vintagestory.Common;
19
20 namespace Automap
21 {
22         public class AutomapSystem
23         {
24                 private Thread cartographer_thread;
25                 private ICoreClientAPI ClientAPI { get; set; }
26                 private ILogger Logger { get; set; }
27                 private IChunkRenderer ChunkRenderer { get; set; }
28
29                 private const string _mapPath = @"Maps";
30                 private const string _chunkPath = @"Chunks";
31                 private const string _domain = @"automap";
32                 private const string chunkFile_filter = @"*_*.png";
33                 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+).png", RegexOptions.Singleline);
34
35                 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
36                 private ColumnsMetadata chunkTopMetadata;
37                 private PointsOfInterest POIs = new PointsOfInterest();
38                 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
39
40                 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
41                 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
42                 internal Dictionary<int, string> RockIdCodes { get; private set; }
43
44                 internal RunState CurrentState { get; set; }
45                 //Run status, Chunks processed, stats, center of map....
46                 private uint nullChunkCount, updatedChunksTotal;
47                 private Vec2i startChunkColumn;
48
49                 private readonly int chunkSize;
50                 private string path;
51                 private IAsset staticMap;
52
53                 public static string AutomapStatusEventKey = @"AutomapStatus";
54                 public static string AutomapCommandEventKey = @"AutomapCommand";
55
56
57                 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger)
58                 {
59                         this.ClientAPI = clientAPI;
60                         this.Logger = logger;
61                         chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
62                         ClientAPI.Event.LevelFinalize += EngageAutomap;
63
64                         //TODO:Choose which one from GUI 
65                         this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
66
67                         //Listen on bus for commands
68                         ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
69
70                 }
71
72
73                 #region Internals
74                 private void EngageAutomap()
75                 {
76                         path = ClientAPI.GetOrCreateDataPath(_mapPath);
77                         path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
78
79
80                         string mapFilename = Path.Combine(path, "automap.html");
81                         StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
82
83                         staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
84                         outputText.Write(staticMap.ToText());
85                         outputText.Flush();
86
87                         Prefill_POI_Designators();
88                         startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / chunkSize));
89                         chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
90
91                         Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
92                         Reload_Metadata();
93
94                         ClientAPI.Event.ChunkDirty += ChunkAChanging;
95
96                         cartographer_thread = new Thread(Cartographer)
97                         {
98                                 Name = "Cartographer",
99                                 Priority = ThreadPriority.Lowest,
100                                 IsBackground = true
101                         };
102
103                         ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
104                 }
105
106                 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
107                 {
108                         Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
109
110                         columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
111                 }
112
113                 private void AwakenCartographer(float delayed)
114                 {
115
116                         if (CurrentState == RunState.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
117                         {
118 #if DEBUG
119                                 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
120 #endif
121
122                                 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
123                                 {
124                                         cartographer_thread.Start();
125                                 }
126                                 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
127                                 {
128                                         //Time to (re)write chunk shards
129                                         cartographer_thread.Interrupt();
130                                 }
131                                 //#if DEBUG
132                                 //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})");
133                                 //#endif
134                         }
135                         else if (CurrentState == RunState.Snapshot)
136                         {
137                                 //TODO: Snapshot generator second thread...
138                         }
139
140                 }
141
142
143                 private void Cartographer()
144                 {
145                         wake:
146                         Logger.VerboseDebug("Cartographer thread awoken");
147
148                         try
149                         {
150                                 uint ejectedItem = 0;
151                                 uint updatedChunks = 0;
152
153                                 //-- Should dodge enumerator changing underfoot....at a cost.
154                                 if (!columnCounter.IsEmpty)
155                                 {
156                                         var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
157                                         foreach (var mostActiveCol in tempSet)
158                                         {
159
160                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
161
162                                                 if (mapChunk == null)
163                                                 {
164                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
165                                                         nullChunkCount++;
166                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
167                                                         continue;
168                                                 }
169
170                                                 ColumnMeta chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
171                                                 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
172                                                 UpdateEntityMetadata();
173                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, chunkMeta);
174
175
176                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out uint updatedPixels);
177
178                                                 if (updatedPixels > 0)
179                                                 {
180
181 #if DEBUG
182                                                         Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
183 #endif
184                                                         updatedChunks++;
185                                                         chunkTopMetadata.Update(chunkMeta);
186                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
187                                                 }
188                                                 else
189                                                 {
190                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
191                                                         Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
192                                                 }
193
194                                         }
195                                 }
196
197                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
198
199                                 if (updatedChunks > 0)
200                                 {
201                                         //What about chunk updates themselves; a update bitmap isn't kept...
202                                         updatedChunksTotal += updatedChunks;
203                                         GenerateJSONMetadata();
204                                         updatedChunks = 0;
205                                 }
206
207                                 //Then sleep until interupted again, and repeat
208
209                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
210
211                                 Thread.Sleep(Timeout.Infinite);
212
213                         }
214                         catch (ThreadInterruptedException)
215                         {
216
217                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
218                                 goto wake;
219
220                         }
221                         catch (ThreadAbortException)
222                         {
223                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
224
225                         }
226                         finally
227                         {
228                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
229                         }
230                 }
231
232                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
233                 {
234                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, RunState.Run);
235
236                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
237                 }
238
239                 private void Prefill_POI_Designators()
240                 {
241
242                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
243                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
244                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock"), EnumBlockMaterial.Stone);
245
246                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
247
248                         Install_POI_Designators(DefaultDesignators.DefaultBlockDesignators(), DefaultDesignators.DefaultEntityDesignators());
249                 }
250
251                 private void Install_POI_Designators(ICollection<BlockDesignator> blockDesig, List<EntityDesignator> entDesig)
252                 {
253                         Logger.VerboseDebug("Connecting {0} standard Block-Designators", blockDesig.Count);
254                         foreach (var designator in blockDesig)
255                         {
256                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
257                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
258                                 foreach (var entry in blockIDs)
259                                 {
260                                         BlockID_Designators.Add(entry.Key, designator);
261                                 }
262                         }
263                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
264
265
266                         Logger.VerboseDebug("Connecting {0} standard Entity-Designators", entDesig.Count);
267                         foreach (var designator in entDesig)
268                         {
269                                 //Get Variants first, from EntityTypes...better be populated!
270                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
271
272                                 foreach (var match in matched)
273                                 {
274                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
275                                         this.Entity_Designators.Add(match.Code, designator);
276                                 }
277
278
279
280                                 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
281                         }
282
283
284                 }
285
286                 /// <summary>
287                 /// Generates the JSON Metadata. (in Map object format )
288                 /// </summary>
289                 private void GenerateJSONMetadata()
290                 {
291                         string jsonFilename = Path.Combine(path, "Metadata.js");
292
293                         StreamWriter jsonWriter = new StreamWriter(jsonFilename, false, Encoding.UTF8);
294                         using (jsonWriter)
295                         {
296                                 jsonWriter.Write("ViewFrame.chunks={};");
297                                 jsonWriter.Write("ViewFrame.chunks.worldSeedNum={0};", ClientAPI.World.Seed);
298                                 jsonWriter.Write("ViewFrame.chunks.genTime=new Date('{0}');", DateTimeOffset.UtcNow.ToString("O"));
299                                 jsonWriter.Write("ViewFrame.chunks.startCoords=[{0},{1}];", startChunkColumn.X, startChunkColumn.Y);
300                                 jsonWriter.Write("ViewFrame.chunks.chunkSize={0};", chunkSize);
301                                 jsonWriter.Write("ViewFrame.chunks.northMostChunk={0};", chunkTopMetadata.North_mostChunk);
302                                 jsonWriter.Write("ViewFrame.chunks.southMostChunk={0};", chunkTopMetadata.South_mostChunk);
303                                 jsonWriter.Write("ViewFrame.chunks.eastMostChunk={0};", chunkTopMetadata.East_mostChunk);
304                                 jsonWriter.Write("ViewFrame.chunks.westMostChunk={0};", chunkTopMetadata.West_mostChunk);
305                                 //MAP object format - [key, value]: key is "x_y"
306                                 jsonWriter.Write("ViewFrame.chunks.chunkMetadata=new Map([");
307                                 foreach (var shard in chunkTopMetadata)
308                                 {
309                                         jsonWriter.Write("['{0}_{1}',", shard.Location.X, shard.Location.Y);
310                                         jsonWriter.Write("{");
311                                         jsonWriter.Write("prettyCoord:'{0}',", shard.Location.PrettyCoords(ClientAPI));
312                                         jsonWriter.Write("chunkAge:'{0}',", shard.ChunkAge.ToString("g"));//World age - relative? or last edit ??
313                                         jsonWriter.Write("temp:'{0}',", shard.Temperature.ToString("F1"));
314                                         jsonWriter.Write("YMax:'{0}',", shard.YMax);
315                                         jsonWriter.Write("fert:'{0}',", shard.Fertility.ToString("F1"));
316                                         jsonWriter.Write("forestDens:'{0}',", shard.ForestDensity.ToString("F1"));
317                                         jsonWriter.Write("rain:'{0}',", shard.Rainfall.ToString("F1"));
318                                         jsonWriter.Write("shrubDens:'{0}',", shard.ShrubDensity.ToString("F1"));
319                                         jsonWriter.Write("airBlocks:'{0}',", shard.AirBlocks);
320                                         jsonWriter.Write("nonAirBlocks:'{0}',", shard.NonAirBlocks);
321                                         //TODO: Heightmap
322                                         //TODO: Rock-ratio
323                                         jsonWriter.Write("}],");
324                                 }
325                                 jsonWriter.Write("]);");
326
327
328                                 jsonWriter.Write("ViewFrame.chunks.pointsOfInterest = new Map([");
329                                 foreach (var poi in POIs)
330                                 {
331                                         jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
332                                         jsonWriter.Write("{");
333                                         jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
334                                         jsonWriter.Write("notes:'{0}',", poi.Notes.Replace("'", "\'").Replace("\n","\\n"));
335                                         jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
336                                         jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
337                                         jsonWriter.Write("}],");
338                                 }
339
340                                 foreach (var poi in EOIs)
341                                 {
342                                         jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
343                                         jsonWriter.Write("{");
344                                         jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
345                                         jsonWriter.Write("notes:'{0}',", poi.Notes.Replace("'", "\'"));
346                                         jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
347                                         jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
348                                         jsonWriter.Write("}],");
349                                 }
350                                 jsonWriter.Write("]);");
351
352                                 jsonWriter.Flush();
353                         }
354
355                 }
356
357
358                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
359                 {
360                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), chunkSize);
361                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
362                                                                                         mapChunk.YMax,
363                                                                                         mostActiveCol.Key.Y * chunkSize);
364
365                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
366                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
367
368                         return data;
369                 }
370
371                 /// <summary>
372                 /// Reload chunk bounds from chunk shards
373                 /// </summary>
374                 /// <returns>The metadata.</returns>
375                 private void Reload_Metadata()
376                 {
377                         var worldmapDir = new DirectoryInfo(path);
378
379                         if (worldmapDir.Exists)
380                         {
381
382                                 var files = worldmapDir.GetFiles(chunkFile_filter);
383
384                                 if (files.Length > 0)
385                                 {
386 #if DEBUG
387                                         Logger.VerboseDebug("{0} Existing world chunk shards", files.Length);
388 #endif
389
390
391
392                                         foreach (var shardFile in files)
393                                         {
394
395                                                 if (shardFile.Length < 512) continue;
396                                                 var result = chunkShardRegex.Match(shardFile.Name);
397                                                 if (result.Success)
398                                                 {
399                                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
400                                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
401
402                                                         //Parse PNG chunks for METADATA in shard
403                                                         using var fileStream = shardFile.OpenRead();
404                                                         //TODO: Add corrupted PNG Exception handing HERE !
405                                                         PngReader pngRead = new PngReader(fileStream);
406                                                         pngRead.ReadSkippingAllRows();
407                                                         pngRead.End();
408
409                                                         PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
410
411                                                         chunkTopMetadata.Add(metadataFromPng.ChunkMetadata);
412
413                                                 }
414                                         }
415
416                                 }
417                         }
418                         else
419                         {
420 #if DEBUG
421                                 Logger.VerboseDebug("Could not open world map directory");
422 #endif
423                         }
424
425
426
427                 }
428
429                 private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
430                 {
431                         ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
432
433                         string filename = $"{coord.X}_{coord.Y}.png";
434                         filename = Path.Combine(path, filename);
435
436                         PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
437                         PngMetadata meta = pngWriter.GetMetadata();
438                         meta.SetTimeNow();
439                         meta.SetText("Chunk_X", coord.X.ToString("D"));
440                         meta.SetText("Chunk_Y", coord.Y.ToString("D"));
441                         //Setup specialized meta-data PNG chunks here...
442                         PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
443                         {
444                                 ChunkMetadata = metadata
445                         };
446                         pngWriter.GetChunksList().Queue(pngChunkMeta);
447
448                         return pngWriter;
449                 }
450
451                 /// <summary>
452                 /// Does the heavy lifting of Scanning columns of chunks - creates Heightmap and Processes POIs, Entities, and stats...
453                 /// </summary>
454                 /// <param name="key">Chunk Coordinate</param>
455                 /// <param name="mapChunk">Map chunk.</param>
456                 /// <param name="chunkMeta">Chunk metadata</param>
457                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ColumnMeta chunkMeta)
458                 {
459
460                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ... 
461                         for (; targetChunkY > 0; targetChunkY--)
462                         {
463                                 if (!(ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) is WorldChunk chunkData) || chunkData.BlockEntities == null)
464                                 {
465 #if DEBUG
466                                         Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
467 #endif
468                                         continue;
469                                 }
470
471                                 /*************** Chunk Entities Scanning *********************/
472                                 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
473                                 {
474 #if DEBUG
475                                         Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
476 #endif
477
478                                         foreach (var blockEnt in chunkData.BlockEntities)
479                                         {
480
481                                                 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
482                                                 {
483                                                         var designator = BlockID_Designators[blockEnt.Block.BlockId];
484                                                         designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
485                                                 }
486                                         }
487
488                                 }
489                                 /********************* Chunk/Column BLOCKs scanning ****************/
490                                 //Heightmap, Stats, block tally
491                                 chunkData.Unpack();
492
493                                 int X_index, Y_index, Z_index;
494                                 X_index = Y_index = Z_index = 0;
495
496                                 do
497                                 {
498                                         do
499                                         {
500                                                 do
501                                                 {
502                                                         /* Encode packed indicie
503                                                         (y * chunksize + z) * chunksize + x
504                                                         */
505                                                         var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
506                                                         int aBlockId = chunkData.Blocks[indicie];
507
508                                                         if (aBlockId == 0)
509                                                         {//Air
510                                                                 chunkMeta.AirBlocks++;
511                                                                 continue;
512                                                         }
513
514                                                         if (RockIdCodes.ContainsKey(aBlockId))
515                                                         {
516                                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
517                                                         }
518
519                                                         chunkMeta.NonAirBlocks++;
520
521                                                         //Heightmap 
522                                                         if (chunkMeta.HeightMap[X_index, Z_index] == 0)
523                                                         { chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize)); }
524
525                                                 }
526                                                 while (X_index++ < (chunkSize - 1));
527                                                 X_index = 0;
528                                         }
529                                         while (Z_index++ < (chunkSize - 1));
530                                         Z_index = 0;
531                                 }
532                                 while (Y_index++ < (chunkSize - 1));
533
534                         }
535                 }
536
537                 private void UpdateEntityMetadata()
538                 {
539                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
540                         //Mabey scan only for 'new' entities by tracking ID in set?
541                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToList())
542                         {
543
544 #if DEBUG
545                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
546 #endif
547
548                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
549                                 if (dMatch.Value != null)
550                                 {
551                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
552                                 }
553
554                         }
555
556
557                 }
558
559                 private void AddNote(string notation)
560                 {
561                         var playerNodePoi = new PointOfInterest()
562                         {
563                                 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
564                                 Notes = notation,
565                                 Timestamp = DateTimeOffset.UtcNow,
566                         };
567
568                         this.POIs.AddReplace(playerNodePoi);
569                 }
570
571
572
573                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
574                 {
575                         Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
576
577                         CommandData cmdData = data as CommandData;
578
579
580                         if (CurrentState != RunState.Snapshot)
581                         {
582                                 switch (cmdData.State)
583                                 {
584                                         case RunState.Run:
585                                                 CurrentState = cmdData.State;
586                                                 AwakenCartographer(0.0f);
587                                                 break;
588
589                                         case RunState.Stop:
590                                                 CurrentState = cmdData.State;
591                                                 break;
592
593                                         case RunState.Snapshot:
594                                                 CurrentState = RunState.Stop;
595                                                 //Snapshot starts a second thread/process...
596
597                                                 break;
598
599                                         case RunState.Notation:
600                                                 //Add to POI list where player location
601                                                 AddNote(cmdData.Notation);
602                                                 break;
603                                 }
604
605                         }
606
607                         if (CurrentState != cmdData.State)
608                         {
609                                 CurrentState = cmdData.State;
610                                 AwakenCartographer(0.0f);
611                         }
612
613 #if DEBUG
614                         Logger.VerboseDebug($"Automap commanded to: {cmdData.State} ");
615 #endif
616
617                 }
618
619
620                 #endregion
621
622         }
623
624 }