using System; using System.Collections.Generic; using NeoModLoader.services; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; namespace IdleSpectator; /// /// Compact dossier: nametag (species/name/lv/task/sex), avatar + mini History, statuses, traits, reason. /// public static class WatchCaption { private const float PanelWidthMax = 420f; private const float SpeciesSize = 16f; private const float SexSize = 14f; private const float LiveMax = 44f; private const float ChipIcon = 12f; /// Fixed nametag task label slot so text swaps do not autofit-tick the header. private const float TaskLabelW = 78f; private const float TraitIcon = 12f; private const float HistoryIcon = 10f; private const float HistoryColMinW = 118f; private const float NameMinW = 28f; /// Hard cap so long "Name (Species/Job)" lines cannot paint under the level chip. private const float NameMaxW = 230f; private const float PadX = 4f; /// Inset from the canvas top-right corner (grows left via pivot). private const float ScreenInset = 12f; private const float PadTop = 4f; private const float HeaderH = 18f; private const float BodyH = 44f; private const float TraitsH = 14f; private const float StatusesH = 14f; private const float ReasonH = 14f; private const float HistoryLineMinH = 13f; private const float HistoryLineMaxH = 100f; private const float Gap = 2f; private const int HistoryPeekMax = 3; private const float BtnSize = 16f; private const float StatusBannerSeconds = 5f; /// History column grows with content until the dossier hits . private static float HistoryColMaxW => Mathf.Max(HistoryColMinW, PanelWidthMax - PadX * 2f - LiveMax - 4f); private static float _panelWidth = LiveMax + PadX * 2f; private static readonly Color NameColor = new Color(0.95f, 0.93f, 0.88f, 1f); private static readonly Color StatValueColor = new Color(1f, 0.62f, 0.28f, 1f); private static readonly Color TaskColor = new Color(0.26f, 1f, 0.26f, 1f); private static readonly Color ReasonColor = new Color(0.95f, 0.72f, 0.38f, 1f); private static readonly Color TraitNameColor = new Color(0.78f, 0.8f, 0.84f, 1f); private static readonly Color StatusNameColor = new Color(0.62f, 0.82f, 0.92f, 1f); private static readonly Color HistoryTextColor = new Color(0.82f, 0.84f, 0.86f, 1f); private static readonly Color StatusBannerColor = new Color(1f, 0.55f, 0.18f, 1f); private static GameObject _root; private static RectTransform _rootRt; private static Image _speciesIcon; private static Image _sexIcon; private static Text _nameText; private static Text _reasonText; private static long _reasonOtherId; private static Image _levelIcon; private static Text _levelValue; private static Image _taskIcon; private static Text _taskText; private static readonly TraitSlot[] _traitSlots = new TraitSlot[UnitDossier.MaxTraitChips]; private static GameObject _traitsRow; private static readonly TraitSlot[] _statusSlots = new TraitSlot[UnitDossier.MaxStatusChips]; private static GameObject _statusesRow; private static int _lastStatusesFingerprint = int.MinValue; private static GameObject _historyCol; private static Image _activityBoxBg; private static RectTransform _lifeSep; private static readonly HistorySlot[] _historySlots = new HistorySlot[HistoryPeekMax]; private static readonly float[] _historySlotHeights = new float[HistoryPeekMax]; private static readonly bool[] _historySlotIsActivity = new bool[HistoryPeekMax]; private static float _historyColW = HistoryColMinW; private static int _lastHistoryCount = -1; private static long _lastHistorySubjectId; private static int _lastLiveHistFingerprint = int.MinValue; private const float LifeSepH = 3f; private static Button _favoriteBtn; private static Image _favoriteIcon; private static bool _pinnedWhilePaused; /// Harness ForceNametagHeadline lock - skip live identity overwrite until rebuild. private static bool _headlineLocked; private static UnitDossier _current; private static Actor _boundActor; private static bool _visible; private static string _statusBanner = ""; private static float _statusBannerUntil; private sealed class TraitSlot { public GameObject Root; public Image Icon; public Text Label; public DossierChipTip Tip; } private sealed class HistorySlot { public GameObject Root; public Image Icon; public Text Label; public Button Button; public Image Hit; public long OtherId; } public static UnitDossier Current => _current; /// Living actor currently bound to the dossier (null for fallen archive). public static Actor BoundActor => _boundActor; public static string LastHeadline { get; private set; } = ""; public static string LastDetail { get; private set; } = ""; public static string LastCaptionText { get; private set; } = ""; /// Harness: newest mini-history line currently shown (if any). public static string LastHistoryPreview { get; private set; } = ""; /// Harness: all visible peek lines joined (activity + life). public static string LastHistoryJoined { get; private set; } = ""; /// Harness: how many history lines are currently visible on the dossier. public static int LastHistoryShown { get; private set; } /// Harness: activity feed lines currently visible. public static int LastActivityShown { get; private set; } /// Harness: Chronicle Life lines currently visible in the dossier column. public static int LastLifeShown { get; private set; } /// Current dossier subject id (0 if none). public static long CurrentUnitId => _current != null ? _current.UnitId : 0; /// True when dossier is shown while idle is paused for Lore browsing. public static bool PinnedWhilePaused => _pinnedWhilePaused; /// True when the history column fills the body width (no empty strip beside it). public static bool LastHistoryFillsBody { get; private set; } /// Legacy alias; dossier history is no longer scrollable. public static bool LastHistoryScrollable => false; /// Legacy alias for harness compatibility. public static bool HistoryExpanded => false; /// Harness: comma-joined top trait labels currently shown. public static string LastTraitsPreview { get; private set; } = ""; /// Harness: comma-joined top status labels currently shown. public static string LastStatusesPreview { get; private set; } = ""; public static Vector2 LastPanelSize { get; private set; } public static bool LastLayoutOk { get; private set; } /// True when the dossier card GameObject is active. public static bool Visible => _visible && _root != null && _root.activeSelf; /// Screen-pixel rect of the dossier card (Unity bottom-left origin), if visible. public static bool TryGetScreenPixelRect(out Rect pixelRect) { pixelRect = default; if (_rootRt == null || _root == null || !_root.activeInHierarchy) { return false; } Vector3[] corners = new Vector3[4]; _rootRt.GetWorldCorners(corners); float xMin = float.MaxValue; float yMin = float.MaxValue; float xMax = float.MinValue; float yMax = float.MinValue; for (int i = 0; i < 4; i++) { Vector2 sp = RectTransformUtility.WorldToScreenPoint(null, corners[i]); xMin = Mathf.Min(xMin, sp.x); yMin = Mathf.Min(yMin, sp.y); xMax = Mathf.Max(xMax, sp.x); yMax = Mathf.Max(yMax, sp.y); } float pad = 4f; pixelRect = Rect.MinMaxRect(xMin - pad, yMin - pad, xMax + pad, yMax + pad); return pixelRect.width > 8f && pixelRect.height > 8f; } /// True if the mouse is over the dossier panel (including the live sprite). public static bool IsPointerOverPanel() { if (_rootRt == null || _root == null || !_root.activeInHierarchy) { return false; } return RectTransformUtility.RectangleContainsScreenPoint(_rootRt, Input.mousePosition, null); } /// True if the mouse is over the dossier live sprite only. public static bool IsPointerOverAvatar() { return DossierAvatar.ContainsScreenPoint(Input.mousePosition); } /// True if the mouse is over a trait/status chip (vanilla tip host). public static bool IsPointerOverAssetChip() { if (!_visible || _root == null || !_root.activeInHierarchy) { return false; } Vector2 mouse = Input.mousePosition; for (int i = 0; i < _traitSlots.Length; i++) { if (IsPointerOverChipRoot(_traitSlots[i]?.Root, mouse)) { return true; } } for (int i = 0; i < _statusSlots.Length; i++) { if (IsPointerOverChipRoot(_statusSlots[i]?.Root, mouse)) { return true; } } return false; } private static bool IsPointerOverChipRoot(GameObject root, Vector2 mouse) { if (root == null || !root.activeInHierarchy) { return false; } RectTransform rt = root.GetComponent(); return rt != null && RectTransformUtility.RectangleContainsScreenPoint(rt, mouse, null); } /// /// Favorite control (and the panel chrome around it). /// Used so idle does not treat those clicks as "manual pause". /// public static bool IsPointerOverInteractive() { if (!IsPointerOverPanel()) { return false; } if (IsPointerOverButton(_favoriteBtn)) { return true; } // Whole dossier counts as UI while visible so history/trait chrome is safe to click. return _root != null && _root.activeInHierarchy; } private static bool IsPointerOverButton(Button button) { if (button == null || !button.gameObject.activeInHierarchy) { return false; } RectTransform rt = button.GetComponent(); return rt != null && RectTransformUtility.RectangleContainsScreenPoint(rt, Input.mousePosition, null); } public static void ToggleFavorite() { Actor actor = _boundActor; if (actor == null || !actor.isAlive()) { if (MoveCamera.hasFocusUnit()) { actor = MoveCamera._focus_unit; } } if (actor != null && actor.isAlive()) { try { actor.switchFavorite(); } catch { return; } Chronicle.SyncFavoriteFromActor(actor); RefreshFavoriteVisual(actor); LogService.LogInfo( $"[IdleSpectator] Favorite toggled name={SafeActorName(actor)} favorite={actor.isFavorite()}"); return; } // Fallen / archive: track in Chronicle so the Fallen filter stays consistent. long id = _current != null ? _current.UnitId : 0; if (id == 0) { id = Chronicle.CurrentHistorySubjectId(); } if (id == 0) { return; } bool next = !Chronicle.IsFavoriteSubject(id); Chronicle.SetFavoriteSubject(id, next); if (_current != null && _current.UnitId == id) { _current.IsFavorite = next; } RefreshFavoriteVisual(null); LogService.LogInfo($"[IdleSpectator] Favorite toggled fallen id={id} favorite={next}"); } public static void PinWhilePaused() { _pinnedWhilePaused = true; if (ModSettings.ShowDossierCaption) { SetVisible(true); } } public static void ClearPausePin() { _pinnedWhilePaused = false; } /// Open this unit's full history in the Lore panel (L / harness); pause idle auto-follow. public static void OpenFullHistoryInLore() { // Prefer the live camera focus so a pinned dossier cannot open the wrong unit's lore. long id = Chronicle.CurrentHistorySubjectId(); if (id == 0 && _current != null) { id = _current.UnitId; } if (id == 0) { return; } ChronicleHud.OpenUnitHistory(id, pauseIdle: true, followFocus: true); LogService.LogInfo($"[IdleSpectator] Open full history in Lore unitId={id}"); } private static string SafeActorName(Actor actor) { try { string n = actor.getName(); if (!string.IsNullOrEmpty(n)) { return n; } } catch { // ignore } return "unit"; } public static void Clear() { _current = null; _boundActor = null; LastHeadline = ""; LastDetail = ""; LastCaptionText = ""; LastHistoryPreview = ""; LastHistoryJoined = ""; LastHistoryShown = 0; LastActivityShown = 0; LastLifeShown = 0; LastHistoryFillsBody = false; _pinnedWhilePaused = false; LastTraitsPreview = ""; LastStatusesPreview = ""; LastPanelSize = Vector2.zero; LastLayoutOk = false; _lastHistoryCount = -1; _lastHistorySubjectId = 0; _lastStatusesFingerprint = int.MinValue; _headlineLocked = false; _historyColW = HistoryColMinW; _statusBanner = ""; _statusBannerUntil = 0f; ApplyVisual(null, null); SetVisible(false); } /// /// Show a short status line on the dossier (replaces the top WorldTip for pause exits). /// public static void ShowStatusBanner(string message, float seconds = StatusBannerSeconds) { if (!ModSettings.ShowDossierCaption || string.IsNullOrEmpty(message)) { return; } EnsureBuilt(); _statusBanner = message; _statusBannerUntil = Time.unscaledTime + Mathf.Max(0.5f, seconds); if (_nameText != null && (string.IsNullOrEmpty(_nameText.text) || _current == null)) { _nameText.text = "Idle Spectator"; LastHeadline = "Idle Spectator"; } if (_reasonText != null) { _reasonText.text = message; _reasonText.color = StatusBannerColor; _reasonText.supportRichText = false; _reasonText.resizeTextForBestFit = false; _reasonText.horizontalOverflow = HorizontalWrapMode.Wrap; _reasonText.verticalOverflow = VerticalWrapMode.Overflow; _reasonText.gameObject.SetActive(true); WireReasonClick(0); } LastCaptionText = (LastHeadline ?? "Idle Spectator") + " | " + message; // Re-fill from the current subject so Relayout cannot resurrect stale history slots // from a previously focused unit (activeSelf stays true while the column is hidden). int hist = _current != null ? FillHistory(_current.UnitId) : 0; bool hasTask = _taskText != null && _taskText.gameObject.activeSelf; bool hasBody = _boundActor != null || hist > 0 || _current != null; Relayout( hasBody, CountActiveTraitSlots(), CountActiveStatusSlots(), hasTask, hasReason: true, hist); SetVisible(true); LogService.LogInfo("[IdleSpectator][CAPTION] status=" + message); } public static void SetFromInterest(InterestEvent interest) { Actor unit = interest != null && interest.HasFollowUnit ? interest.FollowUnit : (MoveCamera.hasFocusUnit() ? MoveCamera._focus_unit : null); if (unit == null || !unit.isAlive()) { if (interest != null) { // Location-only / no unit: tip text for logs; dossier has no owned subject reason. LastHeadline = CameraDirector.FormatWatchTip(interest); LastDetail = ""; LastCaptionText = LastHeadline; LastHistoryPreview = ""; LastHistoryJoined = ""; _current = null; _boundActor = null; EnsureBuilt(); ApplyVisual(null, null); if (_nameText != null) { _nameText.text = LastHeadline; } Relayout(false, 0, 0, false, false, 0); SetVisible(ModSettings.ShowDossierCaption && SpectatorMode.Active); } return; } // Reason ownership comes from InterestDirector.TryGetOwnedReasonCandidate // (active dwell + owned unit), not from a sticky InterestEvent.Label. SetFromActor(unit, label: null); } public static void SetFromActor(Actor actor, string label = null) { if (!_pinnedWhilePaused) { ClearStatusBanner(); } UnitDossier dossier = UnitDossier.FromActor(actor, label); _current = dossier; _boundActor = actor; LastHeadline = dossier.Headline ?? ""; LastDetail = dossier.DetailLine ?? ""; LastCaptionText = dossier.CaptionText ?? ""; EnsureBuilt(); ApplyVisual(actor, dossier); SetVisible(ModSettings.ShowDossierCaption && (SpectatorMode.Active || _pinnedWhilePaused)); LogService.LogInfo("[IdleSpectator][CAPTION] " + LastCaptionText.Replace("\n", " | ")); } /// /// Show a stored dossier with no living actor (Fallen archive last living state). /// public static void SetFromDossier(UnitDossier dossier) { if (dossier == null || dossier.UnitId == 0) { return; } if (!_pinnedWhilePaused) { ClearStatusBanner(); } _current = dossier; _boundActor = null; LastHeadline = dossier.Headline ?? ""; LastDetail = dossier.DetailLine ?? ""; LastCaptionText = dossier.CaptionText ?? ""; EnsureBuilt(); ApplyVisual(null, dossier); SetVisible(ModSettings.ShowDossierCaption && (SpectatorMode.Active || _pinnedWhilePaused)); LogService.LogInfo( "[IdleSpectator][CAPTION] fallen dossier " + LastCaptionText.Replace("\n", " | ")); } public static void Update() { // History / manual pause: keep dossier pinned even after the banner timer expires. if (_pinnedWhilePaused && ModSettings.ShowDossierCaption) { if (SpectatorMode.Active) { ClearPausePin(); ClearStatusBanner(); } else { if (!_visible) { SetVisible(true); } // Keep the pause reason visible while browsing. if (!string.IsNullOrEmpty(_statusBanner)) { _statusBannerUntil = Time.unscaledTime + 1f; } RefreshLivePortrait(); RefreshLiveTask(); RefreshLiveIdentity(); RefreshLiveStatuses(); RefreshOwnedReason(); RefreshHistoryIfChanged(); return; } } if (HasStatusBanner()) { if (!_visible && ModSettings.ShowDossierCaption) { SetVisible(true); } if (!SpectatorMode.Active) { return; } // Idle resumed - drop banner and restore normal reason styling next ApplyVisual. ClearStatusBanner(); } if (!SpectatorMode.Active || !ModSettings.ShowDossierCaption) { if (_visible) { SetVisible(false); } return; } if (_root == null && !string.IsNullOrEmpty(LastCaptionText)) { EnsureBuilt(); Actor focus = MoveCamera.hasFocusUnit() ? MoveCamera._focus_unit : null; if (_current != null) { ApplyVisual(focus ?? _boundActor, _current); } else if (_nameText != null) { _nameText.text = LastHeadline; Relayout(false, 0, 0, false, false, 0); } SetVisible(true); } // Safety net: any focus change that skipped SetFromActor (or rematched follow) // must not leave the nametag on the previous person for a frame. ReconcileDossierToFocus(); RefreshLivePortrait(); RefreshLiveTask(); RefreshLiveIdentity(); RefreshLiveStatuses(); RefreshOwnedReason(); RefreshHistoryIfChanged(); } /// /// While Idle Spectator is live, dossier nametag must track the camera focus unit. /// Skips pause/fallen pins where the archive subject intentionally differs from focus. /// private static void ReconcileDossierToFocus() { if (_pinnedWhilePaused || !SpectatorMode.Active) { return; } if (!MoveCamera.hasFocusUnit() || MoveCamera._focus_unit == null) { return; } Actor focus = MoveCamera._focus_unit; if (!focus.isAlive()) { return; } long focusId = 0; try { focusId = focus.getID(); } catch { return; } if (focusId == 0) { return; } if (_current != null && _current.UnitId == focusId) { return; } SetFromActor(focus); } private static bool HasStatusBanner() { return !string.IsNullOrEmpty(_statusBanner) && Time.unscaledTime < _statusBannerUntil; } private static void ClearStatusBanner() { _statusBanner = ""; _statusBannerUntil = 0f; if (_reasonText != null) { _reasonText.color = ReasonColor; } } private static int CountActiveHistorySlots() { if (_historyCol == null || !_historyCol.activeSelf) { return 0; } int n = 0; for (int i = 0; i < _historySlots.Length; i++) { if (_historySlots[i]?.Root != null && _historySlots[i].Root.activeSelf) { n++; } } return n; } private static int CountActiveTraitSlots() { int n = 0; for (int i = 0; i < _traitSlots.Length; i++) { if (_traitSlots[i]?.Root != null && _traitSlots[i].Root.activeSelf) { n++; } } return n; } private static int CountActiveStatusSlots() { int n = 0; for (int i = 0; i < _statusSlots.Length; i++) { if (_statusSlots[i]?.Root != null && _statusSlots[i].Root.activeSelf) { n++; } } return n; } private static void RefreshLivePortrait() { if (!_visible) { return; } Actor actor = ResolveBoundLiveActor(); if (actor == null) { return; } DossierAvatar.Show(actor); BringHeaderFront(); } /// /// Keep orange reason in sync with director active dwell (clears in quiet_grace). /// private static void RefreshOwnedReason() { if (!_visible || _current == null || HasStatusBanner()) { return; } Actor actor = ResolveBoundLiveActor(); if (actor == null) { return; } // Honor harness reason override the same way FromActor/BuildStoryBeat does. string next; if (!string.IsNullOrEmpty(UnitDossier.HarnessReasonOverride)) { string subject = _current.Name ?? ""; if (string.IsNullOrEmpty(subject)) { subject = EventFeedUtil.SafeName(actor); } string relatedName = UnitDossier.HarnessReasonRelatedName ?? ""; _current.ReasonRelatedId = UnitDossier.HarnessReasonRelatedId != 0 ? UnitDossier.HarnessReasonRelatedId : ActivityLog.ResolveLivingUnitIdByName(relatedName, _current.UnitId); next = ActivityProse.ColorizePersonNames( UnitDossier.HarnessReasonOverride.Trim(), subject, relatedName); } else { next = UnitDossier.OwnedEventReason(actor, _current) ?? ""; } string prev = _current.ReasonLine ?? ""; if (next == prev) { return; } _current.ReasonLine = next; LastDetail = _current.DetailLine ?? ""; LastCaptionText = JoinCaptionLines(_current.Headline, next, _current.DetailLine); bool hasReason = !string.IsNullOrEmpty(next); if (_reasonText != null) { ApplyReasonText(hasReason ? next : "", hasReason ? _current.ReasonRelatedId : 0); } bool hasTask = !string.IsNullOrEmpty(_current.TaskText); Relayout( _current.UnitId != 0, CountActiveTraitSlots(), CountActiveStatusSlots(), hasTask, hasReason, CountActiveHistorySlots()); } private static string JoinCaptionLines(string headline, string reason, string detail) { var sb = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(headline)) { sb.Append(headline); } if (!string.IsNullOrEmpty(reason)) { if (sb.Length > 0) { sb.Append('\n'); } sb.Append(reason); } if (!string.IsNullOrEmpty(detail)) { if (sb.Length > 0) { sb.Append('\n'); } sb.Append(detail); } return sb.ToString(); } /// /// Keep the nametag task chip in sync with live AI (focus snapshot can miss brief no-task gaps). /// Never clears the chip on empty AI gaps - only replaces text when a new task is present. /// private static void RefreshLiveTask() { if (!_visible || _current == null) { return; } Actor actor = ResolveBoundLiveActor(); if (actor == null) { return; } string live = UnitDossier.ReadLiveTask(actor); // Hold the last shown label through brief no-task gaps so autofit does not collapse. if (string.IsNullOrEmpty(live)) { return; } string prev = _current.TaskText ?? ""; if (live == prev) { return; } bool wasShowing = _taskText != null && _taskText.gameObject.activeSelf; _current.TaskText = live; ReplaceTaskChip(live); // First appearance needs layout; later swaps only change text inside a fixed-width slot. if (!wasShowing) { bool hasBody = _current.UnitId != 0; bool hasReason = _reasonText != null && _reasonText.gameObject.activeSelf; Relayout( hasBody, CountActiveTraitSlots(), CountActiveStatusSlots(), hasTask: true, hasReason, CountActiveHistorySlots()); } BringHeaderFront(); } /// Keep nametag Species/Job identity tag in sync with live citizen job. private static void RefreshLiveIdentity() { if (!_visible || _current == null || HasStatusBanner() || _headlineLocked) { return; } Actor actor = ResolveBoundLiveActor(); if (actor == null) { return; } string job = UnitDossier.ReadLiveJobLabel(actor); string tag = UnitDossier.BuildIdentityTag(_current.SpeciesId, job); string headline = UnitDossier.BuildHeadline(_current.Name, tag); if (headline == (_current.Headline ?? "") && tag == (_current.IdentityTag ?? "") && job == (_current.JobLabel ?? "")) { return; } _current.JobLabel = job; _current.IdentityTag = tag; _current.Headline = headline; LastHeadline = headline; LastCaptionText = JoinCaptionLines(headline, _current.ReasonLine, _current.DetailLine); if (_nameText != null) { _nameText.text = headline; } bool hasTask = _taskText != null && _taskText.gameObject.activeSelf; bool hasReason = _reasonText != null && _reasonText.gameObject.activeSelf; Relayout( _current.UnitId != 0, CountActiveTraitSlots(), CountActiveStatusSlots(), hasTask, hasReason, CountActiveHistorySlots()); BringHeaderFront(); } /// Keep status chips in sync with live status set (fingerprint on top-4 ids). private static void RefreshLiveStatuses() { if (!_visible || _current == null) { return; } Actor actor = ResolveBoundLiveActor(); if (actor == null) { return; } UnitDossier probe = new UnitDossier(); UnitDossier.RefreshTopStatuses(probe, actor); int fp = StatusFingerprint(probe); if (fp == _lastStatusesFingerprint && StatusChipsMatch(_current.TopStatuses, probe.TopStatuses)) { return; } UnitDossier.RefreshTopStatuses(_current, actor); int statusCount = ApplyStatusChips(_current); _lastStatusesFingerprint = fp; bool hasTask = _taskText != null && _taskText.gameObject.activeSelf; bool hasReason = _reasonText != null && _reasonText.gameObject.activeSelf; Relayout( _current.UnitId != 0, CountActiveTraitSlots(), statusCount, hasTask, hasReason, CountActiveHistorySlots()); } private static int StatusFingerprint(UnitDossier dossier) { if (dossier == null || dossier.TopStatuses == null || dossier.TopStatuses.Count == 0) { return 0; } unchecked { int h = 17; for (int i = 0; i < dossier.TopStatuses.Count; i++) { string id = dossier.TopStatuses[i]?.Id ?? ""; h = h * 31 + StringComparer.OrdinalIgnoreCase.GetHashCode(id); } return h; } } private static bool StatusChipsMatch( System.Collections.Generic.List a, System.Collections.Generic.List b) { int na = a != null ? a.Count : 0; int nb = b != null ? b.Count : 0; if (na != nb) { return false; } for (int i = 0; i < na; i++) { string idA = a[i]?.Id ?? ""; string idB = b[i]?.Id ?? ""; if (!idA.Equals(idB, System.StringComparison.OrdinalIgnoreCase)) { return false; } } return true; } private static Actor ResolveBoundLiveActor() { Actor actor = _boundActor; if (actor == null || !actor.isAlive()) { if (MoveCamera.hasFocusUnit()) { actor = MoveCamera._focus_unit; } } if (actor == null || !actor.isAlive()) { return null; } if (_current != null && actor.getID() != _current.UnitId) { return null; } return actor; } private static string TruncateTaskLabel(string taskText) { if (string.IsNullOrEmpty(taskText)) { return ""; } return taskText.Length > 14 ? taskText.Substring(0, 13) + "..." : taskText; } /// Show or replace the task chip without ever blanking mid-update. private static void ReplaceTaskChip(string taskText) { if (string.IsNullOrEmpty(taskText)) { return; } if (_taskIcon != null) { HudIcons.Apply(_taskIcon, HudIcons.Task()); _taskIcon.gameObject.SetActive(true); } if (_taskText != null) { _taskText.text = TruncateTaskLabel(taskText); _taskText.gameObject.SetActive(true); } } private static void ApplyTaskChip(string taskText) { if (!string.IsNullOrEmpty(taskText)) { ReplaceTaskChip(taskText); return; } if (_taskIcon != null) { HudIcons.Apply(_taskIcon, null); _taskIcon.gameObject.SetActive(false); } if (_taskText != null) { _taskText.text = ""; _taskText.gameObject.SetActive(false); } } /// /// Harness: simulate a stale empty snapshot, then sync from live AI (replace, never stay blank if live has a task). /// public static string HarnessBlankAndRefreshTask() { if (_current != null) { _current.TaskText = ""; } // Do not hide the chip here - RefreshLiveTask must replace in place when live task exists. RefreshLiveTask(); return _current != null ? (_current.TaskText ?? "") : ""; } /// Harness: text currently shown on the nametag (may be ellipsis-truncated). public static string ShownNameChipText => _nameText != null && _nameText.gameObject.activeSelf ? (_nameText.text ?? "") : ""; /// Harness: text currently shown on the nametag task chip. public static string ShownTaskChipText => _taskText != null && _taskText.gameObject.activeSelf ? (_taskText.text ?? "") : ""; /// Harness: force a long nametag headline and relayout (layout overlap tests). public static void ForceNametagHeadline(string headline) { EnsureBuilt(); string text = string.IsNullOrEmpty(headline) ? "Nobody" : headline.Trim(); _headlineLocked = true; LastHeadline = text; if (_nameText != null) { _nameText.text = text; } if (_current != null) { _current.Headline = text; } bool hasBody = _current != null && _current.UnitId != 0; bool hasTask = _taskText != null && _taskText.gameObject.activeSelf; bool hasReason = _reasonText != null && _reasonText.gameObject.activeSelf; Relayout( hasBody, CountActiveTraitSlots(), CountActiveStatusSlots(), hasTask, hasReason, CountActiveHistorySlots()); } private static void BringHeaderFront() { // Draw nametag above vanilla avatar chrome (which can paint outside its host). void Front(Component c) { if (c != null) { c.transform.SetAsLastSibling(); } } Front(_speciesIcon); Front(_nameText); Front(_levelIcon); Front(_levelValue); Front(_taskIcon); Front(_taskText); Front(_sexIcon); Front(_favoriteBtn); } /// Harness: rebuild the dossier peek column after activity injects. public static void ForceRefreshHistory() { _lastHistoryCount = -1; _lastLiveHistFingerprint = int.MinValue; if (_current == null && MoveCamera.hasFocusUnit() && MoveCamera._focus_unit != null) { SetFromActor(MoveCamera._focus_unit); } if (!_visible || _current == null) { return; } RefreshHistoryIfChanged(); } /// /// Harness: force JobLabel onto the nametag identity tag (and optional orange reason beat). /// public static bool ForceJobLabelOnFocus( string jobLabel, string reasonOverride = "", long reasonRelatedId = 0, string reasonRelatedName = "") { if (!MoveCamera.hasFocusUnit() || MoveCamera._focus_unit == null) { return false; } UnitDossier.HarnessJobLabelOverride = jobLabel ?? ""; UnitDossier.HarnessReasonOverride = reasonOverride ?? ""; UnitDossier.HarnessReasonRelatedId = reasonRelatedId; UnitDossier.HarnessReasonRelatedName = reasonRelatedName ?? ""; SetFromActor(MoveCamera._focus_unit); return _current != null && !string.IsNullOrEmpty(_current.JobLabel) && (_current.Headline ?? "").IndexOf(_current.JobLabel, System.StringComparison.OrdinalIgnoreCase) >= 0; } public static void ClearHarnessJobOverrides() { UnitDossier.ClearHarnessOverrides(); } private static void RefreshHistoryIfChanged() { if (!_visible || _current == null) { return; } long id = _current.UnitId; int count = ActivityLog.CountFor(id) + Chronicle.HistoryCountFor(id); Actor live = ResolveBoundLiveActor(); int fingerprint = ActivityRelevance.LiveFingerprint(live, Time.unscaledTime); if (id == _lastHistorySubjectId && count == _lastHistoryCount && fingerprint == _lastLiveHistFingerprint) { return; } int shown = FillHistory(id); // Re-run layout only when history presence flips or line count changes. bool hasBody = _current != null; bool hasTask = _taskText != null && _taskText.gameObject.activeSelf; bool hasReason = _reasonText != null && _reasonText.gameObject.activeSelf; Relayout( hasBody, CountActiveTraitSlots(), CountActiveStatusSlots(), hasTask, hasReason, shown); } private static void ApplyVisual(Actor actor, UnitDossier dossier) { EnsureBuilt(); if (_root == null) { return; } _headlineLocked = false; bool hasLive = actor != null && actor.isAlive() && dossier != null && actor.getID() == dossier.UnitId; _boundActor = hasLive ? actor : null; if (_speciesIcon != null) { Sprite species = null; if (hasLive) { species = HudIcons.FromActor(actor); } else if (dossier != null) { species = HudIcons.FromSpeciesId(dossier.SpeciesId); } HudIcons.Apply(_speciesIcon, species); } bool hasSex = false; if (_sexIcon != null) { Sprite sexSprite = null; if (dossier != null) { if (dossier.IsMale) { sexSprite = HudIcons.SexMale(); } else if (dossier.IsFemale) { sexSprite = HudIcons.SexFemale(); } } HudIcons.Apply(_sexIcon, sexSprite); hasSex = sexSprite != null; _sexIcon.gameObject.SetActive(hasSex); } if (_nameText != null) { _nameText.text = dossier != null && !string.IsNullOrEmpty(dossier.Headline) ? dossier.Headline : ""; } bool hasBody = dossier != null && dossier.UnitId != 0; DossierAvatar.SetActive(hasBody); // Live units always show level; archive snapshots hide a blank 0. bool hasLevel = hasBody && (hasLive || dossier.Level > 0); if (_levelIcon != null) { HudIcons.Apply(_levelIcon, hasLevel ? HudIcons.Level() : null); _levelIcon.gameObject.SetActive(hasLevel); } if (_levelValue != null) { _levelValue.text = hasLevel ? dossier.Level.ToString() : ""; _levelValue.gameObject.SetActive(hasLevel); } if (hasLive) { DossierAvatar.Show(actor); ActivityLog.EnsureCurrentTask(actor); } else if (hasBody) { DossierAvatar.ShowSpecies(dossier.SpeciesId); } else { DossierAvatar.ClearActor(); } bool hasTask = dossier != null && !string.IsNullOrEmpty(dossier.TaskText); ApplyTaskChip(hasTask ? dossier.TaskText : ""); int traitCount = ApplyTraitChips(dossier); int statusCount = ApplyStatusChips(dossier); _lastStatusesFingerprint = StatusFingerprint(dossier); int historyCount = 0; if (dossier != null) { historyCount = FillHistory(dossier.UnitId); } else { LastHistoryPreview = ""; LastHistoryJoined = ""; LastHistoryShown = 0; LastActivityShown = 0; LastLifeShown = 0; LastHistoryFillsBody = false; if (_historyCol != null) { _historyCol.SetActive(false); } } bool hasReason = dossier != null && !string.IsNullOrEmpty(dossier.ReasonLine); if (_reasonText != null) { ApplyReasonText( hasReason ? dossier.ReasonLine : "", hasReason && dossier != null ? dossier.ReasonRelatedId : 0); } Relayout(hasBody, traitCount, statusCount, hasTask, hasReason, historyCount); RefreshFavoriteVisual(hasLive ? actor : null); } /// Orange story beat with rich-text gold names; empty hides the row. private static void ApplyReasonText(string reasonRichOrPlain, long otherId = 0) { if (_reasonText == null) { return; } bool hasReason = !string.IsNullOrEmpty(reasonRichOrPlain); _reasonText.supportRichText = true; _reasonText.color = ReasonColor; _reasonText.horizontalOverflow = HorizontalWrapMode.Wrap; _reasonText.verticalOverflow = VerticalWrapMode.Overflow; _reasonText.resizeTextForBestFit = false; _reasonText.text = hasReason ? reasonRichOrPlain : ""; _reasonText.gameObject.SetActive(hasReason); WireReasonClick(hasReason ? otherId : 0); } private static void WireReasonClick(long otherId) { long subjectId = CurrentUnitId; _reasonOtherId = otherId != 0 && otherId != subjectId ? otherId : 0; if (_reasonText == null) { return; } var entry = _reasonText.gameObject.GetComponent(); if (entry == null) { entry = _reasonText.gameObject.AddComponent(); } entry.triggers.Clear(); bool clickable = _reasonOtherId != 0 && _reasonText.gameObject.activeSelf; _reasonText.raycastTarget = clickable; if (!clickable) { return; } long captured = _reasonOtherId; var down = new UnityEngine.EventSystems.EventTrigger.Entry { eventID = UnityEngine.EventSystems.EventTriggerType.PointerDown }; down.callback.AddListener(_ => OpenHistoryOtherInLore(captured)); entry.triggers.Add(down); } /// Harness: orange reason names another living unit. public static bool ReasonOtherClickable => _reasonOtherId != 0; /// Harness: click the orange reason to open the related unit in Lore. public static bool ClickReasonOther(out long otherId) { otherId = _reasonOtherId; if (otherId == 0) { return false; } OpenHistoryOtherInLore(otherId); return true; } private static int ApplyTraitChips(UnitDossier dossier) { int traitCount = 0; LastTraitsPreview = ""; if (_traitsRow == null) { return 0; } if (dossier == null || dossier.TopTraits.Count <= 0) { _traitsRow.SetActive(false); return 0; } _traitsRow.SetActive(true); System.Text.StringBuilder traitPreview = new System.Text.StringBuilder(); for (int i = 0; i < _traitSlots.Length; i++) { TraitSlot slot = _traitSlots[i]; if (slot == null || slot.Root == null) { continue; } if (i < dossier.TopTraits.Count) { UnitDossier.TraitChip chip = dossier.TopTraits[i]; slot.Root.SetActive(true); Sprite traitSprite = chip != null ? HudIcons.FromTrait(chip.Trait) : null; if (traitSprite == null && chip != null && !string.IsNullOrEmpty(chip.Id)) { traitSprite = HudIcons.FromUiIcon(chip.Id) ?? HudIcons.FromUiIcon("icon" + chip.Id); } HudIcons.Apply(slot.Icon, traitSprite); string name = chip != null ? (chip.Name ?? "") : ""; if (slot.Label != null) { slot.Label.text = name; } if (slot.Tip != null) { if (chip != null && (chip.Trait != null || !string.IsNullOrEmpty(chip.Id))) { slot.Tip.BindTrait(chip.Trait, chip.Id); slot.Tip.enabled = true; } else { slot.Tip.Clear(); slot.Tip.enabled = false; } } if (traitPreview.Length > 0) { traitPreview.Append(", "); } traitPreview.Append(name); traitCount++; } else { if (slot.Tip != null) { slot.Tip.Clear(); slot.Tip.enabled = false; } slot.Root.SetActive(false); } } LastTraitsPreview = traitPreview.ToString(); return traitCount; } private static int ApplyStatusChips(UnitDossier dossier) { int statusCount = 0; LastStatusesPreview = ""; if (_statusesRow == null) { return 0; } if (dossier == null || dossier.TopStatuses == null || dossier.TopStatuses.Count <= 0) { _statusesRow.SetActive(false); for (int i = 0; i < _statusSlots.Length; i++) { if (_statusSlots[i]?.Root != null) { _statusSlots[i].Root.SetActive(false); } } return 0; } _statusesRow.SetActive(true); System.Text.StringBuilder preview = new System.Text.StringBuilder(); for (int i = 0; i < _statusSlots.Length; i++) { TraitSlot slot = _statusSlots[i]; if (slot == null || slot.Root == null) { continue; } if (i < dossier.TopStatuses.Count) { UnitDossier.StatusChip chip = dossier.TopStatuses[i]; slot.Root.SetActive(true); Sprite sprite = chip != null ? (HudIcons.FromStatus(chip.Status) ?? HudIcons.FromStatusId(chip.Id)) : null; HudIcons.Apply(slot.Icon, sprite); string name = chip != null ? (chip.Name ?? "") : ""; if (slot.Label != null) { slot.Label.text = name; slot.Label.color = StatusNameColor; } if (slot.Tip != null) { if (chip != null && (chip.Status != null || !string.IsNullOrEmpty(chip.Id))) { slot.Tip.BindStatus(chip.Status, chip.Id); slot.Tip.enabled = true; } else { slot.Tip.Clear(); slot.Tip.enabled = false; } } if (preview.Length > 0) { preview.Append(", "); } preview.Append(name); statusCount++; } else { if (slot.Tip != null) { slot.Tip.Clear(); slot.Tip.enabled = false; } slot.Root.SetActive(false); } } LastStatusesPreview = preview.ToString(); return statusCount; } private static int FillHistory(long unitId) { // Activity first (prominent), then Chronicle Life fills remaining peek slots. // Always reserve one Life slot when the subject has chronicle history so Life // does not vanish under a busy activity ring (and chronicle smoke stays valid). int chronicleCount = Chronicle.HistoryCountFor(unitId); int actCap = chronicleCount > 0 ? HistoryPeekMax - 1 : HistoryPeekMax; Actor live = null; try { live = ResolveBoundLiveActor(); if (live != null && live.isAlive() && live.getID() != unitId) { live = null; } if (live == null && MoveCamera.hasFocusUnit() && MoveCamera._focus_unit != null && MoveCamera._focus_unit.isAlive() && MoveCamera._focus_unit.getID() == unitId) { live = MoveCamera._focus_unit; } } catch { live = null; } IReadOnlyList activity = live != null ? ActivityLog.LatestRelevantForSubject(live, unitId, actCap) : ActivityLog.LatestForSubject(unitId, actCap); int lifeNeed = Mathf.Max(0, HistoryPeekMax - (activity?.Count ?? 0)); IReadOnlyList life = lifeNeed > 0 ? Chronicle.LatestForSubject(unitId, lifeNeed) : System.Array.Empty(); _lastHistorySubjectId = unitId; _lastHistoryCount = ActivityLog.CountFor(unitId) + chronicleCount; _lastLiveHistFingerprint = ActivityRelevance.LiveFingerprint(live, Time.unscaledTime); LastHistoryPreview = ""; LastHistoryJoined = ""; LastHistoryShown = 0; LastActivityShown = 0; LastLifeShown = 0; _historyColW = HistoryColMinW; for (int i = 0; i < _historySlotHeights.Length; i++) { _historySlotHeights[i] = HistoryLineMinH; } if (_historyCol == null) { return 0; } int total = (activity?.Count ?? 0) + (life?.Count ?? 0); if (total == 0) { // Soft fallback: show current task as a single activity line when the ring is empty. string taskFallback = ""; try { Actor focus = MoveCamera.hasFocusUnit() ? MoveCamera._focus_unit : null; if (focus != null && focus.isAlive() && focus.getID() == unitId && focus.hasTask() && focus.ai?.task != null) { taskFallback = focus.ai.task.getLocalizedText() ?? ""; } } catch { taskFallback = ""; } if (string.IsNullOrEmpty(taskFallback)) { for (int i = 0; i < _historySlots.Length; i++) { HistorySlot slot = _historySlots[i]; if (slot?.Root != null) { slot.Root.SetActive(false); } if (slot?.Label != null) { slot.Label.text = ""; } _historySlotHeights[i] = 0f; } _historyCol.SetActive(false); LastHistoryShown = 0; LastActivityShown = 0; LastLifeShown = 0; LastHistoryFillsBody = false; LastHistoryPreview = ""; LastHistoryJoined = ""; return 0; } activity = new[] { new ActivityEntry { DisplayLine = taskFallback, Line = taskFallback, Kind = ActivityKind.TaskStart } }; total = 1; } _historyCol.SetActive(true); var lines = new List<(string rich, string plain, bool isActivity, ChronicleKind? kind, string activityKey, long otherId)>( HistoryPeekMax); if (activity != null) { for (int i = 0; i < activity.Count && lines.Count < HistoryPeekMax; i++) { ActivityEntry e = activity[i]; if (e == null) { continue; } string plain = !string.IsNullOrEmpty(e.DisplayLine) ? e.DisplayLine : e.Line; if (string.IsNullOrEmpty(plain)) { continue; } string rich = !string.IsNullOrEmpty(e.DisplayLineRich) ? e.DisplayLineRich : plain; long otherId = ResolveHistoryOtherId(unitId, e.RelatedId, e.TargetLabel); lines.Add((rich, plain, true, null, e.TaskId ?? "", otherId)); } } if (life != null) { for (int i = 0; i < life.Count && lines.Count < HistoryPeekMax; i++) { ChronicleEntry e = life[i]; if (e == null) { continue; } string plain = e.DisplayLine ?? e.HudLine ?? ""; string rich = e.DisplayLineRich ?? plain; if (string.IsNullOrEmpty(plain) && string.IsNullOrEmpty(rich)) { continue; } long otherId = e.OtherId != 0 && e.OtherId != unitId ? e.OtherId : 0; lines.Add((rich, plain, false, e.Kind, "", otherId)); } } float widestLabel = 0f; for (int i = 0; i < lines.Count && i < _historySlots.Length; i++) { HistorySlot slot = _historySlots[i]; if (slot?.Label == null) { continue; } Text label = slot.Label; label.supportRichText = true; label.resizeTextForBestFit = false; label.horizontalOverflow = HorizontalWrapMode.Overflow; label.verticalOverflow = VerticalWrapMode.Overflow; label.alignment = TextAnchor.UpperLeft; label.text = lines[i].plain; Canvas.ForceUpdateCanvases(); try { widestLabel = Mathf.Max(widestLabel, label.preferredWidth); } catch { widestLabel = Mathf.Max(widestLabel, lines[i].plain.Length * 6.2f); } } _historyColW = Mathf.Clamp( widestLabel + HistoryIcon + 4f, HistoryColMinW, HistoryColMaxW); ApplyCombinedSlotContents(lines, _historyColW); LastHistoryShown = CountActiveHistorySlots(); return LastHistoryShown; } private static void ApplyCombinedSlotContents( List<(string rich, string plain, bool isActivity, ChronicleKind? kind, string activityKey, long otherId)> lines, float colW) { float labelW = Mathf.Max(24f, colW - HistoryIcon - 2f); LastHistoryPreview = ""; LastHistoryJoined = ""; LastActivityShown = 0; LastLifeShown = 0; var joined = new List(HistoryPeekMax); for (int i = 0; i < _historySlots.Length; i++) { HistorySlot slot = _historySlots[i]; if (slot?.Root == null) { continue; } if (i >= lines.Count) { slot.Root.SetActive(false); slot.OtherId = 0; WireHistoryRowClick(slot, 0); _historySlotHeights[i] = 0f; _historySlotIsActivity[i] = false; continue; } var row = lines[i]; _historySlotIsActivity[i] = row.isActivity; slot.Root.SetActive(true); slot.OtherId = row.otherId; Sprite icon = row.isActivity ? (HudIcons.ForActivityKey(row.activityKey) ?? HudIcons.FromUiIcon("iconClock") ?? HudIcons.ForChronicleKind(ChronicleKind.Other)) : HudIcons.ForChronicleKind(row.kind ?? ChronicleKind.Other); HudIcons.Apply(slot.Icon, icon); if (slot.Label != null) { slot.Label.supportRichText = true; slot.Label.horizontalOverflow = HorizontalWrapMode.Wrap; slot.Label.verticalOverflow = VerticalWrapMode.Overflow; slot.Label.color = row.isActivity ? new Color(0.88f, 0.9f, 0.78f, 1f) : HistoryTextColor; slot.Label.text = row.rich ?? row.plain ?? ""; RectTransform lrt = slot.Label.GetComponent(); lrt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, labelW); Canvas.ForceUpdateCanvases(); float needed = HistoryLineMinH; try { needed = Mathf.Max(HistoryLineMinH, slot.Label.preferredHeight + 4f); } catch { int chars = (row.plain ?? "").Length; int perLine = Mathf.Max(12, (int)(labelW / 6.2f)); int wrapLines = Mathf.Max(1, (chars + perLine - 1) / perLine); needed = HistoryLineMinH * wrapLines; } _historySlotHeights[i] = Mathf.Clamp(needed, HistoryLineMinH, HistoryLineMaxH); } else { _historySlotHeights[i] = HistoryLineMinH; } WireHistoryRowClick(slot, row.otherId); if (row.isActivity) { LastActivityShown++; } else { LastLifeShown++; } string plain = (row.plain ?? "").Replace("\n", " "); joined.Add(plain); if (string.IsNullOrEmpty(LastHistoryPreview)) { LastHistoryPreview = plain; } } LastHistoryJoined = string.Join(" | ", joined); } private static void WireHistoryRowClick(HistorySlot slot, long otherId) { if (slot?.Root == null) { return; } slot.OtherId = otherId; if (slot.Hit == null) { slot.Hit = slot.Root.GetComponent(); if (slot.Hit == null) { slot.Hit = slot.Root.AddComponent(); } slot.Hit.color = new Color(1f, 1f, 1f, 0.001f); } if (slot.Button == null) { slot.Button = slot.Root.GetComponent