OSDN Git Service

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