Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Languages/ChineseSimplified/Keyed/RimMind_Storyteller.xml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@
<RimMind.Storyteller.UI.Accept>了解</RimMind.Storyteller.UI.Accept>
<RimMind.Storyteller.UI.NoInterfere>你无权干涉叙事者的行动</RimMind.Storyteller.UI.NoInterfere>
<!-- TaskInstruction sub-keys for Incident Selector (extensible list) -->
<RimMind.Storyteller.Prompt.SystemInstruction>你是 RimWorld 的 AI 叙事者。根据殖民地当前状况,选择最合适的事件。综合考虑殖民地财富、威胁等级、食物储备、殖民者数量以及近期事件。输出必须为符合 IncidentOutput 结构的合法 JSON。</RimMind.Storyteller.Prompt.SystemInstruction>
<RimMind.Storyteller.Prompt.WorldRules>叙事者规则:
- 仅从可用的 RimWorld 事件定义中选择
- 结合殖民地财富评估威胁等级
- 平衡正面事件与负面事件
- 食物短缺时应触发相关事件
- 殖民者心情低落时可考虑给予正面事件</RimMind.Storyteller.Prompt.WorldRules>
<RimMind.Storyteller.Prompt.ChatSystemInstruction>你是这座 RimWorld 殖民地的 AI 叙事者,正通过叙事者祭坛与玩家直接对话。请以叙事者与导演的身份回应——敏锐、富有戏剧感,洞悉殖民地历史、叙事张力与近期事件。使用简洁自然的对话文本回复(切勿输出 JSON)。参考玩家的诉求,但不必盲从。</RimMind.Storyteller.Prompt.ChatSystemInstruction>
<RimMind.Storyteller.Prompt.TaskInstruction.Role>你是 RimWorld 游戏的叙事者,负责为殖民地创造有趣的故事。</RimMind.Storyteller.Prompt.TaskInstruction.Role>
<RimMind.Storyteller.Prompt.TaskInstruction.Goal>根据当前游戏状态和候选事件列表,选择最能推进故事的一个事件。</RimMind.Storyteller.Prompt.TaskInstruction.Goal>
<RimMind.Storyteller.Prompt.TaskInstruction.Process>1. 评估当前叙事张力——高张力时优先缓解性事件,低张力时优先挑战性事件
Expand Down
8 changes: 8 additions & 0 deletions Languages/English/Keyed/RimMind_Storyteller.xml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@
<RimMind.Storyteller.UI.Accept>Understood</RimMind.Storyteller.UI.Accept>
<RimMind.Storyteller.UI.NoInterfere>You have no authority to interfere with the storyteller's actions</RimMind.Storyteller.UI.NoInterfere>
<!-- TaskInstruction sub-keys for Incident Selector (extensible list) -->
<RimMind.Storyteller.Prompt.SystemInstruction>You are the RimWorld storyteller AI. Based on the colony's current situation, select the most appropriate incident event. Consider colony wealth, threat level, food supply, colonist count, and recent events. Output must be valid JSON matching the IncidentOutput schema.</RimMind.Storyteller.Prompt.SystemInstruction>
<RimMind.Storyteller.Prompt.WorldRules>Storyteller rules:
- Only select from available RimWorld incident definitions
- Consider threat level relative to colony wealth
- Balance positive and negative events
- Food shortages should trigger related events
- Low mood colonists may need positive events</RimMind.Storyteller.Prompt.WorldRules>
<RimMind.Storyteller.Prompt.ChatSystemInstruction>You are the AI Storyteller of this RimWorld colony speaking directly with the player through the Storyteller Altar. Respond in character as the narrator and director — perceptive, dramatic, and aware of colony history, narrative tension, and recent events. Reply in concise natural prose (do NOT output JSON). Consider player wishes without blindly obeying them.</RimMind.Storyteller.Prompt.ChatSystemInstruction>
<RimMind.Storyteller.Prompt.TaskInstruction.Role>You are the storyteller of a RimWorld game, responsible for creating interesting stories for the colony.</RimMind.Storyteller.Prompt.TaskInstruction.Role>
<RimMind.Storyteller.Prompt.TaskInstruction.Goal>Based on the current game state and candidate event list, select one event that best advances the story.</RimMind.Storyteller.Prompt.TaskInstruction.Goal>
<RimMind.Storyteller.Prompt.TaskInstruction.Process>1. Evaluate current narrative tension — prioritize relief events when tension is high, challenge events when tension is low
Expand Down
2 changes: 1 addition & 1 deletion Source/Debug/StorytellerDebugActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ private static void ForceAIIncidentSelection()
return;
}

if (!RimMindAPI.IsConfigured())
if (!RimMindAPI.Settings.IsConfigured())
{
RimMindErrors.Warn("[RimMind-Storyteller] API not configured.");
return;
Expand Down
10 changes: 3 additions & 7 deletions Source/Extensions/PawnLookup.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
using System;
using RimMind.Presentation.Api;
using Verse;

namespace RimMind.Storyteller.Extensions
{
/// <summary>
/// ContextKey 提供者共享的小人解析逻辑,统一委托给 <see cref="RimMindPawnLookup"/>(不扫描 WorldPawns)。
/// Legacy compatibility forwarder. Delegates directly to Core <see cref="RimMindPawnLookup"/>.
/// </summary>
[Obsolete("Use RimMind.Presentation.Api.RimMindPawnLookup directly.")]
public static class PawnLookup
{
/// <summary>
/// 按 thingIDNumber 查找小人。id 无效(&lt;= 0)或未找到时返回 null。
/// </summary>
public static Pawn? FindPawnById(int pawnId)
=> pawnId <= 0 ? null : RimMindPawnLookup.FindPawnByNumber(pawnId);

/// <summary>
/// 按字符串 ThingID 查找小人。id 为空或未找到时返回 null。
/// </summary>
public static Pawn? FindById(string? pawnId)
=> RimMindPawnLookup.FindPawnById(pawnId);
}
Expand Down
1 change: 1 addition & 0 deletions Source/Extensions/PawnLookupCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace RimMind.Storyteller.Extensions
{
[Obsolete("Use RimMind.Presentation.Api.RimMindPawnLookup directly.")]
public static class PawnLookupCore
{
public static T? FindById<T>(
Expand Down
3 changes: 2 additions & 1 deletion Source/Extensions/StorytellerContextBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text;
using RimMind.Presentation.Api;
using RimWorld;
using Verse;

Expand Down Expand Up @@ -86,7 +87,7 @@ public static void AppendDifficultyContext(StringBuilder sb)
string? guidanceKey = ResolveDifficultyGuidanceKey(tier);
if (guidanceKey != null)
{
string guidanceText = guidanceKey.CanTranslate() ? guidanceKey.TranslateSimple() : guidanceKey;
string guidanceText = RimMindAPI.Text.TrOr(guidanceKey, guidanceKey);
sb.AppendLine("RimMind.Storyteller.Prompt.DifficultyGuidance".Translate(guidanceText));
}
}
Expand Down
2 changes: 1 addition & 1 deletion Source/Extensions/StorytellerIncidentSkipCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ internal sealed class StorytellerIncidentSkipCheck : ISkipCheck
public bool ShouldSkip(in SkipCheckArgs args) => !_settings.enableIntervalTrigger;

public static bool ShouldSkipStorytellerIncident()
=> RimMind.Presentation.Api.RimMindAPI.ShouldSkipStorytellerIncident();
=> RimMind.Presentation.Api.RimMindAPI.Ext.ShouldSkipStorytellerIncident();
}
}
9 changes: 3 additions & 6 deletions Source/Extensions/StorytellerSettingsTab.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
using UnityEngine;
using RimMind.Presentation.Api;
using RimMind.Presentation.Settings;
using RimMind.Storyteller.Settings;
using Verse;
using UnityEngine;

namespace RimMind.Storyteller
{
internal sealed class StorytellerSettingsTabAdapter : ISettingsTab
{
public string Id => "storyteller";
public string OwnerModId => "RimMind.Storyteller";
public string Label => "RimMind.Storyteller.UI.TabLabel".CanTranslate()
? (string)"RimMind.Storyteller.UI.TabLabel".Translate()
: "Storyteller";
public string Label => RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.TabLabel", "Storyteller");
public void Draw(Rect rect) => Settings.StorytellerSettingsTab.Draw(rect);
}
}
71 changes: 13 additions & 58 deletions Source/Memory/StorytellerMemory.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RimMind.Presentation.Api;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;

namespace RimMind.Storyteller.Memory
Expand Down Expand Up @@ -99,8 +98,11 @@ public class StorytellerMemory : WorldComponent

public string CustomSystemPrompt = string.Empty;

private static StorytellerMemory? _instance;
public static StorytellerMemory? Instance => _instance;
private static readonly WorldScopedComponentCache<StorytellerMemory> _instanceCache =
new WorldScopedComponentCache<StorytellerMemory>();
public static StorytellerMemory? Instance => _instanceCache.Get();

internal static void ResetInstanceCache() => _instanceCache.Reset();

private float _tensionLevel = 0.5f;
public float TensionLevel => _tensionLevel;
Expand All @@ -112,7 +114,6 @@ public class StorytellerMemory : WorldComponent

public StorytellerMemory(World world) : base(world)
{
_instance = this;
}

public IReadOnlyList<IncidentHistoryRecord> Records => _records;
Expand Down Expand Up @@ -145,18 +146,7 @@ public void RecordIncident(IncidentDef def, IIncidentTarget target, int tick)
}

public string GetRecentSummary(int count)
{
if (_records.Count == 0) return string.Empty;

var sb = new StringBuilder();
var recent = _records.Skip(System.Math.Max(0, _records.Count - count)).ToList();
foreach (var r in recent)
{
int day = TensionMath.TicksToDay(r.TriggeredTick);
sb.AppendLine("RimMind.Storyteller.Prompt.DaySummary".Translate(day, r.Label, r.MapName));
}
return sb.ToString().TrimEnd();
}
=> StorytellerMemoryPromptFormatter.FormatRecentIncidents(_records, count);

public void ClearRecords() => _records.Clear();

Expand All @@ -171,21 +161,7 @@ public void RecordDialogue(string role, string content, int tick)
}

public string GetRecentDialogueSummary(int count)
{
if (_dialogueRecords.Count == 0) return string.Empty;

var sb = new StringBuilder();
var recent = _dialogueRecords.Skip(System.Math.Max(0, _dialogueRecords.Count - count)).ToList();
foreach (var r in recent)
{
int day = TensionMath.TicksToDay(r.tick);
string prefix = r.role == "user"
? "RimMind.Storyteller.Prompt.RolePlayer".Translate()
: "RimMind.Storyteller.Prompt.RoleNarrator".Translate();
sb.AppendLine("RimMind.Storyteller.Prompt.DialogueRecordLine".Translate($"{day}", prefix, r.content));
}
return sb.ToString().TrimEnd();
}
=> StorytellerMemoryPromptFormatter.FormatRecentDialogues(_dialogueRecords, count);

public void ClearDialogueRecords() => _dialogueRecords.Clear();

Expand All @@ -208,25 +184,15 @@ public void RecordPlayerReaction(string incidentDefName, string incidentLabel, s

public string PeekReactions(int maxCount)
{
if (_playerReactions.Count == 0 || maxCount <= 0)
string formatted = StorytellerMemoryPromptFormatter.FormatPlayerReactions(_playerReactions, maxCount);
if (string.IsNullOrEmpty(formatted))
{
_consumedReactionsText = null;
return string.Empty;
}

int takeCount = System.Math.Min(maxCount, _playerReactions.Count);
var peeked = _playerReactions.Take(takeCount).ToList();

var sb = new StringBuilder();
sb.AppendLine("RimMind.Storyteller.Prompt.PlayerReactions".Translate());
foreach (var r in peeked)
{
int day = TensionMath.TicksToDay(r.tick);
sb.AppendLine("RimMind.Storyteller.Prompt.ReactionRecordLine".Translate(
day.ToString(), r.incidentLabel, r.reactionLabel));
}
_consumedReactionsText = sb.ToString().TrimEnd();
return _consumedReactionsText;
_consumedReactionsText = formatted;
return formatted;
}

public string ConsumeReactions(int maxCount)
Expand Down Expand Up @@ -331,18 +297,7 @@ private void CleanupExpiredChains()
}

public string GetActiveChainsSummary()
{
if (_activeChains.Count == 0) return string.Empty;
var sb = new StringBuilder();
foreach (var chain in _activeChains)
{
var triggeredNames = string.Join(", ", chain.steps.Select(s => s.incidentDefName));
sb.AppendLine("RimMind.Storyteller.Prompt.ChainProgress".Translate(
chain.chainId, $"{chain.currentStep}", $"{chain.totalSteps}", triggeredNames));
sb.AppendLine("RimMind.Storyteller.Prompt.ChainHint".Translate(chain.nextHint ?? ""));
}
return sb.ToString().TrimEnd();
}
=> StorytellerMemoryPromptFormatter.FormatActiveChains(_activeChains);

public override void ExposeData()
{
Expand Down
109 changes: 109 additions & 0 deletions Source/Memory/StorytellerMemoryPromptFormatter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RimMind.Presentation.Api;

namespace RimMind.Storyteller.Memory
{
/// <summary>
/// Stateless prompt-text formatting helpers separated from <see cref="StorytellerMemory"/>
/// ring-buffer storage and WorldComponent persistence.
/// </summary>
internal static class StorytellerMemoryPromptFormatter
{
public static string FormatRecentIncidents(IReadOnlyList<IncidentHistoryRecord> records, int count)
{
if (records == null || records.Count == 0 || count <= 0)
return string.Empty;

var sb = new StringBuilder();
int start = Math.Max(0, records.Count - count);
for (int i = start; i < records.Count; i++)
{
var r = records[i];
int day = TensionMath.TicksToDay(r.TriggeredTick);
sb.AppendLine(RimMindAPI.Text.TrOr(
"RimMind.Storyteller.Prompt.DaySummary",
"Day {0}: {1} ({2})",
day,
r.Label,
r.MapName));
}
return sb.ToString().TrimEnd();
}

public static string FormatRecentDialogues(IReadOnlyList<DialogueRecord> records, int count)
{
if (records == null || records.Count == 0 || count <= 0)
return string.Empty;

var sb = new StringBuilder();
int start = Math.Max(0, records.Count - count);
for (int i = start; i < records.Count; i++)
{
var r = records[i];
int day = TensionMath.TicksToDay(r.tick);
string prefix = string.Equals(r.role, "user", StringComparison.OrdinalIgnoreCase)
? RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.RolePlayer", "Player")
: RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.RoleNarrator", "Narrator");
sb.AppendLine(RimMindAPI.Text.TrOr(
"RimMind.Storyteller.Prompt.DialogueRecordLine",
"Day {0} {1}: {2}",
day.ToString(),
prefix,
r.content));
}
return sb.ToString().TrimEnd();
}

public static string FormatPlayerReactions(IReadOnlyList<PlayerReactionRecord> reactions, int maxCount)
{
if (reactions == null || reactions.Count == 0 || maxCount <= 0)
return string.Empty;

int takeCount = Math.Min(maxCount, reactions.Count);
var sb = new StringBuilder();
sb.AppendLine(RimMindAPI.Text.TrOr(
"RimMind.Storyteller.Prompt.PlayerReactions",
"[Player Reaction Records]"));
for (int i = 0; i < takeCount; i++)
{
var r = reactions[i];
int day = TensionMath.TicksToDay(r.tick);
sb.AppendLine(RimMindAPI.Text.TrOr(
"RimMind.Storyteller.Prompt.ReactionRecordLine",
"Day {0} {1} → Player: {2}",
day.ToString(),
r.incidentLabel,
r.reactionLabel));
}
return sb.ToString().TrimEnd();
}

public static string FormatActiveChains(IReadOnlyList<EventChain> chains)
{
if (chains == null || chains.Count == 0)
return string.Empty;

var sb = new StringBuilder();
for (int i = 0; i < chains.Count; i++)
{
var chain = chains[i];
string triggeredNames = string.Join(", ", chain.steps.Select(s => s.incidentDefName));
sb.AppendLine(RimMindAPI.Text.TrOr(
"RimMind.Storyteller.Prompt.ChainProgress",
"{0} (step {1}/{2}, triggered: {3})",
chain.chainId,
chain.currentStep.ToString(),
chain.totalSteps.ToString(),
triggeredNames));
sb.AppendLine(RimMindAPI.Text.TrOr(
"RimMind.Storyteller.Prompt.ChainHint",
" AI hint: {0}",
chain.nextHint ?? string.Empty));
}
return sb.ToString().TrimEnd();
}
}
}
13 changes: 7 additions & 6 deletions Source/Patch/Patch_IncidentWorker_TryExecute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ static void Postfix(IncidentWorker __instance, IncidentParms parms, bool __resul
if (!isThreat || parms?.quest != null)
return;

RimMindAPI.NotifyIncidentExecuted();
RimMindAPI.Ext.NotifyIncidentExecuted();

if (RimMindAPI.CanTriggerDialogue)
if (RimMindAPI.Ext.CanTriggerDialogue)
{
var map = parms?.target as Map;
if (map != null)
Expand All @@ -47,10 +47,11 @@ static void Postfix(IncidentWorker __instance, IncidentParms parms, bool __resul
{
Rand.PopState();
}
string incidentContext = "RimMind.Storyteller.Context.IncidentOccurred".CanTranslate()
? "RimMind.Storyteller.Context.IncidentOccurred".Translate(__instance.def.label).ToString()
: $"Incident occurred: {__instance.def.label}";
RimMindAPI.TriggerDialogue(pawn, incidentContext);
string incidentContext = RimMindAPI.Text.TrOr(
"RimMind.Storyteller.Context.IncidentOccurred",
"Incident occurred: {0}",
__instance.def.label);
RimMindAPI.Ext.TriggerDialogue(pawn, incidentContext);
}
}
}
Expand Down
Loading