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
12 changes: 10 additions & 2 deletions Parlance.Tests/ConformanceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,13 @@ public void ResolveCheck()
var rngSpec = v.ContainsKey("rng") ? v["rng"] : 0.0f;
var rng = RngFrom(rngSpec);

var got = Runtime.ResolveCheck(check, state, rng, defaultDice, criticals);
// A check with modifiers requires a project, as a real caller always
// has one: the vector's when it carries one (quest state), else {}.
bool hasModifiers = check.TryGetValue("modifiers", out var mods) && mods is List<object> modList && modList.Count > 0;
var project = v.ContainsKey("project") ? (Dictionary<string, object>)v["project"]
: hasModifiers ? new Dictionary<string, object>() : null;

var got = Runtime.ResolveCheck(check, state, rng, defaultDice, criticals, project);
var want = (Dictionary<string, object>)v["expected"];
AssertDeepEqual(want, got, (string)v["description"]);
}
Expand Down Expand Up @@ -229,7 +235,9 @@ public void ResolveCharacterDialogue()
var character = (Dictionary<string, object>)v["character"];
var project = v.ContainsKey("project") ? (Dictionary<string, object>)v["project"] : new Dictionary<string, object>();

var got = Runtime.ResolveCharacterDialogue(state, character, project);
var visited = v.ContainsKey("visited") ? (List<object>)v["visited"] : null;

var got = Runtime.ResolveCharacterDialogue(state, character, project, visited);
var expected = v["expected"];

AssertDeepEqual(expected, got, (string)v["description"]);
Expand Down
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@ A C# runtime for [Parlance](https://github.com/Orbitope/parlance), a git-native

**Parlance is the authoring tool; this is the Unity runtime for what it produces.** You write your story in Parlance's visual editor — dialogue and quest canvases, a searchable reference index, live playtest — and it saves as human-readable JSON directly in your repo. No database, no import/export step, git as the single source of truth.

This package reads that JSON and runs it in Unity: dialogues, conditions, effects, skill checks, character dialogue ladders, quests, endings. It is verified against Parlance's published conformance vectors rather than against its author's confidence.
This package reads that JSON and runs it in Unity: dialogues, conditions, effects, skill checks (with conditional modifiers), character dialogue offers, quests, endings. It is verified against Parlance's published conformance vectors rather than against its author's confidence.

## Compatibility

| parlance-unity | Parlance spec | Families |
|---|---|---|
| `main` (unreleased) | v0.9.0 — pre-tag, pinned to [`1a4e657`](conformance/PIN) | 7 of 10 |
| `main` (unreleased) | v0.14.0 — pinned to [`f4a25b0`](conformance/PIN) | 8 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 @@ -61,21 +63,23 @@ state = outcome["newState"];

if (outcome.ContainsKey("checkResult"))
{
Debug.Log(outcome["checkResult"]); // passed, roll, total, skillValue, dice
Debug.Log(outcome["checkResult"]); // passed, roll, total, skillValue, dice (+ bonus, appliedModifiers)
}
var nextNodeId = outcome.GetValueOrDefault("nextNodeId"); // null on a terminal choice
```

### Important Notes
- **`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.
- **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

You can verify the runtime against the exact same conformance vectors used by the GDScript implementation. Since it's a pure C# library, you can run the NUnit tests from the command line without launching Unity:

```bash
cd Tests
cd Parlance.Tests
dotnet test
```

Expand Down
135 changes: 118 additions & 17 deletions Runtime/Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,32 @@
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>());
}

// How specific a condition is, for offer ranking: absent 0, leaf 1,
// all = sum, any = min (0 if empty), not = its operand's.
public static int ConditionSpecificity(object conditionObj)
{
if (!(conditionObj is Dictionary<string, object> condition)) return 0;
string type = condition.TryGetValue("type", out var typeObj) && typeObj is string t ? t : "";
condition.TryGetValue("of", out var ofObj);
switch (type)
{
case "all":
return ofObj is IEnumerable<object> allOf ? allOf.Sum(ConditionSpecificity) : 0;
case "any":
return ofObj is IEnumerable<object> anyOf && anyOf.Any() ? anyOf.Min(ConditionSpecificity) : 0;
case "not":
return ConditionSpecificity(ofObj);
default:
return 1;
}
}

private static bool _Evaluate(object conditionObj, State state, Dictionary<string, object> project, Dictionary<string, bool> visiting)
{
if (!(conditionObj is Dictionary<string, object> condition)) return false;
Expand Down Expand Up @@ -184,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 @@ -284,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 @@ -300,8 +320,17 @@

// ------------------------------------------------------------ resolveCheck --

public static Dictionary<string, object> ResolveCheck(Dictionary<string, object> check, State state, Func<float> rng, object defaultDice = null, bool criticals = false)
// 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)
{
return new Dictionary<string, object> { { "error", "ResolveCheck: check has modifiers; pass project" } };
}

object diceObj = check.TryGetValue("dice", out var dObj) ? dObj : defaultDice;
string notation = diceObj != null ? diceObj.ToString() : "1d20";
var spec = ParseDice(notation);
Expand All @@ -317,7 +346,8 @@

string skill = check.TryGetValue("skill", out var s) && s is string sStr ? sStr : "";
float skillValue = state.Skills.TryGetValue(skill, out var sv) ? sv : 0f;
float total = roll + skillValue;
var mod = hasModifiers ? CheckBonus(check, state, project) : (bonus: 0f, appliedModifiers: new List<object>());
float total = roll + skillValue + mod.bonus;

float difficulty = check.TryGetValue("difficulty", out var diffObj) ? Convert.ToSingle(diffObj) : 0f;
bool passed = total >= difficulty;
Expand All @@ -330,6 +360,13 @@
{ "skillValue", skillValue },
{ "dice", $"{spec.n}d{spec.m}" }
};
// Present only when the check declares a modifier, so an unmodified
// check's result is unchanged from before modifiers existed.
if (hasModifiers)
{
result["bonus"] = mod.bonus;
result["appliedModifiers"] = mod.appliedModifiers;
}

if (criticals)
{
Expand All @@ -355,6 +392,39 @@
return result;
}

// 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>();
if (check.TryGetValue("modifiers", out var modsObj) && modsObj is IEnumerable<object> mods)
{
int i = 0;
foreach (var mObj in mods)
{
if (mObj is Dictionary<string, object> m
&& Evaluate(m.TryGetValue("when", out var w) ? w as Dictionary<string, object> : null, state, project))
{
bonus += m.TryGetValue("bonus", out var b) ? Convert.ToSingle(b) : 0f;
applied.Add(i);
}
i++;
}
}
return (bonus, applied);
}

// 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;
float difficulty = check.TryGetValue("difficulty", out var diffObj) ? Convert.ToSingle(diffObj) : 0f;
return skillValue + CheckBonus(check, state, project).bonus >= difficulty;
}

private static (int n, int m) ParseDice(string notation)
{
var parts = notation.Trim().ToLower().Split('d');
Expand All @@ -367,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 @@ -451,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 @@ -492,7 +562,8 @@
object defaultDice = checkRules.TryGetValue("dice", out var ddObj) ? ddObj : null;
bool criticals = checkRules.TryGetValue("criticals", out var critObj) && critObj is bool cBool ? cBool : false;

var result = ResolveCheck(check, nextState, rng, defaultDice, criticals);
var result = ResolveCheck(check, nextState, rng, defaultDice, criticals, project);
if (result.ContainsKey("error")) return result;
bool passed = (bool)result["passed"];

object nextNodeId = null;
Expand Down Expand Up @@ -578,25 +649,55 @@
};
}

// ------------------------------------------- resolveCharacterDialogue (feed) --
// ----------------------------------------- resolveCharacterDialogue (offers) --

public static object ResolveCharacterDialogue(State state, Dictionary<string, object> character, Dictionary<string, object> project = null)
// The dialogue this character offers right now, or null. Candidates are
// dialogues carrying an `offer` whose `offer.character ?? speakerId` is
// this character; those whose `when` fails, and (given `visited`) any
// visited non-replayable one, are dropped. The winner is the highest
// priority tier, then the most specific `when`, then the lowest id by
// ordinal compare. Order in the project never matters.
public static object ResolveCharacterDialogue(State state, Dictionary<string, object> character, Dictionary<string, object> project = null, IEnumerable<object> visited = null)
{
if (project == null) project = new Dictionary<string, object>();

if (character.TryGetValue("dialogues", out var dialoguesObj) && dialoguesObj is IEnumerable<object> dialoguesList)
if (!(project.TryGetValue("dialogues", out var dsObj) && dsObj is Dictionary<string, object> dialogues)) return null;

object characterId = character.TryGetValue("id", out var cid) ? cid : null;
var seen = visited != null ? new HashSet<string>(visited.Select(x => x?.ToString())) : null;

Dictionary<string, object> best = null;
foreach (var dObj in dialogues.Values)
{
foreach (var rungObj in dialoguesList)
{
if (!(rungObj is Dictionary<string, object> rung)) continue;
if (rung.TryGetValue("showIf", out var showIfObj))
{
if (!Evaluate(showIfObj as Dictionary<string, object> ?? new Dictionary<string, object>(), state, project)) continue;
}
return rung.TryGetValue("dialogue", out var diagObj) ? diagObj : null;
}
if (!(dObj is Dictionary<string, object> dialogue)) continue;
if (!(dialogue.TryGetValue("offer", out var oObj) && oObj is Dictionary<string, object> offer)) continue;

object offeredBy = offer.TryGetValue("character", out var oc) ? oc : (dialogue.TryGetValue("speakerId", out var sp) ? sp : null);
if (!Equals(offeredBy, characterId)) continue;

if (offer.TryGetValue("when", out var whenObj) && !Evaluate(whenObj as Dictionary<string, object>, state, project)) continue;

bool replayable = dialogue.TryGetValue("replayable", out var rp) && rp is bool rpb && rpb;
string id = dialogue.TryGetValue("id", out var idObj) ? idObj?.ToString() : null;
if (seen != null && !replayable && seen.Contains(id)) continue;

if (best == null || BetterOffer(dialogue, best)) best = dialogue;
}
return null;
return best != null && best.TryGetValue("id", out var bestId) ? bestId : null;
}

private static bool BetterOffer(Dictionary<string, object> a, Dictionary<string, object> b)
{
var oa = (Dictionary<string, object>)a["offer"];
var ob = (Dictionary<string, object>)b["offer"];
int pa = oa.TryGetValue("priority", out var pao) ? Convert.ToInt32(pao) : 0;
int pb = ob.TryGetValue("priority", out var pbo) ? Convert.ToInt32(pbo) : 0;
if (pa != pb) return pa > pb;
int sa = ConditionSpecificity(oa.TryGetValue("when", out var wa) ? wa : null);
int sb = ConditionSpecificity(ob.TryGetValue("when", out var wb) ? wb : null);
if (sa != sb) return sa > sb;
string ia = a.TryGetValue("id", out var iao) ? iao?.ToString() ?? "" : "";
string ib = b.TryGetValue("id", out var ibo) ? ibo?.ToString() ?? "" : "";
return string.CompareOrdinal(ia, ib) < 0;
}

// ------------------------------------------------------ speaker / portrait --
Expand Down
4 changes: 2 additions & 2 deletions conformance/PIN
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# These vectors are a PINNED COPY, not a fork. Never hand-edit them: they are
# generated from and asserted against the reference implementation, so an edit
# here makes this port chase a ghost. Re-copy from the named ref instead.
parlanceVersion=v0.12.0
parlanceCommit=a45908cf66b87c5dd1e6db68be88d90a734ea117
parlanceVersion=v0.14.0
parlanceCommit=f4a25b0d94ca8569a2897e8354a3f1317f826a82
parlanceRepo=git@github.com:Orbitope/parlance.git
#
Loading
Loading