From a9e897328c441dd5a43165fc78701fa834b55746 Mon Sep 17 00:00:00 2001 From: Smoebo Date: Sat, 21 Nov 2026 00:33:39 -0500 Subject: [PATCH 1/2] An opportunity attack and a death save show their dice in the chronicle on the line they post, and a rest's hit dice, the stable wait's d4, an item's charges at dawn and the dice a call rolls as it opens a fight are on that call's turn The opportunity, clock and initiative families of the roll-record ledger move onto recordRoll (issue #915, part four). An opportunity strike posts a line of its own in a GM call and out of one, as a death save does, and nothing draws cards from the short turn the strike opens. So the line is the home of the strike's cards: its attack and damage are recorded with home "line", and the line lists them and then the public rolls the blow went on to make on the short turn (a rider's save). A death save's line lists the save, and the die of the stable wait a third success or a Periapt of Wound Closure rolls. At a table a person runs, a roll that held its call is listed on the line the call posts once it lands. One that a line of its own already carries stays on that line alone (persons-record.ts, messages.ts lineCarriesRoll). A character's opportunity swing, death save and Stealth as an ambush opens come through rollCharacterD20, so dice the player entered at the table are on record and sent as theirs. The clock's dice (hit dice, the stable wait's d4 from stabilize, a knockout or a rage that ends at 0, an item's charges, a Ring of Regeneration) and a character's initiative and Stealth as a fight opens join the turn of the GM call that rolled them. On an AI's turn the custom rolls among them are stamped spent as that call ends, as every die of the engine's own is. Rolled where no call runs, they are on no turn, as before. The ledger reads 7 files (store 4, send 5, join 2). 14 sweep runs are struck from its rows: 69 are left, none failing "sent". Co-Authored-By: Claude Fable 5.2 --- scripts/roll-record-sites.json | 31 +-- scripts/test-enforce-roll-record.mjs | 281 ++++++++++++++++++++++++++- src/lib/db/messages.ts | 13 ++ src/lib/dm/death.ts | 53 ++--- src/lib/dm/encounter-open.ts | 40 ++-- src/lib/dm/encounter-tools.ts | 14 +- src/lib/dm/hit-dice.ts | 13 +- src/lib/dm/item-charges.ts | 11 +- src/lib/dm/opportunity-pets.ts | 22 ++- src/lib/dm/opportunity-sides.ts | 28 +-- src/lib/dm/opportunity-strike.ts | 76 +++++--- src/lib/dm/opportunity.ts | 50 ++--- src/lib/dm/persons-record.ts | 8 +- src/lib/dm/regeneration-ring.ts | 11 +- src/lib/dm/stabilize.ts | 2 +- 15 files changed, 489 insertions(+), 164 deletions(-) diff --git a/scripts/roll-record-sites.json b/scripts/roll-record-sites.json index dd21796cce..e340fc827c 100644 --- a/scripts/roll-record-sites.json +++ b/scripts/roll-record-sites.json @@ -1,27 +1,14 @@ { "_about": "Every file that still puts a roll on record by hand, outside the one door for it (src/lib/dm/roll-record.ts recordRoll): how many times it stores one (insertRoll), sends one (a publish of \"roll_result\") and adds one to a turn's cards (a push or other write onto rollIds, or joinStoredTurn), and the family of sites it moves onto the door with. A site moved is struck off, so the counts only go down; `total` is their sum. A send through a file's own wrapper is counted once, where the wrapper is written; a new site in such a file still shows, because it has to store its roll. Held by scripts/test-roll-record-sites.mjs; `node scripts/test-roll-record-sites.mjs --counts` prints what the source holds now.", - "total": { "store": 20, "send": 19, "join": 2 }, + "total": { "store": 4, "send": 5, "join": 2 }, "families": { - "opportunity": "An opportunity attack's swing and damage, made on a stand-in turn that nothing draws its cards from.", - "clock": "Dice rolled as time passes or a rest is taken, with no GM call around them: death saves and the stable timer, hit dice, an item's charges. Death saves post a line of their own, which is their card's home.", - "initiative": "The dice that open a fight. Creatures' initiative and stealth are stored for the GM and handed no turn; by the ruling on issue #915 they join the turn as a creature's saves do.", "requests": "A roll a person asked for outright (the dice tray, the GM's roll table), a parked roll put on record as it lands, and a secret roll sent again once it comes out." }, "sites": { "app/api/campaigns/[campaignId]/dm/roll-tables/[tableId]/roll/route.ts": { "store": 1, "send": 1, "family": "requests" }, "app/api/campaigns/[campaignId]/rolls/route.ts": { "store": 1, "send": 1, "family": "requests" }, - "lib/dm/death.ts": { "store": 2, "send": 2, "family": "clock" }, - "lib/dm/encounter-open.ts": { "store": 2, "send": 1, "family": "initiative" }, - "lib/dm/encounter-tools.ts": { "store": 1, "send": 1, "family": "initiative" }, "lib/dm/held-call.ts": { "store": 1, "send": 1, "family": "requests" }, - "lib/dm/hit-dice.ts": { "store": 1, "send": 1, "family": "clock" }, - "lib/dm/item-charges.ts": { "store": 1, "send": 1, "family": "clock" }, - "lib/dm/opportunity-pets.ts": { "store": 2, "send": 2, "family": "opportunity" }, - "lib/dm/opportunity-sides.ts": { "store": 2, "send": 2, "family": "opportunity" }, - "lib/dm/opportunity-strike.ts": { "store": 2, "send": 1, "family": "opportunity" }, - "lib/dm/opportunity.ts": { "store": 2, "send": 2, "family": "opportunity" }, "lib/dm/pending-roll-land.ts": { "store": 1, "send": 1, "family": "requests" }, - "lib/dm/regeneration-ring.ts": { "store": 1, "send": 1, "family": "clock" }, "lib/dm/retry-turn.ts": { "join": 1, "family": "requests" }, "lib/dm/roll-card.ts": { "send": 1, "family": "requests" }, "lib/dm/turn.ts": { "join": 1, "family": "requests" } @@ -61,8 +48,6 @@ "request_roll.save.in_fight@console": ["home"], "pc_attack.weapon@console": ["home"], "pc_attack.spell@console": ["home"], - "opportunity.enemy_walks_off@console": ["home", "sent"], - "opportunity.enemy_flees@console": ["home", "sent"], "cast_at_player.hazard@console": ["roller"], "cast_at_player.hazard@ai": ["roller"], "apply_hazard.falling@console": ["roller"], @@ -95,21 +80,9 @@ "apply_hazard.trap.Sphere of Annihilation@ai": ["roller"], "apply_hazard.trap.Rolling Sphere@console": ["roller"], "apply_hazard.trap.Rolling Sphere@ai": ["roller"], - "death_save.turn_pass@console": ["home", "sent"], - "death_save.turn_pass@ai": ["home", "sent"], "concentration.damage@console": ["roller"], "concentration.damage@ai": ["roller"], - "stabilize.check@console": ["home"], - "stabilize.check@ai": ["home"], - "stabilize.kit@console": ["home"], - "stabilize.kit@ai": ["home"], - "take_rest.hit_dice@console": ["home"], - "take_rest.hit_dice@ai": ["home"], "start_encounter.plain@console": ["home"], - "start_encounter.plain@ai": ["home"], - "start_encounter.party_ambush@console": ["home", "sent"], - "start_encounter.party_ambush@ai": ["home", "sent"], - "start_encounter.enemies_ambush@console": ["home"], - "start_encounter.enemies_ambush@ai": ["home"] + "start_encounter.enemies_ambush@console": ["home"] } } diff --git a/scripts/test-enforce-roll-record.mjs b/scripts/test-enforce-roll-record.mjs index 317a783a1e..fdd90099a4 100644 --- a/scripts/test-enforce-roll-record.mjs +++ b/scripts/test-enforce-roll-record.mjs @@ -38,6 +38,14 @@ // damage, the swing queued behind it), are on the attack's turn, and the // d20 itself is listed ahead of them, on the turn and on the line a // person's turn posts; +// - an opportunity attack's cards are on the line the strike posts, in a +// GM call and out of one: its attack, its damage, then what the blow went +// on to roll on its short turn. A death save's card is on its line the +// same way, with the die of the stable wait a third success rolls. At +// a table a person runs, such a roll its player entered is on that line +// alone, not on the line the GM's call posts as well; +// - the dice the clock throws inside a GM call (an item's charges at dawn, +// a Ring of Regeneration's) are on that call's turn; // - at the engine: Sleep's pool and a creature's initiative are on the // turn of the call that rolled them. // @@ -65,11 +73,11 @@ const { getDatabase } = await import("../src/lib/db/core.ts"); const { insertCampaignMessage, listRecentMessages } = await import("../src/lib/db/messages.ts"); const { insertPlayerWhisper } = await import("../src/lib/db/dm-whispers.ts"); const relationships = await import("../src/lib/db/relationships.ts"); -const { allocateSeq, setDmMode } = await import("../src/lib/db/campaigns.ts"); +const { allocateSeq, setDmMode, setMemberRealDice } = await import("../src/lib/db/campaigns.ts"); const { firstStoredAfter, getRoll } = await import("../src/lib/db/rolls.ts"); const { getSheetById } = await import("../src/lib/db/sheets.ts"); const { invokeEngine } = await import("../src/lib/dm/invoke.ts"); -const { rollExpression } = await import("../src/lib/dice.ts"); +const { entryDice, rollExpression } = await import("../src/lib/dice.ts"); const { isHeldPark, parkHeldCall, runHeld, takeDecided } = await import("../src/lib/dm/held-call.ts"); const { recordRoll } = await import("../src/lib/dm/roll-record.ts"); const { dmRoll, rollCard, secretRoll } = await import("../src/lib/dm/roll-card.ts"); @@ -552,8 +560,277 @@ await test("an AI GM's answer to a whisper stays out of the shared chat when the } }); +// ---- opportunity attacks, death saves and the clock's dice ---- + +const { resolveOpportunityAttacks } = await import("../src/lib/dm/opportunity.ts"); +const { enemiesStrikeWalker } = await import("../src/lib/dm/opportunity-sides.ts"); +const { strikePetsOnWalk } = await import("../src/lib/dm/opportunity-pets.ts"); +const { rollDeathSave } = await import("../src/lib/dm/death.ts"); +const { rechargeAtDawn } = await import("../src/lib/dm/item-charges.ts"); +const { regenerationClock } = await import("../src/lib/dm/regeneration-ring.ts"); +const { patchEnemyConditions } = await import("../src/lib/db/encounters.ts"); + +// The one line that carries these rolls' cards: it lists them in the order +// they were made, no other line lists any of them, and each has one home. +function onOneLine(rolls, what, table = world) { + assert.ok(rolls.length, `${what}: no roll was made`); + const lines = listRecentMessages(table.campaignId, 80).filter((message) => message.authorType === "system" && rolls.some((roll) => message.rollIds?.includes(roll.id))); + assert.equal(lines.length, 1, `${what}: ${lines.length} lines list its rolls: ${lines.map((line) => line.content).join(" | ")}`); + assert.deepEqual(lines[0].rollIds, rolls.map((roll) => roll.id), `${what}: the line does not list its rolls in the order they were made`); + for (const roll of rolls) { + assert.equal(homeProblem(roll.id), null, `${what}: ${roll.kind} "${roll.detail}"`); + } + return lines[0]; +} + +// On no turn: its line is its only home. +const onNoTurn = (rolls, what) => { + for (const roll of rolls) { + assert.deepEqual(rollHomes(roll.id).turns, [], `${what}: its ${roll.kind} is on a turn as well as on its line`); + } +}; + +// A fight on a bare floor with everyone far apart, and its creatures. +async function bareFight(count = 1) { + await kit.fight(count, { heroFaces: { [hero.id]: 19, [mage.id]: 5 } }); + kit.openField(); + kit.scatter(); + const enemies = world.enemies(); + for (const enemy of enemies) { + kit.setEnemy(enemy.id, { maxHp: 200, currentHp: 200 }); + } + return enemies; +} + +await test("a creature's opportunity attack on a character who walks away outside any GM call is on the line the strike posts: the attack, its damage, then the save its rider forced on the strike's short turn", async () => { + const [enemy] = await bareFight(); + // A wolf's bite: a Strength save or be knocked prone. + kit.setEnemy(enemy.id, { stats: { attacks: [{ name: "Bite", toHit: 4, damage: "2d4+2", type: "piercing", mode: "melee", onHit: { save: "str", dc: 11, condition: "prone" } }] } }); + kit.place(enemy.id, 5, 5); + kit.place(mage.id, 6, 5); + const mark = rollMark(); + // The creature's d20, its two damage dice, the mage's Strength save. + world.dice(19, 2, 2, 5); + const out = resolveOpportunityAttacks(campaign(), mage.id, { x: 6, y: 5 }, { x: 8, y: 5 }, false, [{ x: 7, y: 5 }, { x: 8, y: 5 }]); + world.clearDice(); + const made = rollsAfter(world.campaignId, mark); + await kit.endFight(); + assert.equal(out.notes.length, 1, `the walk posted ${out.notes.length} lines: ${out.notes.join(" ")}`); + assert.deepEqual(made.map((roll) => roll.kind), ["attack", "damage", "saving_throw"], made.map((roll) => roll.detail).join(", ")); + const line = onOneLine(made, "the strike"); + assert.equal(line.content, out.notes[0]); + const [toHit, damage, save] = made; + assert.equal(toHit.attacker?.id, enemy.id); + assert.equal(damage.attacker?.id, enemy.id); + onNoTurn([toHit, damage], "the strike"); + assert.equal(rollHomes(save.id).turns.length, 1, "the save the rider forced is not on the strike's short turn"); +}); + +await test("inside a GM call, a creature's opportunity attack is on the strike's line all the same, and not on the call's turn", async () => { + const [enemy] = await bareFight(); + kit.place(enemy.id, 5, 5); + kit.place(mage.id, 6, 5); + const turn = newTurn(); + const mark = rollMark(); + world.dice(19, 4); + const out = runHeld(campaign(), turn, SPEC, () => resolveOpportunityAttacks(campaign(), mage.id, { x: 6, y: 5 }, { x: 8, y: 5 }, false, [{ x: 7, y: 5 }, { x: 8, y: 5 }])); + world.clearDice(); + saveDmTurn(turn); + const made = rollsAfter(world.campaignId, mark); + await kit.endFight(); + assert.equal(out.notes.length, 1, `the walk posted ${out.notes.length} lines: ${out.notes.join(" ")}`); + assert.deepEqual(made.map((roll) => roll.kind), ["attack", "damage"]); + onOneLine(made, "the strike"); + onNoTurn(made, "the strike"); + assert.deepEqual(storedIds(turn.id), [], "the call's turn lists the strike's dice"); +}); + +await test("a character's opportunity swing at a creature the GM walks off is on the line the swing posts, and not on the turn of the call that moved the creature", async () => { + const [enemy] = await bareFight(); + const carried = world.sheet(hero.id).equipment; + world.patch(hero.id, { equipment: [{ name: "Longsword", qty: 1, equipped: true }] }); + kit.place(hero.id, 5, 5); + kit.place(enemy.id, 6, 5); + kit.enemyTurn(enemy.id); + const mark = rollMark(); + // The fighter's d20 (a hit) and the sword's d8. + world.dice(15, 5); + const out = await world.invoke("move_token", { token: enemy.id, x: 9, y: 5 }); + world.clearDice(); + const made = rollsAfter(world.campaignId, mark).filter((roll) => /opportunity attack/.test(roll.detail)); + await kit.endFight(); + world.patch(hero.id, { equipment: carried }); + assert.equal(out.ok, true, `refused: ${out.error}`); + assert.deepEqual(made.map((roll) => roll.kind), ["attack", "damage"]); + const line = onOneLine(made, "the swing"); + assert.match(line.content, /opportunity attack/); + assert.ok(made.every((roll) => roll.attacker?.id === hero.id), "the swing names another roller"); + onNoTurn(made, "the swing"); +}); + +await test("at a table a person runs, an opportunity swing its player rolled on their own dice is on the swing's line alone, not on the line the GM's call posts as well", async () => { + const table = await openWorld({ gameSettings: { dicePolicy: "real_allowed" } }); + assert.ok(setDmMode(table.campaignId, "human", table.owner.id)?.dmUserId, "the owner takes the GM's seat"); + const tableKit = await combatKit(table); + const fighter = table.addHero({ + user: table.addUser(), name: "Reya", class: "fighter", level: 5, maxHp: 44, abilities: { str: 16 }, proficiencies: TRAINED, + equipment: [{ name: "Longsword", qty: 1, equipped: true }], + }); + await tableKit.fight(1, { heroFaces: { [fighter.id]: 19 } }); + tableKit.openField(); + tableKit.scatter(); + const [enemy] = table.enemies(); + tableKit.setEnemy(enemy.id, { maxHp: 200, currentHp: 200 }); + tableKit.place(fighter.id, 5, 5); + tableKit.place(enemy.id, 6, 5); + tableKit.enemyTurn(enemy.id); + setMemberRealDice(table.campaignId, table.sheet(fighter.id).userId, true); + const mark = rollMark(); + const walked = await table.invoke("move_token", { token: enemy.id, x: 9, y: 5 }); + assert.equal(walked.ok, true, `refused: ${walked.error}`); + assert.equal(walked.result?.parked, true, `the walk did not wait on the seat's dice: ${JSON.stringify(walked.result)}`); + // The seat enters its d20 (a hit), then the damage the call asks for next. + const submit = await table.route("campaigns/[campaignId]/pending-rolls/[pendingRollId]"); + for (let round = 0; round < 4; round += 1) { + const open = listOpenPendingRolls(table.campaignId).filter((pending) => pending.parkedFor === "real_dice"); + if (!open.length) { + break; + } + for (const pending of open) { + table.signIn({ id: pending.userId }); + const landed = await callRoute(submit, "POST", { dice: entryDice(pending.expression).map((sides) => (sides === 20 ? 15 : 3)) }, { campaignId: table.campaignId, pendingRollId: pending.id }); + assert.equal(landed.status, 200, JSON.stringify(landed.json)); + } + } + const made = rollsAfter(table.campaignId, mark).filter((roll) => /opportunity attack/.test(roll.detail)); + assert.deepEqual(made.map((roll) => roll.kind), ["attack", "damage"]); + assert.ok(made.every((roll) => /\(physical\)$/.test(roll.detail)), "the seat's own dice are not on record as theirs"); + const line = onOneLine(made, "the swing", table); + assert.match(line.content, /opportunity attack/); + onNoTurn(made, "the swing"); + table.close(); +}); + +await test("inside a GM call, a creature's opportunity attack on a pet walking off with its owner, and on a creature of the other side, are each on the line that strike posts and not on the call's turn", async () => { + const [enemy] = await bareFight(); + world.patch(hero.id, { pets: [{ name: "Ember", kind: "familiar", form: "imp", hp: 30, maxHp: 30, ac: 10, speed: 20, attacks: [], notes: "" }] }); + kit.place(enemy.id, 5, 5); + kit.place(hero.id, 6, 5); + const turn = newTurn(); + let mark = rollMark(); + world.dice(15, 4); + const atPet = runHeld(campaign(), turn, SPEC, () => strikePetsOnWalk(campaign(), hero.id, [{ x: 6, y: 5 }, { x: 7, y: 5 }, { x: 8, y: 5 }])); + world.clearDice(); + let made = rollsAfter(world.campaignId, mark); + world.patch(hero.id, { pets: [] }); + await kit.endFight(); + assert.equal(atPet.length, 1, `the pet's walk posted ${atPet.length} lines`); + assert.deepEqual(made.map((roll) => roll.kind), ["attack", "damage"]); + assert.equal(onOneLine(made, "the strike at the pet").content, atPet[0]); + onNoTurn(made, "the strike at the pet"); + assert.ok(made.every((roll) => roll.attacker?.id === enemy.id && roll.characterId === hero.id), "the strike at the pet names another roller or owner"); + + // Two creatures: the first fights for the party (Dominate Person) and + // strikes the second as it walks off. + const [turned, walker] = await bareFight(2); + patchEnemyConditions(turned.id, ["charmed"], { charmed: { spell: "Dominate Person", source: hero.id } }); + kit.place(turned.id, 5, 5); + kit.place(walker.id, 6, 5); + mark = rollMark(); + world.dice(15, 4); + const atWalker = runHeld(campaign(), turn, SPEC, () => enemiesStrikeWalker(world.campaignId, walker.id, [{ x: 6, y: 5 }, { x: 7, y: 5 }, { x: 8, y: 5 }], 1)); + world.clearDice(); + saveDmTurn(turn); + made = rollsAfter(world.campaignId, mark).filter((roll) => roll.visibility === "public"); + await kit.endFight(); + assert.equal(atWalker.length, 1, `the creature's walk posted ${atWalker.length} lines`); + assert.deepEqual(made.map((roll) => roll.kind), ["attack", "damage"]); + assert.equal(onOneLine(made, "the strike at the creature").content, atWalker[0]); + onNoTurn(made, "the strike at the creature"); + assert.ok(made.every((roll) => roll.attacker?.id === turned.id), "the strike at the creature names another roller"); + assert.deepEqual(storedIds(turn.id), [], "the call's turn lists a strike's dice"); +}); + +await test("a death save is on the line it posts and on no turn, outside a GM call and inside one, where a third success's line lists the save and then the die of the stable wait", () => { + const dying = (successes = 0) => world.patch(hero.id, { currentHp: 0, deathSaves: { successes, failures: 0, stable: false, dead: false }, conditions: ["unconscious", "prone"], conditionMeta: {} }); + const saved = (mark) => rollsAfter(world.campaignId, mark); + dying(); + let mark = rollMark(); + world.dice(12); + const said = rollDeathSave(campaign(), hero.id); + world.clearDice(); + let made = saved(mark); + assert.deepEqual(made.map((roll) => roll.kind), ["saving_throw"]); + assert.equal(onOneLine(made, "a death save outside a call").content, said); + onNoTurn(made, "a death save outside a call"); + + dying(2); + const turn = newTurn(); + mark = rollMark(); + // The save, then the d4 of hours. + world.dice(12, 3); + runHeld(campaign(), turn, SPEC, () => rollDeathSave(campaign(), hero.id, turn.id)); + world.clearDice(); + saveDmTurn(turn); + made = saved(mark); + world.patch(hero.id, { currentHp: 44, deathSaves: null, conditions: [], conditionMeta: {} }); + assert.deepEqual(made.map((roll) => roll.kind), ["saving_throw", "custom"]); + onOneLine(made, "a third success inside a call"); + onNoTurn(made, "a third success inside a call"); + assert.deepEqual(storedIds(turn.id), [], "the call's turn lists the save or the die of the stable wait"); +}); + +await test("the dice the clock throws inside a GM call are on that call's turn: an item's charges at dawn and a Ring of Regeneration's", () => { + world.patch(hero.id, { + currentHp: 10, + equipment: [{ name: "Wand of Magic Missiles", qty: 1, charges: 1 }, { name: "Ring of Regeneration", qty: 1, attuned: true, equipped: true }], + }); + const turn = newTurn(); + const mark = rollMark(); + world.dice(3, 2); + runHeld(campaign(), turn, SPEC, () => { + rechargeAtDawn(world.campaignId, 0, 24 * 60); + regenerationClock(world.campaignId, 0, 10); + }); + world.clearDice(); + saveDmTurn(turn); + const made = rollsAfter(world.campaignId, mark); + world.patch(hero.id, { currentHp: 44, equipment: [] }); + assert.equal(made.length, 2, `the clock stored ${made.length} rolls: ${made.map((roll) => roll.detail).join(", ")}`); + assert.match(made[0].detail, /Wand of Magic Missiles regains charges at dawn/); + assert.match(made[1].detail, /Ring of Regeneration/); + assert.deepEqual(storedIds(turn.id), made.map((roll) => roll.id), "the call's turn does not hold the clock's two rolls"); + for (const roll of made) { + assert.equal(homeProblem(roll.id), null, roll.detail); + } +}); + // ---- a roll that joins its turn pays for no number of the model's ---- +await test("an AI GM's bare heal equal to a Ring of Regeneration's dice is refused: thrown as its pass_time moved the clock, they are on the turn now, and spent as that call ends", async () => { + world.patch(hero.id, { currentHp: 10, equipment: [{ name: "Ring of Regeneration", qty: 1, attuned: true, equipped: true }] }); + world.say("player", "We wait ten minutes for the rain to pass.", getSheetById(hero.id)); + const turn = createDmTurn(world.campaignId, [], "ai"); + const call = (name, args) => invokeEngine(campaign(), { kind: "ai", turnId: turn.id }, { name, args }); + const mark = rollMark(); + world.dice(4); + const waited = await call("pass_time", { amount: 10, unit: "minutes" }); + world.clearDice(); + assert.equal(waited.ok, true, `refused: ${waited.error}`); + const found = rollsAfter(world.campaignId, mark).find((roll) => /Ring of Regeneration/.test(roll.detail)); + assert.ok(found, "the ring rolled nothing"); + const ring = getRoll(found.id); + assert.deepEqual(rollHomes(ring.id).turns, [turn.id], "the ring's dice are not on the AI's turn"); + const before = world.sheet(hero.id).currentHp; + const healed = await call("heal", { characterId: hero.id, amount: ring.total }); + const after = world.sheet(hero.id).currentHp; + world.patch(hero.id, { currentHp: 44, equipment: [] }); + turn.status = "done"; + saveDmTurn(turn); + assert.equal(healed.ok, false, `a bare heal of ${ring.total}, the total of the ring's dice, was taken and healed ${after - before}`); + assert.equal(after, before); +}); + await test("an AI GM's bare heal equal to Sleep's pool is refused: the pool is on the turn now, and it is the engine's own, spent as its call ends", async () => { await kit.fight(2, { heroFaces: { [mage.id]: 19, [hero.id]: 5 } }); const [enemy] = world.enemies(); diff --git a/src/lib/db/messages.ts b/src/lib/db/messages.ts index 469cbd033c..add2579387 100644 --- a/src/lib/db/messages.ts +++ b/src/lib/db/messages.ts @@ -236,6 +236,19 @@ export function listRecentMessages(campaignId: string, limit = 100): CampaignMes return rows.map(mapMessage); } +// Whether a line already carries this roll's card: a roll its site posted a +// line for has that line as its home (src/lib/dm/roll-record.ts), and is +// listed on no other. +export function lineCarriesRoll(campaignId: string, rollId: string): boolean { + const found = getDatabase() + .prepare( + `SELECT 1 FROM campaign_messages AS m, json_each(m.roll_ids_json) AS listed + WHERE m.campaign_id = ? AND m.roll_ids_json IS NOT NULL AND listed.value = ? LIMIT 1`, + ) + .get(campaignId, rollId); + return Boolean(found); +} + // The GM's own messages from `sinceSeq` on, the newest `limit` of them, in // ascending seq order (src/lib/dm/improvise.ts reads the place's narration). export function listDmMessagesSince(campaignId: string, sinceSeq: number, limit: number): CampaignMessage[] { diff --git a/src/lib/dm/death.ts b/src/lib/dm/death.ts index 62303775e6..4bd41c66f2 100644 --- a/src/lib/dm/death.ts +++ b/src/lib/dm/death.ts @@ -14,7 +14,7 @@ import { insertSheetAudit } from "@/lib/db/sheet-audit"; import { insertCharacterEvent } from "@/lib/db/character-events"; import { noteDeathMoment } from "@/lib/dm/revival"; import { insertCampaignMessage } from "@/lib/db/messages"; -import { insertRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { rollExpression } from "@/lib/dice"; import { publishPersisted, publishWithSeq } from "@/lib/events"; import type { CharacterSheet, DeathSaves, FullPatchSheetInput } from "@/lib/schemas/sheet"; @@ -111,7 +111,9 @@ export function killOutright(campaign: Campaign, turnId: string | null, sheet: C return getSheetById(sheet.id); } -function tableNote(campaign: Campaign, content: string, glyph: SystemGlyph) { +// `rollIds`: the rolls whose cards this line is the home of (a death save +// and the die of the stable wait it rolls; roll-record.ts `home: "line"`). +function tableNote(campaign: Campaign, content: string, glyph: SystemGlyph, rollIds: readonly string[] = []) { const seq = tableNoteSeq(campaign.id); const message = insertCampaignMessage({ campaignId: campaign.id, @@ -119,6 +121,7 @@ function tableNote(campaign: Campaign, content: string, glyph: SystemGlyph) { authorType: "system", glyph, content, + rollIds, }); publishWithSeq(campaign.id, seq, "message_added", { message }); } @@ -204,7 +207,7 @@ export function applyDamageDeathHook( // Creature Out): no death saves, the stable wait for the hit point, and // no instant death, which the attacker chose not to deal. if (nonlethal) { - const wait = rollStableTimer(campaign, fresh); + const wait = rollStableTimer(campaign, fresh, { turnId }); writeDeathState(campaign, turnId, fresh, stableDeathTrack(), "death_state", "knocked out", { conditions: wait.conditions, conditionMeta: wait.conditionMeta, @@ -310,25 +313,28 @@ export function healDeathHook( // A stabilized creature's wait for its hit point: 1d4 hours, rolled here so // the table sees the die. Returns the condition metadata carrying the wait. -export function rollStableTimer(campaign: Campaign, sheet: CharacterSheet) { +// Its card joins the turn its caller holds (`turnId`; inside a GM call, that +// call's own), or, `onLine`, is left to the line its caller posts (a death +// save's), which lists `rollId`. +export function rollStableTimer(campaign: Campaign, sheet: CharacterSheet, where: { turnId?: string | null; onLine?: boolean } = {}) { const outcome = rollExpression("1d4"); - const roll = insertRoll({ + const roll = recordRoll({ campaignId: campaign.id, characterId: sheet.id, requestedBy: "dm", kind: "custom", detail: `hours until ${sheet.name} regains 1 hit point (1d4)`, result: outcome, - }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { - roll, - source: "digital", + ...(where.onLine ? { home: "line" as const } : { turnId: where.turnId ?? null }), + // Thrown here, on the server's dice. + landing: null, }); const held = downConditions(sheet); return { hours: outcome.total, conditions: held.conditions, conditionMeta: stableTimer(held, outcome.total), + rollId: roll.id, }; } @@ -368,7 +374,9 @@ export function registerDeathSaveStandIn(hook: DeathSaveStandIn) { // One automatic death save, rolled server-side when the initiative pointer // passes a dying PC. Publishes the dice card and a table note so both the -// players and the model (via history) see the result. +// players and the model (via history) see the result. The note is the home +// of the save's card, and of the stable wait's die when the save rolls one +// (issue #915): the save joins no turn, in a fight or out of one. // `at`: the in-world instant of this save when the clock has already moved // past it (settleDying on the clock), for the moment of a death it brings. export function rollDeathSave(campaign: Campaign, characterId: string, turnId: string | null = null, at?: number): string | null { @@ -390,13 +398,13 @@ export function rollDeathSave(campaign: Campaign, characterId: string, turnId: s // dying at the start of your turn." The save this would have been is not // rolled; the wearer waits out the stable creature's 1d4 hours. if (wearsWorkingItem(sheet.equipment, sheet, WOUND_CLOSURE)) { - const wait = rollStableTimer(campaign, sheet); + const wait = rollStableTimer(campaign, sheet, { onLine: true }); writeDeathState(campaign, turnId, sheet, stableDeathTrack(), "death_state", WOUND_CLOSURE, { conditions: wait.conditions, conditionMeta: wait.conditionMeta, }); const line = `${sheet.name}'s ${WOUND_CLOSURE} closes their wounds: they are stable (unconscious at 0 HP) and regain 1 hit point in ${wait.hours} hour${wait.hours === 1 ? "" : "s"}.`; - tableNote(campaign, line, "cue-heal"); + tableNote(campaign, line, "cue-heal", [wait.rollId]); return line; } // A death save is a saving throw tied to no ability: it takes what every @@ -442,7 +450,9 @@ export function rollDeathSave(campaign: Campaign, characterId: string, turnId: s const current = getSheetById(characterId) ?? sheet; const advantage = /^2d20kh1/.test(resolved.expression) ? "advantage" : /^2d20kl1/.test(resolved.expression) ? "disadvantage" : "none"; const notes = [...(resolved.conditionNotes ?? []), ...(hope ? [`${hope}: advantage`] : []), ...(feat ? [`${feat}: advantage`] : [])]; - const roll = insertRoll({ + // Their own dice, through the door above: entered at the table, they are + // on record and sent as theirs. + const roll = recordRoll({ campaignId: campaign.id, characterId: sheet.id, requestedBy: "dm", @@ -451,10 +461,7 @@ export function rollDeathSave(campaign: Campaign, characterId: string, turnId: s dc: 10, ...(advantage === "none" ? {} : { advantage }), result: outcome, - }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { - roll, - source: "digital", + home: "line", }); const applied = applyDeathSaveRoll(track, outcome.natural ?? outcome.total, outcome.total); // A death save that succeeds steadies them (last-save.ts): Defy Death answers it. @@ -470,7 +477,7 @@ export function rollDeathSave(campaign: Campaign, characterId: string, turnId: s ...wakeConditions(current), }); const line = `${rolled("natural 20")} ${sheet.name} rolls a natural 20 on their death save and regains 1 HP!`; - tableNote(campaign, line, "cue-heal"); + tableNote(campaign, line, "cue-heal", [roll.id]); return line; } // Rage Beyond Death: stable or dead on the track, a raging zealot stays up @@ -480,30 +487,30 @@ export function rollDeathSave(campaign: Campaign, characterId: string, turnId: s const line = applied.outcome === "stable" ? `${rolled("success")} ${sheet.name} succeeds their third death save and is stable at 0 HP, still raging on their feet.` : `${rolled("failure")} ${sheet.name} fails their third death save. Rage Beyond Death holds the death off: they die when the rage ends, if they are still at 0 hit points then.`; - tableNote(campaign, line, applied.outcome === "stable" ? "cue-heal" : "cue-death"); + tableNote(campaign, line, applied.outcome === "stable" ? "cue-heal" : "cue-death", [roll.id]); return line; } if (applied.outcome === "stable") { - const wait = rollStableTimer(campaign, current); + const wait = rollStableTimer(campaign, current, { onLine: true }); writeDeathState(campaign, turnId, current, applied.track, "death_state", "automatic death save", { conditions: wait.conditions, conditionMeta: wait.conditionMeta, }); const line = `${rolled("success")} ${sheet.name} succeeds their third death save and is stable (unconscious at 0 HP). They regain 1 hit point in ${wait.hours} hour${wait.hours === 1 ? "" : "s"}.`; - tableNote(campaign, line, "cue-heal"); + tableNote(campaign, line, "cue-heal", [roll.id, wait.rollId]); return line; } writeDeathState(campaign, turnId, current, applied.track, "death_state", "automatic death save"); if (applied.outcome === "dead") { recordDeath(campaign, current, "failed death saving throws", at); const line = `${rolled("failure")} ${sheet.name} fails their final death save and dies.`; - tableNote(campaign, line, "cue-death"); + tableNote(campaign, line, "cue-death", [roll.id]); return line; } const line = `${sheet.name} death save: rolled ${outcome.total}, ${ applied.outcome === "success" ? "success" : "failure" } (${tally(applied.track)}).`; - tableNote(campaign, line, "die-d20"); + tableNote(campaign, line, "die-d20", [roll.id]); return line; } diff --git a/src/lib/dm/encounter-open.ts b/src/lib/dm/encounter-open.ts index b009981ce3..9a20dfe624 100644 --- a/src/lib/dm/encounter-open.ts +++ b/src/lib/dm/encounter-open.ts @@ -1,11 +1,10 @@ -import { allocateSeq, type Campaign } from "@/lib/db/campaigns"; +import type { Campaign } from "@/lib/db/campaigns"; import { cannotBeSurprised } from "@/lib/dm/surprise-guard"; import { canSurprise } from "@/lib/dm/genre-b-surprise"; import type { EncounterEnemy } from "@/lib/db/encounters"; -import { insertRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { getSheetById } from "@/lib/db/sheets"; import { d20Expression } from "@/lib/dice"; -import { publishWithSeq } from "@/lib/events"; import { watchfulPassivePerception } from "@/lib/bestiary/enemy-numbers"; import { passiveScore } from "@/lib/dm/check-tools"; import { getClock } from "@/lib/db/clock"; @@ -22,6 +21,13 @@ import { dmRoll } from "@/lib/dm/roll-card"; // Perception, and the initiative rolls of every character the server rolls // for. Split from encounter-tools.ts, which calls it; it must not import // encounter-tools (the initiative totals go back through a callback). +// +// Inside the GM call that opens the fight, every roll here joins that call's +// turn (issue #915): a creature's Stealth through dmRoll, a character's +// Stealth and initiative through the one door for a roll's record +// (roll-record.ts). No turn is handed in, so a fight opened outside a call +// (a companion turning on the party, encounter-tools.ts startFightAgainst) +// leaves them on none. // A creature's Stealth: its block's skill, else its Dexterity. function enemyStealth(enemy: EncounterEnemy): number { @@ -29,10 +35,6 @@ function enemyStealth(enemy: EncounterEnemy): number { return typeof skill === "number" && Number.isFinite(skill) ? skill : enemy.stats.dexMod; } -function publish(campaign: Campaign, roll: ReturnType) { - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { roll, source: "digital" }); -} - export type Ambush = { surprisedIds: string[]; lines: string[] }; // The side lying in wait rolls Stealth, each creature once; every opponent @@ -106,17 +108,16 @@ export function decideAmbush( dc: unseen, settleHeldDie: waits, }); - publish( - campaign, - insertRoll({ - campaignId: campaign.id, - characterId: sheet.id, - requestedBy: "dm", - kind: "skill_check", - detail: "stealth, lying in wait", - result: outcome, - }), - ); + // Their own dice, through the door above: entered at the table, they + // are on record and sent as theirs. + recordRoll({ + campaignId: campaign.id, + characterId: sheet.id, + requestedBy: "dm", + kind: "skill_check", + detail: "stealth, lying in wait", + result: outcome, + }); stealth.push(outcome.total); } const lowest = stealth.length ? Math.min(...stealth) : 0; @@ -170,7 +171,7 @@ export function rollOpeningInitiative( // Thrown by the server, and still the player's to answer with what they // hold (Lucky, Bardic Inspiration: WAVE1 R4) before the order locks. const outcome = rollCharacterD20(campaign, sheet, { kind: "initiative", expression: resolved.expression, detail: resolved.detail, mayWait: false }); - const roll = insertRoll({ + const roll = recordRoll({ campaignId: campaign.id, characterId: sheet.id, requestedBy: "dm", @@ -178,7 +179,6 @@ export function rollOpeningInitiative( detail: resolved.detail, result: outcome, }); - publish(campaign, roll); note = record(sheet.id, roll.total) ?? note; applyInitiativeRefills(campaign, sheet.id); rolled.push(`${sheet.name} ${roll.total}`); diff --git a/src/lib/dm/encounter-tools.ts b/src/lib/dm/encounter-tools.ts index 6f991e0c24..94b6667681 100644 --- a/src/lib/dm/encounter-tools.ts +++ b/src/lib/dm/encounter-tools.ts @@ -16,7 +16,6 @@ import { spellAuthorsFor } from "@/lib/dm/spell-authors"; import { sceneIds } from "@/lib/ambience/catalog"; import { z } from "zod"; import { - allocateSeq, getCampaignById, latestSeq, listMembers, @@ -47,7 +46,8 @@ import { } from "@/lib/db/encounters"; import { getSheetById, listSheets } from "@/lib/db/sheets"; import { feralInstinctOpening } from "@/lib/dm/mt-srd-barbarian"; -import { getRoll, insertRoll } from "@/lib/db/rolls"; +import { getRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { getLatestDmMessage, insertCampaignMessage, listRecentMessages } from "@/lib/db/messages"; import { closeStandInTurn, getDmTurn, listOpenPendingRolls, listPendingForTurn, openStandInTurn, saveDmTurn, setPendingAttack, type DmTurn } from "@/lib/db/dm-turns"; import { currentTurnId, runInTurnScope } from "@/lib/dm/job-control"; @@ -1010,17 +1010,17 @@ export function ensureInitiativeProgress(campaign: Campaign): string | null { const outcome = rollExpression(characterInitiativeExpression(campaign, sheet, computeSheetDerived(sheet).initiative), undefined, { purpose: { roller: "hero", kind: "initiative", who: sheet.name }, }); - const roll = insertRoll({ + // Rolled before the AI's turn is opened (turn.ts openTurn), so it is on + // no turn. + recordRoll({ campaignId: campaign.id, characterId: sheet.id, requestedBy: "dm", kind: "initiative", detail: "initiative", result: outcome, - }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { - roll, - source: "digital", + // Thrown here, on the server's dice. + landing: null, }); note = recordInitiativeRoll(campaign.id, sheet.id, outcome.total) ?? note; } diff --git a/src/lib/dm/hit-dice.ts b/src/lib/dm/hit-dice.ts index 687fd03139..e1f2caf4a2 100644 --- a/src/lib/dm/hit-dice.ts +++ b/src/lib/dm/hit-dice.ts @@ -23,10 +23,10 @@ import { getSheetById, listSheets, patchSheet } from "@/lib/db/sheets"; import { claimRestDie, restDieLeft } from "@/lib/db/clock"; import { hearsSong } from "@/lib/dm/mt-srd-bard"; import { insertSheetAudit } from "@/lib/db/sheet-audit"; -import { insertRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { rollEnteredDice, rollExpression, type RollResult } from "@/lib/dice"; import { rollCharacterDice, type DoorLanding } from "@/lib/dm/character-roll"; -import { onlineUserIds, publishPersisted, publishWithSeq } from "@/lib/events"; +import { onlineUserIds, publishPersisted } from "@/lib/events"; import { computeSheetDerived } from "@/lib/srd"; import { songOfRestDieFor } from "@/lib/srd/feature-effects"; import { healMath } from "@/lib/dm/mutation-math"; @@ -137,15 +137,18 @@ export function spendHitDice(input: { } else { outcome = rollExpression(expression); } - const roll = insertRoll({ + // On the turn of the call that spends them (the rest's, a feature's). The + // player's own spend from their sheet is made on no turn. + const roll = recordRoll({ campaignId: campaign.id, characterId: sheet.id, requestedBy: input.requestedBy, kind: "custom", - detail: landing?.physical ? `${detail} (physical)` : detail, + detail, result: outcome, + turnId: input.turnId, + landing, }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { roll, source: landing?.source ?? "digital" }); // Each die is floored at 0 on its own; the total is not what is floored. // Sewer plague: hit dice heal half the normal number (afflictions.ts). // Durable floors each die at twice the Constitution modifier; Stalwart diff --git a/src/lib/dm/item-charges.ts b/src/lib/dm/item-charges.ts index 2cff0fcb84..8f1812731b 100644 --- a/src/lib/dm/item-charges.ts +++ b/src/lib/dm/item-charges.ts @@ -16,10 +16,10 @@ import { allocateSeq } from "@/lib/db/campaigns"; import { insertSheetAudit } from "@/lib/db/sheet-audit"; -import { insertRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { listSheets, patchSheet } from "@/lib/db/sheets"; import { rollExpression } from "@/lib/dice"; -import { publishPersisted, publishWithSeq } from "@/lib/events"; +import { publishPersisted } from "@/lib/events"; import { MINUTES_PER_DAY, MINUTES_PER_HOUR } from "@/lib/dm/calendar"; import type { ChargeRule } from "@/lib/srd/magic-gear"; import type { CharacterSheet, EquipmentItem } from "@/lib/schemas/sheet"; @@ -277,15 +277,18 @@ export function rechargeAtDawn(campaignId: string, from: number, to: number): st continue; } const rolled = rollExpression(rule.regain); - const roll = insertRoll({ + // On the turn of the call that moved the clock (a rest, a journey); + // the clock moved outside one holds no turn. + recordRoll({ campaignId, characterId: sheet.id, requestedBy: "dm", kind: "custom", detail: `${item.name} regains charges at ${rule.regainAtDusk ? "dusk" : "dawn"}`, result: rolled, + // Thrown here, on the server's dice. + landing: null, }); - publishWithSeq(campaignId, allocateSeq(campaignId), "roll_result", { roll, source: "digital" }); charges = Math.min(most, charges + Math.max(0, rolled.total)); } if (charges === item.charges) { diff --git a/src/lib/dm/opportunity-pets.ts b/src/lib/dm/opportunity-pets.ts index 139b3046a1..3e21d6fe98 100644 --- a/src/lib/dm/opportunity-pets.ts +++ b/src/lib/dm/opportunity-pets.ts @@ -19,7 +19,7 @@ import { allocateSeq, type Campaign } from "@/lib/db/campaigns"; import { getActiveEncounter, listEnemies, saveEncounter } from "@/lib/db/encounters"; import { getBattleMapForEncounter, getTokenByRef } from "@/lib/db/battle-maps"; import { insertCampaignMessage } from "@/lib/db/messages"; -import { insertRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { getSheetById } from "@/lib/db/sheets"; import { enemyFootprint } from "@/lib/battlemap/footprint"; import { d20Expression, rollExpression } from "@/lib/dice"; @@ -37,7 +37,7 @@ import { opportunityWeapon } from "@/lib/dm/enemy-profile"; import { goadBarsOpportunity } from "@/lib/dm/goaded"; import { hasTrait } from "@/lib/dm/monster-abilities"; import { leavesReachAt } from "@/lib/dm/opportunity-reach-logic"; -import { enemyOpportunityRiders, opportunitySight } from "@/lib/dm/opportunity-strike"; +import { enemyOpportunityRiders, opportunitySight, strikeCards } from "@/lib/dm/opportunity-strike"; import { hurtPet } from "@/lib/dm/pet-tools"; import { creatureUnderwaterSwing } from "@/lib/dm/pet-underwater"; import { enfeebledBlow, spendEnemyRiders } from "@/lib/dm/spell-retort"; @@ -73,6 +73,8 @@ export function strikePetsOnWalk(campaign: Campaign, ownerId: string, steps: XY[ } const ownerSide = sideOf(encounter, "sheet", ownerId); const notes: string[] = []; + // The cards of each strike's line, by the line's place in `notes`. + const cards = new Map(); for (const enemy of listEnemies(encounter.id)) { const live = getSheetById(ownerId) ?? owner; const pet = (live.pets ?? []).find(petProvokes); @@ -128,10 +130,12 @@ export function strikePetsOnWalk(campaign: Campaign, ownerId: string, steps: XY[ const label = rollAgainst(`${attack.name} (opportunity attack)`, pet.name); const toHit = rollExpression(`${d20Expression(attack.toHit + effect.bonus, advantage)}${own.riders.diceSuffix}`, undefined, { purpose: { roller: "enemy", kind: "attack", who: enemy.displayName } }); spendEnemyRiders(enemy, own.riders); - const hitRoll = insertRoll({ campaignId: campaign.id, characterId: ownerId, requestedBy: "dm", kind: "attack", detail: label, advantage, result: toHit, attacker: { kind: "enemy", id: enemy.id, name: enemy.displayName } }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { roll: hitRoll, source: "digital" }); + // On the line this strike posts (opportunity-strike.ts strikeCards), and + // thrown here, on the server's dice. + const hitRoll = recordRoll({ campaignId: campaign.id, characterId: ownerId, requestedBy: "dm", kind: "attack", detail: label, advantage, result: toHit, attacker: { kind: "enemy", id: enemy.id, name: enemy.displayName }, home: "line", landing: null }); const hit = toHit.crit !== "nat1" && (toHit.crit === "nat20" || toHit.total >= pet.ac); if (!hit) { + cards.set(notes.length, strikeCards([hitRoll.id])); notes.push(`${enemy.displayName} takes an opportunity attack as ${pet.name} pulls away with ${live.name} and misses (${toHit.total} vs AC ${pet.ac}).`); continue; } @@ -141,8 +145,7 @@ export function strikePetsOnWalk(campaign: Campaign, ownerId: string, steps: XY[ undefined, { purpose: { roller: "enemy", kind: "damage", who: enemy.displayName } }, ); - const damageRoll = insertRoll({ campaignId: campaign.id, characterId: ownerId, requestedBy: "dm", kind: "damage", detail: label, result: damage, attacker: { kind: "enemy", id: enemy.id, name: enemy.displayName } }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { roll: damageRoll, source: "digital" }); + const damageRoll = recordRoll({ campaignId: campaign.id, characterId: ownerId, requestedBy: "dm", kind: "damage", detail: label, result: damage, attacker: { kind: "enemy", id: enemy.id, name: enemy.displayName }, home: "line", landing: null }); const blow = blowByType(attack, damage, crit); // Enlarge/Reduce's floor and Ray of Enfeeblement's halving on the whole // blow, then a blow of two types (a hell hound's piercing and fire) meets @@ -155,12 +158,13 @@ export function strikePetsOnWalk(campaign: Campaign, ownerId: string, steps: XY[ magical: hasTrait(enemy.stats, "magicWeapons") || attack.magical === true, }); const after = String(struck.vanished ?? struck.down ?? (struck.hp ? `${pet.name} is at ${struck.hp}` : "")); + cards.set(notes.length, strikeCards([hitRoll.id, damageRoll.id])); notes.push(`${enemy.displayName} takes an opportunity attack as ${pet.name} pulls away with ${live.name}: ${crit ? "a critical hit for " : "hit for "}${String(struck.damage ?? 0)} damage.${after ? ` ${after}` : ""}`); } - for (const content of notes) { + notes.forEach((content, index) => { const seq = allocateSeq(campaign.id); - const message = insertCampaignMessage({ campaignId: campaign.id, seq, authorType: "system", glyph: "cue-battle", content }); + const message = insertCampaignMessage({ campaignId: campaign.id, seq, authorType: "system", glyph: "cue-battle", content, rollIds: cards.get(index) ?? [] }); publishWithSeq(campaign.id, seq, "message_added", { message }); - } + }); return notes; } diff --git a/src/lib/dm/opportunity-sides.ts b/src/lib/dm/opportunity-sides.ts index c2bd822e82..21001de48f 100644 --- a/src/lib/dm/opportunity-sides.ts +++ b/src/lib/dm/opportunity-sides.ts @@ -16,11 +16,11 @@ // so a wolf's bite at a dominated goblin walking off its packmate rolled one // d20 and never knocked it down. -import { allocateSeq, getCampaignById } from "@/lib/db/campaigns"; +import { getCampaignById } from "@/lib/db/campaigns"; import { getActiveEncounter, getEnemy, listEnemies, saveEncounter, type EncounterEnemy } from "@/lib/db/encounters"; import { getBattleMapForEncounter, getTokenByRef } from "@/lib/db/battle-maps"; import { insertCampaignMessage } from "@/lib/db/messages"; -import { insertRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { listSheets } from "@/lib/db/sheets"; import { enemyFootprint, type Footprint } from "@/lib/battlemap/footprint"; import { d20Expression, rollExpression } from "@/lib/dice"; @@ -39,7 +39,7 @@ import { critDamageExpression } from "@/lib/dm/encounter-logic"; import { leavesReachAt } from "@/lib/dm/opportunity-reach-logic"; import { conditionBlocksReactions } from "@/lib/srd/condition-effects"; import { tableNoteSeq } from "@/lib/dm/narration-slot"; -import { enemyOpportunityRiders, withOpportunityTurn } from "@/lib/dm/opportunity-strike"; +import { enemyOpportunityRiders, strikeCards, withOpportunityTurn } from "@/lib/dm/opportunity-strike"; import { enfeebledBlow, spendEnemyRiders } from "@/lib/dm/spell-retort"; import { hasTrait } from "@/lib/dm/monster-abilities"; import { allyBeside } from "@/lib/dm/side-allies"; @@ -70,6 +70,8 @@ export function enemiesStrikeWalker(campaignId: string, walkerId: string, steps: } const walkerSide = sideOf(encounter, "enemy", walkerId); const notes: string[] = []; + // The cards of each strike's line, by the line's place in `notes`. + const cards = new Map(); for (const reactor of listEnemies(encounter.id)) { const walker = getEnemy(walkerId); if (!walker || walker.status !== "alive") { @@ -139,12 +141,14 @@ export function enemiesStrikeWalker(campaignId: string, walkerId: string, steps: const toHit = rollExpression(`${d20Expression(attack.toHit + effect.bonus, advantage)}${own.riders.diceSuffix}`, undefined, { purpose: { roller: "enemy", kind: "attack", who: reactor.displayName } }); spendEnemyRiders(reactor, own.riders); const label = rollAgainst(`${attack.name} (opportunity attack)`, walker.displayName); - const hitRoll = insertRoll({ campaignId, characterId: null, requestedBy: "dm", kind: "attack", detail: label, advantage, result: toHit, attacker: { kind: "enemy", id: reactor.id, name: reactor.displayName } }); - publishWithSeq(campaignId, allocateSeq(campaignId), "roll_result", { roll: hitRoll, source: "digital" }); + // On the line this strike posts (opportunity-strike.ts strikeCards), and + // thrown here, on the server's dice. + const hitRoll = recordRoll({ campaignId, characterId: null, requestedBy: "dm", kind: "attack", detail: label, advantage, result: toHit, attacker: { kind: "enemy", id: reactor.id, name: reactor.displayName }, home: "line", landing: null }); const struck = toHit.crit !== "nat1" && (toHit.crit === "nat20" || toHit.total >= vsAc); // The walker's Parry or Shield, as on every other door (enemy-reactions.ts). const parry = struck && toHit.crit !== "nat20" ? tryParry({ encounter, enemy: walker, total: toHit.total, natural20: false, ac: vsAc, melee: true, attackerUnseen: attackerUnseen(reactor.conditions, walker.conditions, sight) }) : null; if (!struck || parry) { + cards.set(notes.length, strikeCards([hitRoll.id])); notes.push(`${reactor.displayName} takes an opportunity attack as ${walker.displayName} pulls away and misses (${toHit.total} vs AC ${vsAc}${parry ? `; ${parry.note}` : ""}).`); continue; } @@ -158,8 +162,9 @@ export function enemiesStrikeWalker(campaignId: string, walkerId: string, steps: undefined, { purpose: { roller: "enemy", kind: "damage", who: reactor.displayName } }, ); - const damageRoll = insertRoll({ campaignId, characterId: null, requestedBy: "dm", kind: "damage", detail: label, result: damage, attacker: { kind: "enemy", id: reactor.id, name: reactor.displayName } }); - publishWithSeq(campaignId, allocateSeq(campaignId), "roll_result", { roll: damageRoll, source: "digital" }); + const damageRoll = recordRoll({ campaignId, characterId: null, requestedBy: "dm", kind: "damage", detail: label, result: damage, attacker: { kind: "enemy", id: reactor.id, name: reactor.displayName }, home: "line", landing: null }); + // What the blow goes on to roll on its short turn, for the line. + const onTurn: string[] = []; const blow = blowByType(attack, damage, crit); // No floor of 1: a penalty can bring a blow to nothing (SRD 5.1), as on // every other door; only Reduce's own "can't reduce below 1" holds one. @@ -171,16 +176,17 @@ export function enemiesStrikeWalker(campaignId: string, walkerId: string, steps: const hit: Record = dealt > 0 ? landCreatureBlow({ campaign, turn, encounter, target: walker, dealt, blow, sheets, sheetsById, crit, magical, holdVictory: true }) : {}; const necrotic = /necrotic/i.test(blow.type ?? attack.type) ? dealt : 0; return { landed: hit, rider: hit.dead ? null : resolveRowOnHit(campaign, turn, reactor, attack, walker.id, { sheets, sheetsById, dealt: { total: dealt, necrotic } }) }; - }); + }, onTurn); const laid = Array.isArray(rider?.riderCondition) ? ` ${walker.displayName} is ${(rider.riderCondition as string[]).join(" and ")}.` : ""; + cards.set(notes.length, strikeCards([hitRoll.id, damageRoll.id], onTurn)); notes.push( `${reactor.displayName} takes an opportunity attack as ${walker.displayName} pulls away: ${crit ? "a critical hit for " : "hit for "}${dealt} damage${landed.dead ? `, and ${walker.displayName} falls` : ""}.${laid}`, ); } - for (const content of notes) { + notes.forEach((content, index) => { const seq = tableNoteSeq(campaignId); - const message = insertCampaignMessage({ campaignId, seq, authorType: "system", glyph: "cue-battle", content }); + const message = insertCampaignMessage({ campaignId, seq, authorType: "system", glyph: "cue-battle", content, rollIds: cards.get(index) ?? [] }); publishWithSeq(campaignId, seq, "message_added", { message }); - } + }); return notes; } diff --git a/src/lib/dm/opportunity-strike.ts b/src/lib/dm/opportunity-strike.ts index 0098956ce4..7237ee2c93 100644 --- a/src/lib/dm/opportunity-strike.ts +++ b/src/lib/dm/opportunity-strike.ts @@ -12,6 +12,17 @@ // The move route that provokes these has no DM turn, and the damage paths // keep their rolls and audit rows on one, so a short human-DM turn is // opened for the swing and closed with it. +// +// Where a strike's cards live (issue #915): on the line the strike posts, as +// a death save's are on its own (death.ts). Nothing draws cards from the +// short turn, and a walk through the move route has no GM turn at all, so +// the line is the one place every strike has. Its attack and damage are +// recorded with `home: "line"`, and the line lists them and then what the +// blow went on to roll on the short turn (strikeCards). Not on the line: a +// roll the damage path makes with no turn in hand (a concentration save; +// inside a GM call it is on that call's turn), a ward's save before the +// attack (opportunity-wards.ts), and a War Caster's spell cast in the +// swing's place. import { holdsFeature } from "@/lib/srd/feature-names"; import { getFoe } from "@/lib/dm/sheet-foe"; @@ -19,18 +30,19 @@ import { isSheetFoe } from "@/lib/dm/combat-sides-logic"; import { openLastHit } from "@/lib/dm/last-hit"; import { hasSentinel } from "@/lib/srd/feat-combat"; import { attackerUnseen, tryParry } from "@/lib/dm/enemy-reactions"; -import { allocateSeq, type Campaign } from "@/lib/db/campaigns"; +import type { Campaign } from "@/lib/db/campaigns"; import type { XY } from "@/lib/battlemap/types"; import { closeStandInTurn, dicePreferencesOf, openStandInTurn, type DmTurn } from "@/lib/db/dm-turns"; import { parkReasonFor } from "@/lib/dice/held-rolls"; import { damageDiceSteps } from "@/lib/dm/attack-damage-dice"; import { orderEntryId, patchEnemyConditions, type Encounter, type EncounterEnemy } from "@/lib/db/encounters"; -import { insertRoll, markRollApplied } from "@/lib/db/rolls"; +import { getRoll, markRollApplied } from "@/lib/db/rolls"; import { rollAgainst } from "@/lib/roll-labels"; import { getSheetById, listSheets, patchSheet } from "@/lib/db/sheets"; import { d20Expression, rollExpression, type Advantage } from "@/lib/dice"; import { rollCharacterD20 } from "@/lib/dm/character-roll"; -import { publishPersisted, publishWithSeq } from "@/lib/events"; +import { recordRoll } from "@/lib/dm/roll-record"; +import { publishPersisted } from "@/lib/events"; import { healthState } from "@/lib/bestiary/health"; import { enemyAcWithEffects } from "@/lib/dm/ac-effects"; import { coverFor } from "@/lib/dm/attack-spatial"; @@ -76,18 +88,30 @@ import { inDirectSunlight } from "@/lib/dm/sunlight"; import { characterSwims, underwaterOpportunity } from "@/lib/dm/underwater"; // A turn for the swing's rolls and audit rows, closed as soon as it is used -// so nothing waits on it. -export function withOpportunityTurn(campaignId: string, run: (turn: DmTurn) => T): T { +// so nothing waits on it. `rolled` is handed the rolls the turn was left +// with (the save a creature's rider forces, an answering spell's damage), +// for the strike's line. +export function withOpportunityTurn(campaignId: string, run: (turn: DmTurn) => T, rolled?: string[]): T { const turn = openStandInTurn(campaignId); try { return run(turn); } finally { + // Closing saves the turn, which reads back the rolls written to its row. closeStandInTurn(turn); + rolled?.push(...turn.rollIds); } } -function publishRoll(campaignId: string, roll: ReturnType) { - publishWithSeq(campaignId, allocateSeq(campaignId), "roll_result", { roll, source: "digital" }); +// The cards a strike's line carries: its attack and damage, then what the +// blow went on to roll on its short turn. A line reaches every seat, so it +// lists only the rolls every seat is sent, as a person's record does +// (persons-record.ts): one behind the screen stays with the seats that may +// read it. +export function strikeCards(own: readonly string[], onTurn: readonly string[] = []): string[] { + return [...new Set([...own, ...onTurn])].filter((id) => { + const visibility = getRoll(id)?.visibility; + return visibility === "public" || visibility === "blind"; + }); } // The light between a reactor and the creature leaving: null off the board. @@ -185,7 +209,7 @@ export function pcOpportunitySwing(input: { // Divine Smite's slot, when the player took it on the card // (opportunity-ask.ts): paid only on a hit. smiteSlot?: number; -}): { note: string; dropped: boolean } { +}): { note: string; dropped: boolean; rollIds: string[] } { const { campaign, encounter, sheet, enemy, resolved } = input; const natural = input.natural ?? null; const kind = natural ? "natural" : "weapon"; @@ -277,7 +301,9 @@ export function pcOpportunitySwing(input: { advantage, attack: { ac: targetAc, critRange: riders.critRange ?? 20, melee: true }, }); - const hitRoll = insertRoll({ + // Their own dice, through the door above: entered at the table, they are + // on record and sent as theirs. + const hitRoll = recordRoll({ campaignId: campaign.id, characterId: sheet.id, requestedBy: "dm", @@ -286,8 +312,8 @@ export function pcOpportunitySwing(input: { advantage, result: hitOutcome, attacker: { kind: "sheet", id: sheet.id, name: sheet.name }, + home: "line", }); - publishRoll(campaign.id, hitRoll); const judged = adjudicateHit(hitOutcome.total, hitOutcome.crit, targetAc, { natural: hitOutcome.natural, critRange: riders.critRange, @@ -323,9 +349,12 @@ export function pcOpportunitySwing(input: { return { note: `${sheet.name} swings at ${enemy.displayName} as it breaks away and misses (${hitOutcome.total} vs AC ${targetAc}${parry ? `; ${parry.note}` : ""}).`, dropped: false, + rollIds: strikeCards([hitRoll.id]), }; } const crit = adjudicated.crit || context.autoCrit; + // What the hit goes on to roll on its short turns, for the line. + const onTurn: string[] = []; // A natural 20's magic weapon dice (a Vicious Weapon's 2d6). const critGear = hitOutcome.crit === "nat20" ? gearCritRiders(profile, enemy.stats.type) : null; if (critGear?.suffix) { @@ -343,7 +372,7 @@ export function pcOpportunitySwing(input: { const paid = withOpportunityTurn(campaign.id, (turn) => { const sheets = listSheets(campaign.id); return spendOnHit(campaign, turn.id, spends, sheets, new Map(sheets.map((entry) => [entry.id, entry]))); - }); + }, onTurn); notes.push(...paid.notes); if (paid.suffix) { profile = { ...profile, damageExpression: `${profile.damageExpression}${paid.suffix}` }; @@ -376,17 +405,17 @@ export function pcOpportunitySwing(input: { ...(rerollBelow ? { throwIt: () => rollExpression(damageExpression, undefined, { rerollBelow, purpose: damageTag }) } : {}), }); const dealt = Math.max(0, damageOutcome.total); - return withOpportunityTurn(campaign.id, (turn) => { - const damageRoll = insertRoll({ - campaignId: campaign.id, - characterId: sheet.id, - requestedBy: "dm", - kind: "damage", - detail: rollAgainst(`${profile.weapon} (opportunity attack)`, enemy.displayName), - result: damageOutcome, - attacker: { kind: "sheet", id: sheet.id, name: sheet.name }, - }); - publishRoll(campaign.id, damageRoll); + const damageRoll = recordRoll({ + campaignId: campaign.id, + characterId: sheet.id, + requestedBy: "dm", + kind: "damage", + detail: rollAgainst(`${profile.weapon} (opportunity attack)`, enemy.displayName), + result: damageOutcome, + attacker: { kind: "sheet", id: sheet.id, name: sheet.name }, + home: "line", + }); + const swing = withOpportunityTurn(campaign.id, (turn) => { const sheets = listSheets(campaign.id); const applied = landBlow({ campaign, @@ -448,7 +477,8 @@ export function pcOpportunitySwing(input: { }`, dropped, }; - }); + }, onTurn); + return { ...swing, rollIds: strikeCards([hitRoll.id, damageRoll.id], onTurn) }; } // What the swing uses up: the attacker's hiding, Invisibility and Sanctuary diff --git a/src/lib/dm/opportunity.ts b/src/lib/dm/opportunity.ts index 2bc6ee2c0f..ddd4e9d301 100644 --- a/src/lib/dm/opportunity.ts +++ b/src/lib/dm/opportunity.ts @@ -15,7 +15,7 @@ import { entersReachAt, leavesReachAt, movesWithinReachAt } from "@/lib/dm/oppor import { getBattleMapForEncounter, getTokenByRef } from "@/lib/db/battle-maps"; import { getSheetById, listSheets, patchSheet } from "@/lib/db/sheets"; -import { insertRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { rollAgainst } from "@/lib/roll-labels"; import { enemyFootprint } from "@/lib/battlemap/footprint"; import { characterFootprint } from "@/lib/dm/board-reach"; @@ -56,7 +56,7 @@ import { opportunityReactionKey } from "@/lib/srd/authored-effects-more"; import { conditionsOf } from "@/lib/dm/vitals-logic"; import { attackSenses, characterSenses, enemySenses, fearAsRolled, lightOnAttack, sensesReaching } from "@/lib/dm/attack-light"; import { charmedBy, opportunityWeapon } from "@/lib/dm/enemy-profile"; -import { enemyOpportunityRiders, opportunitySight, opportunitySmiteSlot, pcOpportunitySwing, withOpportunityTurn } from "@/lib/dm/opportunity-strike"; +import { enemyOpportunityRiders, opportunitySight, opportunitySmiteSlot, pcOpportunitySwing, strikeCards, withOpportunityTurn } from "@/lib/dm/opportunity-strike"; import { holdsFeat } from "@/lib/srd/feat-effects"; import { warCasterOpportunity } from "@/lib/dm/ar-wbf-feat-warcaster"; import { martialArtsApplies } from "@/lib/dm/pc-attack-options"; @@ -89,7 +89,8 @@ import type { CharacterSheet } from "@/lib/schemas/sheet"; // Resolved here rather than through handleEnemyAttack because the trigger // fires from the player's own token-move route, which has no DM turn to // hang tool calls on. The outcome posts as a table note, exactly like the -// death saves the server rolls between turns. +// death saves the server rolls between turns, and like theirs the note is +// the home of the strike's cards (opportunity-strike.ts strikeCards). // // The move is walked square by square: what provokes is LEAVING a reach, // wherever the move began and ended, so a runner who passes a guard in a @@ -97,7 +98,7 @@ import type { CharacterSheet } from "@/lib/schemas/sheet"; type XY = { x: number; y: number }; -function tableNote(campaign: Campaign, content: string) { +function tableNote(campaign: Campaign, content: string, rollIds: readonly string[] = []) { const seq = allocateSeq(campaign.id); const message = insertCampaignMessage({ campaignId: campaign.id, @@ -105,6 +106,7 @@ function tableNote(campaign: Campaign, content: string) { authorType: "system", glyph: "cue-battle", content, + rollIds, }); publishWithSeq(campaign.id, seq, "message_added", { message }); } @@ -186,6 +188,8 @@ export function resolveOpportunityAttacks( } const steps = [from, ...(path?.length ? path : [to])]; const notes: string[] = []; + // The cards of each strike's line, by the line's place in `notes`. + const cards = new Map(); let downed = false; let downedAt: XY | undefined; // Only the other side reacts (src/lib/dm/combatant.ts): an enemy does not @@ -345,7 +349,7 @@ export function resolveOpportunityAttacks( purpose: { roller: "enemy", kind: "attack", who: enemy.displayName }, }); spendEnemyRiders(enemy, own.riders); - const hitRoll = insertRoll({ + const hitRoll = recordRoll({ campaignId: campaign.id, characterId: null, requestedBy: "dm", @@ -354,19 +358,20 @@ export function resolveOpportunityAttacks( advantage, result: hitOutcome, attacker: { kind: "enemy", id: enemy.id, name: enemy.displayName }, - }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { - roll: hitRoll, - source: "digital", + home: "line", + // Thrown here, on the server's dice. + landing: null, }); // Mirror Image: a duplicate may take the attack instead (spell-defenses.ts). const decoy = opportunityDecoy(campaign.id, sheet.id, hitOutcome.total, enemy); if (decoy) { + cards.set(notes.length, strikeCards([hitRoll.id])); notes.push(`${shownName(encounter.id, enemy.id, enemy.displayName)} takes an opportunity attack as ${sheet.name} pulls away: ${decoy}.`); continue; } const adjudicated = adjudicateHit(hitOutcome.total, hitOutcome.crit, targetAc); if (!adjudicated.hit) { + cards.set(notes.length, strikeCards([hitRoll.id])); notes.push( `${shownName(encounter.id, enemy.id, enemy.displayName)} takes an opportunity attack as ${sheet.name} pulls away and misses (${hitOutcome.total} vs AC ${targetAc}).`, ); @@ -385,7 +390,7 @@ export function resolveOpportunityAttacks( undefined, { purpose: { roller: "enemy", kind: "damage", who: enemy.displayName } }, ); - const damageRoll = insertRoll({ + const damageRoll = recordRoll({ campaignId: campaign.id, characterId: null, requestedBy: "dm", @@ -393,11 +398,12 @@ export function resolveOpportunityAttacks( detail: rollAgainst(`${attack.name} (opportunity attack)`, sheet.name), result: damageOutcome, attacker: { kind: "enemy", id: enemy.id, name: enemy.displayName }, + home: "line", + // Thrown here, on the server's dice. + landing: null, }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { - roll: damageRoll, - source: "digital", - }); + // What the blow goes on to roll on its short turn, for the line. + const onTurn: string[] = []; // Kept so a reaction can answer the hit (src/lib/dm/last-hit.ts). const hitLog = openLastHit(campaign.id, sheet.id); @@ -453,7 +459,7 @@ export function resolveOpportunityAttacks( const laid = unridden && ridden ? (rider?.swallowed ? swallowMark(campaign.id, unridden, ridden, sheet.id, grips, own) : riderMarkOf(unridden, ridden, own)) : null; const answered = measureRetort(enemy.id, () => spellRetort(campaign, turn, enemy, sheet.id, true, reach <= 1, hitSheets, hitSheetsById, sheet.tempHp ?? 0, waits), (out) => out.by, (out) => out.shares); return { landed: applied, onHit: rider, answered, psychicBack, laid, waits }; - }); + }, onTurn); const updated = getSheetById(sheet.id); // A critical's normal figure, for Sentinel at Death's Door (last-hit.ts). const normalRoll = crit @@ -480,6 +486,7 @@ export function resolveOpportunityAttacks( } const byType = Array.isArray(landed.damageByType) ? ` (${(landed.damageByType as string[]).join(", ")})` : typeof landed.resistance === "string" ? ` (${landed.resistance})` : ""; const riderNote = `${Array.isArray(onHit?.riderCondition) ? ` ${sheet.name} is ${(onHit.riderCondition as string[]).join(" and ")}.` : ""}${[...wards.notes, ...warded.notes].map((line) => ` ${line}.`).join("")}`; + cards.set(notes.length, strikeCards([hitRoll.id, damageRoll.id], onTurn)); notes.push( `${shownName(encounter.id, enemy.id, enemy.displayName)} takes an opportunity attack as ${sheet.name} pulls away: ${ crit ? "a critical hit for " : "hit for " @@ -490,9 +497,7 @@ export function resolveOpportunityAttacks( } } - for (const note of notes) { - tableNote(campaign, note); - } + notes.forEach((note, index) => tableNote(campaign, note, cards.get(index))); // A pet walking with them provokes too, from a creature whose reaction is // still in hand (opportunity-pets.ts). if (!downed) { @@ -580,6 +585,8 @@ export function resolvePcOpportunityWalk( } const steps = [from, ...(path?.length ? path : [to])]; const notes: string[] = []; + // The cards of each swing's line, by the line's place in `notes`. + const cards = new Map(); // The walker's size: an ogre leaves a reach when its last square does. const moverFootprint = enemyFootprint(getFoe(enemyId)); const moverKind = getEnemy(enemyId) ? "enemy" : "sheet"; @@ -732,7 +739,7 @@ export function resolvePcOpportunityWalk( // The swing itself, with everything their attack carries // (src/lib/dm/opportunity-strike.ts). - const { note, dropped } = pcOpportunitySwing({ + const { note, dropped, rollIds } = pcOpportunitySwing({ campaign, encounter, sheet, @@ -744,6 +751,7 @@ export function resolvePcOpportunityWalk( moverAt, ...(answer?.smite && smiteSlot ? { smiteSlot } : {}), }); + cards.set(notes.length, rollIds); notes.push(answer?.timedOut ? timedOutNote(sheet.name, note) : note); stops(); if (dropped) { @@ -751,9 +759,7 @@ export function resolvePcOpportunityWalk( } } - for (const note of notes) { - tableNote(campaign, note); - } + notes.forEach((note, index) => tableNote(campaign, note, cards.get(index))); // A creature the party dominates walking away from its old allies: they // strike it as it goes (opportunity-sides.ts posts its own lines), over // the squares it walked. diff --git a/src/lib/dm/persons-record.ts b/src/lib/dm/persons-record.ts index d7b2b6209f..0a6c245017 100644 --- a/src/lib/dm/persons-record.ts +++ b/src/lib/dm/persons-record.ts @@ -2,7 +2,7 @@ import { allocateSeq, campaignSeats, type Campaign } from "@/lib/db/campaigns"; import { getBattleMapForEncounter, listHiddenRefIds } from "@/lib/db/battle-maps"; import type { DmTurn } from "@/lib/db/dm-turns"; import { getActiveEncounter, listEnemies, type EnemyStatus } from "@/lib/db/encounters"; -import { insertCampaignMessage } from "@/lib/db/messages"; +import { insertCampaignMessage, lineCarriesRoll } from "@/lib/db/messages"; import { hasHumanDm } from "@/lib/dm/viewer"; import { firstStoredAfter, getRoll } from "@/lib/db/rolls"; import { listAuditForTurn } from "@/lib/db/sheet-audit"; @@ -63,7 +63,9 @@ function foeChanges(start: RecordStart): FoeChange[] { // `rollIds` are the call's rolls the turn does not list (a player's dice // entered for a parked roll); `changes` false leaves the sentence to a path -// that posts its own (the server playing the enemies says each blow). +// that posts its own (the server playing the enemies says each blow). One of +// them that a line of its own already carries (a death save, an opportunity +// swing: roll-record.ts `home: "line"`) stays on that line alone. export function postPersonsRecord( campaign: Campaign, turn: DmTurn, @@ -86,7 +88,7 @@ export function postPersonsRecord( const onTurn = turn.rollIds.slice(start.rolls); const listed = [...onTurn]; for (const id of options.rollIds ?? []) { - if (!listed.includes(id)) { + if (!listed.includes(id) && !lineCarriesRoll(campaign.id, id)) { const next = firstStoredAfter(id, onTurn); listed.splice(next ? listed.indexOf(next) : listed.length, 0, id); } diff --git a/src/lib/dm/regeneration-ring.ts b/src/lib/dm/regeneration-ring.ts index 88562f2b92..a25dc81053 100644 --- a/src/lib/dm/regeneration-ring.ts +++ b/src/lib/dm/regeneration-ring.ts @@ -11,13 +11,11 @@ // stone orbiting is "an object that is being worn", and it is attuned. import { getCampaignById, type Campaign } from "@/lib/db/campaigns"; -import { allocateSeq } from "@/lib/db/campaigns"; -import { insertRoll } from "@/lib/db/rolls"; +import { recordRoll } from "@/lib/dm/roll-record"; import { getSheetById, listSheets } from "@/lib/db/sheets"; import { rollExpression } from "@/lib/dice"; import { effectiveMaxHp } from "@/lib/dm/condition-logic"; import { regainHitPoints } from "@/lib/dm/regain"; -import { publishWithSeq } from "@/lib/events"; import { wearsWorkingItem } from "@/lib/srd/magic-items"; import type { CharacterSheet } from "@/lib/schemas/sheet"; @@ -50,15 +48,18 @@ function ringHeals(campaign: Campaign, sheet: CharacterSheet, marks: number) { return; } const rolled = rollExpression(`${marks}d6`); - const roll = insertRoll({ + // On the turn of the call that moved the clock; the clock moved outside + // one holds no turn. + recordRoll({ campaignId: campaign.id, characterId: sheet.id, requestedBy: "dm", kind: "custom", detail: `${REGENERATION_RING}: ${marks * 10} minutes`, result: rolled, + // Thrown here, on the server's dice. + landing: null, }); - publishWithSeq(campaign.id, allocateSeq(campaign.id), "roll_result", { roll, source: "digital" }); regainHitPoints(campaign, null, sheet, rolled.total, REGENERATION_RING); } diff --git a/src/lib/dm/stabilize.ts b/src/lib/dm/stabilize.ts index 37b7ffbe46..7465a5a1ba 100644 --- a/src/lib/dm/stabilize.ts +++ b/src/lib/dm/stabilize.ts @@ -321,7 +321,7 @@ export function handleStabilize( const triage = triageWait(campaign, turn ?? null, healer, sheet, { conditions: sheet.conditions, conditionMeta: sheet.conditionMeta }); // Field Surgeon: a minute, not 1d4 hours (genre-a-cyberpunk-defenses.ts). const minute = triage ? null : fieldSurgeonWait(healer, sheet); - const wait = triage ?? minute ?? rollStableTimer(campaign, sheet); + const wait = triage ?? minute ?? rollStableTimer(campaign, sheet, { turnId }); const laid = rites ? ritesWard(wait.conditions, wait.conditionMeta) : wait; // Stable resets both counts (SRD 5.1, Stabilizing a Creature). const nextTrack = stableDeathTrack(); From 0188cec77989a8867e5ed1f9ef68878ac5bef33a Mon Sep 17 00:00:00 2001 From: Smoebo Date: Sat, 21 Nov 2026 10:32:51 -0500 Subject: [PATCH 2/2] A trap's, a fall's and a poison's dice name their source on the roll card, where they read as the roll of the character they landed on, and every attack or damage roll says who or what made it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ruling 2 of issue #915: a roll nobody at the table made names its source, and the character it lands on is its target. A roll's attacker gains a fourth kind, "hazard", with no id, a name, and a field that says what it is: a fall, the GM's own dice for harm nothing names, a trap, an item, the effect of a spell or feature, or a hazard by the words the GM gave it. A hit's record already had that kind for a fall (last-hit.ts) and now carries the field too. Nothing reads what a source is from its name. A source that was given a name shows it in front of its rolls; a fall and the GM's own dice are worded there by the field, in the table's language. Every source is built in one module (src/lib/roll-sources.ts), and a test holds that no other file writes one out. A site that knows what its harm is hands that value on, so it is not read back from words further in: apply_hazard builds its source once and passes it to the save it asks of a character and to the trap it springs on a creature, and a trap's darts and its poison name the same trap. Where one site writes both a roll and the hit's record, the record is handed the roll's source; apply_damage's record is built by the same builder from the same arguments as its dice. A creature's save spell stays on record as that spell's effect, as it was, while its roll names the creature. A source's roll is put on record by five helpers in roll-card.ts (sourceDamage, sourceDamageThrown, sourceAttack, castDamage, castersDamage), which word it in one place from what was thrown and on whom, so the source goes in front of the card and is not said again: "Spiked Pit · Damage (2d10 piercing on Aria)", "The fall · Damage (30 ft, 3d6 bludgeoning on Aria)". Dice the GM sends for harm name the words given for it: "falling rubble · Damage (2d6 bludgeoning on Aria)", and name a creature they land on as the table may read it. The roll tools' free text keeps the words the GM typed. The type of an attack or damage roll no longer allows a missing attacker (insertRoll, recordRoll, rollCard), so the type checker listed every site: 47 in 36 files. A character's own feature or spell names the character, which reads as before; three of those cards no longer say the character's name twice. A roll card's own damage dice and the roll tools' free text name the character they were asked of, else the GM. Later damage of a spell is its caster's roll, a creature's as well as a character's, and the spell's own once neither is at the table. The Grasping Arrow's brambles are the archer's roll. The dice stage tells sources apart by what they are and their name, so a trap's damage joins that trap's attack and no other's. The dice-site sweep's "roller" check also holds every sourced roll it reaches: the source says what it is, is not said a second time, and the roll names the character it lands on; and a hazard's own row may not name that character as the roller. The 34 runs listed as failing "roller" pass and are struck from the ledger's rows: 35 are left, all "home", the requests family's. Co-Authored-By: Claude Fable 5.2 --- scripts/roll-record-sites.json | 36 +-- scripts/test-enforce-ai-gates.mjs | 19 ++ scripts/test-enforce-damage-cards.mjs | 24 +- scripts/test-enforce-roll-attacker.mjs | 261 +++++++++++++++++- ...-enforce-sweep-clauses-martial-fighter.mjs | 4 + scripts/test-enforce-sweep-dice-sites.mjs | 31 ++- scripts/test-roll-labels.mjs | 92 ++++++ scripts/test-roll-stage.mjs | 10 + src/lib/db/core.ts | 5 +- src/lib/db/rolls.ts | 31 ++- src/lib/dice/roll-stage-logic.ts | 8 +- src/lib/dm/ai-gate.ts | 22 +- src/lib/dm/aoe-damage.ts | 12 +- src/lib/dm/ar-ws-charm-miss.ts | 5 +- src/lib/dm/arcane-triggered.ts | 6 +- src/lib/dm/ask.ts | 3 +- src/lib/dm/attack-onhit.ts | 17 +- src/lib/dm/authored-hooks.ts | 4 +- src/lib/dm/authored-mote.ts | 4 +- src/lib/dm/authored-reactions-more.ts | 4 +- src/lib/dm/cast-at-player.ts | 36 ++- src/lib/dm/caster-features.ts | 6 +- src/lib/dm/consumables.ts | 8 +- src/lib/dm/encounter-summary.ts | 4 +- src/lib/dm/enemy-fall.ts | 18 +- src/lib/dm/enemy-trap.ts | 17 +- src/lib/dm/genre-a-cyberpunk-defenses.ts | 4 +- src/lib/dm/genre-a-cyberpunk-spends.ts | 4 +- src/lib/dm/genre-a-horror-casts.ts | 4 +- src/lib/dm/genre-b-steampunk-ends.ts | 4 +- src/lib/dm/genre-cc-a-turns.ts | 4 +- src/lib/dm/hazard-tools.ts | 18 +- src/lib/dm/held-call.ts | 8 +- src/lib/dm/improvise.ts | 4 +- src/lib/dm/invoke-roll.ts | 8 +- src/lib/dm/last-hit.ts | 24 +- src/lib/dm/mt-fb-arrow-riders.ts | 9 +- src/lib/dm/mutations.ts | 5 +- src/lib/dm/object-damage.ts | 16 +- src/lib/dm/pending-roll-land.ts | 18 +- src/lib/dm/pet-save.ts | 11 +- src/lib/dm/roll-card.ts | 142 +++++++++- src/lib/dm/spell-retort.ts | 4 +- src/lib/dm/spell-self.ts | 4 +- src/lib/dm/spell-turn-end.ts | 14 +- src/lib/dm/spirit-projection.ts | 4 +- src/lib/dm/trap-escape.ts | 6 +- src/lib/dm/trap-run.ts | 14 +- src/lib/dm/zone-quake.ts | 10 +- src/lib/i18n/fr.json | 1 + src/lib/roll-labels.ts | 61 +++- src/lib/roll-sources.ts | 85 ++++++ 52 files changed, 952 insertions(+), 221 deletions(-) create mode 100644 src/lib/roll-sources.ts diff --git a/scripts/roll-record-sites.json b/scripts/roll-record-sites.json index e340fc827c..1cb539719c 100644 --- a/scripts/roll-record-sites.json +++ b/scripts/roll-record-sites.json @@ -13,7 +13,7 @@ "lib/dm/roll-card.ts": { "send": 1, "family": "requests" }, "lib/dm/turn.ts": { "join": 1, "family": "requests" } }, - "_rows": "The rows of scripts/test-enforce-sweep-dice-sites.mjs whose call stores a roll that fails a check of its record, and which checks: home (the roll is on no turn and no line, so the chronicle never shows its card), sent (dice the seat entered are on record and sent as the server's, so the stage throws them again), roller (an attack or damage roll names nobody, so it reads as the roll of the character it lands on). Each is a site in `sites` above that has not moved onto recordRoll yet. A row is struck off when it passes; `ODM_SWEEP_ROWS=print node scripts/test-enforce-sweep-dice-sites.mjs` prints the list as it stands.", + "_rows": "The rows of scripts/test-enforce-sweep-dice-sites.mjs whose call stores a roll that fails a check of its record, and which checks: home (the roll is on no turn and no line, so the chronicle never shows its card), sent (dice the seat entered are on record and sent as the server's, so the stage throws them again), roller (an attack or damage roll names nobody, so it reads as the roll of the character it lands on; or a roll nobody made names a source that does not say what it is, says that source a second time, or does not name the character it lands on). Each is a site in `sites` above that has not moved onto recordRoll yet. A row is struck off when it passes; `ODM_SWEEP_ROWS=print node scripts/test-enforce-sweep-dice-sites.mjs` prints the list as it stands.", "rows": { "request_roll.skill_check.public@console": ["home"], "request_roll.skill_check.blind@console": ["home"], @@ -48,40 +48,6 @@ "request_roll.save.in_fight@console": ["home"], "pc_attack.weapon@console": ["home"], "pc_attack.spell@console": ["home"], - "cast_at_player.hazard@console": ["roller"], - "cast_at_player.hazard@ai": ["roller"], - "apply_hazard.falling@console": ["roller"], - "apply_hazard.falling@ai": ["roller"], - "apply_hazard.trap@console": ["roller"], - "apply_hazard.trap@ai": ["roller"], - "apply_hazard.generic@console": ["roller"], - "apply_hazard.generic@ai": ["roller"], - "apply_hazard.trap.Hunting Trap@console": ["roller"], - "apply_hazard.trap.Hunting Trap@ai": ["roller"], - "apply_hazard.trap.Collapsing Roof@console": ["roller"], - "apply_hazard.trap.Collapsing Roof@ai": ["roller"], - "apply_hazard.trap.Fire-Breathing Statue@console": ["roller"], - "apply_hazard.trap.Fire-Breathing Statue@ai": ["roller"], - "apply_hazard.trap.Simple Pit@console": ["roller"], - "apply_hazard.trap.Simple Pit@ai": ["roller"], - "apply_hazard.trap.Hidden Pit@console": ["roller"], - "apply_hazard.trap.Hidden Pit@ai": ["roller"], - "apply_hazard.trap.Locking Pit@console": ["roller"], - "apply_hazard.trap.Locking Pit@ai": ["roller"], - "apply_hazard.trap.Spiked Pit@console": ["roller"], - "apply_hazard.trap.Spiked Pit@ai": ["roller"], - "apply_hazard.trap.Spiked Pit (poisoned)@console": ["roller"], - "apply_hazard.trap.Spiked Pit (poisoned)@ai": ["roller"], - "apply_hazard.trap.Poison Darts@console": ["roller"], - "apply_hazard.trap.Poison Darts@ai": ["roller"], - "apply_hazard.trap.Poison Needle@console": ["roller"], - "apply_hazard.trap.Poison Needle@ai": ["roller"], - "apply_hazard.trap.Sphere of Annihilation@console": ["roller"], - "apply_hazard.trap.Sphere of Annihilation@ai": ["roller"], - "apply_hazard.trap.Rolling Sphere@console": ["roller"], - "apply_hazard.trap.Rolling Sphere@ai": ["roller"], - "concentration.damage@console": ["roller"], - "concentration.damage@ai": ["roller"], "start_encounter.plain@console": ["home"], "start_encounter.enemies_ambush@console": ["home"] } diff --git a/scripts/test-enforce-ai-gates.mjs b/scripts/test-enforce-ai-gates.mjs index ef8db686e9..c1428069e2 100644 --- a/scripts/test-enforce-ai-gates.mjs +++ b/scripts/test-enforce-ai-gates.mjs @@ -61,6 +61,25 @@ await test("Dice the AI sends are rolled by the server: 2d6 of 3 and 4 is 7.", a assert.equal(hp(), 33); }); +await test("Dice the AI sends for harm are on record as the roll of the words it gave for the harm, with the character as its target; healing dice name no roller.", async () => { + await stage(); + const { listRecentRolls } = await import("../src/lib/db/rolls.ts"); + const call = aiTurn(); + const harm = await call("apply_damage", { characterId: hero.id, dice: "2d6", type: "bludgeoning", reason: "falling rubble" }); + assert.equal(harm.ok, true, harm.error); + const [rubble] = listRecentRolls(world.campaignId, 1); + assert.equal(rubble.kind, "damage"); + assert.deepEqual(rubble.attacker, { kind: "hazard", id: null, name: "falling rubble", hazard: "named" }); + assert.equal(rubble.characterId, hero.id); + assert.equal(rubble.detail, `2d6 bludgeoning on ${world.sheet(hero.id).name}`); + // Healing is no attack and no damage: it names no roller, as before. + const mend = await call("heal", { characterId: hero.id, dice: "2d4+2" }); + assert.equal(mend.ok, true, mend.error); + const [healed] = listRecentRolls(world.campaignId, 1); + assert.equal(healed.kind, "custom"); + assert.equal(healed.attacker, null); +}); + await test("A damage total the server rolled this turn is accepted once, and only once.", async () => { await stage(); const call = aiTurn(); diff --git a/scripts/test-enforce-damage-cards.mjs b/scripts/test-enforce-damage-cards.mjs index b3b65cc46c..b3afa483b1 100644 --- a/scripts/test-enforce-damage-cards.mjs +++ b/scripts/test-enforce-damage-cards.mjs @@ -161,7 +161,7 @@ await test("Bestow Curse: the extra necrotic when the curser's spell harms the c // ---- costs paid in the caster's own hit points ---- -await test("Overchannel's second use: the necrotic it costs is the wizard's card, with no attacker.", async () => { +await test("Overchannel's second use: the necrotic it costs is the wizard's own roll.", async () => { const { world, sheets: [wizard], enemies: [goblin] } = await table([caster("wizard", "int", ["Fireball"], [], 14)]); world.patch(wizard.id, { features: [...world.sheet(wizard.id).features, { name: "Overchannel", source: "test" }] }); world.dice(1); @@ -175,12 +175,12 @@ await test("Overchannel's second use: the necrotic it costs is the wizard's card world.clearDice(); const cost = cardsSince(world, before).find((card) => card.detail === "Overchannel"); assert.ok(cost, "no Overchannel card"); - assert.equal(cost.attacker, null); + assert.deepEqual(cost.attacker, { kind: "sheet", id: wizard.id, name: world.sheet(wizard.id).name }); assert.equal(cost.characterId, wizard.id); assert.equal(cost.total, 6); }); -await test("Contact Other Plane: the psychic backlash of a failed save is the caster's card, with no attacker.", async () => { +await test("Contact Other Plane: the psychic backlash of a failed save is the caster's own roll.", async () => { const world = await openWorld(); const wizard = world.addHero(caster("wizard", "int", ["Contact Other Plane"], [], 9)); const before = snapshot(world); @@ -188,40 +188,44 @@ await test("Contact Other Plane: the psychic backlash of a failed save is the ca const cast = await world.invoke("use_spell_slot", { characterId: wizard.id, spell: "Contact Other Plane", level: 5 }); world.clearDice(); assert.equal(cast.ok, true, cast.error); - expectCard(world, before, { attacker: null, detail: "Contact Other Plane", characterId: wizard.id, total: 6 }); + expectCard(world, before, { attacker: { kind: "sheet", id: wizard.id, name: world.sheet(wizard.id).name }, detail: "Contact Other Plane", characterId: wizard.id, total: 6 }); world.close(); }); // ---- hazards and objects ---- +// A roll nobody at the table made names its source (issue 915, ruling 2): the +// source is its attacker, a "hazard" with no id and a field that says what it +// is, and the character it lands on is its target. Named in front of the +// card, the source is not said again in the detail. -await test("A character's fall is a card with no attacker that names who fell, as an enemy's fall is.", async () => { +await test("A character's fall is the fall's roll, and names who fell as its target, as an enemy's fall does.", async () => { const { world, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); const before = snapshot(world); world.dice(2, 2, 2); const out = await world.invoke("apply_hazard", { type: "falling", characterIds: [fighter.id], feet: 30 }); world.clearDice(); assert.equal(out.ok, true, out.error); - expectCard(world, before, { attacker: null, detail: "30 ft fall (3d6 bludgeoning) on Aria", characterId: fighter.id, total: 6 }); + expectCard(world, before, { attacker: { kind: "hazard", id: null, name: "the fall", hazard: "fall" }, detail: "30 ft, 3d6 bludgeoning on Aria", characterId: fighter.id, total: 6 }); }); -await test("A potion of poison's damage is a card about the drinker, with no attacker.", async () => { +await test("A potion of poison's damage is the potion's roll, with the drinker as its target.", async () => { const { world, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria", equipment: [...FIGHTER.equipment, { name: "Potion of Poison", qty: 1 }] }]); const before = snapshot(world); world.dice(2, 2, 2, 20); const out = await world.invoke("use_item", { characterId: fighter.id, item: "Potion of Poison" }); world.clearDice(); assert.equal(out.ok, true, out.error); - expectCard(world, before, { attacker: null, detail: "Potion of Poison: it was poison", characterId: fighter.id, total: 6 }); + expectCard(world, before, { attacker: { kind: "hazard", id: null, name: "Potion of Poison", hazard: "item" }, detail: "3d6 poison on Aria", characterId: fighter.id, total: 6 }); }); -await test("Dice of harm no character dealt to an object are a card with no attacker that names the object.", async () => { +await test("Dice of harm no character dealt to an object are the GM's roll, and name the object.", async () => { const { world } = await table([FIGHTER]); const before = snapshot(world); world.dice(3, 3); const out = await world.invoke("damage_object", { name: "the oak door", material: "wood", size: "medium", damage: "2d6", damageType: "fire" }); world.clearDice(); assert.equal(out.ok, true, out.error); - expectCard(world, before, { attacker: null, detail: "fire on the oak door", characterId: null, total: 6 }); + expectCard(world, before, { attacker: { kind: "hazard", id: null, name: "the GM", hazard: "gm" }, detail: "2d6 fire on the oak door", characterId: null, total: 6 }); }); // ---- the rest of the server's dice ---- diff --git a/scripts/test-enforce-roll-attacker.mjs b/scripts/test-enforce-roll-attacker.mjs index ab31fbc997..f1b5540c5a 100644 --- a/scripts/test-enforce-roll-attacker.mjs +++ b/scripts/test-enforce-roll-attacker.mjs @@ -344,13 +344,13 @@ await test("An enemy's opportunity attack is the enemy's, against the character expectRoll(damage, { kind: "damage", ...expected }); }); -await test("A falling enemy's damage has no attacker and names the creature it lands on.", async () => { +await test("A falling enemy's damage is the fall's roll and names the creature it lands on.", async () => { const [enemy] = await stage(aria); const before = snapshot(); const out = await mk.forced([3, 3, 3], () => world.invoke("damage_enemy", { enemyId: enemy.id, source: "hazard", fallFeet: 30 })); assert.equal(out.ok, true, out.error); const [fall] = combatSince(before); - expectRoll(fall, { kind: "damage", attacker: null, detail: `30 ft fall (3d6 bludgeoning) on ${enemy.displayName}`, characterId: null }); + expectRoll(fall, { kind: "damage", attacker: { kind: "hazard", id: null, name: "the fall", hazard: "fall" }, detail: `30 ft, 3d6 bludgeoning on ${enemy.displayName}`, characterId: null }); }); await test("The post-fight summary does not give a character the enemy's natural 20 against them.", async () => { @@ -381,7 +381,7 @@ await test("cast_at_enemy stores a public damage card of its dice: the caster's, assert.ok(onTurn(spells.campaignId, card.id), "the card is not on the turn's rolls"); }); -await test("cast_at_player stores a public damage card: the casting enemy's, or nobody's for a trap, against the character.", async () => { +await test("cast_at_player stores a public damage card: the casting enemy's, or its named source's, against the character.", async () => { const { world: spells, sheets: [fighter], enemies: [shaman] } = await table([{ ...FIGHTER, name: "Aria" }], 1, { spells: ["Sacred Flame"] }); const before = new Set(listRecentRolls(spells.campaignId, 200).map((roll) => roll.id)); spells.dice(1, 6); @@ -394,10 +394,263 @@ await test("cast_at_player stores a public damage card: the casting enemy's, or assert.equal(trap.ok, true, trap.error); const [spell, dart] = combatSince(before, spells.campaignId); expectRoll(spell, { kind: "damage", attacker: asEnemy(shaman), detail: "Sacred Flame vs Aria", characterId: fighter.id }); - expectRoll(dart, { kind: "damage", attacker: null, detail: "Poison dart trap vs Aria", characterId: fighter.id }); + expectRoll(dart, { kind: "damage", attacker: { kind: "hazard", id: null, name: "Poison dart trap", hazard: "named" }, detail: "1d4 poison on Aria", characterId: fighter.id }); assert.ok(onTurn(spells.campaignId, spell.id), "the card is not on the turn's rolls"); }); +// ---- rolls nobody at the table made (issue 915, ruling 2) ---- +// Each names its source as its attacker: a "hazard" with no id, a field that +// says what it is, and the name it was given (src/lib/roll-sources.ts). The +// character or creature it lands on is its target: characterId for a +// character, and the detail says who. Named in front of the card, a source is +// not named again in the detail. + +const source = (hazard, name) => ({ kind: "hazard", id: null, name, hazard }); +const idsOf = (campaignId) => new Set(listRecentRolls(campaignId, 200).map((roll) => roll.id)); + +await test("A trap's attacks and the damage of each are the trap's own rolls, against the character it springs on.", async () => { + const { world: traps, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(traps.campaignId); + // The first dart's d20: a hit whatever the armour. + traps.dice(20); + const out = await traps.invoke("apply_hazard", { type: "trap", trap: "Poison Darts", characterIds: [fighter.id] }); + traps.clearDice(); + assert.equal(out.ok, true, out.error); + const rolls = combatSince(before, traps.campaignId); + assert.ok(rolls.some((roll) => roll.kind === "attack") && rolls.some((roll) => roll.kind === "damage"), JSON.stringify(rolls.map((roll) => roll.detail))); + for (const roll of rolls) { + assert.deepEqual(roll.attacker, source("trap", "Poison Darts"), roll.detail); + assert.equal(roll.characterId, fighter.id, roll.detail); + assert.equal(roll.visibility, "public"); + assert.ok(!roll.detail.includes("Poison Darts"), `the trap is named twice: ${roll.detail}`); + assert.match(roll.detail, roll.kind === "attack" ? /^Attack vs Aria, AC \d+$/ : / on Aria$/); + } +}); + +await test("A pit's fall is the fall's roll and its spikes are the pit's, against the character who fell in.", async () => { + const { world: traps, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(traps.campaignId); + const out = await traps.invoke("apply_hazard", { type: "trap", trap: "Spiked Pit", characterIds: [fighter.id] }); + assert.equal(out.ok, true, out.error); + const [fall, spikes, ...more] = combatSince(before, traps.campaignId); + assert.deepEqual(more, []); + expectRoll(fall, { kind: "damage", attacker: source("fall", "the fall"), detail: "10 ft into Spiked Pit, 1d6 bludgeoning on Aria", characterId: fighter.id }); + expectRoll(spikes, { kind: "damage", attacker: source("trap", "Spiked Pit"), detail: "2d10 piercing on Aria", characterId: fighter.id }); +}); + +await test("A trap sprung on a creature is the trap's own roll too, against the creature.", async () => { + const { world: traps, enemies: [goblin] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(traps.campaignId); + traps.dice(20); + const out = await traps.invoke("apply_hazard", { type: "trap", trap: "Poison Darts", enemyIds: [goblin.id] }); + traps.clearDice(); + assert.equal(out.ok, true, out.error); + const rolls = combatSince(before, traps.campaignId); + assert.ok(rolls.some((roll) => roll.kind === "attack") && rolls.some((roll) => roll.kind === "damage"), JSON.stringify(rolls.map((roll) => roll.detail))); + for (const roll of rolls) { + assert.deepEqual(roll.attacker, source("trap", "Poison Darts"), roll.detail); + assert.equal(roll.characterId, null); + assert.ok(!roll.detail.includes("Poison Darts"), `the trap is named twice: ${roll.detail}`); + assert.ok(roll.detail.includes(goblin.displayName), `the creature is not named: ${roll.detail}`); + } +}); + +await test("A spell the GM casts at a character with no creature behind it is the spell's own roll, or its named source's.", async () => { + const { world: spells, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(spells.campaignId); + const bare = await spells.invoke("cast_at_player", { characterId: fighter.id, spell: "Burning Hands", saveAbility: "dex", dc: 12, damage: "3d6", damageType: "fire", halfOnSave: true }); + assert.equal(bare.ok, true, bare.error); + const named = await spells.invoke("cast_at_player", { characterId: fighter.id, spell: "Burning Hands", source: "a glyph on the door", saveAbility: "dex", dc: 12, damage: "3d6", damageType: "fire", halfOnSave: true }); + assert.equal(named.ok, true, named.error); + const [first, second] = combatSince(before, spells.campaignId); + expectRoll(first, { kind: "damage", attacker: source("effect", "Burning Hands"), detail: "3d6 fire on Aria", characterId: fighter.id }); + expectRoll(second, { kind: "damage", attacker: source("named", "a glyph on the door"), detail: "Burning Hands, 3d6 fire on Aria", characterId: fighter.id }); +}); + +await test("A damage roll the GM asks the server to throw for a character is that character's own.", async () => { + const { world: asks, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(asks.campaignId); + const own = await asks.invoke("request_roll", { characterId: fighter.id, kind: "damage", expression: "1d8+3", reason: "a thrown chair" }); + assert.equal(own.ok, true, own.error); + const [roll] = combatSince(before, asks.campaignId); + assert.ok(roll, "no damage roll was stored"); + assert.deepEqual(roll.attacker, { kind: "sheet", id: fighter.id, name: "Aria" }); + assert.equal(roll.characterId, fighter.id); +}); + +await test("The helpers that put a source's roll on record word it from what it threw and on whom, and do not say the source again.", async () => { + const { castDamage, castersDamage, sourceAttack, sourceDamage, sourceDamageThrown } = await import("../src/lib/dm/roll-card.ts"); + const { rollExpression } = await import("../src/lib/dice.ts"); + const { castSource, effectSource, fallSource, gmSource, itemSource, namedSource, trapSource } = await import("../src/lib/roll-sources.ts"); + const { world: words, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); + const campaign = words.campaign(); + const before = idsOf(words.campaignId); + const aria = { characterId: fighter.id, names: ["Aria"] }; + sourceDamage(campaign, null, trapSource("Scything Blade"), aria, { dice: "2d10", type: "slashing" }); + sourceDamage(campaign, null, fallSource(), aria, { note: "30 ft", dice: "3d6", type: "bludgeoning" }); + sourceDamage(campaign, null, itemSource("Potion of Poison"), aria, { note: "turn 2", dice: "2d6", type: "poison" }); + sourceAttack(campaign, null, trapSource("Scything Blade"), { characterId: fighter.id, name: "Aria" }, 16, "1d20+8"); + // A character's later damage is theirs while their sheet is there, a creature's is that creature's, and the spell's own once neither is left. + castersDamage(campaign, null, fighter, "Bestow Curse vs Goblin", "Bestow Curse", "Goblin", { dice: "1d8", type: "necrotic" }); + castersDamage(campaign, null, null, "Bestow Curse vs Goblin", "Bestow Curse", "Goblin", { dice: "1d8", type: "necrotic" }); + castersDamage(campaign, null, null, "Acid Arrow (second burn) vs Aria", "Acid Arrow", "Aria", { dice: "2d4", type: "acid" }, { id: "enemy-mage", displayName: "Mage" }); + // Dice a site threw itself are worded the same way. + sourceDamageThrown(campaign, null, gmSource(), { names: ["Goblin 1", "Goblin 2"] }, { dice: "2d6", type: "fire" }, rollExpression("2d6")); + // A cast with no creature behind it: the named source says its spell, the spell alone says what it throws, and so do the GM's own dice. + const on = { characterId: fighter.id, name: "Aria" }; + castDamage(campaign, null, castSource("a glyph on the door", "Burning Hands"), "Burning Hands", on, { dice: "3d6", type: "fire" }); + castDamage(campaign, null, castSource(undefined, "Burning Hands"), "Burning Hands", on, { dice: "3d6", type: "fire" }); + castDamage(campaign, null, castSource("a gout of flame", undefined), undefined, on, { dice: "2d6", type: "fire" }); + castDamage(campaign, null, castSource(" ", ""), undefined, on, { dice: "2d6", type: "fire" }); + // A trap that casts a spell says the spell too. + castDamage(campaign, null, castSource("a rune trap", "Fireball", true), "Fireball", on, { dice: "8d6", type: "fire" }); + const told = combatSince(before, words.campaignId).map((roll) => [roll.attacker.kind === "hazard" ? `${roll.attacker.hazard}:${roll.attacker.name}` : roll.attacker.name, roll.kind, roll.detail, roll.characterId]); + assert.deepEqual(told, [ + ["trap:Scything Blade", "damage", "2d10 slashing on Aria", fighter.id], + ["fall:the fall", "damage", "30 ft, 3d6 bludgeoning on Aria", fighter.id], + ["item:Potion of Poison", "damage", "turn 2, 2d6 poison on Aria", fighter.id], + ["trap:Scything Blade", "attack", "Attack vs Aria, AC 16", fighter.id], + ["Aria", "damage", "Bestow Curse vs Goblin", fighter.id], + ["effect:Bestow Curse", "damage", "1d8 necrotic on Goblin", null], + ["Mage", "damage", "Acid Arrow (second burn) vs Aria", null], + ["gm:the GM", "damage", "2d6 fire on Goblin 1, Goblin 2", null], + ["named:a glyph on the door", "damage", "Burning Hands, 3d6 fire on Aria", fighter.id], + ["effect:Burning Hands", "damage", "3d6 fire on Aria", fighter.id], + ["named:a gout of flame", "damage", "2d6 fire on Aria", fighter.id], + ["gm:the GM", "damage", "2d6 fire on Aria", fighter.id], + ["trap:a rune trap", "damage", "Fireball, 8d6 fire on Aria", fighter.id], + ]); + // A name is kept as it was given, and a source with no name is the GM's own dice. + assert.deepEqual(namedSource(" a gout of flame "), { kind: "hazard", id: null, name: "a gout of flame", hazard: "named" }); + assert.deepEqual(trapSource(""), gmSource()); + assert.deepEqual(effectSource(" "), gmSource()); +}); + +await test("A spell that hits with no roll and no creature behind it is the spell's own roll, and the hit's record names the same source.", async () => { + const { openHits } = await import("../src/lib/dm/last-hit.ts"); + const { world: spells, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(spells.campaignId); + const out = await spells.invoke("cast_at_player", { characterId: fighter.id, spell: "Magic Missile", damage: "3d4+3", damageType: "force" }); + assert.equal(out.ok, true, out.error); + const [roll] = combatSince(before, spells.campaignId); + expectRoll(roll, { kind: "damage", attacker: source("effect", "Magic Missile"), detail: "3d4+3 force on Aria", characterId: fighter.id }); + const record = openHits(spells.campaignId, fighter.id).at(-1); + assert.ok(record, "the missiles left no record of the hit"); + assert.deepEqual(record.attacker, roll.attacker); +}); + +await test("An improvised action's damage is the character's roll, and its card does not say their name twice.", async () => { + const { world: acts, sheets: [fighter], enemies: [goblin] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(acts.campaignId); + acts.say("dm", "A chandelier hangs low over the hall on a single rope."); + // The creature's d20, then the character's: the action carries. + acts.dice(1, 20); + const out = await acts.invoke("take_action", { characterId: fighter.id, action: "improvise", reason: "drops the chandelier", skill: "athletics", difficulty: "easy", scene: "the chandelier", targetEnemyId: goblin.id, damage: "1d10", damageType: "bludgeoning" }); + acts.clearDice(); + assert.equal(out.ok, true, out.error); + const roll = combatSince(before, acts.campaignId).find((entry) => entry.kind === "damage"); + assert.ok(roll, `the improvised action rolled no damage: ${JSON.stringify(out).slice(0, 300)}`); + expectRoll(roll, { kind: "damage", attacker: { kind: "sheet", id: fighter.id, name: "Aria" }, detail: "drops the chandelier", characterId: fighter.id }); +}); + +await test("One hazard names one source for everyone it catches: the words the GM gave it, a trap by them when it is one, else the GM's own dice.", async () => { + const { world: pipes, sheets: [fighter], enemies: [goblin] } = await table([{ ...FIGHTER, name: "Aria" }]); + const rollsOf = async (args) => { + const before = idsOf(pipes.campaignId); + // Each save's d20: a failure, so the damage is rolled. + pipes.dice(1, 1); + const out = await pipes.invoke("apply_hazard", { characterIds: [fighter.id], enemyIds: [goblin.id], saveAbility: "dex", dc: 25, damage: "2d6", damageType: "fire", ...args }); + pipes.clearDice(); + assert.equal(out.ok, true, out.error); + return combatSince(before, pipes.campaignId); + }; + const named = await rollsOf({ type: "generic", reason: "a burst pipe" }); + assert.equal(named.length, 2, JSON.stringify(named.map((roll) => roll.detail))); + for (const roll of named) { + assert.deepEqual(roll.attacker, source("named", "a burst pipe"), roll.detail); + assert.ok(!roll.detail.includes("burst pipe"), `the source is said twice: ${roll.detail}`); + } + assert.equal(named.find((roll) => roll.characterId)?.detail, "2d6 fire on Aria"); + assert.ok(named.find((roll) => !roll.characterId)?.detail.endsWith(` on ${goblin.displayName}`)); + // Left unnamed, it is the GM's own dice: the words the server has for it sit in a sentence, never in front of a roll. + const { rollCardLabel } = await import("../src/lib/roll-labels.ts"); + const plain = (key) => key; + for (const [args, words] of [[{ type: "generic" }, "the hazard"], [{ type: "trap" }, "a trap"]]) { + const unnamed = await rollsOf(args); + assert.ok(unnamed.length >= 2, JSON.stringify(unnamed.map((roll) => roll.detail))); + for (const roll of unnamed) { + assert.deepEqual(roll.attacker, source("gm", words), roll.detail); + assert.ok(rollCardLabel(plain, roll, "Aria").startsWith("The GM · "), rollCardLabel(plain, roll, "Aria")); + } + } + // A trap the GM describes is a trap by their words, for the character and the creature alike. + const trap = await rollsOf({ type: "trap", reason: "a scything blade" }); + assert.ok(trap.length >= 2, JSON.stringify(trap.map((roll) => roll.detail))); + for (const roll of trap) { + assert.deepEqual(roll.attacker, source("trap", "a scything blade"), roll.detail); + } +}); + +await test("A trap cast_at_player is told of is the trap's roll.", async () => { + const { world: spells, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(spells.campaignId); + spells.dice(1); + const told = await spells.invoke("cast_at_player", { characterId: fighter.id, source: "a dart trap", hazard: "trap", saveAbility: "dex", dc: 25, damage: "1d4", damageType: "poison" }); + spells.clearDice(); + assert.equal(told.ok, true, told.error); + const [roll] = combatSince(before, spells.campaignId); + expectRoll(roll, { kind: "damage", attacker: source("trap", "a dart trap"), detail: "1d4 poison on Aria", characterId: fighter.id }); +}); + +await test("Dice the GM sends for harm name the words they gave it, and the hit's record names the same source.", async () => { + const { openHits } = await import("../src/lib/dm/last-hit.ts"); + const { createDmTurn } = await import("../src/lib/db/dm-turns.ts"); + const { invokeEngine } = await import("../src/lib/dm/invoke.ts"); + const { world: harm, sheets: [fighter] } = await table([{ ...FIGHTER, name: "Aria" }]); + const turn = createDmTurn(harm.campaignId, []); + const before = idsOf(harm.campaignId); + const out = await invokeEngine(harm.campaign(), { kind: "ai", turnId: turn.id }, { name: "apply_damage", args: { characterId: fighter.id, dice: "2d6", type: "bludgeoning", reason: "falling rubble" } }); + assert.equal(out.ok, true, out.error); + const [roll] = combatSince(before, harm.campaignId); + expectRoll(roll, { kind: "damage", attacker: source("named", "falling rubble"), detail: "2d6 bludgeoning on Aria", characterId: fighter.id }); + const record = openHits(harm.campaignId, fighter.id).at(-1); + assert.ok(record, "the harm left no record of the hit"); + assert.deepEqual(record.attacker, roll.attacker); +}); + +await test("An area of harm with no creature behind it names the words the GM gave it, or is the GM's own dice, and names the creatures it catches.", async () => { + const { world: areas, enemies: [goblin] } = await table([{ ...FIGHTER, name: "Aria" }]); + const before = idsOf(areas.campaignId); + const out = await areas.invoke("aoe_damage", { enemyIds: [goblin.id], damage: "2d6", type: "fire", saveAbility: "dex", dc: 12, halfOnSave: true, reason: "a vat of oil catches" }); + assert.equal(out.ok, true, out.error); + const [roll] = combatSince(before, areas.campaignId); + expectRoll(roll, { kind: "damage", attacker: source("named", "a vat of oil catches"), detail: `2d6 fire on ${goblin.displayName}`, characterId: null }); + const again = idsOf(areas.campaignId); + const bare = await areas.invoke("aoe_damage", { enemyIds: [goblin.id], damage: "2d6", type: "fire", saveAbility: "dex", dc: 12, halfOnSave: true }); + assert.equal(bare.ok, true, bare.error); + const [own] = combatSince(again, areas.campaignId); + expectRoll(own, { kind: "damage", attacker: source("gm", "the GM"), detail: `2d6 fire on ${goblin.displayName}`, characterId: null }); +}); + +await test("A damage roll the GM asks of a player on their own dice lands as that character's roll.", async () => { + await kit.endFight(); + setMemberRealDice(world.campaignId, aria.userId, true); + const before = snapshot(); + const parked = await world.invoke("request_roll", { characterId: aria.id, kind: "damage", expression: "1d8+3", reason: "a thrown chair" }); + assert.equal(parked.ok, true, parked.error); + const pending = listOpenPendingRolls(world.campaignId).find((entry) => entry.kind === "damage"); + assert.ok(pending, "no damage roll was parked"); + world.signIn({ id: aria.userId }); + const out = await call(submitRoute, "POST", { dice: [5] }, { campaignId: world.campaignId, pendingRollId: pending.id }); + assert.equal(out.status, 200, JSON.stringify(out.json)); + setMemberRealDice(world.campaignId, aria.userId, false); + const [roll] = combatSince(before); + assert.ok(roll, "the damage the player rolled is on no record"); + assert.deepEqual(roll.attacker, asSheet(aria)); + assert.equal(roll.characterId, aria.id); + assert.match(roll.detail, /\(physical\)$/); +}); + await test("Each damaging ray of Prismatic Spray stores a card: the caster's, against the creature it strikes.", async () => { const { world: spells, sheets: [wizard, fighter], enemies: [goblin] } = await table([caster("wizard", "int", ["Prismatic Spray"], [], 13), { ...FIGHTER, name: "Bren" }]); const before = new Set(listRecentRolls(spells.campaignId, 200).map((roll) => roll.id)); diff --git a/scripts/test-enforce-sweep-clauses-martial-fighter.mjs b/scripts/test-enforce-sweep-clauses-martial-fighter.mjs index f5bb86bd80..6462fd60b6 100644 --- a/scripts/test-enforce-sweep-clauses-martial-fighter.mjs +++ b/scripts/test-enforce-sweep-clauses-martial-fighter.mjs @@ -163,6 +163,10 @@ const d20sOf = (log) => log.filter((die) => die.sides === 20).map((die) => die.f const first = await r.forced([3, 4], () => world.invoke("move_token", { token: enemy.id, x: 9, y: 5 })); assert.equal(first.ok, true, first.error); assert.equal(before - foe(enemy).currentHp, 7, `2d6 slashing (3 + 4) as it moves: ${show(first)}`); + // The condition keeps whose arrow it was: the brambles are the archer's roll. + const { listRecentRolls } = await import("../src/lib/db/rolls.ts"); + const torn = listRecentRolls(world.campaignId, 20).find((roll) => roll.detail.includes("brambles")); + assert.deepEqual(torn?.attacker, { kind: "sheet", id: archer.id, name: world.sheet(archer.id).name }, "the brambles are not the archer's roll"); const again = await r.forced([3, 4], () => world.invoke("move_token", { token: enemy.id, x: 10, y: 5 })); assert.equal(again.ok, true, again.error); assert.equal(before - foe(enemy).currentHp, 7, "a second move on the same turn tore it again"); diff --git a/scripts/test-enforce-sweep-dice-sites.mjs b/scripts/test-enforce-sweep-dice-sites.mjs index 566960bb5b..6d8c9bbe13 100644 --- a/scripts/test-enforce-sweep-dice-sites.mjs +++ b/scripts/test-enforce-sweep-dice-sites.mjs @@ -42,6 +42,9 @@ // the server's own as digital; // roller it names who rolled it: an attack or damage roll with no roller // reads as the roll of the character it lands on (a fall, a trap). +// A roll nobody made names its source (src/lib/roll-sources.ts), +// which goes in front of its card: its words do not say the source +// a second time, and they name the character it lands on. // // One function does all of these (src/lib/dm/roll-record.ts recordRoll). A // row whose site still records its roll by hand and misses one is listed @@ -396,7 +399,10 @@ async function enterParked() { } // What is wrong with the record of the rolls stored since `mark`, check by check. -function recordProblems(mark, seq, cards) { +// What a source can say it is (src/lib/db/rolls.ts HazardKind). +const HAZARDS = new Set(["fall", "gm", "trap", "item", "effect", "named"]); + +function recordProblems(mark, seq, cards, hazardRow = false) { const rolls = rollsAfter(world.campaignId, mark); const problems = { home: [], sent: [], roller: [] }; const mine = (roll) => roll.characterId === hero.id || roll.attacker?.id === hero.id; @@ -446,6 +452,25 @@ function recordProblems(mark, seq, cards) { } else if (!roll.attacker && !roll.characterId && roll.requestedBy !== "dm") { problems.roller.push(`${what}: names nobody`); } + const lands = roll.characterId ? world.sheet(roll.characterId)?.name : null; + if (roll.attacker?.kind === "hazard") { + const by = roll.attacker; + if (!HAZARDS.has(by.hazard)) { + problems.roller.push(`${what}: its source, ${by.name}, says it is "${by.hazard}", which is no kind of source`); + } + // Whatever the case: the words in front of the card, in its words again. + const said = roll.detail.toLowerCase(); + const again = by.hazard === "fall" ? "fall" : by.hazard === "gm" ? "the gm" : by.name.toLowerCase(); + if (said.includes(again)) { + problems.roller.push(`${what}: says its source, ${by.name}, a second time`); + } + if (lands && !roll.detail.includes(lands)) { + problems.roller.push(`${what}: ${by.name}'s roll does not name ${lands}, whom it lands on`); + } + } else if (hazardRow && roll.attacker?.kind === "sheet" && roll.attacker.id === roll.characterId && (roll.kind === "attack" || roll.kind === "damage")) { + // A hazard's own row: what lands on a character there is not their roll. + problems.roller.push(`${what}: a hazard's roll names ${lands}, whom it lands on, as its roller`); + } } return { problems, rolls: rolls.length }; } @@ -497,7 +522,7 @@ async function run(entry, door, seed) { } // The verdict is read before the seat answers: the dice it enters now are // its own, and the call runs on with them. - const record = recordProblems(mark, seq, await enterParked()); + const record = recordProblems(mark, seq, await enterParked(), /^(apply_hazard|cast_at_player\.hazard|concentration\.damage)/.test(entry.id)); spy.take(); return { verdict, where: where.filter((id) => !RULED_SITES[id]), out, parked, dice, record }; } @@ -663,7 +688,7 @@ const SITES = { // An opportunity attack's damage with Great Weapon Fighting's rerolls, // thrown through the character's door as its throwIt (audit 1116, A06). "lib/dm/opportunity-strike.ts#pcOpportunitySwing": "D an opportunity attack's damage, its 1s and 2s rerolled for Great Weapon Fighting", - "lib/dm/attack-onhit.ts#hurlReturn": "D", "lib/dm/attack-onhit.ts#poisonOnHit": "D", + "lib/dm/attack-onhit.ts#poisonOnHit": "D", "lib/dm/between-io.ts#publicDie": "F a table die", "lib/dm/character-roll.ts#initiativeWaits": "F no die: the lowest initiative, to read what the after-the-roll card would offer", "lib/dm/character-roll.ts#rollAtDoor": "H the one door a character's d20 is thrown through (src/lib/dm/character-roll.ts rollCharacterD20)", diff --git a/scripts/test-roll-labels.mjs b/scripts/test-roll-labels.mjs index 83f8f5d28d..ca2e4bd16c 100644 --- a/scripts/test-roll-labels.mjs +++ b/scripts/test-roll-labels.mjs @@ -169,6 +169,98 @@ await test("The post-fight summary credits a natural 20 to the PC who rolled it, assert.equal(summary.totals.nat20s, 1); }); +// Issue 915, ruling 2: a roll nobody at the table made names its source. +const source = (hazard, name) => ({ kind: "hazard", id: null, name, hazard }); +const sourced = [ + store([4, 5], "2d10", { characterId: aria.id, kind: "damage", detail: "2d10 piercing on Aria", attacker: source("trap", "Spiked Pit") }), + store([2, 2, 2], "3d6", { characterId: aria.id, kind: "damage", detail: "30 ft, 3d6 bludgeoning on Aria", attacker: source("fall", "the fall") }), + store([20], "1d20+8", { characterId: aria.id, kind: "attack", detail: "Attack vs Aria, AC 16", attacker: source("trap", "Poison Darts") }), + store([3, 3], "2d6", { characterId: aria.id, kind: "damage", detail: "2d6 fire on Aria", attacker: source("gm", "the GM") }), +]; + +// The fall and the GM's own dice are stored by a name that sits inside a +// sentence ("the fall"), and are worded in front of a roll by what they are. +await test("A roll nobody at the table made puts its source in front, where it read as the roll of the character it lands on.", () => { + assert.deepEqual(sourced.map((roll) => rollCardLabel(enT, roll, sheetName(roll))), [ + "Spiked Pit · Damage (2d10 piercing on Aria)", + "The fall · Damage (30 ft, 3d6 bludgeoning on Aria)", + "Poison Darts · Attack roll (Attack vs Aria, AC 16)", + "The GM · Damage (2d6 fire on Aria)", + ]); + const leads = [ + "Spiked Pit · 2d10 piercing on Aria", + "The fall · 30 ft, 3d6 bludgeoning on Aria", + "Poison Darts · Attack vs Aria, AC 16", + "The GM · 2d6 fire on Aria", + ]; + assert.deepEqual(sourced.map((roll) => rollToastLead(enT, roll, sheetName(roll))), leads); + assert.deepEqual(sourced.map((roll) => rollChronicleLead(enT, roll, sheetName(roll))), leads); + assert.deepEqual(gameState(sourced), [ + "- Spiked Pit: damage (2d10 piercing on Aria) rolled 9", + "- The fall: damage (30 ft, 3d6 bludgeoning on Aria) rolled 6", + "- Poison Darts: attack (Attack vs Aria, AC 16) rolled 28 (natural 20)", + "- The GM: damage (2d6 fire on Aria) rolled 6", + ]); +}); + +await test("No file but roll-sources.ts writes a source out: every other one asks it for one.", async () => { + const fs = await import("node:fs"); + const path = await import("node:path"); + const root = path.join(import.meta.dirname, "..", "src"); + // The module that builds them, the type that describes them, and an unrelated visual effect of the same word. + const allowed = new Set(["lib/roll-sources.ts", "lib/db/rolls.ts", "lib/battlemap/fx-plan.ts"]); + const found = []; + const walk = (dir) => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + walk(full); + } else if (/\.tsx?$/.test(entry.name)) { + const rel = path.relative(root, full).split(path.sep).join("/"); + if (!allowed.has(rel) && /kind:\s*"hazard"/.test(fs.readFileSync(full, "utf8"))) { + found.push(rel); + } + } + } + }; + walk(root); + assert.deepEqual(found, [], `a source is written out by hand in: ${found.join(", ")}`); +}); + +await test("The two sources that are never given a name are read in the table's language, by what they are and never by their name; a trap keeps the name it was given.", async () => { + await import("../src/lib/i18n/fr-catalog.ts"); + const frT = Object.assign((key, vars) => translate("fr", key, vars), { locale: "fr" }); + assert.ok(rollCardLabel(frT, sourced[1], "Aria").startsWith("La chute · "), rollCardLabel(frT, sourced[1], "Aria")); + assert.ok(rollToastLead(frT, sourced[3], "Aria").startsWith("Le MJ · "), rollToastLead(frT, sourced[3], "Aria")); + assert.ok(rollChronicleLead(frT, sourced[1], "Aria").startsWith("La chute · "), rollChronicleLead(frT, sourced[1], "Aria")); + assert.ok(rollCardLabel(frT, sourced[0], "Aria").startsWith("Spiked Pit · "), rollCardLabel(frT, sourced[0], "Aria")); + // A creature, or a hazard the GM named, that happens to be called "The fall" keeps its name. + assert.ok(rollCardLabel(frT, { ...sourced[1], attacker: { kind: "enemy", id: "e", name: "The fall" } }, "Aria").startsWith("The fall · ")); + assert.ok(rollCardLabel(frT, { ...sourced[1], attacker: source("named", "The fall") }, "Aria").startsWith("The fall · ")); + // And the fall is the fall whatever its stored name says. + assert.ok(rollCardLabel(frT, { ...sourced[1], attacker: source("fall", "the fall") }, "Aria").startsWith("La chute · ")); + assert.ok(rollCardLabel(enT, { ...sourced[1], attacker: source("fall", "the fall") }, "Aria").startsWith("The fall · ")); + // The GM's own dice for a trap nothing named: a sentence calls it "a trap", and its roll is the GM's. + assert.ok(rollCardLabel(enT, { ...sourced[3], attacker: source("gm", "a trap") }, "Aria").startsWith("The GM · ")); + assert.ok(rollCardLabel(frT, { ...sourced[3], attacker: source("gm", "a trap") }, "Aria").startsWith("Le MJ · ")); +}); + +await test("The post-fight summary does not give a character a trap's natural 20 against them.", () => { + const rolls = sourced.map((roll) => ({ characterId: roll.characterId, attacker: roll.attacker, kind: roll.kind, total: roll.total, applied: true, targetEnemyId: null, crit: roll.breakdown.crit ?? null })); + const summary = computeEncounterSummary({ + outcome: "victory", rounds: 1, startedAt: "2026-10-01T10:00:00.000Z", endedAt: "2026-10-01T10:05:00.000Z", + enemies: [{ status: "dead" }], sheets: world.sheets().map((sheet) => ({ id: sheet.id, name: sheet.name })), rolls, audits: [], + }); + const line = summary.fighters.find((fighter) => fighter.characterId === aria.id); + assert.equal(line.nat20s, 0); + // Stored with no attacker, as these were, the natural 20 was Aria's. + const unnamed = computeEncounterSummary({ + outcome: "victory", rounds: 1, startedAt: "2026-10-01T10:00:00.000Z", endedAt: "2026-10-01T10:05:00.000Z", + enemies: [{ status: "dead" }], sheets: world.sheets().map((sheet) => ({ id: sheet.id, name: sheet.name })), rolls: rolls.map((roll) => ({ ...roll, attacker: null })), audits: [], + }); + assert.equal(unnamed.fighters.find((fighter) => fighter.characterId === aria.id).nat20s, 1); +}); + // Issue #622: the beat drafts read the newest changes, and a fight's rounds // write a time-only tick for each character every round. The ticks are no // beat, and they must not crowd the changes that are out of the forty read. diff --git a/scripts/test-roll-stage.mjs b/scripts/test-roll-stage.mjs index afd2932d74..957808a393 100644 --- a/scripts/test-roll-stage.mjs +++ b/scripts/test-roll-stage.mjs @@ -168,6 +168,16 @@ test("the stream keeps a three-swing burst with its on-hit dice whole", () => { assert.ok(STAGE_HEARD_MAX >= 9); }); +test("a source nobody is (a trap) keeps its own damage with its attack, and not another source's", () => { + const darts = { kind: "hazard", id: null, name: "Poison Darts", hazard: "trap" }; + const pit = { kind: "hazard", id: null, name: "Spiked Pit", hazard: "trap" }; + const attack = placeRoll(null, roll("dart", "attack", darts), 1, 0); + assert.equal(placeRoll(attack.open, roll("dart-damage", "damage", darts), 2, 10).group, attack.group); + assert.notEqual(placeRoll(attack.open, roll("spikes", "damage", pit), 3, 20).group, attack.group); + // The same name on another kind of source is another source. + assert.notEqual(placeRoll(attack.open, roll("named", "damage", { ...darts, hazard: "named" }), 4, 30).group, attack.group); +}); + test("the stale window sits under the stuck-throw deadline", () => { assert.ok(DICE_STALE_MS < DICE_ROLL_DEADLINE_MS); }); diff --git a/src/lib/db/core.ts b/src/lib/db/core.ts index a9bfa84185..2a7047eb91 100644 --- a/src/lib/db/core.ts +++ b/src/lib/db/core.ts @@ -2263,8 +2263,9 @@ function ensureSchema(db: SqliteDatabase) { // Who made an attack or damage roll, by name as they were when it was // rolled (src/lib/db/rolls.ts RollAttacker). character_id is the PC the // roll concerns, which for an enemy's attack is its target, so it cannot - // say who rolled. NULL: nobody did (a fall), a roll tool, or a roll - // stored before the column. + // say who rolled. A roll nobody made (a fall, a trap) names its source + // here. NULL: a roll that is neither an attack nor damage, or one stored + // before the column. ["attacker_json", `TEXT`], ]); diff --git a/src/lib/db/rolls.ts b/src/lib/db/rolls.ts index 7fc5be2263..a9e54bbb42 100644 --- a/src/lib/db/rolls.ts +++ b/src/lib/db/rolls.ts @@ -26,7 +26,27 @@ export type RollVisibility = (typeof ROLL_VISIBILITIES)[number] | "secret"; // A character's bound creature has no id of its own (it lives on its owner's // sheet), so a pet's id is its owner's sheet id. characterId cannot say this: // it is the PC the roll concerns, the target of an enemy's attack. -export type RollAttacker = { kind: "sheet" | "enemy" | "pet"; id: string; name: string }; +// A roll nobody at the table made names its source, a "hazard" with no id, +// as a hit's record does (src/lib/dm/last-hit.ts): unnamed, it read as the +// roll of the character it landed on. `hazard` says what the source is, so +// no reader works that out from its name: a fall, the GM's own dice for +// harm nothing names, a trap, an item, the effect of a spell or feature, or +// a hazard by the words the GM gave it. Every source is built in +// src/lib/roll-sources.ts. +export type HazardKind = "fall" | "gm" | "trap" | "item" | "effect" | "named"; +export type RollSource = { kind: "hazard"; id: null; name: string; hazard: HazardKind }; +export type RollAttacker = { kind: "sheet" | "enemy" | "pet"; id: string; name: string } | RollSource; + +// The kind and roller of a roll whose kind is only known as it runs (a roll +// card's own dice, the roll tools): an attack or damage roll takes +// `otherwise` when nobody else is named, and the other kinds may name nobody. +export function kindAndRoller( + kind: RollKind, + attacker: RollAttacker | null, + otherwise: RollAttacker, +): { kind: "attack" | "damage"; attacker: RollAttacker } | { kind: Exclude; attacker: RollAttacker | null } { + return kind === "attack" || kind === "damage" ? { kind, attacker: attacker ?? otherwise } : { kind, attacker }; +} export type StoredRoll = { id: string; @@ -50,8 +70,9 @@ export type StoredRoll = { // call of its own or as a roll card landed (markRollSpent), so it pays for // no number sent later. applied: boolean; - // Attack and damage rolls: who rolled. Null when nobody did (a fall), for - // the roll tools' rolls, and for rolls stored before it was recorded. + // Attack and damage rolls: who rolled, or the source of a roll nobody made + // (a fall). Null for other kinds of roll, and for rolls stored before it + // was recorded. attacker: RollAttacker | null; createdAt: string; }; @@ -139,7 +160,7 @@ export function landRoll(rollId: string, targetEnemyId: string return result; } -// An attack or damage roll must say who made it, or that nobody did. +// An attack or damage roll must say who made it, or name its source. export type RollInsert = { campaignId: string; characterId?: string | null; @@ -151,7 +172,7 @@ export type RollInsert = { visibility?: RollVisibility; messageId?: string | null; } & ( - | { kind: "attack" | "damage"; attacker: RollAttacker | null } + | { kind: "attack" | "damage"; attacker: RollAttacker } | { kind: Exclude; attacker?: RollAttacker | null } ); diff --git a/src/lib/dice/roll-stage-logic.ts b/src/lib/dice/roll-stage-logic.ts index 73cdbd083a..76b56b70ac 100644 --- a/src/lib/dice/roll-stage-logic.ts +++ b/src/lib/dice/roll-stage-logic.ts @@ -20,7 +20,7 @@ export type StageRoll = { kind: RollKind; visibility: RollVisibility; total: number | null; - attacker: Pick | null; + attacker: (Pick & { name?: string; hazard?: string }) | null; hidden?: boolean; }; @@ -66,8 +66,12 @@ export const STAGE_HEARD_MAX = 12; // on-hit roll of the same attacker joins. export type OpenAction = { group: number; actor: string | null; lastAt: number } | null; +// A source nobody at the table is (a trap, a fall: src/lib/db/rolls.ts) has +// no id: it is told apart by what it is and the name it was given, so a +// trap's damage joins the attack that trap made and no other source's. export function actorOf(roll: Pick): string | null { - return roll.attacker ? `${roll.attacker.kind}:${roll.attacker.id}` : null; + const by = roll.attacker; + return by ? `${by.kind}:${by.id ?? `${by.hazard ?? ""}:${by.name ?? ""}`}` : null; } // Which action a roll heard at `at` belongs to. An attack always opens a new diff --git a/src/lib/dm/ai-gate.ts b/src/lib/dm/ai-gate.ts index 2d171b6b48..a1fde4ff95 100644 --- a/src/lib/dm/ai-gate.ts +++ b/src/lib/dm/ai-gate.ts @@ -19,13 +19,15 @@ import { splitParts } from "@/lib/dm/action-parts-logic"; import type { Campaign } from "@/lib/db/campaigns"; import type { DmTurn } from "@/lib/db/dm-turns"; -import { getActiveEncounter } from "@/lib/db/encounters"; +import { getActiveEncounter, getEnemy } from "@/lib/db/encounters"; +import { shownName } from "@/lib/dm/board-hidden"; import { getRoll, markRollApplied, markRollSpent } from "@/lib/db/rolls"; import { awayRefusal, canCrossAway } from "@/lib/dm/fight-away-logic"; import { isValidExpression } from "@/lib/dice"; import { spellFactsFor } from "@/lib/content"; import { rollAgainst } from "@/lib/roll-labels"; -import { rollCard } from "@/lib/dm/roll-card"; +import { rollCard, sourceDamage } from "@/lib/dm/roll-card"; +import { harmSource, UNNAMED_HARM } from "@/lib/roll-sources"; import { rollCharacterSave } from "@/lib/dm/forced-save"; import { canonicalCondition } from "@/lib/dm/set-condition"; import { trapHoldOn } from "@/lib/dm/trap-escape"; @@ -239,9 +241,21 @@ function number(ctx: GateContext, args: Record, what: "damage" return { result: { error: `"${dice}" is not dice the server can roll; send it like "2d6+3".`, retry: true } }; } const sheet = ctx.sheetsById.get(targetId); - const label = rollAgainst(String(args.reason ?? (what === "damage" ? "Damage" : "Healing")).slice(0, 60), sheet?.name ?? "the target"); + const said = (value: unknown) => (typeof value === "string" ? value.trim() : ""); + // Whom it lands on, as the card says it: a pet by its own name, and a + // creature by the name the table may read now (a hidden one stays so). + const foe = sheet ? null : getEnemy(targetId); + const whom = said(args.petName) || sheet?.name || (foe ? shownName(foe.encounterId, foe.id, foe.displayName) : "the target"); const before = ctx.turn.rollIds.length; - const rolled = rollCard(ctx.campaign, ctx.turn, sheet ? sheet.id : null, what === "damage" ? "damage" : "custom", label, dice, null); + // The model's own dice for harm with no creature behind it: the roll of + // the spell it is, else of the words it gave for it, else the GM's own + // dice. The hit's record is built from the same two arguments + // (mutations.ts apply_damage). Whoever it lands on is its target. + // Healing is no attack and no damage: it names no roller. + const rolled = + what === "damage" + ? sourceDamage(ctx.campaign, ctx.turn, harmSource(said(args.spell), said(args.reason), UNNAMED_HARM), { characterId: sheet ? sheet.id : null, names: [whom] }, { dice, type: said(args.type) || undefined }) + : rollCard(ctx.campaign, ctx.turn, sheet ? sheet.id : null, "custom", rollAgainst(said(args.reason).slice(0, 60) || "Healing", whom), dice, null); // Spent as it is rolled: the call let through below applies it, and the // same total sent bare afterwards would land it a second time. for (const id of ctx.turn.rollIds.slice(before)) { diff --git a/src/lib/dm/aoe-damage.ts b/src/lib/dm/aoe-damage.ts index bfe6a5fe84..5f217a02db 100644 --- a/src/lib/dm/aoe-damage.ts +++ b/src/lib/dm/aoe-damage.ts @@ -18,6 +18,8 @@ import type { Campaign } from "@/lib/db/campaigns"; import { getActiveEncounter, getEnemy, listEnemies, type EncounterEnemy } from "@/lib/db/encounters"; import type { RollAttacker } from "@/lib/db/rolls"; import { recordRoll } from "@/lib/dm/roll-record"; +import { sourceDamageThrown } from "@/lib/dm/roll-card"; +import { harmSource } from "@/lib/roll-sources"; import { getBattleMapForEncounter, listHiddenRefIds } from "@/lib/db/battle-maps"; import { rollOn } from "@/lib/roll-labels"; import type { DmTurn } from "@/lib/db/dm-turns"; @@ -595,13 +597,19 @@ export function handleAoeDamage( const outcome = burst?.outcome ?? thrown; bombardNote = burst?.note ?? bombardNote; rolled.push({ amount: outcome.total, type }); + if (!areaBy) { + // An area no creature made is the roll of the spell it is, else of + // the words the GM gave for it, else the GM's own dice, and says + // what it threw, as every source's roll does. + sourceDamageThrown(campaign, turn, harmSource(args.spell, args.reason), { names: caught }, { dice: expression, type }, outcome); + continue; + } recordRoll({ campaignId: campaign.id, characterId: null, requestedBy: "dm", kind: "damage", - // The type tells a two-type spell's rolls apart, and is all an - // unnamed effect has. + // The type tells a two-type spell's rolls apart. detail: rollOn(`${areaName ?? "area effect"}${type && (split || !areaName) ? ` (${type})` : ""}`, caught), result: outcome, attacker: areaBy, diff --git a/src/lib/dm/ar-ws-charm-miss.ts b/src/lib/dm/ar-ws-charm-miss.ts index 170faadde7..86b0a2e509 100644 --- a/src/lib/dm/ar-ws-charm-miss.ts +++ b/src/lib/dm/ar-ws-charm-miss.ts @@ -74,10 +74,11 @@ export function landTurnedMiss(ctx: Ctx, encounter: Encounter, found: { record: settle(ctx, record, record.swings, key); const against = meets(ctx.campaign.id, taker, swing, record); const { attacker, attack } = attackOf(record, swing); - if (!against.lands || !attack) { + // An attack on record comes with the creature that made it. + if (!against.lands || !attack || !attacker) { return { applied: `The attack turns onto ${taker.name} and misses them too (${swing.total} against AC ${against.ac}).` }; } - const rolled = Math.max(0, rollCard(ctx.campaign, ctx.turn, null, "damage", rollAgainst(`${attack.name} (${feature})`, taker.name), attack.damage!, attacker ? enemyAttacker(attacker) : null).total); + const rolled = Math.max(0, rollCard(ctx.campaign, ctx.turn, null, "damage", rollAgainst(`${attack.name} (${feature})`, taker.name), attack.damage!, enemyAttacker(attacker)).total); const type = attack.type ?? record.type; const magical = hasTrait(attacker?.stats, "magicWeapons") || attack.magical === true || attack.spellAttack === true; const applied = diff --git a/src/lib/dm/arcane-triggered.ts b/src/lib/dm/arcane-triggered.ts index d7e22cd31b..8f29077497 100644 --- a/src/lib/dm/arcane-triggered.ts +++ b/src/lib/dm/arcane-triggered.ts @@ -33,7 +33,7 @@ import { applyEnemyDamage, publishEncounter } from "@/lib/dm/enemy-damage"; import { heaviestHit, hitIdOf, openHits, type LastHit, type SwingRecord } from "@/lib/dm/last-hit"; import { openTriggersFor, type TriggerAsk } from "@/lib/dm/reaction-triggers"; import { settleLastHit } from "@/lib/dm/reaction-refund"; -import { rollCard } from "@/lib/dm/roll-card"; +import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import { resolveTargetFoe } from "@/lib/dm/sheet-foe"; import { summonAccursedSpecter } from "@/lib/dm/summon-arcane"; import type { ToolError } from "@/lib/dm/tool-errors"; @@ -77,7 +77,7 @@ function violentAttraction(input: Input, ask: TriggerAsk): Plan | ToolError { if (unseen) return unseen; return { apply: () => { - const rolled = rollCard(campaign, turn, sheet.id, "damage", `Violent Attraction: ${striker.name}'s hit on ${enemy.displayName}`, "1d10", null).total; + const rolled = rollCard(campaign, turn, sheet.id, "damage", `Violent Attraction: ${striker.name}'s hit on ${enemy.displayName}`, "1d10", sheetAttacker(sheet)).total; const applied = turn ? applyEnemyDamage(campaign, turn, encounter, enemy, rolled, input.sheets, input.sheetsById, undefined, { magical: true }) : {}; publishEncounter(campaign.id); return { rolled: `1d10: ${rolled}`, applied: `${striker.name}'s weapon hits ${enemy.displayName} harder: ${rolled} more damage.`, ...applied }; @@ -93,7 +93,7 @@ function violentAttraction(input: Input, ask: TriggerAsk): Plan | ToolError { if (unseen) return unseen; return { apply: () => { - const rolled = rollCard(campaign, turn, sheet.id, "damage", `Violent Attraction: ${record.attacker.name}'s hit`, "1d10", null).total; + const rolled = rollCard(campaign, turn, sheet.id, "damage", `Violent Attraction: ${record.attacker.name}'s hit`, "1d10", sheetAttacker(sheet)).total; const swing = record.swings[index]; const settled = settle(input, record, record.swings.map((entry, at) => (at === index ? { ...swing, raw: swing.raw + rolled } : entry)), "violent attraction"); return { rolled: `1d10: ${rolled}`, applied: `${record.attacker.name}'s weapon hits harder: ${rolled} more damage. HP ${settled.hp}.` }; diff --git a/src/lib/dm/ask.ts b/src/lib/dm/ask.ts index 59f5b9f793..f85c2a4e1d 100644 --- a/src/lib/dm/ask.ts +++ b/src/lib/dm/ask.ts @@ -9,6 +9,7 @@ import { listRecentMessages } from "@/lib/db/messages"; import { listNpcs } from "@/lib/db/npcs"; import { listRuleChunks } from "@/lib/db/rules"; import { listRollsVisibleTo } from "@/lib/db/rolls"; +import { rollerName } from "@/lib/roll-labels"; import { getSheetForUser, listSheets } from "@/lib/db/sheets"; import { arcTextTimeoutMs, utilityContextTokens, type ChatMessage } from "@/lib/model-client"; import { requestUtilityMessage } from "@/lib/dm/model"; @@ -176,7 +177,7 @@ function mechanicalRecord(campaignId: string, ownedCharacterIds: string[]): stri rolls.length ? `The most recent dice the server rolled, oldest first (every attack and every point of damage is here; "not applied" means it changed no hit points):\n${rolls .map((roll) => { - const roller = roll.attacker?.name ?? (roll.characterId ? names.get(roll.characterId) : null) ?? "The table"; + const roller = rollerName(roll, roll.characterId ? names.get(roll.characterId) : undefined) ?? "The table"; const outcome = roll.success === null ? "" : roll.success ? ", success" : ", failure"; const landed = roll.kind === "damage" && roll.targetEnemyId ? (roll.applied ? ", applied" : ", not applied") : ""; return `[roll:${roll.id.slice(0, 8)}] ${roller}: ${roll.kind}, ${roll.detail.slice(0, 120)} (${roll.expression}) = ${roll.total}${outcome}${landed}`; diff --git a/src/lib/dm/attack-onhit.ts b/src/lib/dm/attack-onhit.ts index c3c23c6fc5..cd0c73d122 100644 --- a/src/lib/dm/attack-onhit.ts +++ b/src/lib/dm/attack-onhit.ts @@ -19,6 +19,7 @@ import { settleEnemyIncapacitation } from "@/lib/dm/enemy-incapacitation"; import { getActiveEncounter, patchEnemyConditions, type EncounterEnemy } from "@/lib/db/encounters"; import { recordRoll } from "@/lib/dm/roll-record"; import { rollAgainst } from "@/lib/roll-labels"; +import { castersDamage } from "@/lib/dm/roll-card"; import { insertSheetAudit } from "@/lib/db/sheet-audit"; import { getSheetById, listSheets, patchSheet } from "@/lib/db/sheets"; import { rollExpression } from "@/lib/dice"; @@ -342,20 +343,10 @@ export function hurlReturn(campaign: Campaign, enemy: EncounterEnemy, meta: Cond if (/fiend/i.test(String(enemy.stats.type ?? ""))) { return `${enemy.displayName} returns from the lower planes unharmed: it is a fiend.`; } - const outcome = rollExpression("10d10"); const warlock = meta.source ? getSheetById(meta.source) : null; - // Handed no turn: inside a GM call it joins the call's own. - recordRoll({ - campaignId: campaign.id, - characterId: meta.source ?? null, - requestedBy: "dm", - kind: "damage", - detail: rollAgainst("Hurl Through Hell", enemy.displayName), - result: outcome, - attacker: warlock ? { kind: "sheet", id: warlock.id, name: warlock.name } : null, - // Thrown here, on the server's dice. - landing: null, - }); + // The warlock's roll; the feature's own once their sheet has left the + // table. Handed no turn: inside a GM call it joins the call's own. + const outcome = castersDamage(campaign, null, warlock, rollAgainst("Hurl Through Hell", enemy.displayName), "Hurl Through Hell", enemy.displayName, { dice: "10d10", type: "psychic" }); damageEnemy(campaign, enemy, outcome.total, "psychic"); return `${enemy.displayName} returns from the lower planes, reeling from the horror, and takes ${outcome.total} psychic damage (Hurl Through Hell).`; } diff --git a/src/lib/dm/authored-hooks.ts b/src/lib/dm/authored-hooks.ts index a3d4136b17..2015899772 100644 --- a/src/lib/dm/authored-hooks.ts +++ b/src/lib/dm/authored-hooks.ts @@ -71,7 +71,7 @@ import { naturalWeaponOnHit } from "@/lib/dm/authored-attacks"; import { weaponNamed } from "@/lib/srd/weapons"; import { authoredNaturalWeapon } from "@/lib/srd/authored-effects-more"; import type { CharacterSheet } from "@/lib/schemas/sheet"; -import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; +import { castersDamage, rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import { rollAgainst } from "@/lib/roll-labels"; import { noteCurseHeal } from "@/lib/dm/master-of-hexes"; @@ -466,7 +466,7 @@ export function authoredOnHit( delete meta[cursed]; patchEnemyConditions(enemy.id, cleared, meta); const cleric = getSheetById(curse.source); - const amount = rollCard(campaign, null, cleric?.id ?? null, "damage", rollAgainst("Order's Wrath", enemy.displayName), curse.dice ?? "2d8", cleric ? sheetAttacker(cleric) : null).total; + const amount = castersDamage(campaign, null, cleric, rollAgainst("Order's Wrath", enemy.displayName), "Order's Wrath", enemy.displayName, { dice: curse.dice ?? "2d8", type: curse.type ?? "psychic" }).total; const fresh = getEnemy(enemy.id); if (fresh) { lines.push(hurtEnemy(campaign, encounter, fresh, amount, curse.type ?? "psychic", "Order's Wrath")); diff --git a/src/lib/dm/authored-mote.ts b/src/lib/dm/authored-mote.ts index 992b3d152a..97bed73dd7 100644 --- a/src/lib/dm/authored-mote.ts +++ b/src/lib/dm/authored-mote.ts @@ -30,7 +30,7 @@ import { applyEnemyDamage, publishEncounter } from "@/lib/dm/enemy-damage"; import { withinFeet } from "@/lib/dm/authored-saves"; import { rollEnemySave } from "@/lib/dm/forced-save"; import type { CharacterSheet } from "@/lib/schemas/sheet"; -import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; +import { castersDamage, rollCard } from "@/lib/dm/roll-card"; import { rollAgainst } from "@/lib/roll-labels"; // `rolled`: what the die showed on the attack roll that spent it (withMoteRoll). @@ -129,7 +129,7 @@ export function moteBurst(campaign: Campaign, turn: DmTurn, mote: HeldMote | nul continue; } // The mote is the bard's: the burst is theirs. - amount ??= rollCard(campaign, turn, bard?.id ?? null, "damage", rollAgainst("Mote of Potential", enemy.displayName), `1${mote.die}`, bard ? sheetAttacker(bard) : null).total; + amount ??= castersDamage(campaign, turn, bard, rollAgainst("Mote of Potential", enemy.displayName), "Mote of Potential", enemy.displayName, { dice: `1${mote.die}`, type: "thunder" }).total; const dealt = Math.max(1, amount); applyEnemyDamage(campaign, turn, encounter, getEnemy(enemy.id) ?? enemy, dealt, sheets, sheetsById, "thunder", { magical: true }); lines.push(`${enemy.displayName} takes ${dealt} thunder damage`); diff --git a/src/lib/dm/authored-reactions-more.ts b/src/lib/dm/authored-reactions-more.ts index bc52d4592b..650999fce4 100644 --- a/src/lib/dm/authored-reactions-more.ts +++ b/src/lib/dm/authored-reactions-more.ts @@ -182,11 +182,11 @@ function redirectMiss(ctx: Ctx, name: string, rangeFt: number): ToolResult { } const attacker = getEnemy(record.attacker.id); const attack = (attacker?.stats.attacks ?? []).find((entry) => textKey(entry.name) === textKey(record.attack)); - if (!attack?.damage) { + if (!attacker || !attack?.damage) { return { error: `The server has no damage on record for ${record.attacker.name}'s ${record.attack}. Nothing was spent.`, refused: "rules" }; } // The attacker's own blow, turned (Stand Against the Tide reads the same). - const rolled = Math.max(0, rollCard(campaign, ctx.turn, null, "damage", rollAgainst(`${attack.name} (${name})`, target.displayName), attack.damage, attacker ? enemyAttacker(attacker) : null).total); + const rolled = Math.max(0, rollCard(campaign, ctx.turn, null, "damage", rollAgainst(`${attack.name} (${name})`, target.displayName), attack.damage, enemyAttacker(attacker)).total); const type = attack.type ?? record.type; // Still the attacker's blow: a creature whose weapon attacks are magical, // or a block that prints the blow as magical, strikes the other with magic. diff --git a/src/lib/dm/cast-at-player.ts b/src/lib/dm/cast-at-player.ts index ab61e84b85..db0d2713c1 100644 --- a/src/lib/dm/cast-at-player.ts +++ b/src/lib/dm/cast-at-player.ts @@ -26,9 +26,9 @@ import { prepareEnemyUse, type EnemyUse } from "@/lib/dm/enemy-casting"; import { rollCharacterSave, type SaveOrigin } from "@/lib/dm/forced-save"; import { noteSaveDamage, recordTrigger } from "@/lib/dm/last-save"; import { openEffect } from "@/lib/dm/last-hit"; -import { rollCard } from "@/lib/dm/action-common"; -import type { RollAttacker } from "@/lib/db/rolls"; -import { rollAgainst } from "@/lib/roll-labels"; +import { castDamage, enemyAttacker } from "@/lib/dm/roll-card"; +import type { RollSource } from "@/lib/db/rolls"; +import { castSource, effectSource } from "@/lib/roll-sources"; import { publishFx, tokenPosition } from "@/lib/dm/fx"; import { applyDmMutation, canonicalCondition } from "@/lib/dm/mutations"; import { resolveSheetRef, unknownSheetRef } from "@/lib/dm/rolls"; @@ -265,7 +265,7 @@ function autoSpellAtPlayer( sheet: CharacterSheet, use: EnemyUse | null, spell: string, - cast: { damage?: string; damageType?: string; secondType?: string; source?: string; ward: string | null }, + cast: { damage?: string; damageType?: string; secondType?: string; source?: string; trap?: boolean; ward: string | null }, sheets: CharacterSheet[], sheetsById: Map, ): ToolResult { @@ -280,9 +280,11 @@ function autoSpellAtPlayer( if (cast.ward) { return { ok: true, target: sheet.name, source, ...castToNoEffect(cast.ward) }; } - const caster: RollAttacker | null = use ? { kind: "enemy", id: use.enemy.id, name: use.enemy.displayName } : null; + // A spell no creature cast is the roll of the source the GM named, else of + // the spell itself. The hit's record below is handed the same value. + const caster = use ? ({ kind: "enemy", id: use.enemy.id, name: use.enemy.displayName } as const) : castSource(cast.source, spell, cast.trap); const hitLog = openLastHit(campaign.id, sheet.id); - const outcome = rollCard(campaign, turn, sheet.id, "damage", rollAgainst(spell, sheet.name), cast.damage, caster); + const outcome = castDamage(campaign, turn, caster, spell, { characterId: sheet.id, name: sheet.name }, { dice: cast.damage, type: cast.damageType }); const shielded = isNamed(spell, "magic missile") && (getSheetById(sheet.id) ?? sheet).conditions.some((entry) => isConditionNamed(entry, "shielded")); const dealt = shielded ? 0 : Math.max(0, outcome.total); // A spell of two types: each part meets the character's defences on its @@ -307,7 +309,7 @@ function autoSpellAtPlayer( : {}; hitLog.swing(outcome, 0, { hit: dealt > 0, crit: false, raw: dealt, advantage: "none", ...(cast.damageType ? { type: cast.damageType } : {}), ...(parts && dealt > 0 ? { parts } : {}), ranged: true, attack: spell, flags: { magical: true, spell: true } }); hitLog.close({ - attacker: use ? { kind: "enemy", id: use.enemy.id, name: use.enemy.displayName } : { kind: "hazard", id: null, name: source }, + attacker: caster, attack: spell, type: cast.damageType ?? "force", ranged: true, @@ -330,6 +332,10 @@ export function handleCastAtPlayer( rawArguments: string, sheets: CharacterSheet[], sheetsById: Map, + // The source a caller inside the engine already knows this harm by (a trap + // or hazard apply_hazard sprang): its roll names that one, not one read + // back from the call's words. + by?: RollSource, ): ToolResult { let args: z.infer; try { @@ -440,7 +446,7 @@ export function handleCastAtPlayer( const castName = use?.name || args.spell; const unsaved = castName && !use?.save && !args.saveAbility ? spellMechanicsFor({ spell: castName, userIds: spellAuthorsFor(campaign) }) : null; if (castName && unsaved?.mech.resolution === "auto") { - return autoSpellAtPlayer(campaign, turn, sheet, use, castName, { damage: (use?.fromBlock ? use.damage : undefined) ?? args.damage, damageType: (use?.fromBlock ? use.damageType : undefined) ?? args.damageType ?? unsaved.mech.damageType, secondType: use?.secondType ?? unsaved.mech.secondType, source: args.source, ward }, sheets, sheetsById); + return autoSpellAtPlayer(campaign, turn, sheet, use, castName, { damage: (use?.fromBlock ? use.damage : undefined) ?? args.damage, damageType: (use?.fromBlock ? use.damageType : undefined) ?? args.damageType ?? unsaved.mech.damageType, secondType: use?.secondType ?? unsaved.mech.secondType, source: args.source, trap: args.hazard === "trap", ward }, sheets, sheetsById); } const byBlock = Boolean(use?.fromBlock); const ability = (use?.save ?? args.saveAbility) as SaveAbility | undefined; @@ -552,8 +558,13 @@ export function handleCastAtPlayer( if (damage) { // The card shows the dice as rolled; the save halves or stops what lands. - const caster: RollAttacker | null = use ? { kind: "enemy", id: use.enemy.id, name: use.enemy.displayName } : null; - const outcome = rollCard(campaign, turn, sheet.id, "damage", rollAgainst(use?.name || args.spell || args.source || "Effect", sheet.name), damage, caster); + // A hazard with no creature behind it is the roll of the source its + // caller hands in (a trap's save is the roll of the same trap its darts + // were). Called on its own, it is the roll of the source the call names + // (a trap, when the call says it is one), else of its spell, else the + // GM's own dice. + const caster = use ? enemyAttacker(use.enemy) : (by ?? castSource(args.source, args.spell, args.hazard === "trap", source)); + const outcome = castDamage(campaign, turn, caster, use?.name || args.spell, { characterId: sheet.id, name: sheet.name }, { dice: damage, type: damageType }); // The one save-for-half rule every path shares, Evasion included // (src/lib/srd/trait-rules.ts). const taken = saveDamageTaken({ total: outcome.total, saved, halfOnSave, ability, sheet }); @@ -634,7 +645,10 @@ export function handleCastAtPlayer( sheets, sheetsById, ).result; - effect.close({ raw: dealt, type: typedParts ? "" : (damageType ?? ""), name: source }); + // The record is handed the source its roll names. A creature's spell + // is on record as that spell's effect, as it always was: the record of + // a save's damage names no creature. + effect.close({ raw: dealt, type: typedParts ? "" : (damageType ?? ""), by: caster.kind === "hazard" ? caster : effectSource(source) }); // Thought Shield: the psychic damage a warlock took goes back to the caster. const back = thoughtShieldBack(campaign, turn, sheet, use?.enemy.id, { amount: dealt, type: typedParts ? undefined : damageType, parts: typedParts ?? undefined, flags: { magical: use?.magical === true, spell: Boolean(use?.spell ?? args.spell) } }, sheets, sheetsById); Object.assign(base, { damage: dealt, ...applied, ...back }); diff --git a/src/lib/dm/caster-features.ts b/src/lib/dm/caster-features.ts index 7400c4ffa3..b8d0a1c23a 100644 --- a/src/lib/dm/caster-features.ts +++ b/src/lib/dm/caster-features.ts @@ -18,7 +18,7 @@ import { getSheetById, patchSheet } from "@/lib/db/sheets"; import { applyPcDamage } from "@/lib/dm/pc-damage"; import type { CharacterSheet } from "@/lib/schemas/sheet"; import type { SpellFacts } from "@/lib/srd/spell-facts"; -import { rollCard } from "@/lib/dm/roll-card"; +import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import type { ToolError } from "@/lib/dm/tool-errors"; import { textKey } from "@/lib/language/text-logic"; import { holdsFeature } from "@/lib/srd/feature-names"; @@ -75,8 +75,8 @@ export function payOverchannel(campaign: Campaign, turn: DmTurn, casterId: strin return `Overchannel: ${sheet.name} deals the spell's maximum damage; the next use before a long rest will cost them.`; } const dice = `${(used + 1) * spellLevel}d12`; - // A cost to the caster's own hit points: their card, nobody's attack. - const rolled = rollCard(campaign, turn, sheet.id, "damage", "Overchannel", dice, null).total; + // A cost to the caster's own hit points: their own roll. + const rolled = rollCard(campaign, turn, sheet.id, "damage", "Overchannel", dice, sheetAttacker(sheet)).total; // Typeless on purpose: the SRD says this damage ignores resistance and // immunity. applyPcDamage(campaign, turn.id, getSheetById(sheet.id) ?? sheet, { amount: rolled, reason: "Overchannel" }); diff --git a/src/lib/dm/consumables.ts b/src/lib/dm/consumables.ts index d3294ad052..9c24e1bdea 100644 --- a/src/lib/dm/consumables.ts +++ b/src/lib/dm/consumables.ts @@ -40,7 +40,8 @@ import { markItemSpellOnTurn } from "@/lib/dm/item-casts"; import { casterStateProblem } from "@/lib/dm/cast-rules"; import { afflictCondition, afflictionConditionsFor } from "@/lib/dm/afflictions"; import type { CharacterSheet, EquipmentItem } from "@/lib/schemas/sheet"; -import { rollCard } from "@/lib/dm/roll-card"; +import { rollCard, sourceDamage } from "@/lib/dm/roll-card"; +import { itemSource } from "@/lib/roll-sources"; import type { ToolError } from "@/lib/dm/tool-errors"; import { textKey } from "@/lib/language/text-logic"; import { hasItemTag, itemRow, type TaggedItem } from "@/lib/srd/item-tags"; @@ -277,7 +278,8 @@ export function applyConsumable( return "error" in applied ? { effect: `No effect: ${String(applied.error)}` } : { effect: `${sheet.name} can fly at ${feet} feet, and hover, for an hour; if the hour ends aloft they fall.` }; } case "poison": { - const damage = rollCard(campaign, null, sheet.id, "damage", `${itemName}: it was poison`, "3d6", null); + // Nobody rolled it: the roll is the draught's, and the drinker its target. + const damage = sourceDamage(campaign, null, itemSource(itemName), { characterId: sheet.id, names: [sheet.name] }, { dice: "3d6", type: "poison" }); const hurt = applyPcDamage(campaign, turnId, sheet, { amount: damage.total, type: "poison", reason }); const save = rollSave(campaign, getSheetById(sheet.id) ?? sheet, 13, `${sheet.name}: CON save vs ${itemName}`); if (save.success) { @@ -313,7 +315,7 @@ function poisonCourse(campaign: Campaign, turnId: string, sheetId: string, itemN break; } rounds += 1; - const hit = rollCard(campaign, null, before.id, "damage", `${itemName}: the poison, turn ${rounds}`, `${dice}d6`, null); + const hit = sourceDamage(campaign, null, itemSource(itemName), { characterId: before.id, names: [before.name] }, { note: `turn ${rounds}`, dice: `${dice}d6`, type: "poison" }); dealt += hit.total; applyPcDamage(campaign, turnId, before, { amount: hit.total, type: "poison", reason: itemName }); const after = getSheetById(sheetId); diff --git a/src/lib/dm/encounter-summary.ts b/src/lib/dm/encounter-summary.ts index 46f1f3c930..c260ad4786 100644 --- a/src/lib/dm/encounter-summary.ts +++ b/src/lib/dm/encounter-summary.ts @@ -24,7 +24,7 @@ export type SummaryRoll = { characterId: string | null; // Who rolled it (src/lib/db/rolls.ts); absent or null, the roll is the // characterId sheet's, as every roll was before it was recorded. - attacker?: { kind: string; id: string; name?: string } | null; + attacker?: { kind: string; id: string | null; name?: string } | null; kind: string; total: number; applied?: boolean; @@ -35,7 +35,7 @@ export type SummaryRoll = { export type SummaryAudit = { characterId: string; kind: string; delta: Record }; // The sheet that made a roll: its attacker when one is recorded (none for -// an enemy's), else the sheet the roll concerns. +// an enemy's, or for a trap's or a fall's), else the sheet the roll concerns. function rollerOf(roll: SummaryRoll): string | null { return roll.attacker ? (roll.attacker.kind === "sheet" ? roll.attacker.id : null) : roll.characterId; } diff --git a/src/lib/dm/enemy-fall.ts b/src/lib/dm/enemy-fall.ts index 05b6464fea..49281bfee6 100644 --- a/src/lib/dm/enemy-fall.ts +++ b/src/lib/dm/enemy-fall.ts @@ -7,8 +7,8 @@ import type { Campaign } from "@/lib/db/campaigns"; import type { DmTurn } from "@/lib/db/dm-turns"; import { getEnemy, patchEnemyConditions, type Encounter, type EncounterEnemy } from "@/lib/db/encounters"; -import { recordRoll } from "@/lib/dm/roll-record"; -import { rollOn } from "@/lib/roll-labels"; +import { sourceDamageThrown } from "@/lib/dm/roll-card"; +import { fallSource } from "@/lib/roll-sources"; import { rollExpression } from "@/lib/dice"; import { applyEnemyDamage, publishEncounter } from "@/lib/dm/enemy-damage"; import { fallingDamageDice } from "@/lib/srd/hazards"; @@ -28,18 +28,8 @@ export function enemyFalls( return { ok: true, name: enemy.displayName, feet, note: "Too short a fall to hurt." }; } const outcome = rollExpression(dice); - recordRoll({ - campaignId: campaign.id, - characterId: null, - requestedBy: "dm", - kind: "damage", - detail: rollOn(`${feet} ft fall (${dice} bludgeoning)`, [enemy.displayName]), - result: outcome, - attacker: null, - turn, - // Thrown here, on the server's dice. - landing: null, - }); + // Nobody made it: the roll names the fall. + sourceDamageThrown(campaign, turn, fallSource(), { names: [enemy.displayName] }, { note: `${feet} ft`, dice, type: "bludgeoning" }, outcome); const applied = applyEnemyDamage( campaign, turn, diff --git a/src/lib/dm/enemy-trap.ts b/src/lib/dm/enemy-trap.ts index a067fb5fc6..bf4e2c760d 100644 --- a/src/lib/dm/enemy-trap.ts +++ b/src/lib/dm/enemy-trap.ts @@ -29,11 +29,12 @@ import { bindsWorthResisting } from "@/lib/dm/legendary-logic"; import { enemyExhaustion } from "@/lib/dm/monster-abilities"; import { rollCharacterCheck } from "@/lib/dm/contest-roll"; import { critDamageExpression } from "@/lib/dm/encounter-logic"; -import { dmRoll, rollCard } from "@/lib/dm/roll-card"; +import { dmRoll, sourceAttack, sourceDamage } from "@/lib/dm/roll-card"; +import type { RollSource } from "@/lib/db/rolls"; +import { trapSource } from "@/lib/roll-sources"; import { trapHoldOn } from "@/lib/dm/trap-escape"; import { toolError, type ToolError, type ToolResult } from "@/lib/dm/tool-errors"; import { fieldedSheets } from "@/lib/dm/roster"; -import { rollOn } from "@/lib/roll-labels"; import { abilityMod } from "@/lib/srd"; import type { TrapSpec } from "@/lib/srd/trap-specs"; import type { CharacterSheet } from "@/lib/schemas/sheet"; @@ -87,6 +88,9 @@ export function springOnEnemy( trap: TrapSpec, from: { fromX?: number; fromY?: number } = {}, lasting: "trap" | "saveEnds" = "trap", + // What its rolls name as their source: the trap, unless the caller sprang + // something else through here (a hazard the GM named: hazard-tools.ts). + by: RollSource = trapSource(name), ): Record { const { campaign, turn, encounter, sheets, sheetsById } = ctx; const live = () => getEnemy(start.id) ?? start; @@ -120,7 +124,8 @@ export function springOnEnemy( if (trap.attackBonus !== undefined) { const ac = enemyAcWithEffects(campaign.id, live()); const sign = trap.attackBonus >= 0 ? "+" : "-"; - const attack = rollCard(campaign, turn, null, "attack", rollOn(`${name} attacks (vs AC ${ac})`, [start.displayName]), `1d20${sign}${Math.abs(trap.attackBonus)}`, null); + // The trap's own roll: it is named in front, and the creature is its target. + const attack = sourceAttack(campaign, turn, by, { name: start.displayName }, ac, `1d20${sign}${Math.abs(trap.attackBonus)}`); const hit = attack.crit !== "nat1" && (attack.crit === "nat20" || attack.total >= ac); if (!hit) { return { name: start.displayName, hit: false, note: `${name} misses ${start.displayName} (${attack.crit === "nat1" ? "a natural 1" : `${attack.total} vs AC ${ac}`}).` }; @@ -141,7 +146,7 @@ export function springOnEnemy( multiplyNumeric: campaign.gameSettings?.variantRules?.criticalDamageMods, }) : part.dice; - const amount = /^\d+$/.test(dice) ? Number(dice) : rollCard(campaign, turn, null, "damage", rollOn(`${name} (${dice} ${part.type})`, [start.displayName]), dice, null).total; + const amount = /^\d+$/.test(dice) ? Number(dice) : sourceDamage(campaign, turn, by, { names: [start.displayName] }, { dice, type: part.type }).total; if (amount > 0) { lines.push(`${land(amount, part.type)} ${part.type}.`); } @@ -172,7 +177,7 @@ export function springOnEnemy( } const hpBefore = live().currentHp; if (trap.damage && (!save.success || halfOnSave)) { - const rolled = rollCard(campaign, turn, null, "damage", rollOn(`${name} (${trap.damage.dice} ${trap.damage.type})`, [start.displayName]), trap.damage.dice, null).total; + const rolled = sourceDamage(campaign, turn, by, { names: [start.displayName] }, { dice: trap.damage.dice, type: trap.damage.type }).total; const amount = save.success ? Math.floor(rolled / 2) : rolled; if (amount > 0) { lines.push(`${land(amount, trap.damage.type)} ${trap.damage.type}${save.success ? " (half, on the save)" : ""}.`); @@ -230,7 +235,7 @@ export function enemyTrapEscape(campaign: Campaign, turn: DmTurn, enemy: Encount const escaped = total >= hold.dc; let bitten = 0; if (!escaped && hold.hurts) { - bitten = rollCard(campaign, turn, null, "damage", rollOn(`${hold.trap} (${hold.hurts.dice} ${hold.hurts.type})`, [enemy.displayName]), hold.hurts.dice, null).total; + bitten = sourceDamage(campaign, turn, trapSource(hold.trap), { names: [enemy.displayName] }, { dice: hold.hurts.dice, type: hold.hurts.type }).total; if (bitten > 0) { // The party, for the XP if the bite ends the fight. const party = fieldedSheets(campaign); diff --git a/src/lib/dm/genre-a-cyberpunk-defenses.ts b/src/lib/dm/genre-a-cyberpunk-defenses.ts index 0e6ea8f4cc..dddea629ce 100644 --- a/src/lib/dm/genre-a-cyberpunk-defenses.ts +++ b/src/lib/dm/genre-a-cyberpunk-defenses.ts @@ -25,7 +25,7 @@ import type { Campaign } from "@/lib/db/campaigns"; import type { DmTurn } from "@/lib/db/dm-turns"; import { getActiveEncounter, getEnemy, type EncounterEnemy } from "@/lib/db/encounters"; import { hurtEnemy } from "@/lib/dm/spell-aura"; -import { rollCard } from "@/lib/dm/roll-card"; +import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import { getSheetById, listSheets } from "@/lib/db/sheets"; import { withinFeet } from "@/lib/dm/authored-saves"; import { activeAuthored, type AuthoredSheet } from "@/lib/srd/authored-effects"; @@ -71,6 +71,6 @@ export function counterIntrusion(campaign: Campaign, turn: DmTurn | null, sheet: if (!encounter || live.status !== "alive" || !holdsFeature(sheet, COUNTER_INTRUSION)) { return null; } - const amount = rollCard(campaign, turn, sheet.id, "damage", `${COUNTER_INTRUSION}: ${live.displayName}`, "2d8", null).total; + const amount = rollCard(campaign, turn, sheet.id, "damage", `${COUNTER_INTRUSION}: ${live.displayName}`, "2d8", sheetAttacker(sheet)).total; return `${COUNTER_INTRUSION}: ${hurtEnemy(campaign, encounter, live, amount, "psychic", COUNTER_INTRUSION)}`; } diff --git a/src/lib/dm/genre-a-cyberpunk-spends.ts b/src/lib/dm/genre-a-cyberpunk-spends.ts index a4bb125982..ff463bec6e 100644 --- a/src/lib/dm/genre-a-cyberpunk-spends.ts +++ b/src/lib/dm/genre-a-cyberpunk-spends.ts @@ -24,7 +24,7 @@ import { patchSheetAudited } from "@/lib/dm/audited-patch"; import { withinFeet } from "@/lib/dm/authored-saves"; import { riggerDrones } from "@/lib/dm/genre-a-summons"; import { hurtEnemy } from "@/lib/dm/spell-aura"; -import { rollCard } from "@/lib/dm/roll-card"; +import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import { attacksAllowedFor, budgetFor, storeBudget } from "@/lib/dm/turn-budget"; import { conditionTurnShape } from "@/lib/srd/condition-effects"; import { matchWeapon } from "@/lib/srd/weapons"; @@ -129,7 +129,7 @@ function whirl({ campaign, sheet, label }: Ctx): Out { } const mods = computeSheetDerived(sheet).abilityMods; const mod = weapon.finesse ? Math.max(mods.str, mods.dex) : mods.str; - const rolled = rollCard(campaign, null, sheet.id, "damage", `${label} (${weapon.name})`, mod ? `${weapon.dice}${mod > 0 ? "+" : ""}${mod}` : weapon.dice, null).total; + const rolled = rollCard(campaign, null, sheet.id, "damage", `${label} (${weapon.name})`, mod ? `${weapon.dice}${mod > 0 ? "+" : ""}${mod}` : weapon.dice, sheetAttacker(sheet)).total; storeBudget(encounter, { ...budget, actionUsed: true, attacksMade: budget.attacksMade + 1 }); const lines = foes.map((enemy) => hurtEnemy(campaign, getActiveEncounter(campaign.id) ?? encounter, getEnemy(enemy.id) ?? enemy, Math.max(0, rolled), weapon.type, label, true)); return { result: { applied: lines, damage: rolled } }; diff --git a/src/lib/dm/genre-a-horror-casts.ts b/src/lib/dm/genre-a-horror-casts.ts index 046ca7a7a4..b0e4fb103e 100644 --- a/src/lib/dm/genre-a-horror-casts.ts +++ b/src/lib/dm/genre-a-horror-casts.ts @@ -9,7 +9,7 @@ import { getSheetById, patchSheet } from "@/lib/db/sheets"; import { publishPersisted } from "@/lib/events"; import { applyPcDamage } from "@/lib/dm/pc-damage"; -import { rollCard } from "@/lib/dm/roll-card"; +import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import type { SpendContext } from "@/lib/dm/authored-spend-effects"; import type { ToolError } from "@/lib/dm/tool-errors"; import type { SpendDoes } from "@/lib/srd/authored-effects-types"; @@ -30,7 +30,7 @@ export function layCastMark(ctx: SpendContext, does: Extract = {}; if (args.damage && args.damageType) { - const rolled = rollCard(campaign, turn, sheet.id, "damage", `${sheet.name}: ${what}`.slice(0, 120), args.damage, null); + const rolled = rollCard(campaign, turn, sheet.id, "damage", what.slice(0, 120), args.damage, sheetAttacker(sheet)); Object.assign(result, applyEnemyDamage(campaign, turn, encounter, enemy, rolled.total, sheets, sheetsById, args.damageType)); landed.push(`${rolled.total} ${args.damageType} damage (${args.damage})`); } diff --git a/src/lib/dm/invoke-roll.ts b/src/lib/dm/invoke-roll.ts index a14e16dc73..9d16122643 100644 --- a/src/lib/dm/invoke-roll.ts +++ b/src/lib/dm/invoke-roll.ts @@ -12,6 +12,8 @@ // digital, an initiative roll feeds the encounter, and a damage roll aimed at // an enemy applies itself. import { recordRoll } from "@/lib/dm/roll-record"; +import { cardRoller } from "@/lib/dm/roll-card"; +import { kindAndRoller } from "@/lib/db/rolls"; import { beforeRollWords, ownBeforeRollChoices } from "@/lib/dm/before-roll-logic"; import { recordRequestedSave } from "@/lib/dm/last-save"; import { afterRollOptions, canWaitOnRoll } from "@/lib/dm/after-roll-logic"; @@ -412,13 +414,13 @@ export function handleRequestRoll( campaignId, characterId: sheet?.id ?? null, requestedBy: "dm", - kind: args.kind, + // Free text about the sheet's own roll: its owner reads as the roller, + // and an attack or damage roll says so. With no sheet it is the GM's. + ...kindAndRoller(args.kind, null, cardRoller(sheet)), detail: resolved.detail, advantage: args.advantage ?? "none", dc: args.dc ?? null, result: outcome, - // Free text about the sheet's own roll: its owner reads as the roller. - attacker: null, // A screen is a person's tool; the model's rolls are the table's. visibility: model ? "public" : args.visibility ?? "public", turn, diff --git a/src/lib/dm/last-hit.ts b/src/lib/dm/last-hit.ts index 6addca6365..f11a0f5730 100644 --- a/src/lib/dm/last-hit.ts +++ b/src/lib/dm/last-hit.ts @@ -36,7 +36,8 @@ import { getActiveEncounter, listEnemies, orderEntryId, turnKey, type Encounter, import { getSheetById, listSheets } from "@/lib/db/sheets"; import { currentTurnId, owningTurnOf } from "@/lib/dm/job-control"; import type { RollResult, Advantage } from "@/lib/dice"; -import { listRecentRolls, type RollAttacker } from "@/lib/db/rolls"; +import { listRecentRolls, type HazardKind, type RollAttacker, type RollSource } from "@/lib/db/rolls"; +import { fallSource, recordSource } from "@/lib/roll-sources"; import { spellMechanicsFor } from "@/lib/content"; import type { CharacterSheet } from "@/lib/schemas/sheet"; import { wardOf } from "@/lib/dm/arcane-ward"; @@ -226,7 +227,9 @@ export type LastHit = { undo?: Array<{ turnId: string; was: LastHit }>; // Who made it: an enemy, a character fighting on the other side (a // turncoat's pc_attack, issue 503), or a hazard, which is nobody. - attacker: { kind: "enemy" | "sheet" | "hazard"; id: string | null; name: string }; + // A hazard says what it is (src/lib/roll-sources.ts), as its roll does; a + // record written before that was kept says nothing. + attacker: { kind: "enemy" | "sheet" | "hazard"; id: string | null; name: string; hazard?: HazardKind }; attack: string; type: string; ranged: boolean; @@ -267,12 +270,14 @@ export type LastHit = { }; // Who rolls the recorded attack again (Protection and its kin): the enemy -// that made it; a hazard is nobody. -export function rerollAttacker(record: LastHit): RollAttacker | null { +// that made it. A record with no creature behind it hands back its source, +// which no attack on record has today (a hazard's records are falls, effects +// and missiles): the roll must still name someone. +export function rerollAttacker(record: LastHit): RollAttacker { const id = attackerFoeId(record); return id && (record.attacker.kind === "enemy" || record.attacker.kind === "sheet") ? { kind: record.attacker.kind, id, name: record.attacker.name } - : null; + : recordSource(record.attacker); } // The creature that made the recorded attack, by combatant id (an enemy row @@ -975,7 +980,8 @@ export function recordFall( turn: encounter ? turnKey(encounter) : "", ...(encounter && enemiesTakingTurns(encounter) ? { enemyTurns: true } : {}), ...rollingTurn(), - attacker: { kind: "hazard", id: null, name: "the fall" }, + // The same source the fall's own roll names. + attacker: fallSource(), attack: "falling", type: "bludgeoning", ranged: false, @@ -1003,7 +1009,9 @@ export function openEffect(campaignId: string, characterId: string) { const startedAt = nowIso(); const openSeq = latestSeq(campaignId); return { - close(what: { raw: number; type: string; name: string }) { + // `by` is the source of the damage, built by the door that deals it + // (src/lib/roll-sources.ts): the one its own roll names, where it rolled. + close(what: { raw: number; type: string; by: RollSource }) { const now = getSheetById(characterId); if (!before || !now || what.raw <= 0) { return; @@ -1016,7 +1024,7 @@ export function openEffect(campaignId: string, characterId: string) { turn: encounter ? turnKey(encounter) : "", ...(encounter && enemiesTakingTurns(encounter) ? { enemyTurns: true } : {}), ...rollingTurn(), - attacker: { kind: "hazard", id: null, name: what.name }, + attacker: what.by, attack: "damage", type: what.type, ranged: false, diff --git a/src/lib/dm/mt-fb-arrow-riders.ts b/src/lib/dm/mt-fb-arrow-riders.ts index 0b3a9fb7f3..cc84c750c8 100644 --- a/src/lib/dm/mt-fb-arrow-riders.ts +++ b/src/lib/dm/mt-fb-arrow-riders.ts @@ -19,7 +19,8 @@ import type { Campaign } from "@/lib/db/campaigns"; import { getActiveEncounter, getEnemy, patchEnemyConditions, turnKey } from "@/lib/db/encounters"; import { removeConditions, type ConditionMetaMap } from "@/lib/dm/condition-logic"; import { publishEncounter } from "@/lib/dm/enemy-damage"; -import { rollCard } from "@/lib/dm/roll-card"; +import { getSheetById } from "@/lib/db/sheets"; +import { castersDamage } from "@/lib/dm/roll-card"; import { hurtEnemy } from "@/lib/dm/spell-aura"; import { isConditionNamed } from "@/lib/srd/feature-names"; import { BEGUILED, GRASPING } from "@/lib/srd/mt-fb-arcane-shot"; @@ -41,7 +42,11 @@ export function bramblesAfterMove(campaign: Campaign, encounterId: string, enemy return []; } patchEnemyConditions(enemy.id, enemy.conditions, { ...meta, [held]: { ...meta[held], tornOn: key } } as typeof enemy.conditionMeta); - const rolled = rollCard(campaign, null, null, "damage", `${enemy.displayName}: the Grasping Arrow's brambles as it moves`, "2d6", null).total; + // The condition keeps whose arrow it was (authored-spend-effects.ts + // enemyCondition): the brambles are the archer's roll. + const by = meta[held]?.source; + const archer = typeof by === "string" ? getSheetById(by) : null; + const rolled = castersDamage(campaign, null, archer, `${enemy.displayName}: the Grasping Arrow's brambles as it moves`, "Grasping Arrow", enemy.displayName, { dice: "2d6", type: "slashing" }).total; return [hurtEnemy(campaign, encounter, getEnemy(enemyId) ?? enemy, rolled, "slashing", "the Grasping Arrow's brambles")]; } diff --git a/src/lib/dm/mutations.ts b/src/lib/dm/mutations.ts index dccda921df..3d8984e9d2 100644 --- a/src/lib/dm/mutations.ts +++ b/src/lib/dm/mutations.ts @@ -136,6 +136,7 @@ import { healCeiling } from "@/lib/dm/afflictions"; import { spreadGear } from "@/lib/dm/gear-zones"; import { actorOfCall, calledOnItsOwn, withActor } from "@/lib/dm/acting-party"; import { openEffect } from "@/lib/dm/last-hit"; +import { harmSource, UNNAMED_HARM } from "@/lib/roll-sources"; // DM stat authority: the model changes sheets ONLY through these tools. @@ -939,7 +940,9 @@ function dmMutation( noCreature: true, reason, }); - effect?.close({ raw: Math.min(amount, 200), type: args.type ?? "", name: args.spell?.trim() || reason || "the harm" }); + // The source the harm's own dice name, when the model sent dice + // (ai-gate.ts): both are built from the call's spell and reason. + effect?.close({ raw: Math.min(amount, 200), type: args.type ?? "", by: harmSource(args.spell, reason, UNNAMED_HARM) }); return { result: landed }; } case "heal": { diff --git a/src/lib/dm/object-damage.ts b/src/lib/dm/object-damage.ts index d2f92ea73f..8cf19a35b4 100644 --- a/src/lib/dm/object-damage.ts +++ b/src/lib/dm/object-damage.ts @@ -21,7 +21,7 @@ import { getClock, setClock } from "@/lib/db/clock"; import { getCurrentLocation } from "@/lib/db/locations"; import type { ObjectRecord } from "@/lib/dm/march-state"; import type { RollAttacker } from "@/lib/db/rolls"; -import { rollAgainst, rollOn } from "@/lib/roll-labels"; +import { rollAgainst } from "@/lib/roll-labels"; import { getSheetById, listSheets } from "@/lib/db/sheets"; import { d20Expression, isValidExpression, rollExpression, type Advantage, type RollResult } from "@/lib/dice"; import { ragingMeleeBonus, type AttackProfile } from "@/lib/dm/attack-logic"; @@ -33,6 +33,8 @@ import { hasHalflingLuck } from "@/lib/srd/feature-effects"; import type { CharacterSheet } from "@/lib/schemas/sheet"; import { rollCharacterD20 } from "@/lib/dm/character-roll"; import { recordRoll } from "@/lib/dm/roll-record"; +import { sourceDamageThrown } from "@/lib/dm/roll-card"; +import { harmSource } from "@/lib/roll-sources"; import { critDamageExpression } from "@/lib/dm/encounter-logic"; import { buildAttackProfile } from "@/lib/dm/pc-attack-profile"; import { objectProfile, type ObjectMaterial, type ObjectSize } from "@/lib/srd/objects"; @@ -86,10 +88,9 @@ function keyOf(campaignId: string, name: string): string { // A roll at an object, on record. A character's own attack and damage come // through rollCharacterD20, so the door reads whose dice they were: entered -// at the table, they are stored and sent as the player's. `thrownHere` is for -// harm no character dealt, which the server throws where it stands. -function cardRoll(campaign: Campaign, turn: DmTurn | null, characterId: string | null, kind: "attack" | "damage", detail: string, result: RollResult, attacker: RollAttacker | null, thrownHere = false) { - recordRoll({ campaignId: campaign.id, characterId, requestedBy: "dm", kind, detail, result, attacker, turn, ...(thrownHere ? { landing: null } : {}) }); +// at the table, they are stored and sent as the player's. +function cardRoll(campaign: Campaign, turn: DmTurn | null, characterId: string | null, kind: "attack" | "damage", detail: string, result: RollResult, attacker: RollAttacker) { + recordRoll({ campaignId: campaign.id, characterId, requestedBy: "dm", kind, detail, result, attacker, turn }); } // What the clock keeps of a named object, or null for one never named. @@ -244,9 +245,10 @@ export function damageObject( dealt = Number(args.damage.trim()); } else if (isValidExpression(args.damage)) { const rolled = rollExpression(args.damage); - // Harm no character dealt (a hazard, a falling block): nobody's roll. + // Harm no character dealt (a hazard, a falling block): the roll of + // the words the GM gave for it, else the GM's own dice. if (campaign) { - cardRoll(campaign, turn, null, "damage", rollOn(type || "damage", [args.name ?? "an object"]), rolled, null, true); + sourceDamageThrown(campaign, turn, harmSource(null, args.reason), { names: [args.name ?? "an object"] }, { dice: args.damage.trim(), type: type || undefined }, rolled); } dealt = rolled.total; } else { diff --git a/src/lib/dm/pending-roll-land.ts b/src/lib/dm/pending-roll-land.ts index f43faf6981..f72e8dfe2c 100644 --- a/src/lib/dm/pending-roll-land.ts +++ b/src/lib/dm/pending-roll-land.ts @@ -16,7 +16,8 @@ import { publicPendingRoll, type PendingRoll, } from "@/lib/db/dm-turns"; -import { insertRoll, markRollSpent, type StoredRoll } from "@/lib/db/rolls"; +import { insertRoll, kindAndRoller, markRollSpent, type StoredRoll } from "@/lib/db/rolls"; +import { cardRoller } from "@/lib/dm/roll-card"; import { getSheetById } from "@/lib/db/sheets"; import { settleAttackDie } from "@/lib/dm/forced-save"; import { rollsCanWait } from "@/lib/dm/after-roll"; @@ -133,19 +134,20 @@ function landOne(campaign: Campaign, pending: PendingRoll, thrown: RollResult, l campaignId, characterId: pending.characterId, requestedBy: "player", - kind: pending.kind, + // A parked pc_attack roll (to-hit or damage) is the PC's own; any other + // parked roll is a roll tool's free text about its sheet, whose attack or + // damage roll is that character's too. + ...kindAndRoller( + pending.kind, + pending.attack && pending.characterId ? { kind: "sheet", id: pending.characterId, name: pending.attack.attacker } : null, + cardRoller(pending.characterId ? getSheetById(pending.characterId) : null), + ), // Once any face was drawn by the server the "(physical)" label would // overclaim, so a mixed or fully digital submission keeps the plain detail. detail: landing.physical ? `${pending.detail || pending.kind} (physical)`.trim() : pending.detail, advantage: pending.advantage, dc: pending.dc, result: outcome, - // A parked pc_attack roll (to-hit or damage) is the PC's own; any other - // parked roll is a roll tool's free text about its sheet. - attacker: - pending.attack && pending.characterId - ? { kind: "sheet", id: pending.characterId, name: pending.attack.attacker } - : null, // A roll the DM asked for behind the screen lands behind it. visibility: pending.visibility, }); diff --git a/src/lib/dm/pet-save.ts b/src/lib/dm/pet-save.ts index ce67842c58..e6730162ca 100644 --- a/src/lib/dm/pet-save.ts +++ b/src/lib/dm/pet-save.ts @@ -22,10 +22,9 @@ import { sparedByIntelligence } from "@/lib/dm/spell-spares-logic"; import type { Campaign } from "@/lib/db/campaigns"; import type { DmTurn } from "@/lib/db/dm-turns"; -import type { RollAttacker } from "@/lib/db/rolls"; import { getSheetById } from "@/lib/db/sheets"; import { isValidExpression } from "@/lib/dice"; -import { rollAgainst } from "@/lib/roll-labels"; +import { castSource } from "@/lib/roll-sources"; import type { SaveAbility } from "@/lib/bestiary/statblock"; import { spellFactsFor, spellMechanicsFor } from "@/lib/content"; import type { CharacterSheet, SheetPet } from "@/lib/schemas/sheet"; @@ -39,7 +38,7 @@ import { layPetFailedSave, layPetSpellConditions, type PetLaid } from "@/lib/dm/ import { petDamageShare } from "@/lib/dm/pet-save-logic"; import { petIntelligence, rollPetSave, type PetSave } from "@/lib/dm/pet-save-roll"; import { findPet, hurtPet, noPet } from "@/lib/dm/pet-tools"; -import { rollCard } from "@/lib/dm/roll-card"; +import { castDamage, enemyAttacker } from "@/lib/dm/roll-card"; import { spellAuthorsFor } from "@/lib/dm/spell-authors"; import type { ToolResult } from "@/lib/dm/tool-errors"; @@ -245,8 +244,10 @@ export function castAtPet(campaign: Campaign, turn: DmTurn, args: CastAtPetArgs, ...(use?.corrections.length ? { corrected: use.corrections } : {}), }; if (damage) { - const caster: RollAttacker | null = use ? { kind: "enemy", id: use.enemy.id, name: use.enemy.displayName } : null; - const outcome = rollCard(campaign, turn, null, "damage", rollAgainst(castName || args.source || "Effect", pet.name), damage, caster); + // A hazard with no creature behind it is the roll of the source the GM + // named, else of its spell, else the GM's own dice (cast-at-player.ts). + const caster = use ? enemyAttacker(use.enemy) : castSource(args.source, castName); + const outcome = castDamage(campaign, turn, caster, castName, { name: pet.name }, { dice: damage, type: damageType }); // A creature's effect of two types: each share meets the pet's defenses // on its own (src/lib/dm/cast-at-player.ts does the same for a character). const secondType = byBlock ? use?.secondType : undefined; diff --git a/src/lib/dm/roll-card.ts b/src/lib/dm/roll-card.ts index b407fd2779..c01dbc1dcc 100644 --- a/src/lib/dm/roll-card.ts +++ b/src/lib/dm/roll-card.ts @@ -11,18 +11,42 @@ import { allocateSeq, type Campaign } from "@/lib/db/campaigns"; import type { DmTurn } from "@/lib/db/dm-turns"; -import { revealRollRow, type RollAttacker, type RollKind } from "@/lib/db/rolls"; -import { rollExpression, type RollOptions } from "@/lib/dice"; +import { revealRollRow, type RollAttacker, type RollKind, type RollSource } from "@/lib/db/rolls"; +import { rollExpression, type RollOptions, type RollResult } from "@/lib/dice"; import type { RollTag } from "@/lib/dice-script-logic"; import { recordRoll } from "@/lib/dm/roll-record"; import { publishWithSeq } from "@/lib/events"; +import { attackOn, rollAgainst, thrownOn, type Thrown } from "@/lib/roll-labels"; +import { effectSource, gmSource } from "@/lib/roll-sources"; // `turn` is the DM turn the card belongs to, when the site holds one; inside // a GM call the card joins the call's own turn whatever is handed in, and a roll // outside one with no turn (the clock's) stands alone. `attacker` -// is who made an attack or damage roll (null: nobody, or not a combat roll). +// is who made an attack or damage roll, which always names one: a creature, +// or the source of a roll nobody at the table made (src/lib/roll-sources.ts). +// Null is for the other kinds of roll alone. // A flat amount (Aura of Conquest's half a level) rolls no dice and gets no // card. +export function rollCard( + campaign: Pick, + turn: DmTurn | null, + characterId: string | null, + kind: "attack" | "damage", + detail: string, + expression: string, + attacker: RollAttacker, + options?: RollOptions, +): RollResult; +export function rollCard( + campaign: Pick, + turn: DmTurn | null, + characterId: string | null, + kind: Exclude, + detail: string, + expression: string, + attacker: RollAttacker | null, + options?: RollOptions, +): RollResult; export function rollCard( campaign: Pick, turn: DmTurn | null, @@ -33,7 +57,7 @@ export function rollCard( attacker: RollAttacker | null, // How the dice are thrown (an Empowered Spell's rerolls: src/lib/dice.ts). options: RollOptions = {}, -) { +): RollResult { const outcome = rollExpression(expression, undefined, options); if (!outcome.terms.some((term) => term.kind === "dice")) { return outcome; @@ -42,10 +66,10 @@ export function rollCard( campaignId: campaign.id, characterId, requestedBy: "dm", - kind, + // The signatures above hold an attack or damage roll to a named roller. + ...(kind === "attack" || kind === "damage" ? { kind, attacker: attacker as RollAttacker } : { kind, attacker }), detail: detail.slice(0, 120), result: outcome, - attacker, turn, // Thrown here, on the server's dice. landing: null, @@ -59,6 +83,112 @@ export const sheetAttacker = (sheet: { id: string; name: string }): RollAttacker // Who an enemy is, as a roll's attacker. export const enemyAttacker = (enemy: { id: string; displayName: string }): RollAttacker => ({ kind: "enemy", id: enemy.id, name: enemy.displayName }); +// Who rolled a roll card's own attack or damage dice, or the roll tools' +// free text: the character they were asked of, else the GM, whose roll then +// keeps the words the GM typed for it. +export const cardRoller = (sheet: { id: string; name: string } | null | undefined): RollAttacker => (sheet ? sheetAttacker(sheet) : gmSource()); + +// What a source's roll threw, with its dice. +type Dice = Thrown & { dice: string }; + +// The damage of a roll nobody at the table made (issue 915, ruling 2), on +// record. The source is the roller and goes in front of the card, so no site +// writes this roll's words: they are what was thrown and on whom +// (roll-labels.ts thrownOn), and never the source a second time. +// `characterId` is the character it lands on, when it lands on one. +export function sourceDamage( + campaign: Pick, + turn: DmTurn | null, + source: RollSource, + on: { characterId?: string | null; names: string[] }, + thrown: Dice, + options?: RollOptions, +): RollResult { + return rollCard(campaign, turn, on.characterId ?? null, "damage", thrownOn(thrown, on.names), thrown.dice, source, options); +} + +// The same, for a site that has thrown the dice itself (an area's, with its +// own rules for them; a creature's fall). +export function sourceDamageThrown( + campaign: Pick, + turn: DmTurn | null, + source: RollSource, + on: { characterId?: string | null; names: string[] }, + thrown: Dice, + result: RollResult, +): void { + recordRoll({ + campaignId: campaign.id, + characterId: on.characterId ?? null, + requestedBy: "dm", + kind: "damage", + detail: thrownOn(thrown, on.names), + result, + attacker: source, + turn, + // Thrown by its site, on the server's dice. + landing: null, + }); +} + +// A source's attack roll (a trap's dart) against one target's armour. +export function sourceAttack( + campaign: Pick, + turn: DmTurn | null, + source: RollSource, + on: { characterId?: string | null; name: string }, + ac: number, + expression: string, +): RollResult { + return rollCard(campaign, turn, on.characterId ?? null, "attack", attackOn(on.name, ac), expression, source); +} + +// The damage of a spell or effect cast at one target. A creature's cast says +// its spell ("Shaman · Damage (Sacred Flame vs Aria)"). A source's says what +// it throws, as every source's roll does, with the spell in front of the +// dice ("a glyph on the door · Damage (Burning Hands, 3d6 fire on Aria)") +// unless the spell is the source itself. That is decided by what the source +// is, never by reading its words: a source the GM named in words that say +// the spell too has it said twice, as the GM wrote it. +export function castDamage( + campaign: Pick, + turn: DmTurn | null, + by: RollAttacker, + spell: string | null | undefined, + on: { characterId?: string | null; name: string }, + thrown: Dice, +): RollResult { + if (by.kind !== "hazard") { + return rollCard(campaign, turn, on.characterId ?? null, "damage", rollAgainst(spell || "Effect", on.name), thrown.dice, by); + } + const note = spell && by.hazard !== "effect" ? spell : undefined; + return sourceDamage(campaign, turn, by, { characterId: on.characterId, names: [on.name] }, { ...thrown, note }); +} + +// Later damage of a spell or feature (a curse's rider, a second burn), +// rolled when whoever cast it may have left the table. While the character's +// sheet is there it is their roll, worded as its site words it; a creature +// that cast it (`foe`) rolls it the same way. With neither left, the spell +// is the source, and the card says what it throws. +export function castersDamage( + campaign: Pick, + turn: DmTurn | null, + caster: { id: string; name: string } | null | undefined, + detail: string, + spell: string, + target: string, + thrown: Dice, + foe?: { id: string; displayName: string } | null, +): RollResult { + if (caster) { + return rollCard(campaign, turn, caster.id, "damage", detail, thrown.dice, sheetAttacker(caster)); + } + if (foe) { + return rollCard(campaign, turn, null, "damage", detail, thrown.dice, enemyAttacker(foe)); + } + return sourceDamage(campaign, turn, effectSource(spell), { names: [target] }, thrown); +} + // A roll the players are not shown (an enemy's initiative, its stealth, a // recharge, an NPC's private choice): stored for the DM alone and kept on the // turn, exactly as an enemy's saving throw is (src/lib/dm/forced-save.ts). diff --git a/src/lib/dm/spell-retort.ts b/src/lib/dm/spell-retort.ts index 7b2ae12155..ee5baf62fd 100644 --- a/src/lib/dm/spell-retort.ts +++ b/src/lib/dm/spell-retort.ts @@ -29,7 +29,7 @@ import { BURNING_OIL_DAMAGE, oilCatches } from "@/lib/srd/gear-weapons"; import { applyEnemyDamage, publishEncounter } from "@/lib/dm/enemy-damage"; import { rollEnemySave } from "@/lib/dm/forced-save"; import type { CharacterSheet } from "@/lib/schemas/sheet"; -import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; +import { castersDamage, rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import { rollAgainst } from "@/lib/roll-labels"; import { isConditionNamed, isNamed, nameChoice } from "@/lib/srd/feature-names"; import { textKey } from "@/lib/language/text-logic"; @@ -379,7 +379,7 @@ export function curseBurn( return null; } const caster = getSheetById(casterId); - const rolled = rollCard(campaign, turn, caster?.id ?? null, "damage", rollAgainst("Bestow Curse", enemy.displayName), rider.dice, caster ? sheetAttacker(caster) : null).total; + const rolled = castersDamage(campaign, turn, caster, rollAgainst("Bestow Curse", enemy.displayName), "Bestow Curse", enemy.displayName, { dice: rider.dice, type: rider.type }).total; const applied = applyEnemyDamage(campaign, turn, encounter, enemy, rolled, sheets, sheetsById, rider.type, { magical: true, spell: true }); // The curse's own necrotic killed it (ar-ws-harvest.ts). const onKill = applied.dead ? spellKill(campaign, encounter, enemy, casterId, { spell: "Bestow Curse" }) : []; diff --git a/src/lib/dm/spell-self.ts b/src/lib/dm/spell-self.ts index 966a2af133..a3bab1570d 100644 --- a/src/lib/dm/spell-self.ts +++ b/src/lib/dm/spell-self.ts @@ -17,7 +17,7 @@ import { rollCharacterSave } from "@/lib/dm/forced-save"; import { applyPcDamage } from "@/lib/dm/pc-damage"; import { handleSetCondition } from "@/lib/dm/set-condition"; import type { CharacterSheet } from "@/lib/schemas/sheet"; -import { rollCard } from "@/lib/dm/roll-card"; +import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import { textKey } from "@/lib/language/text-logic"; export const INSANE = "insane (contact other plane)"; @@ -35,7 +35,7 @@ export function casterCost(campaign: Campaign, sheet: CharacterSheet, spell: str if (save.success) { return { casterCost: `${sheet.name}'s mind holds against the other plane (INT save ${save.total} against DC 15).` }; } - const amount = rollCard(campaign, turn, sheet.id, "damage", named, "6d6", null).total; + const amount = rollCard(campaign, turn, sheet.id, "damage", named, "6d6", sheetAttacker(sheet)).total; applyPcDamage(campaign, turn.id, getSheetById(sheet.id) ?? sheet, { amount, type: "psychic", reason: `${named}: the mind recoils` }); const standing = getSheetById(sheet.id); if (standing && !standing.deathSaves?.dead) { diff --git a/src/lib/dm/spell-turn-end.ts b/src/lib/dm/spell-turn-end.ts index b3849f8ae3..5e4e310739 100644 --- a/src/lib/dm/spell-turn-end.ts +++ b/src/lib/dm/spell-turn-end.ts @@ -19,7 +19,7 @@ import type { Campaign } from "@/lib/db/campaigns"; import { closeStandInTurn, openStandInTurn } from "@/lib/db/dm-turns"; -import { getActiveEncounter, patchEnemyConditions, type Encounter, type EncounterEnemy } from "@/lib/db/encounters"; +import { getActiveEncounter, getEnemy, patchEnemyConditions, type Encounter, type EncounterEnemy } from "@/lib/db/encounters"; import { getSheetById } from "@/lib/db/sheets"; import { isSheetFoe } from "@/lib/dm/combat-sides-logic"; import { applyPcDamage } from "@/lib/dm/pc-damage"; @@ -33,7 +33,7 @@ import { rollEnemySave } from "@/lib/dm/forced-save"; import { lastCastSlot } from "@/lib/dm/spell-effects"; import { hurtEnemy } from "@/lib/dm/spell-aura"; import { runningSpellKill } from "@/lib/dm/ar-ws-harvest"; -import { rollCard, sheetAttacker } from "@/lib/dm/roll-card"; +import { castersDamage } from "@/lib/dm/roll-card"; import { rollAgainst } from "@/lib/roll-labels"; import { textKey } from "@/lib/language/text-logic"; import { withActor, withTurnOf } from "@/lib/dm/acting-party"; @@ -63,6 +63,12 @@ function hurtHeld(campaign: Campaign, encounter: Encounter, enemy: EncounterEnem } } +// The creature that laid the mark, when no character did: its later damage +// is that creature's roll (the mark's source is a sheet's id or an enemy's). +function castingFoe(meta: ConditionMeta, caster: { id: string } | null | undefined): EncounterEnemy | null { + return !caster && meta.source ? getEnemy(meta.source) : null; +} + // Acid Arrow's second burn. function acidArrowBurn(campaign: Campaign, enemy: EncounterEnemy, meta: ConditionMeta): string | null { const encounter = getActiveEncounter(campaign.id); @@ -72,7 +78,7 @@ function acidArrowBurn(campaign: Campaign, enemy: EncounterEnemy, meta: Conditio const slot = meta.slotLevel ?? (meta.source ? lastCastSlot(meta.source, "Acid Arrow") : null) ?? 2; const dice = addDice("2d4", "1d4", Math.max(0, slot - 2)); const caster = meta.source ? getSheetById(meta.source) : null; - const burn = rollCard(campaign, null, caster?.id ?? null, "damage", rollAgainst("Acid Arrow (second burn)", enemy.displayName), dice, caster ? sheetAttacker(caster) : null).total; + const burn = castersDamage(campaign, null, caster, rollAgainst("Acid Arrow (second burn)", enemy.displayName), "Acid Arrow", enemy.displayName, { note: "second burn", dice, type: "acid" }, castingFoe(meta, caster)).total; const line = hurtHeld(campaign, encounter, enemy, burn, "acid", "Acid Arrow's acid"); // The burn killed it (Grim Harvest, ar-ws-harvest.ts). return [line, ...runningSpellKill(campaign, encounter, enemy, caster?.id, { spell: "Acid Arrow", slotLevel: slot })].join(" "); @@ -150,7 +156,7 @@ function saveAtTurnEnd(campaign: Campaign, enemy: EncounterEnemy, meta: Conditio if (!dice) { return null; } - const hurt = rollCard(campaign, null, caster?.id ?? null, "damage", rollAgainst(resolved.name, enemy.displayName), dice, caster ? sheetAttacker(caster) : null).total; + const hurt = castersDamage(campaign, null, caster, rollAgainst(resolved.name, enemy.displayName), resolved.name, enemy.displayName, { dice, type: edge.type ?? "psychic" }, castingFoe(meta, caster)).total; return hurtHeld(campaign, encounter, enemy, hurt, edge.type ?? "psychic", resolved.name); } diff --git a/src/lib/dm/spirit-projection.ts b/src/lib/dm/spirit-projection.ts index 03c047bbf9..85abd8ef8b 100644 --- a/src/lib/dm/spirit-projection.ts +++ b/src/lib/dm/spirit-projection.ts @@ -41,7 +41,7 @@ import { applyPcDamage } from "@/lib/dm/pc-damage"; import { currentActor } from "@/lib/dm/acting-party"; import { ownTurnOf } from "@/lib/dm/held-turn"; import { patchSheetAudited } from "@/lib/dm/audited-patch"; -import { enemyAttacker, rollCard } from "@/lib/dm/roll-card"; +import { enemyAttacker, rollCard, sheetAttacker } from "@/lib/dm/roll-card"; import { noneNamed, type ToolResult } from "@/lib/dm/tool-errors"; import { textKey } from "@/lib/language/text-logic"; import type { CharacterSheet } from "@/lib/schemas/sheet"; @@ -185,7 +185,7 @@ export function projectionTurnEnd(campaign: Campaign, combatantIds: string[]): s // spell area's turn-end strike has (zone-triggers.ts). const turn = openStandInTurn(campaign.id); try { - const rolled = rollCard(campaign, turn, sheet.id, "damage", `${sheet.name}: the turn ends inside ${inside.name}`, INSIDE_DAMAGE, null); + const rolled = rollCard(campaign, turn, sheet.id, "damage", `the turn ends inside ${inside.name}`, INSIDE_DAMAGE, sheetAttacker(sheet)); const hurt = applyPcDamage(campaign, turn.id, sheet, { amount: rolled.total, type: "force", reason: `the spirit's turn ended inside ${inside.name}` }); lines.push(`${sheet.name}'s spirit ends its turn inside ${inside.name} and takes ${"error" in hurt ? rolled.total : (hurt.damageApplied ?? rolled.total)} force damage.`); } finally { diff --git a/src/lib/dm/trap-escape.ts b/src/lib/dm/trap-escape.ts index ae38df7cb9..2fc053c994 100644 --- a/src/lib/dm/trap-escape.ts +++ b/src/lib/dm/trap-escape.ts @@ -8,8 +8,8 @@ import { trapAt } from "@/lib/srd/table-hazards"; import type { CharacterSheet } from "@/lib/schemas/sheet"; import type { ToolResult } from "@/lib/dm/tool-errors"; import { applyPcDamage } from "@/lib/dm/pc-damage"; -import { rollCard } from "@/lib/dm/roll-card"; -import { rollOn } from "@/lib/roll-labels"; +import { sourceDamage } from "@/lib/dm/roll-card"; +import { trapSource } from "@/lib/roll-sources"; // A trap's hold on a character (a falling net's restraint): a condition the // trap lays on everyone it catches (conditionsAlways in @@ -64,7 +64,7 @@ export function characterTrapEscape( const escaped = !check.autoFailed && check.total >= hold.dc; // A hunting trap's jaws bite on each failed check (TrapSpec escapeHurts). const bitten = !escaped && hold.hurts - ? rollCard(campaign, turn, sheet.id, "damage", rollOn(`${hold.trap} (${hold.hurts.dice} ${hold.hurts.type})`, [sheet.name]), hold.hurts.dice, null).total + ? sourceDamage(campaign, turn, trapSource(hold.trap), { characterId: sheet.id, names: [sheet.name] }, { dice: hold.hurts.dice, type: hold.hurts.type }).total : 0; if (bitten > 0 && hold.hurts) { applyPcDamage(campaign, turn.id, getSheetById(sheet.id) ?? sheet, { amount: bitten, type: hold.hurts.type, noCreature: true, reason: hold.trap }); diff --git a/src/lib/dm/trap-run.ts b/src/lib/dm/trap-run.ts index bc90a97039..a7d272bc9b 100644 --- a/src/lib/dm/trap-run.ts +++ b/src/lib/dm/trap-run.ts @@ -7,8 +7,8 @@ import { afflictCondition } from "@/lib/dm/afflictions"; import { canonicalCondition } from "@/lib/dm/set-condition"; import { wakesOnDamage } from "@/lib/dm/condition-logic"; import { openFall } from "@/lib/dm/last-hit"; -import { rollCard } from "@/lib/dm/roll-card"; -import { rollOn } from "@/lib/roll-labels"; +import { sourceAttack, sourceDamage } from "@/lib/dm/roll-card"; +import { fallSource, trapSource } from "@/lib/roll-sources"; import { acWithEffects } from "@/lib/dm/ac-effects"; import { critDamageExpression } from "@/lib/dm/encounter-logic"; import { wornArmorTurnsCrits } from "@/lib/srd/armor"; @@ -43,7 +43,9 @@ export function springTrapOn( if (trap.attackBonus !== undefined) { const ac = acWithEffects(campaign.id, sheet()); const sign = trap.attackBonus >= 0 ? "+" : "-"; - const attack = rollCard(campaign, turn, victim.id, "attack", rollOn(`${name} attacks (vs AC ${ac})`, [victim.name]), `1d20${sign}${Math.abs(trap.attackBonus)}`, null); + // The trap's own roll: it is named in front, and the character is its + // target, not its roller. + const attack = sourceAttack(campaign, turn, trapSource(name), { characterId: victim.id, name: victim.name }, ac, `1d20${sign}${Math.abs(trap.attackBonus)}`); const natural = attack.crit; const hit = natural !== "nat1" && (natural === "nat20" || attack.total >= ac); if (!hit) { @@ -61,7 +63,7 @@ export function springTrapOn( if (trap.fallFeet) { const dice = fallingDamageDice(trap.fallFeet); if (dice !== "0") { - const rolled = rollCard(campaign, turn, victim.id, "damage", rollOn(`${trap.fallFeet} ft fall into ${name} (${dice} bludgeoning)`, [victim.name]), dice, null); + const rolled = sourceDamage(campaign, turn, fallSource(), { characterId: victim.id, names: [victim.name] }, { note: `${trap.fallFeet} ft into ${name}`, dice, type: "bludgeoning" }); const fall = openFall(campaign.id, victim.id); applyPcDamage(campaign, turn.id, sheet(), { noCreature: true, amount: rolled.total, type: "bludgeoning", knocksProne: true, reason: name }); fall.close(rolled.total); @@ -81,7 +83,7 @@ export function springTrapOn( const dice = critical(part.dice); const amount = /^\d+$/.test(dice) ? Number(dice) - : rollCard(campaign, turn, victim.id, "damage", rollOn(`${name} (${dice} ${part.type})`, [victim.name]), dice, null).total; + : sourceDamage(campaign, turn, trapSource(name), { characterId: victim.id, names: [victim.name] }, { dice, type: part.type }).total; if (amount > 0) { applyPcDamage(campaign, turn.id, sheet(), { noCreature: true, amount, type: part.type, reason: name }); lines.push(`${amount} ${part.type}.`); @@ -119,6 +121,8 @@ export function springTrapOn( }), sheets, sheetsById, + // The same trap its darts were. + trapSource(name), ); // What a failed save leaves is the trap's, for as long as the trap says, // with the trap as its source (a hunting trap's jaws are then the hold its diff --git a/src/lib/dm/zone-quake.ts b/src/lib/dm/zone-quake.ts index 4382e8cefd..9a5aa85948 100644 --- a/src/lib/dm/zone-quake.ts +++ b/src/lib/dm/zone-quake.ts @@ -36,8 +36,8 @@ import { applyPcDamage } from "@/lib/dm/pc-damage"; import { handleSetCondition } from "@/lib/dm/set-condition"; import { breakConcentration, clearSpellConditionsByName } from "@/lib/dm/concentration"; import { laySpellConditionsOnEnemy } from "@/lib/dm/spell-effects"; -import { rollCard } from "@/lib/dm/roll-card"; -import { rollOn } from "@/lib/roll-labels"; +import { sourceDamage } from "@/lib/dm/roll-card"; +import { fallSource } from "@/lib/roll-sources"; import { layPetCondition } from "@/lib/dm/pet-condition-lay"; import { rollPetSave } from "@/lib/dm/pet-save-roll"; @@ -179,7 +179,7 @@ export function quakeFissures(campaign: Campaign, encounter: Encounter, map: Bat function fallIn(campaign: Campaign, encounter: Encounter, zone: SpellZone, token: BattleToken, dc: number, depth: number): string | null { const dice = `${Math.min(20, Math.max(1, Math.floor(depth / 10)))}d6`; // A fall: nobody made it, as an enemy's fall (src/lib/dm/enemy-fall.ts). - const fall = `${depth} ft fall into a fissure (${dice} bludgeoning)`; + const fall = { note: `${depth} ft into a fissure`, dice, type: "bludgeoning" }; if (token.kind === "enemy") { const enemy = getEnemy(token.refId); if (!enemy || enemy.status !== "alive") { @@ -189,7 +189,7 @@ function fallIn(campaign: Campaign, encounter: Encounter, zone: SpellZone, token if (save.success) { return `${enemy.displayName} keeps its footing at the fissure's edge.`; } - const landed = rollCard(campaign, null, null, "damage", rollOn(fall, [enemy.displayName]), dice, null).total; + const landed = sourceDamage(campaign, null, fallSource(), { names: [enemy.displayName] }, fall).total; const hurt = hurtEnemy(campaign, encounter, enemy, landed, "bludgeoning", `falling ${depth} feet into a fissure`); const standing = getEnemy(enemy.id); if (standing?.status === "alive") { @@ -206,7 +206,7 @@ function fallIn(campaign: Campaign, encounter: Encounter, zone: SpellZone, token if (save.success) { return `${sheet.name} keeps their footing at the fissure's edge.`; } - const amount = rollCard(campaign, turn, sheet.id, "damage", rollOn(fall, [sheet.name]), dice, null).total; + const amount = sourceDamage(campaign, turn, fallSource(), { characterId: sheet.id, names: [sheet.name] }, fall).total; applyPcDamage(campaign, turn.id, getSheetById(sheet.id) ?? sheet, { noCreature: true, amount, type: "bludgeoning", reason: `fell ${depth} feet into a fissure (${zone.spell})` }); const standing = getSheetById(sheet.id); if (standing && !standing.deathSaves?.dead && !prone(standing.conditions)) { diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json index 4315d0556e..7f48cc7ff3 100644 --- a/src/lib/i18n/fr.json +++ b/src/lib/i18n/fr.json @@ -9447,6 +9447,7 @@ "Ability check": "Test de caractéristique", "Attack roll": "Jet d’attaque", "The GM · ": "Le MJ · ", + "The fall": "La chute", "An encounter with someone": "Une rencontre avec quelqu’un", "An ally": "Un allié", "A twist": "Un retournement", diff --git a/src/lib/roll-labels.ts b/src/lib/roll-labels.ts index 6300a02119..06e836b982 100644 --- a/src/lib/roll-labels.ts +++ b/src/lib/roll-labels.ts @@ -2,13 +2,16 @@ // writes, the chronicle card, cinematic mode's toast and chronicle line. An // attack or damage roll records its attacker, who goes in front, and its // detail says what was used and against whom, so each creature is named -// once. Every other roll, and one stored before the attacker was recorded, -// keeps the sheet it concerns (characterId) in front, as it always has. +// once. A roll nobody at the table made (a trap's, a fall's, the GM's own +// dice) records its source as its attacker, so the source goes in front and +// the character it lands on is named in the detail, as a target is. Every +// other roll, and one stored before the attacker was recorded, keeps the +// sheet it concerns (characterId) in front, as it always has. // Pure (type imports only), so client components and test scripts import it. // The kind words are the dictionaries' (rollmap.kind.*); the surface that // shows them passes its translator. -import type { StoredRoll } from "@/lib/db/rolls"; +import type { HazardKind, StoredRoll } from "@/lib/db/rolls"; import { contentName } from "@/lib/content/names"; import { textKey } from "@/lib/language/text-logic"; @@ -40,6 +43,26 @@ function localizeDetail(detail: string, locale: "en" | "fr"): string { return localizeRollWhat(detail, locale); } +// What a source's roll threw (src/lib/roll-sources.ts): its dice, the type +// of harm, and a few words in front where they are needed ("30 ft"). +export type Thrown = { dice?: string; type?: string; note?: string }; + +// The words of a roll its source made, whose name goes in front of the card: +// what was thrown and on whom, and never the source again. +// "30 ft, 3d6 bludgeoning on Aria". +export function thrownOn(thrown: Thrown, targets: string[]): string { + const dice = [thrown.dice, thrown.type].filter(Boolean).join(" "); + // The note is held short, so a target after it survives the 120 + // characters a roll card keeps of its words (roll-card.ts rollCard). + return rollOn([thrown.note?.slice(0, NOTE_MAX), dice].filter(Boolean).join(", ") || "damage", targets); +} +const NOTE_MAX = 60; + +// A source's attack roll against one target's armour: "Attack vs Aria, AC 16". +export function attackOn(target: string, ac: number): string { + return `${rollAgainst("Attack", target)}, AC ${ac}`; +} + // One target: "Club vs Aria". export function rollAgainst(what: string, target: string): string { return `${what} vs ${target}`; @@ -51,9 +74,31 @@ export function rollOn(what: string, targets: string[]): string { return targets.length ? `${what} on ${targets.join(", ")}` : what; } -// Who made the roll: its attacker, else the sheet it concerns. +// The two sources that are never given a name, in front of a roll. They are +// chosen by what the source is and never by its name, which is what a +// sentence calls it (src/lib/roll-sources.ts). +const SERVER_NAMED: Partial> = { fall: "The fall", gm: "The GM" }; + +// Who made the roll: its attacker, else the sheet it concerns. A trap's or a +// hazard's own name is as it was given. export function rollerName(roll: Pick, sheetName: string | undefined): string | undefined { - return roll.attacker ? roll.attacker.name : sheetName; + const by = roll.attacker; + if (!by) { + return sheetName; + } + return by.kind === "hazard" ? (SERVER_NAMED[by.hazard] ?? by.name) : by.name; +} + +// The same, as a seat reads it: the server's two are the dictionaries' words. +function shownRoller(t: T, roll: Pick, sheetName: string | undefined): string | undefined { + const by = roll.attacker; + if (by?.kind === "hazard" && by.hazard === "fall") { + return t("The fall"); + } + if (by?.kind === "hazard" && by.hazard === "gm") { + return t("The GM"); + } + return rollerName(roll, sheetName); } // A roll kind as the table reads it, on every card and in cinematic mode. @@ -73,7 +118,7 @@ export function rollKindLabel(t: T, kind: string): string { // The chronicle card's line: "Goblin · Attack roll (Club vs Aria)". export function rollCardLabel(t: T, roll: Worded, sheetName: string | undefined): string { - const who = rollerName(roll, sheetName); + const who = shownRoller(t, roll, sheetName); const locale = t.locale ?? "en"; const detail = roll.detail ? localizeDetail(roll.detail.replaceAll("_", " "), locale) : ""; return `${who ? `${who} · ` : ""}${rollKindLabel(t, roll.kind)}${detail ? ` (${detail})` : ""}`; @@ -81,7 +126,7 @@ export function rollCardLabel(t: T, roll: Worded, sheetName: string | undefined) // Cinematic mode's roll pill, up to the dice: "Goblin · Club vs Aria". export function rollToastLead(t: T, roll: Worded & Pick, sheetName: string | undefined): string { - const who = rollerName(roll, sheetName); + const who = shownRoller(t, roll, sheetName); const locale = t.locale ?? "en"; const what = localizeDetail(roll.detail.trim(), locale) || rollKindLabel(t, roll.kind); return `${who ? `${who} · ` : roll.requestedBy === "dm" ? t("The GM · ") : ""}${what}`; @@ -96,7 +141,7 @@ export function rollChronicleLead(t: T, roll: Worded, sheetName: string | undefi const locale = t.locale ?? "en"; const detail = localizeDetail(roll.detail.trim(), locale); if (roll.attacker) { - return `${roll.attacker.name} · ${detail || label}`; + return `${shownRoller(t, roll, sheetName)} · ${detail || label}`; } return detail || (sheetName ? `${sheetName} · ${label}` : label); } diff --git a/src/lib/roll-sources.ts b/src/lib/roll-sources.ts new file mode 100644 index 0000000000..9d97e24d55 --- /dev/null +++ b/src/lib/roll-sources.ts @@ -0,0 +1,85 @@ +// The source of a roll nobody at the table made (issue 915, ruling 2): a +// trap, a fall, a poisoned draught, the effect of a spell or feature with no +// caster at the table, a hazard the GM named, or the GM's own dice for harm +// nothing names. It is the roll's attacker (src/lib/db/rolls.ts RollSource), +// so it goes in front of the roll's card, and the character or creature the +// roll lands on is its target. +// +// Every source is built here: no other module writes one out +// (scripts/test-roll-labels.mjs holds that). What it is goes in a field +// (`hazard`), set from what its site knows it to be, so no reader works that +// out from its name. +// +// The name is what a sentence calls it ("damage from the fall", "from a +// trap"), which is where a hit's record is read (src/lib/dm/last-hit.ts). A +// source that was given a name keeps it and shows it in front of its rolls. +// The two that never are (a fall, the GM's own dice) are worded there by the +// field, in the table's language (src/lib/roll-labels.ts). +// +// A hit's record names the same sources: it is handed the roll's own value +// where one site writes both. +// +// Pure (type imports only), so client components and test scripts import it. + +import type { HazardKind, RollSource } from "@/lib/db/rolls"; + +// The longest name a source keeps. +const NAME_MAX = 80; + +function source(hazard: HazardKind, name: string): RollSource { + return { kind: "hazard", id: null, name, hazard }; +} + +// A source by the name it was given. With none it is the GM's own dice, +// which a sentence calls by `unnamed` ("a trap", "the effect"). +function named(hazard: HazardKind, said: string | null | undefined, unnamed?: string): RollSource { + const name = (said ?? "").trim().slice(0, NAME_MAX); + return name ? source(hazard, name) : gmSource(unnamed); +} + +// A fall, whatever its height. +export const fallSource = (): RollSource => source("fall", "the fall"); + +// Dice the GM threw for harm that no creature made and nothing names. +// `words` is what a sentence calls that harm where its site has some ("a +// trap", "the hazard"); in front of a roll it is the GM's all the same. +export const gmSource = (words?: string): RollSource => source("gm", (words ?? "").trim().slice(0, NAME_MAX) || "the GM"); + +// A trap, by its name in the catalog or the words the GM gave it. +export const trapSource = (name: string | null | undefined, unnamed?: string): RollSource => named("trap", name, unnamed); + +// An item that harms whoever uses it (a potion of poison). +export const itemSource = (name: string | null | undefined): RollSource => named("item", name); + +// The effect of a spell or a feature: of one whose caster is nobody at the +// table or has left it, and of a creature's own in a hit's record of harm no +// attack made, which names no creature. +export const effectSource = (name: string | null | undefined, unnamed?: string): RollSource => named("effect", name, unnamed); + +// A hazard in the words the GM gave it ("a gout of flame"). +export const namedSource = (said: string | null | undefined, unnamed?: string): RollSource => named("named", said, unnamed); + +// What a spell, trap or hazard with no creature behind it is the roll of, +// from what its call says: the source it names (a trap, when the call says +// it is one), else its spell, else the GM's own dice. +export function castSource(said: string | null | undefined, spell: string | null | undefined, trap = false, unnamed?: string): RollSource { + const words = (said ?? "").trim(); + return words ? (trap ? trapSource(words) : namedSource(words)) : effectSource(spell, unnamed); +} + +// Harm the GM deals with dice of their own and no creature (apply_damage, +// damage_enemy, an area): the spell it is, else the words they gave for it, +// else their own dice. +export function harmSource(spell: string | null | undefined, reason: string | null | undefined, unnamed?: string): RollSource { + return (spell ?? "").trim() ? effectSource(spell) : namedSource(reason, unnamed); +} + +// What a sentence calls harm the GM dealt with a tool of their own and named +// nothing for: its dice (ai-gate.ts) and its record (mutations.ts) both say so. +export const UNNAMED_HARM = "the harm"; + +// The source behind a hit's record no creature made, as a roll names it. A +// record written before it said what it is reads as a hazard by its name. +export function recordSource(attacker: { name: string; hazard?: HazardKind }): RollSource { + return named(attacker.hazard ?? "named", attacker.name); +}