2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
8 using System.Text.RegularExpressions;
9 using System.Threading;
12 using Mono.Collections.Generic;
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;
25 public class AutomapSystem
27 private Thread cartographer_thread;
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; }
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);
46 private ConcurrentDictionary<Vec2i, ColumnCounter> columnCounters = new ConcurrentDictionary<Vec2i, ColumnCounter>(3, 150);
47 private Queue<Vec2i> revisitChunkList = new Queue<Vec2i>();
48 private ColumnsMetadata chunkTopMetadata;
49 internal PointsOfInterest POIs = new PointsOfInterest();
50 internal EntitiesOfInterest EOIs = new EntitiesOfInterest();
52 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
53 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
54 internal Dictionary<int, string> RockIdCodes { get; private set; }
55 internal Dictionary<int, string> AiryIdCodes { get; private set; }
57 internal CommandType CurrentState { get; set; }
58 //Run status, Chunks processed, stats, center of map....
59 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
60 private Vec2i startChunkColumn;
62 private readonly int chunkSize;
64 private IAsset staticMap;
65 private PersistedConfiguration configuration;
68 public static string AutomapStatusEventKey = @"AutomapStatus";
69 public static string AutomapCommandEventKey = @"AutomapCommand";
71 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
73 this.ClientAPI = clientAPI;
75 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
77 configuration = config;
78 ClientAPI.Event.LevelFinalize += EngageAutomap;
80 this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
82 //Listen on bus for commands
83 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
88 private void EngageAutomap()
90 path = ClientAPI.GetOrCreateDataPath(_mapPath);
91 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
92 ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
94 JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
96 string mapFilename = Path.Combine(path, "automap.html");
97 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
99 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
100 outputText.Write(staticMap.ToText());
103 Prefill_POI_Designators();
104 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
105 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
106 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
109 ClientAPI.Event.ChunkDirty += ChunkAChanging;
111 cartographer_thread = new Thread(Cartographer)
113 Name = "Cartographer",
114 Priority = ThreadPriority.Lowest,
118 ClientAPI.Event.RegisterGameTickListener(ThreadDecider, 6000);
120 if (configuration.Autostart) {
121 CurrentState = CommandType.Run;
125 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
127 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
128 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
130 columnCounters.AddOrUpdate(topPosition,
131 new ColumnCounter(chunkSize, newOrEdit, chunkCoord),
132 (chkPos, chkChng) => chkChng.Update(chunkCoord, chunkSize, newOrEdit)
137 /// Cartographer Thread 'decider'
139 /// <param name="delayed">called delay offset</param>
140 private void ThreadDecider(float delayed)
143 if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
146 Logger.VerboseDebug("ThreadDecider re-trigger from [{0}]", cartographer_thread.ThreadState);
149 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
151 cartographer_thread.Start();
153 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
155 //Time to (re)write chunk shards
156 cartographer_thread.Interrupt();
159 //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})");
162 else if (CurrentState == CommandType.Snapshot)
164 //Prepare for taking a snopshot
165 if (snapshot == null) {
166 snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize, ClientAPI.World.Seed);
168 Logger.VerboseDebug("Starting new Snapshot: {0} Wx{1} Hx{2}", snapshot.fileName, snapshot.Width, snapshot.Height);
172 else if (snapshot != null && snapshot.Finished) {
174 Logger.VerboseDebug("COMPLETED Snapshot: {0} Wx{1} Hx{2}, taking {3}", snapshot.fileName, snapshot.Width, snapshot.Height, snapshot.Timer.Elapsed);
177 CurrentState = CommandType.Run;
183 private void Cartographer()
186 Logger.VerboseDebug("Cartographer thread awoken");
190 ColumnCounter ejectedItem ;
191 uint updatedChunks = 0;
192 uint updatedPixels = 0;
195 //Revisit failed chunks first;
196 while (revisitChunkList.Count > 0)
198 var revisitCoord = revisitChunkList.Dequeue( );
199 var rv_mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(revisitCoord);
201 if (rv_mapChunk == null) continue;
203 ColumnMeta rv_chunkMeta;
204 if (chunkTopMetadata.Contains(revisitCoord))
206 rv_chunkMeta = chunkTopMetadata[revisitCoord];
208 Logger.VerboseDebug("(re)Loaded meta-chunk {0}", revisitCoord);
213 rv_chunkMeta = CreateColumnMetadata(revisitCoord, rv_mapChunk);
215 Logger.VerboseDebug("(re)Created meta-chunk {0}", revisitCoord);
218 //TODO: Double validation of....?
219 ProcessChunkBlocks(revisitCoord, rv_mapChunk, ref rv_chunkMeta);
221 ChunkRenderer.SetupPngImage(revisitCoord, path, _chunkPath, ref rv_chunkMeta);
222 ChunkRenderer.GenerateChunkPngShard(revisitCoord, rv_mapChunk, rv_chunkMeta, ref chunkTopMetadata, out updatedPixels);
224 if (updatedPixels > 0)
227 Logger.VerboseDebug("(re)Wrote top-chunk shard: ({0}), Pixels#:{1}", revisitCoord, updatedPixels);
230 chunkTopMetadata.Update(rv_chunkMeta);
232 }//*********** REVISIT'd ******************
234 if (!columnCounters.IsEmpty)
235 {//Resulting snapshot keys mabey NON-UNIQUE!!! a *FEATURE* of ConcurrentDict !
236 var columnsSnapshot = columnCounters.Where(cks => cks.Value.WeightedSum > editThreshold).OrderByDescending(kvp => kvp.Value.WeightedSum).ToArray( );
238 UpdateEntityMetadata();
240 foreach (var mostActiveCol in columnsSnapshot)
242 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
244 if (mapChunk == null)
247 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
250 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
251 revisitChunkList.Enqueue(mostActiveCol.Key);
255 ColumnMeta chunkMeta;
256 if (chunkTopMetadata.Contains(mostActiveCol.Key))
258 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
260 Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
265 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
267 Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
271 /********* Special Interlock with C.D. *************/
272 if (columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem)) {
273 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
274 ejectedItem.SetCutoff(chunkMeta.YMax / chunkSize);
276 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
277 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
281 Logger.Warning("Prevented duplicate processing of: {0}",mostActiveCol.Key );
285 if (updatedPixels > 0)
288 Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
291 chunkTopMetadata.Update(chunkMeta);
292 //columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
296 //columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
298 Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
300 revisitChunkList.Enqueue(mostActiveCol.Key);
305 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
307 if (updatedChunks > 0)
309 //What about chunk updates themselves; a update bitmap isn't kept...
310 updatedChunksTotal += updatedChunks;
311 JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
314 //Cleanup in-memory Metadata...
315 chunkTopMetadata.ClearMetadata( );
319 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
322 columnCounters.Clear( );
324 //Then sleep until interupted again, and repeat
326 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
328 Thread.Sleep(Timeout.Infinite);
331 catch (ThreadInterruptedException)
335 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
340 catch (ThreadAbortException)
343 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
349 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
352 Write_PlainMetadata( );
360 Logger.VerboseDebug("Snapshot started");
366 Logger.VerboseDebug("Snapshot sleeping");
368 CurrentState = CommandType.Run;
369 Thread.Sleep(Timeout.Infinite);
371 catch (ThreadInterruptedException)
374 Logger.VerboseDebug("Snapshot intertupted");
380 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
382 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
384 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
387 private void Prefill_POI_Designators()
390 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
391 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
392 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
394 var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
395 where airyBlock.MatterState == EnumMatterState.Solid
396 where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
397 where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 || airyBlock.RainPermeable == true
399 //^^ 'Solid' phase - 'Plant' Blocks without any bounding-box; OR 'Invisible' shapes...
400 var invisibleBlocksQuery = from novisBlock in ClientAPI.World.Blocks
401 where novisBlock.Shape == null || novisBlock.Shape.Base.EndsWith(GlobalConstants.DefaultDomain, @"invisible") //Whaat! [ base: "block/basic/invisible" ]
403 this.AiryIdCodes = airBlocksQuery.Union(invisibleBlocksQuery).ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
406 foreach (var fluffBlock in AiryIdCodes) {
407 Logger.VerboseDebug("ID#\t{0}:\t{1} IGNORED", fluffBlock.Key, fluffBlock.Value);
409 Logger.VerboseDebug("Ignoring {0} blocks", AiryIdCodes.Count);
412 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
413 Reload_POI_Designators();
416 private void Reload_POI_Designators()
418 uint poisSetup =0, eoiSetup = 0;
419 foreach (var designator in configuration.BlockDesignators)
421 if (designator.Enabled == false) continue;
422 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
423 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
424 foreach (var entry in blockIDs)
426 BlockID_Designators.Add(entry.Key, designator);
430 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
431 Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
434 foreach (var designator in configuration.EntityDesignators)
436 if (designator.Enabled == false) continue;
437 //Get Variants first, from EntityTypes...better be populated!
438 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
440 foreach (var match in matched)
442 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
443 this.Entity_Designators.Add(match.Code, designator);
447 Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
454 /// Store Points/Entity of Interest
456 private void PersistPointsData()
458 //POI and EOI raw dump files ~ WRITE em!
459 //var poiRawFile = File.
460 string poiPath = Path.Combine(path, poiFileName);
461 string eoiPath = Path.Combine(path, eoiFileName);
463 if (this.POIs.Count > 0)
465 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.Write, FileShare.None))
467 Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
472 if (this.EOIs.Count > 0)
474 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.Write, FileShare.None))
476 Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
481 //Create Easy to Parse TSV file for tool/human use....
482 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
484 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
486 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
487 foreach (var point in this.POIs)
489 tsvWriter.Write(point.Name + "\t");
490 var notes = point.Notes
491 .Replace('\n', '\x001f')
492 .Replace("\t", "\\t")
493 .Replace("\\", "\\\\");
494 tsvWriter.Write(notes + "\t");
495 tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
496 tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
497 tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
498 tsvWriter.Write("null\t");
499 tsvWriter.WriteLine();
501 foreach (var entity in this.EOIs)
503 tsvWriter.Write(entity.Name + "\t");
504 var notes = entity.Notes
505 .Replace('\n', '\x001f')
506 .Replace("\t", "\\t")
507 .Replace("\\", "\\\\");
508 tsvWriter.Write(notes + "\t");
509 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
510 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
511 tsvWriter.Write("---\t");
512 tsvWriter.Write(entity.EntityId.ToString("D"));
513 tsvWriter.WriteLine();
515 tsvWriter.WriteLine();
521 private void Write_PlainMetadata( )
523 string metaPath = Path.Combine(path, plainMetadataFileName);
525 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
526 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII))
528 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
529 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
530 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
531 //mdWriter.WriteLine("CurrentPlayerSpawn", ClientAPI.World.Player.WorldData.EntityPlayer.);
532 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
533 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
534 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
535 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
536 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
537 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
538 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
539 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
540 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
541 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);
548 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
550 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
551 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
553 mostActiveCol.Key.Y * chunkSize);
555 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
556 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
561 private ColumnMeta CreateColumnMetadata(Vec2i coords, IMapChunk mapChunk)
563 ColumnMeta data = new ColumnMeta(coords, ClientAPI, ( byte )chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
564 BlockPos equivBP = new BlockPos(coords.X * chunkSize,
566 coords.Y * chunkSize);
568 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
569 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
575 /// Reload chunk bounds from chunk shards
577 /// <returns>The metadata.</returns>
578 private void Reload_Metadata()
580 var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
582 if (!shardsDir.Exists)
585 Logger.VerboseDebug("Could not open world map (shards) directory");
589 var shardFiles = shardsDir.GetFiles(chunkFile_filter);
591 if (shardFiles.Length > 0)
594 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
597 foreach (var shardFile in shardFiles)
600 if (shardFile.Length < 1024) continue;
601 var result = chunkShardRegex.Match(shardFile.Name);
602 if (!result.Success) continue;
604 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
605 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
609 using (var fileStream = shardFile.OpenRead())
612 PngReader pngRead = new PngReader(fileStream);
613 pngRead.ReadSkippingAllRows();
615 //Parse PNG chunks for METADATA in shard
616 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
617 var column = metadataFromPng.ChunkMetadata;
618 if (column.PrettyLocation == null)
619 column = column.Reload(ClientAPI);
620 chunkTopMetadata.Add(column);
624 catch (PngjException someEx)
626 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
629 catch (ProtoException protoEx)
631 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
637 //POI and EOI raw dump files ~ reload em!
638 //var poiRawFile = File.
639 string poiPath = Path.Combine(path, poiFileName);
640 string eoiPath = Path.Combine(path, eoiFileName);
642 if (File.Exists(poiPath))
644 using (var poiFile = File.OpenRead(poiPath))
646 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
647 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
651 if (File.Exists(eoiPath))
653 using (var eoiFile = File.OpenRead(eoiPath))
655 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
656 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
665 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
667 /// <param name="key">Chunk Coordinate</param>
668 /// <param name="mapChunk">Map chunk.</param>
669 /// <param name="chunkMeta">Chunk metadata</param>
670 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
672 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish...
676 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
679 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
681 for (; targetChunkY > 0; targetChunkY--)
683 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
685 if (worldChunk == null || worldChunk.BlockEntities == null || worldChunk.Disposed)
688 Logger.VerboseDebug("WORLD chunk, null/disposed OR B.E. null: X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
694 if (worldChunk.IsPacked())
697 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
699 //VALIDATE: check Read-only applicable
700 if (worldChunk.Unpack_ReadOnly( ) == false)
702 Logger.Warning("Failed to unpack chunk: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
708 /*************** Chunk Entities Scanning *********************/
709 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
712 Logger.VerboseDebug("Scan in Chunk:({0}, Y {2}): found {1} BlockEntities", key, worldChunk.BlockEntities.Count,targetChunkY);
715 foreach (var blockEnt in worldChunk.BlockEntities)
717 var blockEntityPos = blockEnt.Key;
718 var blockEntity = blockEnt.Value;
719 if (blockEntityPos == null || blockEntity == null ) continue;
720 if (blockEntity.Block != null && !blockEntity.Block.IsMissing && BlockID_Designators.ContainsKey(blockEntity.Block.BlockId))
722 var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
723 if (designator != null && designator.SpecialAction != null) designator.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
728 /********************* Chunk/Column BLOCKs scanning ****************/
729 //Heightmap, Stats, block tally
731 int X_index, Y_index, Z_index;
733 //First Chance fail-safe;
734 if (worldChunk.MaybeBlocks == null || worldChunk.MaybeBlocks.Length <= 0) {
736 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
742 chunkMeta.ColumnPresense[targetChunkY] = true;
744 for (Y_index = 0; Y_index < chunkSize; Y_index++)
746 for (Z_index = 0; Z_index < chunkSize; Z_index++)
748 for (X_index = 0; X_index < chunkSize; X_index++)
750 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
752 //'Last' Chance fail-safe;
753 if (worldChunk.MaybeBlocks == null || worldChunk.MaybeBlocks.Length <= 0) {
755 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
761 int aBlockId = worldChunk.MaybeBlocks[indicie];
763 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
764 chunkMeta.AirBlocks++;
768 if (RockIdCodes.ContainsKey(aBlockId)) {
769 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
770 chunkMeta.RockRatio[aBlockId]++;
772 chunkMeta.RockRatio.Add(aBlockId, 1);
775 chunkMeta.NonAirBlocks++;
777 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
778 //Heightmap - Need to ignore Grass & Snow
779 if (localHeight > chunkMeta.HeightMap[X_index, Z_index])
781 chunkMeta.HeightMap[X_index, Z_index] = localHeight;
782 if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
790 Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
794 private void UpdateEntityMetadata()
797 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
800 var keyList = new long[ClientAPI.World.LoadedEntities.Keys.Count];
801 ClientAPI.World.LoadedEntities.Keys.CopyTo(keyList, 0);
803 //'ElementAt'; worse! instead; walk fixed list...
805 foreach (var key in keyList)
807 if (ClientAPI.World.LoadedEntities.TryGetValue(key, out loadedEntity))
810 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
813 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Code));
814 if (dMatch.Value != null)
816 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Pos.AsBlockPos.Copy( ), loadedEntity);
822 private void AddNote(string notation)
824 var playerNodePoi = new PointOfInterest()
827 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
829 Timestamp = DateTime.UtcNow,
832 this.POIs.AddReplace(playerNodePoi);
837 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
839 //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
841 CommandData cmdData = data as CommandData;
843 switch (cmdData.State)
845 case CommandType.Run:
846 case CommandType.Stop:
847 case CommandType.Snapshot:
848 if (CurrentState != cmdData.State)
850 CurrentState = cmdData.State;
855 case CommandType.Notation:
856 //Add to POI list where player location
857 AddNote(cmdData.Notation);
861 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
866 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
868 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
869 switch (rendererName)
871 case StandardRenderer.Name:
872 return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
874 case AlternateRenderer.Name:
875 return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
877 case FlatRenderer.Name:
878 return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
881 throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");