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;
27 private Thread snapshotThread;
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 private const string _domain = @"automap";
37 private const string chunkFile_filter = @"*_*.png";
38 private const string poiFileName = @"poi_binary";
39 private const string eoiFileName = @"eoi_binary";
40 private const string pointsTsvFileName = @"points_of_interest.tsv";
41 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
43 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
44 private ColumnsMetadata chunkTopMetadata;
45 private PointsOfInterest POIs = new PointsOfInterest();
46 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
48 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
49 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
50 internal Dictionary<int, string> RockIdCodes { get; private set; }
51 internal Dictionary<int, string> AiryIdCodes { 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;
75 //TODO:Choose which one from GUI
76 this.ChunkRenderer = new StandardRenderer(clientAPI, logger, this.configuration.SeasonalColors);
78 //Listen on bus for commands
79 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 ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
98 JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
100 string mapFilename = Path.Combine(path, "automap.html");
101 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
103 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
104 outputText.Write(staticMap.ToText());
107 Prefill_POI_Designators();
108 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
109 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
110 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
113 ClientAPI.Event.ChunkDirty += ChunkAChanging;
115 cartographer_thread = new Thread(Cartographer)
117 Name = "Cartographer",
118 Priority = ThreadPriority.Lowest,
122 snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize,ClientAPI.World.Seed );
123 snapshotThread = new Thread(Snap)
126 Priority = ThreadPriority.Lowest,
130 ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
133 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
135 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
137 //TODO: Track Y Chunk - Column, surface chunks being more important
138 //Only NEW/LOADED chunks unless edits > N
139 //if (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded)
141 columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
145 private void AwakenCartographer(float delayed)
148 if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
151 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
154 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
156 cartographer_thread.Start();
158 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
160 //Time to (re)write chunk shards
161 cartographer_thread.Interrupt();
164 //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})");
167 else if (CurrentState == CommandType.Snapshot)
169 if (snapshotThread.ThreadState.HasFlag(ThreadState.Unstarted))
171 snapshotThread.Start();
172 } else if (snapshotThread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
174 snapshotThread.Interrupt();
181 private void Cartographer()
184 Logger.VerboseDebug("Cartographer thread awoken");
188 uint ejectedItem = 0;
189 uint updatedChunks = 0;
190 uint updatedPixels = 0;
192 //-- Should dodge enumerator changing underfoot....at a cost.
193 if (!columnCounter.IsEmpty)
195 var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
196 UpdateEntityMetadata();
198 foreach (var mostActiveCol in tempSet)
200 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
202 if (mapChunk == null)
204 //TODO: REVISIT THIS CHUNK!
205 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
207 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
211 ColumnMeta chunkMeta;
212 if (chunkTopMetadata.Contains(mostActiveCol.Key))
214 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
216 Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
221 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
223 Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
226 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
228 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
229 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
231 if (updatedPixels > 0)
234 Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
237 chunkTopMetadata.Update(chunkMeta);
238 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
242 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
244 Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
250 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
252 if (updatedChunks > 0)
254 //What about chunk updates themselves; a update bitmap isn't kept...
255 updatedChunksTotal += updatedChunks;
256 JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
259 //Cleanup in-memory Metadata...
260 chunkTopMetadata.ClearMetadata( );
263 //Then sleep until interupted again, and repeat
265 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
267 Thread.Sleep(Timeout.Infinite);
270 catch (ThreadInterruptedException)
274 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
279 catch (ThreadAbortException)
282 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
288 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
298 Logger.VerboseDebug("Snapshot started");
304 Logger.VerboseDebug("Snapshot sleeping");
306 CurrentState = CommandType.Run;
307 Thread.Sleep(Timeout.Infinite);
309 catch (ThreadInterruptedException)
312 Logger.VerboseDebug("Snapshot intertupted");
318 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
320 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
322 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
325 private void Prefill_POI_Designators()
328 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
329 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
330 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
332 var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
333 where airyBlock.MatterState == EnumMatterState.Solid
334 where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
335 where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0
337 //^^ 'Solid' phase - 'Plant' Blocks without any boundg box ? Except water...
338 this.AiryIdCodes = airBlocksQuery.ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
340 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
341 Reload_POI_Designators();
344 private void Reload_POI_Designators()
346 Logger.VerboseDebug("Connecting {0} Configured Block-Designators", configuration.BlockDesignators.Count);
347 foreach (var designator in configuration.BlockDesignators)
349 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
350 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
351 foreach (var entry in blockIDs)
353 BlockID_Designators.Add(entry.Key, designator);
356 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
359 Logger.VerboseDebug("Connecting {0} Configured Entity-Designators", configuration.EntityDesignators.Count);
360 foreach (var designator in configuration.EntityDesignators)
362 //Get Variants first, from EntityTypes...better be populated!
363 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
365 foreach (var match in matched)
367 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
368 this.Entity_Designators.Add(match.Code, designator);
371 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
380 /// Store Points/Entity of Interest
382 private void PersistPointsData()
384 //POI and EOI raw dump files ~ WRITE em!
385 //var poiRawFile = File.
386 string poiPath = Path.Combine(path, poiFileName);
387 string eoiPath = Path.Combine(path, eoiFileName);
389 if (this.POIs.Count > 0)
391 using (var poiFile = File.OpenWrite(poiPath))
393 Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
397 if (this.EOIs.Count > 0)
399 using (var eoiFile = File.OpenWrite(eoiPath))
401 Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
405 //Create Easy to Parse TSV file for tool/human use....
406 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
408 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
410 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination");
411 foreach (var point in this.POIs)
413 tsvWriter.Write(point.Name + "\t");
414 var notes = point.Notes
415 .Replace("\n", "\\n")
416 .Replace("\t", "\\t")
417 .Replace("\\", "\\\\");
418 tsvWriter.Write(notes + "\t");
419 tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
420 tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
421 tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
422 tsvWriter.WriteLine();
424 foreach (var entity in this.EOIs)
426 tsvWriter.Write(entity.Name + "\t");
427 var notes = entity.Notes
428 .Replace("\n", "\\n")
429 .Replace("\t", "\\t")
430 .Replace("\\", "\\\\");
431 tsvWriter.Write(notes + "\t");
432 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
433 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
434 tsvWriter.Write("n/a\t");
435 tsvWriter.WriteLine();
437 tsvWriter.WriteLine();
443 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
445 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
446 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
448 mostActiveCol.Key.Y * chunkSize);
450 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
451 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
457 /// Reload chunk bounds from chunk shards
459 /// <returns>The metadata.</returns>
460 private void Reload_Metadata()
462 var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
464 if (!shardsDir.Exists)
467 Logger.VerboseDebug("Could not open world map (shards) directory");
471 var shardFiles = shardsDir.GetFiles(chunkFile_filter);
473 if (shardFiles.Length > 0)
476 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
479 foreach (var shardFile in shardFiles)
482 if (shardFile.Length < 1024) continue;
483 var result = chunkShardRegex.Match(shardFile.Name);
484 if (!result.Success) continue;
486 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
487 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
491 using (var fileStream = shardFile.OpenRead())
494 PngReader pngRead = new PngReader(fileStream);
495 pngRead.ReadSkippingAllRows();
497 //Parse PNG chunks for METADATA in shard
498 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
499 var column = metadataFromPng.ChunkMetadata;
500 if (column.PrettyLocation == null)
501 column = column.Reload(ClientAPI);
502 chunkTopMetadata.Add(column);
506 catch (PngjException someEx)
508 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
511 catch (ProtoException protoEx)
513 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
519 //POI and EOI raw dump files ~ reload em!
520 //var poiRawFile = File.
521 string poiPath = Path.Combine(path, poiFileName);
522 string eoiPath = Path.Combine(path, eoiFileName);
524 if (File.Exists(poiPath))
526 using (var poiFile = File.OpenRead(poiPath))
528 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
529 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
533 if (File.Exists(eoiPath))
535 using (var eoiFile = File.OpenRead(eoiPath))
537 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
538 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
547 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
549 /// <param name="key">Chunk Coordinate</param>
550 /// <param name="mapChunk">Map chunk.</param>
551 /// <param name="chunkMeta">Chunk metadata</param>
552 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
554 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish...
558 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
561 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
563 for (; targetChunkY > 0; targetChunkY--)
565 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
567 if (worldChunk == null || worldChunk.BlockEntities == null)
570 Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
576 if (worldChunk.IsPacked())
578 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
579 worldChunk.Unpack( );//RESEARCH: Thread Unsafe?
582 /*************** Chunk Entities Scanning *********************/
583 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
586 Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
589 foreach (var blockEnt in worldChunk.BlockEntities)
591 if (blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
593 var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
594 designator.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
599 /********************* Chunk/Column BLOCKs scanning ****************/
600 //Heightmap, Stats, block tally
602 int X_index, Y_index, Z_index;
604 //First Chance fail-safe;
605 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
606 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
611 chunkMeta.ColumnPresense[targetChunkY] = true;
613 for (Y_index = 0; Y_index < chunkSize; Y_index++)
615 for (Z_index = 0; Z_index < chunkSize; Z_index++)
617 for (X_index = 0; X_index < chunkSize; X_index++)
619 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
621 //'Last' Chance fail-safe;
622 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
623 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
628 int aBlockId = worldChunk.Blocks[indicie];
630 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
631 chunkMeta.AirBlocks++;
635 if (RockIdCodes.ContainsKey(aBlockId)) {
636 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
637 chunkMeta.RockRatio[aBlockId]++;
639 chunkMeta.RockRatio.Add(aBlockId, 1);
642 chunkMeta.NonAirBlocks++;
644 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
645 //Heightmap - Need to ignore Grass & Snow
646 if (localHeight > chunkMeta.HeightMap[X_index, Z_index])
648 chunkMeta.HeightMap[X_index, Z_index] = localHeight;
649 if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
656 Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
659 private void UpdateEntityMetadata()
661 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
662 //Mabey scan only for 'new' entities by tracking ID in set?
663 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
667 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
670 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
671 if (dMatch.Value != null)
673 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.Pos.AsBlockPos.Copy(), loadedEntity.Value);
681 private void AddNote(string notation)
683 var playerNodePoi = new PointOfInterest()
686 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
688 Timestamp = DateTime.UtcNow,
691 this.POIs.AddReplace(playerNodePoi);
696 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
698 //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
700 CommandData cmdData = data as CommandData;
702 switch (cmdData.State)
704 case CommandType.Run:
705 case CommandType.Stop:
706 case CommandType.Snapshot:
707 if (CurrentState != cmdData.State)
709 CurrentState = cmdData.State;
710 AwakenCartographer(0.0f);
714 case CommandType.Notation:
715 //Add to POI list where player location
716 AddNote(cmdData.Notation);
720 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");