worldbox-observer-mod/IdleSpectator/Story/LifeSagaPanel.cs
DazedAnon 58a67a198d feat(saga): replace tabs with character beat captions
- Compose Identity, Beat, and Context without mutating camera labels
- Move Cast and Legacy details into a hover-only panel
- Centralize relation, title, stake, and legacy prose
- Make rail clicks toggle Prefer without pinning a Saga subject
- Add harness coverage for caption composition and hover behavior
2026-07-22 17:09:13 -05:00

524 lines
17 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace IdleSpectator;
/// <summary>
/// Saga depth card under the character beat caption: Cast + Legacy.
/// Bound to the hover preview id. Identity lives on the caption (name · title);
/// no portrait / name / title / stake chrome here - that space goes to Cast.
/// Width is fixed to the rail chrome so right-anchored hover cannot slide the rail.
/// Height sizes to content (capped) so lines wrap fully instead of ellipsis.
/// </summary>
public static class LifeSagaPanel
{
/// <summary>Matches WatchCaption rail chrome inner width (PanelWidthMax - pads).</summary>
public const float BodyWidthFixed = 232f;
/// <summary>Hard cap so Saga never eats the screen.</summary>
public const float BodyHeightMax = 172f;
public const float BodyWidthMin = BodyWidthFixed;
public const float BodyWidthMax = BodyWidthFixed;
public const float BodyHeightMin = 12f;
public const float BodyHeightFixed = BodyHeightMax;
/// <summary>Shared cast budget for panel slots and presentation model.</summary>
public const int MaxCast = 8;
private const int MaxLegacy = 6;
private const int CastPerRow = 4;
private const float Pad = 3f;
private const float CastFace = 16f;
private const float CastSlotW = 54f;
private const float SecLabelH = 10f;
private const float LineH = 10f;
private const int BodyFont = 7;
private const int BuildVersion = 10;
private static GameObject _root;
private static RectTransform _rootRt;
private static Text _castHead;
private static Text _legacyHead;
private static Text _legacyText;
private static readonly CastSlot[] CastSlots = new CastSlot[MaxCast];
private static long _boundId;
private static string _speciesId = "";
private static string _fingerprint = "";
private static int _builtVersion;
private static float _laidOutHeight = BodyHeightMin;
private sealed class CastSlot
{
public GameObject Root;
public Image FaceBg;
public Image Face;
public Text Name;
public Text Relation;
public long UnitId;
}
public static bool Visible => _root != null && _root.activeSelf;
public static float BodyHeight => _laidOutHeight;
public static float BodyWidthPx => BodyWidthFixed;
public static long BoundUnitId => _boundId;
/// <summary>Always false - caption owns identity; panel never steals DossierAvatar.</summary>
public static bool OwnsAvatar => false;
public static string LastLayoutDebug { get; private set; } = "";
public static void EnsureBuilt(Transform parent)
{
if (parent == null)
{
return;
}
if (_root != null && _builtVersion == BuildVersion)
{
return;
}
if (_root != null)
{
UnityEngine.Object.Destroy(_root);
_root = null;
_rootRt = null;
_castHead = null;
_legacyHead = null;
_legacyText = null;
}
_root = new GameObject("LifeSagaPanel", typeof(RectTransform));
_root.transform.SetParent(parent, false);
_rootRt = _root.GetComponent<RectTransform>();
_rootRt.pivot = new Vector2(0f, 1f);
_rootRt.anchorMin = new Vector2(0f, 1f);
_rootRt.anchorMax = new Vector2(0f, 1f);
_rootRt.sizeDelta = new Vector2(BodyWidthFixed, BodyHeightMin);
_castHead = MakeLabel(_root.transform, "CastHead", BodyFont, HudTheme.Muted, FontStyle.Bold);
_castHead.text = "Cast";
_legacyHead = MakeLabel(_root.transform, "LegacyHead", BodyFont, HudTheme.Muted, FontStyle.Bold);
_legacyHead.text = "Legacy";
_legacyText = MakeLabel(_root.transform, "LegacyBody", BodyFont, HudTheme.Body, FontStyle.Normal);
_legacyText.horizontalOverflow = HorizontalWrapMode.Wrap;
_legacyText.verticalOverflow = VerticalWrapMode.Overflow;
for (int i = 0; i < MaxCast; i++)
{
CastSlots[i] = BuildCast(i);
}
_builtVersion = BuildVersion;
_root.SetActive(false);
}
public static void Clear()
{
_boundId = 0;
_speciesId = "";
_fingerprint = "";
_laidOutHeight = BodyHeightMin;
if (_root != null)
{
_root.SetActive(false);
}
}
public static void SetVisible(bool visible)
{
if (_root == null)
{
return;
}
_root.SetActive(visible);
}
public static void Bind(LifeSagaViewModel model)
{
if (_root == null)
{
return;
}
if (model == null || model.UnitId == 0)
{
Clear();
return;
}
string fp = Fingerprint(model);
bool same = string.Equals(fp, _fingerprint, System.StringComparison.Ordinal) && _boundId == model.UnitId;
_fingerprint = fp;
_boundId = model.UnitId;
_speciesId = model.SpeciesId ?? "";
if (!same)
{
int shownCast = 0;
for (int i = 0; i < model.Cast.Count && shownCast < CastSlots.Length; i++)
{
LifeSagaCastMember member = model.Cast[i];
if (member == null || CastDuplicatesCurrentBeat(member))
{
continue;
}
BindCast(CastSlots[shownCast], member);
shownCast++;
}
for (int i = shownCast; i < CastSlots.Length; i++)
{
CastSlots[i].Root.SetActive(false);
CastSlots[i].UnitId = 0;
}
var legacyParts = new List<string>(MaxLegacy);
var seen = new HashSet<string>();
string stakeKey = (model.StakeLine ?? "").Trim().ToLowerInvariant();
for (int i = 0; i < model.Legacy.Count && legacyParts.Count < MaxLegacy; i++)
{
if (model.Legacy[i] == null || string.IsNullOrEmpty(model.Legacy[i].Line))
{
continue;
}
string line = model.Legacy[i].Line.Trim();
string key = line.ToLowerInvariant();
if (!string.IsNullOrEmpty(stakeKey)
&& string.Equals(key, stakeKey, System.StringComparison.Ordinal))
{
continue;
}
if (!seen.Add(key))
{
continue;
}
legacyParts.Add(line);
}
_legacyText.text = legacyParts.Count > 0 ? string.Join("\n", legacyParts) : "";
}
Layout();
_root.SetActive(true);
}
public static float Place(float y, float padX)
{
if (!Visible || _rootRt == null)
{
return y;
}
_rootRt.anchoredPosition = new Vector2(padX, -y);
_rootRt.sizeDelta = new Vector2(BodyWidthFixed, _laidOutHeight);
return y + _laidOutHeight + 2f;
}
private static void Layout()
{
float fullX = Pad;
float fullW = BodyWidthFixed - Pad * 2f;
float y = Pad;
float yMax = BodyHeightMax - Pad;
// The Beat can update after the presentation model binds in the same frame.
// Recheck visible slots at layout time so the current scene partner is never
// repeated immediately below ("Bound with X" + "Lover X").
string liveBeat = WatchCaption.VisibleBeatLine ?? "";
for (int i = 0; i < CastSlots.Length; i++)
{
CastSlot slot = CastSlots[i];
if (slot?.Root == null || !slot.Root.activeSelf || slot.Name == null)
{
continue;
}
string castName = slot.Name.text ?? "";
if (!string.IsNullOrEmpty(castName)
&& liveBeat.IndexOf(castName, StringComparison.OrdinalIgnoreCase) >= 0)
{
slot.Root.SetActive(false);
slot.UnitId = 0;
}
}
int castN = 0;
for (int i = 0; i < CastSlots.Length; i++)
{
if (CastSlots[i].Root.activeSelf)
{
castN++;
}
}
if (castN > 0)
{
PlaceText(_castHead, fullX, y, fullW, SecLabelH);
y += SecLabelH;
float castRowH = CastFace + 18f;
float castX = fullX;
int col = 0;
for (int i = 0; i < CastSlots.Length; i++)
{
if (!CastSlots[i].Root.activeSelf)
{
continue;
}
if (col >= CastPerRow)
{
y += castRowH + 2f;
castX = fullX;
col = 0;
}
RectTransform rt = CastSlots[i].Root.GetComponent<RectTransform>();
rt.anchoredPosition = new Vector2(castX, -y);
rt.sizeDelta = new Vector2(CastSlotW, castRowH);
CastSlots[i].Root.transform.SetAsLastSibling();
castX += CastSlotW + 2f;
col++;
}
y += castRowH + 2f;
}
else
{
Hide(_castHead);
}
bool hasLegacy = !string.IsNullOrEmpty(_legacyText.text);
if (hasLegacy && y + SecLabelH + LineH <= yMax)
{
PlaceText(_legacyHead, fullX, y, fullW, SecLabelH);
y += SecLabelH;
float legacyH = Mathf.Clamp(
EstimateWrapHeight(_legacyText.text, fullW, BodyFont),
LineH,
LineH * 6f);
legacyH = Mathf.Min(legacyH, Mathf.Max(LineH, yMax - y));
PlaceText(_legacyText, fullX, y, fullW, legacyH);
_legacyText.horizontalOverflow = HorizontalWrapMode.Wrap;
_legacyText.verticalOverflow = VerticalWrapMode.Overflow;
y += legacyH + 2f;
}
else
{
Hide(_legacyHead);
Hide(_legacyText);
hasLegacy = false;
}
y = Mathf.Max(y + Pad, BodyHeightMin);
_laidOutHeight = Mathf.Clamp(y, BodyHeightMin, BodyHeightMax);
if (_rootRt != null)
{
_rootRt.sizeDelta = new Vector2(BodyWidthFixed, _laidOutHeight);
}
LastLayoutDebug =
$"w={BodyWidthFixed} h={_laidOutHeight:0.#} cast={castN} legacy={(hasLegacy ? 1 : 0)} castFirst=1";
}
private static float EstimateWrapHeight(string text, float width, float fontSize)
{
if (string.IsNullOrEmpty(text))
{
return LineH;
}
string[] paragraphs = text.Split('\n');
float total = 0f;
float charsPerLine = Mathf.Max(8f, width / Mathf.Max(3.8f, fontSize * 0.55f));
for (int i = 0; i < paragraphs.Length; i++)
{
string p = paragraphs[i];
int lines = Mathf.Max(1, Mathf.CeilToInt(Mathf.Max(1, p.Length) / charsPerLine));
total += lines * (fontSize + 2f);
}
return total;
}
private static CastSlot BuildCast(int index)
{
GameObject root = new GameObject("Cast" + index, typeof(RectTransform));
root.transform.SetParent(_root.transform, false);
RectTransform rootRt = root.GetComponent<RectTransform>();
rootRt.pivot = new Vector2(0f, 1f);
rootRt.anchorMin = new Vector2(0f, 1f);
rootRt.anchorMax = new Vector2(0f, 1f);
GameObject bgGo = new GameObject("FaceBg", typeof(RectTransform), typeof(Image));
bgGo.transform.SetParent(root.transform, false);
Image bg = bgGo.GetComponent<Image>();
bg.color = new Color(0.12f, 0.13f, 0.16f, 0.95f);
bg.raycastTarget = false;
RectTransform bgRt = bgGo.GetComponent<RectTransform>();
bgRt.pivot = new Vector2(0f, 1f);
bgRt.anchorMin = new Vector2(0f, 1f);
bgRt.anchorMax = new Vector2(0f, 1f);
bgRt.anchoredPosition = Vector2.zero;
bgRt.sizeDelta = new Vector2(CastFace, CastFace);
GameObject faceGo = new GameObject("Face", typeof(RectTransform), typeof(Image));
faceGo.transform.SetParent(bgGo.transform, false);
Image face = faceGo.GetComponent<Image>();
face.preserveAspect = true;
face.raycastTarget = false;
RectTransform faceRt = faceGo.GetComponent<RectTransform>();
faceRt.pivot = new Vector2(0.5f, 0.5f);
faceRt.anchorMin = new Vector2(0.5f, 0.5f);
faceRt.anchorMax = new Vector2(0.5f, 0.5f);
faceRt.anchoredPosition = Vector2.zero;
faceRt.sizeDelta = new Vector2(CastFace - 2f, CastFace - 2f);
Text name = MakeLabel(root.transform, "Name", BodyFont, HudTheme.Body, FontStyle.Normal);
Text relation = MakeLabel(root.transform, "Rel", BodyFont, HudTheme.Muted, FontStyle.Normal);
RectTransform nameRt = name.rectTransform;
nameRt.anchoredPosition = new Vector2(0f, -(CastFace + 1f));
nameRt.sizeDelta = new Vector2(CastSlotW, 9f);
RectTransform relRt = relation.rectTransform;
relRt.anchoredPosition = new Vector2(0f, -(CastFace + 9f));
relRt.sizeDelta = new Vector2(CastSlotW, 9f);
root.SetActive(false);
return new CastSlot
{
Root = root,
FaceBg = bg,
Face = face,
Name = name,
Relation = relation
};
}
private static void BindCast(CastSlot slot, LifeSagaCastMember member)
{
slot.UnitId = member.UnitId;
string name = string.IsNullOrEmpty(member.Name) ? "Someone" : member.Name;
string rel = string.IsNullOrEmpty(member.Relation) ? "Linked" : member.Relation;
FitCastText(slot.Name, name);
FitCastText(slot.Relation, rel);
Actor live = member.Alive ? EventFeedUtil.FindAliveById(member.UnitId) : null;
Sprite sprite = HudIcons.FromActorRailFace(live, member.SpeciesId)
?? HudIcons.FromSpeciesId(member.SpeciesId)
?? HudIcons.FromUiIcon("iconCitizen");
slot.Face.sprite = sprite;
slot.Face.enabled = sprite != null;
slot.Face.color = sprite != null ? Color.white : new Color(0.35f, 0.36f, 0.4f, 1f);
slot.FaceBg.color = member.Alive
? new Color(0.12f, 0.13f, 0.16f, 0.95f)
: new Color(0.18f, 0.12f, 0.12f, 0.95f);
slot.Root.SetActive(true);
}
/// <summary>The live Beat already explains the person currently on screen.</summary>
private static bool CastDuplicatesCurrentBeat(LifeSagaCastMember member)
{
string beat = WatchCaption.VisibleBeatLine ?? "";
return member != null
&& !string.IsNullOrEmpty(member.Name)
&& beat.IndexOf(member.Name, StringComparison.OrdinalIgnoreCase) >= 0;
}
private static void FitCastText(Text text, string value)
{
if (text == null)
{
return;
}
text.text = value ?? "";
text.resizeTextForBestFit = true;
text.resizeTextMinSize = 6;
text.resizeTextMaxSize = BodyFont;
text.horizontalOverflow = HorizontalWrapMode.Overflow;
text.verticalOverflow = VerticalWrapMode.Truncate;
}
private static Text MakeLabel(Transform parent, string name, int fontSize, Color color, FontStyle style)
{
int fitSize = fontSize < 7 ? 7 : fontSize;
Text text = HudCanvas.MakeText(parent, name, "", fitSize);
text.color = color;
text.fontStyle = style;
text.alignment = TextAnchor.UpperLeft;
text.horizontalOverflow = HorizontalWrapMode.Overflow;
text.verticalOverflow = VerticalWrapMode.Overflow;
text.raycastTarget = false;
RectTransform rt = text.rectTransform;
rt.pivot = new Vector2(0f, 1f);
rt.anchorMin = new Vector2(0f, 1f);
rt.anchorMax = new Vector2(0f, 1f);
return text;
}
private static void PlaceText(Text text, float x, float y, float w, float h)
{
if (text == null)
{
return;
}
text.resizeTextForBestFit = false;
text.enabled = true;
Color c = text.color;
if (c.a < 0.99f)
{
c.a = 1f;
text.color = c;
}
RectTransform rt = text.rectTransform;
rt.anchoredPosition = new Vector2(x, -y);
rt.sizeDelta = new Vector2(w, h);
text.gameObject.SetActive(!string.IsNullOrEmpty(text.text));
}
private static void Hide(Text text)
{
if (text != null)
{
text.gameObject.SetActive(false);
}
}
private static string Fingerprint(LifeSagaViewModel model)
{
var sb = new StringBuilder(192);
sb.Append(model.UnitId).Append('|').Append(model.StakeLine)
.Append('|').Append(WatchCaption.VisibleBeatLine);
for (int i = 0; i < model.Cast.Count; i++)
{
var c = model.Cast[i];
if (c == null)
{
continue;
}
sb.Append('|').Append(c.UnitId).Append(':').Append(c.Relation).Append(':').Append(c.Name);
}
for (int i = 0; i < model.Legacy.Count; i++)
{
if (model.Legacy[i] != null)
{
sb.Append('#').Append(model.Legacy[i].Line);
}
}
return sb.ToString();
}
}