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 Thread snapshotThread;
31 private Snapshotter snapshot;
32 private ICoreClientAPI ClientAPI { get; set; }
33 private ILogger Logger { get; set; }
34 private IChunkRenderer ChunkRenderer { get; set; }
35 private JsonGenerator JsonGenerator { get; set; }
37 internal const string _mapPath = @"Maps";
38 internal const string _chunkPath = @"Chunks";
39 private const string _domain = @"automap";
40 private const string chunkFile_filter = @"*_*.png";
41 private const string poiFileName = @"poi_binary";
42 private const string eoiFileName = @"eoi_binary";
43 private const string pointsTsvFileName = @"points_of_interest.tsv";
44 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
46 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
47 private ColumnsMetadata chunkTopMetadata;
48 private PointsOfInterest POIs = new PointsOfInterest();
49 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
51 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
52 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
53 internal Dictionary<int, string> RockIdCodes { 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;
74 ClientAPI.Event.LevelFinalize += EngageAutomap;
75 configuration = config;
77 //TODO:Choose which one from GUI
78 this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
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.Debug("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.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.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 snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize,ClientAPI.World.Seed );
125 snapshotThread = new Thread(Snap)
128 Priority = ThreadPriority.Lowest,
132 ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
135 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
137 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
139 columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
142 private void AwakenCartographer(float delayed)
145 if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
148 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
151 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
153 cartographer_thread.Start();
155 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
157 //Time to (re)write chunk shards
158 cartographer_thread.Interrupt();
161 //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})");
164 else if (CurrentState == CommandType.Snapshot)
166 if (snapshotThread.ThreadState.HasFlag(ThreadState.Unstarted))
168 snapshotThread.Start();
169 } else if (snapshotThread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
171 snapshotThread.Interrupt();
178 private void Cartographer()
181 Logger.VerboseDebug("Cartographer thread awoken");
185 uint ejectedItem = 0;
186 uint updatedChunks = 0;
187 uint updatedPixels = 0;
189 //-- Should dodge enumerator changing underfoot....at a cost.
190 if (!columnCounter.IsEmpty)
192 var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
193 UpdateEntityMetadata();
195 foreach (var mostActiveCol in tempSet)
197 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
199 if (mapChunk == null)
201 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
203 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
207 ColumnMeta chunkMeta;
208 if (chunkTopMetadata.Contains(mostActiveCol.Key))
210 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
212 Logger.VerboseDebug("Loaded chunk {0}", mostActiveCol.Key);
217 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
219 Logger.VerboseDebug("Created chunk {0}", mostActiveCol.Key);
222 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
224 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, ref chunkMeta);
225 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
227 if (updatedPixels > 0)
230 Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
233 chunkTopMetadata.Update(chunkMeta);
234 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
238 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
240 Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
244 //Cleanup persisted Metadata...
245 chunkTopMetadata.ClearMetadata();
248 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
250 if (updatedChunks > 0)
252 //What about chunk updates themselves; a update bitmap isn't kept...
253 updatedChunksTotal += updatedChunks;
254 JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
258 //Then sleep until interupted again, and repeat
260 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
262 Thread.Sleep(Timeout.Infinite);
265 catch (ThreadInterruptedException)
269 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
274 catch (ThreadAbortException)
277 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
283 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
293 Logger.VerboseDebug("Snapshot started");
299 Logger.VerboseDebug("Snapshot sleeping");
301 CurrentState = CommandType.Run;
302 Thread.Sleep(Timeout.Infinite);
304 catch (ThreadInterruptedException)
307 Logger.VerboseDebug("Snapshot intertupted");
313 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
315 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
317 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
320 private void Prefill_POI_Designators()
323 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
324 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
325 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
327 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
329 Reload_POI_Designators();
332 private void Reload_POI_Designators()
334 Logger.VerboseDebug("Connecting {0} Configured Block-Designators", configuration.BlockDesignators.Count);
335 foreach (var designator in configuration.BlockDesignators)
337 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
338 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
339 foreach (var entry in blockIDs)
341 BlockID_Designators.Add(entry.Key, designator);
344 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
347 Logger.VerboseDebug("Connecting {0} Configured Entity-Designators", configuration.EntityDesignators.Count);
348 foreach (var designator in configuration.EntityDesignators)
350 //Get Variants first, from EntityTypes...better be populated!
351 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
353 foreach (var match in matched)
355 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
356 this.Entity_Designators.Add(match.Code, designator);
359 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
368 /// Store Points/Entity of Interest
370 private void PersistPointsData()
372 //POI and EOI raw dump files ~ WRITE em!
373 //var poiRawFile = File.
374 string poiPath = Path.Combine(path, poiFileName);
375 string eoiPath = Path.Combine(path, eoiFileName);
377 if (this.POIs.Count > 0)
379 using (var poiFile = File.OpenWrite(poiPath))
381 Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
385 if (this.EOIs.Count > 0)
387 using (var eoiFile = File.OpenWrite(eoiPath))
389 Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
393 //Create Easy to Parse TSV file for tool/human use....
394 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
396 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
398 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\t");
399 foreach (var point in this.POIs)
401 tsvWriter.Write(point.Name + "\t");
402 var notes = point.Notes
403 .Replace("\n", "\\n")
404 .Replace("\t", "\\t")
405 .Replace("\\", "\\\\");
406 tsvWriter.Write(notes + "\t");
407 tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
408 tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
409 tsvWriter.WriteLine();
411 foreach (var entity in this.EOIs)
413 tsvWriter.Write(entity.Name + "\t");
414 var notes = entity.Notes
415 .Replace("\n", "\\n")
416 .Replace("\t", "\\t")
417 .Replace("\\", "\\\\");
418 tsvWriter.Write(notes + "\t");
419 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
420 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
421 tsvWriter.WriteLine();
423 tsvWriter.WriteLine();
429 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
431 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize);
432 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
434 mostActiveCol.Key.Y * chunkSize);
436 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
437 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
443 /// Reload chunk bounds from chunk shards
445 /// <returns>The metadata.</returns>
446 private void Reload_Metadata()
448 var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
450 if (!shardsDir.Exists)
453 Logger.VerboseDebug("Could not open world map (shards) directory");
457 var shardFiles = shardsDir.GetFiles(chunkFile_filter);
459 if (shardFiles.Length > 0)
462 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
465 foreach (var shardFile in shardFiles)
468 if (shardFile.Length < 1024) continue;
469 var result = chunkShardRegex.Match(shardFile.Name);
470 if (!result.Success) continue;
472 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
473 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
477 using (var fileStream = shardFile.OpenRead())
480 PngReader pngRead = new PngReader(fileStream);
481 pngRead.ReadSkippingAllRows();
483 //Parse PNG chunks for METADATA in shard
484 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
485 var column = metadataFromPng.ChunkMetadata;
486 if (column.PrettyLocation == null)
487 column = column.Reload(ClientAPI);
488 chunkTopMetadata.Add(column);
492 catch (PngjException someEx)
494 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
500 //POI and EOI raw dump files ~ reload em!
501 //var poiRawFile = File.
502 string poiPath = Path.Combine(path, poiFileName);
503 string eoiPath = Path.Combine(path, eoiFileName);
505 if (File.Exists(poiPath))
507 using (var poiFile = File.OpenRead(poiPath))
509 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
510 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
514 if (File.Exists(eoiPath))
516 using (var eoiFile = File.OpenRead(eoiPath))
518 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
519 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
525 private PngWriter SetupPngImage(Vec2i coord, ref ColumnMeta metadata)
527 ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
529 string filename = $"{coord.X}_{coord.Y}.png";
530 filename = Path.Combine(path, _chunkPath ,filename);
532 PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
533 PngMetadata meta = pngWriter.GetMetadata();
535 meta.SetText("Chunk_X", coord.X.ToString("D"));
536 meta.SetText("Chunk_Y", coord.Y.ToString("D"));
537 //Setup specialized meta-data PNG chunks here...
538 PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
540 ChunkMetadata = metadata
542 pngWriter.GetChunksList().Queue(pngChunkMeta);
543 pngWriter.CompLevel = 5;// 9 is the maximum compression but thats too high for the small benefit it gives
544 pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
550 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
552 /// <param name="key">Chunk Coordinate</param>
553 /// <param name="mapChunk">Map chunk.</param>
554 /// <param name="chunkMeta">Chunk metadata</param>
555 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
558 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ...
559 for (; targetChunkY > 0; targetChunkY--)
561 WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
563 if (chunkData == null || chunkData.BlockEntities == null)
566 Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
572 /*************** Chunk Entities Scanning *********************/
573 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
576 Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
579 foreach (var blockEnt in chunkData.BlockEntities)
581 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
583 var designator = BlockID_Designators[blockEnt.Block.BlockId];
584 designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
588 /********************* Chunk/Column BLOCKs scanning ****************/
589 //Heightmap, Stats, block tally
592 //int X_index, Y_index, Z_index;
594 //Ensure ChunkData Metadata fields arn't null...due to being tossed out
595 //if (chunkMeta.HeightMap == null) { chunkMeta.HeightMap = new ushort[chunkSize, chunkSize]; }
596 //if (chunkMeta.RockRatio == null) { chunkMeta.RockRatio = new Dictionary<int, uint>(10); }
598 //for (Y_index = 0; Y_index < chunkSize - 1; Y_index++)
600 // for (Z_index = 0; Z_index < chunkSize - 1; Z_index++)
602 // for (X_index = 0; X_index < chunkSize - 1; X_index++)
604 // /* Encode packed indicie
605 // (y * chunksize + z) * chunksize + x
607 // var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
608 // int aBlockId = chunkData.Blocks[indicie];
610 // if (aBlockId == 0)
612 // chunkMeta.AirBlocks++;
616 // if (RockIdCodes.ContainsKey(aBlockId))
618 // if (chunkMeta.RockRatio.ContainsKey(aBlockId))
619 // chunkMeta.RockRatio[aBlockId]++;
621 // chunkMeta.RockRatio.Add(aBlockId, 1);
624 // chunkMeta.NonAirBlocks++;
627 // //if (chunkMeta.HeightMap[X_index, Z_index] == 0)
630 // // chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize));
640 private void UpdateEntityMetadata()
642 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
643 //Mabey scan only for 'new' entities by tracking ID in set?
644 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
648 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
651 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
652 if (dMatch.Value != null)
654 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
662 private void AddNote(string notation)
664 var playerNodePoi = new PointOfInterest()
667 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
669 Timestamp = DateTime.UtcNow,
672 this.POIs.AddReplace(playerNodePoi);
677 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
679 //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
681 CommandData cmdData = data as CommandData;
683 switch (cmdData.State)
685 case CommandType.Run:
686 case CommandType.Stop:
687 case CommandType.Snapshot:
688 if (CurrentState != cmdData.State)
690 CurrentState = cmdData.State;
691 AwakenCartographer(0.0f);
695 case CommandType.Notation:
696 //Add to POI list where player location
697 AddNote(cmdData.Notation);
701 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");