2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
8 using System.Text.RegularExpressions;
9 using System.Threading;
15 using Vintagestory.API.Client;
16 using Vintagestory.API.Common;
17 using Vintagestory.API.Config;
18 using Vintagestory.API.Datastructures;
19 using Vintagestory.API.MathTools;
20 using Vintagestory.Common;
24 public class AutomapSystem
26 private Thread cartographer_thread;
28 private Snapshotter snapshot;
29 private ICoreClientAPI ClientAPI { get; set; }
30 private ILogger Logger { get; set; }
31 private AChunkRenderer ChunkRenderer { get; set; }
32 private JsonGenerator JsonGenerator { get; set; }
34 internal const string _mapPath = @"Maps";
35 internal const string _chunkPath = @"Chunks";
36 internal const uint editThreshold = 9;
37 private const string _domain = @"automap";
38 private const string chunkFile_filter = @"*_*.png";
39 private const string poiFileName = @"poi_binary";
40 private const string eoiFileName = @"eoi_binary";
41 private const string pointsTsvFileName = @"points_of_interest.tsv";
42 private const string plainMetadataFileName = @"map_metadata.txt";
43 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
45 private ConcurrentDictionary<Vec2i, ColumnCounter> columnCounters = new ConcurrentDictionary<Vec2i, ColumnCounter>(3, 150);
46 private ColumnsMetadata chunkTopMetadata;
47 internal PointsOfInterest POIs = new PointsOfInterest();
48 internal EntitiesOfInterest EOIs = new EntitiesOfInterest();
50 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
51 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
52 internal Dictionary<int, string> RockIdCodes { get; private set; }
53 internal Dictionary<int, string> AiryIdCodes { get; private set; }
55 internal CommandType CurrentState { get; set; }
56 //Run status, Chunks processed, stats, center of map....
57 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
58 private Vec2i startChunkColumn;
60 private readonly int chunkSize;
62 private IAsset staticMap;
63 private PersistedConfiguration configuration;
66 public static string AutomapStatusEventKey = @"AutomapStatus";
67 public static string AutomapCommandEventKey = @"AutomapCommand";
69 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
71 this.ClientAPI = clientAPI;
73 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
75 configuration = config;
76 ClientAPI.Event.LevelFinalize += EngageAutomap;
78 this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
80 //Listen on bus for commands
81 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
84 if (configuration.Autostart)
86 CurrentState = CommandType.Run;
87 Logger.Notification("Autostart is Enabled.");
94 private void EngageAutomap()
96 path = ClientAPI.GetOrCreateDataPath(_mapPath);
97 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
98 ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
100 JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
102 string mapFilename = Path.Combine(path, "automap.html");
103 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
105 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
106 outputText.Write(staticMap.ToText());
109 Prefill_POI_Designators();
110 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
111 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
112 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
115 ClientAPI.Event.ChunkDirty += ChunkAChanging;
117 cartographer_thread = new Thread(Cartographer)
119 Name = "Cartographer",
120 Priority = ThreadPriority.Lowest,
124 ClientAPI.Event.RegisterGameTickListener(ThreadDecider, 6000);
127 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
129 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
130 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
132 columnCounters.AddOrUpdate(topPosition,
133 new ColumnCounter(chunkSize, newOrEdit, chunkCoord),
134 (chkPos, chkChng) => chkChng.Update(chunkCoord, chunkSize, newOrEdit)
140 /// Cartographer Thread 'decider'
142 /// <param name="delayed">called delay offset</param>
143 private void ThreadDecider(float delayed)
146 if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
149 Logger.VerboseDebug("ThreadDecider re-trigger from [{0}]", cartographer_thread.ThreadState);
152 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
154 cartographer_thread.Start();
156 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
158 //Time to (re)write chunk shards
159 cartographer_thread.Interrupt();
162 //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})");
165 else if (CurrentState == CommandType.Snapshot)
167 //Prepare for taking a snopshot
168 if (snapshot == null) {
169 snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize, ClientAPI.World.Seed);
171 Logger.VerboseDebug("Starting new Snapshot: {0} Wx{1} Hx{2}", snapshot.fileName, snapshot.Width, snapshot.Height);
175 else if (snapshot != null && snapshot.Finished) {
177 Logger.VerboseDebug("COMPLETED Snapshot: {0} Wx{1} Hx{2}, taking {3}", snapshot.fileName, snapshot.Width, snapshot.Height, snapshot.Timer.Elapsed);
180 CurrentState = CommandType.Run;
186 private void Cartographer()
189 Logger.VerboseDebug("Cartographer thread awoken");
193 ColumnCounter ejectedItem ;
194 uint updatedChunks = 0;
195 uint updatedPixels = 0;
197 //-- Should dodge enumerator changing underfoot....at a cost.
198 if (!columnCounters.IsEmpty)
200 var tempSet = columnCounters.ToArray().Where(cks => cks.Value.WeightedSum > editThreshold) .OrderByDescending(kvp => kvp.Value.WeightedSum);
201 UpdateEntityMetadata();
203 foreach (var mostActiveCol in tempSet)
205 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
207 if (mapChunk == null)
209 //TODO: REVISIT THIS CHUNK!
211 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
214 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
218 ColumnMeta chunkMeta;
219 if (chunkTopMetadata.Contains(mostActiveCol.Key))
221 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
223 Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
228 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
230 Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
233 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
234 mostActiveCol.Value.SetCutoff(chunkMeta.YMax / chunkSize);
236 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
237 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
239 if (updatedPixels > 0)
242 Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
245 chunkTopMetadata.Update(chunkMeta);
246 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
250 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
252 Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
258 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
260 if (updatedChunks > 0)
262 //What about chunk updates themselves; a update bitmap isn't kept...
263 updatedChunksTotal += updatedChunks;
264 JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
267 //Cleanup in-memory Metadata...
268 chunkTopMetadata.ClearMetadata( );
272 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
275 columnCounters.Clear( );
277 //Then sleep until interupted again, and repeat
279 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
281 Thread.Sleep(Timeout.Infinite);
284 catch (ThreadInterruptedException)
288 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
293 catch (ThreadAbortException)
296 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
302 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
305 Write_PlainMetadata( );
313 Logger.VerboseDebug("Snapshot started");
319 Logger.VerboseDebug("Snapshot sleeping");
321 CurrentState = CommandType.Run;
322 Thread.Sleep(Timeout.Infinite);
324 catch (ThreadInterruptedException)
327 Logger.VerboseDebug("Snapshot intertupted");
333 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
335 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
337 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
340 private void Prefill_POI_Designators()
343 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
344 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
345 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
347 var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
348 where airyBlock.MatterState == EnumMatterState.Solid
349 where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
350 where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 ||airyBlock.RainPermeable == true
352 //^^ 'Solid' phase - 'Plant' Blocks without any boundg box ? Except water...
353 this.AiryIdCodes = airBlocksQuery.ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
355 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
356 Reload_POI_Designators();
359 private void Reload_POI_Designators()
361 uint poisSetup =0, eoiSetup = 0;
362 foreach (var designator in configuration.BlockDesignators)
364 if (designator.Enabled == false) continue;
365 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
366 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
367 foreach (var entry in blockIDs)
369 BlockID_Designators.Add(entry.Key, designator);
373 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
374 Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
377 foreach (var designator in configuration.EntityDesignators)
379 if (designator.Enabled == false) continue;
380 //Get Variants first, from EntityTypes...better be populated!
381 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
383 foreach (var match in matched)
385 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
386 this.Entity_Designators.Add(match.Code, designator);
390 Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
397 /// Store Points/Entity of Interest
399 private void PersistPointsData()
401 //POI and EOI raw dump files ~ WRITE em!
402 //var poiRawFile = File.
403 string poiPath = Path.Combine(path, poiFileName);
404 string eoiPath = Path.Combine(path, eoiFileName);
406 if (this.POIs.Count > 0)
408 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.Write, FileShare.None))
410 Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
415 if (this.EOIs.Count > 0)
417 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.Write, FileShare.None))
419 Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
424 //Create Easy to Parse TSV file for tool/human use....
425 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
427 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
429 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
430 foreach (var point in this.POIs)
432 tsvWriter.Write(point.Name + "\t");
433 var notes = point.Notes
434 .Replace('\n', '\x001f')
435 .Replace("\t", "\\t")
436 .Replace("\\", "\\\\");
437 tsvWriter.Write(notes + "\t");
438 tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
439 tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
440 tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
441 tsvWriter.Write("null\t");
442 tsvWriter.WriteLine();
444 foreach (var entity in this.EOIs)
446 tsvWriter.Write(entity.Name + "\t");
447 var notes = entity.Notes
448 .Replace('\n', '\x001f')
449 .Replace("\t", "\\t")
450 .Replace("\\", "\\\\");
451 tsvWriter.Write(notes + "\t");
452 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
453 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
454 tsvWriter.Write("---\t");
455 tsvWriter.Write(entity.EntityId.ToString("D"));
456 tsvWriter.WriteLine();
458 tsvWriter.WriteLine();
464 private void Write_PlainMetadata( )
466 string metaPath = Path.Combine(path, plainMetadataFileName);
468 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
469 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII))
471 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
472 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
473 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
474 //mdWriter.WriteLine("CurrentPlayerSpawn", ClientAPI.World.Player.WorldData.EntityPlayer.);
475 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
476 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
477 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
478 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
479 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
480 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
481 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
482 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
483 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
484 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);
491 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
493 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
494 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
496 mostActiveCol.Key.Y * chunkSize);
498 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
499 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
505 /// Reload chunk bounds from chunk shards
507 /// <returns>The metadata.</returns>
508 private void Reload_Metadata()
510 var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
512 if (!shardsDir.Exists)
515 Logger.VerboseDebug("Could not open world map (shards) directory");
519 var shardFiles = shardsDir.GetFiles(chunkFile_filter);
521 if (shardFiles.Length > 0)
524 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
527 foreach (var shardFile in shardFiles)
530 if (shardFile.Length < 1024) continue;
531 var result = chunkShardRegex.Match(shardFile.Name);
532 if (!result.Success) continue;
534 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
535 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
539 using (var fileStream = shardFile.OpenRead())
542 PngReader pngRead = new PngReader(fileStream);
543 pngRead.ReadSkippingAllRows();
545 //Parse PNG chunks for METADATA in shard
546 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
547 var column = metadataFromPng.ChunkMetadata;
548 if (column.PrettyLocation == null)
549 column = column.Reload(ClientAPI);
550 chunkTopMetadata.Add(column);
554 catch (PngjException someEx)
556 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
559 catch (ProtoException protoEx)
561 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
567 //POI and EOI raw dump files ~ reload em!
568 //var poiRawFile = File.
569 string poiPath = Path.Combine(path, poiFileName);
570 string eoiPath = Path.Combine(path, eoiFileName);
572 if (File.Exists(poiPath))
574 using (var poiFile = File.OpenRead(poiPath))
576 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
577 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
581 if (File.Exists(eoiPath))
583 using (var eoiFile = File.OpenRead(eoiPath))
585 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
586 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
595 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
597 /// <param name="key">Chunk Coordinate</param>
598 /// <param name="mapChunk">Map chunk.</param>
599 /// <param name="chunkMeta">Chunk metadata</param>
600 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
602 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish...
606 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
609 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
611 for (; targetChunkY > 0; targetChunkY--)
613 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
615 if (worldChunk == null || worldChunk.BlockEntities == null)
618 Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
624 if (worldChunk.IsPacked())
627 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
629 worldChunk.Unpack( );//RESEARCH: Thread Unsafe?
632 /*************** Chunk Entities Scanning *********************/
633 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
636 Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
639 foreach (var blockEnt in worldChunk.BlockEntities)
641 if (blockEnt.Key != null && blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
643 var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
644 designator?.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
649 /********************* Chunk/Column BLOCKs scanning ****************/
650 //Heightmap, Stats, block tally
652 int X_index, Y_index, Z_index;
654 //First Chance fail-safe;
655 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
657 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
663 chunkMeta.ColumnPresense[targetChunkY] = true;
665 for (Y_index = 0; Y_index < chunkSize; Y_index++)
667 for (Z_index = 0; Z_index < chunkSize; Z_index++)
669 for (X_index = 0; X_index < chunkSize; X_index++)
671 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
673 //'Last' Chance fail-safe;
674 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
676 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
682 int aBlockId = worldChunk.Blocks[indicie];
684 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
685 chunkMeta.AirBlocks++;
689 if (RockIdCodes.ContainsKey(aBlockId)) {
690 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
691 chunkMeta.RockRatio[aBlockId]++;
693 chunkMeta.RockRatio.Add(aBlockId, 1);
696 chunkMeta.NonAirBlocks++;
698 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
699 //Heightmap - Need to ignore Grass & Snow
700 if (localHeight > chunkMeta.HeightMap[X_index, Z_index])
702 chunkMeta.HeightMap[X_index, Z_index] = localHeight;
703 if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
711 Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
715 private void UpdateEntityMetadata()
718 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
720 //Mabey scan only for 'new' entities by tracking ID in set?
721 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
725 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
728 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
729 if (dMatch.Value != null)
731 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.Pos.AsBlockPos.Copy(), loadedEntity.Value);
739 private void AddNote(string notation)
741 var playerNodePoi = new PointOfInterest()
744 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
746 Timestamp = DateTime.UtcNow,
749 this.POIs.AddReplace(playerNodePoi);
754 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
756 //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
758 CommandData cmdData = data as CommandData;
760 switch (cmdData.State)
762 case CommandType.Run:
763 case CommandType.Stop:
764 case CommandType.Snapshot:
765 if (CurrentState != cmdData.State)
767 CurrentState = cmdData.State;
772 case CommandType.Notation:
773 //Add to POI list where player location
774 AddNote(cmdData.Notation);
778 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
783 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
785 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
786 switch (rendererName)
788 case StandardRenderer.Name:
789 return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
791 case AlternateRenderer.Name:
792 return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
794 case FlatRenderer.Name:
795 return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
798 throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");