OSDN Git Service

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