OSDN Git Service

2nd Entity processing fix attempt
[automap/automap.git] / Automap / Subsystems / AutomapSystem.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
5 using System.IO;
6 using System.Linq;
7 using System.Text;
8 using System.Text.RegularExpressions;
9 using System.Threading;
10
11 using Hjg.Pngcs;
12 using Mono.Collections.Generic;
13 using ProtoBuf;
14
15 using Vintagestory.API.Client;
16 using Vintagestory.API.Common;
17 using Vintagestory.API.Common.Entities;
18 using Vintagestory.API.Config;
19 using Vintagestory.API.Datastructures;
20 using Vintagestory.API.MathTools;
21 using Vintagestory.Common;
22
23 namespace Automap
24 {
25         public class AutomapSystem
26         {
27                 private Thread cartographer_thread;
28
29                 private Snapshotter snapshot;
30                 private ICoreClientAPI ClientAPI { get; set; }
31                 private ILogger Logger { get; set; }
32                 private AChunkRenderer ChunkRenderer { get; set; }
33                 private JsonGenerator JsonGenerator { get; set; }
34
35                 internal const string _mapPath = @"Maps";
36                 internal const string _chunkPath = @"Chunks";
37                 internal const uint editThreshold = 9;
38                 private const string _domain = @"automap";
39                 private const string chunkFile_filter = @"*_*.png";
40                 private const string poiFileName = @"poi_binary";
41                 private const string eoiFileName = @"eoi_binary";
42                 private const string pointsTsvFileName = @"points_of_interest.tsv";
43                 private const string plainMetadataFileName = @"map_metadata.txt";
44                 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
45
46                 private ConcurrentDictionary<Vec2i, ColumnCounter> columnCounters = new ConcurrentDictionary<Vec2i, ColumnCounter>(3, 150);
47                 private ColumnsMetadata chunkTopMetadata;
48                 internal PointsOfInterest POIs = new PointsOfInterest();
49                 internal 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                 internal Dictionary<int, string> AiryIdCodes { get; private set; }
55
56                 internal CommandType CurrentState { get; set; }
57                 //Run status, Chunks processed, stats, center of map....
58                 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
59                 private Vec2i startChunkColumn;
60
61                 private readonly int chunkSize;
62                 private string path;
63                 private IAsset staticMap;
64                 private PersistedConfiguration configuration;
65
66
67                 public static string AutomapStatusEventKey = @"AutomapStatus";
68                 public static string AutomapCommandEventKey = @"AutomapCommand";
69
70                 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
71                 {
72                         this.ClientAPI = clientAPI;
73                         this.Logger = logger;
74                         chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
75
76                         configuration = config;
77                         ClientAPI.Event.LevelFinalize += EngageAutomap;
78
79                         this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
80
81                         //Listen on bus for commands
82                         ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
83
84
85                         if (configuration.Autostart)
86                         {
87                                 CurrentState = CommandType.Run;
88                                 Logger.Notification("Autostart is Enabled.");
89                         }
90
91                 }
92
93
94                 #region Internals
95                 private void EngageAutomap()
96                 {
97                         path = ClientAPI.GetOrCreateDataPath(_mapPath);
98                         path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
99                         ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
100                                                   
101                         JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
102
103                         string mapFilename = Path.Combine(path, "automap.html");
104                         StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
105
106                         staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
107                         outputText.Write(staticMap.ToText());
108                         outputText.Flush();
109
110                         Prefill_POI_Designators();
111                         startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
112                         chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
113                         Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
114                         Reload_Metadata();
115
116                         ClientAPI.Event.ChunkDirty += ChunkAChanging;
117
118                         cartographer_thread = new Thread(Cartographer)
119                         {
120                                 Name = "Cartographer",
121                                 Priority = ThreadPriority.Lowest,
122                                 IsBackground = true
123                         };
124
125                         ClientAPI.Event.RegisterGameTickListener(ThreadDecider, 6000);
126                 }
127
128                 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
129                 {
130                 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);              
131                 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
132                 
133                 columnCounters.AddOrUpdate(topPosition, 
134                                               new ColumnCounter(chunkSize, newOrEdit, chunkCoord), 
135                                               (chkPos, chkChng) => chkChng.Update(chunkCoord, chunkSize, newOrEdit)
136                                              );
137                 
138                 }
139
140                 /// <summary>
141                 /// Cartographer Thread 'decider'
142                 /// </summary>
143                 /// <param name="delayed">called delay offset</param>
144                 private void ThreadDecider(float delayed)
145                 {
146
147                         if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
148                         {
149                                 #if DEBUG
150                                 Logger.VerboseDebug("ThreadDecider re-trigger from [{0}]", cartographer_thread.ThreadState);
151                                 #endif
152
153                                 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
154                                 {
155                                         cartographer_thread.Start();
156                                 }
157                                 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
158                                 {
159                                         //Time to (re)write chunk shards
160                                         cartographer_thread.Interrupt();
161                                 }
162                                 //#if DEBUG
163                                 //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})");
164                                 //#endif
165                         }
166                         else if (CurrentState == CommandType.Snapshot)
167                         {
168                         //Prepare for taking a snopshot
169                         if (snapshot == null) {         
170                                 snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize, ClientAPI.World.Seed);
171                                 #if DEBUG
172                                 Logger.VerboseDebug("Starting new Snapshot: {0} Wx{1} Hx{2}", snapshot.fileName, snapshot.Width, snapshot.Height);
173                                 #endif
174                                 snapshot.Take( );
175                                 }
176                         else if (snapshot != null && snapshot.Finished) {
177                                 #if DEBUG
178                                         Logger.VerboseDebug("COMPLETED Snapshot: {0} Wx{1} Hx{2}, taking {3}", snapshot.fileName, snapshot.Width, snapshot.Height, snapshot.Timer.Elapsed);
179                                 #endif
180                                 snapshot = null;
181                                 CurrentState = CommandType.Run;
182                                 }
183                         }
184                 }
185
186
187                 private void Cartographer()
188                 {
189                         wake:
190                         Logger.VerboseDebug("Cartographer thread awoken");
191
192                         try
193                         {
194                                 ColumnCounter ejectedItem ;
195                                 uint updatedChunks = 0;
196                                 uint updatedPixels = 0;
197
198                                 //-- Should dodge enumerator changing underfoot....at a cost.
199                                 if (!columnCounters.IsEmpty)
200                                 {
201                                         var tempSet = columnCounters.ToArray().Where(cks => cks.Value.WeightedSum > editThreshold) .OrderByDescending(kvp => kvp.Value.WeightedSum);
202                                         UpdateEntityMetadata();
203
204                                         foreach (var mostActiveCol in tempSet)
205                                         {
206                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
207
208                                                 if (mapChunk == null)
209                                                 {
210                                                         //TODO: REVISIT THIS CHUNK!
211                                                         #if DEBUG
212                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
213                                                         #endif
214                                                         nullMapCount++;
215                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
216                                                         continue;
217                                                 }
218
219                                                 ColumnMeta chunkMeta;
220                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key))
221                                                 {
222                                                         chunkMeta = chunkTopMetadata[mostActiveCol.Key];
223                                                         #if DEBUG
224                                                         Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
225                                                         #endif
226                                                 }
227                                                 else
228                                                 {
229                                                         chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
230                                                         #if DEBUG
231                                                         Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
232                                                         #endif
233                                                 }
234                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
235                                                 mostActiveCol.Value.SetCutoff(chunkMeta.YMax / chunkSize);
236
237                                                 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
238                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
239
240                                                 if (updatedPixels > 0)
241                                                 {
242                                                         #if DEBUG
243                                                         Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
244                                                         #endif
245                                                         updatedChunks++;
246                                                         chunkTopMetadata.Update(chunkMeta);
247                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
248                                                 }
249                                                 else
250                                                 {
251                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
252                                                         #if DEBUG
253                                                         Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
254                                                         #endif
255                                                 }
256                                         }
257                                 }
258
259                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
260
261                                 if (updatedChunks > 0)
262                                 {
263                                         //What about chunk updates themselves; a update bitmap isn't kept...
264                                         updatedChunksTotal += updatedChunks;
265                                         JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
266                                         updatedChunks = 0;
267
268                                         //Cleanup in-memory Metadata...
269                                         chunkTopMetadata.ClearMetadata( );
270                                 }
271
272                                 #if DEBUG
273                                 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
274                                 #endif
275
276                                 columnCounters.Clear( );
277
278                                 //Then sleep until interupted again, and repeat
279 #if DEBUG
280                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
281 #endif
282                                 Thread.Sleep(Timeout.Infinite);
283
284                         }
285                         catch (ThreadInterruptedException)
286                         {
287
288 #if DEBUG
289                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
290 #endif
291                                 goto wake;
292
293                         }
294                         catch (ThreadAbortException)
295                         {
296 #if DEBUG
297                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
298 #endif
299                         }
300                         finally
301                         {
302 #if DEBUG
303                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
304 #endif
305                                 PersistPointsData();
306                                 Write_PlainMetadata( );
307                         }
308                 }
309
310                 private void Snap()
311                 {
312                         snapshotTake:
313 #if DEBUG
314                         Logger.VerboseDebug("Snapshot started");
315 #endif
316                         try
317                         {
318                                 snapshot.Take();
319 #if DEBUG
320                                 Logger.VerboseDebug("Snapshot sleeping");
321 #endif
322                                 CurrentState = CommandType.Run;
323                                 Thread.Sleep(Timeout.Infinite);
324                         }
325                         catch (ThreadInterruptedException)
326                         {
327 #if DEBUG
328                                 Logger.VerboseDebug("Snapshot intertupted");
329 #endif
330                                 goto snapshotTake;
331                         }
332                 }
333
334                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
335                 {
336                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
337
338                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
339                 }
340
341                 private void Prefill_POI_Designators()
342                 {
343
344                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
345                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
346                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
347
348                         var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
349                                                          where airyBlock.MatterState == EnumMatterState.Solid
350                                                          where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves 
351                                                          where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 || airyBlock.RainPermeable == true                                       
352                                                                 select airyBlock;                       
353                         //^^ 'Solid' phase - 'Plant' Blocks without any bounding-box; OR 'Invisible' shapes...
354                         var invisibleBlocksQuery = from novisBlock in ClientAPI.World.Blocks                                                                       
355                                                                            where novisBlock.Shape == null || novisBlock.Shape.Base.EndsWith(GlobalConstants.DefaultDomain, @"invisible")   //Whaat! [ base: "block/basic/invisible" ]
356                                                                                 select novisBlock;                      
357                         this.AiryIdCodes = airBlocksQuery.Union(invisibleBlocksQuery).ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
358
359                         #if DEBUG
360                         foreach (var fluffBlock in AiryIdCodes) {
361                         Logger.VerboseDebug("ID#\t{0}:\t{1} IGNORED", fluffBlock.Key, fluffBlock.Value);
362                         }
363                         Logger.VerboseDebug("Ignoring {0} blocks", AiryIdCodes.Count);
364                         #endif
365
366                 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
367                 Reload_POI_Designators();
368                 }
369
370                 private void Reload_POI_Designators()
371                 {
372                 uint poisSetup =0, eoiSetup = 0;
373                         foreach (var designator in configuration.BlockDesignators)
374                         {
375                                 if (designator.Enabled == false) continue;
376                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
377                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
378                                 foreach (var entry in blockIDs)
379                                 {
380                                         BlockID_Designators.Add(entry.Key, designator);
381                                         poisSetup++;
382                                 }
383                         }
384                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
385                         Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
386
387
388                         foreach (var designator in configuration.EntityDesignators)
389                         {
390                                 if (designator.Enabled == false) continue;
391                                 //Get Variants first, from EntityTypes...better be populated!
392                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
393
394                                 foreach (var match in matched)
395                                 {                                       
396                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
397                                         this.Entity_Designators.Add(match.Code, designator);
398                                         eoiSetup++;
399                                 }
400                         }
401                         Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
402
403                 }
404
405
406
407                 /// <summary>
408                 /// Store Points/Entity of Interest
409                 /// </summary>
410                 private void PersistPointsData()
411                 {
412                         //POI and EOI raw dump files ~ WRITE em!
413                         //var poiRawFile = File.
414                         string poiPath = Path.Combine(path, poiFileName);
415                         string eoiPath = Path.Combine(path, eoiFileName);
416
417                         if (this.POIs.Count > 0)
418                         {
419                                 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.Write, FileShare.None))
420                                 {
421                                         Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
422                                         poiFile.Flush(true);
423                                 }
424                         }
425
426                         if (this.EOIs.Count > 0)
427                         {
428                                 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.Write, FileShare.None))
429                                 {
430                                         Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
431                                         eoiFile.Flush(true);
432                                 }
433                         }
434
435                         //Create Easy to Parse TSV file for tool/human use....
436                         string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
437
438                         using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
439                         {
440                                 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
441                                 foreach (var point in this.POIs)
442                                 {
443                                         tsvWriter.Write(point.Name + "\t");
444                                         var notes = point.Notes
445                                                 .Replace('\n', '\x001f')
446                                                 .Replace("\t", "\\t")
447                                                 .Replace("\\", "\\\\");
448                                         tsvWriter.Write(notes + "\t");
449                                         tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
450                                         tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
451                                         tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
452                                         tsvWriter.Write("null\t");
453                                         tsvWriter.WriteLine();
454                                 }
455                                 foreach (var entity in this.EOIs)
456                                 {
457                                         tsvWriter.Write(entity.Name + "\t");
458                                         var notes = entity.Notes
459                                                 .Replace('\n', '\x001f')
460                                                 .Replace("\t", "\\t")
461                                                 .Replace("\\", "\\\\");
462                                         tsvWriter.Write(notes + "\t");
463                                         tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
464                                         tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
465                                         tsvWriter.Write("---\t");
466                                         tsvWriter.Write(entity.EntityId.ToString("D"));
467                                         tsvWriter.WriteLine();
468                                 }
469                                 tsvWriter.WriteLine();
470                                 tsvWriter.Flush();
471                         }
472
473                 }
474
475                 private void Write_PlainMetadata( )
476                 { 
477                 string metaPath = Path.Combine(path, plainMetadataFileName);
478
479                 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
480                 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII)) 
481                         {
482                                 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
483                                 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
484                                 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
485                                 //mdWriter.WriteLine("CurrentPlayerSpawn", ClientAPI.World.Player.WorldData.EntityPlayer.);
486                                 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
487                                 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
488                                 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
489                                 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
490                                 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
491                                 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
492                                 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
493                                 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
494                                 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
495                                 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);        
496                                 mdWriter.Flush( );
497                         }
498                 }
499                 }
500                         
501
502                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
503                 {
504                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
505                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
506                                                                                         mapChunk.YMax,
507                                                                                         mostActiveCol.Key.Y * chunkSize);
508
509                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
510                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
511
512                         return data;
513                 }
514
515                 /// <summary>
516                 /// Reload chunk bounds from chunk shards
517                 /// </summary>
518                 /// <returns>The metadata.</returns>
519                 private void Reload_Metadata()
520                 {
521                         var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
522
523                         if (!shardsDir.Exists)
524                         {
525                                 #if DEBUG
526                                 Logger.VerboseDebug("Could not open world map (shards) directory");
527                                 #endif
528                                 return;
529                         }
530                         var shardFiles = shardsDir.GetFiles(chunkFile_filter);
531
532                         if (shardFiles.Length > 0)
533                         {
534                                 #if DEBUG
535                                 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
536                                 #endif
537
538                                 foreach (var shardFile in shardFiles)
539                                 {
540
541                                         if (shardFile.Length < 1024) continue;
542                                         var result = chunkShardRegex.Match(shardFile.Name);
543                                         if (!result.Success) continue;
544
545                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
546                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
547
548                                         try
549                                         {
550                                                 using (var fileStream = shardFile.OpenRead())
551                                                 {
552
553                                                         PngReader pngRead = new PngReader(fileStream);
554                                                         pngRead.ReadSkippingAllRows();
555                                                         pngRead.End();
556                                                         //Parse PNG chunks for METADATA in shard
557                                                         PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
558                                                         var column = metadataFromPng.ChunkMetadata;
559                                                         if (column.PrettyLocation == null)
560                                                                 column = column.Reload(ClientAPI);
561                                                         chunkTopMetadata.Add(column);
562                                                 }
563
564                                         }
565                                         catch (PngjException someEx)
566                                         {
567                                                 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
568                                                 continue;
569                                         }
570                                         catch (ProtoException protoEx) 
571                                         {
572                                                 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
573                                                 continue;
574                                         }
575                                 }
576                         }
577
578                         //POI and EOI raw dump files ~ reload em!
579                         //var poiRawFile = File.
580                         string poiPath = Path.Combine(path, poiFileName);
581                         string eoiPath = Path.Combine(path, eoiFileName);
582
583                         if (File.Exists(poiPath))
584                         {
585                                 using (var poiFile = File.OpenRead(poiPath))
586                                 {
587                                         this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
588                                         Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
589                                 }
590                         }
591
592                         if (File.Exists(eoiPath))
593                         {
594                                 using (var eoiFile = File.OpenRead(eoiPath))
595                                 {
596                                         this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
597                                         Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
598                                 }
599                         }
600
601                 }
602
603
604
605                 /// <summary>
606                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
607                 /// </summary>
608                 /// <param name="key">Chunk Coordinate</param>
609                 /// <param name="mapChunk">Map chunk.</param>
610                 /// <param name="chunkMeta">Chunk metadata</param>
611                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
612                 {
613                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish... 
614                         byte chunkTally = 0;
615
616                 #if DEBUG
617                 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
618                 #endif
619
620                 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
621
622                 for (; targetChunkY > 0; targetChunkY--)
623                         {
624                                 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
625
626                                 if (worldChunk == null || worldChunk.BlockEntities == null)
627                                 {
628                                         #if DEBUG
629                                         Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
630                                         #endif
631                                         nullChunkCount++;
632                                         continue;
633                                 }
634
635                                 if (worldChunk.IsPacked()) 
636                                 {
637                                 #if DEBUG
638                                 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
639                                 #endif
640                                 worldChunk.Unpack( );//RESEARCH: Thread Unsafe? 
641                                 }
642
643                                 /*************** Chunk Entities Scanning *********************/
644                                 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
645                                 {
646                                         #if DEBUG
647                                         Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
648                                         #endif
649
650                                         foreach (var blockEnt in worldChunk.BlockEntities)
651                                         {
652                                                 if (blockEnt.Key != null && blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
653                                                 {
654                                                         var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
655                                                         designator?.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
656                                                 }
657                                         }
658                                 }
659
660                                 /********************* Chunk/Column BLOCKs scanning ****************/
661                                 //Heightmap, Stats, block tally
662
663                                 int X_index, Y_index, Z_index;
664
665                                 //First Chance fail-safe;
666                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
667                                 #if DEBUG
668                                 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
669                                 #endif
670                                 nullChunkCount++;
671                                 continue;
672                                 }               
673
674                                 chunkMeta.ColumnPresense[targetChunkY] = true;
675                                 chunkTally++;
676                                 for (Y_index = 0; Y_index < chunkSize; Y_index++)
677                                 {
678                                         for (Z_index = 0; Z_index < chunkSize; Z_index++)
679                                         {
680                                                 for (X_index = 0; X_index < chunkSize; X_index++) 
681                                                 {
682                                                 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
683
684                                                 //'Last' Chance fail-safe;
685                                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
686                                                 #if DEBUG
687                                                 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
688                                                 #endif
689                                                 nullChunkCount++;
690                                                 goto loop_bustout; 
691                                                 }
692
693                                                 int aBlockId = worldChunk.Blocks[indicie];
694
695                                                 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
696                                                 chunkMeta.AirBlocks++;
697                                                 continue;
698                                                 }
699
700                                                 if (RockIdCodes.ContainsKey(aBlockId)) {
701                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
702                                                         chunkMeta.RockRatio[aBlockId]++;
703                                                 else
704                                                         chunkMeta.RockRatio.Add(aBlockId, 1);
705                                                 }
706
707                                                 chunkMeta.NonAirBlocks++;
708
709                                                 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
710                                                 //Heightmap - Need to ignore Grass & Snow
711                                                 if (localHeight > chunkMeta.HeightMap[X_index, Z_index]) 
712                                                         {
713                                                         chunkMeta.HeightMap[X_index, Z_index] = localHeight;
714                                                         if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
715                                                         }
716                                                 }
717                                         }
718                                 }
719                                 loop_bustout:;
720                         }
721                         #if DEBUG
722                         Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
723                         #endif
724                 }
725
726                 private void UpdateEntityMetadata()
727                 {
728                 #if DEBUG
729                 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
730                 #endif
731
732                 var keyList = new long[ClientAPI.World.LoadedEntities.Keys.Count];
733                 ClientAPI.World.LoadedEntities.Keys.CopyTo(keyList, 0);
734
735              //'ElementAt'; worse! instead; walk fixed list...
736                 Entity loadedEntity;
737                 foreach (var key in keyList)
738                         {
739                         if (ClientAPI.World.LoadedEntities.TryGetValue(key, out loadedEntity))
740                                 {               
741                                 #if DEBUG
742                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
743                                 #endif
744
745                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Code));
746                                 if (dMatch.Value != null) 
747                                         {
748                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Pos.AsBlockPos.Copy( ), loadedEntity);
749                                         }
750                                 }                               
751                         }
752                 }
753
754                 private void AddNote(string notation)
755                 {
756                         var playerNodePoi = new PointOfInterest()
757                         {
758                                 Name = "Note",
759                                 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
760                                 Notes = notation,
761                                 Timestamp = DateTime.UtcNow,
762                         };
763
764                         this.POIs.AddReplace(playerNodePoi);
765                 }
766
767
768
769                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
770                 {
771                         //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
772
773                         CommandData cmdData = data as CommandData;
774
775                         switch (cmdData.State)
776                         {
777                                 case CommandType.Run:
778                                 case CommandType.Stop:
779                                 case CommandType.Snapshot:
780                                         if (CurrentState != cmdData.State)
781                                         {
782                                                 CurrentState = cmdData.State;
783                                                 ThreadDecider(0.0f);
784                                         }
785                                         break;
786
787                                 case CommandType.Notation:
788                                         //Add to POI list where player location
789                                         AddNote(cmdData.Notation);
790                                         break;
791                         }
792
793                         ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
794
795                 }
796 #endregion
797
798                 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
799                 {
800                 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
801                 switch (rendererName) 
802                 {                               
803                 case StandardRenderer.Name:
804                         return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
805                 
806                 case AlternateRenderer.Name:
807                         return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
808         
809                 case FlatRenderer.Name:
810                         return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);  
811
812                 default:
813                         throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");
814                 }
815
816                 return null;
817                 }
818         }
819
820 }