OSDN Git Service

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