Snapshot for release 2026.10.6.1 (internal 1cbe514)
This commit is contained in:
parent
913a2a00b6
commit
abf9146a5b
93 changed files with 10168 additions and 597 deletions
|
|
@ -127,8 +127,8 @@ internal static class EngineFrameController
|
|||
// between launches. Allocated once, kept alive for the process lifetime.
|
||||
try
|
||||
{
|
||||
const string iniPath = @"C:\Games\RynthSuite\RynthAi\imgui.ini";
|
||||
System.IO.Directory.CreateDirectory(@"C:\Games\RynthSuite\RynthAi");
|
||||
string iniPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini");
|
||||
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
|
||||
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
|
||||
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
|
||||
RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}");
|
||||
|
|
@ -500,7 +500,8 @@ internal static class EngineFrameController
|
|||
if (Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled) return true;
|
||||
if (!PanelsLive) return false;
|
||||
ImGuiPanelHost.RestoreOnce();
|
||||
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame;
|
||||
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame
|
||||
|| D3D9.VideoPatch.WantsBanner;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -543,7 +544,7 @@ internal static class EngineFrameController
|
|||
}
|
||||
|
||||
private static bool HasImGuiContentNoRestore() =>
|
||||
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame));
|
||||
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner));
|
||||
|
||||
// Keyboard owner between the stacks (plan §3.2 d): whichever side started
|
||||
// text entry most recently keeps the keyboard.
|
||||
|
|
@ -661,7 +662,10 @@ internal static class EngineFrameController
|
|||
{
|
||||
// World overlays: built into UnderUiLayer's list, drawn next frame at
|
||||
// AC's 3D->UI transition (under AC's UI and every panel), no input.
|
||||
Hud.MonsterHud.Draw(_uiScale);
|
||||
// Video patch: with no 3D scene only the screen-fixed player plate draws.
|
||||
Hud.MonsterHud.Draw(_uiScale, worldVisible: !D3D9.VideoPatch.SkipWorldThisFrame);
|
||||
// Video patch "all": the "rendering paused" banner (background list, under the panels).
|
||||
VideoPatchBanner.Draw();
|
||||
if (ImGuiBar.Visible)
|
||||
ImGuiBar.Draw(_uiScale);
|
||||
ImGuiPanelHost.DrawAll(_uiScale);
|
||||
|
|
|
|||
|
|
@ -45,7 +45,8 @@ internal static class ImGuiBar
|
|||
bool ImGuiOnly = false);
|
||||
|
||||
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
|
||||
private static readonly string[] ImGuiOnlyBarPanels = { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title };
|
||||
private static readonly string[] ImGuiOnlyBarPanels =
|
||||
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title };
|
||||
|
||||
// Known panels' icons (DrakBot's where the same window exists); others show their first letter.
|
||||
private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase)
|
||||
|
|
@ -69,6 +70,8 @@ internal static class ImGuiBar
|
|||
["Status"] = PhosphorIcons.Info,
|
||||
["Inventory"] = PhosphorIcons.Package, // not Backpack: the dashboard's Items launcher has that
|
||||
["Log"] = PhosphorIcons.TerminalWindow,
|
||||
["Item Count"] = PhosphorIcons.Bag,
|
||||
["Mini Remote"] = PhosphorIcons.SquaresFour,
|
||||
};
|
||||
|
||||
/// <summary>A panel's bar icon: its Phosphor icon, else its first letter (letter = true).</summary>
|
||||
|
|
|
|||
|
|
@ -676,7 +676,7 @@ internal static unsafe class ImGuiPopOuts
|
|||
public static string? RequestSnapshot(string title)
|
||||
{
|
||||
if (!Pops.TryGetValue(title, out PopOut? pop)) return null;
|
||||
string path = System.IO.Path.Combine(@"C:\Games\RynthCore\Logs", $"popout_{title.Replace(' ', '_')}.bmp");
|
||||
string path = System.IO.Path.Combine(LogPaths.LogDirectory, $"popout_{title.Replace(' ', '_')}.bmp");
|
||||
pop.Surface.SnapshotPath = path;
|
||||
pop.HotFrames = Math.Max(pop.HotFrames, 2);
|
||||
return path;
|
||||
|
|
|
|||
|
|
@ -714,16 +714,24 @@ internal static class MonsterHud
|
|||
public ImDrawListPtr Dl;
|
||||
}
|
||||
|
||||
/// <summary>AC's render thread, inside the ImGui frame (between NewFrame and Render).</summary>
|
||||
public static void Draw(float uiScale)
|
||||
/// <summary>
|
||||
/// AC's render thread, inside the ImGui frame (between NewFrame and Render).
|
||||
/// <paramref name="worldVisible"/> false (the video patch skipped AC's 3D scene): only
|
||||
/// the screen-fixed player plate draws; the world-anchored plates and combat text don't
|
||||
/// (nothing to anchor them to, and no invisible plate takes a click).
|
||||
/// </summary>
|
||||
public static void Draw(float uiScale, bool worldVisible = true)
|
||||
{
|
||||
if (!_hasContent) { ResetClick(); PlayerPlate.DropDrag(); return; }
|
||||
try
|
||||
{
|
||||
if (!TryBeginFrame(uiScale, out Frame f)) { ResetClick(); PlayerPlate.DropDrag(); return; }
|
||||
DrawPlates(ref f, MonsterHudSettings.Enabled);
|
||||
PlayerPlate.Draw(ref f);
|
||||
CombatText.Draw(ref f);
|
||||
if (worldVisible)
|
||||
{
|
||||
DrawPlates(ref f, MonsterHudSettings.Enabled);
|
||||
PlayerPlate.Draw(ref f);
|
||||
CombatText.Draw(ref f);
|
||||
}
|
||||
// The player plate fixed on screen: ImGui's background list (the normal UI pass), not the layer above.
|
||||
PlayerPlate.DrawScreen(ref f);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,14 +3,17 @@
|
|||
// ImGui face of the RynthChat rule editor (the old Avalonia face is
|
||||
// UI/Panels/RynthChatFiltersPanel.cs). One card per rule:
|
||||
//
|
||||
// [#] [on] [regex ..........................] [up] [down] [delete]
|
||||
// [#] [on] [Contains v] [pattern ...................] [up] [down] [delete]
|
||||
// When [Any line v] [Move to v] [Junk v] [Colour line v] [swatch]
|
||||
// (a regex error, a timed-out rule, a missing tab, or its hit count)
|
||||
//
|
||||
// The order and what each action does are spelled out in the header lines
|
||||
// (and in UI/Data/ChatData.cs). Below the rules: Add, Import / Export (the
|
||||
// clipboard, JSON), and a test box - paste a line, pick where it came from,
|
||||
// and see which rules match and where it ends up. The test runs on an edit,
|
||||
// (and in UI/Data/ChatData.cs). A pattern is plain text (Contains, Starts
|
||||
// with, Ends with) or a regex (ChatRuleMatching.cs). Below the rules: Add,
|
||||
// Standard filters (ready-made Hide rules, ChatFilterPresets.cs), Import /
|
||||
// Export (the clipboard, JSON), and a test box - paste a line, pick where it
|
||||
// came from, and see which rules match and where it ends up, which standard
|
||||
// filter would catch it, or make a rule from it. The test runs on an edit,
|
||||
// never per frame; the chat itself is routed on the pump.
|
||||
//
|
||||
// The rules live in ChatModel. Each edit applies (the pump re-routes the
|
||||
|
|
@ -62,12 +65,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
private int _testSourceSeen = -1;
|
||||
private long _testVersion = -1;
|
||||
private readonly List<(string Text, uint Color)> _testResult = new();
|
||||
private string _testLine = ""; // the tested text, timestamp removed ("Make rule" uses it)
|
||||
|
||||
public void OnShown() => ChatModel.EnsureSettingsLoaded();
|
||||
|
||||
private const string AddLabel = PhosphorIcons.Plus + " Add rule";
|
||||
private const string ImportLabel = PhosphorIcons.ClipboardText + " Import";
|
||||
private const string ExportLabel = PhosphorIcons.Copy + " Export";
|
||||
private const string PresetsLabel = PhosphorIcons.ListChecks + " Standard filters";
|
||||
private const string MakeRuleLabel = PhosphorIcons.Plus + " Make rule";
|
||||
private const string Caret = " " + PhosphorIcons.CaretDown;
|
||||
|
||||
private static readonly string[] ActionLabels = { "Move to", "Copy to", "Hide", "Colour only" };
|
||||
|
|
@ -79,6 +85,20 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
"Colour only: no routing; the rule just colours.",
|
||||
};
|
||||
private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match" };
|
||||
private static readonly string[] ModeHelp =
|
||||
{
|
||||
"Regex: a case-insensitive regular expression (^ start, $ end, \\d+ a number...).",
|
||||
"Contains: the text anywhere in the line. Any case; . ( * \" are just characters.",
|
||||
"Starts with: the line begins with the text. Any case.",
|
||||
"Ends with: the line ends with the text. Any case.",
|
||||
};
|
||||
private static readonly string[] ModeHints =
|
||||
{
|
||||
"regex, e.g. ^You have been healed",
|
||||
"text, e.g. evaded your attack",
|
||||
"text, e.g. You say, \"",
|
||||
"text, e.g. has expired.",
|
||||
};
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
|
|
@ -94,7 +114,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
}
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text, as a case-insensitive regex.", Mute);
|
||||
Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text: plain text (any case) or a regex.", Mute);
|
||||
Label("Where it shows: Copy rules add a tab and go on; the first Move or Hide that matches decides.", Mute);
|
||||
Label("Colour: the first \"Colour line\" wins; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
|
@ -127,10 +147,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
if (Button("##add", AddLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(AddLabel) + 4, 24), Text, AddBg))
|
||||
{
|
||||
// An empty pattern matches nothing until typed; saved now so the row survives a relaunch mid-edit.
|
||||
var rule = new ChatFilterRule();
|
||||
// New rules are plain text (Contains); rules made from a chat line stay regexes.
|
||||
var rule = new ChatFilterRule { Mode = ChatMatchMode.Contains };
|
||||
edit = () => ChatModel.AddRule(rule);
|
||||
}
|
||||
bx += ButtonWidth(AddLabel) + 8;
|
||||
bx += ButtonWidth(AddLabel) + 4;
|
||||
if (Button("##presets", PresetsLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(PresetsLabel), 24), Text, BtnFill))
|
||||
OpenPresetPicker(new Vector2(bx, ap.Y));
|
||||
ImGuiNET.ImGui.SetItemTooltip("Ready-made rules that hide common game spam (spell words, evades, busy...).\nPicking one adds it as a Hide rule you can edit or delete.");
|
||||
bx += ButtonWidth(PresetsLabel) + 8;
|
||||
if (Button("##import", ImportLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(ImportLabel), 24), Text, BtnFill))
|
||||
Flash(ChatModel.ImportRules(ChatModel.GetClipboardText()));
|
||||
ImGuiNET.ImGui.SetItemTooltip("Add the rules on the clipboard (an Export, or a rynthchat_settings.json) after these.");
|
||||
|
|
@ -186,8 +211,21 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
|
||||
const float btn = 22;
|
||||
float x = p.X + 42;
|
||||
int modeIdx = (int)r.Mode;
|
||||
string modeText = ChatRuleMatching.Labels[modeIdx] + Caret;
|
||||
float modeW = ButtonWidth(ChatRuleMatching.Labels[2] + Caret); // the widest, so patterns line up
|
||||
ChatFilterRule moded = r;
|
||||
if (Button("##mode", modeText, new Vector2(x, p.Y), new Vector2(modeW, rowH), Text, BtnFill, leftAlign: true))
|
||||
_picker.Open(new Vector2(x, p.Y + rowH + 2), ChatRuleMatching.Labels, modeIdx, k =>
|
||||
{
|
||||
moded.Mode = (ChatMatchMode)k;
|
||||
moded.Recompile();
|
||||
ChatModel.FiltersChanged();
|
||||
}, 120);
|
||||
ImGuiNET.ImGui.SetItemTooltip(ModeHelp[modeIdx]);
|
||||
x += modeW + 4;
|
||||
float patW = Math.Max(80, card.X + rowW - 4 - 3 * (btn + 2) - 4 - x);
|
||||
if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, "regex, e.g. ^You have been healed", out bool patActive))
|
||||
if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, ModeHints[modeIdx], out bool patActive))
|
||||
{
|
||||
r.Pattern = Utf8(b.Pattern);
|
||||
r.Recompile();
|
||||
|
|
@ -255,7 +293,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
rule.ColorMode = (ChatColorMode)k;
|
||||
ChatModel.FiltersChanged();
|
||||
}, 130);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the regex matched.");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the rule matched.");
|
||||
if (r.ColorMode != ChatColorMode.None)
|
||||
{
|
||||
Vector2 sPos = flow.Place(rowH);
|
||||
|
|
@ -314,7 +352,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
|
||||
private static (string? Note, uint Color) RuleNote(ChatFilterRule r)
|
||||
{
|
||||
if (r.Pattern.Length == 0) return ("Type a pattern: the rule matches nothing until then.", Faded(Mute));
|
||||
if (r.Pattern.Trim().Length == 0) return ("Type a pattern: the rule matches nothing until then.", Faded(Mute));
|
||||
if (r.Invalid) return ("Regex error: " + (r.Error ?? "doesn't compile"), Red);
|
||||
if (r.Slow) return ("Too slow: matching it took too long (see the RynthCore log), so the rule is skipped. Edit the pattern to try again.", Amber);
|
||||
if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy && r.Tab.Length == 0)
|
||||
|
|
@ -341,6 +379,20 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>The standard filters; a tick marks the ones already in the rules (picking one again turns it on).</summary>
|
||||
private void OpenPresetPicker(Vector2 at)
|
||||
{
|
||||
ChatFilterPreset[] presets = ChatFilterPresets.All;
|
||||
var labels = new string[presets.Length];
|
||||
for (int k = 0; k < presets.Length; k++)
|
||||
{
|
||||
ChatFilterRule? have = ChatModel.FindPresetRule(presets[k]);
|
||||
string mark = have == null ? " " : have.Enabled ? PhosphorIcons.Check + " " : "(off) ";
|
||||
labels[k] = mark + presets[k].PickerLabel;
|
||||
}
|
||||
_picker.Open(at + new Vector2(0, 26), labels, -1, k => Flash(ChatModel.AddPresetRule(presets[k])), 300);
|
||||
}
|
||||
|
||||
private void OpenWhenPicker(ChatFilterRule rule, Vector2 at)
|
||||
{
|
||||
var labels = new string[ChatModel.Conditions.Length];
|
||||
|
|
@ -427,7 +479,18 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
string srcLabel = "from: " + ChatModel.Conditions[_testSource].Label + Caret;
|
||||
float srcW = Math.Min(ButtonWidth(srcLabel), 230);
|
||||
TextBox("##test", _test, p, Math.Max(80, w - srcW - 4), "e.g. Bob tells you, \"hi\"", out _);
|
||||
float makeW = ButtonWidth(MakeRuleLabel);
|
||||
TextBox("##test", _test, p, Math.Max(80, w - srcW - makeW - 8), "e.g. Bob tells you, \"hi\"", out _);
|
||||
var mp = new Vector2(p.X + w - srcW - makeW - 4, p.Y);
|
||||
if (Button("##makerule", MakeRuleLabel, mp, new Vector2(makeW, 22), Text, AddBg, _testLine.Length > 0))
|
||||
{
|
||||
// Plain text, held to where the line came from; pick what it does on the new card.
|
||||
string when = ChatModel.Conditions[_testSource].Value;
|
||||
string pattern = _testLine.Length > 140 ? _testLine[..140] : _testLine;
|
||||
ChatModel.AddRule(new ChatFilterRule { Mode = ChatMatchMode.Contains, Pattern = pattern, When = when });
|
||||
Flash("Made a Contains rule from the test line: trim it down and pick what it does.");
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Add a rule that matches this line as plain text (Contains), for lines from the source picked here.");
|
||||
var sp = new Vector2(p.X + w - srcW, p.Y);
|
||||
if (Button("##testsrc", srcLabel, sp, new Vector2(srcW, 22), Text, BtnFill, leftAlign: true))
|
||||
{
|
||||
|
|
@ -468,6 +531,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
text = text.Trim();
|
||||
// A line copied from the chat starts with its timestamp; the rules never see that.
|
||||
if (text.Length > 9 && text[2] == ':' && text[5] == ':' && text[8] == ' ' && char.IsDigit(text[0])) text = text[9..];
|
||||
_testLine = text;
|
||||
if (text.Length == 0) { _testResult.Add(("Paste a line to see which rules match and where it goes.", Faded(Mute))); return; }
|
||||
|
||||
string when = ChatModel.Conditions[_testSource].Value;
|
||||
|
|
@ -498,6 +562,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
}
|
||||
uint color = RynthTheme.Argb(route.LineArgb ?? ChatModel.ChannelArgb(channel));
|
||||
_testResult.Add((where + (route.LineArgb != null ? " (this is its colour)" : ""), route.Hidden ? Faded(Mute) : color));
|
||||
|
||||
// Not hidden: name a standard filter that would hide it (one not in the rules yet).
|
||||
if (!route.Hidden)
|
||||
foreach (ChatFilterPreset preset in ChatFilterPresets.All)
|
||||
if (preset.Matches(text, channel, type) && ChatModel.FindPresetRule(preset) == null)
|
||||
{
|
||||
_testResult.Add(($"Standard filter \"{preset.PickerLabel}\" would hide it (Standard filters, above).", Teal));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Buffers for each rule; refilled from the rules when another face changed them,
|
||||
|
|
|
|||
|
|
@ -122,6 +122,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
InventoryModel.Hover(0);
|
||||
InventoryModel.Unsubscribe();
|
||||
_dragItem = _pressItem = null;
|
||||
UiDropTargets.EngineDragObject = 0;
|
||||
_lootAdd.Cancel();
|
||||
}
|
||||
|
||||
|
|
@ -152,6 +153,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
|
||||
InventoryModel.Hover(_dragItem == null ? _hover?.Id ?? 0 : 0);
|
||||
FinishDrag();
|
||||
UiDropTargets.EngineDragObject = _dragItem?.Id ?? 0;
|
||||
End(origin, size);
|
||||
|
||||
Tooltip();
|
||||
|
|
@ -756,6 +758,10 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
DropOn(t.Kind, t.Id, t.Name, item);
|
||||
return;
|
||||
}
|
||||
// Let go outside this panel: another engine panel that takes items (Item Count,
|
||||
// Mini Remote, the Loot Editor) gets it, as with a drag out of AC's own inventory.
|
||||
if (!ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem))
|
||||
UiDropTargets.TryClaim(item.Id, 0, out _);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
249
src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs
Normal file
249
src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/ItemCountFace.cs
|
||||
// The Item Count panel: chosen items by name, each with how many the character
|
||||
// carries (every stack with that name, whole stacks summed; worn ones too, so
|
||||
// wielded arrows count). Engine only, ImGui only. (An idea from Silentkelpie's
|
||||
// rynth PR #1, done as an engine face.)
|
||||
//
|
||||
// add row a text box (Enter adds), Add, and "add the selected item"
|
||||
// rows icon, name, count (amber when none carried); X removes
|
||||
// drop drag an item from the game's inventory (or the Inventory panel)
|
||||
// onto the panel to add its name (UiDropTargets)
|
||||
//
|
||||
// Data: InventoryModel's published view (the face subscribes while open) and
|
||||
// ItemHudStore (item_huds.txt, per character). Draw reads snapshots and posts
|
||||
// edits; no AC calls except a dropped item's name when it isn't carried (the
|
||||
// Loot Editor's way); no file I/O; counts are worked out when the view or the
|
||||
// list changes, not per frame.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class ItemCountFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Item Count";
|
||||
private const string DropKey = "ItemCount";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(250, 230), new Vector2(170, 110), EdgeToEdge: true, GripInBody: true),
|
||||
() => new ItemCountFace());
|
||||
ItemHudStore.EnsureLoadQueued();
|
||||
}
|
||||
|
||||
private const float RowH = 22f, Icon = 18f, XW = 18f;
|
||||
|
||||
private readonly byte[] _input = new byte[ItemHudCharacter.MaxNameLength + 1];
|
||||
private readonly HudItemCache _items = new();
|
||||
private string _message = "";
|
||||
private uint _messageColor;
|
||||
private long _messageUntilMs;
|
||||
|
||||
// Counts for the shown list, rebuilt when the carried items or the list change.
|
||||
private int _countsItemsVersion = -1;
|
||||
private ItemHudCharacter? _countsFor;
|
||||
private string[] _countText = Array.Empty<string>();
|
||||
private bool[] _none = Array.Empty<bool>();
|
||||
private uint[] _iconId = Array.Empty<uint>();
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
ItemHudStore.EnsureLoadQueued();
|
||||
InventoryModel.Subscribe();
|
||||
}
|
||||
|
||||
public void OnHidden() => InventoryModel.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
InventoryView view = InventoryModel.Current;
|
||||
HudItem[] items = _items.Get(view);
|
||||
ItemHudCharacter data = ItemHudStore.Current;
|
||||
|
||||
DrawAddRow(w, view, items);
|
||||
DrawStatus(view);
|
||||
float bodyH = Math.Max(30, Remaining(origin, size) - GripOverlap());
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
|
||||
ImGuiNET.ImGui.BeginChild("##itemcount_rows", new Vector2(w, bodyH));
|
||||
DrawRows(data, items);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
End(origin, size);
|
||||
|
||||
AcceptDrops(origin, size, items);
|
||||
}
|
||||
|
||||
// ── Add row ─────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawAddRow(float w, InventoryView view, HudItem[] items)
|
||||
{
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float h = 22, iconW = 22;
|
||||
string addLabel = PhosphorIcons.Plus + " Add";
|
||||
float addW = ButtonWidth(addLabel);
|
||||
float boxW = Math.Max(50, w - addW - iconW - 8);
|
||||
bool ready = ItemHudStore.Loaded && ItemHudStore.HasCharacter;
|
||||
|
||||
bool enter = TextBox("##itemcount_input", _input, start, boxW, "Item name", out _, ImGuiInputTextFlags.EnterReturnsTrue, h);
|
||||
bool add = Button("##itemcount_add", addLabel, new Vector2(start.X + boxW + 4, start.Y), new Vector2(addW, h), Text, BtnFill, enabled: ready);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Count this item (Enter in the box does the same). The name must match the item's name; any case.");
|
||||
if (enter || add)
|
||||
{
|
||||
string text = Utf8(_input);
|
||||
if (Add(text)) WriteUtf8(_input, "");
|
||||
}
|
||||
|
||||
uint sel = InventoryModel.SelectedItem;
|
||||
bool haveSel = ready && sel != 0 && ItemHudMath.TryFind(items, sel, out _);
|
||||
if (IconButton("##itemcount_sel", PhosphorIcons.Crosshair, new Vector2(start.X + boxW + 4 + addW + 4, start.Y), new Vector2(iconW, h), Text, BtnFill, enabled: haveSel))
|
||||
{
|
||||
if (ItemHudMath.TryFind(items, sel, out HudItem it)) Add(it.Name);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(haveSel ? "Count the selected item" : "Select an item in your inventory to count it (or drag one onto this panel)");
|
||||
NextLine(start, h + 4);
|
||||
}
|
||||
|
||||
private bool Add(string name)
|
||||
{
|
||||
string msg = "";
|
||||
bool ok = ItemHudStore.Update(d => d.WithCount(name, out msg), out string why);
|
||||
if (!ok) { ShowMessage(why, Amber); return false; }
|
||||
bool added = msg.StartsWith("Counting", StringComparison.Ordinal);
|
||||
ShowMessage(msg, added ? Mute : Amber);
|
||||
return added;
|
||||
}
|
||||
|
||||
private void ShowMessage(string text, uint color)
|
||||
{
|
||||
_message = text;
|
||||
_messageColor = color;
|
||||
_messageUntilMs = Environment.TickCount64 + 3000;
|
||||
}
|
||||
|
||||
private void DrawStatus(InventoryView view)
|
||||
{
|
||||
if (_message.Length > 0 && Environment.TickCount64 < _messageUntilMs) { Label(_message, _messageColor); return; }
|
||||
if (!ItemHudStore.Loaded) Label("Loading...", Mute);
|
||||
else if (!ItemHudStore.HasCharacter || view.PlayerId == 0) Label("Waiting for your character...", Mute);
|
||||
else Label("Carried (all stacks):", Faded(Mute));
|
||||
}
|
||||
|
||||
// ── Rows ────────────────────────────────────────────────────────────
|
||||
|
||||
private void RefreshCounts(ItemHudCharacter data, HudItem[] items)
|
||||
{
|
||||
if (ReferenceEquals(data, _countsFor) && _countsItemsVersion == _items.Version) return;
|
||||
_countsFor = data;
|
||||
_countsItemsVersion = _items.Version;
|
||||
int n = data.Counts.Length;
|
||||
_countText = new string[n];
|
||||
_none = new bool[n];
|
||||
_iconId = new uint[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
long c = ItemHudMath.Count(items, data.Counts[i]);
|
||||
_countText[i] = c.ToString("N0", CultureInfo.InvariantCulture);
|
||||
_none[i] = c == 0;
|
||||
_iconId[i] = _items.IdOf(data.Counts[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawRows(ItemHudCharacter data, HudItem[] items)
|
||||
{
|
||||
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
if (data.Counts.Length == 0)
|
||||
{
|
||||
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(6, 6);
|
||||
dl.AddText(at, Faded(Mute), "Nothing counted yet: type a name above,\nor drag an item here.");
|
||||
return;
|
||||
}
|
||||
RefreshCounts(data, items);
|
||||
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float fontH = ImGuiNET.ImGui.GetFontSize();
|
||||
int remove = -1;
|
||||
for (int i = 0; i < data.Counts.Length; i++)
|
||||
{
|
||||
var p = new Vector2(start.X, start.Y + i * RowH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw - XW, RowH));
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (hot) ImGuiNET.ImGui.SetItemTooltip($"{data.Counts[i]}: {_countText[i]} carried");
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + bw - XW, p.Y));
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(XW, RowH))) remove = i;
|
||||
bool hotX = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (hotX) ImGuiNET.ImGui.SetItemTooltip("Stop counting");
|
||||
ImGuiNET.ImGui.PopID();
|
||||
|
||||
uint bg = hot ? Lighten(PanelBg) : (i & 1) == 1 ? RowAlt : 0;
|
||||
if (bg != 0) dl.AddRectFilled(p, p + new Vector2(bw, RowH), bg);
|
||||
Vector2 ip = new(p.X + 3, p.Y + (RowH - Icon) * 0.5f);
|
||||
if (_iconId[i] != 0 && ScriptIcons.TryGet(ScriptIconKind.Object, _iconId[i], out IntPtr tex))
|
||||
dl.AddImage(tex, ip, ip + new Vector2(Icon, Icon));
|
||||
else
|
||||
dl.AddRect(ip, ip + new Vector2(Icon, Icon), Faded(BtnBord), 2);
|
||||
|
||||
float ty = p.Y + (RowH - fontH) * 0.5f;
|
||||
Vector2 cs = ImGuiNET.ImGui.CalcTextSize(_countText[i]);
|
||||
float countX = p.X + bw - XW - 6 - cs.X;
|
||||
dl.PushClipRect(new Vector2(p.X + Icon + 8, p.Y), new Vector2(countX - 6, p.Y + RowH), true);
|
||||
dl.AddText(new Vector2(p.X + Icon + 8, ty), _none[i] ? Faded(Text) : Text, data.Counts[i]);
|
||||
dl.PopClipRect();
|
||||
dl.AddText(new Vector2(countX, ty), _none[i] ? Amber : Teal, _countText[i]);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.X, new Vector2(p.X + bw - XW, p.Y), new Vector2(XW, RowH),
|
||||
hotX ? Red : Faded(Mute));
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(start);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(bw, data.Counts.Length * RowH));
|
||||
|
||||
if (remove >= 0)
|
||||
{
|
||||
string name = data.Counts[remove];
|
||||
if (ItemHudStore.Update(d => d.WithoutCount(d.IndexOfCount(name)), out string why))
|
||||
ShowMessage($"Stopped counting \"{name}\".", Mute);
|
||||
else ShowMessage(why, Amber);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Drops (an item dragged from the game's inventory or the Inventory panel) ──
|
||||
|
||||
private void AcceptDrops(Vector2 origin, Vector2 size, HudItem[] items)
|
||||
{
|
||||
bool can = ItemHudStore.Loaded && ItemHudStore.HasCharacter;
|
||||
UiDropTargets.Publish(DropKey, Title, origin, origin + size, can);
|
||||
if (UiDropTargets.TryTake(DropKey, out uint itemId) && can)
|
||||
{
|
||||
string name = NameOf(itemId, items);
|
||||
if (name.Length > 0) Add(name);
|
||||
else ShowMessage("That item's name isn't known yet; try again in a moment.", Amber);
|
||||
}
|
||||
|
||||
if (!can || !UiDropTargets.AnyDragInProgress) return;
|
||||
bool over = UiDropTargets.IsCursorOver(DropKey);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRect(origin + new Vector2(1, 1), origin + size - new Vector2(1, 1), over ? Green : Teal, 4, ImDrawFlags.None, over ? 3f : 1.5f);
|
||||
}
|
||||
|
||||
/// <summary>A dropped item's name: from the carried items, else the client's (a corpse's or chest's item).</summary>
|
||||
internal static string NameOf(uint itemId, HudItem[] items)
|
||||
{
|
||||
if (ItemHudMath.TryFind(items, itemId, out HudItem it) && it.Name.Length > 0) return it.Name;
|
||||
if (ClientObjectHooks.TryGetSnapshotName(itemId, out string n) && n.Length > 0) return n;
|
||||
return ClientObjectHooks.TryGetObjectName(itemId, out n) ? n ?? string.Empty : string.Empty;
|
||||
}
|
||||
}
|
||||
671
src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs
Normal file
671
src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs
Normal file
|
|
@ -0,0 +1,671 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/MetaFace.Editor.cs
|
||||
// The Meta panel's rule editor and its state pickers (2026-10-05 clean-up):
|
||||
//
|
||||
// [<- Back] Edit rule Saved
|
||||
// State: [Combat v]
|
||||
// +- Conditions ------ [+ Add] -+ +- Actions --------- [+ Add] -+
|
||||
// | [Landblock == v] | | [Chat Command v] |
|
||||
// | [A9B40000 ][Set current] | | [/say hello ] |
|
||||
// +-----------------------------+ +-----------------------------+
|
||||
// [Revert] [Delete rule]
|
||||
//
|
||||
// Conditions and Actions sit side by side, each scrolling on its own; under
|
||||
// SideBySideMinWidth they stack. "+ Add" turns a single condition into the
|
||||
// first of an All (a single action into the first of a DoAll), or adds one
|
||||
// more to an All / Any / DoAll.
|
||||
//
|
||||
// Saving: every change marks the rule dirty (MetaAutosave); 0.75 s after the
|
||||
// last change, and never while a text box is being typed in, the rule goes
|
||||
// to RynthAi as add_rule (a new rule, the first time, and only once its
|
||||
// condition and action are filled in: MetaRuleEdit.ReadyToAdd) or
|
||||
// update_rule, and RynthAi writes the file. Back, closing the panel and switching metas save
|
||||
// at once. update_rule keeps the running rule's fired latch (RynthAi
|
||||
// MetaRuleEdits), so a save never re-fires a rule, restarts the state's
|
||||
// clocks or changes the current state.
|
||||
//
|
||||
// New states: every state picker (the rule's State, Set / Call Meta State
|
||||
// targets, the bottom bar) ends with "+ New state...". Picking it turns the
|
||||
// picker into a name box with OK / Cancel (Enter / Esc); the name is trimmed,
|
||||
// must not be empty, contain { } or match an existing state (ignoring case,
|
||||
// as RynthAi does). A state exists only while a rule uses it (RynthAi lists
|
||||
// its rules' states; the .af file has a STATE: block per state with rules),
|
||||
// so a new state is never left empty:
|
||||
// - the rule's own State picker moves this rule into it;
|
||||
// - a Set / Call Meta State target and the bottom bar add an empty
|
||||
// Never -> None rule in it at once (it never fires; edit or delete it).
|
||||
// The bottom bar also makes it the current state, like any state picked
|
||||
// there, and opens that rule.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed partial class MetaFace
|
||||
{
|
||||
/// <summary>Under this width Conditions and Actions stack instead of sitting side by side.</summary>
|
||||
private const float SideBySideMinWidth = 400;
|
||||
|
||||
private MetaRuleDto? _editOriginal; // as opened (Revert); null for a new rule
|
||||
private MetaRuleDto? _lastSaved; // as last sent to RynthAi; finds the rule again by content
|
||||
private bool _editChanged; // set by this frame's widgets
|
||||
private bool _typingNow, _editTyping; // a data box is being typed in (this frame / last frame)
|
||||
private bool _editConfirmDelete;
|
||||
private string _editFile = string.Empty; // the meta file the open rule belongs to
|
||||
private string _listNote = string.Empty; // shown over the rule list for a few seconds
|
||||
private long _listNoteAt;
|
||||
|
||||
// The one state picker turned into a name box (ImGui id, 0 = none).
|
||||
private uint _namingKey;
|
||||
private readonly byte[] _nameBuf = new byte[64];
|
||||
private bool _nameFocus, _nameWasActive;
|
||||
private string? _nameProblem;
|
||||
private const string NewStateEntry = PhosphorIcons.Plus + " New state...";
|
||||
|
||||
private const string BackLabel = PhosphorIcons.ArrowLeft + " Back";
|
||||
private const string AddLabel = PhosphorIcons.Plus + " Add";
|
||||
private const string SetCurrentLabel = PhosphorIcons.MapPin + " Set current";
|
||||
|
||||
// =====================================================================
|
||||
// Open / save / leave
|
||||
// =====================================================================
|
||||
|
||||
private void OpenEditor(int index, MetaRuleDto rule)
|
||||
{
|
||||
FlushEdit();
|
||||
_editIndex = index;
|
||||
_editFile = EditFileOf(_data.CurrentMetaPath);
|
||||
_editRule = index >= 0 ? rule.Clone() : rule;
|
||||
_editOriginal = index >= 0 ? rule.Clone() : null;
|
||||
_lastSaved = index >= 0 ? rule.Clone() : null;
|
||||
_autosave.Clear();
|
||||
_fields.Clear();
|
||||
_editConfirmDelete = false;
|
||||
_editTyping = false;
|
||||
CancelNaming();
|
||||
_view = View.Editor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Another meta was loaded while a rule was open (the Meta Manager, a chat command): the rule's
|
||||
/// index means nothing in that meta, so the editor closes without saving into it. RynthAi
|
||||
/// saving a .met as its .af is the same meta.
|
||||
/// </summary>
|
||||
private void EditorGuard()
|
||||
{
|
||||
if (string.Equals(_editFile, EditFileOf(_data.CurrentMetaPath), StringComparison.OrdinalIgnoreCase)) return;
|
||||
bool lost = _autosave.Dirty;
|
||||
_autosave.Clear();
|
||||
CancelNaming();
|
||||
_view = View.List;
|
||||
_listNote = lost
|
||||
? "Another meta was loaded while you edited a rule; your last change to it was not saved."
|
||||
: "Another meta was loaded, so the rule editor closed.";
|
||||
_listNoteAt = NowMs;
|
||||
}
|
||||
|
||||
private static string EditFileOf(string? metaPath) =>
|
||||
string.IsNullOrEmpty(metaPath) ? string.Empty : MetaBackupPlan.WrittenFile(metaPath);
|
||||
|
||||
private void LeaveEditor()
|
||||
{
|
||||
FlushEdit();
|
||||
CancelNaming();
|
||||
_view = View.List;
|
||||
}
|
||||
|
||||
/// <summary>Saves a pending edit now (Back, panel closed, meta switch).</summary>
|
||||
private void FlushEdit()
|
||||
{
|
||||
if (_view == View.Editor && _autosave.Dirty) CommitEdit();
|
||||
}
|
||||
|
||||
/// <summary>Sends the edited rule: add_rule the first time for a new rule, then update_rule.</summary>
|
||||
private void CommitEdit()
|
||||
{
|
||||
if (!string.Equals(_editFile, EditFileOf(_data.CurrentMetaPath), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
EditorGuard(); // never save into a meta loaded meanwhile
|
||||
return;
|
||||
}
|
||||
if (!_autosave.Take()) return;
|
||||
MetaRuleDto send = _editRule.Clone();
|
||||
if (_editIndex < 0)
|
||||
{
|
||||
_editIndex = _data.Rules.Count; // add_rule appends
|
||||
SendEdit(new MetaCmd { Op = "add_rule", Rule = send });
|
||||
_data.Rules.Add(send.Clone());
|
||||
}
|
||||
else
|
||||
{
|
||||
// Commands address rules by index: find the rule again in case the snapshot moved it.
|
||||
if (_lastSaved != null) _editIndex = MetaRuleEdit.Locate(_data.Rules, _lastSaved, _editIndex);
|
||||
SendEdit(new MetaCmd { Op = "update_rule", Index = _editIndex, Rule = send });
|
||||
if (_editIndex < _data.Rules.Count) _data.Rules[_editIndex] = send.Clone();
|
||||
}
|
||||
_lastSaved = send.Clone();
|
||||
RebuildCaches();
|
||||
}
|
||||
|
||||
private void DeleteEditedRule()
|
||||
{
|
||||
_autosave.Clear();
|
||||
if (_editIndex >= 0)
|
||||
{
|
||||
int index = _lastSaved != null ? MetaRuleEdit.Locate(_data.Rules, _lastSaved, _editIndex) : _editIndex;
|
||||
if (index >= 0 && index < _data.Rules.Count)
|
||||
{
|
||||
SendEdit(new MetaCmd { Op = "delete_rule", Index = index });
|
||||
_data.Rules.RemoveAt(index);
|
||||
_expanded.Clear();
|
||||
RebuildCaches();
|
||||
}
|
||||
}
|
||||
CancelNaming();
|
||||
_view = View.List;
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Editor view
|
||||
// =====================================================================
|
||||
|
||||
private void EditorView(Vector2 size)
|
||||
{
|
||||
_editChanged = false;
|
||||
_typingNow = false;
|
||||
MetaRuleDto r = _editRule;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float w = size.X;
|
||||
|
||||
// [<- Back] New rule / Edit rule Saved
|
||||
float backW = BtnW(BackLabel, 60);
|
||||
if (Button(BackLabel + "##back", top, new Vector2(backW, 22), Mute, BtnFill, BtnBord))
|
||||
{
|
||||
LeaveEditor();
|
||||
return;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Back to the rule list (saves this rule)");
|
||||
float indW = SaveIndicatorWidth(editor: true);
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
float tx = top.X + backW + 8;
|
||||
string title = _editIndex < 0 ? "New rule" : "Edit rule";
|
||||
ImGuiNET.ImGui.PushFont(bold);
|
||||
dl.AddText(new Vector2(tx, top.Y + (22 - bold.FontSize) * 0.5f), Teal, Fit(title, Math.Max(10, top.X + w - indW - 8 - tx)));
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
SaveIndicator(new Vector2(top.X + w - indW, top.Y), indW, 22);
|
||||
|
||||
// State: [picker]
|
||||
float y = top.Y + 26;
|
||||
float lw = ImGuiNET.ImGui.CalcTextSize("State:").X + 6;
|
||||
dl.AddText(new Vector2(top.X, y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "State:");
|
||||
string? state = StatePicker("##ed_state", r.State, _statePicks, IndexOf(_statePicks, r.State),
|
||||
new Vector2(top.X + lw, y), w - lw, out _);
|
||||
if (state != null && state != r.State)
|
||||
{
|
||||
r.State = state; // a new state is made by moving this rule into it
|
||||
_editChanged = true;
|
||||
}
|
||||
y += 22 + ProblemLine("##ed_state", new Vector2(top.X + lw, y + 22), w - lw) + 6;
|
||||
|
||||
// Conditions | Actions
|
||||
const float footerH = 24;
|
||||
float colsH = Math.Max(60, top.Y + size.Y - y - footerH - 6);
|
||||
if (w >= SideBySideMinWidth)
|
||||
{
|
||||
float cw = (w - 6) * 0.5f;
|
||||
Column("##ed_conds", new Vector2(top.X, y), new Vector2(cw, colsH), actions: false);
|
||||
Column("##ed_acts", new Vector2(top.X + cw + 6, y), new Vector2(w - cw - 6, colsH), actions: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
float ch = (colsH - 6) * 0.5f;
|
||||
Column("##ed_conds", new Vector2(top.X, y), new Vector2(w, ch), actions: false);
|
||||
Column("##ed_acts", new Vector2(top.X, y + ch + 6), new Vector2(w, colsH - ch - 6), actions: true);
|
||||
}
|
||||
|
||||
EditorFooter(new Vector2(top.X, y + colsH + 6), w, footerH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(top.X, y + colsH + 6 + footerH));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
|
||||
if (_editChanged)
|
||||
{
|
||||
_autosave.Changed(NowMs);
|
||||
_editConfirmDelete = false;
|
||||
}
|
||||
_editTyping = _typingNow;
|
||||
}
|
||||
|
||||
/// <summary>A bordered column: a fixed header (title, "+ Add") over a body that scrolls on its own.</summary>
|
||||
private void Column(string id, Vector2 pos, Vector2 size, bool actions)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
MetaRuleDto r = _editRule;
|
||||
const float hh = 24;
|
||||
dl.AddRectFilled(pos, pos + size, PanelBg, 3);
|
||||
dl.AddRectFilled(pos, pos + new Vector2(size.X, hh), StateHdrA, 3);
|
||||
dl.AddRect(pos, pos + size, BtnBord, 3);
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
dl.AddText(bold, bold.FontSize, pos + new Vector2(7, (hh - bold.FontSize) * 0.5f), Amber, actions ? "Actions" : "Conditions");
|
||||
|
||||
bool canAdd = actions || MetaRuleEdit.CanAddCondition(r);
|
||||
float addW = BtnW(AddLabel, 52);
|
||||
if (Button(AddLabel + id + "_add", new Vector2(pos.X + size.X - addW - 3, pos.Y + 2), new Vector2(addW, hh - 4), Teal, BtnFill, BtnBord,
|
||||
enabled: canAdd))
|
||||
{
|
||||
if (actions) MetaRuleEdit.AddAction(r); else MetaRuleEdit.AddCondition(r);
|
||||
_editChanged = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(actions
|
||||
? (r.Action == MetaRuleEdit.DoAll ? "Add one more action" : "Add another action: this one and the new one run in order (All)")
|
||||
: !canAdd ? "A Not has one condition"
|
||||
: r.Condition is MetaRuleEdit.All or MetaRuleEdit.Any or MetaRuleEdit.Not ? "Add one more condition"
|
||||
: "Add another condition: the rule fires when all of them are true (All)");
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos + new Vector2(5, hh + 4));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
|
||||
ImGuiNET.ImGui.BeginChild(id, new Vector2(Math.Max(10, size.X - 10), Math.Max(10, size.Y - hh - 8)));
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
float cw = Math.Max(40, ImGuiNET.ImGui.GetContentRegionAvail().X - 2);
|
||||
if (actions) ActionsBody(r, cw); else ConditionsBody(r, cw);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
}
|
||||
|
||||
private void ConditionsBody(MetaRuleDto r, float w)
|
||||
{
|
||||
int picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, w);
|
||||
if (picked >= 0 && picked != r.Condition)
|
||||
{
|
||||
SetCondition(r, picked);
|
||||
_editChanged = true;
|
||||
}
|
||||
if (!MetaVocabulary.IsCompositeCondition(r.Condition))
|
||||
{
|
||||
ConditionField("##ed_cdata", r, w, 22);
|
||||
return;
|
||||
}
|
||||
SmallLabel(r.Condition switch
|
||||
{
|
||||
MetaRuleEdit.Not => "Not: true while this one is false",
|
||||
MetaRuleEdit.All => "All of these:",
|
||||
_ => "Any of these:",
|
||||
});
|
||||
if (r.Children.Count == 0) Note("None yet: + Add (top right).");
|
||||
SubRules(r.Children, action: false, 0, r.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, w);
|
||||
}
|
||||
|
||||
private void ActionsBody(MetaRuleDto r, float w)
|
||||
{
|
||||
int picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, w);
|
||||
if (picked >= 0 && picked != r.Action)
|
||||
{
|
||||
r.Action = picked;
|
||||
if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear();
|
||||
_editChanged = true;
|
||||
}
|
||||
if (!MetaVocabulary.IsAllAction(r.Action))
|
||||
{
|
||||
ActionField("##ed_adata", r, w, 22, problemLine: true);
|
||||
return;
|
||||
}
|
||||
SmallLabel("All of these, in order:");
|
||||
if (r.ActionChildren.Count == 0) Note("None yet: + Add (top right).");
|
||||
SubRules(r.ActionChildren, action: true, 0, int.MaxValue, w);
|
||||
}
|
||||
|
||||
private static void SetCondition(MetaRuleDto c, int picked)
|
||||
{
|
||||
c.Condition = picked;
|
||||
if (!MetaVocabulary.IsCompositeCondition(picked)) c.Children.Clear();
|
||||
else if (picked == MetaRuleEdit.Not && c.Children.Count > 1) c.Children.RemoveRange(1, c.Children.Count - 1);
|
||||
}
|
||||
|
||||
/// <summary>A condition's value at the cursor: a text box (with Set current for landblock / landcell),
|
||||
/// or a note when the condition takes nothing. Leaves the cursor under it.</summary>
|
||||
private void ConditionField(string id, MetaRuleDto c, float width, float height)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (!MetaRuleEdit.ConditionTakesData(c.Condition) && c.ConditionData.Length == 0)
|
||||
NoteAt(p, "Nothing to set.", height);
|
||||
else if (MetaLocation.TakesPosition(c.Condition))
|
||||
{
|
||||
// "Set current" fills in where the player is, from the engine's per-frame pose copy
|
||||
// (no call into AC from here), in the 8-digit form RynthAi and VTank both read.
|
||||
float bw = Math.Min(BtnW(SetCurrentLabel, 70), width * 0.5f);
|
||||
float boxW = Math.Max(30, width - bw - 4);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
DataBox(id, c, action: false, MetaVocabulary.ConditionHint(c.Condition), boxW, height);
|
||||
string? here = PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out uint cell, out _, out _, out _, out _, out _, out _, out _) && cell != 0
|
||||
? MetaLocation.Text(c.Condition, cell) : null;
|
||||
if (Button((bw >= BtnW(SetCurrentLabel, 0) ? SetCurrentLabel : PhosphorIcons.MapPin) + id + "_here",
|
||||
new Vector2(p.X + width - bw, p.Y), new Vector2(bw, height), Teal, BtnFill, BtnBord, enabled: here != null) && here != null)
|
||||
{
|
||||
c.ConditionData = here;
|
||||
_editChanged = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(here != null
|
||||
? $"Set to where you are now: {here}"
|
||||
: "Your position isn't known right now (portal space, or not in the world).");
|
||||
}
|
||||
else
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
DataBox(id, c, action: false, MetaVocabulary.ConditionHint(c.Condition), width, height);
|
||||
if (c.Condition == MetaRuleEdit.NoKillsWithinMinutes)
|
||||
ImGuiNET.ImGui.SetItemTooltip(MetaRuleEdit.NoKillsTooltip(c.ConditionData).Replace("%", "%%")); // a format string: typed text may hold %
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + height));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
}
|
||||
|
||||
/// <summary>An action's value at the cursor: a state picker (Set / Call Meta State), the route picker
|
||||
/// (Embedded Nav Route), a text box, or a note. Leaves the cursor under it.</summary>
|
||||
private void ActionField(string id, MetaRuleDto a, float width, float height, bool problemLine)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float extra = 0;
|
||||
if (a.Action is 2 or 5) // Set / Call Meta State
|
||||
{
|
||||
string? target = StatePicker(id, a.ActionData.Length == 0 ? "Select state..." : a.ActionData, _statesOnly,
|
||||
IndexOf(_statesOnly, a.ActionData), p, width, out bool isNew, height);
|
||||
if (target != null)
|
||||
{
|
||||
if (isNew) CreateState(target, openIt: false); // an empty first rule keeps it
|
||||
if (target != a.ActionData)
|
||||
{
|
||||
a.ActionData = target;
|
||||
_editChanged = true;
|
||||
}
|
||||
}
|
||||
if (problemLine) extra = ProblemLine(id, new Vector2(p.X, p.Y + height), width);
|
||||
}
|
||||
else if (a.Action == 3) // Embedded Nav Route
|
||||
{
|
||||
int picked = Picker(id, a.ActionData.Length == 0 ? "Select route..." : a.ActionData, _routePicks,
|
||||
Array.IndexOf(_routePicks, a.ActionData), p, width, height);
|
||||
if (picked >= 0 && _routePicks[picked] != a.ActionData)
|
||||
{
|
||||
a.ActionData = _routePicks[picked];
|
||||
_editChanged = true;
|
||||
}
|
||||
}
|
||||
else if (!MetaRuleEdit.ActionTakesData(a.Action) && a.ActionData.Length == 0)
|
||||
NoteAt(p, "Nothing to set.", height);
|
||||
else
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
DataBox(id, a, action: true, MetaVocabulary.ActionHint(a.Action), width, height);
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + height + extra));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
}
|
||||
|
||||
// Sub-conditions nest (All/Any/Not under All/Any/Not, MaxSubConditionDepth levels; a Not takes
|
||||
// one); DoAll's sub-actions are a flat list. Each row: [type][value][x]; in a narrow column the
|
||||
// value goes on a second line. The top level's "+ Add" is in the column header.
|
||||
private void SubRules(List<MetaRuleDto> subs, bool action, int depth, int maxCount, float w)
|
||||
{
|
||||
string[] names = action ? MetaVocabulary.ActionNames : MetaVocabulary.ConditionNames;
|
||||
bool narrow = w < 300;
|
||||
const float rh = 20, xw = 20;
|
||||
for (int i = 0; i < subs.Count; i++)
|
||||
{
|
||||
MetaRuleDto sub = subs[i];
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float pickW = narrow ? w - xw - 4 : (w - xw - 8) * 0.45f;
|
||||
|
||||
int current = action ? sub.Action : sub.Condition;
|
||||
string shown = action ? MetaVocabulary.ActionName(sub.Action) : MetaVocabulary.ConditionName(sub.Condition);
|
||||
int picked = Picker("##type", shown, names, current, p, pickW, rh);
|
||||
if (picked >= 0 && picked != current)
|
||||
{
|
||||
if (action) sub.Action = picked; else SetCondition(sub, picked);
|
||||
_editChanged = true;
|
||||
}
|
||||
|
||||
bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth;
|
||||
bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + w - xw, p.Y), new Vector2(xw, rh), TextDim, DelFill, BtnBord);
|
||||
ImGuiNET.ImGui.SetItemTooltip(action ? "Remove this action" : "Remove this condition");
|
||||
|
||||
float rowH = rh;
|
||||
if (nests)
|
||||
{
|
||||
if (!narrow)
|
||||
NoteAt(new Vector2(p.X + pickW + 6, p.Y), sub.Condition == MetaRuleEdit.Not ? "(the condition below)" : "(the conditions below)", rh);
|
||||
}
|
||||
else
|
||||
{
|
||||
Vector2 vp = narrow ? new Vector2(p.X + 12, p.Y + rh + 2) : new Vector2(p.X + pickW + 4, p.Y);
|
||||
float vw = narrow ? w - 12 : w - pickW - 4 - xw - 4;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(vp);
|
||||
if (action) ActionField("##data", sub, vw, rh, problemLine: false);
|
||||
else ConditionField("##data", sub, vw, rh);
|
||||
if (narrow) rowH = rh * 2 + 2;
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH + 2));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
|
||||
if (!removed && nests)
|
||||
{
|
||||
ImGuiNET.ImGui.Indent(14);
|
||||
SmallLabel(sub.Condition switch { MetaRuleEdit.Not => "Not:", MetaRuleEdit.All => "All of:", _ => "Any of:" });
|
||||
SubRules(sub.Children, action: false, depth + 1, sub.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, w - 14);
|
||||
ImGuiNET.ImGui.Unindent(14);
|
||||
}
|
||||
ImGuiNET.ImGui.PopID();
|
||||
if (removed)
|
||||
{
|
||||
subs.RemoveAt(i);
|
||||
_editChanged = true;
|
||||
break; // indices shifted: the rest draws next frame
|
||||
}
|
||||
}
|
||||
|
||||
// Nested groups get their own Add; the top level's is in the column header.
|
||||
if (depth == 0 || subs.Count >= maxCount) return;
|
||||
ImGuiNET.ImGui.PushID(depth * 1000 + subs.Count);
|
||||
if (FlowButton(AddLabel + "##add_sub", Teal, BtnFill, BtnBord, height: 20))
|
||||
{
|
||||
subs.Add(new MetaRuleDto { State = _editRule.State, Condition = MetaRuleEdit.Never });
|
||||
_editChanged = true;
|
||||
}
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
|
||||
/// <summary>[Revert] on the left (once something changed); Delete on its own at the far right.</summary>
|
||||
private void EditorFooter(Vector2 p, float w, float h)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
bool canRevert = _editOriginal != null && !MetaRuleEdit.SameContent(_editRule, _editOriginal);
|
||||
if (canRevert)
|
||||
{
|
||||
string label = PhosphorIcons.ArrowCounterClockwise + " Revert";
|
||||
if (Button(label + "##ed_revert", p, new Vector2(BtnW(label, 60), h), Mute, BtnFill, BtnBord))
|
||||
{
|
||||
_editRule = _editOriginal!.Clone();
|
||||
_fields.Clear();
|
||||
_editChanged = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Undo every change since you opened this rule (and save that)");
|
||||
}
|
||||
else
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
dl.AddText(new Vector2(p.X, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute),
|
||||
_editIndex < 0 ? "Added once it is filled in, or on Back." : "Changes save on their own.");
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
bool draft = _editIndex < 0;
|
||||
if (!_editConfirmDelete)
|
||||
{
|
||||
string label = PhosphorIcons.Trash + (draft ? " Discard" : " Delete rule");
|
||||
float dw = BtnW(label, 70);
|
||||
if (Button(label + "##ed_del", new Vector2(p.X + w - dw, p.Y), new Vector2(dw, h), TextDim, DelFill, BtnBord))
|
||||
{
|
||||
if (draft) { _autosave.Clear(); LeaveEditor(); }
|
||||
else _editConfirmDelete = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(draft ? "Drop this new rule (it was never added)" : "Delete this rule (asks first)");
|
||||
}
|
||||
else
|
||||
{
|
||||
float kw = BtnW("Keep", 50), yw = BtnW("Delete", 56);
|
||||
dl.AddText(new Vector2(p.X + w - kw - yw - 8 - ImGuiNET.ImGui.CalcTextSize("Delete this rule?").X - 6,
|
||||
p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Red, "Delete this rule?");
|
||||
if (Button("Delete##ed_del_yes", new Vector2(p.X + w - kw - yw - 4, p.Y), new Vector2(yw, h), TextDim, DelFill, Red))
|
||||
{
|
||||
DeleteEditedRule();
|
||||
return;
|
||||
}
|
||||
if (Button("Keep##ed_del_no", new Vector2(p.X + w - kw, p.Y), new Vector2(kw, h), Mute, BtnFill, BtnBord))
|
||||
_editConfirmDelete = false;
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// State pickers and new states
|
||||
// =====================================================================
|
||||
|
||||
/// <summary>
|
||||
/// A state picker ending with "+ New state...". Returns the picked state, or a new state's name
|
||||
/// (<paramref name="isNew"/> true) once its name box is confirmed; else null.
|
||||
/// </summary>
|
||||
private string? StatePicker(string id, string shown, string[] items, int selected, Vector2 pos, float width, out bool isNew,
|
||||
float height = 22)
|
||||
{
|
||||
isNew = false;
|
||||
uint key = ImGuiNET.ImGui.GetID(id);
|
||||
if (_namingKey == key) return NamingBox(id, pos, width, height, out isNew);
|
||||
int picked = Picker(id, shown, items, selected, pos, width, height, NewStateEntry);
|
||||
if (picked == items.Length)
|
||||
{
|
||||
_namingKey = key;
|
||||
Array.Clear(_nameBuf);
|
||||
_nameFocus = true;
|
||||
_nameWasActive = false;
|
||||
_nameProblem = null;
|
||||
return null;
|
||||
}
|
||||
return picked >= 0 ? items[picked] : null;
|
||||
}
|
||||
|
||||
/// <summary>The name box a state picker turns into: [name][OK][Cancel]; Enter = OK, Esc = Cancel.</summary>
|
||||
private string? NamingBox(string id, Vector2 pos, float width, float height, out bool isNew)
|
||||
{
|
||||
isNew = false;
|
||||
float bw = height + 4;
|
||||
float boxW = Math.Max(30, width - 2 * (bw + 3));
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
if (_nameFocus)
|
||||
{
|
||||
ImGuiNET.ImGui.SetKeyboardFocusHere();
|
||||
_nameFocus = false;
|
||||
}
|
||||
bool enter = TextBox(id + "_name", _nameBuf, boxW, "New state name...", ImGuiInputTextFlags.EnterReturnsTrue, out bool active, height);
|
||||
// Esc deactivates the box in the same frame, so "was it being typed in" is last frame's.
|
||||
bool esc = (active || _nameWasActive) && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape, false);
|
||||
_nameWasActive = active;
|
||||
|
||||
string typed = Utf8(_nameBuf);
|
||||
_nameProblem = MetaStateName.Problem(typed, _statePicks, out string name);
|
||||
if (_nameProblem != null && name.Length > 0)
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddRect(pos, pos + new Vector2(boxW, height), Red, 3);
|
||||
bool ok = IconButton(id + "_ok", PhosphorIcons.Check, new Vector2(pos.X + boxW + 3, pos.Y), new Vector2(bw, height), Green, NewFill, Green,
|
||||
enabled: _nameProblem == null);
|
||||
ImGuiNET.ImGui.SetItemTooltip(_nameProblem ?? $"Make the state '{name}' (Enter)");
|
||||
bool cancel = IconButton(id + "_cancel", PhosphorIcons.X, new Vector2(pos.X + boxW + bw + 6, pos.Y), new Vector2(bw, height),
|
||||
TextDim, BtnFill, BtnBord);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Cancel (Esc)");
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, pos.Y + height));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
|
||||
if ((enter || ok) && _nameProblem == null)
|
||||
{
|
||||
CancelNaming();
|
||||
AddLocalState(name);
|
||||
isNew = true;
|
||||
return name;
|
||||
}
|
||||
if (enter) _nameFocus = true; // a bad name: keep typing (the reason shows under it)
|
||||
if (cancel || esc) CancelNaming();
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The name box's problem under a picker in the editor's flow; its height (0 when none).</summary>
|
||||
private float ProblemLine(string id, Vector2 pos, float width)
|
||||
{
|
||||
if (_namingKey == 0 || _namingKey != ImGuiNET.ImGui.GetID(id) || _nameProblem == null || Utf8(_nameBuf).Trim().Length == 0)
|
||||
return 0;
|
||||
ImFontPtr small = ImGuiFonts.Get(UiFont.Ui9);
|
||||
ImGuiNET.ImGui.PushFont(small);
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(pos + new Vector2(2, 1), Red, Fit(_nameProblem, width - 4));
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
return small.FontSize + 3;
|
||||
}
|
||||
|
||||
private void CancelNaming()
|
||||
{
|
||||
_namingKey = 0;
|
||||
_nameProblem = null;
|
||||
}
|
||||
|
||||
/// <summary>Offers <paramref name="name"/> in every state picker until the snapshot lists it.</summary>
|
||||
private void AddLocalState(string name)
|
||||
{
|
||||
_localStates.Add(name);
|
||||
if (IndexOf(_statePicks, name) < 0) _statePicks = With(_statePicks, name);
|
||||
if (IndexOf(_statesOnly, name) < 0) _statesOnly = With(_statesOnly, name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes state <paramref name="name"/> with its first rule, an empty Never -> None (it never fires),
|
||||
/// added at once: a state exists only while a rule uses it, so this is what keeps it through a
|
||||
/// save and reload. <paramref name="openIt"/> opens that rule in the editor.
|
||||
/// </summary>
|
||||
private void CreateState(string name, bool openIt)
|
||||
{
|
||||
AddLocalState(name);
|
||||
MetaRuleDto first = MetaRuleEdit.Placeholder(name);
|
||||
int index = _data.Rules.Count; // add_rule appends
|
||||
SendEdit(new MetaCmd { Op = "add_rule", Rule = first.Clone() });
|
||||
_data.Rules.Add(first.Clone());
|
||||
RebuildCaches();
|
||||
if (openIt) OpenEditor(index, first);
|
||||
}
|
||||
|
||||
// ── Small helpers ────────────────────────────────────────────────────
|
||||
|
||||
private static int IndexOf(string[] items, string value)
|
||||
{
|
||||
for (int i = 0; i < items.Length; i++)
|
||||
if (string.Equals(items[i], value, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static void SmallLabel(string text)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), text);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
private static void Note(string text)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
private static void NoteAt(Vector2 p, string text, float height)
|
||||
{
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + 4, p.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), text);
|
||||
}
|
||||
}
|
||||
|
|
@ -83,12 +83,12 @@ internal sealed partial class MetaFace
|
|||
|
||||
Separator(w);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float newW = 80;
|
||||
float newW = BtnW(PhosphorIcons.Plus + " New Rule", 80);
|
||||
if (Button(PhosphorIcons.Plus + " New Rule##sched_new", new Vector2(p.X, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green))
|
||||
OpenScheduleEditor(-1, new ScheduleRuleDto { Meta = FirstMetaFile() });
|
||||
if (sc.Rules.Count > 0)
|
||||
{
|
||||
if (Button(PhosphorIcons.ArrowCounterClockwise + " Re-arm all##sched_reset", new Vector2(p.X + newW + 4, p.Y), new Vector2(86, 24),
|
||||
if (Button(PhosphorIcons.ArrowCounterClockwise + " Re-arm all##sched_reset", new Vector2(p.X + newW + 4, p.Y), new Vector2(BtnW(PhosphorIcons.ArrowCounterClockwise + " Re-arm all", 86), 24),
|
||||
Mute, BtnFill, BtnBord))
|
||||
MetaCommands.Simple("mm_reset", -1);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Clear every rule's fired / error / holding state");
|
||||
|
|
|
|||
|
|
@ -3,16 +3,28 @@
|
|||
// ImGui face of the Meta panel (docs/IMGUI_PARITY_PLAN.md §2.13), with the
|
||||
// Avalonia face's look and three views:
|
||||
//
|
||||
// List file picker / refresh / Save / Save As; Visual|Source; Meta, Debug;
|
||||
// rules grouped by state (collapsible, red while firing), rows with
|
||||
// enable, expand, up/down within the state, duplicate, delete; click
|
||||
// a row to edit it; State picker and New Rule at the bottom.
|
||||
// Editor state, condition (with nested All/Any/Not sub-conditions), action
|
||||
// (state and route pickers, DoAll sub-actions); Add/Save, Cancel.
|
||||
// List file picker / refresh / Save As / "Saved" indicator; Visual|Source;
|
||||
// Meta, Debug; rules grouped by state (collapsible, red while
|
||||
// firing), rows with enable, expand, up/down within the state,
|
||||
// duplicate, and delete on the far right (click twice); click a row
|
||||
// to edit it; State picker and New Rule at the bottom.
|
||||
// Editor (MetaFace.Editor.cs) state; Conditions and Actions side by side
|
||||
// (stacked when the panel is narrow), each with "+ Add"; Set current
|
||||
// for landblock / landcell; every change saves on its own.
|
||||
// Source the .af text in a coloured editor (CodeEditor) with Ctrl+Space
|
||||
// completion (and after "IF: " etc.); Apply shows the plugin's real
|
||||
// result; unapplied edits survive switching views; Revert.
|
||||
//
|
||||
// Every state picker ends with "+ New state...", which turns it into a name
|
||||
// box (Enter = OK, Esc = Cancel); see MetaFace.Editor.cs for how a new state
|
||||
// is kept (a state exists while a rule uses it).
|
||||
//
|
||||
// Saving (2026-10-05): there is no Save button. RynthAi writes the meta file
|
||||
// after every rule command (TryAutoSaveMetaCmd); the editor sends its rule
|
||||
// 0.75 s after the last change (MetaAutosave), and at once on Back, close or
|
||||
// a meta switch. The first save of a session first copies the file to
|
||||
// <file>.bak (MetaBackupPlan, MetaCommands.Backup).
|
||||
//
|
||||
// Data: UiSources.Meta (hub snapshot) and MetaCommands. List edits change a
|
||||
// private copy at once and the next snapshot (taken after the plugin applied
|
||||
// the command) replaces it.
|
||||
|
|
@ -62,8 +74,8 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
private string _fileDisplay = "-- None --", _sourceFileLabel = "File: Unsaved";
|
||||
private IReadOnlyList<string> _completionNavs = Array.Empty<string>();
|
||||
|
||||
// Ellipsized row text, recomputed only when the column width changes.
|
||||
private readonly Dictionary<string, (float Width, string Shown)> _fit = new();
|
||||
// Ellipsized text per (text, width), so one text shown at two widths doesn't recompute each frame.
|
||||
private readonly Dictionary<(string Text, int Width), string> _fit = new();
|
||||
|
||||
private View _view = View.List;
|
||||
private readonly HashSet<string> _collapsed = new();
|
||||
|
|
@ -71,6 +83,22 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
private bool _saveAs, _saveAsFocus;
|
||||
private readonly byte[] _saveName = new byte[128];
|
||||
|
||||
// States made with "+ New state..." that the snapshot doesn't list yet (MetaFace.Editor.cs).
|
||||
private readonly HashSet<string> _localStates = new(StringComparer.OrdinalIgnoreCase);
|
||||
private string _statesPath = string.Empty; // the meta _localStates belong to
|
||||
|
||||
// Delete on a rule row: the first click arms it (3 s), the second deletes.
|
||||
private MetaRuleDto? _confirmDelete;
|
||||
private int _confirmDeleteIndex = -1;
|
||||
private long _confirmDeleteUntil;
|
||||
|
||||
// ── Saving ───────────────────────────────────────────────────────────
|
||||
private readonly MetaAutosave _autosave = new();
|
||||
private readonly MetaBackupPlan _backup = new();
|
||||
private long _saveSentAt = -1; // ms (TickCount64) of the last rule command, for "Saving..."
|
||||
private long _saveSentVersion; // the snapshot version then
|
||||
private static long NowMs => Environment.TickCount64;
|
||||
|
||||
// ── Rule editor ──────────────────────────────────────────────────────
|
||||
private int _editIndex = -1;
|
||||
private MetaRuleDto _editRule = new() { Action = 1 };
|
||||
|
|
@ -109,10 +137,13 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
UiSources.Meta.Subscribe();
|
||||
UiSources.Meta.RequestRefresh();
|
||||
CodeEditor.SetMetaVocabulary(MetaVocabulary.StructKeywords, MetaVocabulary.ConditionKeywords, MetaVocabulary.ActionKeywords);
|
||||
_backup.NewSession(); // a new editing session: the first save backs the file up again
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
FlushEdit(); // closing saves the rule being edited at once
|
||||
CancelNaming();
|
||||
UiSources.Meta.Unsubscribe();
|
||||
_editor?.Dispose();
|
||||
_editor = null;
|
||||
|
|
@ -125,6 +156,10 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
public void Draw()
|
||||
{
|
||||
TakeSnapshot();
|
||||
if (_view == View.Editor) EditorGuard();
|
||||
// A new rule waits until it is filled in (MetaRuleEdit.ReadyToAdd); Back / close add it anyway.
|
||||
if (_view == View.Editor && _autosave.Due(NowMs, _editTyping) && (_editIndex >= 0 || MetaRuleEdit.ReadyToAdd(_editRule)))
|
||||
CommitEdit();
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
|
|
@ -192,8 +227,20 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
_groupFiring[g] = firing;
|
||||
_groupLabel[g] = firing ? $"{_groups[g].State} ({_groups[g].Rules.Count}) — firing" : $"{_groups[g].State} ({_groups[g].Rules.Count})";
|
||||
}
|
||||
// States made here that the snapshot doesn't list yet (dropped once it does, or on a meta switch).
|
||||
if (!string.Equals(_statesPath, _data.CurrentMetaPath, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_statesPath = _data.CurrentMetaPath;
|
||||
_localStates.Clear();
|
||||
}
|
||||
foreach (string s in _data.States) _localStates.Remove(s);
|
||||
_statePicks = MetaVocabulary.StatePicks(_data);
|
||||
_statesOnly = _data.States.ToArray();
|
||||
foreach (string s in _localStates)
|
||||
{
|
||||
_statePicks = With(_statePicks, s);
|
||||
_statesOnly = With(_statesOnly, s);
|
||||
}
|
||||
_routePicks = MetaVocabulary.RoutePicks(_data);
|
||||
_fileDisplays = new string[_data.Files.Count];
|
||||
for (int i = 0; i < _fileDisplays.Length; i++) _fileDisplays[i] = _data.Files[i].Display;
|
||||
|
|
@ -214,6 +261,12 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
Separator(w);
|
||||
ModeRow(w, source: false);
|
||||
Separator(w);
|
||||
if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), Fit(_listNote, w));
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
const float bottomH = 24;
|
||||
float listH = Math.Max(40, origin.Y + size.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - bottomH - 9);
|
||||
|
|
@ -233,7 +286,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
{
|
||||
if (_saveAs)
|
||||
{
|
||||
float btn = 52, sx = ImGuiNET.ImGui.GetCursorScreenPos().X, y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
float btn = BtnW(SaveLabel, 52), sx = ImGuiNET.ImGui.GetCursorScreenPos().X, y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
float boxW = w - btn - 26 - 8;
|
||||
if (_saveAsFocus) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _saveAsFocus = false; }
|
||||
bool enter = TextBox("##save_name", _saveName, boxW, "Filename (no ext)...", ImGuiInputTextFlags.EnterReturnsTrue, out _);
|
||||
|
|
@ -241,7 +294,14 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
{
|
||||
string n = Utf8(_saveName).Trim();
|
||||
if (n.Length > 0)
|
||||
MetaCommands.Simple("save_file", path: System.IO.Path.Combine(MetaVocabulary.MetaFolder, n + ".af"));
|
||||
{
|
||||
string target = System.IO.Path.Combine(MetaVocabulary.MetaFolder, n + ".af");
|
||||
// Saving over another meta keeps that one's old copy as <file>.bak.
|
||||
MetaCommands.Backup(target, MetaBackupPlan.BackupOf(target));
|
||||
MetaCommands.Simple("save_file", path: target);
|
||||
_saveSentAt = NowMs;
|
||||
_saveSentVersion = _seenVersion;
|
||||
}
|
||||
_saveAs = false;
|
||||
}
|
||||
if (IconButton("##save_as_x", PhosphorIcons.X, new Vector2(sx + boxW + 8 + btn, y), new Vector2(26, 22), TextDim, BtnFill, BtnBord,
|
||||
|
|
@ -253,12 +313,17 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
return;
|
||||
}
|
||||
|
||||
// [file v][refresh][Save As] Saved (no Save button: every change saves on its own)
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float refreshW = 26, saveW = 52, saveAsW = 60;
|
||||
float pickW = w - refreshW - saveW - saveAsW - 12;
|
||||
const float refreshW = 26;
|
||||
float saveAsW = BtnW("Save As", 60), indW = SaveIndicatorWidth();
|
||||
float pickW = Math.Max(60, w - refreshW - saveAsW - indW - 12);
|
||||
int picked = Picker("##file", _fileDisplay, _fileDisplays, MetaVocabulary.CurrentFileIndex(_data), p, pickW);
|
||||
if (picked >= 0 && picked < _data.Files.Count)
|
||||
{
|
||||
FlushEdit(); // a meta switch saves a pending edit first
|
||||
MetaCommands.Simple("load_file", path: _data.Files[picked].Path);
|
||||
}
|
||||
|
||||
float x = p.X + pickW + 4;
|
||||
if (IconButton("##refresh", PhosphorIcons.ArrowsClockwise, new Vector2(x, p.Y), new Vector2(refreshW, 22), TextDim, BtnFill, BtnBord,
|
||||
|
|
@ -266,18 +331,74 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
UiSources.Meta.RequestRefresh();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Refresh file list");
|
||||
x += refreshW + 4;
|
||||
if (Button(SaveLabel + "##save", new Vector2(x, p.Y), new Vector2(saveW, 22), TextDim, BtnFill, BtnBord))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(_data.CurrentMetaPath)) MetaCommands.Simple("save_file", path: _data.CurrentMetaPath);
|
||||
else BeginSaveAs();
|
||||
}
|
||||
x += saveW + 4;
|
||||
if (Button("Save As##save_as", new Vector2(x, p.Y), new Vector2(saveAsW, 22), TextDim, BtnFill, BtnBord))
|
||||
bool noFile = string.IsNullOrEmpty(_data.CurrentMetaPath);
|
||||
if (Button("Save As##save_as", new Vector2(x, p.Y), new Vector2(saveAsW, 22), TextDim, noFile ? NewFill : BtnFill, noFile ? Green : BtnBord))
|
||||
BeginSaveAs();
|
||||
ImGuiNET.ImGui.SetItemTooltip(noFile ? "Name a file for this meta; after that every change saves on its own."
|
||||
: "Save a copy under a new name (and keep editing that one).");
|
||||
x += saveAsW + 4;
|
||||
SaveIndicator(new Vector2(x, p.Y), p.X + w - x, 22);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
}
|
||||
|
||||
// ── "Saved" indicator ────────────────────────────────────────────────
|
||||
|
||||
private const string SavedText = PhosphorIcons.Check + " Saved", SavingText = PhosphorIcons.FloppyDisk + " Saving...",
|
||||
EditingText = PhosphorIcons.PencilSimple + " Editing", NoFileText = PhosphorIcons.Warning + " Not saved",
|
||||
DraftText = PhosphorIcons.PencilSimple + " Not added yet";
|
||||
|
||||
private static float SaveIndicatorWidth(bool editor = false)
|
||||
{
|
||||
float m = Math.Max(ImGuiNET.ImGui.CalcTextSize(SavedText).X, ImGuiNET.ImGui.CalcTextSize(SavingText).X);
|
||||
m = Math.Max(m, Math.Max(ImGuiNET.ImGui.CalcTextSize(EditingText).X, ImGuiNET.ImGui.CalcTextSize(NoFileText).X));
|
||||
if (editor) m = Math.Max(m, ImGuiNET.ImGui.CalcTextSize(DraftText).X);
|
||||
return m + 6;
|
||||
}
|
||||
|
||||
private (string Text, uint Color, string Tip) SaveStatus()
|
||||
{
|
||||
string file = System.IO.Path.GetFileName(_data.CurrentMetaPath ?? "");
|
||||
if (string.IsNullOrEmpty(file))
|
||||
return (NoFileText, Amber, "This meta has no file yet. Save As names one; after that every change saves on its own.");
|
||||
if (_view == View.Editor && _autosave.Dirty && _editIndex < 0 && !_editTyping && !MetaRuleEdit.ReadyToAdd(_editRule))
|
||||
return (DraftText, Amber, "A new rule is added once its condition and action are filled in, or when you go Back.");
|
||||
if (_view == View.Editor && _autosave.Dirty)
|
||||
return _editTyping
|
||||
? (EditingText, Amber, "Saves when you leave the box (Enter, Tab or click elsewhere).")
|
||||
: (SavingText, Amber, "Saving in a moment...");
|
||||
if (_saveSentAt >= 0 && _seenVersion == _saveSentVersion && NowMs - _saveSentAt < 2500)
|
||||
return (SavingText, Amber, "Saving " + file + "...");
|
||||
string bak = System.IO.Path.GetFileName(MetaBackupPlan.BackupOf(MetaBackupPlan.WrittenFile(_data.CurrentMetaPath!)));
|
||||
return (SavedText, Green, $"Every change saves to {file} on its own. The first change after opening this panel keeps the file as it was in {bak}.");
|
||||
}
|
||||
|
||||
/// <summary>The save status, right-aligned in (pos, width); hover for details.</summary>
|
||||
private void SaveIndicator(Vector2 pos, float width, float height)
|
||||
{
|
||||
if (width < 8) return;
|
||||
(string text, uint color, string tip) = SaveStatus();
|
||||
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
ImGuiNET.ImGui.InvisibleButton("##save_ind", new Vector2(width, height));
|
||||
ImGuiNET.ImGui.SetItemTooltip(tip);
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + Math.Max(0, width - tw), pos.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
|
||||
color, text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every command that changes the meta's rules goes through here: before the first one of this
|
||||
/// session the file is backed up, and the indicator shows "Saving..." until the next snapshot.
|
||||
/// (RynthAi writes the file after each such command.)
|
||||
/// </summary>
|
||||
private void SendEdit(MetaCmd cmd)
|
||||
{
|
||||
if (_backup.Before(_data.CurrentMetaPath) is { } b) MetaCommands.Backup(b.File, b.Backup);
|
||||
MetaCommands.Send(cmd);
|
||||
_saveSentAt = NowMs;
|
||||
_saveSentVersion = _seenVersion;
|
||||
}
|
||||
|
||||
private void BeginSaveAs()
|
||||
{
|
||||
_saveAs = true;
|
||||
|
|
@ -341,6 +462,8 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
// the text starts within a row (from the last row drawn).
|
||||
private static float _condFrac = Math.Clamp(RynthCore.Engine.UI.PanelColumnStore.Get("Meta.condFrac", 0.5f), 0.15f, 0.85f);
|
||||
private float _textStartOff;
|
||||
/// <summary>The far-right delete button and the gap before it: the row text ends this far from the edge.</summary>
|
||||
private const float DeleteColumnW = 30;
|
||||
|
||||
private void RuleList(float w)
|
||||
{
|
||||
|
|
@ -360,7 +483,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
{
|
||||
Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float hh = 16;
|
||||
float tx = hp.X + _textStartOff, tw = Math.Max(1, hp.X + w - tx);
|
||||
float tx = hp.X + _textStartOff, tw = Math.Max(1, hp.X + w - DeleteColumnW - tx);
|
||||
float split = tw * _condFrac;
|
||||
float hy = hp.Y + (hh - bold.FontSize) * 0.5f;
|
||||
dl.AddText(bold, bold.FontSize, new Vector2(tx + 3, hy), C(0xFFC8D6E4), "Condition");
|
||||
|
|
@ -424,7 +547,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
rule.Enabled ? Green : Mute, BtnFill, BtnBord))
|
||||
{
|
||||
rule.Enabled = !rule.Enabled;
|
||||
MetaCommands.Simple("set_rule_enabled", index, rule.Enabled ? "true" : "false");
|
||||
SendEdit(new MetaCmd { Op = "set_rule_enabled", Index = index, Value = rule.Enabled ? "true" : "false" });
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(rule.Enabled ? "Enabled — click to disable" : "Disabled — click to enable");
|
||||
x += 16;
|
||||
|
|
@ -451,29 +574,45 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
// Duplicate
|
||||
if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord))
|
||||
{
|
||||
MetaCommands.Send(new MetaCmd { Op = "duplicate_rule", Index = index, Rule = rule.Clone() });
|
||||
SendEdit(new MetaCmd { Op = "duplicate_rule", Index = index, Rule = rule.Clone() });
|
||||
_data.Rules.Insert(Math.Min(index + 1, _data.Rules.Count), rule.Clone());
|
||||
changed = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Duplicate rule");
|
||||
x += 18;
|
||||
x += 20;
|
||||
|
||||
// Delete
|
||||
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x + 1, p.Y + 2), new Vector2(18, 16), TextDim, DelFill, BtnBord))
|
||||
// Delete: on its own at the far right, away from the other buttons (2026-10-05). A rule
|
||||
// with anything in it takes a second click within 3 s; an empty Never -> None one goes at once.
|
||||
bool arming = _confirmDeleteIndex == index && _confirmDelete != null && NowMs < _confirmDeleteUntil
|
||||
&& MetaRuleEdit.SameContent(_confirmDelete, rule);
|
||||
float delW = arming ? BtnW("Delete?", 50) : 20;
|
||||
float delX = p.X + w - delW - 2;
|
||||
if (arming
|
||||
? Button("Delete?##del", new Vector2(delX, p.Y + 2), new Vector2(delW, 16), TextDim, DelFill, Red)
|
||||
: IconButton("##del", PhosphorIcons.Trash, new Vector2(delX, p.Y + 2), new Vector2(delW, 16), TextDim, DelFill, BtnBord))
|
||||
{
|
||||
MetaCommands.Simple("delete_rule", index);
|
||||
_data.Rules.RemoveAt(index);
|
||||
_expanded.Clear();
|
||||
changed = true;
|
||||
if (arming || MetaRuleEdit.IsPlaceholder(rule))
|
||||
{
|
||||
SendEdit(new MetaCmd { Op = "delete_rule", Index = index });
|
||||
_data.Rules.RemoveAt(index);
|
||||
_expanded.Clear();
|
||||
_confirmDelete = null;
|
||||
changed = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_confirmDelete = rule.Clone();
|
||||
_confirmDeleteIndex = index;
|
||||
_confirmDeleteUntil = NowMs + 3000;
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Delete rule");
|
||||
x += 22;
|
||||
ImGuiNET.ImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule");
|
||||
|
||||
// Condition | action text; clicking it edits the rule.
|
||||
float textW = p.X + w - x;
|
||||
float textW = Math.Max(1, p.X + w - DeleteColumnW - x);
|
||||
_textStartOff = x - p.X;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y));
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(Math.Max(1, textW), h)))
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(textW, h)))
|
||||
OpenEditor(index, rule);
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
|
|
@ -485,7 +624,9 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
uint condCol = firing ? Red : TextDim, actCol = firing ? Amber : C(0xFFC8D8E8);
|
||||
if (!rule.Enabled) { condCol = Faded(condCol); actCol = Faded(actCol); }
|
||||
dl.AddText(new Vector2(x + 3, ty), condCol, Fit(_condText[index], col - 5));
|
||||
dl.AddText(new Vector2(x + col + 2, ty), actCol, Fit(_actText[index], col - 4));
|
||||
// The armed "Delete?" button is wider than the column gap: the action text stops short of it.
|
||||
float actW = Math.Min(textW - col - 4, delX - 6 - (x + col + 2));
|
||||
dl.AddText(new Vector2(x + col + 2, ty), actCol, Fit(_actText[index], actW));
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
|
||||
|
|
@ -527,7 +668,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
{
|
||||
int other = MetaVocabulary.SwapPartner(_data.Rules, index, direction);
|
||||
if (other < 0) return false;
|
||||
MetaCommands.Simple(direction < 0 ? "move_up" : "move_down", index);
|
||||
SendEdit(new MetaCmd { Op = direction < 0 ? "move_up" : "move_down", Index = index });
|
||||
(_data.Rules[index], _data.Rules[other]) = (_data.Rules[other], _data.Rules[index]);
|
||||
_expanded.Clear();
|
||||
return true;
|
||||
|
|
@ -539,182 +680,34 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float labelW = ImGuiNET.ImGui.CalcTextSize("State:").X;
|
||||
dl.AddText(new Vector2(p.X, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "State:");
|
||||
const float newW = 72;
|
||||
// Buttons sized from their text, so a larger panel text size can't overflow them
|
||||
// (2026-10-05: "+ New Rule" spilled past its fixed 72 px button).
|
||||
string ruleLabel = PhosphorIcons.Plus + " New Rule";
|
||||
float newW = ImGuiNET.ImGui.CalcTextSize(ruleLabel).X + 18;
|
||||
// The bar sits on the body's bottom edge: it stops short of the resize grip (GripInBody).
|
||||
float grip = ImGuiPanelHost.BodyGripReserve;
|
||||
float pickW = w - labelW - 4 - newW - 4 - grip;
|
||||
int picked = Picker("##cur_state", _data.CurrentState, _statePicks, Array.IndexOf(_statePicks, _data.CurrentState),
|
||||
new Vector2(p.X + labelW + 4, p.Y + 1), pickW);
|
||||
if (picked >= 0)
|
||||
float ruleX = p.X + w - grip - newW;
|
||||
float pickX = p.X + labelW + 4;
|
||||
float pickW = Math.Max(40, ruleX - 4 - pickX);
|
||||
|
||||
// The meta's current state. "+ New state..." at the end of the list makes one: it starts
|
||||
// with an empty Never -> None rule (that rule is what keeps it), becomes the current state
|
||||
// like any state picked here, and that rule opens in the editor.
|
||||
string? chosen = StatePicker("##cur_state", _data.CurrentState, _statePicks, Array.IndexOf(_statePicks, _data.CurrentState),
|
||||
new Vector2(pickX, p.Y + 1), pickW, out bool isNew);
|
||||
if (chosen != null)
|
||||
{
|
||||
_data.CurrentState = _statePicks[picked];
|
||||
MetaCommands.Simple("set_state", value: _statePicks[picked]);
|
||||
if (isNew) CreateState(chosen, openIt: true);
|
||||
_data.CurrentState = chosen;
|
||||
MetaCommands.Simple("set_state", value: chosen);
|
||||
}
|
||||
if (Button(PhosphorIcons.Plus + " New Rule##new", new Vector2(p.X + w - newW - grip, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green))
|
||||
if (Button(ruleLabel + "##new", new Vector2(ruleX, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green))
|
||||
OpenEditor(-1, new MetaRuleDto { State = _data.CurrentState, Action = 1 });
|
||||
ImGuiNET.ImGui.SetItemTooltip("A new rule in the current state (added once its condition and action are filled in)");
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Rule editor view
|
||||
// =====================================================================
|
||||
|
||||
private void OpenEditor(int index, MetaRuleDto rule)
|
||||
{
|
||||
_editIndex = index;
|
||||
_editRule = index >= 0 ? rule.Clone() : rule;
|
||||
_fields.Clear();
|
||||
_view = View.Editor;
|
||||
}
|
||||
|
||||
private void EditorView(Vector2 size)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
|
||||
ImGuiNET.ImGui.BeginChild("##meta_editor", size);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
MetaRuleDto r = _editRule;
|
||||
|
||||
if (FlowButton(PhosphorIcons.ArrowLeft + " Back to List##back", Mute, BtnFill, BtnBord)) _view = View.List;
|
||||
Separator(w);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _editIndex == -1 ? "New Rule" : $"Edit Rule (index {_editIndex})");
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
// State
|
||||
FieldLabel("State:");
|
||||
int picked = FlowPicker("##ed_state", r.State, _statePicks, Array.IndexOf(_statePicks, r.State), w);
|
||||
if (picked >= 0) r.State = _statePicks[picked];
|
||||
|
||||
// Condition
|
||||
FieldLabel("Condition:");
|
||||
picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, w);
|
||||
if (picked >= 0)
|
||||
{
|
||||
r.Condition = picked;
|
||||
if (!MetaVocabulary.IsCompositeCondition(picked)) r.Children.Clear();
|
||||
else if (picked == 20 && r.Children.Count > 1) r.Children.RemoveRange(1, r.Children.Count - 1);
|
||||
}
|
||||
if (!MetaVocabulary.IsCompositeCondition(r.Condition))
|
||||
DataBox("##ed_cdata", r, action: false, MetaVocabulary.ConditionHint(r.Condition), w);
|
||||
else
|
||||
SubRules(r.Children, r.Condition == 20 ? "Not (one condition):" : "Sub-Conditions", action: false, 0,
|
||||
r.Condition == 20 ? 1 : int.MaxValue, w);
|
||||
|
||||
// Action
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Separator(w);
|
||||
FieldLabel("Action:");
|
||||
picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, w);
|
||||
if (picked >= 0)
|
||||
{
|
||||
r.Action = picked;
|
||||
if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear();
|
||||
}
|
||||
if (!MetaVocabulary.IsAllAction(r.Action))
|
||||
{
|
||||
if (r.Action is 2 or 5) // Set / Call Meta State
|
||||
{
|
||||
picked = FlowPicker("##ed_astate", r.ActionData.Length == 0 ? "Select state..." : r.ActionData,
|
||||
_statesOnly, Array.IndexOf(_statesOnly, r.ActionData), w);
|
||||
if (picked >= 0) r.ActionData = _statesOnly[picked];
|
||||
}
|
||||
else if (r.Action == 3) // Embedded Nav Route
|
||||
{
|
||||
picked = FlowPicker("##ed_route", r.ActionData.Length == 0 ? "Select route..." : r.ActionData,
|
||||
_routePicks, Array.IndexOf(_routePicks, r.ActionData), w);
|
||||
if (picked >= 0) r.ActionData = _routePicks[picked];
|
||||
}
|
||||
else
|
||||
DataBox("##ed_adata", r, action: true, MetaVocabulary.ActionHint(r.Action), w);
|
||||
}
|
||||
else
|
||||
SubRules(r.ActionChildren, "Sub-Actions", action: true, 0, int.MaxValue, w);
|
||||
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Separator(w);
|
||||
|
||||
// Add/Save, Cancel
|
||||
if (FlowButton(_editIndex == -1 ? "Add Rule##save_rule" : "Save Rule##save_rule", TextDim, NewFill, Green))
|
||||
{
|
||||
if (_editIndex == -1) MetaCommands.Send(new MetaCmd { Op = "add_rule", Rule = r.Clone() });
|
||||
else MetaCommands.Send(new MetaCmd { Op = "update_rule", Index = _editIndex, Rule = r.Clone() });
|
||||
_view = View.List;
|
||||
}
|
||||
ImGuiNET.ImGui.SameLine(0, 6);
|
||||
if (FlowButton("Cancel##cancel_rule", Mute, BtnFill, BtnBord)) _view = View.List;
|
||||
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
}
|
||||
|
||||
// Sub-conditions nest (All/Any/Not under All/Any/Not, MaxSubConditionDepth
|
||||
// levels; a Not takes one); DoAll's sub-actions are a flat list.
|
||||
private void SubRules(List<MetaRuleDto> subs, string label, bool action, int depth, int maxCount, float w)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), label);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
string[] names = action ? MetaVocabulary.ActionNames : MetaVocabulary.ConditionNames;
|
||||
for (int i = 0; i < subs.Count; i++)
|
||||
{
|
||||
MetaRuleDto sub = subs[i];
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float half = (w - 24) * 0.5f;
|
||||
|
||||
// Appendix A4: the label indexes by the sub-rule's own kind.
|
||||
int current = action ? sub.Action : sub.Condition;
|
||||
string shown = action ? MetaVocabulary.ActionName(sub.Action) : MetaVocabulary.ConditionName(sub.Condition);
|
||||
int picked = Picker("##type", shown, names, current, p, half - 2, 20);
|
||||
if (picked >= 0)
|
||||
{
|
||||
if (action) sub.Action = picked;
|
||||
else
|
||||
{
|
||||
sub.Condition = picked;
|
||||
if (!MetaVocabulary.IsCompositeCondition(picked)) sub.Children.Clear();
|
||||
else if (picked == 20 && sub.Children.Count > 1) sub.Children.RemoveRange(1, sub.Children.Count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth;
|
||||
if (nests)
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + half + 4, p.Y + (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
|
||||
TextDim, sub.Condition == 20 ? "(the condition below)" : "(the conditions below)");
|
||||
else
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + half + 2, p.Y));
|
||||
DataBox("##data", sub, action, "data...", half, 20);
|
||||
}
|
||||
|
||||
bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + w - 20, p.Y), new Vector2(20, 20), TextDim, DelFill, BtnBord);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 21));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
|
||||
if (!removed && nests)
|
||||
{
|
||||
ImGuiNET.ImGui.Indent(14);
|
||||
SubRules(sub.Children, sub.Condition switch { 20 => "Not:", 2 => "All of:", _ => "Any of:" },
|
||||
action: false, depth + 1, sub.Condition == 20 ? 1 : int.MaxValue, w - 14);
|
||||
ImGuiNET.ImGui.Unindent(14);
|
||||
}
|
||||
ImGuiNET.ImGui.PopID();
|
||||
if (removed)
|
||||
{
|
||||
subs.RemoveAt(i);
|
||||
break; // indices shifted: the rest draws next frame
|
||||
}
|
||||
}
|
||||
|
||||
if (subs.Count >= maxCount) return; // a Not already has its one operand
|
||||
ImGuiNET.ImGui.PushID(depth * 1000 + subs.Count);
|
||||
if (FlowButton(PhosphorIcons.Plus + " Add##add_sub", Teal, BtnFill, BtnBord, height: 20))
|
||||
subs.Add(new MetaRuleDto { State = _editRule.State });
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Source view
|
||||
// =====================================================================
|
||||
|
|
@ -733,13 +726,11 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
float w = size.X;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
|
||||
// File: name [Save]
|
||||
// File: name Saved (Apply saves; no Save button)
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, _sourceFileLabel);
|
||||
float lw = ImGuiNET.ImGui.CalcTextSize(_sourceFileLabel).X;
|
||||
if (Button(SaveLabel + "##src_save", new Vector2(p.X + lw + 8, p.Y), new Vector2(52, 22), TextDim, BtnFill, BtnBord)
|
||||
&& !string.IsNullOrEmpty(_data.CurrentMetaPath))
|
||||
MetaCommands.Simple("save_file", path: _data.CurrentMetaPath);
|
||||
float indW = SaveIndicatorWidth();
|
||||
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, Fit(_sourceFileLabel, Math.Max(10, w - indW - 8)));
|
||||
SaveIndicator(new Vector2(p.X + w - indW, p.Y), indW, 22);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
Separator(w);
|
||||
|
|
@ -786,7 +777,9 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
if (_editor == null) return;
|
||||
_applySeqBefore = _data.ApplyResult?.Seq ?? -1;
|
||||
_applySentAt = DateTime.Now;
|
||||
MetaCommands.Send(new MetaCmd { Op = "set_source", Text = _editor.GetText() });
|
||||
// Apply replaces every rule and re-enters the current state (RynthAi's set_source); it is
|
||||
// the one explicit "reload", never sent by autosave.
|
||||
SendEdit(new MetaCmd { Op = "set_source", Text = _editor.GetText() });
|
||||
SetMsg("Applying…", ok: true);
|
||||
}
|
||||
|
||||
|
|
@ -1126,15 +1119,19 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// A picker button showing <paramref name="shown"/>; click opens a 240 px
|
||||
/// list (current item highlighted). Returns the picked index or -1.
|
||||
/// A picker button showing <paramref name="shown"/> (cut with "..." before the arrow); click opens
|
||||
/// a list at least 240 px wide (current item highlighted). <paramref name="extra"/>, when given, is
|
||||
/// one more entry after the items ("+ New state..."): picking it returns items.Length. Returns the
|
||||
/// picked index or -1.
|
||||
/// </summary>
|
||||
private static int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22)
|
||||
private int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22,
|
||||
string? extra = null)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.PushID(id);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##btn", new Vector2(Math.Max(1, width), height)) && items.Length > 0)
|
||||
int rows = items.Length + (extra != null ? 1 : 0);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##btn", new Vector2(Math.Max(1, width), height)) && rows > 0)
|
||||
{
|
||||
float listW = Math.Max(240, width);
|
||||
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
|
||||
|
|
@ -1144,9 +1141,12 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
dl.AddRectFilled(pos, pos + new Vector2(width, height), hot ? Lighten(BtnFill) : BtnFill, 3);
|
||||
dl.AddRect(pos, pos + new Vector2(width, height), BtnBord, 3);
|
||||
dl.PushClipRect(pos, pos + new Vector2(width - 4, height), true);
|
||||
dl.AddText(pos + new Vector2(6, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, shown);
|
||||
dl.PopClipRect();
|
||||
// The arrow has its own strip on the right; the text is cut before it (2026-10-05: long
|
||||
// state names ran under the arrow).
|
||||
const float caretW = 14;
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown,
|
||||
new Vector2(pos.X + width - caretW - 3, pos.Y), new Vector2(caretW, height), Mute);
|
||||
dl.AddText(pos + new Vector2(6, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, Fit(shown, width - 6 - caretW - 6));
|
||||
|
||||
int picked = -1;
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
|
|
@ -1154,7 +1154,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
|
||||
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(Math.Max(240, width), Math.Min(items.Length * 21 + 4, 320)));
|
||||
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(Math.Max(240, width), Math.Min(rows * 21 + 4, 320)));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##list");
|
||||
ImGuiNET.ImGui.PopStyleVar(3);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
|
|
@ -1162,17 +1162,19 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
{
|
||||
var pdl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float iw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
for (int i = 0; i < items.Length; i++)
|
||||
for (int i = 0; i < rows; i++)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool click = ImGuiNET.ImGui.InvisibleButton("##item", new Vector2(iw, 20));
|
||||
bool ih = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
bool sel = i == selected;
|
||||
pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? PickSel : ih ? Lighten(BtnFill) : BtnFill);
|
||||
pdl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord);
|
||||
pdl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : TextDim, items[i]);
|
||||
bool isExtra = i == items.Length;
|
||||
bool sel = !isExtra && i == selected;
|
||||
pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? PickSel : ih ? Lighten(BtnFill) : isExtra ? NewFill : BtnFill);
|
||||
pdl.AddRect(ip, ip + new Vector2(iw, 20), isExtra ? Green : BtnBord);
|
||||
pdl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), isExtra ? Green : sel ? Teal : TextDim,
|
||||
Fit(isExtra ? extra! : items[i], iw - 12));
|
||||
if (click)
|
||||
{
|
||||
picked = i;
|
||||
|
|
@ -1187,8 +1189,24 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
return picked;
|
||||
}
|
||||
|
||||
/// <summary>A button width that fits its label at the current font size (labels overflowed fixed
|
||||
/// widths at larger panel text sizes, 2026-10-05); never under <paramref name="min"/>.</summary>
|
||||
internal static float BtnW(string label, float min)
|
||||
{
|
||||
int cut = label.IndexOf("##", StringComparison.Ordinal);
|
||||
return Math.Max(min, ImGuiNET.ImGui.CalcTextSize(cut >= 0 ? label[..cut] : label).X + 18);
|
||||
}
|
||||
|
||||
private static string[] With(string[] items, string added)
|
||||
{
|
||||
var grown = new string[items.Length + 1];
|
||||
items.CopyTo(grown, 0);
|
||||
grown[^1] = added;
|
||||
return grown;
|
||||
}
|
||||
|
||||
/// <summary>A full-width picker at the layout cursor.</summary>
|
||||
private static int FlowPicker(string id, string shown, string[] items, int selected, float width)
|
||||
private int FlowPicker(string id, string shown, string[] items, int selected, float width)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
int picked = Picker(id, shown, items, selected, p, width);
|
||||
|
|
@ -1209,11 +1227,13 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
buf.Shown = value;
|
||||
}
|
||||
bool edited = TextBox(id, buf.Bytes, width, hint, ImGuiInputTextFlags.None, out buf.Active, height);
|
||||
_typingNow |= buf.Active; // autosave waits until the box is left
|
||||
if (edited)
|
||||
{
|
||||
string typed = Utf8(buf.Bytes);
|
||||
if (action) rule.ActionData = typed; else rule.ConditionData = typed;
|
||||
buf.Shown = typed;
|
||||
_editChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1253,7 +1273,8 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
/// <summary><paramref name="text"/> cut to <paramref name="width"/> with "…", cached per text and width.</summary>
|
||||
private string Fit(string text, float width)
|
||||
{
|
||||
if (_fit.TryGetValue(text, out var hit) && Math.Abs(hit.Width - width) < 0.5f) return hit.Shown;
|
||||
var key = (text, (int)MathF.Round(width));
|
||||
if (_fit.TryGetValue(key, out string? hit)) return hit;
|
||||
string shown = text;
|
||||
if (ImGuiNET.ImGui.CalcTextSize(text).X > width)
|
||||
{
|
||||
|
|
@ -1261,7 +1282,8 @@ internal sealed partial class MetaFace : IImGuiPanel
|
|||
while (n > 0 && ImGuiNET.ImGui.CalcTextSize(text.AsSpan(0, n).ToString() + "…").X > width) n--;
|
||||
shown = text.Substring(0, n) + "…";
|
||||
}
|
||||
_fit[text] = (width, shown);
|
||||
if (_fit.Count > 4000) _fit.Clear(); // widths change while a panel is resized
|
||||
_fit[key] = shown;
|
||||
return shown;
|
||||
}
|
||||
|
||||
|
|
|
|||
278
src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs
Normal file
278
src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/MiniRemoteFace.cs
|
||||
// The Mini Remote: a small grid of slots the player fills with items; a click
|
||||
// uses that item. Engine only, ImGui only. (An idea from Silentkelpie's rynth
|
||||
// PR #1, done as an engine face.)
|
||||
//
|
||||
// slots the item's icon and carried count; an empty slot shows +
|
||||
// click uses the slot's item (the same object if still carried, else a
|
||||
// stack with its name); on an empty slot, puts the selected
|
||||
// inventory item there
|
||||
// right Set to the selected item, Clear, More / Fewer slots
|
||||
// drop drag an item from the game's inventory (or the Inventory panel)
|
||||
// onto a slot to put it there (UiDropTargets, one target a slot)
|
||||
// status the use waiting for the server, or how the last one ended
|
||||
//
|
||||
// A click never calls AC from the render thread: it posts an InventoryModel
|
||||
// Use request, which AC's main thread sends at its next tick behind the
|
||||
// client's own item gate (one item action at a time; a click while one waits
|
||||
// is refused, not queued). Slots are saved per character (ItemHudStore).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class MiniRemoteFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Mini Remote";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(184, 150), new Vector2(110, 96), EdgeToEdge: true, GripInBody: true),
|
||||
() => new MiniRemoteFace());
|
||||
ItemHudStore.EnsureLoadQueued();
|
||||
}
|
||||
|
||||
private const float Slot = 36f, Gap = 4f, IconSize = 32f, StatusH = 18f;
|
||||
private const string MenuId = "##miniremote_menu";
|
||||
private static readonly string[] DropKeys = BuildDropKeys();
|
||||
|
||||
private static string[] BuildDropKeys()
|
||||
{
|
||||
var keys = new string[ItemHudCharacter.MaxSlots];
|
||||
for (int i = 0; i < keys.Length; i++) keys[i] = "MiniRemote#" + i.ToString(CultureInfo.InvariantCulture);
|
||||
return keys;
|
||||
}
|
||||
|
||||
private readonly HudItemCache _items = new();
|
||||
private string _message = "";
|
||||
private uint _messageColor;
|
||||
private long _messageUntilMs;
|
||||
private int _menuSlot = -1;
|
||||
private bool _openMenu;
|
||||
|
||||
// Per-slot resolved item and count text, rebuilt when the carried items or the slots change.
|
||||
private int _resolvedItemsVersion = -1;
|
||||
private ItemHudCharacter? _resolvedFor;
|
||||
private uint[] _slotItem = Array.Empty<uint>();
|
||||
private string[] _slotCount = Array.Empty<string>();
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
ItemHudStore.EnsureLoadQueued();
|
||||
InventoryModel.Subscribe();
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
InventoryModel.Unsubscribe();
|
||||
_menuSlot = -1;
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
InventoryView view = InventoryModel.Current;
|
||||
HudItem[] items = _items.Get(view);
|
||||
ItemHudCharacter data = ItemHudStore.Current;
|
||||
bool ready = ItemHudStore.Loaded && ItemHudStore.HasCharacter && view.PlayerId != 0;
|
||||
Resolve(data, items);
|
||||
|
||||
float gridH = Math.Max(Slot, Remaining(origin, size) - StatusH - GripOverlap());
|
||||
DrawGrid(data, items, w, gridH, ready);
|
||||
DrawStatus(ready);
|
||||
End(origin, size);
|
||||
DrawMenu(data, items);
|
||||
}
|
||||
|
||||
private void Resolve(ItemHudCharacter data, HudItem[] items)
|
||||
{
|
||||
if (ReferenceEquals(data, _resolvedFor) && _resolvedItemsVersion == _items.Version) return;
|
||||
_resolvedFor = data;
|
||||
_resolvedItemsVersion = _items.Version;
|
||||
int n = data.Slots.Length;
|
||||
_slotItem = new uint[n];
|
||||
_slotCount = new string[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
RemoteSlot? s = data.Slots[i];
|
||||
if (s == null) { _slotCount[i] = ""; continue; }
|
||||
_slotItem[i] = ItemHudMath.Resolve(items, s);
|
||||
long c = s.Name.Length > 0 ? ItemHudMath.Count(items, s.Name) : _slotItem[i] != 0 ? 1 : 0;
|
||||
_slotCount[i] = c > 1 ? c.ToString(CultureInfo.InvariantCulture) : c == 0 ? "0" : "";
|
||||
}
|
||||
}
|
||||
|
||||
// ── Grid ────────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawGrid(ItemHudCharacter data, HudItem[] items, float w, float h, bool ready)
|
||||
{
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
int cols = Math.Max(1, (int)((w + Gap) / (Slot + Gap)));
|
||||
bool dragging = ready && UiDropTargets.AnyDragInProgress;
|
||||
int clicked = -1;
|
||||
|
||||
for (int i = 0; i < data.Slots.Length; i++)
|
||||
{
|
||||
var p = new Vector2(start.X + (i % cols) * (Slot + Gap), start.Y + (i / cols) * (Slot + Gap));
|
||||
var max = p + new Vector2(Slot, Slot);
|
||||
RemoteSlot? s = data.Slots[i];
|
||||
|
||||
// One drop target a slot, so the item lands where it was let go.
|
||||
UiDropTargets.Publish(DropKeys[i], Title, p, max, ready);
|
||||
if (UiDropTargets.TryTake(DropKeys[i], out uint dropped) && ready)
|
||||
SetSlot(i, dropped, items);
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##slot", new Vector2(Slot, Slot))) clicked = i;
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _menuSlot = i; _openMenu = true; }
|
||||
ImGuiNET.ImGui.PopID();
|
||||
|
||||
bool dropHot = dragging && UiDropTargets.IsCursorOver(DropKeys[i]);
|
||||
dl.AddRectFilled(p, max, dropHot ? Green : hot ? Lighten(BtnFill) : BtnFill, 3);
|
||||
dl.AddRect(p, max, dropHot || dragging ? Teal : BtnBord, 3);
|
||||
|
||||
uint id = s != null && i < _slotItem.Length ? _slotItem[i] : 0;
|
||||
Vector2 ip = p + new Vector2((Slot - IconSize) * 0.5f, (Slot - IconSize) * 0.5f);
|
||||
if (s == null)
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Plus, p, new Vector2(Slot, Slot), Faded(Mute));
|
||||
if (hot) ImGuiNET.ImGui.SetItemTooltip("Empty slot: click to put the selected inventory item here, or drag an item onto it.");
|
||||
continue;
|
||||
}
|
||||
if (id != 0 && ScriptIcons.TryGet(ScriptIconKind.Object, id, out IntPtr tex))
|
||||
dl.AddImage(tex, ip, ip + new Vector2(IconSize, IconSize));
|
||||
else
|
||||
{
|
||||
string initial = s.Name.Length > 0 ? s.Name[..1].ToUpperInvariant() : "?";
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(initial);
|
||||
dl.AddText(p + (new Vector2(Slot, Slot) - ts) * 0.5f, Faded(Text), initial);
|
||||
}
|
||||
string count = _slotCount[i];
|
||||
if (count.Length > 0)
|
||||
{
|
||||
Vector2 cs = ImGuiNET.ImGui.CalcTextSize(count);
|
||||
Vector2 cp = max - cs - new Vector2(3, 1);
|
||||
dl.AddText(cp + new Vector2(1, 1), 0xE0000000, count);
|
||||
dl.AddText(cp, id == 0 ? Amber : Text, count);
|
||||
}
|
||||
if (hot)
|
||||
ImGuiNET.ImGui.SetItemTooltip(id == 0
|
||||
? $"{s.Name}: none carried.\nRight-click for options."
|
||||
: $"{s.Name} ({count switch { "" => "1", _ => count }} carried)\nClick to use. Right-click for options.");
|
||||
}
|
||||
int rows = (data.Slots.Length + cols - 1) / cols;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(start);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, Math.Min(h, rows * (Slot + Gap))));
|
||||
|
||||
if (clicked >= 0 && ready) Click(data, items, clicked);
|
||||
else if (clicked >= 0) ShowMessage(ItemHudStore.Loaded ? "Waiting for your character..." : "Loading...", Amber);
|
||||
}
|
||||
|
||||
private void Click(ItemHudCharacter data, HudItem[] items, int i)
|
||||
{
|
||||
RemoteSlot? s = data.Slots[i];
|
||||
if (s == null)
|
||||
{
|
||||
uint sel = InventoryModel.SelectedItem;
|
||||
if (sel != 0) SetSlot(i, sel, items);
|
||||
else ShowMessage("Select an inventory item (or drag one here) to fill this slot.", Amber);
|
||||
return;
|
||||
}
|
||||
uint id = i < _slotItem.Length ? _slotItem[i] : 0;
|
||||
if (id == 0) { ShowMessage($"No {s.Name} carried.", Amber); return; }
|
||||
// Posted to AC's main thread (InventoryModel's tick), never sent from here.
|
||||
var request = new InventoryRequest { Kind = InventoryActionKind.Use, ItemId = id, ItemName = s.Name };
|
||||
if (!InventoryModel.Request(request, out string why)) ShowMessage(why, Amber);
|
||||
}
|
||||
|
||||
private void SetSlot(int i, uint itemId, HudItem[] items)
|
||||
{
|
||||
string name = ItemCountFace.NameOf(itemId, items);
|
||||
if (name.Length == 0) { ShowMessage("That item's name isn't known yet; try again in a moment.", Amber); return; }
|
||||
if (!ItemHudMath.TryFind(items, itemId, out _))
|
||||
ShowMessage($"{name} isn't in your inventory; the slot uses one once you carry it.", Mute);
|
||||
else ShowMessage($"Slot {i + 1}: {name}.", Mute);
|
||||
if (!ItemHudStore.Update(d => d.WithSlot(i, new RemoteSlot(itemId, name)), out string why)) ShowMessage(why, Amber);
|
||||
}
|
||||
|
||||
// ── Status ──────────────────────────────────────────────────────────
|
||||
|
||||
private void ShowMessage(string text, uint color)
|
||||
{
|
||||
_message = text;
|
||||
_messageColor = color;
|
||||
_messageUntilMs = Environment.TickCount64 + 3500;
|
||||
}
|
||||
|
||||
private void DrawStatus(bool ready)
|
||||
{
|
||||
InventoryPending? pending = InventoryModel.Pending;
|
||||
InventoryResult? last = InventoryModel.LastResult;
|
||||
long nowTicks = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
string text;
|
||||
uint color;
|
||||
if (_message.Length > 0 && Environment.TickCount64 < _messageUntilMs) { text = _message; color = _messageColor; }
|
||||
else if (pending != null) { text = pending.WaitingForGame ? "Waiting for the game: " + pending.Label : pending.Label + "..."; color = Teal; }
|
||||
else if (last != null && nowTicks - last.AtTicks < System.Diagnostics.Stopwatch.Frequency * 4) { text = last.Text; color = last.Ok ? Green : Amber; }
|
||||
else if (!ready) { text = ItemHudStore.Loaded ? "Waiting for your character..." : "Loading..."; color = Mute; }
|
||||
else { text = "Click: use. Right-click: options."; color = Faded(Mute); }
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X - BodyGripRoom();
|
||||
dl.PushClipRect(p, p + new Vector2(Math.Max(10, w), StatusH), true);
|
||||
dl.AddText(p + new Vector2(0, 2), color, text);
|
||||
dl.PopClipRect();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(Math.Max(10, w), StatusH));
|
||||
}
|
||||
|
||||
private static float BodyGripRoom() => ImGuiPanelHost.BodyGripReserve;
|
||||
|
||||
// ── Right-click menu ────────────────────────────────────────────────
|
||||
|
||||
private void DrawMenu(ItemHudCharacter data, HudItem[] items)
|
||||
{
|
||||
if (_openMenu)
|
||||
{
|
||||
_openMenu = false;
|
||||
ImGuiNET.ImGui.OpenPopup(MenuId);
|
||||
}
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup(MenuId);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
if (!open) return;
|
||||
|
||||
int i = _menuSlot;
|
||||
RemoteSlot? s = i >= 0 && i < data.Slots.Length ? data.Slots[i] : null;
|
||||
Label(i >= 0 ? $"Slot {i + 1}{(s != null ? ": " + s.Name : " (empty)")}" : "Mini Remote", Mute);
|
||||
uint sel = InventoryModel.SelectedItem;
|
||||
string selName = sel != 0 && ItemHudMath.TryFind(items, sel, out HudItem it) ? it.Name : "";
|
||||
if (ImGuiNET.ImGui.MenuItem(selName.Length > 0 ? "Set to " + selName : "Set to the selected item", "", false, i >= 0 && selName.Length > 0))
|
||||
SetSlot(i, sel, items);
|
||||
if (ImGuiNET.ImGui.MenuItem("Clear slot", "", false, s != null))
|
||||
if (!ItemHudStore.Update(d => d.WithSlot(i, null), out string why)) ShowMessage(why, Amber);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
int n = data.Slots.Length;
|
||||
if (ImGuiNET.ImGui.MenuItem($"More slots ({n} now)", "", false, n < ItemHudCharacter.MaxSlots))
|
||||
ItemHudStore.Update(d => d.WithSlotCount(d.Slots.Length + 4), out _);
|
||||
if (ImGuiNET.ImGui.MenuItem("Fewer slots (drops the last 4)", "", false, n > ItemHudCharacter.MinSlots))
|
||||
ItemHudStore.Update(d => d.WithSlotCount(d.Slots.Length - 4), out _);
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
|
|
@ -36,6 +36,10 @@ internal static class P1Faces
|
|||
SkillsFace.Register();
|
||||
// Sense (watch list of names, anywhere the client knows): ImGui only, like Skills.
|
||||
SenseFace.Register();
|
||||
// Item Count and Mini Remote (items by name with their carried count; a grid of
|
||||
// items to use): ImGui only, saved per character in item_huds.txt.
|
||||
ItemCountFace.Register();
|
||||
MiniRemoteFace.Register();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,8 +9,10 @@
|
|||
// dungeons, towns, portals, with type and distance; takes
|
||||
// coordinates too), favorites and recent places while it's empty,
|
||||
// Go / Route / Arrow / Stop, the "Use portals and recalls" and
|
||||
// "Recalls" switches, the route step by step (the current step
|
||||
// highlighted, with the distance left), then two sections that
|
||||
// "Recalls" switches, the path markers switches (RynthNav 0.6.6:
|
||||
// the trip on the ground, labels, guide line), the route step by
|
||||
// step (the current step highlighted, with the distance left) and
|
||||
// "save as nav route" (a RynthAi .nav in NavProfiles), then two sections that
|
||||
// fold: Recalls (portal ties and where they land, "which tie was
|
||||
// it?", the recalls routes can use) and Info (here, the NavData
|
||||
// folder, the route graph, tiles; Load / Test / Preview and the
|
||||
|
|
@ -327,6 +329,7 @@ internal sealed class RynthNavFace : IImGuiPanel
|
|||
}
|
||||
NextLine(p, 28);
|
||||
if (st.HasAvoid) AvoidRows(st, w);
|
||||
if (st.HasMarkers) MarkerRow(st, w);
|
||||
}
|
||||
Line(w);
|
||||
|
||||
|
|
@ -507,6 +510,7 @@ internal sealed class RynthNavFace : IImGuiPanel
|
|||
dl.AddRectFilled(new Vector2(top.X, top.Y), new Vector2(top.X + 3, bottom), RunGreen, 1);
|
||||
}
|
||||
}
|
||||
DrawSaveRoute(st, cw);
|
||||
}
|
||||
|
||||
// ── Recalls section ──────────────────────────────────────────────────
|
||||
|
|
@ -672,6 +676,76 @@ internal sealed class RynthNavFace : IImGuiPanel
|
|||
NextLine(p, 26);
|
||||
}
|
||||
|
||||
// Path markers (RynthNav 0.6.6+): the planned trip on the ground, its labels, the guide line.
|
||||
// Each click sends /rnav markers ... (saved in rynthnav.json by RynthNav).
|
||||
private static void MarkerRow(RynthNavStatus st, float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float w1 = (w - 8) * 0.40f, w2 = (w - 8) * 0.28f, w3 = w - 8 - w1 - w2;
|
||||
if (Toggle("##mk_on", "Path markers", st.MarkersOn, p, w1))
|
||||
RynthNavCommands.Command(st.MarkersOn ? "markers off" : "markers on");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Show the planned trip on the ground, the way RynthAi shows its nav routes: rings at the\n"
|
||||
+ "waypoints, lines between them, the portals, recalls and the goal in their own colours.\n"
|
||||
+ "They go when the trip ends, you stop, or you land somewhere that isn't on it."
|
||||
+ (st.MarkerStatus.Length > 0 ? "\n\nNow: " + st.MarkerStatus : ""));
|
||||
if (Toggle("##mk_labels", "Labels", st.MarkerLabels, new Vector2(p.X + w1 + 4, p.Y), w2))
|
||||
RynthNavCommands.Command(st.MarkerLabels ? "markers labels off" : "markers labels on");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Names over the portal, recall, Town Network and goal markers.");
|
||||
if (Toggle("##mk_guide", "Guide line", st.MarkerGuide, new Vector2(p.X + w1 + w2 + 8, p.Y), w3))
|
||||
RynthNavCommands.Command(st.MarkerGuide ? "markers guide off" : "markers guide on");
|
||||
ImGuiNET.ImGui.SetItemTooltip("A line from your feet to the next waypoint (to the nearest marker for a plan you're not walking).");
|
||||
NextLine(p, 26);
|
||||
}
|
||||
|
||||
// ── Save as nav route (RynthNav 0.6.6+) ──────────────────────────────
|
||||
|
||||
private readonly byte[] _saveName = new byte[96];
|
||||
private string _saveSeenFor = "\u0001";
|
||||
|
||||
/// <summary>
|
||||
/// Below the route: a name (the place's, to start with) and Save, which writes the trip as a
|
||||
/// RynthAi nav route into NavProfiles (/rnav saveroute). A name already taken: Replace.
|
||||
/// </summary>
|
||||
private void DrawSaveRoute(RynthNavStatus st, float cw)
|
||||
{
|
||||
if (!st.HasSave || !st.CanSave) return;
|
||||
if (st.SaveFor != _saveSeenFor) { _saveSeenFor = st.SaveFor; WriteUtf8(_saveName, st.SaveName); }
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
SectionLabel("SAVE AS NAV ROUTE");
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float bw = 78;
|
||||
float boxW = Math.Max(60, cw - bw - 4);
|
||||
bool enter = TextBox("##save_name", _saveName, p, boxW, "Route name", out _, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
string name = Utf8(_saveName).Trim();
|
||||
bool can = name.Length > 0 && !st.SaveBusy;
|
||||
if (Button("##save_go", st.SaveBusy ? "Saving…" : PhosphorIcons.FloppyDisk + " Save", new Vector2(p.X + boxW + 4, p.Y), new Vector2(bw, 22),
|
||||
Teal, BtnFill, enabled: can) || (enter && can))
|
||||
RynthNavCommands.Command("saveroute " + name);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Write this trip as a RynthAi nav route (NavProfiles\\" + (name.Length > 0 ? name : "name") + ".nav):\n"
|
||||
+ "the walks as waypoints, portals as portal steps, recalls as recall steps.\n"
|
||||
+ "RynthAi lists it in its Nav picker; /ra nav load " + (name.Length > 0 ? name : "<name>") + " loads it.");
|
||||
NextLine(p, 26);
|
||||
if (st.SaveConflict.Length > 0 && st.SaveConflict.Equals(name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float rw = 78, tw = Math.Max(40, cw - rw - 4);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.PushClipRect(p, new Vector2(p.X + tw, p.Y + 22), true);
|
||||
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, name + ".nav is already there.");
|
||||
dl.PopClipRect();
|
||||
if (Button("##save_replace", "Replace", new Vector2(p.X + tw + 4, p.Y), new Vector2(rw, 22), Text, BtnFill, enabled: !st.SaveBusy, border: Amber))
|
||||
RynthNavCommands.Command("saveroute " + name + " overwrite");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Replace NavProfiles\\" + name + ".nav with this trip");
|
||||
NextLine(p, 26);
|
||||
}
|
||||
if (st.SaveLast.Length > 0)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
Wrapped(st.SaveLast, Mute, cw);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Toggle(string id, string label, bool on, Vector2 pos, float width)
|
||||
{
|
||||
string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label;
|
||||
|
|
|
|||
|
|
@ -42,6 +42,20 @@ internal static class UiDropTargets
|
|||
private static readonly Dictionary<string, Target> Targets = new(StringComparer.Ordinal);
|
||||
private static readonly object Sync = new();
|
||||
|
||||
/// <summary>
|
||||
/// The item being dragged in the engine's own Inventory panel (0 = none). Set by
|
||||
/// InventoryFace each frame; a drop outside that panel is offered here with TryClaim.
|
||||
/// </summary>
|
||||
public static uint EngineDragObject
|
||||
{
|
||||
get => System.Threading.Volatile.Read(ref _engineDrag);
|
||||
set => System.Threading.Volatile.Write(ref _engineDrag, value);
|
||||
}
|
||||
private static uint _engineDrag;
|
||||
|
||||
/// <summary>An item is being dragged, out of AC's UI or the Inventory panel (the faces' "drop here" look). AC thread.</summary>
|
||||
public static bool AnyDragInProgress => EngineDragObject != 0 || Compatibility.UiElementHooks.CurrentDragObject != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Once per frame from a face's Draw: <paramref name="min"/>..<paramref name="max"/> is the
|
||||
/// body in screen coordinates as ImGui sees them (FaceKit.Begin's origin and size).
|
||||
|
|
|
|||
43
src/RynthCore.Engine/ImGui/VideoPatchBanner.cs
Normal file
43
src/RynthCore.Engine/ImGui/VideoPatchBanner.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/VideoPatchBanner.cs
|
||||
// The "rendering paused" banner of the video patch's "all" mode
|
||||
// (D3D9/VideoPatch.cs): AC draws nothing then (the back buffer is only
|
||||
// cleared to black), so the window says why and how to get it back. Drawn on
|
||||
// ImGui's background list, under every panel. AC's render thread, inside the
|
||||
// main ImGui frame.
|
||||
// ============================================================================
|
||||
|
||||
using System.Numerics;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class VideoPatchBanner
|
||||
{
|
||||
private const string Line1 = "Rendering paused (video patch: all)";
|
||||
private const string Line2 = "Type /rc video off, or Settings > Misc > Video patch";
|
||||
|
||||
private static readonly uint Back = RynthTheme.Argb(0xC0101820);
|
||||
private static readonly uint Border = RynthTheme.Argb(0xFF34587A);
|
||||
private static readonly uint Title = RynthTheme.Argb(0xFF26D9E6);
|
||||
private static readonly uint Text = RynthTheme.Argb(0xFFB8C8D8);
|
||||
|
||||
public static void Draw()
|
||||
{
|
||||
if (!D3D9.VideoPatch.WantsBanner) return;
|
||||
ImGuiNET.ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
Vector2 display = io.DisplaySize;
|
||||
if (display.X <= 1 || display.Y <= 1) return;
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetBackgroundDrawList();
|
||||
Vector2 s1 = ImGuiNET.ImGui.CalcTextSize(Line1);
|
||||
Vector2 s2 = ImGuiNET.ImGui.CalcTextSize(Line2);
|
||||
float w = System.MathF.Max(s1.X, s2.X) + 32f;
|
||||
float h = s1.Y + s2.Y + 28f;
|
||||
Vector2 min = new((display.X - w) * 0.5f, (display.Y - h) * 0.5f);
|
||||
Vector2 max = min + new Vector2(w, h);
|
||||
dl.AddRectFilled(min, max, Back, 6f);
|
||||
dl.AddRect(min, max, Border, 6f);
|
||||
dl.AddText(new Vector2((display.X - s1.X) * 0.5f, min.Y + 10f), Title, Line1);
|
||||
dl.AddText(new Vector2((display.X - s2.X) * 0.5f, min.Y + 18f + s1.Y), Text, Line2);
|
||||
}
|
||||
}
|
||||
|
|
@ -84,13 +84,10 @@ internal static unsafe class Win32Backend
|
|||
/// HWNDs drop WM_LBUTTONDOWN on Win11 in some focus states).</summary>
|
||||
public const uint WM_RYNTH_RUN_ACTION = 0x8002;
|
||||
|
||||
/// <summary>UI deep-dive finding P0-1 belt-and-braces (2026-07-02):
|
||||
/// posted (not sent) by LayeredWindow.Dispose to destroy an HWND on the
|
||||
/// game thread without blocking the calling thread — DestroyWindow must
|
||||
/// run on the owning thread, but the caller (often the Avalonia UI
|
||||
/// thread, e.g. redocking a panel) doesn't need to wait for it to
|
||||
/// finish. wParam carries the HWND to destroy.</summary>
|
||||
public const uint WM_RYNTH_DESTROY_HWND = 0x8003;
|
||||
// 0x8003 was WM_RYNTH_DESTROY_HWND: LayeredWindow.Dispose's backup that posted a
|
||||
// panel's DestroyWindow to the game thread. Removed 2026-10-05 - DestroyWindow only
|
||||
// works on the window's owner thread, which isn't always the game thread. Panels now
|
||||
// destroy themselves (LayeredWindow WM_RYNTH_SELF_DESTROY). Don't reuse 0x8003.
|
||||
|
||||
/// <summary>Destroys floating-panel HWNDs on the game thread (their owner).
|
||||
/// wParam != 0 includes this engine load's own panels (sent synchronously by
|
||||
|
|
@ -395,38 +392,6 @@ internal static unsafe class Win32Backend
|
|||
RunOnGameThread<bool>(() => { action(); return true; });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI deep-dive finding P0-1 (2026-07-02): posts (does not block on) a
|
||||
/// DestroyWindow for <paramref name="hwnd"/> onto the game thread.
|
||||
/// DestroyWindow must run on the HWND's owning thread, but unlike
|
||||
/// RunOnGameThread this never needs the caller to observe a result — so
|
||||
/// it uses a dedicated PostMessage instead of the shared
|
||||
/// RunOnGameThread action slot, avoiding any risk of blocking the
|
||||
/// caller (e.g. LayeredWindow.Dispose called from the Avalonia UI
|
||||
/// thread while redocking a panel) on the game thread's WndProc.
|
||||
/// </summary>
|
||||
public static void PostDestroyWindow(IntPtr hwnd)
|
||||
{
|
||||
if (hwnd == IntPtr.Zero) return;
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
{
|
||||
// No game thread to marshal to (e.g. very early/late in
|
||||
// lifecycle) — best-effort inline as LayeredWindow.Dispose's own
|
||||
// fallback already does for the RunOnGameThread-unavailable case.
|
||||
DestroyWindow(hwnd);
|
||||
return;
|
||||
}
|
||||
|
||||
GetWindowThreadProcessId(_gameHwnd, out uint gameThreadId);
|
||||
if (gameThreadId == GetCurrentThreadId())
|
||||
{
|
||||
DestroyWindow(hwnd);
|
||||
return;
|
||||
}
|
||||
|
||||
PostMessage(_gameHwnd, WM_RYNTH_DESTROY_HWND, hwnd, IntPtr.Zero);
|
||||
}
|
||||
|
||||
/// <summary>Deactivates chat capture. The game HWND retains focus throughout so no
|
||||
/// Win32 focus transfer is needed.</summary>
|
||||
public static void ReturnFocusToGame() => ChatCaptureActive = false;
|
||||
|
|
@ -797,24 +762,6 @@ internal static unsafe class Win32Backend
|
|||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
if (msg == WM_RYNTH_DESTROY_HWND)
|
||||
{
|
||||
IntPtr target = wParam;
|
||||
try
|
||||
{
|
||||
bool destroyed = DestroyWindow(target);
|
||||
int err = destroyed ? 0 : Marshal.GetLastWin32Error();
|
||||
RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND DestroyWindow(0x{target.ToInt64():X}) = {destroyed} err={err}.");
|
||||
// 5 = ACCESS_DENIED: the window belongs to another thread. At least
|
||||
// take it off the screen so a closed panel can't linger beside a
|
||||
// reopened one (ShowWindow works across threads).
|
||||
if (!destroyed && err == 5)
|
||||
ShowWindow(target, 0 /* SW_HIDE */);
|
||||
}
|
||||
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
if (msg == WM_RYNTH_SWEEP_PANELS)
|
||||
{
|
||||
try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); }
|
||||
|
|
|
|||
Loading…
Reference in a new issue