Snapshot for release 2026.10.13.1 (internal d2b5fb3)

This commit is contained in:
Tom Bohar 2026-10-13 14:25:49 -04:00
commit 319740ff5d
291 changed files with 58505 additions and 2107 deletions

View file

@ -5,6 +5,8 @@ namespace RynthCore.MonsterEditor;
[JsonSerializable(typeof(List<MonsterRule>))]
[JsonSerializable(typeof(EditorSettings))]
// UB damage-insights seed written for the RynthAi plugin (see UbMobSeedImport).
[JsonSerializable(typeof(RynthCore.CreatureSeed.UbMobSeedFile))]
// Case-insensitive like the plugin's RynthAiJsonContext, which reads the same files.
[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true, PropertyNameCaseInsensitive = true)]
internal partial class EditorJsonContext : JsonSerializerContext { }

View file

@ -169,14 +169,19 @@
</DataGridTemplateColumn>
<!-- Priority -->
<DataGridTemplateColumn Header="P" Width="32" MinWidth="30">
<DataGridTemplateColumn Width="40" MinWidth="36">
<DataGridTemplateColumn.Header>
<TextBlock Text="P" ToolTip.Tip="Priority: higher is fought first. 0 = IGNORE: never attacked, even if it attacks you, and it does not hold up nav, looting or buffs."/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate><DataTemplate>
<TextBlock Text="{Binding Priority}"
<TextBlock Text="{Binding PriorityText}"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
VerticalAlignment="Center"
ToolTip.Tip="Priority: higher is fought first. 0 = IGNORE: never attacked, even if it attacks you, and it does not hold up nav, looting or buffs."/>
</DataTemplate></DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate><DataTemplate>
<TextBox Text="{Binding Priority, Mode=TwoWay}" Padding="3,1"/>
<TextBox Text="{Binding Priority, Mode=TwoWay}" Padding="3,1"
ToolTip.Tip="Priority: higher is fought first. 0 = IGNORE: never attacked, even if it attacks you, and it does not hold up nav, looting or buffs."/>
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

View file

@ -21,6 +21,7 @@ public class MonsterRule : INotifyPropertyChanged
private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast, _useWall;
private string _exVuln = "None";
private int _offhandId;
private int _preferredAmmoItemId;
private string _petDamage = "PAuto";
public string Name { get => _name; set { _name = value; OnPropertyChanged(); } }
@ -32,7 +33,12 @@ public class MonsterRule : INotifyPropertyChanged
/// Empty = match by name only. Kept and editable here (before 2026-10-05 an editor save
/// dropped it, so expression rules fell back to name-only).</summary>
public string MatchExpression { get => _matchExpression; set { _matchExpression = value ?? ""; OnPropertyChanged(); } }
public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); } }
/// <summary>Target order: a higher Priority is fought first. 0 (or less) means IGNORE: RynthAi never targets the
/// monster, even one attacking the player, and does not wait on it.</summary>
public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); OnPropertyChanged(nameof(PriorityText)); } }
/// <summary>What the Priority column shows: the number, or "ign" for Priority 0 (ignore).</summary>
[JsonIgnore]
public string PriorityText => _priority <= 0 ? "ign" : _priority.ToString();
public string DamageType { get => _damageType; set { _damageType = value; OnPropertyChanged(); } }
public int WeaponId { get => _weaponId; set { _weaponId = value; OnPropertyChanged(); } }
public bool Fester { get => _fester; set { _fester = value; OnPropertyChanged(); } }
@ -49,6 +55,8 @@ public class MonsterRule : INotifyPropertyChanged
public bool UseWall { get => _useWall; set { _useWall = value; OnPropertyChanged(); } }
public string ExVuln { get => _exVuln; set { _exVuln = value; OnPropertyChanged(); } }
public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } }
/// <summary>Optional loose ammo stack id for missile combat while this rule matches (0 = auto).</summary>
public int PreferredAmmoItemId { get => _preferredAmmoItemId; set { _preferredAmmoItemId = value; OnPropertyChanged(); } }
public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } }
/// <summary>Every field in the file this class doesn't know (e.g. the plugin's CustomDebuffs,
@ -57,8 +65,65 @@ public class MonsterRule : INotifyPropertyChanged
public Dictionary<string, JsonElement>? ExtraFields { get; set; }
[JsonIgnore]
/// <summary>True for the special row named "Default" — the catch-all when no other rule matches.</summary>
public bool IsDefault => string.Equals(_name, "Default", System.StringComparison.OrdinalIgnoreCase);
/// <summary>Full copy (for import merge). Copies every rule field, UseBlast included.</summary>
public MonsterRule Clone()
{
return new MonsterRule
{
Name = _name,
Category = _category,
MatchExpression = _matchExpression,
Priority = _priority,
DamageType = _damageType,
WeaponId = _weaponId,
Fester = _fester,
Broadside = _broadside,
GravityWell = _gravityWell,
Imperil = _imperil,
Yield = _yield,
Vuln = _vuln,
UseArc = _useArc,
UseBolt = _useBolt,
UseRing = _useRing,
UseStreak = _useStreak,
UseBlast = _useBlast,
ExVuln = _exVuln,
OffhandId = _offhandId,
PreferredAmmoItemId = _preferredAmmoItemId,
PetDamage = _petDamage,
};
}
/// <summary>Overwrites combat fields (used to merge a VT Default row into the Rynth Default row).</summary>
public void CopyCombatSettingsFrom(MonsterRule? src)
{
if (src == null) return;
// Keep Name: must stay "Default". Use public setters so the grid updates.
Category = src.Category;
MatchExpression = src.MatchExpression;
Priority = src.Priority;
DamageType = src.DamageType;
WeaponId = src.WeaponId;
Fester = src.Fester;
Broadside = src.Broadside;
GravityWell = src.GravityWell;
Imperil = src.Imperil;
Yield = src.Yield;
Vuln = src.Vuln;
UseArc = src.UseArc;
UseBolt = src.UseBolt;
UseRing = src.UseRing;
UseStreak = src.UseStreak;
UseBlast = src.UseBlast;
ExVuln = src.ExVuln;
OffhandId = src.OffhandId;
PreferredAmmoItemId = src.PreferredAmmoItemId;
PetDamage = src.PetDamage;
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? name = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

View file

@ -16,6 +16,18 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Controls.DataGrid" Version="11.2.3" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.0" />
<!-- Reads UtilityBelt's mob_damage_insights.ldb (same LiteDB version UB writes with). -->
<PackageReference Include="LiteDB" Version="5.0.21" />
<!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>
<!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). -->
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- UB damage-insights seed schema, shared with the RynthAi plugin. -->
<Compile Include="..\..\Shared\UbMobSeed.cs" Link="Shared\UbMobSeed.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,318 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using LiteDB;
using RynthCore.CreatureSeed;
// LiteDB ships its own JsonSerializer; the seed is written with System.Text.Json (source-generated).
using StjSerializer = System.Text.Json.JsonSerializer;
namespace RynthCore.MonsterEditor;
/// <summary>
/// Converts UtilityBelt's <c>mob_damage_insights.ldb</c> (LiteDB 5) into the RynthAi
/// damage-type seed (<see cref="UbMobSeedFile"/>). Runs here rather than in the plugin
/// because LiteDB is reflection-heavy and the RynthAi plugin is NativeAOT.
/// <para>
/// UB rows record damage players dealt TO each monster, per damage type. The
/// per-character databases are pushed into the shared server database every 12 hours,
/// so they are mostly a subset of it: for each monster the single row with the most hits
/// wins (summing would double-count).
/// </para>
/// </summary>
internal static class UbMobSeedImport
{
/// <summary>Hits a damage type needs before it is ranked.</summary>
public const int DefaultMinHitsPerType = 20;
private const string DbFileName = "mob_damage_insights.ldb";
private const string WcidCollection = "mob_damage_agg";
private const string MagCollection = "mob_mag_name_agg";
/// <summary>UB damage-type flags (ACE <c>DamageType</c>) mapped to RynthAi element names.
/// Normal (0) and combined flags are not castable choices and are skipped.</summary>
private static readonly Dictionary<string, string> FlagToElement = new()
{
["1"] = "Slash",
["2"] = "Pierce",
["4"] = "Bludgeon",
["8"] = "Cold",
["16"] = "Fire",
["32"] = "Acid",
["64"] = "Lightning",
["1024"] = "Nether",
};
/// <summary>Outcome of an import run.</summary>
public sealed record Result(bool Ok, string Message, UbMobSeedFile? Seed);
/// <summary>UB's per-world folder for InfiniteLeaftide (holds the shared server database).</summary>
public static string DefaultServerFolder => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"Decal Plugins", "UtilityBelt", "InfiniteLeaftide");
/// <summary>Where the plugin reads the seed: <c>&lt;SuiteDir&gt;\RynthAi\CreatureData\ub-mob-seed.json</c>.</summary>
public static string DefaultOutputPath => Path.Combine(
RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData", UbMobSeedFile.FileName);
/// <summary>
/// Lists the shared server database (first) and every per-character database
/// one level below it.
/// </summary>
public static List<string> FindDatabases(string serverFolder)
{
var list = new List<string>();
if (!Directory.Exists(serverFolder)) return list;
string shared = Path.Combine(serverFolder, DbFileName);
if (File.Exists(shared)) list.Add(shared);
foreach (string dir in Directory.GetDirectories(serverFolder).OrderBy(d => d, StringComparer.OrdinalIgnoreCase))
{
string perChar = Path.Combine(dir, DbFileName);
if (File.Exists(perChar)) list.Add(perChar);
}
return list;
}
/// <summary>
/// Reads every database under <paramref name="serverFolder"/>, ranks damage types per
/// monster and writes the seed to <paramref name="outputPath"/> atomically.
/// </summary>
public static Result Run(string serverFolder, string outputPath, int minHitsPerType = DefaultMinHitsPerType)
{
List<string> dbs = FindDatabases(serverFolder);
if (dbs.Count == 0)
return new Result(false, $"No {DbFileName} found in {serverFolder}.", null);
// Best row per wcid / per normalized Mag-Tools name, across all sources.
var bestWcid = new Dictionary<uint, BsonDocument>();
var bestMag = new Dictionary<string, BsonDocument>(StringComparer.OrdinalIgnoreCase);
var used = new List<string>();
var errors = new List<string>();
foreach (string db in dbs)
{
try
{
ReadDatabase(db, bestWcid, bestMag);
used.Add(db);
}
catch (Exception ex)
{
errors.Add($"{Path.GetFileName(Path.GetDirectoryName(db))}: {ex.Message}");
}
}
if (used.Count == 0)
return new Result(false, "Could not read any UB database: " + string.Join("; ", errors), null);
var seed = new UbMobSeedFile
{
GeneratedUtc = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture),
MinHitsPerType = minHitsPerType,
Sources = used,
World = MostCommonWorld(bestWcid.Values),
};
// Live UB rows keyed by wcid.
var wcidNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var (wcid, doc) in bestWcid.OrderBy(kv => kv.Key))
{
string name = Str(doc, "LastSeenName");
if (name.Length > 0) wcidNames.Add(name);
var elements = RankElements(doc, minHitsPerType, hasPeaks: true);
if (elements.Count < 2) continue; // one type alone says nothing about weakness
seed.Entries.Add(new UbMobSeedEntry
{
Wcid = wcid,
Name = name,
Source = "ub",
TotalHits = Num(doc, "TotalHits"),
Elements = elements,
});
}
// Mag-Tools name-only rows, skipped when a wcid row already covers the name.
foreach (var doc in bestMag.Values)
{
string name = Str(doc, "LastSeenDisplayName");
if (name.Length == 0) name = Str(doc, "NormalizedMobName");
if (name.Length == 0 || wcidNames.Contains(name)) continue;
var elements = RankElements(doc, minHitsPerType, hasPeaks: false);
if (elements.Count < 2) continue;
seed.Entries.Add(new UbMobSeedEntry
{
Wcid = 0,
Name = name,
Source = "magtools",
TotalHits = elements.Sum(e => (long)e.Hits),
Elements = elements,
});
}
WriteAtomic(outputPath, StjSerializer.Serialize(seed, EditorJsonContext.Default.UbMobSeedFile));
int ub = seed.Entries.Count(e => e.Source == "ub");
int mag = seed.Entries.Count - ub;
string msg = $"UB seed written: {ub} monster(s) by wcid + {mag} by name (Mag-Tools) from {used.Count} database(s) → {outputPath}";
if (errors.Count > 0) msg += $" Skipped: {string.Join("; ", errors)}";
return new Result(true, msg, seed);
}
/// <summary>
/// Opens a snapshot copy of <paramref name="dbPath"/> (UB may have the live file open)
/// and folds its rows into the best-row maps.
/// </summary>
private static void ReadDatabase(string dbPath, Dictionary<uint, BsonDocument> bestWcid,
Dictionary<string, BsonDocument> bestMag)
{
string tempDir = Path.Combine(Path.GetTempPath(), "RynthUbSeed-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
string copy = Path.Combine(tempDir, DbFileName);
CopyShared(dbPath, copy);
// LiteDB 5 keeps uncommitted pages in "<name>-log.ldb"; copy it so recent hits are included.
string log = Path.Combine(Path.GetDirectoryName(dbPath)!, Path.GetFileNameWithoutExtension(dbPath) + "-log.ldb");
if (File.Exists(log))
CopyShared(log, Path.Combine(tempDir, Path.GetFileNameWithoutExtension(DbFileName) + "-log.ldb"));
// Writable connection on the private copy so LiteDB can replay the log; the original is untouched.
using var db = new LiteDatabase(new ConnectionString { Filename = copy, Connection = ConnectionType.Direct });
if (db.CollectionExists(WcidCollection))
{
foreach (var doc in db.GetCollection(WcidCollection).FindAll())
{
long wcid = Num(doc, "Wcid");
// wcid 1 is the player weenie (self/PvP lines), not a monster.
if (wcid <= 1 || wcid > uint.MaxValue) continue;
KeepBest(bestWcid, (uint)wcid, doc, Num(doc, "TotalHits"));
}
}
if (db.CollectionExists(MagCollection))
{
foreach (var doc in db.GetCollection(MagCollection).FindAll())
{
string key = Str(doc, "NormalizedMobName");
if (key.Length == 0) continue;
KeepBest(bestMag, key, doc, SumValues(doc, "HitsByType"));
}
}
}
finally
{
try { Directory.Delete(tempDir, recursive: true); } catch { /* temp cleanup is best-effort */ }
}
}
/// <summary>Keeps the row with the most hits per key (sources overlap; see class remarks).</summary>
private static void KeepBest<TKey>(Dictionary<TKey, BsonDocument> map, TKey key, BsonDocument doc, long hits)
where TKey : notnull
{
if (!map.TryGetValue(key, out var existing) || hits > HitsOf(existing))
map[key] = doc;
}
/// <summary>Total hits of a row in either collection's shape.</summary>
private static long HitsOf(BsonDocument doc)
{
long total = Num(doc, "TotalHits");
return total > 0 ? total : SumValues(doc, "HitsByType");
}
/// <summary>
/// Ranks the castable damage types with at least <paramref name="minHits"/> hits.
/// Score blends average damage (vs the best average) with UB's own effectiveness
/// measure, peak hit vs the best peak, when peaks are recorded.
/// </summary>
private static List<UbMobSeedElement> RankElements(BsonDocument doc, int minHits, bool hasPeaks)
{
var hits = Doc(doc, "HitsByType");
var sums = Doc(doc, "SumDamageByType");
var peaks = hasPeaks ? Doc(doc, "MaxDamageByType") : null;
if (hits == null || sums == null) return new List<UbMobSeedElement>();
var list = new List<UbMobSeedElement>();
foreach (string flag in hits.Keys)
{
if (!FlagToElement.TryGetValue(flag, out string? element)) continue;
int n = (int)Math.Min(int.MaxValue, Num(hits, flag));
if (n < minHits || !sums.ContainsKey(flag)) continue;
list.Add(new UbMobSeedElement
{
Element = element,
Hits = n,
AvgDamage = Math.Round(Num(sums, flag) / (double)n, 2),
MaxHit = peaks != null && peaks.ContainsKey(flag) ? Num(peaks, flag) : 0,
});
}
if (list.Count == 0) return list;
double bestAvg = list.Max(e => e.AvgDamage);
long bestPeak = list.Max(e => e.MaxHit);
foreach (var e in list)
{
double avgRatio = bestAvg > 0 ? e.AvgDamage / bestAvg : 0;
double score = bestPeak > 0
? 0.5 * avgRatio + 0.5 * (e.MaxHit / (double)bestPeak)
: avgRatio;
e.Score = Math.Round(score, 4);
}
return list.OrderByDescending(e => e.Score).ThenByDescending(e => e.Hits).ToList();
}
/// <summary>Most frequent <c>WorldName</c> among the rows (empty when none recorded).</summary>
private static string MostCommonWorld(IEnumerable<BsonDocument> rows) =>
rows.Select(r => Str(r, "WorldName"))
.Where(w => w.Length > 0)
.GroupBy(w => w, StringComparer.OrdinalIgnoreCase)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.FirstOrDefault() ?? string.Empty;
/// <summary>Copies a file another process may hold open for writing.</summary>
private static void CopyShared(string source, string dest)
{
using var src = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var dst = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None);
src.CopyTo(dst);
}
/// <summary>Writes via a temp file so the plugin never reads a half-written seed.</summary>
private static void WriteAtomic(string path, string contents)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, contents);
File.Move(tmp, path, overwrite: true);
}
// ── BSON helpers (schema-tolerant: UB may store numbers as Int32, Int64 or Double) ──
private static BsonDocument? Doc(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsDocument ? v.AsDocument : null;
private static string Str(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsString ? v.AsString.Trim() : string.Empty;
private static long Num(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsNumber ? Convert.ToInt64(v.RawValue, CultureInfo.InvariantCulture) : 0;
private static long SumValues(BsonDocument doc, string field)
{
var d = Doc(doc, field);
if (d == null) return 0;
long total = 0;
foreach (string k in d.Keys) total += Num(d, k);
return total;
}
}

View file

@ -0,0 +1,548 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Data.Sqlite;
namespace RynthCore.MonsterEditor;
/// <summary>
/// Best-effort import of VirindiTank "user" macro profiles (typically <c>.usd</c>) into RynthAi
/// <see cref="MonsterRule"/> rows. Tries, in order: (1) line-oriented SCF <c>MyMonsters</c> (classic
/// uTank2 <c>*.usd</c> in <c>VirindiPlugins\VirindiTank</c>); (2) SQLite; (3) binary scan for
/// vTank-style match expressions.
/// </summary>
public static class VirindiTankUsdImport
{
public sealed class Result
{
public bool Ok { get; set; }
public List<MonsterRule> Rules { get; } = new();
/// <summary>Human-readable summary: counts, method used, warnings.</summary>
public string Message { get; set; } = string.Empty;
}
public static Result TryImport(string filePath)
{
var r = new Result();
if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
{
r.Message = "File not found.";
return r;
}
string? allText;
try
{
// VT text profiles are UTF-8; invalid sequences become replacement chars, still OK for SCF.
allText = File.ReadAllText(filePath, Encoding.UTF8);
}
catch (Exception ex)
{
r.Message = $"Read failed: {ex.Message}";
return r;
}
// Primary path: SCF <c>MyMonsters</c> block (see VirindiPlugins\VirindiTank\*.usd, format 8+).
if (VirindiTankUsdTextScfParser.TryParseMyMonsters(allText, r.Rules, out string? scfNote) && r.Rules.Count > 0)
{
r.Ok = true;
r.Message = BuildMessage("MyMonsters (VT SCF / line format)", r.Rules.Count, scfNote);
return r;
}
r.Rules.Clear();
byte[] bytes;
try
{
bytes = File.ReadAllBytes(filePath);
}
catch (Exception ex2)
{
r.Message = $"Read as bytes failed: {ex2.Message}";
return r;
}
if (IsSqliteDatabase(bytes))
{
try
{
if (TryImportFromSqlite(filePath, r.Rules, out int count, out string? sqlNote))
{
r.Ok = true;
r.Message = BuildMessage("SQLite (Virindi uTank settings database)", count, sqlNote);
return r;
}
}
catch (Exception ex)
{
const string pfx = "SQLite read error: ";
string errMsg = pfx + ex.Message;
if (TryImportFromStringScan(bytes, r.Rules, out int exprCount, out string? scanNote))
{
r.Ok = exprCount > 0;
r.Message = BuildMessage("Text scan (after SQLite exception)", exprCount, errMsg + " " + scanNote);
}
else
r.Message = errMsg;
return r;
}
}
string? fallNote;
if (TryImportFromStringScan(bytes, r.Rules, out int n, out fallNote))
{
r.Ok = n > 0;
r.Message = n > 0
? BuildMessage("Expression scan (non-SQLite or unreadable table)", n, fallNote)
: "Could not import: no vTank-style match expressions in file. " + (fallNote ?? string.Empty) +
" If this is a Virindi Tank user profile, ensure the file is a .usd from your VirindiPlugins\\VirindiTank folder (SQLite based).";
}
else
{
r.Message = fallNote ?? "Import failed.";
}
return r;
}
private static string BuildMessage(string method, int count, string? extra)
{
var sb = new StringBuilder();
sb.Append(CultureInfo.InvariantCulture, $"Imported {count} rule(s) using {method}.");
if (!string.IsNullOrWhiteSpace(extra))
{
sb.Append(' ');
sb.Append(extra);
}
return sb.ToString();
}
private static bool IsSqliteDatabase(byte[] header)
{
const string sig = "SQLite format 3\0";
if (header.Length < sig.Length) return false;
for (int i = 0; i < sig.Length; i++)
{
if (header[i] != sig[i]) return false;
}
return true;
}
private static bool TryImportFromSqlite(string filePath, List<MonsterRule> outList, out int count, out string? note)
{
count = 0;
note = null;
outList.Clear();
var csb = new SqliteConnectionStringBuilder
{
DataSource = filePath,
Mode = SqliteOpenMode.ReadOnly,
};
using var con = new SqliteConnection(csb.ToString());
con.Open();
// Discover tables and their columns; pick the best "monster list" table.
var tableScores = new List<(string name, int score)>();
using (var listCmd = con.CreateCommand())
{
listCmd.CommandText = "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
using var r = listCmd.ExecuteReader();
while (r.Read())
{
string t = r.GetString(0);
if (!IsSafeTableName(t)) continue;
int s = ScoreTableIntent(con, t);
if (s > 0) tableScores.Add((t, s));
}
}
if (tableScores.Count == 0)
{
// Unknown schema — try every user table; ReadMonsterTable skips unsuitable ones.
using (var listCmd2 = con.CreateCommand())
{
listCmd2.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
using var r2 = listCmd2.ExecuteReader();
while (r2.Read())
{
string t = r2.GetString(0);
if (IsSafeTableName(t)) tableScores.Add((t, 1));
}
}
}
if (tableScores.Count == 0)
{
note = "No user tables in SQLite file.";
return false;
}
tableScores.Sort((a, b) => b.score.CompareTo(a.score));
var best = tableScores[0].name;
if (!ReadMonsterTable(con, best, outList, out int readCount, out string? readErr))
{
note = readErr;
return false;
}
count = readCount;
note = $"Table \"{best}\" (score {tableScores[0].score}). {readErr ?? string.Empty}".Trim();
return count > 0;
}
private static bool IsSafeTableName(string t)
{
foreach (char c in t)
{
if (char.IsLetterOrDigit(c) || c is '_' or '-') continue;
return false;
}
return t.Length is > 0 and < 200;
}
private static int ScoreTableIntent(SqliteConnection con, string table)
{
int s = 0;
if (table.IndexOf("monster", StringComparison.OrdinalIgnoreCase) >= 0) s += 15;
if (table.IndexOf("mob", StringComparison.OrdinalIgnoreCase) >= 0) s += 8;
if (table.IndexOf("attack", StringComparison.OrdinalIgnoreCase) >= 0) s += 4;
using var c = con.CreateCommand();
c.CommandText = $"PRAGMA table_info(\"{table}\")";
using var r = c.ExecuteReader();
while (r.Read())
{
string col = r.GetString(1);
s += ColumnScore(col);
}
return s;
}
private static int ColumnScore(string col)
{
string c = col.ToLowerInvariant();
if (c.Contains("fester", StringComparison.Ordinal) || c is "f") return 4;
if (c.Contains("broad", StringComparison.Ordinal) || c is "b" or "broadside") return 4;
if (c.Contains("gravity", StringComparison.Ordinal) || c is "g") return 2;
if (c.Contains("imperil", StringComparison.Ordinal) || c is "i") return 2;
if (c.Contains("yield", StringComparison.Ordinal) || c is "y") return 2;
if (c.Contains("vuln", StringComparison.Ordinal) && c.Contains("ex", StringComparison.Ordinal) == false) return 2;
if (c is "v") return 2;
if (c.Contains("expression", StringComparison.Ordinal) || c is "matchexpr" or "matchexpression" or "match" or "expr" or "e")
return 8;
if (c is "name" or "mname" or "monstername" or "n")
return 6;
if (c.Contains("damag", StringComparison.Ordinal) || c.Contains("element", StringComparison.Ordinal) || c is "dmg" or "dt")
return 4;
if (c.Contains("priority", StringComparison.Ordinal) || c is "p" or "pri" or "sort" or "idx" or "ordinal")
return 2;
if (c.Contains("weapon", StringComparison.Ordinal) || c.Contains("wand", StringComparison.Ordinal)) return 2;
if (c is "a" or "r" or "s" or "w" or "u") return 1; // A/R/S are ambiguous; low weight
return 0;
}
private static bool ReadMonsterTable(SqliteConnection con, string table, List<MonsterRule> outList, out int count, out string? err)
{
count = 0;
err = null;
// Prefer stable ordering when a dedicated column exists (ROWID is the SQLite insert order for many VT exports).
string orderBy = "ROWID";
if (TableHasColumn(con, table, "Order")) orderBy = "CAST([Order] AS INTEGER)";
else if (TableHasColumn(con, table, "SortIndex")) orderBy = "SortIndex";
else if (TableHasColumn(con, table, "Index")) orderBy = "[Index]";
using var cmd = con.CreateCommand();
cmd.CommandText = $"SELECT * FROM \"{table}\" ORDER BY {orderBy} ASC";
using var r = cmd.ExecuteReader();
int ordName = FindOrdinalByHints(r, "name", "monstername", "mname", "entry", "n", "text0");
int ordExpr = FindOrdinalByHints(r, "matchexpression", "match", "expression", "expr", "e", "ed");
if (ordExpr < 0) ordExpr = FindExpressionColumn(r);
int ordDmg = FindOrdinalByHints(r, "damagetype", "element", "dmg", "de", "delement");
int ordPri = FindOrdinalByHints(r, "priority", "p", "pri", "importance", "ipriority");
int ordEx = FindOrdinalByHints(r, "exvuln", "exvul", "extravuln", "vulnextra");
int ordWep = FindOrdinalByHints(r, "weaponid", "weapon", "windex", "weaponindex");
int ordOff = FindOrdinalByHints(r, "offhand", "offhandid", "shield");
int ordF = FindOrdinalByHints(r, "fester", "f", "b_fester", "bisfester", "festerb");
int ordB = FindOrdinalByHints(r, "broadside", "b", "broad", "broadb");
int ordG = FindOrdinalByHints(r, "gravity", "g", "grav");
int ordI = FindOrdinalByHints(r, "imperil", "i", "imprl");
int ordY = FindOrdinalByHints(r, "yield", "y", "yld");
int ordV = FindOrdinalByHints(r, "vulnerability", "v", "vuln", "b_vuln", "bisfestervuln", "bisfesterv"); // be careful: skip ex vuln
// VT often: UseArc, UseRing, Streak, Bolt
int ordA = FindOrdinalByHints(r, "usearc", "arc", "a");
int ordR = FindOrdinalByHints(r, "usering", "ring", "r", "b_ring");
int ordS = FindOrdinalByHints(r, "streak", "s", "usestreak", "b_streak", "bisfeststreak", "bisfstreak", "bisfstreak2");
int ordBl= FindOrdinalByHints(r, "usebolt", "bolt", "bl", "b_bolt", "bisfstreakbolt", "bisfstreakbol", "bisfb");
if (ordName < 0 && ordExpr < 0)
{
err = "Table has no recognizable name/expression column.";
return false;
}
while (r.Read())
{
var m = new MonsterRule();
string? name = GetStr(r, ordName);
string? expr = GetStr(r, ordExpr);
if (!string.IsNullOrWhiteSpace(name) && name.Trim().Equals("default", StringComparison.OrdinalIgnoreCase))
{
m.Name = "Default";
m.MatchExpression = string.Empty;
}
else
{
m.Name = name?.Trim() ?? string.Empty;
m.MatchExpression = expr?.Trim() ?? string.Empty;
}
m.Priority = 1;
if (ordPri >= 0) m.Priority = Math.Clamp(ToInt32(r, ordPri, 1), -100, 10000);
m.DamageType = string.IsNullOrEmpty(GetStr(r, ordDmg)) ? "Auto" : MapDamageType(GetStr(r, ordDmg) ?? "Auto");
m.ExVuln = string.IsNullOrEmpty(GetStr(r, ordEx)) ? "None" : (GetStr(r, ordEx) ?? "None");
m.WeaponId = ordWep >= 0 ? Math.Max(0, ToInt32(r, ordWep, 0)) : 0;
m.OffhandId = ordOff >= 0 ? Math.Max(0, ToInt32(r, ordOff, 0)) : 0;
m.Fester = GetBoolish(r, ordF);
m.Broadside = GetBoolish(r, ordB);
m.GravityWell= GetBoolish(r, ordG);
m.Imperil = GetBoolish(r, ordI);
m.Yield = GetBoolish(r, ordY);
m.Vuln = GetBoolish(r, ordV);
m.UseArc = GetBoolish(r, ordA);
m.UseRing = GetBoolish(r, ordR);
m.UseStreak = GetBoolish(r, ordS);
m.UseBolt = ordBl >= 0 ? GetBoolish(r, ordBl) : m.UseBolt;
// If row is empty, skip
if (string.IsNullOrEmpty(m.Name) && string.IsNullOrEmpty(m.MatchExpression))
{
bool anyToggle = m.Fester || m.Broadside || m.GravityWell || m.Imperil || m.Yield || m.Vuln
|| m.UseArc || m.UseRing || m.UseStreak;
if (!anyToggle) continue;
}
if (m.Name.Length == 0 && m.MatchExpression.Length == 0)
continue;
outList.Add(m);
}
count = outList.Count;
if (count == 0) err = "No mappable rows.";
return true;
}
private static bool TableHasColumn(SqliteConnection con, string table, string col)
{
using var c = con.CreateCommand();
c.CommandText = $"PRAGMA table_info(\"{table}\")";
using var r = c.ExecuteReader();
while (r.Read())
{
if (r.GetString(1).Equals(col, StringComparison.OrdinalIgnoreCase)) return true;
}
return false;
}
/// <summary>Column whose name is exactly <paramref name="hints"/> (lowercase) or a short exact code (P, V, etc.).</summary>
private static int FindOrdinalByHints(SqliteDataReader r, params string[] hints)
{
for (int i = 0; i < r.FieldCount; i++)
{
string n = r.GetName(i);
string nl = n.ToLowerInvariant();
foreach (string h in hints)
{
if (h.Equals("p", StringComparison.Ordinal) && nl is "p" or "ipriority")
return i;
if (h.Equals("v", StringComparison.Ordinal) && (nl is "v" or "b_v" or "b_vuln" or "vuln")
&& !nl.Contains("exvul", StringComparison.Ordinal) && !nl.Contains("ex_vul", StringComparison.Ordinal))
return i;
if (nl == h.ToLowerInvariant()) return i;
}
}
return -1;
}
private static int FindExpressionColumn(SqliteDataReader r)
{
for (int i = 0; i < r.FieldCount; i++)
{
string nl = r.GetName(i).ToLowerInvariant();
if (nl.Contains("matchexpr", StringComparison.Ordinal)
|| (nl.Contains("match", StringComparison.Ordinal) && nl.Contains("exp", StringComparison.Ordinal)))
return i;
}
return -1;
}
private static string? GetStr(SqliteDataReader r, int ord) => ord < 0 || r.IsDBNull(ord) ? null : r.GetValue(ord)?.ToString();
private static int ToInt32(SqliteDataReader r, int ord, int dft)
{
try
{
if (r.IsDBNull(ord)) return dft;
return Convert.ToInt32(r.GetValue(ord), CultureInfo.InvariantCulture);
}
catch
{
if (int.TryParse(r.GetValue(ord)?.ToString(), out int p)) return p;
return dft;
}
}
private static bool GetBoolish(SqliteDataReader r, int ord)
{
if (ord < 0 || r.IsDBNull(ord)) return false;
var v = r.GetValue(ord);
if (v is long l) return l != 0;
if (v is int i) return i != 0;
if (v is bool b) return b;
string? s = v?.ToString()?.Trim();
if (string.IsNullOrEmpty(s)) return false;
if (s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1" || s.Equals("yes", StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
private static string MapDamageType(string raw)
{
string t = raw.Trim();
if (t.Length == 0) return "Auto";
if (t.Contains('<', StringComparison.Ordinal) && t.Contains('>', StringComparison.Ordinal)) // <auto>
{
if (t.Contains("auto", StringComparison.OrdinalIgnoreCase)) return "Auto";
}
// VT uses words like "Slash" — normalize first letter
if (t.Equals("Auto", StringComparison.OrdinalIgnoreCase)) return "Auto";
foreach (string s in new[] { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" })
{
if (s.Equals(t, StringComparison.OrdinalIgnoreCase)) return s;
}
// Unknown — keep for display, Rynth will treat oddly if not in list; still better than Data loss
return t;
}
// ── Binary / UTF-16 / UTF-8 string scan: expression fallbacks ────────────
private static bool TryImportFromStringScan(byte[] data, List<MonsterRule> outList, out int count, out string? note)
{
count = 0;
note = null;
outList.Clear();
var strs = new HashSet<string>(StringComparer.Ordinal);
foreach (string s in ExtractAllStrings(data, minLen: 8, maxLen: 480))
{
if (LooksLikeVtExpression(s))
strs.Add(s.Trim());
}
if (strs.Count == 0)
{
count = 0;
return false;
}
// Prefer longer expressions (often more specific)
foreach (string s in strs.OrderByDescending(x => x.Length))
{
outList.Add(new MonsterRule
{
Name = string.Empty,
MatchExpression = s,
DamageType = "Auto",
UseBolt = true,
});
}
count = outList.Count;
note = "Binary mode only recovers vTank **match expression** rows (name-only entries must be added by hand, or re-export from a SQLite .usd).";
return true;
}
/// <summary>Pull printable ASCII/UTF-8 (single-byte) and UTF-16-LE "wide string" runs from a blob.</summary>
private static IEnumerable<string> ExtractAllStrings(byte[] data, int minLen, int maxLen)
{
// 7-bit runs (covers most human-readable .usd contents outside SQLite BLOBs)
int start = -1;
for (int i = 0; i < data.Length; i++)
{
byte b = data[i];
if ((b >= 0x20 && b <= 0x7E) || b == 0x09) // printables + tab
{
if (start < 0) start = i;
}
else
{
if (start >= 0)
{
int len = i - start;
if (len >= minLen)
yield return Encoding.UTF8.GetString(data, start, len > maxLen ? maxLen : len);
}
start = -1;
}
}
if (start >= 0)
{
int len2 = data.Length - start;
if (len2 >= minLen)
yield return Encoding.UTF8.GetString(data, start, len2 > maxLen ? maxLen : len2);
}
// UTF-16-LE ASCII: [char][0][char][0] (common in Windows/.NET-originated data)
for (int i = 0; i < data.Length - 1;)
{
if (data[i + 1] != 0) { i++; continue; }
if (data[i] < 0x20) { i++; continue; }
{
char ch = (char)data[i];
if (!char.IsLetter(ch) && !char.IsDigit(ch) && ch is not ( '<' or '=' or '(' or '!' or 'f' or 't')) { i++; continue; }
}
int p = i;
var sb = new StringBuilder();
while (p + 1 < data.Length)
{
if (data[p + 1] != 0) break;
int c = data[p];
if (c < 0x20) break;
if (c > 0x7E) break;
sb.Append((char)c);
p += 2;
if (sb.Length >= maxLen) break;
}
if (sb.Length >= minLen) yield return sb.ToString();
if (p > i) { i = p; }
else { i++; }
}
}
private static bool LooksLikeVtExpression(string s)
{
s = s.Trim();
if (s.Length < 6) return false;
if (s.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) return false;
if (s.Contains("SQLite format", StringComparison.Ordinal)) return false;
if (s.Contains("&&", StringComparison.Ordinal) || s.Contains("||", StringComparison.Ordinal)) return true;
if (s.Contains("==", StringComparison.Ordinal) && (
s.Contains("range", StringComparison.Ordinal)
|| s.Contains("species", StringComparison.Ordinal)
|| s.Contains("typeid", StringComparison.Ordinal)
|| s.Contains("name", StringComparison.Ordinal)
|| s.Contains("maxhp", StringComparison.Ordinal)
|| s.Contains("hasshield", StringComparison.Ordinal)
|| s.Contains("metastate", StringComparison.Ordinal)))
return true;
// e.g. range>5 && !foo
if (Regex.IsMatch(s, @"(?i)range\s*[<>=!]+")) return true;
return false;
}
}

View file

@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace RynthCore.MonsterEditor;
// In-game VirindiTank import uses the same MyMonsters layout in Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankUsdMyMonstersScfParser.cs — keep in sync.
/// <summary>
/// Line-oriented uTank2 SCF <c>.usd</c> (e.g. format 8) — the common format under
/// <c>C:\Games\VirindiPlugins\VirindiTank\*.usd</c>, with a <c>MyMonsters</c> table using <c>s</c>/<c>i</c>/<c>b</c> value lines.
/// Reference: <c>--Silentkelpie_InfiniteLeaftide.usd</c> (MyMonsters 21 columns, 110+ rows in sample file).
/// </summary>
public static class VirindiTankUsdTextScfParser
{
public static bool TryParseMyMonsters(string allText, List<MonsterRule> outList, out string? note)
{
outList.Clear();
note = null;
if (string.IsNullOrWhiteSpace(allText) || allText.IndexOf("MyMonsters", StringComparison.Ordinal) < 0)
return false;
string[] L = allText
.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)
.Select(s => s.Trim())
.ToArray();
if (L.Length < 8) { note = "File too short."; return false; }
int idx = 0;
for (; idx < L.Length; idx++) if (L[idx] == "MyMonsters") break;
if (idx >= L.Length) { note = "MyMonsters not found."; return false; }
idx++;
if (!int.TryParse(L[idx], out int colCount) || colCount < 1) { note = "MyMonsters: bad column count."; return false; }
idx += 1 + colCount * 2; // names + y/n
if (idx >= L.Length) { note = "MyMonsters: truncated after header."; return false; }
if (!int.TryParse(L[idx], out int rowCount) || rowCount < 0) { note = "MyMonsters: bad row count."; return false; }
idx++;
// Empty table: treat as "no data" so the importer can fall back to SQLite / byte scan.
if (rowCount == 0) { note = "MyMonsters has no rows."; return false; }
if (colCount < 4 + 3) { note = "MyMonsters: column count too small."; return false; }
int nBool = colCount - 4 - 3;
for (int r = 0; r < rowCount; r++)
{
if (idx + 1 >= L.Length) { note = $"No data for row {r + 1} (early EOF)."; return outList.Count > 0; }
if (!T(L, "s", ref idx)) { note = RowErr(r, "s"); return outList.Count > 0; }
if (!ValStr(L, ref idx, out string raw)) { note = RowErr(r, "name"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i ap"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int ap, out int err) || err != 0) { note = RowErr(r, "ap int"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i dt"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int vtDmg, out err) || err != 0) { note = RowErr(r, "dt int"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i wep"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int wep, out err) || err != 0) { note = RowErr(r, "wep int"); return outList.Count > 0; }
if (nBool < 14) { note = "Expected at least 14 bool columns in mob row."; return outList.Count > 0; }
if (nBool < 1) { note = "nBool<1."; return false; }
var b = new bool[nBool];
for (int k = 0; k < nBool; k++)
{
if (!T(L, "b", ref idx) || !ValBool(L, ref idx, out b[k])) { note = RowErr(r, $"b{k}"); return outList.Count > 0; }
}
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int sev, out err) || err != 0) { note = RowErr(r, "sec vuln int"); return outList.Count > 0; }
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int ofh, out err) || err != 0) { note = RowErr(r, "offh int"); return outList.Count > 0; }
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int pet, out err) || err != 0) { note = RowErr(r, "pet int"); return outList.Count > 0; }
outList.Add(MakeRule(raw, ap, vtDmg, wep, b, sev, ofh, pet));
}
if (outList.Count == 0) { note = "No rows were parsed from MyMonsters."; return false; }
return true;
}
private static string RowErr(int r, string what) => $"MyMonsters row {r + 1} ({what}).";
private static bool T(string[] L, string t, ref int i)
{
if (i >= L.Length || L[i] != t) return false;
i++;
return true;
}
private static bool ValStr(string[] L, ref int i, out string s)
{
s = "";
if (i >= L.Length) return false;
s = L[i++]; return true;
}
private static bool ValInt(string[] L, ref int i, out int v, out int err)
{
err = 0;
v = 0;
if (i >= L.Length) { err = 1; return false; }
if (!int.TryParse(L[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out v) &&
!int.TryParse(L[i], out v))
{
err = 1; return false;
}
i++;
return true;
}
private static bool ValBool(string[] L, ref int i, out bool b)
{
b = false;
if (i >= L.Length) return false;
string t = L[i++];
if (string.Equals(t, "True", StringComparison.OrdinalIgnoreCase)) { b = true; return true; }
if (string.Equals(t, "False", StringComparison.OrdinalIgnoreCase)) { b = false; return true; }
return false;
}
/// b[0] Imperil, [1] Vuln, [2] Yield, [3] GravityW, [4] Attack, [5] Ring, [6] Broad, [7] Fester, [8..12] WC/FC/Cp/DC/Cs, [13] Streak.
private static MonsterRule MakeRule(
string raw, int ap, int vtDmg, int wep, bool[] b, int sev, int ofh, int pet)
{
string n = Nm(raw);
if (b.Length < 14) b = Pad(b, 14);
bool i = b[0], v = b[1], y = b[2], gW = b[3];
bool useBolt = b[4], useRing = b[5], broad = b[6], fest = b[7];
bool strk = b[13];
return new MonsterRule
{
Name = n,
Priority = ap,
DamageType = MapDmg(vtDmg),
WeaponId = WepId(wep),
Imperil = i,
Vuln = v,
Yield = y,
GravityWell = gW,
UseBolt = useBolt,
UseRing = useRing,
Broadside = broad,
Fester = fest,
UseStreak = strk,
// VT extra curses (b[8]..b[12]) — no Rynth match
ExVuln = "None", // sev = spell/element code; Rynth list is by name; leave None; user can tune
OffhandId = WepId(ofh),
PetDamage = MapPet(pet, sev),
};
}
private static bool[] Pad(bool[] b, int min)
{
if (b.Length >= min) return b;
var r = new bool[min];
for (int i = 0; i < b.Length; i++) r[i] = b[i];
return r;
}
private static string Nm(string s)
{
s = s.Trim();
if (s.Length > 1 && s[0] == '<' && s[^1] == '>')
{
string t = s.Substring(1, s.Length - 2);
if (t.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) return "Default";
return t;
}
return s;
}
private static int WepId(int w) => w; // Rynth keeps AC-style ids (often large negatives); editor shows &lt;ID:…&gt; if not in list
/// <summary>uTank2 damage int — 8 and negatives typically mean "Auto" in exports.</summary>
private static string MapDmg(int c) => c switch
{
8 => "Auto",
1 => "Slash", 2 => "Pierce", 3 => "Bludgeon", 4 => "Acid", 5 => "Fire", 6 => "Cold", 7 => "Lightning", 0 => "Nether",
_ => "Auto",
};
private static string MapPet(int pdt, int _ /* secondary vuln int from VT; ExVuln string not derived */)
{
if (pdt is 0 or 101) return "PAuto";
if (pdt is >= 1 and <= 8)
{
// Narrowed 1..8: pet damage type codes in VT SCF.
return pdt switch
{
1 => "Slash", 2 => "Pierce", 3 => "Bludgeon", 4 => "Fire", 5 => "Cold", 6 => "Lightning", 7 => "Acid", 8 => "Nether",
_ => "PAuto",
};
}
return "PAuto";
}
}