## Summary
- **Add a self-referencing `InterpolationHandler` to `ValueStringBuilder`** that writes directly into the builder's buffer — zero intermediate allocation, works with `stackalloc`-backed builders
- **Replace all `System.Text.StringBuilder` usage** across the codebase with `ValueStringBuilder`
- **Convert `ValueStringBuilder.Create()` to `stackalloc`** at 10 sites where output length is provably bounded
- **Convert manual `Dispose()` to `using var`** where possible, and hoist loop-scoped builders outside loops with `Reset()`
- **Convert verbose `Append()` chains to `Append($"...")`** interpolation for readability
- **Add comprehensive documentation** for string handling patterns
## InterpolationHandler Design
`ValueStringBuilder` is a `ref struct`, which creates challenges for C#'s interpolated string handler pattern:
- **`ref` fields to ref structs are not allowed** (CS9050)
- **`[InterpolatedStringHandlerArgument("")]` passes struct receivers by value**, not by ref
- **`ISelfInterpolatedStringHandler` requires boxing** ref structs into interface fields
**Solution: Copy-and-reconcile pattern.** The handler receives a value copy of the builder. The copy shares the same underlying `char` buffer (`Span` points to the same `stackalloc`/pooled memory), so writes go to the original buffer. `Append()` reconciles by `this = handler._builder`, updating `_length` and any buffer references changed by `Grow()`.
This is safe because:
- The game loop is single-threaded — no concurrent access between handler construction and reconciliation
- If `Grow()` occurs in the copy, the original's stale buffer isn't accessed until `Append()` replaces it
- `Dispose()` correctly returns the reconciled buffer to the pool
## Changes by Category
### ValueStringBuilder (`Projects/Server/Buffers/ValueStringBuilder.cs`)
- Added nested `InterpolationHandler` ref struct with copy-and-reconcile pattern
- Added `Append([InterpolatedStringHandlerArgument("")] scoped ref InterpolationHandler)` method
- Removed `RawInterpolatedStringHandler` overloads (new handler replaces them)
- All `AppendFormatted` overloads delegate to existing `Append` methods (no code duplication)
- Alignment support via direct private field access (nested type privilege)
### StringBuilder → ValueStringBuilder (15 files)
Replaced all `new StringBuilder()` with `ValueStringBuilder.Create()` or `stackalloc`:
- ConPVP games: KingOfTheHill, DoubleDom, CTF, BombingRun, TourneyMatch
- ConPVP infrastructure: Tournament, Participant, TourneyParticipant
- ConPVP gumps: ArenaGump, TournamentBracketGump, AcceptTeamGump, ConfirmSignupGump
- Commands: Handlers, Logging, Add
- Other: TownCrier, SpeechLogGump, TestCenter
Key patterns:
- `sb = new StringBuilder()` reassignment → `sb.Reset()`
- `sb.AppendFormat("{0:N0}", value)` → `sb.Append($"{value:N0}")`
- `sb.Append(x).Append(y)` chains → separate statements (VSB returns void)
### Create() → stackalloc (10 files)
Converted heap-allocated builders to stackalloc where output is bounded:
- ClientVersion (32), MapSelection (160), HouseRaffleStone (48)
- HolySense (96), UnholySense (96), ClientVerification (192)
- AcceptTeamGump (64), ConfirmSignupGump (64)
- BaseWeapon (160), BaseArmor (128)
### Loop optimizations (2 files)
Hoisted `ValueStringBuilder` creation outside loops with `Reset()` per iteration:
- TourneyMatch.cs: `using var` inside for loop → stackalloc before loop
- ArenaGump.cs: `Create()` + `Dispose()` per iteration → stackalloc before loop
### Append chain → interpolation (5 files)
Converted multi-line `Append()` chains to `Append($"...")`:
- BountyMessage.cs: title switch (6 cases), paragraph (15→1 Append), description lines, closing
- AcceptTeamGump, ConfirmSignupGump, TournamentBracketGump: tournament type strings
- AdminGump: comment/tag formatting in loops
### Documentation
- `dev-docs/string-handling.md`: Full reference — construction, interpolation, disposal, decision guide
- `dev-docs/claude-skills/modernuo-string-handling.md`: Claude skill with quick reference
- `CLAUDE.md`: Added rule 17 (no StringBuilder), dev-docs table entry, skills table entry
- `dev-docs/code-standards.md`: Updated memory management section
## Test Plan
- [x] `dotnet build` — 0 errors, 0 warnings
- [x] `dotnet test` — 940/940 tests pass
- [x] 28 ValueStringBuilder tests covering all reconciliation scenarios:
- Stackalloc no-grow, stackalloc with grow (→pool transition)
- Heap no-grow, heap with grow, heap double grow
- Pre-existing content with and without grow
- Sequential multiple `Append($"...")` calls
- Mixed plain + interpolated Append
- Empty interpolation, literal-only, format specifiers
- Null string holes, ISpanFormattable types
- Dispose after stackalloc→pool grow
282 lines
7.5 KiB
C#
282 lines
7.5 KiB
C#
using System.Collections.Generic;
|
|
using ModernUO.Serialization;
|
|
using Server.Gumps;
|
|
using Server.Mobiles;
|
|
using Server.Network;
|
|
using Server.Text;
|
|
|
|
namespace Server.Engines.ConPVP;
|
|
|
|
[SerializationGenerator(0, false)]
|
|
public partial class ArenasMoongate : Item
|
|
{
|
|
[Constructible]
|
|
public ArenasMoongate() : base(0x1FD4)
|
|
{
|
|
Movable = false;
|
|
Light = LightType.Circle300;
|
|
}
|
|
|
|
public override string DefaultName => "arena moongate";
|
|
|
|
public bool UseGate(Mobile from)
|
|
{
|
|
if (DuelContext.CheckCombat(from))
|
|
{
|
|
from.SendMessage(0x22, "You have recently been in combat with another player and cannot use this moongate.");
|
|
return false;
|
|
}
|
|
|
|
if (from.Spell != null)
|
|
{
|
|
from.SendLocalizedMessage(1049616); // You are too busy to do that at the moment.
|
|
return false;
|
|
}
|
|
|
|
from.SendGump(new ArenaGump(from, this));
|
|
|
|
if (!from.Hidden || from.AccessLevel == AccessLevel.Player)
|
|
{
|
|
Effects.PlaySound(from.Location, from.Map, 0x20E);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public override void OnDoubleClick(Mobile from)
|
|
{
|
|
if (from.InRange(GetWorldLocation(), 1))
|
|
{
|
|
UseGate(from);
|
|
}
|
|
else
|
|
{
|
|
from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1019045); // I can't reach that
|
|
}
|
|
}
|
|
|
|
public override bool OnMoveOver(Mobile m) => !m.Player || UseGate(m);
|
|
}
|
|
|
|
public class ArenaGump : Gump
|
|
{
|
|
private readonly List<Arena> m_Arenas;
|
|
private readonly Mobile m_From;
|
|
private readonly ArenasMoongate m_Gate;
|
|
|
|
private int m_ColumnX = 12;
|
|
|
|
public override bool Singleton => true;
|
|
|
|
public ArenaGump(Mobile from, ArenasMoongate gate) : base(50, 50)
|
|
{
|
|
m_From = from;
|
|
m_Gate = gate;
|
|
m_Arenas = Arena.Arenas;
|
|
|
|
AddPage(0);
|
|
|
|
var height = 12 + 20 + m_Arenas.Count * 31 + 24 + 12;
|
|
|
|
AddBackground(0, 0, 499 + 40, height, 0x2436);
|
|
|
|
var list = m_Arenas;
|
|
|
|
for (var i = 1; i < list.Count; i += 2)
|
|
{
|
|
AddImageTiled(12, 32 + i * 31, 475 + 40, 30, 0x2430);
|
|
}
|
|
|
|
AddAlphaRegion(10, 10, 479 + 40, height - 20);
|
|
|
|
AddColumnHeader(35, null);
|
|
AddColumnHeader(115, "Arena");
|
|
AddColumnHeader(325, "Participants");
|
|
AddColumnHeader(40, "Obs");
|
|
|
|
AddButton(499 + 40 - 12 - 63 - 4 - 63, height - 12 - 24, 247, 248, 1);
|
|
AddButton(499 + 40 - 12 - 63, height - 12 - 24, 241, 242, 2);
|
|
|
|
var sb = new ValueStringBuilder(stackalloc char[256]);
|
|
|
|
for (var i = 0; i < list.Count; ++i)
|
|
{
|
|
var ar = list[i];
|
|
|
|
var x = 12;
|
|
var y = 32 + i * 31;
|
|
|
|
var color = ar.Players.Count > 0 ? 0xCCFFCC : 0xCCCCCC;
|
|
|
|
AddRadio(x + 3, y + 1, 9727, 9730, false, i);
|
|
x += 35;
|
|
|
|
AddBorderedText(x + 5, y + 5, 115 - 5, ar.Name ?? "(no name)", color, 0);
|
|
x += 115;
|
|
|
|
sb.Reset();
|
|
|
|
if (ar.Players.Count > 0)
|
|
{
|
|
var ladder = Ladder.Instance;
|
|
|
|
if (ladder == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
LadderEntry p1 = null, p2 = null, p3 = null, p4 = null;
|
|
|
|
for (var j = 0; j < ar.Players.Count; ++j)
|
|
{
|
|
var mob = ar.Players[j];
|
|
var c = ladder.Find(mob);
|
|
|
|
if (p1 == null || c.Index < p1.Index)
|
|
{
|
|
p4 = p3;
|
|
p3 = p2;
|
|
p2 = p1;
|
|
p1 = c;
|
|
}
|
|
else if (p2 == null || c.Index < p2.Index)
|
|
{
|
|
p4 = p3;
|
|
p3 = p2;
|
|
p2 = c;
|
|
}
|
|
else if (p3 == null || c.Index < p3.Index)
|
|
{
|
|
p4 = p3;
|
|
p3 = c;
|
|
}
|
|
else if (p4 == null || c.Index < p4.Index)
|
|
{
|
|
p4 = c;
|
|
}
|
|
}
|
|
|
|
Append(ref sb, p1);
|
|
Append(ref sb, p2);
|
|
Append(ref sb, p3);
|
|
Append(ref sb, p4);
|
|
|
|
if (ar.Players.Count > 4)
|
|
{
|
|
sb.Append(", ...");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
sb.Append("Empty");
|
|
}
|
|
|
|
AddBorderedText(x + 5, y + 5, 325 - 5, sb.ToString(), color, 0);
|
|
x += 325;
|
|
|
|
AddBorderedText(x, y + 5, 40, Html.Center($"{ar.Spectators}"), color, 0);
|
|
}
|
|
|
|
sb.Dispose();
|
|
}
|
|
|
|
private void Append(ref ValueStringBuilder sb, LadderEntry le)
|
|
{
|
|
if (le == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (sb.Length > 0)
|
|
{
|
|
sb.Append(", ");
|
|
}
|
|
|
|
sb.Append(le.Mobile.Name);
|
|
}
|
|
|
|
public override void OnResponse(NetState sender, in RelayInfo info)
|
|
{
|
|
if (info.ButtonID != 1)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var switches = info.Switches;
|
|
|
|
if (switches.Length == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var opt = switches[0];
|
|
|
|
if (opt < 0 || opt >= m_Arenas.Count)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var arena = m_Arenas[opt];
|
|
|
|
if (!m_From.InRange(m_Gate.GetWorldLocation(), 1) || m_From.Map != m_Gate.Map)
|
|
{
|
|
m_From.SendLocalizedMessage(1019002); // You are too far away to use the gate.
|
|
}
|
|
else if (DuelContext.CheckCombat(m_From))
|
|
{
|
|
m_From.SendMessage(
|
|
0x22,
|
|
"You have recently been in combat with another player and cannot use this moongate."
|
|
);
|
|
}
|
|
else if (m_From.Spell != null)
|
|
{
|
|
m_From.SendLocalizedMessage(1049616); // You are too busy to do that at the moment.
|
|
}
|
|
else if (m_From.Map == arena.Facet && arena.Zone.Contains(m_From.Location))
|
|
{
|
|
m_From.SendLocalizedMessage(1019003); // You are already there.
|
|
}
|
|
else
|
|
{
|
|
BaseCreature.TeleportPets(m_From, arena.GateIn, arena.Facet);
|
|
|
|
m_From.Combatant = null;
|
|
m_From.Warmode = false;
|
|
m_From.Hidden = true;
|
|
|
|
m_From.MoveToWorld(arena.GateIn, arena.Facet);
|
|
|
|
Effects.PlaySound(arena.GateIn, arena.Facet, 0x1FE);
|
|
}
|
|
}
|
|
|
|
private void AddBorderedText(int x, int y, int width, string text, int color, int borderColor)
|
|
{
|
|
/*AddColoredText( x - 1, y, width, text, borderColor );
|
|
AddColoredText( x + 1, y, width, text, borderColor );
|
|
AddColoredText( x, y - 1, width, text, borderColor );
|
|
AddColoredText( x, y + 1, width, text, borderColor );*/
|
|
/*AddColoredText( x - 1, y - 1, width, text, borderColor );
|
|
AddColoredText( x + 1, y + 1, width, text, borderColor );*/
|
|
AddColoredText(x, y, width, text, color);
|
|
}
|
|
|
|
private void AddColoredText(int x, int y, int width, string text, int color)
|
|
{
|
|
AddHtml(x, y, width, 20, color == 0 ? text : text.Color(color));
|
|
}
|
|
|
|
private void AddColumnHeader(int width, string name)
|
|
{
|
|
AddBackground(m_ColumnX, 12, width, 20, 0x242C);
|
|
AddImageTiled(m_ColumnX + 2, 14, width - 4, 16, 0x2430);
|
|
|
|
if (name != null)
|
|
{
|
|
AddBorderedText(m_ColumnX, 13, width, name.Center(), 0xFFFFFF, 0);
|
|
}
|
|
|
|
m_ColumnX += width;
|
|
}
|
|
}
|