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
85 changes: 85 additions & 0 deletions Parlance.Tests/ConformanceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,91 @@ public void ResolveCharacterDialogue()
}
}

[Test]
public void NextContinuations()
{
var vectors = Load("nextContinuations.json");
Assert.NotNull(vectors);
foreach (var vObj in vectors)
{
var v = (Dictionary<string, object>)vObj;
var state = State.FromDict((Dictionary<string, object>)v["state"]);
var project = (Dictionary<string, object>)v["project"];
var visited = v.ContainsKey("visited") ? (List<object>)v["visited"] : new List<object>();

// Compared by id, as the reference harness does.
var got = new List<object>();
foreach (var c in Runtime.NextContinuations(state, project, visited, (string)v["currentDialogueId"]))
{
if ((string)c["kind"] == "cutscene")
{
got.Add(new Dictionary<string, object> { { "kind", "cutscene" }, { "cutscene", ((Dictionary<string, object>)c["cutscene"])["id"] } });
}
else
{
got.Add(new Dictionary<string, object>
{
{ "kind", "dialogue" },
{ "characterId", c["characterId"] },
{ "dialogue", ((Dictionary<string, object>)c["dialogue"])["id"] },
{ "queued", c["queued"] }
});
}
}
AssertDeepEqual(v["expected"], got, (string)v["description"]);
}
}

[Test]
public void ResolveQuests()
{
var vectors = Load("resolve_quests.json");
Assert.NotNull(vectors);
foreach (var vObj in vectors)
{
var v = (Dictionary<string, object>)vObj;
var state = State.FromDict((Dictionary<string, object>)v["state"]);
var project = (Dictionary<string, object>)v["project"];

var result = Runtime.ResolveQuests(state, project);
var firings = new List<object>();
foreach (Dictionary<string, object> f in (List<object>)result["firings"])
{
firings.Add(new Dictionary<string, object> { { "quest", f["quest"] }, { "kind", f["kind"] }, { "id", f["id"] } });
}
var got = new Dictionary<string, object>
{
{ "state", ((State)result["state"]).ToDict() },
{ "firings", firings }
};
AssertDeepEqual(v["expected"], got, (string)v["description"]);
}
}

// progression.json mixes five functions; the vector's `fn` picks one.
[Test]
public void Progression()
{
var vectors = Load("progression.json");
Assert.NotNull(vectors);
foreach (var vObj in vectors)
{
var v = (Dictionary<string, object>)vObj;
var config = (Dictionary<string, object>)v["config"];
string fn = (string)v["fn"];
object got = fn switch
{
"levelForXp" => Runtime.LevelForXp(Convert.ToSingle(v["xp"]), config),
"pointsEarned" => Runtime.PointsEarned(Convert.ToSingle(v["xp"]), config),
"availablePoints" => Runtime.AvailablePoints(State.FromDict((Dictionary<string, object>)v["state"]), config),
"investSkillPoint" => Runtime.InvestSkillPoint(State.FromDict((Dictionary<string, object>)v["state"]), (string)v["skillId"], config).ToDict(),
"recomputeSkills" => Runtime.RecomputeSkills(State.FromDict((Dictionary<string, object>)v["state"]), config).ToDict(),
_ => throw new InvalidOperationException($"unknown progression fn '{fn}'")
};
AssertDeepEqual(v["expected"], got, $"{fn}: {v["description"]}");
}
}

private Func<float> RngFrom(object spec)
{
List<object> values = spec is List<object> l ? l : new List<object> { spec };
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@ This package reads that JSON and runs it in Unity: dialogues, conditions, effect

| parlance-unity | Parlance spec | Families |
|---|---|---|
| `main` (unreleased) | v0.14.0 — pinned to [`f4a25b0`](conformance/PIN) | 8 of 11 |
| `main` (unreleased) | v0.14.0 — pinned to [`f4a25b0`](conformance/PIN) | 11 of 11 |

[`conformance/PIN`](conformance/PIN) is the authoritative record of which upstream ref the vectors came from.

Not ported yet: `resolveQuests`, `progression` and `nextContinuations`. Their vectors are vendored but no test runs them.

## Install

Install this package via the Unity Package Manager (UPM).
Expand Down Expand Up @@ -72,6 +70,9 @@ var nextNodeId = outcome.GetValueOrDefault("nextNodeId"); // null on a terminal
- **`onEnter` effects are not applied for you.** `StepDialogue` returns them; firing them is the caller's job, on first arrival only. Applying them on every render double-counts on a rewind.
- **A node with no choices is not necessarily over.** If it has `next`, call `AdvanceNode` — that's a listen-only beat. Treating it as the end silently truncates ambient chains.
- **Passive checks never roll.** Show or hide a passive-check choice with `PassiveCheckPasses` (`skill + Σbonus >= difficulty`), so a check modifier means the same thing in both modes.
- **Run `ResolveQuests` after every state change.** It fires quest stage `onComplete` and outcome `effects` whose condition holds, once each, and records them in `QuestFired`. It never advances a stage for you.
- **Levelling is derived, not stored.** `Xp` is total-earned; `LevelForXp`, `PointsEarned` and `AvailablePoints` derive from it. `InvestSkillPoint` is a guarded player action, not an effect; call `RecomputeSkills` on load so checks read preset + invested skill.
- **When a scene ends, ask `NextContinuations`.** A pending cutscene comes first, then any character routed with `set_active_dialogue`, otherwise each character's best offer. Consume them with `ClearPendingCutscene` / `ClearActiveDialogue`.
- **Which dialogue a character opens is `ResolveCharacterDialogue`.** It ranks the dialogues whose `offer` names that character (priority tier, then condition specificity, then id); pass your visited set so non-replayable dialogues are not offered twice.

## Verify it yourself
Expand Down
217 changes: 217 additions & 0 deletions Runtime/Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
public static class Runtime
{
// ---------------------------------------------------------------- evaluate --
public static bool Evaluate(Dictionary<string, object> condition, State state, Dictionary<string, object> project = null)

Check warning on line 10 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.
{
if (project == null) project = new Dictionary<string, object>();
return _Evaluate(condition, state, project, new Dictionary<string, bool>());
Expand Down Expand Up @@ -204,7 +204,7 @@

// ------------------------------------------------------------- applyEffect --

public static State ApplyEffect(object effectObj, State state, Dictionary<string, object> project = null)

Check warning on line 207 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.
{
if (project == null) project = new Dictionary<string, object>();
State next = state.Copy();
Expand Down Expand Up @@ -304,7 +304,7 @@
return next;
}

public static State ApplyEffects(IEnumerable<object> effects, State state, Dictionary<string, object> project = null)

Check warning on line 307 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.
{
if (project == null) project = new Dictionary<string, object>();
State next = state;
Expand All @@ -323,7 +323,7 @@
// A check that declares modifiers needs the project to evaluate their
// `when` (quest conditions read stage order); without one this returns
// an error rather than read those conditions as silently false.
public static Dictionary<string, object> ResolveCheck(Dictionary<string, object> check, State state, Func<float> rng, object defaultDice = null, bool criticals = false, Dictionary<string, object> project = null)

Check warning on line 326 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 326 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.
{
bool hasModifiers = check.TryGetValue("modifiers", out var modsObj) && modsObj is IEnumerable<object> modsList && modsList.Any();
if (hasModifiers && project == null)
Expand Down Expand Up @@ -394,7 +394,7 @@

// Sum of every modifier's bonus whose `when` holds, and the indices that
// contributed, in array order. The one place modifiers are summed.
public static (float bonus, List<object> appliedModifiers) CheckBonus(Dictionary<string, object> check, State state, Dictionary<string, object> project = null)

Check warning on line 397 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.
{
float bonus = 0f;
var applied = new List<object>();
Expand All @@ -417,7 +417,7 @@

// The passive-check reveal threshold: skill + bonus >= difficulty.
// Passive checks never roll; use this to show or hide the choice.
public static bool PassiveCheckPasses(Dictionary<string, object> check, State state, Dictionary<string, object> project = null)

Check warning on line 420 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.
{
string skill = check.TryGetValue("skill", out var s) && s is string sStr ? sStr : "";
float skillValue = state.Skills.TryGetValue(skill, out var sv) ? sv : 0f;
Expand All @@ -437,7 +437,7 @@

// ----------------------------------------------------------- stepDialogue --

public static Dictionary<string, object> StepDialogue(Dictionary<string, object> dialogue, string nodeId, State state, Dictionary<string, object> project = null)

Check warning on line 440 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.
{
if (project == null) project = new Dictionary<string, object>();

Expand Down Expand Up @@ -521,7 +521,7 @@

// ----------------------------------------------------------- chooseChoice --

public static Dictionary<string, object> ChooseChoice(Dictionary<string, object> dialogue, string nodeId, string choiceId, State state, Dictionary<string, object> project = null, Func<float> rng = null)

Check warning on line 524 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 524 in Runtime/Runtime.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.
{
if (project == null) project = new Dictionary<string, object>();

Expand Down Expand Up @@ -700,6 +700,223 @@
return string.CompareOrdinal(ia, ib) < 0;
}

// ------------------------------------------------------ nextContinuations --

public static string ActiveDialogueFlag(string characterId) => "active_dialogue__" + characterId;

// Clears a character's forced-dialogue flag once its forced dialogue is consumed.
public static State ClearActiveDialogue(string characterId, State state)
{
var next = state.Copy();
next.Flags[ActiveDialogueFlag(characterId)] = false;
return next;
}

public static State ClearPendingCutscene(State state)
{
var next = state.Copy();
next.PendingCutscene = null;
return next;
}

// What to offer when the current scene ends. Each entry is
// { kind: "cutscene", cutscene } or { kind: "dialogue", characterId, dialogue, queued }.
// A pending cutscene comes first. Then forced routing: characters whose
// active_dialogue__ flag is set and whose winning offer reads that flag
// (queued, visited ignored); if any, only those. Otherwise discovery:
// each character's best eligible offer with the visited filter. The
// current dialogue is excluded and ids are de-duplicated.
public static List<Dictionary<string, object>> NextContinuations(State state, Dictionary<string, object> project, IEnumerable<object> visited, string currentDialogueId)
{
var seen = new HashSet<string> { currentDialogueId };
var dialogues = project.TryGetValue("dialogues", out var dObj) && dObj is Dictionary<string, object> dd ? dd : new Dictionary<string, object>();
var characters = project.TryGetValue("characters", out var cObj) && cObj is Dictionary<string, object> cd ? cd : new Dictionary<string, object>();

var pending = new List<Dictionary<string, object>>();
if (state.PendingCutscene != null
&& project.TryGetValue("cutscenes", out var csObj) && csObj is Dictionary<string, object> cutscenes
&& cutscenes.TryGetValue(state.PendingCutscene, out var cutscene) && cutscene is Dictionary<string, object>)
{
pending.Add(new Dictionary<string, object> { { "kind", "cutscene" }, { "cutscene", cutscene } });
}

var forced = new List<Dictionary<string, object>>();
foreach (var chObj in characters.Values)
{
if (!(chObj is Dictionary<string, object> character)) continue;
string charId = character.TryGetValue("id", out var cid) ? cid?.ToString() ?? "" : "";
string flag = ActiveDialogueFlag(charId);
if (!(state.Flags.TryGetValue(flag, out var set) && set)) continue;
var resolved = ResolveCharacterDialogue(state, character, project)?.ToString();
if (resolved == null || !(dialogues.TryGetValue(resolved, out var dlgObj) && dlgObj is Dictionary<string, object> dialogue)) continue;
var offer = dialogue.TryGetValue("offer", out var oObj) ? oObj as Dictionary<string, object> : null;
object when = null;
offer?.TryGetValue("when", out when);
if (!ConditionReadsFlag(when, flag)) continue;
if (seen.Add(resolved))
{
forced.Add(new Dictionary<string, object> { { "kind", "dialogue" }, { "characterId", charId }, { "dialogue", dialogue }, { "queued", true } });
}
}
if (forced.Count > 0) return pending.Concat(forced).ToList();

var discovered = new List<Dictionary<string, object>>();
foreach (var chObj in characters.Values)
{
if (!(chObj is Dictionary<string, object> character)) continue;
string charId = character.TryGetValue("id", out var cid) ? cid?.ToString() ?? "" : "";
var resolved = ResolveCharacterDialogue(state, character, project, visited ?? new List<object>())?.ToString();
if (resolved == null || !(dialogues.TryGetValue(resolved, out var dlgObj) && dlgObj is Dictionary<string, object> dialogue)) continue;
if (seen.Add(resolved))
{
discovered.Add(new Dictionary<string, object> { { "kind", "dialogue" }, { "characterId", charId }, { "dialogue", dialogue }, { "queued", false } });
}
}
return pending.Concat(discovered).ToList();
}

// Does this gate require `flag` to be true, as a top-level conjunct
// (an `all` flattened)? The test for a forced offer.
private static bool ConditionReadsFlag(object conditionObj, string flag)
{
if (!(conditionObj is Dictionary<string, object> c)) return false;
string type = c.TryGetValue("type", out var t) ? t as string : null;
if (type == "all")
{
return c.TryGetValue("of", out var ofObj) && ofObj is IEnumerable<object> of && of.Any(x => ConditionReadsFlag(x, flag));
}
return type == "flag"
&& c.TryGetValue("flag", out var f) && f as string == flag
&& c.TryGetValue("value", out var v) && v is bool b && b;
}

// ---------------------------------------------------------- resolveQuests --

public static string QuestFiredKey(string questId, string kind, string id) => $"{questId}/{kind}/{id}";

// Fires quest stage onComplete / outcome effects whose completeWhen /
// reachedWhen holds, once each (recorded in QuestFired), to a fixpoint.
// Order: quests by ordinal id, then stages, then outcomes in array
// order. Effects with no condition never auto-fire; QuestStages is
// never written. Returns { state, firings: [{ quest, kind, id, effects }] }.
public static Dictionary<string, object> ResolveQuests(State state, Dictionary<string, object> project)
{
var quests = project.TryGetValue("quests", out var qObj) && qObj is Dictionary<string, object> qd ? qd : new Dictionary<string, object>();
var questIds = quests.Keys.ToList();
questIds.Sort(string.CompareOrdinal);

var current = state;
var firings = new List<object>();
bool changed = true;
while (changed)
{
changed = false;
foreach (var qid in questIds)
{
if (!(quests[qid] is Dictionary<string, object> quest)) continue;
foreach (var item in Items(quest, "stages"))
{
var next = TryFire(current, project, qid, "stage", item, "completeWhen", "onComplete", firings);
if (next != null) { current = next; changed = true; }
}
foreach (var item in Items(quest, "outcomes"))
{
var next = TryFire(current, project, qid, "outcome", item, "reachedWhen", "effects", firings);
if (next != null) { current = next; changed = true; }
}
}
}
return new Dictionary<string, object> { { "state", current }, { "firings", firings } };
}

private static IEnumerable<Dictionary<string, object>> Items(Dictionary<string, object> quest, string key)
{
return quest.TryGetValue(key, out var obj) && obj is IEnumerable<object> list
? list.OfType<Dictionary<string, object>>()
: Enumerable.Empty<Dictionary<string, object>>();
}

// One item's firing attempt: the new state if it fired, else null.
private static State TryFire(State state, Dictionary<string, object> project, string questId, string kind, Dictionary<string, object> item, string whenKey, string effectsKey, List<object> firings)
{
if (!(item.TryGetValue(effectsKey, out var effObj) && effObj is List<object> effects && effects.Count > 0)) return null;
if (!item.TryGetValue(whenKey, out var when)) return null;
string id = item.TryGetValue("id", out var idObj) ? idObj?.ToString() ?? "" : "";
string key = QuestFiredKey(questId, kind, id);
if (state.QuestFired.Contains(key)) return null;
if (!Evaluate(when as Dictionary<string, object>, state, project)) return null;
// Effects are non-empty, so ApplyEffects has already copied.
var next = ApplyEffects(effects, state, project);
next.QuestFired.Add(key);
firings.Add(new Dictionary<string, object> { { "quest", questId }, { "kind", kind }, { "id", id }, { "effects", effects } });
return next;
}

// ------------------------------------------------------------ progression --
// Xp is total-earned and monotonic; levels and points derive from it.
// `config` is progression.json; `skills` is the optional skills
// registry (id -> skill) for per-skill `max` caps.

public static int LevelForXp(float xp, Dictionary<string, object> config)
{
int level = 0;
if (config.TryGetValue("xpThresholds", out var tObj) && tObj is List<object> thresholds)
{
for (int i = 0; i < thresholds.Count; i++)
{
if (xp >= Convert.ToSingle(thresholds[i])) level = i;
else break;
}
}
return level;
}

public static float PointsEarned(float xp, Dictionary<string, object> config)
{
float perLevel = config.TryGetValue("pointsPerLevel", out var p) ? Convert.ToSingle(p) : 0f;
return LevelForXp(xp, config) * perLevel;
}

public static float SkillCap(string skillId, Dictionary<string, object> config, Dictionary<string, object> skills = null)
{
if (skills != null && skills.TryGetValue(skillId, out var sObj) && sObj is Dictionary<string, object> skill && skill.TryGetValue("max", out var max))
return Convert.ToSingle(max);
return config.TryGetValue("maxSkill", out var m) ? Convert.ToSingle(m) : 0f;
}

public static float EffectiveSkill(string skillId, State state, Dictionary<string, object> config, Dictionary<string, object> skills = null)
{
float preset = config.TryGetValue("startingSkills", out var ssObj) && ssObj is Dictionary<string, object> ss && ss.TryGetValue(skillId, out var pv) ? Convert.ToSingle(pv) : 0f;
float invested = state.SkillPointsSpent.TryGetValue(skillId, out var iv) ? iv : 0f;
return Math.Min(preset + invested, SkillCap(skillId, config, skills));
}

public static float AvailablePoints(State state, Dictionary<string, object> config)
{
return PointsEarned(state.Xp, config) - state.SkillPointsSpent.Values.Sum();
}

// Skills = EffectiveSkill for every preset or invested skill; others untouched.
public static State RecomputeSkills(State state, Dictionary<string, object> config, Dictionary<string, object> skills = null)
{
var next = state.Copy();
var ids = new HashSet<string>(state.SkillPointsSpent.Keys);
if (config.TryGetValue("startingSkills", out var ssObj) && ssObj is Dictionary<string, object> ss) ids.UnionWith(ss.Keys);
foreach (var id in ids) next.Skills[id] = EffectiveSkill(id, state, config, skills);
return next;
}

// Spends one point. A player action, not an effect: a no-op unless a
// point is available and the skill is below its ceiling.
public static State InvestSkillPoint(State state, string skillId, Dictionary<string, object> config, Dictionary<string, object> skills = null)
{
if (AvailablePoints(state, config) <= 0) return state;
if (EffectiveSkill(skillId, state, config, skills) >= SkillCap(skillId, config, skills)) return state;
var next = state.Copy();
next.SkillPointsSpent[skillId] = (next.SkillPointsSpent.TryGetValue(skillId, out var v) ? v : 0f) + 1f;
return RecomputeSkills(next, config, skills);
}

// ------------------------------------------------------ speaker / portrait --

public static object EffectiveSpeakerId(Dictionary<string, object> dialogue, Dictionary<string, object> node)
Expand Down
Loading