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.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 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\tDestination");
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.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
410 tsvWriter.WriteLine();
412 foreach (var entity in this.EOIs)
414 tsvWriter.Write(entity.Name + "\t");
415 var notes = entity.Notes
416 .Replace("\n", "\\n")
417 .Replace("\t", "\\t")
418 .Replace("\\", "\\\\");
419 tsvWriter.Write(notes + "\t");
420 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
421 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
422 tsvWriter.Write("n/a\t");
423 tsvWriter.WriteLine();
425 tsvWriter.WriteLine();
431 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
433 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize);
434 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
436 mostActiveCol.Key.Y * chunkSize);
438 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
439 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
445 /// Reload chunk bounds from chunk shards
447 /// <returns>The metadata.</returns>
448 private void Reload_Metadata()
450 var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
452 if (!shardsDir.Exists)
455 Logger.VerboseDebug("Could not open world map (shards) directory");
459 var shardFiles = shardsDir.GetFiles(chunkFile_filter);
461 if (shardFiles.Length > 0)
464 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
467 foreach (var shardFile in shardFiles)
470 if (shardFile.Length < 1024) continue;
471 var result = chunkShardRegex.Match(shardFile.Name);
472 if (!result.Success) continue;
474 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
475 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
479 using (var fileStream = shardFile.OpenRead())
482 PngReader pngRead = new PngReader(fileStream);
483 pngRead.ReadSkippingAllRows();
485 //Parse PNG chunks for METADATA in shard
486 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
487 var column = metadataFromPng.ChunkMetadata;
488 if (column.PrettyLocation == null)
489 column = column.Reload(ClientAPI);
490 chunkTopMetadata.Add(column);
494 catch (PngjException someEx)
496 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
502 //POI and EOI raw dump files ~ reload em!
503 //var poiRawFile = File.
504 string poiPath = Path.Combine(path, poiFileName);
505 string eoiPath = Path.Combine(path, eoiFileName);
507 if (File.Exists(poiPath))
509 using (var poiFile = File.OpenRead(poiPath))
511 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
512 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
516 if (File.Exists(eoiPath))
518 using (var eoiFile = File.OpenRead(eoiPath))
520 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
521 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
527 private PngWriter SetupPngImage(Vec2i coord, ref ColumnMeta metadata)
529 ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
531 string filename = $"{coord.X}_{coord.Y}.png";
532 filename = Path.Combine(path, _chunkPath ,filename);
534 PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
535 PngMetadata meta = pngWriter.GetMetadata();
537 meta.SetText("Chunk_X", coord.X.ToString("D"));
538 meta.SetText("Chunk_Y", coord.Y.ToString("D"));
539 //Setup specialized meta-data PNG chunks here...
540 PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
542 ChunkMetadata = metadata
544 pngWriter.GetChunksList().Queue(pngChunkMeta);
545 pngWriter.CompLevel = 5;// 9 is the maximum compression but thats too high for the small benefit it gives
546 pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
552 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
554 /// <param name="key">Chunk Coordinate</param>
555 /// <param name="mapChunk">Map chunk.</param>
556 /// <param name="chunkMeta">Chunk metadata</param>
557 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
560 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ...
561 for (; targetChunkY > 0; targetChunkY--)
563 WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
565 if (chunkData == null || chunkData.BlockEntities == null)
568 Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
574 /*************** Chunk Entities Scanning *********************/
575 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Count > 0)
578 Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Count);
581 foreach (var blockEnt in chunkData.BlockEntities)
583 if (blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
585 var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
586 designator.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
590 /********************* Chunk/Column BLOCKs scanning ****************/
591 //Heightmap, Stats, block tally
594 //int X_index, Y_index, Z_index;
596 //Ensure ChunkData Metadata fields arn't null...due to being tossed out
597 //if (chunkMeta.HeightMap == null) { chunkMeta.HeightMap = new ushort[chunkSize, chunkSize]; }
598 //if (chunkMeta.RockRatio == null) { chunkMeta.RockRatio = new Dictionary<int, uint>(10); }
600 //for (Y_index = 0; Y_index < chunkSize - 1; Y_index++)
602 // for (Z_index = 0; Z_index < chunkSize - 1; Z_index++)
604 // for (X_index = 0; X_index < chunkSize - 1; X_index++)
606 // /* Encode packed indicie
607 // (y * chunksize + z) * chunksize + x
609 // var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
610 // int aBlockId = chunkData.Blocks[indicie];
612 // if (aBlockId == 0)
614 // chunkMeta.AirBlocks++;
618 // if (RockIdCodes.ContainsKey(aBlockId))
620 // if (chunkMeta.RockRatio.ContainsKey(aBlockId))
621 // chunkMeta.RockRatio[aBlockId]++;
623 // chunkMeta.RockRatio.Add(aBlockId, 1);
626 // chunkMeta.NonAirBlocks++;
629 // //if (chunkMeta.HeightMap[X_index, Z_index] == 0)
632 // // chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize));
642 private void UpdateEntityMetadata()
644 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
645 //Mabey scan only for 'new' entities by tracking ID in set?
646 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
650 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
653 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
654 if (dMatch.Value != null)
656 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.Pos.AsBlockPos.Copy(), loadedEntity.Value);
664 private void AddNote(string notation)
666 var playerNodePoi = new PointOfInterest()
669 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
671 Timestamp = DateTime.UtcNow,
674 this.POIs.AddReplace(playerNodePoi);
679 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
681 //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
683 CommandData cmdData = data as CommandData;
685 switch (cmdData.State)
687 case CommandType.Run:
688 case CommandType.Stop:
689 case CommandType.Snapshot:
690 if (CurrentState != cmdData.State)
692 CurrentState = cmdData.State;
693 AwakenCartographer(0.0f);
697 case CommandType.Notation:
698 //Add to POI list where player location
699 AddNote(cmdData.Notation);
703 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");