Snapshot for release 2026.10.21.1 (internal 32a418d)
This commit is contained in:
commit
6fe5630e8c
202 changed files with 43765 additions and 0 deletions
110
Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs
Normal file
110
Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Threads;
|
||||
|
||||
/// <summary>One number in a modifier's description, with the form it was written in.</summary>
|
||||
internal readonly struct ModNumber
|
||||
{
|
||||
/// <summary>"x1.38" multiplier.</summary>
|
||||
public const string Mult = "mult";
|
||||
/// <summary>"12%".</summary>
|
||||
public const string Pct = "pct";
|
||||
/// <summary>"+29" (or "-5"): a signed amount, e.g. a rating.</summary>
|
||||
public const string Plus = "plus";
|
||||
/// <summary>A plain number.</summary>
|
||||
public const string Num = "num";
|
||||
|
||||
public readonly double Value;
|
||||
public readonly string Kind;
|
||||
/// <summary>As written ("x1.38", "12%", "+29", "75").</summary>
|
||||
public readonly string Text;
|
||||
|
||||
public ModNumber(double value, string kind, string text)
|
||||
{
|
||||
Value = value;
|
||||
Kind = kind;
|
||||
Text = text;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One "Name - description" line of the gem's block.</summary>
|
||||
internal sealed class GemModifier
|
||||
{
|
||||
public string Name = string.Empty;
|
||||
public string Description = string.Empty;
|
||||
public List<ModNumber> Numbers = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One press at a Fragment Press, as the server told it in chat. Everything the server says is
|
||||
/// kept as said (numbers raw): "Level 190, 4 entries." goes into ResultLevel and Entries without
|
||||
/// guessing what entries are.
|
||||
/// </summary>
|
||||
internal sealed class Press
|
||||
{
|
||||
/// <summary>Random id, so a press read back from the shared file isn't counted twice.</summary>
|
||||
public string Id = string.Empty;
|
||||
public DateTime TimeUtc;
|
||||
public string Server = string.Empty;
|
||||
public string Character = string.Empty;
|
||||
|
||||
/// <summary>"Raw Fragment" from "Using the Raw Fragment (Level 185) with the Fragment Press".</summary>
|
||||
public string Fragment = string.Empty;
|
||||
public int? FragmentLevel;
|
||||
/// <summary>"Fragment Press".</summary>
|
||||
public string Tool = string.Empty;
|
||||
|
||||
/// <summary>The "Pressed. ..." line ("Pressed. It holds."), or "" when none came.</summary>
|
||||
public string Outcome = string.Empty;
|
||||
/// <summary>A "Components selected: ..." (or "No components ...") line came.</summary>
|
||||
public bool ComponentsSeen;
|
||||
/// <summary>Sorted, case-insensitively.</summary>
|
||||
public List<string> Components = new();
|
||||
/// <summary>The "... drawn at random." line, or "".</summary>
|
||||
public string RandomNote = string.Empty;
|
||||
public List<GemModifier> Modifiers = new();
|
||||
public int? ResultLevel;
|
||||
public int? Entries;
|
||||
|
||||
/// <summary>Ended on its "Level N, M entries." line. False: timed out, or another "Using ..." line came first.</summary>
|
||||
public bool Complete;
|
||||
/// <summary>Why it ended: "done", "timeout", "next use", "logout".</summary>
|
||||
public string End = string.Empty;
|
||||
|
||||
/// <summary>The press's own lines, in order.</summary>
|
||||
public List<string> Raw = new();
|
||||
/// <summary>Lines that came while the press was open but didn't fit it (other players' chat, or text not known yet).</summary>
|
||||
public List<string> Extra = new();
|
||||
|
||||
/// <summary>The press says "It holds." (the only success text seen so far).</summary>
|
||||
public bool Held => Outcome.IndexOf("holds", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
|
||||
/// <summary>Used by the inference: a finished press with its whole gem block.</summary>
|
||||
public bool Usable => Complete && Modifiers.Count > 0;
|
||||
|
||||
public bool HasComponent(string name)
|
||||
{
|
||||
foreach (string c in Components)
|
||||
if (string.Equals(c, name, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool HasModifier(string name)
|
||||
{
|
||||
foreach (GemModifier m in Modifiers)
|
||||
if (string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public GemModifier? FindModifier(string name)
|
||||
{
|
||||
foreach (GemModifier m in Modifiers)
|
||||
if (string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)) return m;
|
||||
return null;
|
||||
}
|
||||
|
||||
public string ComponentsText => Components.Count == 0 ? "no components" : string.Join(", ", Components);
|
||||
|
||||
public static string NewId() => Guid.NewGuid().ToString("N").Substring(0, 16);
|
||||
}
|
||||
458
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs
Normal file
458
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Threads;
|
||||
|
||||
/// <summary>
|
||||
/// One modifier's rate in a set of presses (a component's, a combination's, ...), with its rate
|
||||
/// in the other presses for comparison.
|
||||
/// </summary>
|
||||
internal sealed class Odds
|
||||
{
|
||||
/// <summary>The modifier's name, or <see cref="PressInference.AffinityGroup"/> for any "<Material> Affinity".</summary>
|
||||
public string Modifier = string.Empty;
|
||||
/// <summary>Presses in the set that had it, of <see cref="N"/>.</summary>
|
||||
public int Hits, N;
|
||||
/// <summary>False for the All presses row: nothing to compare with.</summary>
|
||||
public bool Compared;
|
||||
/// <summary>The other presses (without the component, ...) that had it, of <see cref="OtherN"/>; 0 = no data.</summary>
|
||||
public int OtherHits, OtherN;
|
||||
/// <summary>One-sided Fisher exact p: chance of a rate this much higher here if the set made no difference.</summary>
|
||||
public double P = 1;
|
||||
/// <summary>Clearly higher here than in the other presses (Fisher p < 0.05 or the 95% intervals apart).</summary>
|
||||
public bool MoreLikely;
|
||||
/// <summary>Its numbers in these presses ("x1.38 to x1.52").</summary>
|
||||
public string Values = string.Empty;
|
||||
/// <summary>For the Affinity group: presses per material, most first.</summary>
|
||||
public List<(string Material, int Hits)> Split = new();
|
||||
|
||||
public double Rate => N == 0 ? 0 : (double)Hits / N;
|
||||
public double? OtherRate => OtherN == 0 ? null : (double)OtherHits / OtherN;
|
||||
public bool IsGroup => Modifier == PressInference.AffinityGroup;
|
||||
}
|
||||
|
||||
internal enum GroupKind { All, Component, Combination, NoComponents }
|
||||
|
||||
/// <summary>(fragment level, result level, entries) and how many presses gave it.</summary>
|
||||
internal readonly record struct ResultCount(int? FragmentLevel, int? ResultLevel, int? Entries, int Count);
|
||||
|
||||
/// <summary>A set of presses: All presses, one component's, one exact combination's, or those with no component.</summary>
|
||||
internal sealed class GroupReport
|
||||
{
|
||||
public string Name = string.Empty;
|
||||
public GroupKind Kind;
|
||||
/// <summary>The components (one for a component row, several for a combination, none otherwise).</summary>
|
||||
public List<string> Members = new();
|
||||
public int Presses;
|
||||
public double AvgModifiers;
|
||||
public int MinModifiers, MaxModifiers;
|
||||
/// <summary>Most common first.</summary>
|
||||
public List<ResultCount> Results = new();
|
||||
/// <summary>Every modifier seen in these presses, likeliest first.</summary>
|
||||
public List<Odds> Odds = new();
|
||||
|
||||
/// <summary>What the comparison column is: "without", "other presses", "with components", or "".</summary>
|
||||
public string OtherLabel => Kind switch
|
||||
{
|
||||
GroupKind.Component => "without",
|
||||
GroupKind.Combination => "other presses",
|
||||
GroupKind.NoComponents => "with components",
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
public Odds? Find(string modifier) =>
|
||||
Odds.FirstOrDefault(o => o.Modifier.Equals(modifier, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
internal sealed class ModifierReport
|
||||
{
|
||||
/// <summary>The modifier's name, or <see cref="PressInference.AffinityGroup"/>.</summary>
|
||||
public string Name = string.Empty;
|
||||
public bool IsGroup;
|
||||
public string Example = string.Empty;
|
||||
/// <summary>"reward" (loot, salvage), "harder" (monster health, damage, numbers) or "" when the text doesn't say plainly.</summary>
|
||||
public string Tag = string.Empty;
|
||||
/// <summary>Its rate over all usable presses.</summary>
|
||||
public Odds Overall = new();
|
||||
/// <summary>Its rate in presses with no components (against presses with some); null when there are none.</summary>
|
||||
public Odds? NoComponents;
|
||||
/// <summary>Its rate with each component and combination (0% included), likeliest first.</summary>
|
||||
public List<(GroupReport Group, Odds Odds)> ByGroup = new();
|
||||
public string Values = string.Empty;
|
||||
/// <summary>(fragment level, presses, values), lowest level first; level null = unknown.</summary>
|
||||
public List<(int? Level, int Count, string Values)> ByLevel = new();
|
||||
|
||||
public int Seen => Overall.Hits;
|
||||
}
|
||||
|
||||
internal sealed class ThreadsReport
|
||||
{
|
||||
public int Total, Usable, Incomplete, Characters;
|
||||
/// <summary>Every usable press (the baseline); null when there are none.</summary>
|
||||
public GroupReport? All;
|
||||
public List<GroupReport> Components = new();
|
||||
/// <summary>Exact combinations of two or more components.</summary>
|
||||
public List<GroupReport> Combinations = new();
|
||||
/// <summary>Presses with no components (the plain random draw); null when there are none.</summary>
|
||||
public GroupReport? NoComponents;
|
||||
public List<ModifierReport> Modifiers = new();
|
||||
|
||||
public GroupReport? Component(string name) =>
|
||||
Components.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public GroupReport? Combination(string name) =>
|
||||
Combinations.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public ModifierReport? Modifier(string name) =>
|
||||
Modifiers.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The odds of each modifier from the recorded presses. On DreamWeave a component gives a chance of
|
||||
/// each modifier, not a fixed one, so for every set of presses (All presses, each component, each
|
||||
/// exact combination of components, no components) this counts how often each modifier came:
|
||||
/// hits/N, with a 95% Wilson interval, against its rate in the presses outside the set.
|
||||
///
|
||||
/// Only finished presses with their gem block count (Press.Usable); a finished press without a
|
||||
/// "Components selected" line counts as one with no components. Every gem carries one
|
||||
/// "<Material> Affinity": those are counted together as the Affinity group, with the split by
|
||||
/// material.
|
||||
///
|
||||
/// "More likely with X": the rate with X is above the rate without and either the one-sided Fisher
|
||||
/// exact p is under 0.05 or the two 95% intervals don't overlap. "Always ... so far" only for 100%
|
||||
/// over at least 10 presses.
|
||||
/// </summary>
|
||||
internal static class PressInference
|
||||
{
|
||||
public const string AffinityGroup = "Affinity";
|
||||
private const string AffinitySuffix = " Affinity";
|
||||
private const double Z = 1.96;
|
||||
/// <summary>Intervals are shown below this many presses.</summary>
|
||||
public const int IntervalBelow = 50;
|
||||
public const int AlwaysAtLeast = 10;
|
||||
|
||||
public static ThreadsReport Build(IReadOnlyList<Press> all)
|
||||
{
|
||||
var report = new ThreadsReport { Total = all.Count };
|
||||
var used = new List<Press>();
|
||||
var characters = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (Press p in all)
|
||||
{
|
||||
if (p.Character.Length > 0) characters.Add(p.Character);
|
||||
if (!p.Complete) report.Incomplete++;
|
||||
if (p.Usable) used.Add(p);
|
||||
}
|
||||
report.Usable = used.Count;
|
||||
report.Characters = characters.Count;
|
||||
if (used.Count == 0) return report;
|
||||
|
||||
List<string> components = Distinct(used.SelectMany(p => p.Components));
|
||||
List<string> keys = Distinct(used.SelectMany(Keys));
|
||||
|
||||
report.All = Group("All presses", GroupKind.All, new List<string>(), used, used);
|
||||
|
||||
foreach (string c in components)
|
||||
report.Components.Add(Group(c, GroupKind.Component, new List<string> { c }, used, used.Where(p => p.HasComponent(c)).ToList()));
|
||||
SortGroups(report.Components);
|
||||
|
||||
foreach (var g in used.Where(p => p.Components.Count > 1).GroupBy(ComboKey, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
List<string> members = g.First().Components.OrderBy(x => x, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
report.Combinations.Add(Group(string.Join(" + ", members), GroupKind.Combination, members, used, g.ToList()));
|
||||
}
|
||||
SortGroups(report.Combinations);
|
||||
|
||||
List<Press> plain = used.Where(p => p.Components.Count == 0).ToList();
|
||||
if (plain.Count > 0)
|
||||
report.NoComponents = Group("No components", GroupKind.NoComponents, new List<string>(), used, plain);
|
||||
|
||||
foreach (string k in keys)
|
||||
{
|
||||
List<Press> with = used.Where(p => Has(p, k)).ToList();
|
||||
var mr = new ModifierReport
|
||||
{
|
||||
Name = k,
|
||||
IsGroup = k == AffinityGroup,
|
||||
Example = Find(with[^1], k)!.Description,
|
||||
Overall = Count(k, used, null),
|
||||
Values = Values(with, k),
|
||||
};
|
||||
mr.Tag = Tag(mr.Example);
|
||||
if (report.NoComponents != null) mr.NoComponents = Count(k, plain, used.Where(p => p.Components.Count > 0).ToList());
|
||||
foreach (GroupReport gr in report.Components.Concat(report.Combinations))
|
||||
mr.ByGroup.Add((gr, gr.Find(k) ?? Count(k, Members(used, gr), Others(used, gr))));
|
||||
mr.ByGroup.Sort((a, b) =>
|
||||
{
|
||||
int byOdds = CompareOdds(a.Odds, b.Odds);
|
||||
return byOdds != 0 ? byOdds : string.Compare(a.Group.Name, b.Group.Name, StringComparison.OrdinalIgnoreCase);
|
||||
});
|
||||
foreach (var g in with.GroupBy(p => p.FragmentLevel).OrderBy(g => g.Key ?? int.MaxValue))
|
||||
mr.ByLevel.Add((g.Key, g.Count(), Values(g, k)));
|
||||
report.Modifiers.Add(mr);
|
||||
}
|
||||
report.Modifiers.Sort((a, b) => b.Seen != a.Seen ? b.Seen.CompareTo(a.Seen) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
|
||||
return report;
|
||||
}
|
||||
|
||||
// ── Groups ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static GroupReport Group(string name, GroupKind kind, List<string> members, List<Press> used, List<Press> set)
|
||||
{
|
||||
var g = new GroupReport { Name = name, Kind = kind, Members = members, Presses = set.Count };
|
||||
if (set.Count == 0) return g;
|
||||
g.AvgModifiers = set.Average(p => (double)p.Modifiers.Count);
|
||||
g.MinModifiers = set.Min(p => p.Modifiers.Count);
|
||||
g.MaxModifiers = set.Max(p => p.Modifiers.Count);
|
||||
g.Results = set.GroupBy(p => (p.FragmentLevel, p.ResultLevel, p.Entries))
|
||||
.Select(x => new ResultCount(x.Key.FragmentLevel, x.Key.ResultLevel, x.Key.Entries, x.Count()))
|
||||
.OrderByDescending(r => r.Count).ThenBy(r => r.ResultLevel ?? int.MaxValue).ThenBy(r => r.Entries ?? int.MaxValue)
|
||||
.ToList();
|
||||
List<Press>? others = kind == GroupKind.All ? null : Others(used, g, set);
|
||||
foreach (string k in Distinct(set.SelectMany(Keys)))
|
||||
g.Odds.Add(Count(k, set, others));
|
||||
g.Odds.Sort(CompareOdds);
|
||||
return g;
|
||||
}
|
||||
|
||||
private static void SortGroups(List<GroupReport> groups) =>
|
||||
groups.Sort((a, b) => b.Presses != a.Presses ? b.Presses.CompareTo(a.Presses) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The presses a component or combination row covers.</summary>
|
||||
private static List<Press> Members(List<Press> used, GroupReport g) => g.Kind switch
|
||||
{
|
||||
GroupKind.Component => used.Where(p => p.HasComponent(g.Members[0])).ToList(),
|
||||
GroupKind.Combination => used.Where(p => ComboKey(p).Equals(ComboKey(g.Members), StringComparison.OrdinalIgnoreCase)).ToList(),
|
||||
GroupKind.NoComponents => used.Where(p => p.Components.Count == 0).ToList(),
|
||||
_ => used,
|
||||
};
|
||||
|
||||
/// <summary>The presses a row is compared with: without the component, not this combination, with components.</summary>
|
||||
private static List<Press> Others(List<Press> used, GroupReport g, List<Press>? set = null)
|
||||
{
|
||||
var inSet = new HashSet<Press>(set ?? Members(used, g));
|
||||
return used.Where(p => !inSet.Contains(p)).ToList();
|
||||
}
|
||||
|
||||
private static string ComboKey(Press p) => ComboKey(p.Components);
|
||||
|
||||
private static string ComboKey(IEnumerable<string> components) =>
|
||||
string.Join("\n", components.Select(c => c.ToLowerInvariant()).OrderBy(c => c, StringComparer.Ordinal));
|
||||
|
||||
/// <summary>Likeliest first; then more presses; then by name.</summary>
|
||||
private static int CompareOdds(Odds a, Odds b)
|
||||
{
|
||||
if (a.Rate != b.Rate) return b.Rate.CompareTo(a.Rate);
|
||||
if (a.Hits != b.Hits) return b.Hits.CompareTo(a.Hits);
|
||||
return string.Compare(a.Modifier, b.Modifier, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>Modifier <paramref name="k"/> in <paramref name="set"/>, against <paramref name="others"/> (null = no comparison).</summary>
|
||||
internal static Odds Count(string k, List<Press> set, List<Press>? others)
|
||||
{
|
||||
var o = new Odds { Modifier = k, N = set.Count, Compared = others != null };
|
||||
foreach (Press p in set)
|
||||
if (Has(p, k)) o.Hits++;
|
||||
if (others != null)
|
||||
{
|
||||
o.OtherN = others.Count;
|
||||
foreach (Press p in others)
|
||||
if (Has(p, k)) o.OtherHits++;
|
||||
if (o.OtherN > 0 && o.N > 0)
|
||||
{
|
||||
o.P = FisherGreater(o.Hits, o.N, o.OtherHits, o.OtherN);
|
||||
bool apart = Wilson(o.Hits, o.N).Low > Wilson(o.OtherHits, o.OtherN).High;
|
||||
o.MoreLikely = o.Rate > o.OtherRate!.Value && (o.P < 0.05 || apart);
|
||||
}
|
||||
}
|
||||
o.Values = Values(set, k);
|
||||
if (k == AffinityGroup)
|
||||
{
|
||||
var split = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
var names = new List<string>();
|
||||
foreach (Press p in set)
|
||||
foreach (string mat in p.Modifiers.Select(m => Material(m.Name)).OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!split.ContainsKey(mat)) { split[mat] = 0; names.Add(mat); }
|
||||
split[mat]++;
|
||||
}
|
||||
o.Split = names.Select(n => (n, split[n]))
|
||||
.OrderByDescending(x => x.Item2).ThenBy(x => x.n, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
// ── Modifier keys (the Affinity group) ──────────────────────────────────
|
||||
|
||||
/// <summary>"Amethyst" for "Amethyst Affinity", else null.</summary>
|
||||
internal static string? Material(string modifier) =>
|
||||
modifier.Length > AffinitySuffix.Length && modifier.EndsWith(AffinitySuffix, StringComparison.OrdinalIgnoreCase)
|
||||
? modifier.Substring(0, modifier.Length - AffinitySuffix.Length).Trim()
|
||||
: null;
|
||||
|
||||
/// <summary>The name the counts use: <see cref="AffinityGroup"/> for any affinity, else the modifier's own.</summary>
|
||||
internal static string Key(string modifier) => Material(modifier) != null ? AffinityGroup : modifier;
|
||||
|
||||
private static IEnumerable<string> Keys(Press p) => p.Modifiers.Select(m => Key(m.Name));
|
||||
|
||||
private static bool Has(Press p, string k) => Find(p, k) != null;
|
||||
|
||||
private static GemModifier? Find(Press p, string k)
|
||||
{
|
||||
if (k != AffinityGroup) return p.FindModifier(k);
|
||||
foreach (GemModifier m in p.Modifiers)
|
||||
if (Material(m.Name) != null) return m;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>"Affinity (any)" for the group, else the name.</summary>
|
||||
internal static string Display(string k) => k == AffinityGroup ? "Affinity (any)" : k;
|
||||
|
||||
// ── Statistics ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>95% Wilson score interval for <paramref name="hits"/> of <paramref name="n"/>.</summary>
|
||||
internal static (double Low, double High) Wilson(int hits, int n)
|
||||
{
|
||||
if (n <= 0) return (0, 1);
|
||||
double p = (double)hits / n, z2 = Z * Z;
|
||||
double denom = 1 + z2 / n;
|
||||
double centre = (p + z2 / (2 * n)) / denom;
|
||||
double half = Z * Math.Sqrt(p * (1 - p) / n + z2 / (4.0 * n * n)) / denom;
|
||||
return (Math.Max(0, centre - half), Math.Min(1, centre + half));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One-sided Fisher exact test: the chance of <paramref name="a"/> or more hits in a set of
|
||||
/// <paramref name="n"/> when <paramref name="a"/> + <paramref name="c"/> hits are spread at random
|
||||
/// over the <paramref name="n"/> + <paramref name="m"/> presses.
|
||||
/// </summary>
|
||||
internal static double FisherGreater(int a, int n, int c, int m)
|
||||
{
|
||||
int total = n + m, hits = a + c;
|
||||
if (total == 0) return 1;
|
||||
double logAll = LogChoose(total, n), sum = 0;
|
||||
for (int x = a; x <= Math.Min(n, hits); x++)
|
||||
{
|
||||
if (hits - x > m) continue;
|
||||
sum += Math.Exp(LogChoose(hits, x) + LogChoose(total - hits, n - x) - logAll);
|
||||
}
|
||||
return Math.Min(1, sum);
|
||||
}
|
||||
|
||||
private static double LogChoose(int n, int k)
|
||||
{
|
||||
if (k < 0 || k > n) return double.NegativeInfinity;
|
||||
double r = 0;
|
||||
for (int i = 1; i <= k; i++) r += Math.Log(n - k + i) - Math.Log(i);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ── Text ────────────────────────────────────────────────────────────────
|
||||
|
||||
private static string Pct(double v) => Math.Round(v * 100).ToString("0", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>"75% (3/4, 30-95%)"; the interval only below <see cref="IntervalBelow"/> presses.</summary>
|
||||
internal static string OddsText(Odds o)
|
||||
{
|
||||
if (o.N == 0) return "no data";
|
||||
if (o.N >= IntervalBelow) return $"{Pct(o.Rate)}% ({o.Hits}/{o.N})";
|
||||
var (lo, hi) = Wilson(o.Hits, o.N);
|
||||
return $"{Pct(o.Rate)}% ({o.Hits}/{o.N}, {Pct(lo)}-{Pct(hi)}%)";
|
||||
}
|
||||
|
||||
/// <summary>"without: 20% (1/5)", "without: no data", or "" when not compared.</summary>
|
||||
internal static string OtherText(Odds o, string label)
|
||||
{
|
||||
if (!o.Compared || label.Length == 0) return string.Empty;
|
||||
return o.OtherN == 0 ? label + ": no data" : $"{label}: {Pct(o.OtherRate!.Value)}% ({o.OtherHits}/{o.OtherN})";
|
||||
}
|
||||
|
||||
/// <summary>"more likely with Lead Scarab", "always with Lead Scarab so far" (100% over 10+), or "".</summary>
|
||||
internal static string LikelyText(Odds o, GroupReport g)
|
||||
{
|
||||
if (!o.MoreLikely) return string.Empty;
|
||||
string who = g.Kind == GroupKind.NoComponents ? "no components" : g.Name;
|
||||
return o.Hits == o.N && o.N >= AlwaysAtLeast ? $"always with {who} so far" : $"more likely with {who}";
|
||||
}
|
||||
|
||||
/// <summary>"Amethyst 1, Iron 1" for the Affinity group's split, else "".</summary>
|
||||
internal static string SplitText(Odds o) =>
|
||||
string.Join(", ", o.Split.Select(s => $"{s.Material} {s.Hits}"));
|
||||
|
||||
/// <summary>"5.25 modifiers per press (5-6)".</summary>
|
||||
internal static string ModifiersText(GroupReport g)
|
||||
{
|
||||
string avg = g.AvgModifiers.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
string range = g.MinModifiers == g.MaxModifiers ? "" : $" ({g.MinModifiers}-{g.MaxModifiers})";
|
||||
return $"{avg} modifiers per press{range}";
|
||||
}
|
||||
|
||||
/// <summary>"L185 -> 175, 3 entries: 4" per result, most common first.</summary>
|
||||
internal static string ResultsText(GroupReport g) =>
|
||||
string.Join("; ", g.Results.Select(r =>
|
||||
$"L{N(r.FragmentLevel)} -> {N(r.ResultLevel)}, {N(r.Entries)} entries: {r.Count}"));
|
||||
|
||||
private static string N(int? v) => v?.ToString(CultureInfo.InvariantCulture) ?? "?";
|
||||
|
||||
private static List<string> Distinct(IEnumerable<string> names)
|
||||
{
|
||||
var list = new List<string>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string n in names)
|
||||
if (n.Length > 0 && seen.Add(n)) list.Add(n);
|
||||
list.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The modifier's numbers across presses, position by position: "x1.38 to x1.52, 12%". Empty
|
||||
/// when it has none.
|
||||
/// </summary>
|
||||
internal static string Values(IEnumerable<Press> presses, string k)
|
||||
{
|
||||
var ranges = new List<(string Kind, double Min, double Max)>();
|
||||
foreach (Press p in presses)
|
||||
{
|
||||
GemModifier? gm = Find(p, k);
|
||||
if (gm == null) continue;
|
||||
for (int i = 0; i < gm.Numbers.Count; i++)
|
||||
{
|
||||
ModNumber n = gm.Numbers[i];
|
||||
if (i >= ranges.Count) ranges.Add((n.Kind, n.Value, n.Value));
|
||||
else ranges[i] = (ranges[i].Kind, Math.Min(ranges[i].Min, n.Value), Math.Max(ranges[i].Max, n.Value));
|
||||
}
|
||||
}
|
||||
var sb = new StringBuilder();
|
||||
foreach (var (kind, min, max) in ranges)
|
||||
{
|
||||
if (sb.Length > 0) sb.Append(", ");
|
||||
sb.Append(Format(kind, min));
|
||||
if (max != min) sb.Append(" to ").Append(Format(kind, max));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
internal static string Format(string kind, double v)
|
||||
{
|
||||
string s = v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
return kind switch
|
||||
{
|
||||
ModNumber.Mult => "x" + s,
|
||||
ModNumber.Pct => s + "%",
|
||||
ModNumber.Plus => v >= 0 ? "+" + s : s,
|
||||
_ => s,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"reward" or "harder" when the description says so plainly, else "".</summary>
|
||||
internal static string Tag(string description)
|
||||
{
|
||||
string d = description.ToLowerInvariant();
|
||||
bool reward = d.Contains("loot") || d.Contains("salvage") || d.Contains("drop");
|
||||
bool harder = d.Contains("monsters have") || d.Contains("more monsters") || d.Contains("monsters attack")
|
||||
|| d.Contains("boss attacks") || d.Contains("hitting harder");
|
||||
return reward == harder ? string.Empty : reward ? "reward" : "harder";
|
||||
}
|
||||
}
|
||||
250
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs
Normal file
250
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Threads;
|
||||
|
||||
/// <summary>
|
||||
/// Reads Fragment Press results out of chat, one line at a time. A press starts at
|
||||
/// "Using the Raw Fragment (Level 185) with the Fragment Press"
|
||||
/// and collects, in any order and with other chat in between:
|
||||
/// "Pressed. It holds." the outcome (any "Pressed..." line)
|
||||
/// "Components selected: A, B" (or "No components ...")
|
||||
/// "Remaining slots drawn at random." (any "... drawn at random" line)
|
||||
/// "The gem carries:" then one " Name - description" line per modifier
|
||||
/// and ends at "Level 190, 4 entries." (complete). A press that never gets there is still saved,
|
||||
/// marked incomplete: after <see cref="TimeoutMs"/> without a line of its own, when another
|
||||
/// "Using ..." line comes, or at logout. Lines that don't fit are kept in the press's Extra list
|
||||
/// (other players' chat lands there too). Never throws on odd text.
|
||||
/// </summary>
|
||||
internal sealed class PressParser
|
||||
{
|
||||
/// <summary>A press's lines arrive within the same second; this long without one ends it.</summary>
|
||||
public const long TimeoutMs = 15_000;
|
||||
private const int MaxLineLength = 400;
|
||||
private const int MaxRawLines = 80;
|
||||
private const int MaxExtraLines = 40;
|
||||
private const int MaxModifiers = 40;
|
||||
|
||||
private static readonly RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase;
|
||||
private static readonly Regex UseRx = new(@"^Using (?:the |an? )?(?<item>.+?) with (?:the |an? )?(?<tool>[^.]*\bPress)\b", Opt);
|
||||
private static readonly Regex LevelInName = new(@"^(?<name>.*?)\s*\(\s*Level\s+(?<lvl>\d+)\s*\)\s*$", Opt);
|
||||
private static readonly Regex ComponentsRx = new(@"^Components?(?: selected)?\s*:\s*(?<list>.*)$", Opt);
|
||||
private static readonly Regex NoComponentsRx = new(@"^No components\b", Opt);
|
||||
private static readonly Regex CarriesRx = new(@"^The [^:]{1,40} carries\s*:?\s*$", Opt);
|
||||
private static readonly Regex EndRx = new(@"^Level\s+(?<lvl>\d+)\s*(?:,\s*(?<entries>\d+)\s+entr(?:y|ies))?\s*\.?\s*$", Opt);
|
||||
// "Name - description": a short name of letters, spaces, apostrophes and hyphens.
|
||||
private static readonly Regex ModifierRx = new(@"^(?<name>[A-Za-z][A-Za-z' \-]{0,47}?)\s+[-–—]\s+(?<desc>.+)$", Opt);
|
||||
private static readonly Regex NumberRx = new(
|
||||
@"(?<![A-Za-z0-9.])(?:(?<mult>[x×]\s?\d+(?:\.\d+)?)|(?<plus>[+\-]\d+(?:\.\d+)?)(?!\d|\.\d|\s?%)|(?<pct>[+\-]?\d+(?:\.\d+)?\s?%)|(?<num>\d+(?:\.\d+)?))",
|
||||
RegexOptions.CultureInvariant);
|
||||
|
||||
private enum State { Idle, Open, Carries }
|
||||
|
||||
private State _state = State.Idle;
|
||||
private Press? _press;
|
||||
private long _lastOwnLineMs;
|
||||
|
||||
/// <summary>A press is being read.</summary>
|
||||
public bool Busy => _press != null;
|
||||
|
||||
/// <summary>
|
||||
/// Feeds one chat message (it may hold several lines). Returns the presses it finished, or
|
||||
/// null. <paramref name="nowMs"/> is a monotonic clock (Environment.TickCount64).
|
||||
/// </summary>
|
||||
public List<Press>? Feed(string? text, long nowMs)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return null;
|
||||
List<Press>? done = null;
|
||||
foreach (string piece in text.Split('\n'))
|
||||
{
|
||||
string line = piece.TrimEnd('\r', ' ', '\t');
|
||||
if (line.Trim().Length == 0) continue;
|
||||
if (line.Length > MaxLineLength) line = line.Substring(0, MaxLineLength);
|
||||
try
|
||||
{
|
||||
Press? finished = FeedLine(line, nowMs);
|
||||
if (finished != null) (done ??= new List<Press>()).Add(finished);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Odd text must never stop chat; the line is just not used.
|
||||
}
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
/// <summary>Ends a press that has gone quiet. Returns it (incomplete), or null.</summary>
|
||||
public Press? Tick(long nowMs)
|
||||
{
|
||||
if (_press == null || nowMs - _lastOwnLineMs < TimeoutMs) return null;
|
||||
return Finish("timeout");
|
||||
}
|
||||
|
||||
/// <summary>Ends whatever is open (logout, unload). Returns it (incomplete), or null.</summary>
|
||||
public Press? Flush(string reason) => _press == null ? null : Finish(reason);
|
||||
|
||||
private Press? FeedLine(string line, long nowMs)
|
||||
{
|
||||
string t = line.Trim();
|
||||
Press? previous = null;
|
||||
|
||||
if (t.StartsWith("Using ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Match use = UseRx.Match(t);
|
||||
if (_press != null) previous = Finish("next use");
|
||||
if (!use.Success) return previous;
|
||||
Start(use, line, nowMs);
|
||||
return previous;
|
||||
}
|
||||
if (_press == null) return null;
|
||||
|
||||
if (_state == State.Carries)
|
||||
{
|
||||
Match mod = ModifierRx.Match(t);
|
||||
// Modifier lines are indented; an unindented one must still look exactly like "Name - text".
|
||||
bool indented = line.Length > 0 && char.IsWhiteSpace(line[0]);
|
||||
if (mod.Success && (indented || !LooksLikeChat(t)))
|
||||
{
|
||||
if (_press.Modifiers.Count < MaxModifiers) _press.Modifiers.Add(MakeModifier(mod));
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Match end = EndRx.Match(t);
|
||||
if (end.Success)
|
||||
{
|
||||
_press.ResultLevel = Int(end.Groups["lvl"].Value);
|
||||
if (end.Groups["entries"].Success) _press.Entries = Int(end.Groups["entries"].Value);
|
||||
Own(line, nowMs);
|
||||
return Finish("done", complete: true);
|
||||
}
|
||||
if (t.StartsWith("Pressed", StringComparison.OrdinalIgnoreCase) && _press.Outcome.Length == 0)
|
||||
{
|
||||
_press.Outcome = t;
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
Match comps = ComponentsRx.Match(t);
|
||||
if (comps.Success && !_press.ComponentsSeen)
|
||||
{
|
||||
_press.ComponentsSeen = true;
|
||||
_press.Components = SplitComponents(comps.Groups["list"].Value);
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
if (NoComponentsRx.IsMatch(t) && !_press.ComponentsSeen)
|
||||
{
|
||||
_press.ComponentsSeen = true;
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
if (t.IndexOf("drawn at random", StringComparison.OrdinalIgnoreCase) >= 0 && _press.RandomNote.Length == 0)
|
||||
{
|
||||
_press.RandomNote = t;
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
if (CarriesRx.IsMatch(t))
|
||||
{
|
||||
_state = State.Carries;
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Not ours (or not known yet): keep it beside the press, don't let it extend the timeout.
|
||||
if (_press.Extra.Count < MaxExtraLines) _press.Extra.Add(line);
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Start(Match use, string line, long nowMs)
|
||||
{
|
||||
string item = use.Groups["item"].Value.Trim();
|
||||
var p = new Press
|
||||
{
|
||||
Id = Press.NewId(),
|
||||
TimeUtc = DateTime.UtcNow,
|
||||
Tool = use.Groups["tool"].Value.Trim(),
|
||||
Fragment = item,
|
||||
};
|
||||
Match lv = LevelInName.Match(item);
|
||||
if (lv.Success)
|
||||
{
|
||||
p.Fragment = lv.Groups["name"].Value.Trim();
|
||||
p.FragmentLevel = Int(lv.Groups["lvl"].Value);
|
||||
}
|
||||
_press = p;
|
||||
_state = State.Open;
|
||||
Own(line, nowMs);
|
||||
}
|
||||
|
||||
private void Own(string line, long nowMs)
|
||||
{
|
||||
if (_press!.Raw.Count < MaxRawLines) _press.Raw.Add(line);
|
||||
_lastOwnLineMs = nowMs;
|
||||
}
|
||||
|
||||
private Press Finish(string reason, bool complete = false)
|
||||
{
|
||||
Press p = _press!;
|
||||
p.Complete = complete;
|
||||
p.End = reason;
|
||||
_press = null;
|
||||
_state = State.Idle;
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>Chat from players and channels ("Bob says, ...", "[Trade] ...", "You tell ...").</summary>
|
||||
private static bool LooksLikeChat(string t) =>
|
||||
t.StartsWith("[", StringComparison.Ordinal) || t.Contains(" says, ") || t.Contains(" tells you")
|
||||
|| t.StartsWith("You ", StringComparison.Ordinal) || t.Contains('"');
|
||||
|
||||
internal static List<string> SplitComponents(string list)
|
||||
{
|
||||
var result = new List<string>();
|
||||
string s = list.Trim().TrimEnd('.');
|
||||
if (s.Length == 0 || s.Equals("none", StringComparison.OrdinalIgnoreCase)) return result;
|
||||
foreach (string part in s.Replace(" and ", ",", StringComparison.OrdinalIgnoreCase).Split(','))
|
||||
{
|
||||
string c = part.Trim();
|
||||
if (c.Length > 0 && !result.Exists(x => x.Equals(c, StringComparison.OrdinalIgnoreCase))) result.Add(c);
|
||||
}
|
||||
result.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static GemModifier MakeModifier(Match m)
|
||||
{
|
||||
string desc = m.Groups["desc"].Value.Trim();
|
||||
return new GemModifier
|
||||
{
|
||||
Name = m.Groups["name"].Value.Trim(),
|
||||
Description = desc,
|
||||
Numbers = Numbers(desc),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Every number in a description with its form: x1.38, 12%, +29 (or -5), 75.</summary>
|
||||
internal static List<ModNumber> Numbers(string text)
|
||||
{
|
||||
var list = new List<ModNumber>();
|
||||
foreach (Match m in NumberRx.Matches(text))
|
||||
{
|
||||
string kind;
|
||||
string raw;
|
||||
if (m.Groups["mult"].Success) { kind = ModNumber.Mult; raw = m.Groups["mult"].Value; }
|
||||
else if (m.Groups["plus"].Success) { kind = ModNumber.Plus; raw = m.Groups["plus"].Value; }
|
||||
else if (m.Groups["pct"].Success) { kind = ModNumber.Pct; raw = m.Groups["pct"].Value; }
|
||||
else { kind = ModNumber.Num; raw = m.Groups["num"].Value; }
|
||||
string digits = raw.TrimStart('x', '×', '+').TrimEnd('%').Trim();
|
||||
if (double.TryParse(digits, NumberStyles.Float, CultureInfo.InvariantCulture, out double v))
|
||||
list.Add(new ModNumber(v, kind, raw.Replace(" ", string.Empty)));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static int? Int(string s) =>
|
||||
int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : null;
|
||||
}
|
||||
346
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs
Normal file
346
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs
Normal file
|
|
@ -0,0 +1,346 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Threads;
|
||||
|
||||
/// <summary>
|
||||
/// Every press, one JSON object per line, in one file shared by all characters and clients on the
|
||||
/// PC (%LOCALAPPDATA%\RynthCore\RynthThreads\presses.jsonl). Appends open the file for writing
|
||||
/// alone, so two clients never mix their lines: a writer that finds it busy tries again a few
|
||||
/// times, and a press that still can't be written waits for <see cref="FlushPending"/>.
|
||||
/// Reading follows the file's growth (<see cref="Poll"/>), so other clients' presses show up.
|
||||
/// Written by hand with Utf8JsonWriter and read with JsonDocument: plugin types never go through
|
||||
/// System.Text.Json's serializer (its cache would keep an old plugin alive across a hot reload).
|
||||
/// </summary>
|
||||
internal sealed class PressStore
|
||||
{
|
||||
public const string FileName = "presses.jsonl";
|
||||
private const int AppendTries = 4;
|
||||
private const int AppendWaitMs = 15;
|
||||
private const int MaxPending = 200;
|
||||
|
||||
private readonly List<Press> _presses = new();
|
||||
private readonly HashSet<string> _ids = new(StringComparer.Ordinal);
|
||||
private readonly List<Press> _pending = new();
|
||||
private long _readOffset;
|
||||
|
||||
public readonly string Folder;
|
||||
public string FilePath => Path.Combine(Folder, FileName);
|
||||
|
||||
/// <summary>Every press read or recorded, oldest first.</summary>
|
||||
public IReadOnlyList<Press> Presses => _presses;
|
||||
/// <summary>Presses recorded here that couldn't be written yet.</summary>
|
||||
public int PendingCount => _pending.Count;
|
||||
/// <summary>Lines in the file that couldn't be read (kept in the file, skipped here).</summary>
|
||||
public int BadLines { get; private set; }
|
||||
/// <summary>Bumped whenever <see cref="Presses"/> changes.</summary>
|
||||
public int Version { get; private set; }
|
||||
|
||||
public PressStore(string folder) => Folder = folder;
|
||||
|
||||
/// <summary>%LOCALAPPDATA%\RynthCore\RynthThreads.</summary>
|
||||
public static string DefaultFolder => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "RynthThreads");
|
||||
|
||||
// ── Writing ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the press and appends it to the file. Returns null when written, else why not (it
|
||||
/// stays pending and <see cref="FlushPending"/> tries again).
|
||||
/// </summary>
|
||||
public string? Record(Press p)
|
||||
{
|
||||
if (p.Id.Length == 0) p.Id = Press.NewId();
|
||||
Add(p);
|
||||
string? error = TryAppend(ToJson(p));
|
||||
if (error != null && _pending.Count < MaxPending) _pending.Add(p);
|
||||
return error;
|
||||
}
|
||||
|
||||
/// <summary>Writes presses that found the file busy before. Returns how many are still waiting.</summary>
|
||||
public int FlushPending()
|
||||
{
|
||||
while (_pending.Count > 0)
|
||||
{
|
||||
if (TryAppend(ToJson(_pending[0])) != null) break;
|
||||
_pending.RemoveAt(0);
|
||||
}
|
||||
return _pending.Count;
|
||||
}
|
||||
|
||||
/// <summary>Appends one line, retrying briefly while another writer holds the file.</summary>
|
||||
internal string? TryAppend(string json)
|
||||
{
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(json + "\n");
|
||||
string? last = null;
|
||||
for (int attempt = 0; attempt < AppendTries; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
// FileShare.Read: readers may look, no other writer gets in until this line is down.
|
||||
using var fs = new FileStream(FilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
|
||||
fs.Write(bytes, 0, bytes.Length);
|
||||
return null;
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
last = ex.Message;
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
if (attempt < AppendTries - 1) Thread.Sleep(AppendWaitMs * (attempt + 1)); // at most 90 ms on the pump
|
||||
}
|
||||
return last ?? "the file is busy";
|
||||
}
|
||||
|
||||
// ── Reading ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Reads what was added to the file since the last read (everything the first time). Returns the number of new presses.</summary>
|
||||
public int Poll()
|
||||
{
|
||||
string path = FilePath;
|
||||
long length;
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(path);
|
||||
if (!info.Exists) return 0;
|
||||
length = info.Length;
|
||||
}
|
||||
catch { return 0; }
|
||||
|
||||
if (length < _readOffset) _readOffset = 0; // replaced or cut short: read it all again (ids keep it from doubling)
|
||||
if (length == _readOffset) return 0;
|
||||
|
||||
byte[] data;
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
fs.Seek(_readOffset, SeekOrigin.Begin);
|
||||
data = new byte[length - _readOffset];
|
||||
int got = 0;
|
||||
while (got < data.Length)
|
||||
{
|
||||
int n = fs.Read(data, got, data.Length - got);
|
||||
if (n <= 0) break;
|
||||
got += n;
|
||||
}
|
||||
if (got < data.Length) Array.Resize(ref data, got);
|
||||
}
|
||||
catch { return 0; }
|
||||
|
||||
// Only whole lines; a line still being written is read next time.
|
||||
int lastNewline = Array.LastIndexOf(data, (byte)'\n');
|
||||
if (lastNewline < 0) return 0;
|
||||
_readOffset += lastNewline + 1;
|
||||
|
||||
int added = 0;
|
||||
foreach (string line in Encoding.UTF8.GetString(data, 0, lastNewline).Split('\n'))
|
||||
{
|
||||
string l = line.Trim();
|
||||
if (l.Length == 0) continue;
|
||||
Press? p = FromJson(l);
|
||||
if (p == null) { BadLines++; continue; }
|
||||
if (Add(p)) added++;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
private bool Add(Press p)
|
||||
{
|
||||
if (p.Id.Length > 0 && !_ids.Add(p.Id)) return false;
|
||||
// Kept in time order (other clients' lines can land out of order).
|
||||
int at = _presses.Count;
|
||||
while (at > 0 && _presses[at - 1].TimeUtc > p.TimeUtc) at--;
|
||||
_presses.Insert(at, p);
|
||||
Version++;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── JSON ────────────────────────────────────────────────────────────────
|
||||
|
||||
internal static string ToJson(Press p)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = false }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("v", 1);
|
||||
w.WriteString("id", p.Id);
|
||||
w.WriteString("time", p.TimeUtc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture));
|
||||
w.WriteString("server", p.Server);
|
||||
w.WriteString("character", p.Character);
|
||||
w.WriteString("fragment", p.Fragment);
|
||||
WriteInt(w, "fragmentLevel", p.FragmentLevel);
|
||||
w.WriteString("tool", p.Tool);
|
||||
w.WriteString("outcome", p.Outcome);
|
||||
w.WriteBoolean("componentsSeen", p.ComponentsSeen);
|
||||
w.WriteStartArray("components");
|
||||
foreach (string c in p.Components) w.WriteStringValue(c);
|
||||
w.WriteEndArray();
|
||||
w.WriteString("random", p.RandomNote);
|
||||
w.WriteStartArray("modifiers");
|
||||
foreach (GemModifier m in p.Modifiers)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("name", m.Name);
|
||||
w.WriteString("description", m.Description);
|
||||
w.WriteStartArray("numbers");
|
||||
foreach (ModNumber n in m.Numbers)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("value", n.Value);
|
||||
w.WriteString("kind", n.Kind);
|
||||
w.WriteString("text", n.Text);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
WriteInt(w, "resultLevel", p.ResultLevel);
|
||||
WriteInt(w, "entries", p.Entries);
|
||||
w.WriteBoolean("complete", p.Complete);
|
||||
w.WriteString("end", p.End);
|
||||
WriteStrings(w, "raw", p.Raw);
|
||||
WriteStrings(w, "extra", p.Extra);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(ms.ToArray());
|
||||
}
|
||||
|
||||
private static void WriteInt(Utf8JsonWriter w, string name, int? v)
|
||||
{
|
||||
if (v.HasValue) w.WriteNumber(name, v.Value);
|
||||
else w.WriteNull(name);
|
||||
}
|
||||
|
||||
private static void WriteStrings(Utf8JsonWriter w, string name, List<string> list)
|
||||
{
|
||||
w.WriteStartArray(name);
|
||||
foreach (string s in list) w.WriteStringValue(s);
|
||||
w.WriteEndArray();
|
||||
}
|
||||
|
||||
/// <summary>One line back into a press, or null when it isn't one. Unknown fields are ignored, missing ones left empty.</summary>
|
||||
internal static Press? FromJson(string line)
|
||||
{
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(line);
|
||||
JsonElement r = doc.RootElement;
|
||||
if (r.ValueKind != JsonValueKind.Object) return null;
|
||||
var p = new Press
|
||||
{
|
||||
Id = Str(r, "id"),
|
||||
Server = Str(r, "server"),
|
||||
Character = Str(r, "character"),
|
||||
Fragment = Str(r, "fragment"),
|
||||
FragmentLevel = IntOrNull(r, "fragmentLevel"),
|
||||
Tool = Str(r, "tool"),
|
||||
Outcome = Str(r, "outcome"),
|
||||
ComponentsSeen = Bool(r, "componentsSeen"),
|
||||
Components = Strings(r, "components"),
|
||||
RandomNote = Str(r, "random"),
|
||||
ResultLevel = IntOrNull(r, "resultLevel"),
|
||||
Entries = IntOrNull(r, "entries"),
|
||||
Complete = Bool(r, "complete"),
|
||||
End = Str(r, "end"),
|
||||
Raw = Strings(r, "raw"),
|
||||
Extra = Strings(r, "extra"),
|
||||
};
|
||||
p.Components.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
if (DateTime.TryParse(Str(r, "time"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t))
|
||||
p.TimeUtc = t.ToUniversalTime();
|
||||
if (r.TryGetProperty("modifiers", out JsonElement mods) && mods.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement m in mods.EnumerateArray())
|
||||
{
|
||||
if (m.ValueKind != JsonValueKind.Object) continue;
|
||||
var gm = new GemModifier { Name = Str(m, "name"), Description = Str(m, "description") };
|
||||
if (gm.Name.Length == 0) continue;
|
||||
if (m.TryGetProperty("numbers", out JsonElement nums) && nums.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement n in nums.EnumerateArray())
|
||||
if (n.ValueKind == JsonValueKind.Object && n.TryGetProperty("value", out JsonElement v) && v.TryGetDouble(out double d))
|
||||
gm.Numbers.Add(new ModNumber(d, Str(n, "kind"), Str(n, "text")));
|
||||
p.Modifiers.Add(gm);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Str(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty;
|
||||
|
||||
private static bool Bool(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True;
|
||||
|
||||
private static int? IntOrNull(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : null;
|
||||
|
||||
private static List<string> Strings(JsonElement o, string name)
|
||||
{
|
||||
var list = new List<string>();
|
||||
if (o.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement e in a.EnumerateArray())
|
||||
if (e.ValueKind == JsonValueKind.String) list.Add(e.GetString() ?? string.Empty);
|
||||
return list;
|
||||
}
|
||||
|
||||
// ── CSV ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Writes every press as CSV into this folder (presses-yyyyMMdd-HHmmss.csv). Returns the path.</summary>
|
||||
public string ExportCsv(DateTime localNow)
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
string path = Path.Combine(Folder, "presses-" + localNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + ".csv");
|
||||
File.WriteAllText(path, Csv(_presses), new UTF8Encoding(true));
|
||||
return path;
|
||||
}
|
||||
|
||||
internal static string Csv(IEnumerable<Press> presses)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("time_utc,server,character,fragment,fragment_level,outcome,components,result_level,entries,complete,modifier_count,modifiers\r\n");
|
||||
foreach (Press p in presses)
|
||||
{
|
||||
var mods = new List<string>();
|
||||
foreach (GemModifier m in p.Modifiers) mods.Add(m.Name + ": " + m.Description);
|
||||
Cell(sb, p.TimeUtc.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)); sb.Append(',');
|
||||
Cell(sb, p.Server); sb.Append(',');
|
||||
Cell(sb, p.Character); sb.Append(',');
|
||||
Cell(sb, p.Fragment); sb.Append(',');
|
||||
Cell(sb, p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(',');
|
||||
Cell(sb, p.Outcome); sb.Append(',');
|
||||
Cell(sb, string.Join("; ", p.Components)); sb.Append(',');
|
||||
Cell(sb, p.ResultLevel?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(',');
|
||||
Cell(sb, p.Entries?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(',');
|
||||
Cell(sb, p.Complete ? "yes" : "no (" + p.End + ")"); sb.Append(',');
|
||||
Cell(sb, p.Modifiers.Count.ToString(CultureInfo.InvariantCulture)); sb.Append(',');
|
||||
Cell(sb, string.Join(" | ", mods));
|
||||
sb.Append("\r\n");
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static void Cell(StringBuilder sb, string s)
|
||||
{
|
||||
// A spreadsheet would run a cell starting with = + - @ as a formula: start it with ' instead.
|
||||
if (s.Length > 0 && s[0] is '=' or '+' or '-' or '@') s = "'" + s;
|
||||
bool quote = s.IndexOfAny(new[] { ',', '"', '\n', '\r' }) >= 0;
|
||||
if (!quote) { sb.Append(s); return; }
|
||||
sb.Append('"').Append(s.Replace("\"", "\"\"")).Append('"');
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue