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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .ai/rules/characters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
paths:
- 'app/Livewire/Characters/**'
---

# Characters

## The 5e sheet is a ruleset module: its own table, behind hasCharacterSheet(), storing only what the player decides
character_sheets is one row per character in its own table, never columns on entities, so one ruleset's shape stays off the core table. Ruleset::hasCharacterSheet() is the seam: Characters\Sheet aborts 404 without it, Entities\Show does not mount the card, and the API sets the relation only on such a campaign. Only what a player decides is stored (scores, proficiency lists, hit points, die, slots); modifiers, proficiency bonus, save and skill bonuses, passive Perception and initiative are methods on CharacterSheet that read App\Support\Sheets\FifthEdition, the pure maths class with the unit tests. Never store a derived number. The three lists and the slots are JSON on the row, the calendar's exception. Who writes is EntityPolicy::update(): a GM or the character's player; there is no sheet policy. The ability and skill names are SRD terms, so the card prints config('compendium.attribution').
1 change: 1 addition & 0 deletions .ai/rules/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Before planning or editing, find the row whose globs match the file's path and r
| app/Calendar/**, app/Http/Controllers/CalendarFeedController.php, app/Mail/** | .ai/rules/calendar.md |
| app/Livewire/Calendars/** | .ai/rules/calendars.md |
| app/Actions/Campaigns/**, app/Actions/Campaigns/ExportCampaign.php | .ai/rules/campaigns.md |
| app/Livewire/Characters/** | .ai/rules/characters.md |
| database/srd/**, app/Models/StatBlock.php, config/compendium.php, app/Console/Commands/ImportSrdCommand.php, app/Actions/Compendium/** | .ai/rules/commands.md |
| config/broadcasting.php | .ai/rules/config.md |
| resources/css/** | .ai/rules/css.md |
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ Slice 25 adds **downtime**, what each character did between sessions. A row is w

Slice 26 adds **family trees**. A relationship may carry a kinship, parent, child, sibling, or spouse, read from the side it was written on, and the labels fill in from it when the GM leaves them blank. A character's page draws a "Family" card from the typed rows, two generations up and two down, walked through the relations card's own gate at both ends: a hidden row or a GM-only relative never reaches the party's tree, and the GM reads a mark on each. The kinship travels in the export and on both relation lists of the API.

Slice 27 adds **the 5e character sheet**, as a ruleset module. On a campaign on the SRD 5.2.1 rules a character's page carries a sheet: six ability scores, saving throw and skill proficiencies with expertise, hit points and hit dice, spell slots, armour class and speed, with every modifier, the proficiency bonus, every save and skill bonus, passive Perception and initiative computed from the scores and the level on every read and never stored. The character's player or a GM edits it, takes damage and healing on it, and presses "Long rest"; whoever may read the character reads it, and the party's pack from the ledger sits under it. The sheet lives in its own table behind `Ruleset::hasCharacterSheet()`, so a system-agnostic campaign never sees it, and it travels nested under its character in the export, the vault, and the API.

Your creatures travel in your export with the prose you wrote. A shipped creature never does — it is named in the file and nothing more, exactly as before. The CC BY notice follows the words rather than the table: a creature you wrote carries none, and a copy of a shipped one keeps the source and licence it came from, so the credit travels with the text.

## Local setup
Expand Down
48 changes: 47 additions & 1 deletion app/Actions/Campaigns/ExportCampaign.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Models\Calendar;
use App\Models\Campaign;
use App\Models\CampaignMember;
use App\Models\CharacterSheet;
use App\Models\Clock;
use App\Models\Combatant;
use App\Models\Decision;
Expand Down Expand Up @@ -60,6 +61,7 @@ class ExportCampaign
'quest_objectives' => 'entities[].objectives',
'map_markers' => 'entities[].markers',
'entity_relations' => 'entities[].relations',
'character_sheets' => 'entities[].sheet',
'scenes' => 'sessions[].scenes',
'secrets' => 'sessions[].secrets',
'game_session_entities' => 'sessions[].prepped',
Expand Down Expand Up @@ -355,8 +357,12 @@ private function entities(Campaign $campaign): iterable
->withoutGlobalScopes()
->where('campaign_id', $campaign->id)
->whereNull('deleted_at')
->with(['tags', 'viewers', 'media', 'objectives', 'markers', 'relations', 'statBlock'])
->with(['tags', 'viewers', 'media', 'objectives', 'markers', 'relations', 'statBlock', 'sheet'])
// The id breaks a tie in created_at: PostgreSQL keeps timestamps to the
// second, and two pages made in one second otherwise come out in any
// order, which moved a media ordinal in CI once.
->orderBy('created_at')
->orderBy('id')
->cursor()
->map(fn (Entity $entity) => [
'id' => $entity->id,
Expand Down Expand Up @@ -408,6 +414,9 @@ private function entities(Campaign $campaign): iterable
'player_visible' => $relation->player_visible,
'position' => $relation->position,
])->values()->all(),
// The ruleset's sheet, one-to-one with the character, so nested. Null
// for a character with none and for every other type.
'sheet' => $this->sheet($entity->sheet),
'image' => $this->media($entity->getFirstMedia('image')),
// A handout's attachments, in the same shape as the single image: the
// facts about each file and a URL, never the bytes. The zip with the
Expand Down Expand Up @@ -641,6 +650,43 @@ private function ledger(Campaign $campaign): iterable
]);
}

/**
* The SRD 5.2.1 sheet as the row holds it: the scores, the three lists, the hit
* points, the die, and the slots. Nothing derived, because nothing derived is
* stored.
*
* @return array<string, mixed>|null
*/
private function sheet(?CharacterSheet $sheet): ?array
{
if ($sheet === null) {
return null;
}

return [
'strength' => $sheet->strength,
'dexterity' => $sheet->dexterity,
'constitution' => $sheet->constitution,
'intelligence' => $sheet->intelligence,
'wisdom' => $sheet->wisdom,
'charisma' => $sheet->charisma,
'saving_throws' => $sheet->saving_throws,
'skills' => $sheet->skills,
'expertise' => $sheet->expertise,
'hp_max' => $sheet->hp_max,
'hp_current' => $sheet->hp_current,
'hp_temp' => $sheet->hp_temp,
'hit_die' => $sheet->hit_die,
'hit_dice_spent' => $sheet->hit_dice_spent,
// JSON has no integer keys, so the levels travel as strings and the
// reader turns them back.
'spell_slots' => (object) array_map(fn (array $slot) => ['total' => $slot['total'], 'used' => $slot['used']], array_combine(array_map('strval', array_keys($sheet->slots())), $sheet->slots())),
'spellcasting_ability' => $sheet->spellcasting_ability,
'armor_class' => $sheet->armor_class,
'speed' => $sheet->speed,
];
}

/**
* @return iterable<int, array<string, mixed>> A LazyCollection: it streams row by row.
*/
Expand Down
5 changes: 5 additions & 0 deletions app/Actions/Campaigns/ImportCampaign.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,11 @@ private function children(array $document, IdMap $ids): void
]);
}

// The ruleset's sheet, one-to-one, written after the character it belongs to.
if (($row['sheet'] ?? null) !== null) {
$entity->sheet()->create(['campaign_id' => $entity->campaign_id, ...$row['sheet']]);
}

foreach ($row['relations'] as $relation) {
$entity->relations()->create([
'campaign_id' => $entity->campaign_id,
Expand Down
90 changes: 90 additions & 0 deletions app/Actions/Campaigns/ReadCampaignFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use App\Enums\Visibility;
use App\Models\Calendar;
use App\Models\Campaign;
use App\Models\CharacterSheet;
use App\Models\Combatant;
use App\Models\Decision;
use App\Models\DowntimeActivity;
Expand All @@ -30,6 +31,7 @@
use App\Support\Reckoning\GameDate;
use App\Support\Reckoning\Reckoning;
use App\Support\Reputation\Standing;
use App\Support\Sheets\FifthEdition;
use BackedEnum;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
Expand Down Expand Up @@ -447,6 +449,7 @@ private function entities(array $rows): array
'objectives' => $this->objectives($row),
'markers' => $this->markers($row),
'relations' => $this->relations($row),
'sheet' => $this->sheet($row),
'image' => $image,
'files' => $files,
];
Expand Down Expand Up @@ -545,6 +548,93 @@ private function relations(array $row): array
return $relations;
}

/**
* The SRD 5.2.1 sheet under a character, or null. Absent from a file older than
* slice 27, and null is what that means. A number outside the bounds is refused
* rather than clamped: a sheet is a player's own record, and a quiet clamp would
* hand them a different character.
*
* @param array<string, mixed> $row
* @return array<string, mixed>|null
*/
private function sheet(array $row): ?array
{
$sheet = $row['sheet'] ?? null;

if (! is_array($sheet)) {
return null;
}

$name = (string) ($row['name'] ?? 'a character');
$parts = [];

foreach (CharacterSheet::SCORE_COLUMNS as $column) {
$score = $this->integer($sheet, $column) ?? 10;

if ($score < FifthEdition::MIN_SCORE || $score > FifthEdition::MAX_SCORE) {
$this->errors[] = "The sheet on \"{$name}\" has a {$column} of {$score}, which the rules do not allow.";
}

$parts[$column] = $score;
}

$abilities = array_keys(FifthEdition::ABILITIES);
$skills = array_keys(FifthEdition::SKILLS);

$parts['saving_throws'] = $this->keyList($sheet, 'saving_throws', $abilities);
$parts['skills'] = $this->keyList($sheet, 'skills', $skills);
$parts['expertise'] = $this->keyList($sheet, 'expertise', $skills);
$parts['hp_max'] = max(0, min(FifthEdition::MAX_HIT_POINTS, $this->integer($sheet, 'hp_max') ?? 0));
$parts['hp_current'] = max(0, min($parts['hp_max'], $this->integer($sheet, 'hp_current') ?? 0));
$parts['hp_temp'] = max(0, min(FifthEdition::MAX_HIT_POINTS, $this->integer($sheet, 'hp_temp') ?? 0));
$die = $this->integer($sheet, 'hit_die') ?? 8;
$parts['hit_die'] = in_array($die, FifthEdition::HIT_DICE, true) ? $die : 8;
$parts['hit_dice_spent'] = max(0, min(FifthEdition::MAX_LEVEL, $this->integer($sheet, 'hit_dice_spent') ?? 0));

$slots = [];

foreach (is_array($sheet['spell_slots'] ?? null) ? $sheet['spell_slots'] : [] as $level => $slot) {
$level = (int) $level;
$total = is_array($slot) ? max(0, min(FifthEdition::MAX_SLOTS, (int) ($slot['total'] ?? 0))) : 0;

if ($level >= 1 && $level <= FifthEdition::MAX_SLOT_LEVEL && $total > 0) {
$slots[$level] = ['total' => $total, 'used' => max(0, min($total, (int) ($slot['used'] ?? 0)))];
}
}

ksort($slots);
$parts['spell_slots'] = $slots;

$ability = $this->text($sheet, 'spellcasting_ability', 3);
$parts['spellcasting_ability'] = in_array($ability, $abilities, true) ? $ability : null;

$armor = $this->integer($sheet, 'armor_class');
$parts['armor_class'] = $armor === null ? null : max(0, min(FifthEdition::MAX_ARMOR_CLASS, $armor));

$speed = $this->integer($sheet, 'speed');
$parts['speed'] = $speed === null ? null : max(0, min(FifthEdition::MAX_SPEED, $speed));

return $parts;
}

/**
* A list of keys, keeping only the ones the rules name.
*
* @param array<string, mixed> $row
* @param list<string> $allowed
* @return list<string>
*/
private function keyList(array $row, string $key, array $allowed): array
{
$value = $row[$key] ?? [];

if (! is_array($value)) {
return [];
}

return array_values(array_unique(array_filter($value, fn ($item) => is_string($item) && in_array($item, $allowed, true))));
}

/**
* @param list<array<string, mixed>> $rows
* @return list<array<string, mixed>>
Expand Down
31 changes: 30 additions & 1 deletion app/Actions/Campaigns/WriteCampaignMarkdown.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use App\Models\SessionRsvp;
use App\Support\Reckoning\Reckoning;
use App\Support\Reputation\Standing;
use App\Support\Sheets\FifthEdition;
use Illuminate\Support\Collection;

/**
Expand Down Expand Up @@ -52,7 +53,7 @@ public function handle(Campaign $campaign): array
$entities = Entity::withoutGlobalScopes()
->where('campaign_id', $campaign->id)
->whereNull('deleted_at')
->with(['tags', 'parent', 'arc', 'player', 'objectives', 'relations.target', 'incomingRelations.source', 'reputationChanges.gameSession', 'downtimeActivities.gameSession'])
->with(['tags', 'parent', 'arc', 'player', 'objectives', 'relations.target', 'incomingRelations.source', 'reputationChanges.gameSession', 'downtimeActivities.gameSession', 'sheet'])
->orderBy('name')
->get();

Expand Down Expand Up @@ -243,6 +244,34 @@ private function entity(Entity $entity): string
->implode("\n");
}

// The ruleset's sheet: the scores with their modifiers, the hit points, the
// dice, the proficient skills with their bonuses, and the slots. Derived
// numbers are printed here because a vault page is read, not imported.
if ($entity->isCharacter() && $entity->sheet !== null) {
$sheet = $entity->sheet->setRelation('character', $entity);
$lines = [];

foreach (FifthEdition::ABILITIES as $ability => $name) {
$lines[] = '- '.$name.' '.$sheet->score($ability).' ('.FifthEdition::signed($sheet->modifier($ability)).')';
}

$lines[] = '- Hit points: '.$sheet->hp_current.' of '.$sheet->hp_max.($sheet->hp_temp > 0 ? ' (+'.$sheet->hp_temp.' temporary)' : '');
$lines[] = '- Hit dice: '.$sheet->hitDiceLeft().' of '.$sheet->hitDiceLabel();
$lines[] = '- Proficiency bonus: '.FifthEdition::signed($sheet->proficiencyBonus());

foreach (FifthEdition::SKILLS as $key => $skill) {
if ($sheet->hasSkillProficiency($key) || $sheet->hasExpertise($key)) {
$lines[] = '- '.$skill['name'].' '.FifthEdition::signed($sheet->skillBonus($key)).($sheet->hasExpertise($key) ? ' (expertise)' : '');
}
}

foreach ($sheet->slots() as $level => $slot) {
$lines[] = '- Level '.$level.' slots: '.($slot['total'] - $slot['used']).' of '.$slot['total'];
}

$body[] = "## Character sheet\n\n".implode("\n", $lines);
}

// What the character did between sessions, oldest first, with the days, the
// range in the world when there is one, and the session it happened around.
if ($entity->isCharacter() && $entity->downtimeActivities->isNotEmpty()) {
Expand Down
35 changes: 35 additions & 0 deletions app/Actions/Characters/AdjustHitPoints.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace App\Actions\Characters;

use App\Models\CharacterSheet;

/**
* The two things a table does to a sheet every hour. Damage comes off temporary
* hit points first and the current ones after, never below zero; healing adds to
* the current ones, never above the maximum. Neither touches the maximum.
*/
class AdjustHitPoints
{
public function damage(CharacterSheet $sheet, int $amount): CharacterSheet
{
$amount = max(0, $amount);
$fromTemp = min($sheet->hp_temp, $amount);

$sheet->fill([
'hp_temp' => $sheet->hp_temp - $fromTemp,
'hp_current' => max(0, $sheet->hp_current - ($amount - $fromTemp)),
])->save();

return $sheet;
}

public function heal(CharacterSheet $sheet, int $amount): CharacterSheet
{
$sheet->fill([
'hp_current' => min($sheet->hp_max, $sheet->hp_current + max(0, $amount)),
])->save();

return $sheet;
}
}
25 changes: 25 additions & 0 deletions app/Actions/Characters/LongRest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Actions\Characters;

use App\Models\CharacterSheet;
use App\Support\Sheets\FifthEdition;

/**
* The long rest as the SRD states it: every hit point back, temporary hit points
* gone, every spell slot back, and half the hit dice back, at least one.
*/
class LongRest
{
public function handle(CharacterSheet $sheet): CharacterSheet
{
$sheet->fill([
'hp_current' => $sheet->hp_max,
'hp_temp' => 0,
'hit_dice_spent' => FifthEdition::hitDiceAfterLongRest($sheet->hit_dice_spent, $sheet->level()),
'spell_slots' => array_map(fn (array $slot) => ['total' => (int) $slot['total'], 'used' => 0], $sheet->slots()),
])->save();

return $sheet;
}
}
26 changes: 26 additions & 0 deletions app/Actions/Characters/SaveSheet.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace App\Actions\Characters;

use App\Models\CharacterSheet;
use App\Models\Entity;

class SaveSheet
{
/**
* Creates or replaces the character's one sheet from validated parts. The
* component checked every number against the bounds before it got here.
*
* @param array<string, mixed> $parts
*/
public function handle(Entity $character, array $parts): CharacterSheet
{
/** @var CharacterSheet $sheet */
$sheet = CharacterSheet::query()->updateOrCreate(
['entity_id' => $character->id],
[...$parts, 'campaign_id' => $character->campaign_id],
);

return $sheet;
}
}
10 changes: 10 additions & 0 deletions app/Enums/Ruleset.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,14 @@ public function hasCompendium(): bool
{
return $this === self::Srd5e2024;
}

/**
* Whether a character on this ruleset gets a sheet of the rules' own shape. The
* card, the write, the export section and the API key all read this rather than
* comparing cases, the compendium's way.
*/
public function hasCharacterSheet(): bool
{
return $this === self::Srd5e2024;
}
}
Loading
Loading