Routes & flowchart

A visual novel without maps: the story is a list of events in order, split into routes. Each route gets its own page in the flowchart, where the player can load the story from any scene they have reached.

Visual novel mode

One switch in src/content/config/mode.ts. Only you can change it: players and the debug menu can't.

export default defineMode({
  vnOnly: true, // false = the normal game with maps (everything as before)
})

With vnOnly: true:

The RPG code is still there, just not offered. game.vnOnly tells content which mode it is in.

A route

One folder per route: src/content/routes/<name>/index.ts. common always exists: every new game starts there.

import { defineRoute } from '@/core/define'

export default defineRoute({
  title: 'Common',                    // tab and the box leading here
  description: 'Arriving in town.',  // optional
  color: '#7fb3ff',                  // optional: tab and boxes leading here
  // image: picture,                 // optional: import picture from './art.png'
  run: async ({ event, choice, flag, check, startRoute, movie }) => {
    await event('meeting/special', 'meeting')
    await event('town/thechoice', 'the_choice')
    // The player picks; two ways that join again below.
    const trust = await choice({ yes: 'I trust you', no: 'Not yet' }, { who: 'jack', text: 'Well?' })
    if (trust === 'yes') await event('jack/tells_his_story', 'tells_story')
    else await event('jack/lies_about_himself', 'lies')
    // Only sometimes: otherwise the line goes straight past it.
    if (flag('met_anna')) await event('anna/greeting', 'greeting')
    await event('town/leaving', 'leaving')
    if (check('rich', (game) => game.money.get() > 100)) {
      await movie('credits')
      return // the story ends here: back to the title
    }
    if (trust === 'yes') return startRoute('anna')
    return startRoute('bad_end')
  },
})

Events can still do everything they normally do, also change the flags the route branches on later.

The stage carries over

While a route plays, an event that ends leaves the stage as it is: the background (or CG), the characters where they stand, pictures from image(), weather, the filter, and a fade() colour. The next event (or a route choice) starts on it, with no black frame between them. Change or clear it in the script that should: bg none, hide, image none, weather none, filter none, fade none. Lines, choices, full-page text and the camera always reset.

How the chart is made

Nobody draws the chart. The engine runs run without playing anything, once for every answer of every flag() / check(), and writes down the boxes. Boxes are the keys, so where two ways reach the same key, the lines join. The example above gives:

meeting → the_choice → tells_story ┐
                     → lies ───────┼→ greeting → leaving → …
                                   └──────────→ leaving

It shows every way the code allows. A way the story can never take (an event always changes a flag, say) still shows as "???" boxes: hide them with hidden in flow.ts. More than 4096 ways in one route gives a warning: split it into routes.

Mistakes in a route file (a key used for two events, something after startRoute, a loop) are errors with the route's name. pnpm test checks every route (src/content/routes.test.ts).

flow.ts: titles, descriptions, jumps

Optional, next to index.ts. Box names autocomplete.

import { defineFlow } from '@/core/define'

export default defineFlow('common', {
  the_choice: {
    title: 'The choice',              // default: the event's title
    description: 'Jack asks you to trust him.', // the side panel, before loading
    // image: picture,                // in the box and the side panel
  },
  tells_story: {
    // What this event LEAVES BEHIND: runs instead of it for boxes on the way to a loaded box.
    sets: (game) => {
      game.items.add('letter')
      game.relationships.change('jack', 5)
    },
  },
  leaving: {
    // What this event EXPECTS to find: runs just before it, when the player loads this box.
    before: (game) => game.audio.music('music/town'),
  },
  impossible_box: { hidden: true },   // a way the story can't take
  anna_greeting: { shift: { x: 40, y: -10 } }, // move the box (px); its lines follow
})

shift (and more layout fixes: Fixing the chart by hand) moves one box from where the chart puts it: x (+ right) and y (+ down) in px, both optional. It comes after the automatic layout, so only that box moves; its lines follow, and the other boxes stay where they were. Without any shift the chart is laid out exactly as before. Moving a box above the top moves the whole chart down.

What loading a box does

Loading leaving through tells_story:

  1. A fresh game (like New game; the difficulty is kept, nothing from New Game+ is carried).
  2. Every box on the way runs its sets instead of playing. The way's choice() picks are replayed, and flags the route asked with flag() are set to the way's answers by themselves (a way through if (flag('met_anna')) sets met_anna = true): only write what the chart can't know (items, points, money, numbers, check() conditions).
  3. The loaded box runs before, then its event plays, and the story goes on normally.

.vn scenes need no sets for their plain lines. The engine reads what a .vn scene leaves behind from its set, love, money, give, take, xp, join, achievement, codex, quest, rename and reveal lines, in order and inside the ifs they are in (an if on flag(), has(), love(), money(), seen() or game.…), and runs that on a jump. A sets in flow.ts replaces it for that box. It can't know what a choice inside the scene picked, an if on a value of the scene ($ const roll = random()), a $ line that changes the game, or a nested event: then the parts it knows still run, and in development builds a jump through that box warns you to write a sets for it. Choices are best kept in the route anyway, with what an option does by itself (see above).

Skipped events count as played (game.events.seen). Nothing is shown to the player while sets runs (no toasts, no sounds).

Keeping sets honest: in development builds, each time a box really plays, the engine compares what its event changed with what its sets (or what the engine read from its .vn lines) would do, and warns in the console when they differ ("its flow.ts sets does not leave what the event left: data.flags.met_anna").

Which way loads (VN style)

The flowchart window

Side panel (picture, title, route, description, Load), the chart, and a tab per route reached. The window starts on the box the story is at.

Make it look like your game:

export default defineFlowchart({
  node: { width: 168, height: 52, gapX: 36, gapY: 44, image: 'left' }, // box picture: 'left' | 'right' | 'top' | 'bottom' | 'none'
  shape: 'rounded',         // right angles with round corners | 'elbow' | 'curve' | 'straight'
  corner: 10,               // corner radius of 'rounded' lines, px
  hops: 5,                  // a small arc where a line runs across another, radius px ('rounded' / 'elbow'; null = off)
  branch: { size: 26, side: 'right' }, // flag()/check() diamonds; null = none
  arrows: false,            // true = a small arrow where a line meets the box below
  chapters: { header: 30, size: 12, color: gold, line: { color: '…', width: 1, dash: [6, 4] } }, // null = none
  lineGap: 16,              // least px between side-by-side lines
  autoFix: true,            // lines running across between two rows never lie on top of each other
  compact: null,            // px gap between rows whose lines all go straight down (null = gapY)
  labels: 'middle',         // where option text sits: 'start' | 'middle' | 'end'
  debug: false,             // dev builds: rows, columns, px and every box / diamond key
  line: { color: 'rgba(255, 255, 255, 0.35)', width: 2 },
  pathLine: { color: gold, width: 3 },  // the way that would load
  lockedLine: { color: 'rgba(255, 255, 255, 0.2)', width: 2, dash: [5, 5] }, // 'locked' style only
  unseen: 'hidden',         // boxes not reached: 'hidden' (no spoilers) | 'locked' ("???")
  choiceLabel: { color: gold, size: 12, outline: 'rgba(10, 12, 18, 0.9)' }, // null = no labels
  text: { locked: tx('???'), end: tx('The end'), load: tx('Load'), loadQuestion: tx('…'), cannotLoad: tx('…'),
          routes: tx('Routes'),               // heading over the main story's tabs (null = none)
          afterStories: tx('After Stories') }, // heading over the after stories' tabs (null = line only)
  panel: { width: 0.32, side: 'left' },
  tabs: { side: 'right', image: 'top' },   // tab picture: 'left' | 'right' | 'top' | 'bottom' | 'none'
  height: 0.72,             // share of the screen's height
})

Chapters on the flowchart

A chapter('id') in a route draws "Chapter 1" over a line across the whole chart. There is one line per chapter NUMBER: sub chapters never add one (1.1 and 1.2 are both under "Chapter 1"; a route whose first chapter is 1.1 still gets the heading "Chapter 1"; "Chapter 2" only comes with the first chapter numbered 2). Sub chapters show on saves ("Chapter 1.2: …"). Every box played after the first chapter of a number is below its line; every box before it is above. The same chapter may be started in several places (in different branches): it is still one line. A branch that starts it later than the others keeps its extra boxes above the line, even when they play at the same step as boxes the other branches show below it:

chapter('one')
await event('x/a', 'a')
const p = await choice({ x: 'X', y: 'Y', z: 'Z' })
await event(`x/${p}1`, `${p}1`)
if (p !== 'z') chapter('two')        // x and y: chapter 2 starts before their 2nd event (number: 2)
await event(`x/${p}2`, `${p}2`)       // z2 stays above the line (still chapter 1); x2, y2 below it
if (p === 'z') chapter('two')        // z: only now
await event(`x/${p}3`, `${p}3`)       // all below the line
await event('x/m', 'm')              // the branches join

A box reached by ways in different chapters goes with the latest one. A chapter before the route's first box puts its line at the very top. In the hidden style a chapter's line shows once one of its boxes is reached. Looks: chapters in src/content/config/flowchart.ts (header = room for the number above the line, px; text size / color; line; null = no chapter lines, boxes placed as if there were none).

Fixing the chart by hand

If the automatic layout puts a box, a diamond or a line somewhere you don't like, fix it in the route's flow.ts. Every option is optional: a box without them stays where the chart puts it, and a route without any is laid out exactly as before. They work on event boxes, choice boxes ('?stay_go': '?' + the option keys, or + the choice's key) and flag diamonds ('!leaving' = the diamond right after the box leaving; '!leaving:false' / '!leaving:true' = one further on, after a "no" / "yes"). Set debug: true in src/content/config/flowchart.ts (dev builds only) to see every key, the row and column numbers and px.

export default defineFlow('common', {
  waved: {
    shift: { x: 40, y: -10 },  // move it, px (+ right / down); its lines follow, nothing else moves
    column: 2,                 // or: put it in debug-grid column 2 (0 = the first box; may be negative)
    row: 5,                    // put it in row 5 or lower (never above what leads to it); later boxes move down too
    order: 0,                  // its place in its row, 0 = leftmost (the others keep theirs)
    align: 'arrival',          // same column as another box
  },
  jack_story: {
    branchSide: 'left',        // "yes" leaves its diamond to the left
    branchShift: { x: 12 },    // move the diamonds right after this box
    lines: {                   // its lines (and its diamonds' lines), by the box they go to
      anna_greeting: {
        straight: true,        // this one goes straight through the diamond; "no" leaves from the side
        bend: -8,              // move the part that runs across up (-) / down (+), px
        start: -20, end: 10,   // where it leaves / enters: px from the box's middle
        enter: 'left',         // into the box's 'top', or past the top into its 'left' / 'right' side
        look: { color: '#ff8a80', dash: [2, 4] },  // its own colour / width / dashes
      },
      leaving: { via: [[300, 620]] },  // go through these chart points (px, see debug) instead
    },
  },
  '?stay_go': {                // a choice box
    lines: {
      '@route:bad_end': { label: 'Leave', labelShift: { y: 6 } }, // own text (null = none), moved
      '@route:anna': { hide: true },  // don't draw it
    },
  },
  '!jack_lies': { shift: { y: 6 }, branchSide: 'left' },  // a diamond itself
})

Settings on a box apply to the lines leaving its diamonds too, by the box they end at; to reach a line between two diamonds, write it on the first diamond ('!a': { lines: { '!a:false': … } }). '@end' and '@route:<id>' are the end and route boxes. Strongest first: column, then align, then straight lines; shift is applied last. row / column / align make room by moving other boxes; shift and via don't (you choose the place, so nothing checks for overlaps).

After stories

Extra stories played after an ending, started from the title screen. VN mode only. An after story is a normal route with one more field:

// src/content/routes/anna_after/index.ts
export default defineRoute({
  title: 'A year at the pond',          // the card's title (and the flowchart tab)
  description: 'Anna, one year after you stayed.',
  image: card,                          // the card's picture
  color: '#7fb3ff',
  afterStory: { requiresEnding: ['anna'] }, // ALL listed endings reached ([] = open from the start)
  // afterStory: { requiresEnding: ['anna'], order: 1 } // lower comes first; default folder order
  run: async ({ event }) => {
    await event('anna_after/morning')
  },
})

In a .vn route it is one header line: after story [ending anna] (more [ending …] = all of them).

Routes as .vn scripts

routes/<name>/index.vn works instead of index.ts (see routes/bad_end). flow.ts stays TypeScript.

# The common route
title Common
description Arriving in town.
color #7fb3ff
event meeting/special as meeting
event town/thechoice as the_choice
choice jack: Well?
  * I trust you
    # this event sets the flag jack_trusted (routes read flags; events set them)
    event jack/tells_his_story as tells_story
  * Not yet
    event jack/lies_about_himself as lies
if flag('met_anna'):
  event anna/greeting as greeting
chapter evening
event town/leaving as leaving
if check('rich', game.money.get() > 100):
  movie credits
  end
elif flag('jack_trusted') and not flag('met_anna'):
  route anna
route bad_end

Right under an option you can write what picking it does: love anna +1, set waved = true, money -5, give apple, take apple (also xp, join, achievement, codex, quest, rename, reveal), before the option's other lines. They become the choice's effects:

choice:
  * Wave back
    love anna +1
    event town/waved
  * Look away
    event town/ignored

A choice works like in an event script (each option's text is also its key). choice: alone has no question line; choice: text asks it as narration.

Lines: title (required), description, color, image ./file.png, after story [ending <id>], event <id> as <box>, choice with * option lines, if / elif / else:, movie <id>, chapter <id>, route <id>, ending <id> (= return ending('id')), end (ends without an ending). A hidden option ends with its conditions: * I know who you are [ending anna] (several [ending …] = all of them), [flag met_anna] (both kinds may be given). Conditions: flag('id') and check('label', condition) with and / or / not. The editor extension checks and completes event, route, chapter, ending and flag ids.

Opening the game at a scene while you work: @start

Put @start on a line of a scene (an event a route box plays). While the dev server runs, every page load skips the boot screens and the title, loads that box like a flowchart jump, and runs the scene instantly up to the marker: the line after it is the first one you see. Save the file, the page reloads, you are there again.

# src/content/events/vn_demo/jack_story/index.vn
jack: Good. Then I'll tell you everything.
jack: I came here ten years ago, with nothing but a letter.
@start wave trust
jack: Nobody asked where I was from.    # the game opens here

// a .ts scene
import { devStart } from '@/core/dev/start'
await say('jack', 'I came here ten years ago…')
devStart({ way: ['wave', 'trust'] })

game.routes

CallWhat it does
game.routes.start(id)Starts a route from its top (a new game does start('common') in VN mode).
game.routes.current(){ route, key } of the box the story is at, or null.
game.routes.seen(route, key)Reached in any playthrough?
game.routes.jump(route, key)What the flowchart's Load does. Resolves false if the box can't be loaded.
game.routes.way(route, key)The way that would load (boxes and answers, per route).
await game.routes.afterStories(){ available, locked, launch(id) }: the after stories, in order (empty outside VN mode).
await game.routes.startAfterStory(id)Starts an open after story from a fresh game. False if it isn't one, or isn't open.
game.routes.graph(id)A route's chart: boxes, lines (with the branch each was taken on), every way.

Seen and picked boxes are kept per device across all saves (like read lines), and are part of backups.