Rewrite the two game tutorials as instructions rather than commentary
Some checks failed
akbasic CI Build / cmake_build (push) Failing after 3m21s
akbasic CI Build / sanitizers (push) Failing after 4m32s
akbasic CI Build / coverage (push) Failing after 3m37s
akbasic CI Build / akgl_build (push) Failing after 22s
akbasic CI Build / mutation_test (push) Failing after 3m30s

Chapters 17 and 18 read as a code review of a finished listing: they explained
why each decision had been made, walked through the project's own history, and
led with what had once been broken. A reader who wanted to build the game got
the reasoning and had to reconstruct the program.

Both are now step-by-step. Each opens with a picture of the finished game and a
bullet list of the steps, each bullet is a section, and each section states its
goal, shows the code, and says how to check it. Chapter 17 is sixteen steps and
Chapter 18 is thirteen, and the last of each is the assembly: the order of the
file, the full declaration block, and the routines the earlier steps referred to.
Project history is gone -- it belongs in Chapter 14 and in git -- and where a
listing has to do something awkward, the tutorial shows how first and names the
`TODO.md` item that will make it unnecessary second.

**Three defects had no entry anywhere**, which the rewrite found by trying to
state each rule as a rule. §6 item 35: `a - b + c` computes `a - (b + c)`,
because `subtraction()` sits above `addition()` as its own precedence level and
the inner loop eats the `+`. Item 36: only one unparenthesised `AND` or `OR` is
matched, which is item 12's `if`-where-`while` on the one operator pair item 12
did not reach. Item 37: a `GOTO` out of a `FOR` or a `DO` leaks the loop's scope,
so a main loop written that way stops on the thirty-second lost life -- which is
why both games are built out of `LABEL` and `GOTO`, and it is a workaround rather
than a preference. Chapter 3 gains the identifier rule the third trial ran into:
there is no underscore in a name, and the error says `UNKNOWN TOKEN _`.

**`tools/screenshot.c` learned to draw the text layer**, behind a new `text=1`
fence attribute, because Chapter 17's game is characters in the grid and a figure
without that layer is two sprites on black. It opens the bundled font at the size
the standalone frontend uses, so a figure's cell size is the reader's cell size,
and it uses the akgl sink alone rather than a tee so the program's output lands in
the picture instead of on the stdout the caller reads to decide a figure failed.
Both new figures -- `breakout-game.png` and `breakout-game-artwork.png` -- are
generated from listings in the chapters like every other one.

Verified by handing each chapter, alone, to an agent on a much smaller model and
telling it to build the game from the tutorial text with the `examples/` tree off
limits. The first pass scored 3.5 and 3 out of 10 and named what was missing:
routines referred to but never shown, the third level layout, the sprite `DATA`,
the font table, edits to earlier routines that were never marked as edits. Those
are now in. The second pass built a 658-line Chapter 17 game that plays itself
for ninety seconds with the score at 1890 and no error line, and the third built
a 1053-line Chapter 18 game with 61 labels, no invented routines, no gaps found,
and forty seconds clean. 9/10 and 8/10.

One real bug in the new prose, caught in review: Chapter 18's `HITBAR` did not
set the `HIT#` that `BALLPADDLE` reads to decide whether the paddle already
caught the ball. Both suites green in both configurations, `docs_examples` and
`docs_screenshots --check` pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EwxGB6TdoVvZ11KQQME9cL
This commit is contained in:
2026-08-02 08:08:23 -04:00
parent 0679c3042b
commit 1fb808f480
16 changed files with 3391 additions and 667 deletions

View File

@@ -611,6 +611,7 @@ a missing decision rather than a free pass.
| `text` | **Never executed.** A block diagram, or a stack trace captured from a real run | | `text` | **Never executed.** A block diagram, or a stack trace captured from a real run |
| `basic screenshot=NAME` | Also the source of `docs/images/NAME.png`. The harness checks the file exists; `tools/docs_screenshots.sh` is what makes it | | `basic screenshot=NAME` | Also the source of `docs/images/NAME.png`. The harness checks the file exists; `tools/docs_screenshots.sh` is what makes it |
| `basic size=WxH` | That figure's surface, when 320x200 is not the size the point needs | | `basic size=WxH` | That figure's surface, when 320x200 is not the size the point needs |
| `basic text=1` | That figure is drawn **with** the text layer, for a program whose output is characters |
Attributes combine: `basic requires=akgl setup=ship` is a real tag in `docs/08-sprites.md`. Attributes combine: `basic requires=akgl setup=ship` is a real tag in `docs/08-sprites.md`.
@@ -627,8 +628,18 @@ $ cmake --build build-akgl --target docs_screenshots
`tools/screenshot.c` is a second, much smaller SDL host — the dummy video driver, a `tools/screenshot.c` is a second, much smaller SDL host — the dummy video driver, a
software renderer, run the program to completion, read the target back, write a PNG. It software renderer, run the program to completion, read the target back, write a PNG. It
draws no text layer, deliberately: a `READY` in the corner is noise in a figure about draws no text layer by default, deliberately: a `READY` in the corner is noise in a figure
`BOX`, and skipping it means no font has to be found. about `BOX`, and skipping it means no font has to be found.
**`text=1` turns the text layer on**, for the case that default gets wrong: a figure of a
program whose output *is* characters. `docs/17-tutorial-breakout.md` builds a game whose
wall, HUD and messages are all in the grid, and without the layer its figure is two sprites
on a black field. The tag makes `docs_screenshots.sh` hand the tool
`assets/fonts/C64_Pro_Mono-STYLE.ttf` at `AKBASIC_FRONTEND_FONT_SIZE`, which is what the
standalone frontend opens, so the figure's cell size is the reader's cell size. The sink is
then the akgl one *alone* rather than a tee, so the program's output goes into the picture
instead of onto stdout — which the caller reads to decide a figure failed. A raised error
is still caught, by `docs_examples` running the same block.
Three rules around it: Three rules around it:

114
TODO.md
View File

@@ -2100,6 +2100,120 @@ in either corpus runs for minutes, which is why the first of these had never bee
`AKBASIC_ERR_BOUNDS` from the pool is documented as "bounded and diagnosable, which is the `AKBASIC_ERR_BOUNDS` from the pool is documented as "bounded and diagnosable, which is the
point" (`include/akbasic/value.h:34`). With a `TRAP` armed it is currently neither. point" (`include/akbasic/value.h:34`). With a `TRAP` armed it is currently neither.
### Found while rewriting the game tutorials
Chapters 17 and 18 were rewritten to teach a beginner rather than to explain a finished
listing, which meant writing every rule down as a rule instead of as a comment beside the
code that dodges it. Three of them turned out to have no entry anywhere. The first two are
the same shape as item 12 above — a parser function that consumes one operator where it
should loop — and the third is why both games are built out of `LABEL` and `GOTO`.
35. **An expression mixing `-` and `+` at the same level is evaluated right to left.**
`a - b + c` computes `a - (b + c)`. A C128, and every BASIC this descends from, folds a
run of same-precedence additive operators left to right.
```basic
PRINT 10 - 3 + 2
PRINT 1 - 2 - 3
```
```output
5
-4
```
The second line is right and the first is not; 9 is the answer. **Nothing fails** — this
is item 4's failure mode over again, a program that quietly computes something else — and
the two tutorials work around it by parenthesising every mixed `+` and `-` as a rule
rather than where it happens to matter.
**The cause is the grammar's shape, not a missing loop.** `subtraction()`
(`src/parser.c:425`) sits *above* `addition()` (`:447`) as its own precedence level, and
both loop correctly — but `subtraction()`'s right operand is parsed by `addition()`, which
then consumes the `+` that should have been the *next* term of the subtraction. `1 - 2 - 3`
is right because the outer loop sees both minuses; `10 - 3 + 2` is wrong because the inner
one eats the plus first.
The fix is one additive level rather than two: a single function matching `PLUS` and
`MINUS` in one `while`, building left-associatively, with `multiplication()` beneath it.
That is what item 12 left half-done — it made each of the two levels fold left without
noticing that there should only have been one. Touches `src/parser.c` and wants cases in
`tests/parser_expressions.c` beside item 12's, asserting `10 - 3 + 2` is 9 and
`10 + 3 - 2` is 11 (which already passes, and is the asymmetry that gives it away).
36. **Only one unparenthesised `AND` or `OR` is matched per expression.** A second one is left
in the token stream, and in the place a program actually writes them — a condition — the
`THEN` check then finds the wrong token and the line is refused:
```basic
X# = 1
Y# = 2
IF X# = 1 AND Y# = 2 THEN PRINT "TWO IS FINE"
IF X# = 1 AND Y# = 2 AND X# = 1 THEN PRINT "THREE IS NOT"
```
```output
TWO IS FINE
? 4 : PARSE ERROR Incomplete IF statement
```
Parenthesising is the workaround and it works — `IF (A AND B) AND C THEN` parses — which
is what the tutorials tell a reader to do. It is a refusal rather than a wrong answer, so
it costs a puzzled minute rather than an evening; item 42 in §5 fixed the case of *one*
`AND` and stopped there.
`logicalandor()` (`src/parser.c:329`) is `if ( akbasic_parser_match(obj, OPS, 2) )` at `:339`
where `subtraction()` at `:425` is `while`. **This is item 12's defect exactly**, on the
one operator pair item 12 did not reach, and the reference has the same shape at
`basicparser.go`. The fix is the same fix: `while`, folding left, reassigning `left` from
the leaf built on the previous pass. `tests/parser_expressions.c` for the expression form
and `tests/parser_commands.c` for the `IF` that made it visible.
Worth doing together with item 35: they are one afternoon, one file, and between them they
are the two rules a tutorial currently has to spend a paragraph on.
37. **A `GOTO` that leaves a `FOR` or a `DO` leaks the loop's scope**, so a program that uses
the pattern as its main loop stops after the thirty-second time round:
```basic
N# = 0
LABEL TOP
DO
N# = N# + 1
IF N# < 100 THEN GOTO TOP
LOOP UNTIL N# > 99
PRINT "SURVIVED " + N#
```
```output
? 3 : PARSE ERROR Environment pool exhausted at line 3 (32 in use)
```
Thirty-two is `AKBASIC_MAX_ENVIRONMENTS` (`include/akbasic/types.h:31`), and the branch
that reports is the `DO` being entered for the thirty-third time rather than the `GOTO`
that did the damage — the same misattribution item 2 had. The `FOR` form behaves
identically.
**This is a real pattern rather than a contrivance.** A game's main loop is a loop the
program leaves from the middle of: losing a life, clearing a level and quitting are all
"stop what you are doing and go somewhere else". Both Breakout listings in `examples/`
are built out of `LABEL`/`GOTO` for exactly this reason, which is the shape a reader of
chapters 17 and 18 is now told to copy, and it is a workaround rather than a preference —
a `DO ... LOOP` around the frame would be the natural way to write either one.
The mechanism is the one item 2 documents from the other end: a loop's environment is
pushed when the line is parsed and popped by its `NEXT` or `LOOP`, and nothing else pops
it. `GOTO` sets the next line and returns (`akbasic_cmd_goto()`, `src/runtime_commands.c`);
it has no idea it has just left a scope.
A fix has to know which scopes the branch target is *outside* of, which the environment
stack can answer if a loop's environment records the source line that pushed it: on a
`GOTO`, pop every loop scope whose line is not on the path to the target. That is more
machinery than items 35 and 36 want between them, and it is worth pricing against simply
documenting it — chapters 13 and 17 both now say "loop with `GOTO`, never jump out of a
`DO`", which is a rule a reader can follow. Wants `tests/for_next.c` either way, because
the reduction above is four lines and currently nothing asserts it in either direction.
## 7. Filing gaps against `libakgl` ## 7. Filing gaps against `libakgl`
When phase 7 or phase 8 needs something `libakgl` does not have, **stop and file it** in When phase 7 or phase 8 needs something `libakgl` does not have, **stop and file it** in

View File

@@ -21,6 +21,11 @@ a character that says what it holds:
There is no such thing as a variable with no suffix. A bare name is a **label** — see There is no such thing as a variable with no suffix. A bare name is a **label** — see
Chapter 4 — so `GOTO DONE` and `LABEL DONE` are how the two meet. Chapter 4 — so `GOTO DONE` and `LABEL DONE` are how the two meet.
**A name is letters and digits and nothing else.** There is no underscore: `HIGH_SCORE#`
does not scan, and what it reports is `UNKNOWN TOKEN _` rather than anything about naming,
so it is worth knowing before you meet it. Run words together — `HIGHSCORE#` — or shorten
them, which is what the listings in this guide do.
`@` is the odd one out: it says "a structure" without saying *which*, so a structure `@` is the odd one out: it says "a structure" without saying *which*, so a structure
variable has to be declared with `DIM E@ AS ENEMY` before it can be used. That is variable has to be declared with `DIM E@ AS ENEMY` before it can be used. That is
**[Chapter 16](16-structures.md)**, along with records, pointers and how a host shares its **[Chapter 16](16-structures.md)**, along with records, pointers and how a host shares its

View File

@@ -250,5 +250,5 @@ lines and then presents, and presenting throws the drawing buffer away — so a
drawing verbs longer than one batch is torn rather than merely transient, and an drawing verbs longer than one batch is torn rather than merely transient, and an
`SSHAPE` at the end of it captures only the part issued since the present. Watching `SSHAPE` at the end of it captures only the part issued since the present. Watching
`TI#` change is how a program finds the boundary; Chapter 13 has the measured numbers and `TI#` change is how a program finds the boundary; Chapter 13 has the measured numbers and
[Chapter 18](18-tutorial-breakout-artwork.md#step-4-find-the-frame-boundary) has a [Chapter 18](18-tutorial-breakout-artwork.md#step-5-find-the-frame-boundary) has a
routine that uses them. routine that uses them.

View File

@@ -153,7 +153,7 @@ interpreter's error code, which bears no relation to a Commodore error number. P
256 lines a batch: after synchronising to a jiffy edge, 220 lines of drawing survive a 256 lines a batch: after synchronising to a jiffy edge, 220 lines of drawing survive a
capture and 250 do not. The only way a program can see the boundary is to watch `TI#`, capture and 250 do not. The only way a program can see the boundary is to watch `TI#`,
which is refreshed once per batch — so the step on which it changes is the first step which is refreshed once per batch — so the step on which it changes is the first step
of one. [Chapter 18](18-tutorial-breakout-artwork.md#step-4-find-the-frame-boundary) of one. [Chapter 18](18-tutorial-breakout-artwork.md#step-5-find-the-frame-boundary)
builds a pacing routine out of exactly that. builds a pacing routine out of exactly that.
- **`CHAR` ignores its colour argument** and needs a text device with a cursor. - **`CHAR` ignores its colour argument** and needs a text device with a cursor.

View File

@@ -181,7 +181,7 @@ A script cannot read the budget, but it can *see* it: `akbasic_runtime_settime()
called once per frame by the host, so `TI#` changes on the first step of a batch and called once per frame by the host, so `TI#` changes on the first step of a batch and
nowhere else. Spinning until it changes is the only frame synchronisation this dialect nowhere else. Spinning until it changes is the only frame synchronisation this dialect
has, and it is what has, and it is what
[Chapter 18](18-tutorial-breakout-artwork.md#step-4-find-the-frame-boundary) is built on. [Chapter 18](18-tutorial-breakout-artwork.md#step-5-find-the-frame-boundary) is built on.
A host that gives the interpreter a larger budget makes more drawing fit; one that never A host that gives the interpreter a larger budget makes more drawing fit; one that never
calls `settime()` takes the synchronisation away entirely. calls `settime()` takes the synchronisation away entirely.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -15,7 +15,8 @@ embedding it, debugging it or changing it.
**[Chapters 17](17-tutorial-breakout.md)** and **[18](18-tutorial-breakout-artwork.md)** **[Chapters 17](17-tutorial-breakout.md)** and **[18](18-tutorial-breakout-artwork.md)**
are tutorials rather than reference: they build one complete game twice, two different are tutorials rather than reference: they build one complete game twice, two different
ways, and are where the rules that a real program runs into are collected. ways, in numbered steps you can type in one at a time. Start with 17 — it needs nothing
but the earlier chapters, and 18 assumes it.
## Chapters ## Chapters
@@ -37,8 +38,8 @@ ways, and are where the rules that a real program runs into are collected.
| **[14. Architecture](14-architecture.md)** | How the interpreter is put together, how to debug it, how to change it | | **[14. Architecture](14-architecture.md)** | How the interpreter is put together, how to debug it, how to change it |
| **[15. Error codes](15-error-codes.md)** | Appendix: every value `ER#` can hold and every error line the interpreter prints | | **[15. Error codes](15-error-codes.md)** | Appendix: every value `ER#` can hold and every error line the interpreter prints |
| **[16. Structures](16-structures.md)** | `TYPE`, records, strict pointers, and sharing a C struct with an embedding host | | **[16. Structures](16-structures.md)** | `TYPE`, records, strict pointers, and sharing a C struct with an embedding host |
| **[17. Tutorial: Breakout](17-tutorial-breakout.md)** | Build a whole game out of the text grid and two `DATA` sprites, a step at a time | | **[17. Tutorial: Breakout](17-tutorial-breakout.md)** | Build a whole game out of the text grid and two `DATA` sprites, in sixteen steps |
| **[18. Tutorial: Breakout with artwork](18-tutorial-breakout-artwork.md)** | Build it again out of loaded artwork, powerups and a drawn HUD | | **[18. Tutorial: Breakout with artwork](18-tutorial-breakout-artwork.md)** | Build it again out of loaded artwork, powerups and a drawn colour HUD, in thirteen |
## The shortest possible start ## The shortest possible start

View File

@@ -17,5 +17,6 @@ test will fail on it, because it re-renders every figure and compares byte for b
The tag that ties a figure to its listing is `screenshot=NAME` in the fence info string, The tag that ties a figure to its listing is `screenshot=NAME` in the fence info string,
and `MAINTENANCE.md` documents it along with `size=WxH` for a figure that needs a surface and `MAINTENANCE.md` documents it along with `size=WxH` for a figure that needs a surface
other than 320 by 200. A tagged block with no image here fails `docs_examples` in both other than 320 by 200, and `text=1` for one whose subject is the text grid rather than a
build configurations, so a figure cannot be added to a chapter and then forgotten. drawing. A tagged block with no image here fails `docs_examples` in both build
configurations, so a figure cannot be added to a chapter and then forgotten.

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@@ -27,10 +27,11 @@ does.
## How it works, and how to write your own ## How it works, and how to write your own
**[Chapter 17 of the guide](../../../docs/17-tutorial-breakout.md)** builds this program a **[Chapter 17 of the guide](../../../docs/17-tutorial-breakout.md)** builds this program in
step at a time: what to make a sprite and what to make a character, why every name is fifteen steps you can type in one at a time, starting from an empty file: measuring the
declared before the game starts, how a text row has to be written whole, and the rest of screen, declaring every name before anything uses it, making the two sprites out of `DATA`,
the rules this listing never breaks. It is the tutorial; this is the finished thing. building a text row whole, the main loop, the ball, the bounce, and the attract mode. It is
the tutorial; this is the finished thing.
[Chapter 18](../../../docs/18-tutorial-breakout-artwork.md) does the same for [Chapter 18](../../../docs/18-tutorial-breakout-artwork.md) does the same for
[`../sprites`](../sprites), which builds the same game out of loaded artwork and comes out [`../sprites`](../sprites), which builds the same game out of loaded artwork and comes out

View File

@@ -48,10 +48,10 @@ dive across the field into a save at both ends.
## How it works, and how to write your own ## How it works, and how to write your own
**[Chapter 18 of the guide](../../../docs/18-tutorial-breakout-artwork.md)** builds this **[Chapter 18 of the guide](../../../docs/18-tutorial-breakout-artwork.md)** builds this
program a step at a time: budgeting the eight sprite slots, capturing a drawing into one, program in twelve steps: loading artwork, budgeting the eight sprite slots, capturing a
finding the host's frame boundary with `TI#`, moving everything that is not drawing out of drawing into one, stamping the brick field, finding the host's frame boundary with `TI#`,
the deadline, the stroke font, and the five things in this dialect that do not do what moving everything that is not drawing out of the deadline, the stroke font, the bounce
they look like. without a square root, and the gems.
[Chapter 17](../../../docs/17-tutorial-breakout.md) does the same for [Chapter 17](../../../docs/17-tutorial-breakout.md) does the same for
[`../characters`](../characters), which builds the same game out of the text grid and two [`../characters`](../characters), which builds the same game out of the text grid and two

View File

@@ -103,17 +103,34 @@ attr()
echo "" echo ""
} }
# The font a `text=1` figure is drawn with. The bundled one, at the size the
# standalone frontend opens it at, so a figure of a text-grid program has the
# same cell size the reader's own window will have.
FONT="${ROOT}/assets/fonts/C64_Pro_Mono-STYLE.ttf"
# One figure: write the listing to a file, run it, keep the PNG. # One figure: write the listing to a file, run it, keep the PNG.
render() render()
{ {
local name="$1" body="$2" size="$3" where="$4" setup="$5" local name="$1" body="$2" size="$3" where="$4" setup="$5" text="$6"
local w=320 h=200 out="${OUTDIR}/${name}.png" log="" local w=320 h=200 out="${OUTDIR}/${name}.png" log="" font=""
if [ -n "${size}" ]; then if [ -n "${size}" ]; then
w="${size%x*}" w="${size%x*}"
h="${size#*x}" h="${size#*x}"
fi fi
# `text=1` says this program's output is characters rather than drawing, so
# the tool has to render the grid -- see the comment at the head of
# tools/screenshot.c. Everything else gets no font and no text layer.
if [ -n "${text}" ]; then
if [ ! -r "${FONT}" ]; then
echo "FAIL ${where}: text=1 needs a font at ${FONT}" >&2
FAILURES=$((FAILURES + 1))
return
fi
font="${FONT}"
fi
# The same setup scripts tests/docs_examples.sh uses, run in the same place # The same setup scripts tests/docs_examples.sh uses, run in the same place
# relative to the program. A listing that loads `ship.png` needs one whether # relative to the program. A listing that loads `ship.png` needs one whether
# it is being checked or being photographed. # it is being checked or being photographed.
@@ -136,7 +153,7 @@ render()
# stderr, so merging the two would make every sprite figure look like a # stderr, so merging the two would make every sprite figure look like a
# failing program. stderr is shown when the tool itself refuses, which is # failing program. stderr is shown when the tool itself refuses, which is
# when it is worth reading. # when it is worth reading.
if ! log="$(cd "${WORK}" && "${TOOL}" "${name}.bas" "${out}" "${w}" "${h}" \ if ! log="$(cd "${WORK}" && "${TOOL}" "${name}.bas" "${out}" "${w}" "${h}" "${font}" \
2>"${WORK}/${name}.err")"; then 2>"${WORK}/${name}.err")"; then
echo "FAIL ${where}: ${name} did not render" >&2 echo "FAIL ${where}: ${name} did not render" >&2
cat "${WORK}/${name}.err" >&2 cat "${WORK}/${name}.err" >&2
@@ -196,7 +213,8 @@ for DOC in "${DOCS[@]}"; do
NAME="$(attr screenshot "${INFO}")" NAME="$(attr screenshot "${INFO}")"
if [ -n "${NAME}" ]; then if [ -n "${NAME}" ]; then
render "${NAME}" "${BODY}" "$(attr size "${INFO}")" \ render "${NAME}" "${BODY}" "$(attr size "${INFO}")" \
"${DOC}:${START}" "$(attr setup "${INFO}")" "${DOC}:${START}" "$(attr setup "${INFO}")" \
"$(attr text "${INFO}")"
fi fi
fi fi
;; ;;

View File

@@ -16,10 +16,23 @@
* completion, read the target back, write it out. deps/libakgl/tests/draw.c and * completion, read the target back, write it out. deps/libakgl/tests/draw.c and
* tests/akgl_backends.c set that pattern; this is the third user of it. * tests/akgl_backends.c set that pattern; this is the third user of it.
* *
* **The text layer is deliberately not drawn.** A screenshot in the graphics * **The text layer is not drawn unless a font is named.** A screenshot in the
* chapter is of the drawing, and a `READY` in the corner is noise in a figure * graphics chapter is of the drawing, and a `READY` in the corner is noise in a
* about `CIRCLE`. It also means no font has to be found, which keeps this * figure about `CIRCLE`; leaving the layer out also means no font has to be
* runnable from a build tree with no assets resolved. * found, which keeps this runnable from a build tree with no assets resolved.
*
* A figure of a program whose *output is text* needs the opposite, and
* docs/17-tutorial-breakout.md is one: that game's wall, HUD and messages are
* characters in the grid, so a picture without the text layer is a picture of
* two sprites on a black field. Naming a font as the fifth argument swaps the
* stdio sink for the akgl one and renders the grid before the sprites, in the
* same order src/frontend_akgl.c uses. The fence attribute that asks for it is
* `text=1`; tools/docs_screenshots.sh turns that into this argument.
*
* The sink is the akgl one *alone* rather than a tee, so a program's output
* lands in the picture rather than on stdout -- which is what the caller reads
* to decide a figure failed. Nothing is lost: `screenshot=` blocks are also run
* by tests/docs_examples.sh, which is where a raised error is caught.
*/ */
#include <stdio.h> #include <stdio.h>
@@ -28,6 +41,7 @@
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <SDL3_image/SDL_image.h> #include <SDL3_image/SDL_image.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <akerror.h> #include <akerror.h>
@@ -46,6 +60,7 @@
#include <akbasic/akgl.h> #include <akbasic/akgl.h>
#include <akbasic/error.h> #include <akbasic/error.h>
#include <akbasic/frontend.h>
#include <akbasic/runtime.h> #include <akbasic/runtime.h>
#include <akbasic/sink.h> #include <akbasic/sink.h>
@@ -53,6 +68,9 @@
static akbasic_Runtime RUNTIME; static akbasic_Runtime RUNTIME;
static akbasic_TextSink SINK; static akbasic_TextSink SINK;
static akbasic_StdioSink SINKSTATE; static akbasic_StdioSink SINKSTATE;
/** @brief The text grid, and the font behind it. Only used when one is named. */
static akbasic_AkglSink GRIDSTATE;
static TTF_Font *FONT = NULL;
static akbasic_GraphicsBackend GRAPHICS; static akbasic_GraphicsBackend GRAPHICS;
static akbasic_AkglGraphics GRAPHICSSTATE; static akbasic_AkglGraphics GRAPHICSSTATE;
static akbasic_SpriteBackend SPRITES; static akbasic_SpriteBackend SPRITES;
@@ -68,10 +86,13 @@ static char SOURCE[65536];
static void usage(void) static void usage(void)
{ {
fprintf(stderr, fprintf(stderr,
"usage: akbasic_screenshot <program.bas> <output.png> [width] [height]\n" "usage: akbasic_screenshot <program.bas> <output.png> [width] [height] [font.ttf]\n"
"\n" "\n"
" Runs the program against an offscreen renderer of the given size\n" " Runs the program against an offscreen renderer of the given size\n"
" (default 320x200) and writes what it drew as a PNG.\n"); " (default 320x200) and writes what it drew as a PNG.\n"
"\n"
" Naming a font draws the text grid as well, for a figure of a\n"
" program whose output is characters rather than drawing.\n");
} }
/** @brief Slurp the program. A figure's listing is small; a partial read is not tolerated. */ /** @brief Slurp the program. A figure's listing is small; a partial read is not tolerated. */
@@ -98,7 +119,8 @@ static akerr_ErrorContext AKERR_NOIGNORE *read_program(const char *path)
* Split out so the ATTEMPT in main() has one thing to CATCH and the SDL * Split out so the ATTEMPT in main() has one thing to CATCH and the SDL
* teardown has one place to happen. * teardown has one place to happen.
*/ */
static akerr_ErrorContext AKERR_NOIGNORE *draw_program(const char *outpath, int w, int h) static akerr_ErrorContext AKERR_NOIGNORE *draw_program(const char *outpath, int w, int h,
const char *fontpath)
{ {
PREPARE_ERROR(errctx); PREPARE_ERROR(errctx);
SDL_Surface *shot = NULL; SDL_Surface *shot = NULL;
@@ -132,9 +154,22 @@ static akerr_ErrorContext AKERR_NOIGNORE *draw_program(const char *outpath, int
FAIL_ZERO_RETURN(errctx, SDL_RenderClear(akgl_renderer->sdl_renderer), FAIL_ZERO_RETURN(errctx, SDL_RenderClear(akgl_renderer->sdl_renderer),
AKGL_ERR_SDL, "%s", SDL_GetError()); AKGL_ERR_SDL, "%s", SDL_GetError());
/* stdout: a program that errors puts its "? line : CLASS message" there, /*
which is what the caller shows when a figure comes out wrong. */ * With no font: stdout, so a program that errors puts its
PASS(errctx, akbasic_sink_init_stdio(&SINK, &SINKSTATE, stdout, NULL)); * "? line : CLASS message" where the caller reads it. With one: the grid,
* so the characters the program writes are in the picture. The file comment
* explains why the two are not teed together.
*/
if ( fontpath == NULL ) {
PASS(errctx, akbasic_sink_init_stdio(&SINK, &SINKSTATE, stdout, NULL));
} else {
FAIL_ZERO_RETURN(errctx, TTF_Init(), AKGL_ERR_SDL,
"Couldn't initialize SDL_ttf: %s", SDL_GetError());
FONT = TTF_OpenFont(fontpath, (float)AKBASIC_FRONTEND_FONT_SIZE);
FAIL_ZERO_RETURN(errctx, (FONT != NULL), AKGL_ERR_SDL,
"Couldn't open the font %s: %s", fontpath, SDL_GetError());
PASS(errctx, akbasic_sink_init_akgl(&SINK, &GRIDSTATE, akgl_renderer, FONT, w, h));
}
PASS(errctx, akbasic_runtime_init(&RUNTIME, &SINK)); PASS(errctx, akbasic_runtime_init(&RUNTIME, &SINK));
PASS(errctx, akbasic_graphics_init_akgl(&GRAPHICS, &GRAPHICSSTATE, akgl_renderer)); PASS(errctx, akbasic_graphics_init_akgl(&GRAPHICS, &GRAPHICSSTATE, akgl_renderer));
PASS(errctx, akbasic_sprite_init_akgl(&SPRITES, &SPRITESSTATE, akgl_renderer, &GRAPHICSSTATE)); PASS(errctx, akbasic_sprite_init_akgl(&SPRITES, &SPRITESSTATE, akgl_renderer, &GRAPHICSSTATE));
@@ -144,11 +179,16 @@ static akerr_ErrorContext AKERR_NOIGNORE *draw_program(const char *outpath, int
PASS(errctx, akbasic_runtime_run(&RUNTIME, 0)); PASS(errctx, akbasic_runtime_run(&RUNTIME, 0));
/* /*
* The drawing verbs are immediate and are already on the target. Sprites are * The drawing verbs are immediate and are already on the target. The text
* not: they are libakgl actors and reach the target through a render pass, * grid and the sprites are not: both are redrawn from state the interpreter
* which in the standalone frontend is part of a frame. There is no frame * keeps, which in the standalone frontend happens once a frame. There is no
* here, so this is it. * frame here, so this is it -- and the order is the frontend's, grid first
* and sprites over it, because that ordering is what a program written
* against the real host will have assumed.
*/ */
if ( fontpath != NULL ) {
PASS(errctx, akbasic_sink_akgl_render(&SINK));
}
PASS(errctx, akbasic_sprite_akgl_render(&SPRITES)); PASS(errctx, akbasic_sprite_akgl_render(&SPRITES));
shot = SDL_RenderReadPixels(akgl_renderer->sdl_renderer, NULL); shot = SDL_RenderReadPixels(akgl_renderer->sdl_renderer, NULL);
@@ -167,6 +207,7 @@ int main(int argc, char **argv)
PREPARE_ERROR(errctx); PREPARE_ERROR(errctx);
int w = 320; int w = 320;
int h = 200; int h = 200;
const char *fontpath = NULL;
if ( argc < 3 ) { if ( argc < 3 ) {
usage(); usage();
@@ -178,6 +219,9 @@ int main(int argc, char **argv)
if ( argc > 4 ) { if ( argc > 4 ) {
h = atoi(argv[4]); h = atoi(argv[4]);
} }
if ( argc > 5 && argv[5][0] != '\0' ) {
fontpath = argv[5];
}
if ( w <= 0 || h <= 0 ) { if ( w <= 0 || h <= 0 ) {
usage(); usage();
return 2; return 2;
@@ -194,8 +238,13 @@ int main(int argc, char **argv)
ATTEMPT { ATTEMPT {
CATCH(errctx, read_program(argv[1])); CATCH(errctx, read_program(argv[1]));
CATCH(errctx, draw_program(argv[2], w, h)); CATCH(errctx, draw_program(argv[2], w, h, fontpath));
} CLEANUP { } CLEANUP {
if ( FONT != NULL ) {
TTF_CloseFont(FONT);
FONT = NULL;
TTF_Quit();
}
if ( akgl_window != NULL ) { if ( akgl_window != NULL ) {
SDL_DestroyWindow(akgl_window); SDL_DestroyWindow(akgl_window);
akgl_window = NULL; akgl_window = NULL;