OSDN Git Service

change the way the metadata is exported, typos
[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 using Newtonsoft.Json;
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                                 uint updatedPixels = 0;
153
154                                 //-- Should dodge enumerator changing underfoot....at a cost.
155                                 if (!columnCounter.IsEmpty)
156                                 {
157                                         var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
158                                         foreach (var mostActiveCol in tempSet)
159                                         {
160
161                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
162
163                                                 if (mapChunk == null)
164                                                 {
165                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
166                                                         nullChunkCount++;
167                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
168                                                         continue;
169                                                 }
170
171                                                 ColumnMeta chunkMeta;
172                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key))
173                                                 {
174                                                         chunkMeta = chunkTopMetadata[mostActiveCol.Key];
175                                                 }
176                                                 else
177                                                 {
178                                                         chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
179                                                 }
180
181                                                 UpdateEntityMetadata();
182                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, chunkMeta);
183
184                                                 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
185                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
186
187                                                 if (updatedPixels > 0)
188                                                 {
189
190 #if DEBUG
191                                                         Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
192 #endif
193                                                         updatedChunks++;
194                                                         chunkTopMetadata.Update(chunkMeta);
195                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
196                                                 }
197                                                 else
198                                                 {
199                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
200                                                         Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
201                                                 }
202
203                                         }
204                                 }
205
206                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
207
208                                 if (updatedChunks > 0)
209                                 {
210                                         //What about chunk updates themselves; a update bitmap isn't kept...
211                                         updatedChunksTotal += updatedChunks;
212                                         GenerateJSONMetadata();
213                                         updatedChunks = 0;
214                                 }
215
216                                 //Then sleep until interupted again, and repeat
217
218                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
219
220                                 Thread.Sleep(Timeout.Infinite);
221
222                         }
223                         catch (ThreadInterruptedException)
224                         {
225
226                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
227                                 goto wake;
228
229                         }
230                         catch (ThreadAbortException)
231                         {
232                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
233
234                         }
235                         finally
236                         {
237                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
238                         }
239                 }
240
241                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
242                 {
243                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, RunState.Run);
244
245                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
246                 }
247
248                 private void Prefill_POI_Designators()
249                 {
250
251                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
252                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
253                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock"), EnumBlockMaterial.Stone);
254
255                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
256
257                         Install_POI_Designators(DefaultDesignators.DefaultBlockDesignators(), DefaultDesignators.DefaultEntityDesignators());
258                 }
259
260                 private void Install_POI_Designators(ICollection<BlockDesignator> blockDesig, List<EntityDesignator> entDesig)
261                 {
262                         Logger.VerboseDebug("Connecting {0} standard Block-Designators", blockDesig.Count);
263                         foreach (var designator in blockDesig)
264                         {
265                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
266                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
267                                 foreach (var entry in blockIDs)
268                                 {
269                                         BlockID_Designators.Add(entry.Key, designator);
270                                 }
271                         }
272                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
273
274
275                         Logger.VerboseDebug("Connecting {0} standard Entity-Designators", entDesig.Count);
276                         foreach (var designator in entDesig)
277                         {
278                                 //Get Variants first, from EntityTypes...better be populated!
279                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
280
281                                 foreach (var match in matched)
282                                 {
283                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
284                                         this.Entity_Designators.Add(match.Code, designator);
285                                 }
286
287
288
289                                 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
290                         }
291
292
293                 }
294
295                 /// <summary>
296                 /// Generates the JSON Metadata. (in Map object format )
297                 /// </summary>
298                 private void GenerateJSONMetadata()
299                 {
300                         string jsonFilename = Path.Combine(path, "Metadata.js");
301
302                         StreamWriter jsonWriter = new StreamWriter(jsonFilename, false, Encoding.UTF8);
303                         using (jsonWriter)
304                         {
305                                 jsonWriter.Write("ViewFrame.chunks={};");
306                                 jsonWriter.Write("ViewFrame.chunks.worldSeedNum={0};", ClientAPI.World.Seed);
307                                 jsonWriter.Write("ViewFrame.chunks.genTime=new Date('{0}');", DateTimeOffset.UtcNow.ToString("O"));
308                                 jsonWriter.Write("ViewFrame.chunks.startCoords=[{0},{1}];", startChunkColumn.X, startChunkColumn.Y);
309                                 jsonWriter.Write("ViewFrame.chunks.chunkSize={0};", chunkSize);
310                                 jsonWriter.Write("ViewFrame.chunks.northMostChunk={0};", chunkTopMetadata.North_mostChunk);
311                                 jsonWriter.Write("ViewFrame.chunks.southMostChunk={0};", chunkTopMetadata.South_mostChunk);
312                                 jsonWriter.Write("ViewFrame.chunks.eastMostChunk={0};", chunkTopMetadata.East_mostChunk);
313                                 jsonWriter.Write("ViewFrame.chunks.westMostChunk={0};", chunkTopMetadata.West_mostChunk);
314                                 // this is so that the tool tip doesnt need to be hard coded in the map 
315                                 jsonWriter.Write("ViewFrame.chunks.chunkMetaNames=[");
316                                 // there are 10 (TEN) (ten) things
317                                 jsonWriter.Write("'Loc.','Age','Temp.','Y Max','Fert.','Forest','Rain','Shrub','Air','Non-Air'");
318                                 jsonWriter.Write("];");
319                                 //MAP object format - [key, value]: key is "x_y"
320                                 jsonWriter.Write("ViewFrame.chunks.chunkMetadata=new Map([");
321                                 foreach (var shard in chunkTopMetadata)
322                                 {
323                                         jsonWriter.Write("['{0}_{1}',", shard.Location.X, shard.Location.Y);
324                                         jsonWriter.Write("[");
325                                         // 10 things but 0 indexed so NINE (9)
326                                         jsonWriter.Write("'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}'",
327                                                 shard.Location.PrettyCoords(ClientAPI),
328                                                 shard.ChunkAge.ToString("g"),//World age - relative? or last edit ??
329                                                 shard.Temperature.ToString("F1"),
330                                                 shard.YMax,
331                                                 shard.Fertility.ToString("F1"),
332                                                 shard.ForestDensity.ToString("F1"),
333                                                 shard.Rainfall.ToString("F1"),
334                                                 shard.ShrubDensity.ToString("F1"),
335                                                 shard.AirBlocks,
336                                                 shard.NonAirBlocks
337                                         );
338                                         //TODO: Rock-ratio, also requires a BlockID => Name lookup table....elsewhere
339                                         jsonWriter.Write("]],");
340                                 }
341                                 jsonWriter.Write("]);");
342
343
344                                 jsonWriter.Write("ViewFrame.chunks.pointsOfInterest=new Map([");
345                                 foreach (var poi in POIs)
346                                 {
347                                         jsonWriter.Write("['{0}_{1}',", (float) poi.Location.X / chunkSize, (float) poi.Location.Z / chunkSize);
348                                         jsonWriter.Write("{");
349                                         jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
350                                         jsonWriter.Write("notes:{0},", JsonConvert.ToString(poi.Notes, '\'', StringEscapeHandling.EscapeHtml));
351                                         jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
352                                         jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
353                                         jsonWriter.Write("}],");
354                                 }
355                                 jsonWriter.Write("]);");
356
357                                 jsonWriter.Write("ViewFrame.chunks.entitiesOfInterest=new Map([");
358                                 foreach (var eoi in EOIs)
359                                 {
360                                         jsonWriter.Write("['{0}_{1}',", (float) eoi.Location.X / chunkSize, (float) eoi.Location.Z / chunkSize);
361                                         jsonWriter.Write("{");
362                                         jsonWriter.Write("prettyCoord:'{0}',", eoi.Location.PrettyCoords(ClientAPI));
363                                         jsonWriter.Write("notes:{0},", JsonConvert.ToString(eoi.Notes, '\'', StringEscapeHandling.EscapeHtml));
364                                         jsonWriter.Write("time:new Date('{0}'),", eoi.Timestamp.ToString("O"));
365                                         jsonWriter.Write("chunkPos:'{0}_{1}',", (eoi.Location.X / chunkSize), (eoi.Location.Z / chunkSize));
366                                         jsonWriter.Write("entityId:'{0}'", eoi.EntityId);
367                                         jsonWriter.Write("}],");
368                                 }
369                                 jsonWriter.Write("]);");
370
371                                 jsonWriter.Flush();
372                         }
373
374                 }
375
376
377                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
378                 {
379                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), (byte) chunkSize);
380                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
381                                                                                         mapChunk.YMax,
382                                                                                         mostActiveCol.Key.Y * chunkSize);
383
384                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
385                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
386
387                         return data;
388                 }
389
390                 /// <summary>
391                 /// Reload chunk bounds from chunk shards
392                 /// </summary>
393                 /// <returns>The metadata.</returns>
394                 private void Reload_Metadata()
395                 {
396                         var worldmapDir = new DirectoryInfo(path);
397
398                         if (worldmapDir.Exists)
399                         {
400
401                                 var files = worldmapDir.GetFiles(chunkFile_filter);
402
403                                 if (files.Length > 0)
404                                 {
405 #if DEBUG
406                                         Logger.VerboseDebug("{0} Existing world chunk shards", files.Length);
407 #endif
408
409                                         foreach (var shardFile in files)
410                                         {
411
412                                                 if (shardFile.Length < 1024) continue;
413                                                 var result = chunkShardRegex.Match(shardFile.Name);
414                                                 if (result.Success)
415                                                 {
416                                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
417                                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
418
419                                                         try
420                                                         {
421                                                                 using (var fileStream = shardFile.OpenRead())
422                                                                 {
423
424                                                                         PngReader pngRead = new PngReader(fileStream);
425                                                                         pngRead.ReadSkippingAllRows();
426                                                                         pngRead.End();
427                                                                         //Parse PNG chunks for METADATA in shard
428                                                                         PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
429
430                                                                         chunkTopMetadata.Add(metadataFromPng.ChunkMetadata);
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
445                         }
446                         else
447                         {
448 #if DEBUG
449                                 Logger.VerboseDebug("Could not open world map directory");
450 #endif
451                         }
452
453
454
455                 }
456
457                 private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
458                 {
459                         ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
460
461                         string filename = $"{coord.X}_{coord.Y}.png";
462                         filename = Path.Combine(path, filename);
463
464                         PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
465                         PngMetadata meta = pngWriter.GetMetadata();
466                         meta.SetTimeNow();
467                         meta.SetText("Chunk_X", coord.X.ToString("D"));
468                         meta.SetText("Chunk_Y", coord.Y.ToString("D"));
469                         //Setup specialized meta-data PNG chunks here...
470                         PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
471                         {
472                                 ChunkMetadata = metadata
473                         };
474                         pngWriter.GetChunksList().Queue(pngChunkMeta);
475                         pngWriter.CompLevel = 9;// 9 is the maximum compression
476                         pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
477
478                         return pngWriter;
479                 }
480
481                 /// <summary>
482                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
483                 /// </summary>
484                 /// <param name="key">Chunk Coordinate</param>
485                 /// <param name="mapChunk">Map chunk.</param>
486                 /// <param name="chunkMeta">Chunk metadata</param>
487                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ColumnMeta chunkMeta)
488                 {
489
490                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ... 
491                         for (; targetChunkY > 0; targetChunkY--)
492                         {
493                                 WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
494                                 if (chunkData == null || chunkData.BlockEntities == null)
495                                 {
496 #if DEBUG
497                                         Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
498 #endif
499                                         continue;
500                                 }
501
502                                 /*************** Chunk Entities Scanning *********************/
503                                 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
504                                 {
505 #if DEBUG
506                                         Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
507 #endif
508
509                                         foreach (var blockEnt in chunkData.BlockEntities)
510                                         {
511
512                                                 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
513                                                 {
514                                                         var designator = BlockID_Designators[blockEnt.Block.BlockId];
515                                                         designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
516                                                 }
517                                         }
518
519                                 }
520                                 /********************* Chunk/Column BLOCKs scanning ****************/
521                                 //Heightmap, Stats, block tally
522                                 chunkData.Unpack();
523
524                                 int X_index, Y_index, Z_index;
525                                 X_index = Y_index = Z_index = 0;
526
527                                 do
528                                 {
529                                         do
530                                         {
531                                                 do
532                                                 {
533                                                         /* Encode packed indicie
534                                                         (y * chunksize + z) * chunksize + x
535                                                         */
536                                                         var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
537                                                         int aBlockId = chunkData.Blocks[indicie];
538
539                                                         if (aBlockId == 0)
540                                                         {//Air
541                                                                 chunkMeta.AirBlocks++;
542                                                                 continue;
543                                                         }
544
545                                                         if (RockIdCodes.ContainsKey(aBlockId))
546                                                         {
547                                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
548                                                         }
549
550                                                         chunkMeta.NonAirBlocks++;
551
552                                                         ////Heightmap
553                                                         //if (chunkMeta.HeightMap[X_index, Z_index] == 0)
554                                                         //{
555                                                         //      chunkMeta.HeightMap[X_index, Z_index]
556                                                         //              = (ushort) (Y_index + (targetChunkY * chunkSize));
557                                                         //}
558                                                 }
559                                                 while (X_index++ < (chunkSize - 1));
560                                                 X_index = 0;
561                                         }
562                                         while (Z_index++ < (chunkSize - 1));
563                                         Z_index = 0;
564                                 }
565                                 while (Y_index++ < (chunkSize - 1));
566
567                         }
568                 }
569
570                 private void UpdateEntityMetadata()
571                 {
572                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
573                         //Mabey scan only for 'new' entities by tracking ID in set?
574                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToList())
575                         {
576
577 #if DEBUG
578                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
579 #endif
580
581                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
582                                 if (dMatch.Value != null)
583                                 {
584                                         Logger.Chat("Entity designator hit!");
585                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
586                                 }
587
588                         }
589
590
591                 }
592
593                 private void AddNote(string notation)
594                 {
595                         var playerNodePoi = new PointOfInterest()
596                         {
597                                 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
598                                 Notes = notation,
599                                 Timestamp = DateTimeOffset.UtcNow,
600                         };
601
602                         this.POIs.AddReplace(playerNodePoi);
603                 }
604
605
606
607                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
608                 {
609                         Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
610
611                         CommandData cmdData = data as CommandData;
612
613
614                         if (CurrentState != RunState.Snapshot)
615                         {
616                                 switch (cmdData.State)
617                                 {
618                                         case RunState.Run:
619                                                 CurrentState = cmdData.State;
620                                                 AwakenCartographer(0.0f);
621                                                 break;
622
623                                         case RunState.Stop:
624                                                 CurrentState = cmdData.State;
625                                                 break;
626
627                                         case RunState.Snapshot:
628                                                 CurrentState = RunState.Stop;
629                                                 //Snapshot starts a second thread/process...
630
631                                                 break;
632
633                                         case RunState.Notation:
634                                                 //Add to POI list where player location
635                                                 AddNote(cmdData.Notation);
636                                                 break;
637                                 }
638
639                         }
640
641                         if (CurrentState != cmdData.State)
642                         {
643                                 CurrentState = cmdData.State;
644                                 AwakenCartographer(0.0f);
645                         }
646
647 #if DEBUG
648                         Logger.VerboseDebug($"Automap commanded to: {cmdData.State} ");
649 #endif
650
651                 }
652
653
654                 #endregion
655
656         }
657
658 }