2 using System.Collections.Concurrent;
3 using System.Collections.Generic;
4 using System.Collections.ObjectModel;
9 using System.Text.RegularExpressions;
10 using System.Threading;
14 using Hjg.Pngcs.Chunks;
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;
26 public class AutomapSystem
28 private Thread cartographer_thread;
29 private ICoreClientAPI ClientAPI { get; set; }
30 private ILogger Logger { get; set; }
31 private IChunkRenderer ChunkRenderer { get; set; }
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);
39 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
40 private ColumnsMetadata chunkTopMetadata;
41 private PointsOfInterest POIs = new PointsOfInterest();
42 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
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; }
48 internal RunState CurrentState { get; set; }
49 //Run status, Chunks processed, stats, center of map....
50 private uint nullChunkCount, updatedChunksTotal;
51 private Vec2i startChunkColumn;
53 private readonly int chunkSize;
55 private IAsset stylesFile;
57 public static string AutomapStatusEventKey = @"AutomapStatus";
58 public static string AutomapCommandEventKey = @"AutomapCommand";
61 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger)
63 this.ClientAPI = clientAPI;
65 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
66 ClientAPI.Event.LevelFinalize += EngageAutomap;
68 //TODO:Choose which one from GUI
69 this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
71 //Listen on bus for commands
72 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
78 private void EngageAutomap()
80 path = ClientAPI.GetOrCreateDataPath(_mapPath);
81 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
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);
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);
90 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
93 ClientAPI.Event.ChunkDirty += ChunkAChanging;
95 cartographer_thread = new Thread(Cartographer)
97 Name = "Cartographer",
98 Priority = ThreadPriority.Lowest,
102 ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
105 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
107 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
109 columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
112 private void AwakenCartographer(float delayed)
115 if (CurrentState == RunState.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
118 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
121 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
123 cartographer_thread.Start();
125 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
127 //Time to (re)write chunk shards
128 cartographer_thread.Interrupt();
131 //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})");
134 else if (CurrentState == RunState.Snapshot)
136 //TODO: Snapshot generator second thread...
142 private void Cartographer()
145 Logger.VerboseDebug("Cartographer thread awoken");
149 uint ejectedItem = 0;
150 uint updatedChunks = 0;
152 //-- Should dodge enumerator changing underfoot....at a cost.
153 if (!columnCounter.IsEmpty)
155 var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
156 foreach (var mostActiveCol in tempSet)
159 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
161 if (mapChunk == null)
163 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
165 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
169 ColumnMeta chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
170 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
171 UpdateEntityMetadata();
172 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, chunkMeta);
174 uint updatedPixels = 0;
176 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
178 if (updatedPixels > 0)
182 Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
185 chunkTopMetadata.Update(chunkMeta);
186 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
190 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
191 Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
197 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
199 if (updatedChunks > 0)
201 //What about chunk updates themselves; a update bitmap isn't kept...
202 updatedChunksTotal += updatedChunks;
204 GenerateJSONMetadata();
208 //Then sleep until interupted again, and repeat
210 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
212 Thread.Sleep(Timeout.Infinite);
215 catch (ThreadInterruptedException)
218 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
222 catch (ThreadAbortException)
224 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
229 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
233 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
235 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, RunState.Run);
237 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
240 private void Prefill_POI_Designators()
243 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
244 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
245 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock"), EnumBlockMaterial.Stone);
247 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
249 Install_POI_Designators(DefaultDesignators.DefaultBlockDesignators(), DefaultDesignators.DefaultEntityDesignators());
252 private void Install_POI_Designators(ICollection<BlockDesignator> blockDesig, List<EntityDesignator> entDesig)
254 Logger.VerboseDebug("Connecting {0} standard Block-Designators", blockDesig.Count);
255 foreach (var designator in blockDesig)
257 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
258 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
259 foreach (var entry in blockIDs)
261 BlockID_Designators.Add(entry.Key, designator);
264 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
267 Logger.VerboseDebug("Connecting {0} standard Entity-Designators", entDesig.Count);
268 foreach (var designator in entDesig)
270 //Get Variants first, from EntityTypes...better be populated!
271 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
273 foreach (var match in matched)
275 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
276 this.Entity_Designators.Add(match.Code, designator);
281 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
288 private void GenerateMapHTML()
290 string mapFilename = Path.Combine(path, "Automap.html");
292 int TopNorth = chunkTopMetadata.North_mostChunk;
293 int TopSouth = chunkTopMetadata.South_mostChunk;
294 int TopEast = chunkTopMetadata.East_mostChunk;
295 int TopWest = chunkTopMetadata.West_mostChunk;
297 using (StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)))
299 using (HtmlTextWriter tableWriter = new HtmlTextWriter(outputText))
301 tableWriter.BeginRender();
302 tableWriter.RenderBeginTag(HtmlTextWriterTag.Html);
304 tableWriter.RenderBeginTag(HtmlTextWriterTag.Head);
305 tableWriter.RenderBeginTag(HtmlTextWriterTag.Title);
306 tableWriter.WriteEncodedText("Generated Automap");
307 tableWriter.RenderEndTag();
309 tableWriter.RenderBeginTag(HtmlTextWriterTag.Style);
310 tableWriter.Write(stylesFile.ToText());
311 tableWriter.RenderEndTag();//</style>
313 tableWriter.RenderEndTag();
315 tableWriter.RenderBeginTag(HtmlTextWriterTag.Body);
316 tableWriter.RenderBeginTag(HtmlTextWriterTag.P);
317 tableWriter.WriteEncodedText($"Created {DateTimeOffset.UtcNow.ToString("u")}");
318 tableWriter.RenderEndTag();
319 tableWriter.RenderBeginTag(HtmlTextWriterTag.P);
320 tableWriter.WriteEncodedText($"W:{TopWest}, E: {TopEast}, N:{TopNorth}, S:{TopSouth} ");
321 tableWriter.RenderEndTag();
322 tableWriter.WriteLine();
323 tableWriter.RenderBeginTag(HtmlTextWriterTag.Table);
324 tableWriter.RenderBeginTag(HtmlTextWriterTag.Caption);
325 tableWriter.WriteEncodedText($"Start: {startChunkColumn}, Seed: {ClientAPI.World.Seed}\n");
326 tableWriter.RenderEndTag();
328 //################ X-Axis <thead> #######################
329 tableWriter.RenderBeginTag(HtmlTextWriterTag.Thead);
330 tableWriter.RenderBeginTag(HtmlTextWriterTag.Tr);
332 tableWriter.RenderBeginTag(HtmlTextWriterTag.Th);
333 tableWriter.Write("N, W");
334 tableWriter.RenderEndTag();
336 for (int xAxisT = TopWest; xAxisT <= TopEast; xAxisT++)
338 tableWriter.RenderBeginTag(HtmlTextWriterTag.Th);
339 tableWriter.Write(xAxisT);
340 tableWriter.RenderEndTag();
343 tableWriter.RenderBeginTag(HtmlTextWriterTag.Th);
344 tableWriter.Write("N, E");
345 tableWriter.RenderEndTag();
347 tableWriter.RenderEndTag();
348 tableWriter.RenderEndTag();
349 //###### </thead> ################################
351 //###### <tbody> - Chunk rows & Y-axis cols
352 tableWriter.RenderBeginTag(HtmlTextWriterTag.Tbody);
354 //######## <tr> for every vertical row
355 for (int yAxis = TopNorth; yAxis <= TopSouth; yAxis++)
357 tableWriter.RenderBeginTag(HtmlTextWriterTag.Tr);
358 tableWriter.RenderBeginTag(HtmlTextWriterTag.Td);
359 tableWriter.Write(yAxis);//legend: Y-axis
360 tableWriter.RenderEndTag();
362 for (int xAxis = TopWest; xAxis <= TopEast; xAxis++)
364 //###### <td> #### for chunk shard
365 tableWriter.RenderBeginTag(HtmlTextWriterTag.Td);
366 var colLoc = new Vec2i(xAxis, yAxis);
367 if (chunkTopMetadata.Contains(colLoc))
369 ColumnMeta meta = chunkTopMetadata[colLoc];
371 tableWriter.AddAttribute(HtmlTextWriterAttribute.Class, "tooltip");
372 tableWriter.RenderBeginTag(HtmlTextWriterTag.Div);
374 tableWriter.AddAttribute(HtmlTextWriterAttribute.Src, $"{xAxis}_{yAxis}.png");
375 tableWriter.RenderBeginTag(HtmlTextWriterTag.Img);
376 tableWriter.RenderEndTag();
377 // <span class="tooltiptext">Tooltip text
378 tableWriter.AddAttribute(HtmlTextWriterAttribute.Class, "tooltiptext");
379 tableWriter.RenderBeginTag(HtmlTextWriterTag.Span);
381 StringBuilder tooltipText = new StringBuilder();
382 tooltipText.Append($"{meta.Location.PrettyCoords(ClientAPI)} ");
383 tooltipText.Append($" Max-Height: {meta.YMax}, Temp: {meta.Temperature.ToString("F1")} ");
384 tooltipText.Append($" Rainfall: {meta.Rainfall.ToString("F1")}, ");
385 tooltipText.Append($" Shrubs: {meta.ShrubDensity.ToString("F1")}, ");
386 tooltipText.Append($" Forest: {meta.ForestDensity.ToString("F1")}, ");
387 tooltipText.Append($" Fertility: {meta.Fertility.ToString("F1")}, ");
389 if (meta.RockRatio != null)
391 foreach (KeyValuePair<int, uint> blockID in meta.RockRatio)
393 var block = ClientAPI.World.GetBlock(blockID.Key);
394 tooltipText.AppendFormat(" {0} × {1},\t", block.Code.GetName(), meta.RockRatio[blockID.Key]);
398 tableWriter.WriteEncodedText(tooltipText.ToString());
400 tableWriter.RenderEndTag();//</span>
403 tableWriter.RenderEndTag();//</div> --tooltip enclosure
407 tableWriter.Write("?");
410 tableWriter.RenderEndTag();
411 }//############ </td> ###########
413 tableWriter.RenderBeginTag(HtmlTextWriterTag.Td);
414 tableWriter.Write(yAxis);//legend: Y-axis
415 tableWriter.RenderEndTag();
417 tableWriter.RenderEndTag();
420 tableWriter.RenderEndTag();
422 //################ X-Axis <tfoot> #######################
423 tableWriter.RenderBeginTag(HtmlTextWriterTag.Tfoot);
424 tableWriter.RenderBeginTag(HtmlTextWriterTag.Tr);
426 tableWriter.RenderBeginTag(HtmlTextWriterTag.Td);
427 tableWriter.Write("S, W");
428 tableWriter.RenderEndTag();
430 for (int xAxisB = TopWest; xAxisB <= TopEast; xAxisB++)
432 tableWriter.RenderBeginTag(HtmlTextWriterTag.Td);
433 tableWriter.Write(xAxisB);
434 tableWriter.RenderEndTag();
437 tableWriter.RenderBeginTag(HtmlTextWriterTag.Td);
438 tableWriter.Write("S, E");
439 tableWriter.RenderEndTag();
441 tableWriter.RenderEndTag();
442 tableWriter.RenderEndTag();
443 //###### </tfoot> ################################
446 tableWriter.RenderEndTag();//</table>
448 //############## POI list #####################
449 tableWriter.RenderBeginTag(HtmlTextWriterTag.P);
450 tableWriter.WriteLine("Points of Interest");
451 tableWriter.RenderEndTag();
452 tableWriter.RenderBeginTag(HtmlTextWriterTag.Ul);
453 foreach (var poi in this.POIs)
455 tableWriter.RenderBeginTag(HtmlTextWriterTag.Li);
456 tableWriter.WriteEncodedText(poi.Location.PrettyCoords(this.ClientAPI) + "\t");
457 tableWriter.WriteEncodedText(poi.Notes + "\t");
458 tableWriter.WriteEncodedText(poi.Timestamp.ToString("u"));
459 tableWriter.RenderEndTag();
462 foreach (var eoi in this.EOIs.PointsList)
464 tableWriter.RenderBeginTag(HtmlTextWriterTag.Li);
465 tableWriter.WriteEncodedText(eoi.Location.PrettyCoords(this.ClientAPI) + "\t");
466 tableWriter.WriteEncodedText(eoi.Notes + "\t");
467 tableWriter.WriteEncodedText(eoi.Timestamp.ToString("u"));
468 tableWriter.RenderEndTag();
471 tableWriter.RenderEndTag();
476 tableWriter.RenderEndTag();//### </BODY> ###
478 tableWriter.EndRender();
484 Logger.VerboseDebug("Generated HTML map");
488 /// Generates the JSON Metadata. (in MAP object format )
490 private void GenerateJSONMetadata()
492 string jsonFilename = Path.Combine(path, "Metadata.js");
494 StreamWriter jsonWriter = new StreamWriter(jsonFilename, false, Encoding.UTF8);
497 jsonWriter.Write("ViewFrame.chunks={};");
498 jsonWriter.Write("ViewFrame.chunks.worldSeedNum={0};", ClientAPI.World.Seed);
499 jsonWriter.Write("ViewFrame.chunks.genTime=new Date('{0}');", DateTimeOffset.UtcNow.ToString("O"));
500 jsonWriter.Write("ViewFrame.chunks.startCoords=[{0},{1}];", startChunkColumn.X, startChunkColumn.Y);
501 jsonWriter.Write("ViewFrame.chunks.chunkSize={0};", chunkSize);
502 jsonWriter.Write("ViewFrame.chunks.northMostChunk={0};", chunkTopMetadata.North_mostChunk);
503 jsonWriter.Write("ViewFrame.chunks.southMostChunk={0};", chunkTopMetadata.South_mostChunk);
504 jsonWriter.Write("ViewFrame.chunks.eastMostChunk={0};", chunkTopMetadata.East_mostChunk);
505 jsonWriter.Write("ViewFrame.chunks.westMostChunk={0};", chunkTopMetadata.West_mostChunk);
506 //MAP object format - [key, value]: key is "x_y"
507 jsonWriter.Write("ViewFrame.chunks.chunkMetadata=new Map([");
508 foreach (var shard in chunkTopMetadata)
510 jsonWriter.Write("['{0}_{1}',", shard.Location.X, shard.Location.Y);
511 jsonWriter.Write("{");
512 jsonWriter.Write("prettyCoord:'{0}',", shard.Location.PrettyCoords(ClientAPI));
513 jsonWriter.Write("chunkAge:'{0}',", shard.ChunkAge.ToString("g"));//World age - relative? or last edit ??
514 jsonWriter.Write("temp:{0},", shard.Temperature.ToString("F1"));
515 jsonWriter.Write("YMax:{0},", shard.YMax);
516 jsonWriter.Write("fert:{0},", shard.Fertility.ToString("F1"));
517 jsonWriter.Write("forestDens:{0},", shard.ForestDensity.ToString("F1"));
518 jsonWriter.Write("rain:{0},", shard.Rainfall.ToString("F1"));
519 jsonWriter.Write("shrubDens:{0},", shard.ShrubDensity.ToString("F1"));
520 jsonWriter.Write("airBlocks:{0},", shard.AirBlocks);
521 jsonWriter.Write("nonAirBlocks:{0},", shard.NonAirBlocks);
524 jsonWriter.Write("}],");
526 jsonWriter.Write("]);");
529 jsonWriter.Write("ViewFrame.chunks.pointsOfInterest = new Map([");
530 foreach (var poi in POIs)
532 jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
533 jsonWriter.Write("{");
534 jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
535 jsonWriter.Write("notes:'{0}',", poi.Notes.Replace("'", "\'").Replace("\n","\\n"));
536 jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
537 jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
538 jsonWriter.Write("}],");
541 foreach (var poi in EOIs.PointsList)
543 jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
544 jsonWriter.Write("{");
545 jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
546 jsonWriter.Write("notes:'{0}',", poi.Notes.Replace("'", "\'"));
547 jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
548 jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
549 jsonWriter.Write("}],");
551 jsonWriter.Write("]);");
559 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
561 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), chunkSize);
562 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
564 mostActiveCol.Key.Y * chunkSize);
566 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
567 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
573 /// Reload chunk bounds from chunk shards
575 /// <returns>The metadata.</returns>
576 private void Reload_Metadata()
578 var worldmapDir = new DirectoryInfo(path);
580 if (worldmapDir.Exists)
583 var files = worldmapDir.GetFiles(chunkFile_filter);
585 if (files.Length > 0)
588 Logger.VerboseDebug("{0} Existing world chunk shards", files.Length);
593 foreach (var shardFile in files)
596 if (shardFile.Length < 512) continue;
597 var result = chunkShardRegex.Match(shardFile.Name);
600 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
601 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
603 //Parse PNG chunks for METADATA in shard
604 using (var fileStream = shardFile.OpenRead())
606 //TODO: Add corrupted PNG Exception handing HERE !
607 PngReader pngRead = new PngReader(fileStream);
608 pngRead.ReadSkippingAllRows();
611 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
613 chunkTopMetadata.Add(metadataFromPng.ChunkMetadata);
624 Logger.VerboseDebug("Could not open world map directory");
632 private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
634 ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
636 string filename = $"{coord.X}_{coord.Y}.png";
637 filename = Path.Combine(path, filename);
639 PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
640 PngMetadata meta = pngWriter.GetMetadata();
642 meta.SetText("Chunk_X", coord.X.ToString("D"));
643 meta.SetText("Chunk_Y", coord.Y.ToString("D"));
644 //Setup specialized meta-data PNG chunks here...
645 PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo);
646 pngChunkMeta.ChunkMetadata = metadata;
647 pngWriter.GetChunksList().Queue(pngChunkMeta);
653 /// Does the heavy lifting of Scanning columns of chunks - creates Heightmap and Processes POIs, Entities, and stats...
655 /// <param name="key">Chunk Coordinate</param>
656 /// <param name="mapChunk">Map chunk.</param>
657 /// <param name="chunkMeta">Chunk metadata</param>
658 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ColumnMeta chunkMeta)
661 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ...
662 for (; targetChunkY > 0; targetChunkY--)
664 WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
666 if (chunkData == null || chunkData.BlockEntities == null)
669 Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
674 /*************** Chunk Entities Scanning *********************/
675 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
678 Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
681 foreach (var blockEnt in chunkData.BlockEntities)
684 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
686 var designator = BlockID_Designators[blockEnt.Block.BlockId];
687 designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
692 /********************* Chunk/Column BLOCKs scanning ****************/
693 //Heightmap, Stats, block tally
696 int X_index, Y_index, Z_index;
697 X_index = Y_index = Z_index = 0;
705 /* Encode packed indicie
706 (y * chunksize + z) * chunksize + x
708 var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
709 int aBlockId = chunkData.Blocks[indicie];
713 chunkMeta.AirBlocks++;
717 if (RockIdCodes.ContainsKey(aBlockId))
719 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
722 chunkMeta.NonAirBlocks++;
725 if (chunkMeta.HeightMap[X_index, Z_index] == 0)
726 { chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize)); }
729 while (X_index++ < (chunkSize - 1));
732 while (Z_index++ < (chunkSize - 1));
735 while (Y_index++ < (chunkSize - 1));
740 private void UpdateEntityMetadata()
742 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
743 //Mabey scan only for 'new' entities by tracking ID in set?
744 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToList())
748 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
751 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
752 if (dMatch.Value != null)
754 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
762 private void AddNote(string notation)
764 var playerNodePoi = new PointOfInterest()
766 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
768 Timestamp = DateTimeOffset.UtcNow,
771 this.POIs.AddReplace(playerNodePoi);
776 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
778 Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
780 CommandData cmdData = data as CommandData;
783 if (CurrentState != RunState.Snapshot)
785 switch (cmdData.State)
788 CurrentState = cmdData.State;
789 AwakenCartographer(0.0f);
793 CurrentState = cmdData.State;
796 case RunState.Snapshot:
797 CurrentState = RunState.Stop;
798 //Snapshot starts a second thread/process...
802 case RunState.Notation:
803 //Add to POI list where player location
804 AddNote(cmdData.Notation);
810 if (CurrentState != cmdData.State)
812 CurrentState = cmdData.State;
813 AwakenCartographer(0.0f);
817 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");