2 using System.Collections.Concurrent;
3 using System.Collections.Generic;
6 using System.Reflection;
8 using System.Text.RegularExpressions;
9 using System.Threading;
12 using Hjg.Pngcs.Chunks;
14 using Newtonsoft.Json;
18 using Vintagestory.API.Client;
19 using Vintagestory.API.Common;
20 using Vintagestory.API.Config;
21 using Vintagestory.API.Datastructures;
22 using Vintagestory.API.MathTools;
23 using Vintagestory.Common;
27 public class AutomapSystem
29 private Thread cartographer_thread;
30 private ICoreClientAPI ClientAPI { get; set; }
31 private ILogger Logger { get; set; }
32 private IChunkRenderer ChunkRenderer { get; set; }
33 private JsonGenerator JsonGenerator { get; set; }
35 private const string _mapPath = @"Maps";
36 private const string _chunkPath = @"Chunks";
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 static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+).png", RegexOptions.Singleline);
44 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
45 private ColumnsMetadata chunkTopMetadata;
46 private PointsOfInterest POIs = new PointsOfInterest();
47 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
49 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
50 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
51 internal Dictionary<int, string> RockIdCodes { get; private set; }
53 internal CommandType CurrentState { get; set; }
54 //Run status, Chunks processed, stats, center of map....
55 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
56 private Vec2i startChunkColumn;
58 private readonly int chunkSize;
60 private IAsset staticMap;
61 private PersistedConfiguration configuration;
64 public static string AutomapStatusEventKey = @"AutomapStatus";
65 public static string AutomapCommandEventKey = @"AutomapCommand";
67 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
69 this.ClientAPI = clientAPI;
71 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
72 ClientAPI.Event.LevelFinalize += EngageAutomap;
73 configuration = config;
76 //TODO:Choose which one from GUI
77 this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
79 //Listen on bus for commands
80 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
82 if (configuration.Autostart)
84 CurrentState = CommandType.Run;
85 Logger.Debug("Autostart is Enabled.");
92 private void EngageAutomap()
94 path = ClientAPI.GetOrCreateDataPath(_mapPath);
95 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
96 JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
98 string mapFilename = Path.Combine(path, "automap.html");
99 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
101 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
102 outputText.Write(staticMap.ToText());
105 Prefill_POI_Designators();
106 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / chunkSize));
107 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
109 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
112 ClientAPI.Event.ChunkDirty += ChunkAChanging;
114 cartographer_thread = new Thread(Cartographer)
116 Name = "Cartographer",
117 Priority = ThreadPriority.Lowest,
121 ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
124 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
126 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
128 columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
131 private void AwakenCartographer(float delayed)
134 if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
137 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
140 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
142 cartographer_thread.Start();
144 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
146 //Time to (re)write chunk shards
147 cartographer_thread.Interrupt();
150 //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})");
153 else if (CurrentState == CommandType.Snapshot)
155 //TODO: Snapshot generator second thread...
161 private void Cartographer()
164 Logger.VerboseDebug("Cartographer thread awoken");
168 uint ejectedItem = 0;
169 uint updatedChunks = 0;
170 uint updatedPixels = 0;
172 //-- Should dodge enumerator changing underfoot....at a cost.
173 if (!columnCounter.IsEmpty)
175 var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
176 UpdateEntityMetadata();
178 foreach (var mostActiveCol in tempSet)
180 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
182 if (mapChunk == null)
184 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
186 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
190 ColumnMeta chunkMeta;
191 if (chunkTopMetadata.Contains(mostActiveCol.Key))
193 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
195 Logger.VerboseDebug("Loaded chunk {0}", mostActiveCol.Key);
196 //Console.WriteLine($"Load {mostActiveCol.Key}");
201 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
203 Logger.VerboseDebug("Created chunk {0}", mostActiveCol.Key);
204 //Console.WriteLine($"Created chunk {mostActiveCol.Key}");
208 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
210 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, ref chunkMeta);
211 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
213 if (updatedPixels > 0)
216 Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
219 chunkTopMetadata.Update(chunkMeta);
220 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
224 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
225 Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
228 //Cleanup persisted Metadata...
229 chunkTopMetadata.ClearMetadata( );
232 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
234 if (updatedChunks > 0)
236 //What about chunk updates themselves; a update bitmap isn't kept...
237 updatedChunksTotal += updatedChunks;
238 JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
242 //Then sleep until interupted again, and repeat
244 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
246 Thread.Sleep(Timeout.Infinite);
249 catch (ThreadInterruptedException)
252 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
256 catch (ThreadAbortException)
258 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
263 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
268 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
270 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
272 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
275 private void Prefill_POI_Designators()
278 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
279 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
280 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
282 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
284 Reload_POI_Designators();
287 private void Reload_POI_Designators()
289 Logger.VerboseDebug("Connecting {0} Configured Block-Designators", configuration.BlockDesignators.Count);
290 foreach (var designator in configuration.BlockDesignators)
292 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
293 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
294 foreach (var entry in blockIDs)
296 BlockID_Designators.Add(entry.Key, designator);
299 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
302 Logger.VerboseDebug("Connecting {0} Configured Entity-Designators", configuration.EntityDesignators.Count);
303 foreach (var designator in configuration.EntityDesignators)
305 //Get Variants first, from EntityTypes...better be populated!
306 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
308 foreach (var match in matched)
310 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
311 this.Entity_Designators.Add(match.Code, designator);
316 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
325 /// Store Points/Entity of Interest
327 private void PersistPointsData( )
329 //POI and EOI raw dump files ~ WRITE em!
330 //var poiRawFile = File.
331 string poiPath = Path.Combine(path, poiFileName);
332 string eoiPath = Path.Combine(path, eoiFileName);
334 if (this.POIs.Count > 0) {
335 using (var poiFile = File.OpenWrite(poiPath)) {
336 Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
340 if (this.EOIs.Count > 0) {
341 using (var eoiFile = File.OpenWrite(eoiPath)) {
342 Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
346 //Create Easy to Parse TSV file for tool/human use....
347 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
349 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
351 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\t");
352 foreach (var point in this.POIs) {
353 tsvWriter.Write(point.Name + "\t");
354 tsvWriter.Write(point.Notes + "\t");
355 tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
356 tsvWriter.Write(point.Timestamp.ToString("u")+"\t");
357 tsvWriter.WriteLine();
359 foreach (var entity in this.EOIs) {
360 tsvWriter.Write(entity.Name + "\t");
361 tsvWriter.Write(entity.Notes + "\t");
362 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
363 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
364 tsvWriter.WriteLine( );
366 tsvWriter.WriteLine();
372 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
374 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize);
375 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
377 mostActiveCol.Key.Y * chunkSize);
379 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
380 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
386 /// Reload chunk bounds from chunk shards
388 /// <returns>The metadata.</returns>
389 private void Reload_Metadata()
391 var worldmapDir = new DirectoryInfo(path);
393 if (!worldmapDir.Exists)
396 Logger.VerboseDebug("Could not open world map directory");
400 var shardFiles = worldmapDir.GetFiles(chunkFile_filter);
402 if (shardFiles.Length > 0)
405 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
408 foreach (var shardFile in shardFiles)
411 if (shardFile.Length < 1024) continue;
412 var result = chunkShardRegex.Match(shardFile.Name);
415 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
416 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
420 using (var fileStream = shardFile.OpenRead())
423 PngReader pngRead = new PngReader(fileStream);
424 pngRead.ReadSkippingAllRows();
426 //Parse PNG chunks for METADATA in shard
427 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
428 var column = metadataFromPng.ChunkMetadata;
429 if (column.PrettyLocation == null)
430 column = column.Reload(ClientAPI);
431 chunkTopMetadata.Add(column);
435 catch (PngjException someEx)
437 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
445 //POI and EOI raw dump files ~ reload em!
446 //var poiRawFile = File.
447 string poiPath = Path.Combine(path, poiFileName);
448 string eoiPath = Path.Combine(path, eoiFileName);
450 if (File.Exists(poiPath))
452 using (var poiFile = File.OpenRead(poiPath))
454 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
455 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
459 if (File.Exists(eoiPath))
461 using (var eoiFile = File.OpenRead(eoiPath))
463 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
464 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
470 private PngWriter SetupPngImage(Vec2i coord, ref ColumnMeta metadata)
472 ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
474 string filename = $"{coord.X}_{coord.Y}.png";
475 filename = Path.Combine(path, filename);
477 PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
478 PngMetadata meta = pngWriter.GetMetadata();
480 meta.SetText("Chunk_X", coord.X.ToString("D"));
481 meta.SetText("Chunk_Y", coord.Y.ToString("D"));
482 //Setup specialized meta-data PNG chunks here...
483 PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
485 ChunkMetadata = metadata
487 pngWriter.GetChunksList().Queue(pngChunkMeta);
488 pngWriter.CompLevel = 5;// 9 is the maximum compression but thats too high for the small benefit it gives
489 pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
495 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
497 /// <param name="key">Chunk Coordinate</param>
498 /// <param name="mapChunk">Map chunk.</param>
499 /// <param name="chunkMeta">Chunk metadata</param>
500 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
503 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ...
504 for (; targetChunkY > 0; targetChunkY--)
506 WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
508 if (chunkData == null || chunkData.BlockEntities == null) {
510 Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
516 /*************** Chunk Entities Scanning *********************/
517 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
520 Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
523 foreach (var blockEnt in chunkData.BlockEntities)
525 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
527 var designator = BlockID_Designators[blockEnt.Block.BlockId];
528 designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
532 /********************* Chunk/Column BLOCKs scanning ****************/
533 //Heightmap, Stats, block tally
536 int X_index, Y_index, Z_index;
537 X_index = Y_index = Z_index = 0;
539 //Ensure ChunkData Metadata fields arn't null...due to being tossed out
540 if (chunkMeta.HeightMap == null) { chunkMeta.HeightMap = new ushort[chunkSize, chunkSize]; }
541 if (chunkMeta.RockRatio == null) { chunkMeta.RockRatio = new Dictionary<int, uint>(10); }
549 /* Encode packed indicie
550 (y * chunksize + z) * chunksize + x
552 var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
553 int aBlockId = chunkData.Blocks[indicie];
557 chunkMeta.AirBlocks++;
561 if (RockIdCodes.ContainsKey(aBlockId))
563 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
566 chunkMeta.NonAirBlocks++;
569 if (chunkMeta.HeightMap[X_index, Z_index] == 0)
570 { chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize)); }
573 while (X_index++ < (chunkSize - 1));
576 while (Z_index++ < (chunkSize - 1));
579 while (Y_index++ < (chunkSize - 1));
584 private void UpdateEntityMetadata()
586 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
587 //Mabey scan only for 'new' entities by tracking ID in set?
588 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
592 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
595 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
596 if (dMatch.Value != null)
598 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
606 private void AddNote(string notation)
608 var playerNodePoi = new PointOfInterest()
611 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
613 Timestamp = DateTime.UtcNow,
616 this.POIs.AddReplace(playerNodePoi);
621 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
623 Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
625 CommandData cmdData = data as CommandData;
628 if (CurrentState != CommandType.Snapshot)
630 switch (cmdData.State)
632 case CommandType.Run:
633 case CommandType.Stop:
634 if (CurrentState != cmdData.State)
636 CurrentState = cmdData.State;
637 AwakenCartographer(0.0f);
641 case CommandType.Snapshot:
642 CurrentState = CommandType.Stop;
643 //Snapshot starts a second thread/process...
647 case CommandType.Notation:
648 //Add to POI list where player location
649 AddNote(cmdData.Notation);
657 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");