10 Commits

Author SHA1 Message Date
dc78c791df ci/tasks/readme: register sfx-maker (sfxc)
All checks were successful
release-tools / build-release (push) Successful in 32s
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MmdG9GqfSWCzts7AkDwRDh
2026-07-14 07:08:41 +02:00
d2bf781a71 Merge dev/sfx-maker: sfxc v1 2026-07-14 07:08:05 +02:00
e7ac31b5c8 sfx-maker: sfxc - sfxr-style .sfx text presets -> 16-bit WAV synthesis
- waves: square (duty), saw, sine, triangle, pitched noise (seeded, deterministic)
- envelope attack/sustain/decay, freq slide, vibrato, arpeggio jump,
  one-pole low/high-pass filters, clamped output
- presets blip/coin/explosion/hurt/jump/laser/powerup with seeded variants;
  preset writes editable .sfx or renders .wav directly
- go tests: parse/validate, determinism, per-preset RMS, WAV header roundtrip

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MmdG9GqfSWCzts7AkDwRDh
2026-07-14 07:08:04 +02:00
ec814c373a ci/tasks/readme: register bitmap-font-maker (fontc)
All checks were successful
release-tools / build-release (push) Successful in 36s
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MmdG9GqfSWCzts7AkDwRDh
2026-07-14 07:04:28 +02:00
6b3a493703 Merge dev/bitmap-font-maker: fontc v1 2026-07-14 07:03:15 +02:00
6b10c4a57c bitmap-font-maker: fontc - .font glyph grids -> atlas PNG + metrics JSON + text rendering
- .font format: glyph sections with #/. grids, proportional widths,
  literal unicode glyph names, spacing/space-width/line-height/baseline
- build (atlas white-on-transparent + JSON metrics), render (text -> PNG
  with \n, scale, color), info, preview (terminal half-blocks)
- example tiny5 font: A-Z, ÅÄÖ, 0-9, punctuation (47 glyphs, 3x5)
- go tests: parsing, errors, atlas metrics, text rendering

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MmdG9GqfSWCzts7AkDwRDh
2026-07-14 07:03:04 +02:00
a5b8a249ed Merge dev/mesh-tool: mesht v1
All checks were successful
release-tools / build-release (push) Successful in 1m53s
2026-07-14 02:39:01 +02:00
3eb4fa0b1d Merge dev/pixel-sprite-maker: spritec v1 2026-07-14 02:37:58 +02:00
42422be2f7 scaffolding: root README, plan, VS Code build tasks, Gitea Actions release workflow
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MmdG9GqfSWCzts7AkDwRDh
2026-07-14 02:37:58 +02:00
23135a96d1 pixel-sprite-maker: spritec - .sprite text format -> png/jpg/svg + sprite sheets
- .sprite format: single-char palette keys (hex/rgb()/CSS names/none), grid
  rows, '.' transparent by default, max 256x256 per sprite
- render/sheet/info/preview subcommands; sheets name themselves
  <base>_<cellW>x<cellH>_<cols>x<rows>.<ext> (row-major)
- SVG output RLE-merges pixel runs; JPG composites over --bg
- go tests for parser, colors, scaling, svg, sheet layout

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MmdG9GqfSWCzts7AkDwRDh
2026-07-14 02:22:16 +02:00
57 changed files with 4303 additions and 1 deletions

View File

@@ -0,0 +1,109 @@
name: release-tools
# På varje push till master/main: bygg de tools som fått ändringar
# (linux x64 + arm64) och lägg binärerna på en rullande
# "<tool>-latest"-release på släppsidan i Gitea.
on:
push:
branches: [master, main]
workflow_dispatch: {} # manuell körning bygger ALLA tools
jobs:
build-release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # hela historiken behövs för diffen mot 'before'
- name: Detektera ändrade tools
id: changed
run: |
TOOLS="pixel-sprite-maker mesh-tool bitmap-font-maker sfx-maker"
BEFORE="${{ github.event.before }}"
CHANGED=""
if [ "${{ github.event_name }}" = "workflow_dispatch" ] \
|| [ -z "$BEFORE" ] \
|| echo "$BEFORE" | grep -Eq '^0+$' \
|| ! git cat-file -e "$BEFORE" 2>/dev/null; then
echo "första push / manuell körning -> bygger alla tools"
CHANGED="$TOOLS"
else
for t in $TOOLS; do
if ! git diff --quiet "$BEFORE" "${{ github.sha }}" -- "$t/"; then
CHANGED="$CHANGED $t"
fi
done
fi
CHANGED="$(echo $CHANGED)" # trimma whitespace
echo "tools=$CHANGED" >> "$GITHUB_OUTPUT"
echo "bygger: ${CHANGED:-inget}"
- name: Installera Go
if: steps.changed.outputs.tools != ''
uses: actions/setup-go@v5
with:
go-version: "1.24"
cache: false
- name: Testa + bygg (x64 + arm64)
if: steps.changed.outputs.tools != ''
run: |
set -e
VERSION="latest-$(git rev-parse --short HEAD)"
for t in ${{ steps.changed.outputs.tools }}; do
case "$t" in
pixel-sprite-maker) BIN=spritec ;;
mesh-tool) BIN=mesht ;;
bitmap-font-maker) BIN=fontc ;;
sfx-maker) BIN=sfxc ;;
*) echo "okänt tool $t"; exit 1 ;;
esac
echo "=== $t ($BIN) ==="
cd "$t"
go test ./...
mkdir -p build
GOOS=linux GOARCH=amd64 go build -trimpath \
-ldflags "-s -w -X main.version=$VERSION" -o "build/$BIN-linux-x64" .
GOOS=linux GOARCH=arm64 go build -trimpath \
-ldflags "-s -w -X main.version=$VERSION" -o "build/$BIN-linux-arm64" .
(cd build && sha256sum "$BIN"-linux-* > checksums.txt && ls -la)
cd ..
done
- name: Skapa/uppdatera releaser + ladda upp binärer
if: steps.changed.outputs.tools != ''
env:
API: http://gitea-d:3000/api/v1
REPO: ${{ github.repository }}
TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -e
for t in ${{ steps.changed.outputs.tools }}; do
case "$t" in
pixel-sprite-maker) BIN=spritec ;;
mesh-tool) BIN=mesht ;;
bitmap-font-maker) BIN=fontc ;;
sfx-maker) BIN=sfxc ;;
esac
TAG="$t-latest"
BODY="$t (binär: $BIN) - rullande bygge från senaste master. Commit: ${{ github.sha }}. Arkitekturer: linux x64 + arm64 (Pi5)."
rid=$(curl -s -X POST "$API/repos/$REPO/releases" \
-H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":\"$BODY\"}" | jq -r '.id // empty')
[ -z "$rid" ] && rid=$(curl -s "$API/repos/$REPO/releases/tags/$TAG" \
-H "Authorization: token $TOKEN" | jq -r '.id')
echo "$t -> release id $rid"
for f in "$BIN-linux-x64" "$BIN-linux-arm64" checksums.txt; do
aid=$(curl -s "$API/repos/$REPO/releases/$rid/assets" \
-H "Authorization: token $TOKEN" | jq -r ".[] | select(.name==\"$f\") | .id")
if [ -n "$aid" ] && [ "$aid" != "null" ]; then
curl -s -X DELETE "$API/repos/$REPO/releases/$rid/assets/$aid" \
-H "Authorization: token $TOKEN" -o /dev/null
fi
curl -s -X POST "$API/repos/$REPO/releases/$rid/assets?name=$f" \
-H "Authorization: token $TOKEN" \
-F "attachment=@$t/build/$f" -o /dev/null -w " $f -> HTTP %{http_code}\n"
done
done

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
build/
*.exe
mesh-tool/examples/downloads/

76
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,76 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build pixel-sprite-maker",
"type": "shell",
"command": "go build -trimpath -ldflags '-s -w' -o build/spritec .",
"options": { "cwd": "${workspaceFolder}/pixel-sprite-maker" },
"group": "build",
"problemMatcher": ["$go"]
},
{
"label": "build mesh-tool",
"type": "shell",
"command": "go build -trimpath -ldflags '-s -w' -o build/mesht .",
"options": { "cwd": "${workspaceFolder}/mesh-tool" },
"group": "build",
"problemMatcher": ["$go"]
},
{
"label": "build bitmap-font-maker",
"type": "shell",
"command": "go build -trimpath -ldflags '-s -w' -o build/fontc .",
"options": { "cwd": "${workspaceFolder}/bitmap-font-maker" },
"group": "build",
"problemMatcher": ["$go"]
},
{
"label": "test bitmap-font-maker",
"type": "shell",
"command": "go test ./...",
"options": { "cwd": "${workspaceFolder}/bitmap-font-maker" },
"group": "test",
"problemMatcher": ["$go"]
},
{
"label": "build sfx-maker",
"type": "shell",
"command": "go build -trimpath -ldflags '-s -w' -o build/sfxc .",
"options": { "cwd": "${workspaceFolder}/sfx-maker" },
"group": "build",
"problemMatcher": ["$go"]
},
{
"label": "test sfx-maker",
"type": "shell",
"command": "go test ./...",
"options": { "cwd": "${workspaceFolder}/sfx-maker" },
"group": "test",
"problemMatcher": ["$go"]
},
{
"label": "test pixel-sprite-maker",
"type": "shell",
"command": "go test ./...",
"options": { "cwd": "${workspaceFolder}/pixel-sprite-maker" },
"group": "test",
"problemMatcher": ["$go"]
},
{
"label": "test mesh-tool",
"type": "shell",
"command": "go test ./...",
"options": { "cwd": "${workspaceFolder}/mesh-tool" },
"group": "test",
"problemMatcher": ["$go"]
},
{
"label": "build",
"dependsOn": ["build pixel-sprite-maker", "build mesh-tool", "build bitmap-font-maker", "build sfx-maker"],
"dependsOrder": "parallel",
"group": { "kind": "build", "isDefault": true },
"problemMatcher": []
}
]
}

View File

@@ -1,3 +1,48 @@
# agent-tools # agent-tools
smal tools for ai agents Small, self-contained CLI tools built for **AI agents** to use during
development work. Every tool is a single static Go binary with a
text-first interface: input formats an agent can read and write
directly, and output (names, errors, previews) explicit enough that the
agent understands the result without opening an image viewer.
| Tool | Binary | What it does |
|------|--------|--------------|
| [`pixel-sprite-maker/`](pixel-sprite-maker/) | `spritec` | Turns `.sprite` text files (palette + character grid) into PNG/JPG/SVG pixel art, up to 256x256 px per sprite. Combines several sprites into sprite sheets / animation strips whose **file names document the layout** (`walk_8x8_4x1.png` = 8x8 px frames, 4 columns, 1 row). |
| [`mesh-tool/`](mesh-tool/) | `mesht` | Creates, inspects and edits 3D models (OBJ + STL). ASCII multi-view rendering + measurements (bbox, volume, watertightness) let an agent *see* a model, edit it (scale/rotate/mirror/merge/primitives) and verify the result. |
| [`bitmap-font-maker/`](bitmap-font-maker/) | `fontc` | Turns `.font` text files (pixel glyph grids, proportional widths) into font atlases (PNG + JSON metrics) and renders text strings to PNG or the terminal. |
| [`sfx-maker/`](sfx-maker/) | `sfxc` | Synthesizes retro game sound effects (sfxr-style) from `.sfx` text presets to 16-bit WAV: waves, envelope, pitch slides, vibrato, arpeggio, filters. Deterministic, with built-in presets (jump, coin, laser…). |
Each tool has its own folder, its own README with the full format/CLI
reference, its own tests and its own dev branch (`dev/<tool>`).
## Building
```bash
# Arch/Garuda prerequisite:
sudo pacman -S go
cd <tool>/ && go build -o build/<binary> . # per tool
go test ./... # per tool
```
VS Code: **Terminal → Run Build Task**`build` builds every tool into
its own `<tool>/build/` folder; per-tool `build <tool>` and
`test <tool>` tasks also exist.
## CI / releases
`.gitea/workflows/release.yml` runs on every push to `master`/`main` on
the self-hosted runner: tools whose folders changed are tested, built
for **linux x64 + arm64** (the Pi5), and published to a rolling
release per tool on the repo's release page:
- tag `pixel-sprite-maker-latest` → assets `spritec-linux-x64`, `spritec-linux-arm64`, `checksums.txt`
- tag `mesh-tool-latest` → assets `mesht-linux-x64`, `mesht-linux-arm64`, `checksums.txt`
A manual `workflow_dispatch` run builds all tools regardless of diffs.
## Branch layout
- `main` — stable, releases are built from here
- `dev/pixel-sprite-maker`, `dev/mesh-tool` — per-tool development branches

View File

@@ -0,0 +1,75 @@
# bitmap-font-maker (`fontc`)
Turns `.font` text files — pixel glyph grids an agent can read and edit
directly — into **font atlases (PNG + JSON metrics)** and renders text
strings to PNG. Proportional widths, unicode glyph names (ÅÄÖ works).
Go, zero dependencies, single static binary.
## Build
```bash
# Arch/Garuda: sudo pacman -S go
cd bitmap-font-maker
go build -o build/fontc . # or the VS Code task "build bitmap-font-maker"
go test ./...
```
## The `.font` format
```
# comment
font: tiny5 optional name
spacing: 1 px between glyphs (default 1)
space-width: 3 advance of ' ' (default: width of '0')
line-height: 7 default: glyph height + 1
baseline: 5 default: glyph height
glyph A:
.#.
#.#
###
#.#
#.#
glyph :: the char between "glyph " and ":" is literal
.
#
.
#
.
```
- `#` = pixel on, `.` = off.
- **All glyphs share one height; widths may differ** (proportional fonts —
`M` can be 5 px wide while `.` is 1 px).
- Max glyph size 64x64.
## Commands
```bash
fontc build tiny5.font -o out/tiny5 # -> tiny5.png (atlas) + tiny5.json (metrics)
fontc render tiny5.font 'HEJ!\nRAD 2' --scale 4 --color '#FFD700' -o title.png
fontc info tiny5.font # validate + list glyphs
fontc preview tiny5.font 'HELLO' # draw in the terminal
```
## Atlas + metrics
The atlas draws glyphs **white on transparent** so game engines can tint
them. The JSON carries everything a loader needs:
```json
{
"name": "tiny5", "atlas": "tiny5.png",
"height": 5, "lineHeight": 6, "baseline": 5,
"spacing": 1, "spaceWidth": 3,
"glyphs": { "A": {"x": 0, "y": 0, "w": 3, "h": 5, "advance": 4}, ... }
}
```
Drawing text in a game: blit `glyphs[c]` from the atlas, advance the
cursor by `advance`; spaces advance `spaceWidth + spacing`; new lines
step `lineHeight`.
[`examples/tiny5.font`](examples/tiny5.font) is a complete 3x5 font:
A-Z, ÅÄÖ, 0-9 and punctuation.

Binary file not shown.

After

Width:  |  Height:  |  Size: 405 B

View File

@@ -0,0 +1,340 @@
{
"name": "tiny5",
"atlas": "tiny5.png",
"height": 5,
"lineHeight": 6,
"baseline": 5,
"spacing": 1,
"spaceWidth": 3,
"glyphs": {
"!": {
"x": 36,
"y": 30,
"w": 1,
"h": 5,
"advance": 2
},
"'": {
"x": 24,
"y": 36,
"w": 1,
"h": 5,
"advance": 2
},
"+": {
"x": 18,
"y": 36,
"w": 3,
"h": 5,
"advance": 4
},
",": {
"x": 30,
"y": 30,
"w": 2,
"h": 5,
"advance": 3
},
"-": {
"x": 12,
"y": 36,
"w": 3,
"h": 5,
"advance": 4
},
".": {
"x": 24,
"y": 30,
"w": 1,
"h": 5,
"advance": 2
},
"0": {
"x": 6,
"y": 24,
"w": 3,
"h": 5,
"advance": 4
},
"1": {
"x": 12,
"y": 24,
"w": 3,
"h": 5,
"advance": 4
},
"2": {
"x": 18,
"y": 24,
"w": 3,
"h": 5,
"advance": 4
},
"3": {
"x": 24,
"y": 24,
"w": 3,
"h": 5,
"advance": 4
},
"4": {
"x": 30,
"y": 24,
"w": 3,
"h": 5,
"advance": 4
},
"5": {
"x": 36,
"y": 24,
"w": 3,
"h": 5,
"advance": 4
},
"6": {
"x": 0,
"y": 30,
"w": 3,
"h": 5,
"advance": 4
},
"7": {
"x": 6,
"y": 30,
"w": 3,
"h": 5,
"advance": 4
},
"8": {
"x": 12,
"y": 30,
"w": 3,
"h": 5,
"advance": 4
},
"9": {
"x": 18,
"y": 30,
"w": 3,
"h": 5,
"advance": 4
},
":": {
"x": 6,
"y": 36,
"w": 1,
"h": 5,
"advance": 2
},
"?": {
"x": 0,
"y": 36,
"w": 3,
"h": 5,
"advance": 4
},
"A": {
"x": 0,
"y": 0,
"w": 3,
"h": 5,
"advance": 4
},
"B": {
"x": 6,
"y": 0,
"w": 3,
"h": 5,
"advance": 4
},
"C": {
"x": 12,
"y": 0,
"w": 3,
"h": 5,
"advance": 4
},
"D": {
"x": 18,
"y": 0,
"w": 3,
"h": 5,
"advance": 4
},
"E": {
"x": 24,
"y": 0,
"w": 3,
"h": 5,
"advance": 4
},
"F": {
"x": 30,
"y": 0,
"w": 3,
"h": 5,
"advance": 4
},
"G": {
"x": 36,
"y": 0,
"w": 4,
"h": 5,
"advance": 5
},
"H": {
"x": 0,
"y": 6,
"w": 3,
"h": 5,
"advance": 4
},
"I": {
"x": 6,
"y": 6,
"w": 3,
"h": 5,
"advance": 4
},
"J": {
"x": 12,
"y": 6,
"w": 3,
"h": 5,
"advance": 4
},
"K": {
"x": 18,
"y": 6,
"w": 3,
"h": 5,
"advance": 4
},
"L": {
"x": 24,
"y": 6,
"w": 3,
"h": 5,
"advance": 4
},
"M": {
"x": 30,
"y": 6,
"w": 5,
"h": 5,
"advance": 6
},
"N": {
"x": 36,
"y": 6,
"w": 4,
"h": 5,
"advance": 5
},
"O": {
"x": 0,
"y": 12,
"w": 3,
"h": 5,
"advance": 4
},
"P": {
"x": 6,
"y": 12,
"w": 3,
"h": 5,
"advance": 4
},
"Q": {
"x": 12,
"y": 12,
"w": 4,
"h": 5,
"advance": 5
},
"R": {
"x": 18,
"y": 12,
"w": 3,
"h": 5,
"advance": 4
},
"S": {
"x": 24,
"y": 12,
"w": 3,
"h": 5,
"advance": 4
},
"T": {
"x": 30,
"y": 12,
"w": 3,
"h": 5,
"advance": 4
},
"U": {
"x": 36,
"y": 12,
"w": 3,
"h": 5,
"advance": 4
},
"V": {
"x": 0,
"y": 18,
"w": 3,
"h": 5,
"advance": 4
},
"W": {
"x": 6,
"y": 18,
"w": 5,
"h": 5,
"advance": 6
},
"X": {
"x": 12,
"y": 18,
"w": 3,
"h": 5,
"advance": 4
},
"Y": {
"x": 18,
"y": 18,
"w": 3,
"h": 5,
"advance": 4
},
"Z": {
"x": 24,
"y": 18,
"w": 3,
"h": 5,
"advance": 4
},
"Ä": {
"x": 36,
"y": 18,
"w": 3,
"h": 5,
"advance": 4
},
"Å": {
"x": 30,
"y": 18,
"w": 3,
"h": 5,
"advance": 4
},
"Ö": {
"x": 0,
"y": 24,
"w": 3,
"h": 5,
"advance": 4
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 B

View File

@@ -0,0 +1,334 @@
# tiny5 - a 3x5 pixel font (uppercase + digits + Swedish ÅÄÖ).
# Widths vary: M/W are 5 px, punctuation as narrow as 1 px.
font: tiny5
spacing: 1
space-width: 3
glyph A:
.#.
#.#
###
#.#
#.#
glyph B:
##.
#.#
##.
#.#
##.
glyph C:
.##
#..
#..
#..
.##
glyph D:
##.
#.#
#.#
#.#
##.
glyph E:
###
#..
##.
#..
###
glyph F:
###
#..
##.
#..
#..
glyph G:
.###
#...
#.##
#..#
.##.
glyph H:
#.#
#.#
###
#.#
#.#
glyph I:
###
.#.
.#.
.#.
###
glyph J:
..#
..#
..#
#.#
.#.
glyph K:
#.#
#.#
##.
#.#
#.#
glyph L:
#..
#..
#..
#..
###
glyph M:
#...#
##.##
#.#.#
#...#
#...#
glyph N:
#..#
##.#
#.##
#..#
#..#
glyph O:
.#.
#.#
#.#
#.#
.#.
glyph P:
##.
#.#
##.
#..
#..
glyph Q:
.##.
#..#
#..#
#.#.
.#.#
glyph R:
##.
#.#
##.
#.#
#.#
glyph S:
.##
#..
.#.
..#
##.
glyph T:
###
.#.
.#.
.#.
.#.
glyph U:
#.#
#.#
#.#
#.#
###
glyph V:
#.#
#.#
#.#
#.#
.#.
glyph W:
#...#
#...#
#.#.#
##.##
#...#
glyph X:
#.#
#.#
.#.
#.#
#.#
glyph Y:
#.#
#.#
.#.
.#.
.#.
glyph Z:
###
..#
.#.
#..
###
glyph Å:
.#.
.#.
#.#
###
#.#
glyph Ä:
#.#
.#.
#.#
###
#.#
glyph Ö:
#.#
.#.
#.#
#.#
.#.
glyph 0:
###
#.#
#.#
#.#
###
glyph 1:
.#.
##.
.#.
.#.
###
glyph 2:
##.
..#
.#.
#..
###
glyph 3:
###
..#
.##
..#
###
glyph 4:
#.#
#.#
###
..#
..#
glyph 5:
###
#..
##.
..#
##.
glyph 6:
.##
#..
###
#.#
###
glyph 7:
###
..#
.#.
.#.
.#.
glyph 8:
###
#.#
###
#.#
###
glyph 9:
###
#.#
###
..#
##.
glyph .:
.
.
.
.
#
glyph ,:
..
..
..
.#
#.
glyph !:
#
#
#
.
#
glyph ?:
###
..#
.#.
...
.#.
glyph ::
.
#
.
#
.
glyph -:
...
...
###
...
...
glyph +:
...
.#.
###
.#.
...
glyph ':
#
#
.
.
.

View File

@@ -0,0 +1,238 @@
// Package font parses .font text files and renders bitmap fonts to
// atlases (PNG + JSON metrics) and text images.
package font
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
)
// MaxGlyphSize bounds glyph width/height in pixels.
const MaxGlyphSize = 64
// Glyph is one character's bitmap: rows of booleans (true = pixel on).
// All glyphs in a font share the same height; widths vary
// (proportional fonts).
type Glyph struct {
Char rune
W, H int
Rows [][]bool
}
// Font is a parsed .font file.
type Font struct {
Name string
Height int // glyph height, uniform across the font
LineHeight int // suggested distance between text baselines
Baseline int // rows from glyph top to the baseline
Spacing int // horizontal px between glyphs
SpaceWidth int // advance of ' '
Glyphs map[rune]*Glyph
Order []rune // file order, for stable atlas layout
}
// ParseFile reads a .font file; the font name defaults to the file name.
func ParseFile(path string) (*Font, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
ft, err := Parse(f)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if ft.Name == "" {
ft.Name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
}
return ft, nil
}
// Parse reads the .font text format:
//
// # comment
// font: tiny5 optional name
// spacing: 1 px between glyphs (default 1)
// space-width: 3 advance of ' ' (default: width of '0' or 3)
// line-height: 7 default: glyph height + 1
// baseline: 5 default: glyph height
//
// glyph A:
// .#.
// #.#
// ###
// #.#
// #.#
//
// Glyph grids use '#' for on and '.' for off. Every glyph must have the
// same height; widths may differ. The char between "glyph " and the
// trailing ':' is taken literally (one character, e.g. "glyph ::").
func Parse(r io.Reader) (*Font, error) {
ft := &Font{
Spacing: 1,
SpaceWidth: -1, // resolved in validate
LineHeight: -1,
Baseline: -1,
Glyphs: map[rune]*Glyph{},
}
var cur *Glyph
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
lineNo := 0
flush := func() error {
if cur == nil {
return nil
}
if len(cur.Rows) == 0 {
return fmt.Errorf("glyph %q has no grid rows", string(cur.Char))
}
cur.H = len(cur.Rows)
cur.W = len(cur.Rows[0])
for i, row := range cur.Rows {
if len(row) != cur.W {
return fmt.Errorf("glyph %q row %d is %d px wide, expected %d", string(cur.Char), i+1, len(row), cur.W)
}
}
if cur.W > MaxGlyphSize || cur.H > MaxGlyphSize {
return fmt.Errorf("glyph %q is %dx%d; the maximum is %dx%d", string(cur.Char), cur.W, cur.H, MaxGlyphSize, MaxGlyphSize)
}
if _, dup := ft.Glyphs[cur.Char]; dup {
return fmt.Errorf("glyph %q defined twice", string(cur.Char))
}
ft.Glyphs[cur.Char] = cur
ft.Order = append(ft.Order, cur.Char)
cur = nil
return nil
}
for sc.Scan() {
lineNo++
line := strings.TrimSpace(sc.Text())
if line == "" {
continue
}
// '#' starts a comment — except inside a glyph where a line of
// only '#'/'.' is a grid row.
if strings.HasPrefix(line, "#") && !(cur != nil && isGridLine(line)) {
continue
}
if strings.HasPrefix(strings.ToLower(line), "glyph ") && strings.HasSuffix(line, ":") {
if err := flush(); err != nil {
return nil, fmt.Errorf("line %d: %w", lineNo, err)
}
name := strings.TrimSuffix(line[len("glyph "):], ":")
runes := []rune(name)
if len(runes) != 1 {
return nil, fmt.Errorf("line %d: glyph name %q must be exactly one character", lineNo, name)
}
cur = &Glyph{Char: runes[0]}
continue
}
if cur != nil && isGridLine(line) {
row := make([]bool, 0, len(line))
for _, r := range line {
row = append(row, r == '#')
}
cur.Rows = append(cur.Rows, row)
continue
}
// header key: value
if i := strings.Index(line, ":"); i > 0 && cur == nil {
key := strings.ToLower(strings.TrimSpace(line[:i]))
val := strings.TrimSpace(line[i+1:])
var err error
switch key {
case "font":
ft.Name = val
case "spacing":
ft.Spacing, err = strconv.Atoi(val)
case "space-width":
ft.SpaceWidth, err = strconv.Atoi(val)
case "line-height":
ft.LineHeight, err = strconv.Atoi(val)
case "baseline":
ft.Baseline, err = strconv.Atoi(val)
default:
return nil, fmt.Errorf("line %d: unknown setting %q", lineNo, key)
}
if err != nil {
return nil, fmt.Errorf("line %d: %s: %v", lineNo, key, err)
}
continue
}
return nil, fmt.Errorf("line %d: unexpected %q (want 'key: value', 'glyph X:' or a #/. grid row)", lineNo, line)
}
if err := sc.Err(); err != nil {
return nil, err
}
if err := flush(); err != nil {
return nil, err
}
return ft, ft.validate()
}
// isGridLine reports whether the line consists solely of '#' and '.'.
func isGridLine(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r != '#' && r != '.' {
return false
}
}
return true
}
func (ft *Font) validate() error {
if len(ft.Order) == 0 {
return fmt.Errorf("font has no glyphs")
}
ft.Height = ft.Glyphs[ft.Order[0]].H
for _, r := range ft.Order {
if g := ft.Glyphs[r]; g.H != ft.Height {
return fmt.Errorf("glyph %q is %d px tall but %q is %d — all glyphs must share one height",
string(r), g.H, string(ft.Order[0]), ft.Height)
}
}
if ft.LineHeight < 0 {
ft.LineHeight = ft.Height + 1
}
if ft.Baseline < 0 {
ft.Baseline = ft.Height
}
if ft.SpaceWidth < 0 {
if g, ok := ft.Glyphs['0']; ok {
ft.SpaceWidth = g.W
} else {
ft.SpaceWidth = 3
}
}
if ft.Spacing < 0 {
return fmt.Errorf("spacing must be >= 0")
}
return nil
}
// MaxGlyphWidth returns the widest glyph's width.
func (ft *Font) MaxGlyphWidth() int {
w := 0
for _, r := range ft.Order {
if g := ft.Glyphs[r]; g.W > w {
w = g.W
}
}
return w
}
// SortedChars returns the glyph chars sorted by codepoint (JSON stability).
func (ft *Font) SortedChars() []rune {
out := append([]rune(nil), ft.Order...)
sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
return out
}

View File

@@ -0,0 +1,144 @@
package font
import (
"bytes"
"encoding/json"
"image/color"
"strings"
"testing"
)
const tiny = `
font: t
spacing: 1
space-width: 2
glyph A:
.#.
#.#
###
glyph I:
#
#
#
`
func parseOK(t *testing.T, src string) *Font {
t.Helper()
ft, err := Parse(strings.NewReader(src))
if err != nil {
t.Fatalf("parse: %v", err)
}
return ft
}
func TestParseBasics(t *testing.T) {
ft := parseOK(t, tiny)
if ft.Name != "t" || ft.Height != 3 || len(ft.Order) != 2 {
t.Errorf("name=%q height=%d glyphs=%d", ft.Name, ft.Height, len(ft.Order))
}
a := ft.Glyphs['A']
if a.W != 3 || a.H != 3 {
t.Errorf("A is %dx%d, want 3x3", a.W, a.H)
}
if !a.Rows[1][0] || a.Rows[0][0] {
t.Error("A pixel pattern wrong")
}
i := ft.Glyphs['I']
if i.W != 1 {
t.Errorf("I width = %d, want 1 (proportional)", i.W)
}
if ft.LineHeight != 4 || ft.Baseline != 3 {
t.Errorf("defaults: lineHeight=%d baseline=%d", ft.LineHeight, ft.Baseline)
}
}
func TestParseErrors(t *testing.T) {
cases := map[string]string{
"no glyphs": "font: x\n",
"ragged glyph": "glyph A:\n##\n#\n",
"height differs": "glyph A:\n#\n#\n\nglyph B:\n#\n",
"dup glyph": "glyph A:\n#\n\nglyph A:\n#\n",
"bad name": "glyph AB:\n#\n",
"unknown key": "wat: 3\nglyph A:\n#\n",
}
for name, src := range cases {
if _, err := Parse(strings.NewReader(src)); err == nil {
t.Errorf("%s: expected error", name)
}
}
}
func TestGlyphNameColon(t *testing.T) {
ft := parseOK(t, "glyph ::\n#\n#\n")
if _, ok := ft.Glyphs[':']; !ok {
t.Error("glyph ':' not parsed")
}
}
func TestAtlasAndMetrics(t *testing.T) {
ft := parseOK(t, tiny)
img, m := ft.BuildAtlas("t.png")
if m.Glyphs["A"].Advance != 4 {
t.Errorf("A advance = %d, want 4 (w3 + spacing1)", m.Glyphs["A"].Advance)
}
g := m.Glyphs["A"]
// center-top pixel of A within its atlas cell: (x+1, y+0)
if img.NRGBAAt(g.X+1, g.Y).A == 0 {
t.Error("A apex pixel missing in atlas")
}
if img.NRGBAAt(g.X, g.Y).A != 0 {
t.Error("A corner should be empty")
}
var buf bytes.Buffer
if err := WriteMetrics(&buf, m); err != nil {
t.Fatal(err)
}
var back Metrics
if err := json.Unmarshal(buf.Bytes(), &back); err != nil {
t.Fatalf("metrics json invalid: %v", err)
}
if back.Glyphs["I"].W != 1 {
t.Errorf("metrics roundtrip: I.w = %d", back.Glyphs["I"].W)
}
}
func TestRenderText(t *testing.T) {
ft := parseOK(t, tiny)
white := color.NRGBA{255, 255, 255, 255}
img, warns := ft.RenderText("AI", 1, white)
if len(warns) != 0 {
t.Errorf("warnings: %v", warns)
}
// width: A(3) + spacing(1) + I(1) = 5
if b := img.Bounds(); b.Dx() != 5 || b.Dy() != 3 {
t.Errorf("size = %dx%d, want 5x3", b.Dx(), b.Dy())
}
// I column at x=4
if img.NRGBAAt(4, 0).A == 0 {
t.Error("I pixel missing")
}
_, warns = ft.RenderText("AXA", 1, white)
if len(warns) != 1 {
t.Errorf("missing-glyph warning expected, got %v", warns)
}
img, _ = ft.RenderText(`A\nA`, 1, white)
if b := img.Bounds(); b.Dy() != ft.LineHeight+ft.Height {
t.Errorf("two-line height = %d, want %d", b.Dy(), ft.LineHeight+ft.Height)
}
img2, _ := ft.RenderText("A", 3, white)
if b := img2.Bounds(); b.Dx() != 9 || b.Dy() != 9 {
t.Errorf("scaled size = %dx%d, want 9x9", b.Dx(), b.Dy())
}
}
func TestSpaceWidthDefaultFromZero(t *testing.T) {
ft := parseOK(t, "glyph 0:\n####\n####\n")
if ft.SpaceWidth != 4 {
t.Errorf("space-width = %d, want 4 (width of '0')", ft.SpaceWidth)
}
}

View File

@@ -0,0 +1,165 @@
package font
import (
"encoding/json"
"fmt"
"image"
"image/color"
"image/png"
"io"
"strings"
)
// AtlasGlyph is one glyph's placement in the atlas.
type AtlasGlyph struct {
X int `json:"x"`
Y int `json:"y"`
W int `json:"w"`
H int `json:"h"`
Advance int `json:"advance"` // cursor movement after drawing: W + spacing
}
// Metrics is the JSON sidecar written next to the atlas PNG.
type Metrics struct {
Name string `json:"name"`
Atlas string `json:"atlas"`
Height int `json:"height"`
LineHeight int `json:"lineHeight"`
Baseline int `json:"baseline"`
Spacing int `json:"spacing"`
SpaceWidth int `json:"spaceWidth"`
Glyphs map[string]AtlasGlyph `json:"glyphs"`
}
// BuildAtlas packs all glyphs into a grid atlas image (white pixels on
// transparency, so game engines can tint) and returns the metrics.
// atlasName is stored in the metrics so loaders can find the image.
func (ft *Font) BuildAtlas(atlasName string) (*image.NRGBA, *Metrics) {
n := len(ft.Order)
cols := 1
for cols*cols < n {
cols++
}
rows := (n + cols - 1) / cols
cellW := ft.MaxGlyphWidth() + 1 // 1 px padding against bleed
cellH := ft.Height + 1
img := image.NewNRGBA(image.Rect(0, 0, cols*cellW, rows*cellH))
white := color.NRGBA{255, 255, 255, 255}
m := &Metrics{
Name: ft.Name,
Atlas: atlasName,
Height: ft.Height,
LineHeight: ft.LineHeight,
Baseline: ft.Baseline,
Spacing: ft.Spacing,
SpaceWidth: ft.SpaceWidth,
Glyphs: map[string]AtlasGlyph{},
}
for i, r := range ft.Order {
g := ft.Glyphs[r]
x0 := (i % cols) * cellW
y0 := (i / cols) * cellH
drawGlyph(img, g, x0, y0, white)
m.Glyphs[string(r)] = AtlasGlyph{X: x0, Y: y0, W: g.W, H: g.H, Advance: g.W + ft.Spacing}
}
return img, m
}
func drawGlyph(img *image.NRGBA, g *Glyph, x0, y0 int, c color.NRGBA) {
for y, row := range g.Rows {
for x, on := range row {
if on {
img.SetNRGBA(x0+x, y0+y, c)
}
}
}
}
// RenderText draws text into a new image using the font. scale is an
// integer upscale factor; unknown characters are skipped with a warning
// returned. "\n" (literal backslash-n) and real newlines both break lines.
func (ft *Font) RenderText(text string, scale int, fg color.NRGBA) (*image.NRGBA, []string) {
if scale < 1 {
scale = 1
}
text = strings.ReplaceAll(text, `\n`, "\n")
lines := strings.Split(text, "\n")
var warnings []string
width := 0
for _, line := range lines {
if w := ft.lineWidth(line); w > width {
width = w
}
}
if width == 0 {
width = 1
}
height := ft.LineHeight*(len(lines)-1) + ft.Height
small := image.NewNRGBA(image.Rect(0, 0, width, height))
for li, line := range lines {
x := 0
y := li * ft.LineHeight
for _, r := range line {
if r == ' ' {
x += ft.SpaceWidth + ft.Spacing
continue
}
g, ok := ft.Glyphs[r]
if !ok {
warnings = append(warnings, fmt.Sprintf("no glyph for %q — skipped", string(r)))
x += ft.SpaceWidth + ft.Spacing
continue
}
drawGlyph(small, g, x, y, fg)
x += g.W + ft.Spacing
}
}
if scale == 1 {
return small, warnings
}
b := small.Bounds()
big := image.NewNRGBA(image.Rect(0, 0, b.Dx()*scale, b.Dy()*scale))
for y := 0; y < b.Dy(); y++ {
for x := 0; x < b.Dx(); x++ {
c := small.NRGBAAt(x, y)
for dy := 0; dy < scale; dy++ {
for dx := 0; dx < scale; dx++ {
big.SetNRGBA(x*scale+dx, y*scale+dy, c)
}
}
}
}
return big, warnings
}
func (ft *Font) lineWidth(line string) int {
x := 0
for _, r := range line {
if r == ' ' {
x += ft.SpaceWidth + ft.Spacing
continue
}
if g, ok := ft.Glyphs[r]; ok {
x += g.W + ft.Spacing
} else {
x += ft.SpaceWidth + ft.Spacing
}
}
if x > 0 {
x -= ft.Spacing // no trailing spacing
}
return x
}
// WritePNG encodes an image as PNG.
func WritePNG(w io.Writer, img image.Image) error { return png.Encode(w, img) }
// WriteMetrics encodes metrics as indented JSON.
func WriteMetrics(w io.Writer, m *Metrics) error {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(m)
}

3
bitmap-font-maker/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module gitea.brasse-pc.eu/brasse/agent-tools/bitmap-font-maker
go 1.24

258
bitmap-font-maker/main.go Normal file
View File

@@ -0,0 +1,258 @@
// fontc turns .font text files (pixel glyph grids) into font atlases
// (PNG + JSON metrics) and renders text strings to images.
package main
import (
"flag"
"fmt"
"image/color"
"os"
"path/filepath"
"strings"
"gitea.brasse-pc.eu/brasse/agent-tools/bitmap-font-maker/font"
)
var version = "dev"
const usage = `fontc - bitmap font maker for agents
Usage:
fontc build <file.font> [flags] build atlas PNG + metrics JSON
fontc render <file.font> <text> [flags]
render a text string to PNG
fontc info <file.font> validate + list glyphs
fontc preview <file.font> <text> draw text in the terminal
fontc version
Build flags:
-o <base> output base name -> <base>.png + <base>.json
(default: font file name without extension)
Render flags:
-o <path> output PNG (default text.png)
--scale <n> integer upscale, default 1
--color <c> text color (#RRGGBB, CSS names not supported here), default #FFFFFF
Use \n in <text> for line breaks.
The .font format:
font: tiny5 optional name
spacing: 1 px between glyphs (default 1)
space-width: 3 advance of ' ' (default: width of '0')
line-height: 7 default: glyph height + 1
baseline: 5 default: glyph height
glyph A:
.#.
#.#
###
#.#
#.#
'#' = pixel on, '.' = off. All glyphs share one height; widths may
differ (proportional). The atlas draws glyphs in white so engines can
tint them; metrics JSON carries x/y/w/h/advance per glyph.
`
func main() {
if len(os.Args) < 2 {
fmt.Print(usage)
os.Exit(2)
}
switch os.Args[1] {
case "build":
cmdBuild(os.Args[2:])
case "render":
cmdRender(os.Args[2:])
case "info":
cmdInfo(os.Args[2:])
case "preview":
cmdPreview(os.Args[2:])
case "version", "--version", "-v":
fmt.Println("fontc", version)
case "help", "--help", "-h":
fmt.Print(usage)
default:
die("unknown command %q — run 'fontc help'", os.Args[1])
}
}
// parseInterspersed lets flags appear before or after positional args.
func parseInterspersed(fs *flag.FlagSet, args []string) {
var flags, pos []string
for i := 0; i < len(args); i++ {
a := args[i]
if len(a) > 1 && a[0] == '-' {
flags = append(flags, a)
name := strings.TrimLeft(a, "-")
if !strings.Contains(name, "=") {
f := fs.Lookup(name)
isBool := false
if f != nil {
if bv, ok := f.Value.(interface{ IsBoolFlag() bool }); ok && bv.IsBoolFlag() {
isBool = true
}
}
if !isBool && i+1 < len(args) {
i++
flags = append(flags, args[i])
}
}
} else {
pos = append(pos, a)
}
}
fs.Parse(append(flags, pos...))
}
func cmdBuild(args []string) {
fs := flag.NewFlagSet("build", flag.ExitOnError)
out := fs.String("o", "", "output base name")
parseInterspersed(fs, args)
if fs.NArg() != 1 {
die("build takes exactly one .font file")
}
ft, err := font.ParseFile(fs.Arg(0))
if err != nil {
die("%v", err)
}
base := *out
if base == "" {
base = strings.TrimSuffix(fs.Arg(0), filepath.Ext(fs.Arg(0)))
}
base = strings.TrimSuffix(base, ".png")
img, metrics := ft.BuildAtlas(filepath.Base(base) + ".png")
pngF, err := os.Create(base + ".png")
if err != nil {
die("%v", err)
}
defer pngF.Close()
if err := font.WritePNG(pngF, img); err != nil {
die("%v", err)
}
jsonF, err := os.Create(base + ".json")
if err != nil {
die("%v", err)
}
defer jsonF.Close()
if err := font.WriteMetrics(jsonF, metrics); err != nil {
die("%v", err)
}
b := img.Bounds()
fmt.Printf("%s.png (%dx%d atlas, %d glyphs)\n%s.json\n", base, b.Dx(), b.Dy(), len(ft.Order), base)
}
func parseHexColor(s string) (r, g, b uint8, err error) {
s = strings.TrimPrefix(strings.TrimSpace(s), "#")
if len(s) != 6 {
return 0, 0, 0, fmt.Errorf("color must be #RRGGBB, got %q", s)
}
var v [3]uint8
for i := 0; i < 3; i++ {
var n int
if _, err := fmt.Sscanf(s[i*2:i*2+2], "%02x", &n); err != nil {
return 0, 0, 0, fmt.Errorf("bad hex color %q", s)
}
v[i] = uint8(n)
}
return v[0], v[1], v[2], nil
}
func cmdRender(args []string) {
fs := flag.NewFlagSet("render", flag.ExitOnError)
out := fs.String("o", "text.png", "output PNG")
scale := fs.Int("scale", 1, "integer upscale")
col := fs.String("color", "#FFFFFF", "text color #RRGGBB")
parseInterspersed(fs, args)
if fs.NArg() != 2 {
die("render takes a .font file and a text string")
}
ft, err := font.ParseFile(fs.Arg(0))
if err != nil {
die("%v", err)
}
r, g, b, err := parseHexColor(*col)
if err != nil {
die("%v", err)
}
img, warnings := ft.RenderText(fs.Arg(1), *scale, rgba(r, g, b))
for _, w := range warnings {
fmt.Fprintln(os.Stderr, "fontc:", w)
}
f, err := os.Create(*out)
if err != nil {
die("%v", err)
}
defer f.Close()
if err := font.WritePNG(f, img); err != nil {
die("%v", err)
}
bd := img.Bounds()
fmt.Printf("%s (%dx%d px)\n", *out, bd.Dx(), bd.Dy())
}
func cmdInfo(args []string) {
if len(args) != 1 {
die("info takes exactly one .font file")
}
ft, err := font.ParseFile(args[0])
if err != nil {
die("%v", err)
}
fmt.Printf("font: %s\n", ft.Name)
fmt.Printf("height: %d px\n", ft.Height)
fmt.Printf("line-height: %d px\n", ft.LineHeight)
fmt.Printf("baseline: %d\n", ft.Baseline)
fmt.Printf("spacing: %d px\n", ft.Spacing)
fmt.Printf("space-width: %d px\n", ft.SpaceWidth)
fmt.Printf("glyphs: %d\n", len(ft.Order))
var chars []string
for _, r := range ft.SortedChars() {
chars = append(chars, string(r))
}
fmt.Printf(" %s\n", strings.Join(chars, " "))
fmt.Println("valid: yes")
}
func cmdPreview(args []string) {
if len(args) != 2 {
die("preview takes a .font file and a text string")
}
ft, err := font.ParseFile(args[0])
if err != nil {
die("%v", err)
}
img, warnings := ft.RenderText(args[1], 1, rgba(255, 255, 255))
for _, w := range warnings {
fmt.Fprintln(os.Stderr, "fontc:", w)
}
b := img.Bounds()
for y := 0; y < b.Dy(); y += 2 {
var sb strings.Builder
for x := 0; x < b.Dx(); x++ {
top := img.NRGBAAt(x, y).A >= 128
bot := y+1 < b.Dy() && img.NRGBAAt(x, y+1).A >= 128
switch {
case top && bot:
sb.WriteRune('█')
case top:
sb.WriteRune('▀')
case bot:
sb.WriteRune('▄')
default:
sb.WriteByte(' ')
}
}
fmt.Println(sb.String())
}
}
func rgba(r, g, b uint8) color.NRGBA {
return color.NRGBA{R: r, G: g, B: b, A: 255}
}
func die(format string, a ...any) {
fmt.Fprintf(os.Stderr, "fontc: "+format+"\n", a...)
os.Exit(1)
}

43
doc/plan.md Normal file
View File

@@ -0,0 +1,43 @@
# agent-tools — plan
## Goal
A collection of small, agent-friendly CLI tools. The common thread:
**text in, verifiable artifacts out**. An agent should be able to author
the input format directly, predict what the output will look like, and
verify results without a GUI.
## Stack
- Go (single static binaries, zero deps, trivial cross-compile to the
Pi5's arm64 runner), one Go module per tool.
- Targets: linux x64 + linux arm64.
## Deploy target
Pattern A (distributable binaries): rolling `<tool>-latest` release per
tool on Gitea, built by `.gitea/workflows/release.yml` on push to
master/main. Only tools whose folders changed get rebuilt.
## Milestones
1.`pixel-sprite-maker` (`spritec`): .sprite text format → PNG/JPG/SVG,
sprite sheets with self-documenting file names, terminal preview.
2.`mesh-tool` (`mesht`): OBJ/STL create/inspect/edit with ASCII
multi-view rendering, measurements and watertightness checks.
3. ✅ Per-tool VS Code build tasks → `<tool>/build/`.
4. ✅ CI: changed-tool detection + per-tool rolling releases.
## Roadmap / expansion ideas (not agreed yet)
- spritec: palette import from image files, GIF export for animations,
tile-map composer (map file referencing sprite tiles).
- mesht: OBJ vertex-color support, simple boolean ops (union via
voxelization), PNG snapshot rendering, glTF export.
- New tools: bitmap-font maker, sound-effect generator (sfxr-style text
presets), tiled-map (.tmx) writer.
## Open questions
- Versioned releases (`vX.Y.Z` tags per tool) on top of the rolling
`latest` — add when something depends on a pinned version.

View File

@@ -0,0 +1,86 @@
# pixel-sprite-maker (`spritec`)
Turns human/agent-readable `.sprite` text files into pixel art (**PNG, JPG, SVG**)
and combines several sprites into **sprite sheets / animation strips**.
Written in Go, zero dependencies, single static binary.
## Build
```bash
# Arch/Garuda: sudo pacman -S go
cd pixel-sprite-maker
go build -o build/spritec . # or run the VS Code task "build pixel-sprite-maker"
go test ./...
```
## The `.sprite` format
One file = one sprite. Designed so an agent can *see* the result in the text:
```
# comment lines start with '#'
sprite: coin # optional name
palette:
k = #1A1205 dark outline
y = #FFD700 gold
Y = gold CSS names work too — text after the color is a comment
grid:
..kkkk..
.kyyyYk.
kyyyYYyk
..kkkk..
```
Rules:
- **One character = one pixel.** Every grid row must be the same width.
- Palette keys are exactly one character (any unicode). `#`, `=`, `:` and
whitespace are not allowed as keys — so the number of colors is
practically unlimited (a-z, A-Z, 0-9, `!@%&*`, unicode…).
- `.` is **transparent by default**; override it in the palette if you want.
- Colors: `#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA`, `rgb(r,g,b)`,
`rgba(r,g,b,a)` (alpha 0-255 or 0.0-1.0), all CSS named colors, `none`.
- Max **256x256** pixels per sprite. Sheets may exceed this; single frames may not.
## Commands
```bash
spritec render coin.sprite -o coin.png --scale 8 # png/jpg/svg from extension
spritec render coin.sprite --format svg # -> coin.svg
spritec render heart.sprite -o heart.jpg --bg '#222034' # jpg has no alpha: pick bg
spritec info coin.sprite # validate + palette stats
spritec preview coin.sprite # draw in the terminal (truecolor)
# Sprite sheets / animations — row-major (left→right, then top→bottom):
spritec sheet walk_1.sprite walk_2.sprite walk_3.sprite walk_4.sprite -o walk # 1 row
spritec sheet walk_*.sprite --cols 2 -o walkgrid # 2D: 2 columns x 2 rows
```
Flags: `-o` output, `--format png|jpg|svg`, `--scale n` (integer nearest-neighbour
upscale), `--bg color` + `--quality 1-100` (jpg only), `--cols n` (sheet only).
## Sheet output naming — read the layout from the file name
```
<name>_<cellW>x<cellH>_<cols>x<rows>.<ext>
walk_8x8_4x1.png = 8x8 px per frame, 4 columns, 1 row (animation strip)
tiles_16x16_4x2.png = 16x16 px per frame, 4 columns, 2 rows
```
Frame order is always **row-major**: index = `row * cols + col`, frame 0 is
top-left. If the frame count doesn't fill the grid, trailing cells are
transparent. In game code:
```
frameX = (index % cols) * cellW
frameY = (index / cols) * cellH
```
## Exit codes & errors
`0` on success, `1` on any error, `2` on missing command. Parse errors name
the exact line/row/column and what was expected, so an agent can fix the
file without guessing.
Examples live in [`examples/`](examples/); generated output in `examples/out/`.

View File

@@ -0,0 +1,17 @@
# A small gold coin, 8x8.
# '.' is transparent by default and never needs a palette entry.
sprite: coin
palette:
k = #1A1205 dark outline
y = #FFD700 gold
Y = #FFF3A0 highlight
s = #B8860B shadow
grid:
..kkkk..
.kyyyYk.
kyyyYYsk
kyyYyysk
kyYyyysk
kYyyyssk
.kysssk.
..kkkk..

View File

@@ -0,0 +1,25 @@
# A 16x16 heart with shading, shows named colors and rgb().
sprite: heart
palette:
k = #2B0A10 outline
r = crimson main red
R = rgb(255, 90, 110) light red
d = #8B1A2B dark red
w = #FFFFFFCC semi-transparent shine
grid:
................
..kkk....kkk....
.krrRk..kRrrk...
krrRRrkkrRrrrk..
krRwRrrrrrrrdk..
krRwwRrrrrrrdk..
krRwRrrrrrrddk..
krrRrrrrrrrddk..
.krrrrrrrrrdk...
..krrrrrrrdk....
...krrrrrdk.....
....krrrdk......
.....krdk.......
......kk........
................
................

Binary file not shown.

After

Width:  |  Height:  |  Size: 344 B

View File

@@ -0,0 +1,34 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 8 8" shape-rendering="crispEdges">
<rect x="2" y="0" width="4" height="1" fill="#1a1205"/>
<rect x="1" y="1" width="1" height="1" fill="#1a1205"/>
<rect x="2" y="1" width="3" height="1" fill="#ffd700"/>
<rect x="5" y="1" width="1" height="1" fill="#fff3a0"/>
<rect x="6" y="1" width="1" height="1" fill="#1a1205"/>
<rect x="0" y="2" width="1" height="1" fill="#1a1205"/>
<rect x="1" y="2" width="3" height="1" fill="#ffd700"/>
<rect x="4" y="2" width="2" height="1" fill="#fff3a0"/>
<rect x="6" y="2" width="1" height="1" fill="#b8860b"/>
<rect x="7" y="2" width="1" height="1" fill="#1a1205"/>
<rect x="0" y="3" width="1" height="1" fill="#1a1205"/>
<rect x="1" y="3" width="2" height="1" fill="#ffd700"/>
<rect x="3" y="3" width="1" height="1" fill="#fff3a0"/>
<rect x="4" y="3" width="2" height="1" fill="#ffd700"/>
<rect x="6" y="3" width="1" height="1" fill="#b8860b"/>
<rect x="7" y="3" width="1" height="1" fill="#1a1205"/>
<rect x="0" y="4" width="1" height="1" fill="#1a1205"/>
<rect x="1" y="4" width="1" height="1" fill="#ffd700"/>
<rect x="2" y="4" width="1" height="1" fill="#fff3a0"/>
<rect x="3" y="4" width="3" height="1" fill="#ffd700"/>
<rect x="6" y="4" width="1" height="1" fill="#b8860b"/>
<rect x="7" y="4" width="1" height="1" fill="#1a1205"/>
<rect x="0" y="5" width="1" height="1" fill="#1a1205"/>
<rect x="1" y="5" width="1" height="1" fill="#fff3a0"/>
<rect x="2" y="5" width="3" height="1" fill="#ffd700"/>
<rect x="5" y="5" width="2" height="1" fill="#b8860b"/>
<rect x="7" y="5" width="1" height="1" fill="#1a1205"/>
<rect x="1" y="6" width="1" height="1" fill="#1a1205"/>
<rect x="2" y="6" width="1" height="1" fill="#ffd700"/>
<rect x="3" y="6" width="3" height="1" fill="#b8860b"/>
<rect x="6" y="6" width="1" height="1" fill="#1a1205"/>
<rect x="2" y="7" width="4" height="1" fill="#1a1205"/>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 508 B

View File

@@ -0,0 +1,57 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" shape-rendering="crispEdges">
<rect x="2" y="0" width="3" height="1" fill="#101018"/>
<rect x="10" y="0" width="3" height="1" fill="#101018"/>
<rect x="2" y="1" width="1" height="1" fill="#101018"/>
<rect x="3" y="1" width="2" height="1" fill="#f2c09a"/>
<rect x="10" y="1" width="1" height="1" fill="#101018"/>
<rect x="11" y="1" width="2" height="1" fill="#f2c09a"/>
<rect x="2" y="2" width="1" height="1" fill="#101018"/>
<rect x="3" y="2" width="2" height="1" fill="#f2c09a"/>
<rect x="10" y="2" width="1" height="1" fill="#101018"/>
<rect x="11" y="2" width="2" height="1" fill="#f2c09a"/>
<rect x="1" y="3" width="1" height="1" fill="#101018"/>
<rect x="2" y="3" width="3" height="1" fill="#2e5fb7"/>
<rect x="5" y="3" width="1" height="1" fill="#101018"/>
<rect x="9" y="3" width="1" height="1" fill="#101018"/>
<rect x="10" y="3" width="3" height="1" fill="#2e5fb7"/>
<rect x="13" y="3" width="1" height="1" fill="#101018"/>
<rect x="2" y="4" width="3" height="1" fill="#2e5fb7"/>
<rect x="10" y="4" width="3" height="1" fill="#2e5fb7"/>
<rect x="2" y="5" width="3" height="1" fill="#22406e"/>
<rect x="10" y="5" width="3" height="1" fill="#22406e"/>
<rect x="2" y="6" width="1" height="1" fill="#22406e"/>
<rect x="4" y="6" width="1" height="1" fill="#22406e"/>
<rect x="9" y="6" width="1" height="1" fill="#22406e"/>
<rect x="13" y="6" width="1" height="1" fill="#22406e"/>
<rect x="2" y="7" width="1" height="1" fill="#101018"/>
<rect x="4" y="7" width="1" height="1" fill="#101018"/>
<rect x="9" y="7" width="1" height="1" fill="#101018"/>
<rect x="13" y="7" width="1" height="1" fill="#101018"/>
<rect x="2" y="8" width="3" height="1" fill="#101018"/>
<rect x="10" y="8" width="3" height="1" fill="#101018"/>
<rect x="2" y="9" width="1" height="1" fill="#101018"/>
<rect x="3" y="9" width="2" height="1" fill="#f2c09a"/>
<rect x="10" y="9" width="1" height="1" fill="#101018"/>
<rect x="11" y="9" width="2" height="1" fill="#f2c09a"/>
<rect x="2" y="10" width="1" height="1" fill="#101018"/>
<rect x="3" y="10" width="2" height="1" fill="#f2c09a"/>
<rect x="10" y="10" width="1" height="1" fill="#101018"/>
<rect x="11" y="10" width="2" height="1" fill="#f2c09a"/>
<rect x="2" y="11" width="3" height="1" fill="#2e5fb7"/>
<rect x="5" y="11" width="1" height="1" fill="#101018"/>
<rect x="9" y="11" width="1" height="1" fill="#101018"/>
<rect x="10" y="11" width="3" height="1" fill="#2e5fb7"/>
<rect x="13" y="11" width="1" height="1" fill="#101018"/>
<rect x="1" y="12" width="1" height="1" fill="#101018"/>
<rect x="2" y="12" width="3" height="1" fill="#2e5fb7"/>
<rect x="10" y="12" width="3" height="1" fill="#2e5fb7"/>
<rect x="2" y="13" width="3" height="1" fill="#22406e"/>
<rect x="10" y="13" width="3" height="1" fill="#22406e"/>
<rect x="2" y="14" width="1" height="1" fill="#22406e"/>
<rect x="4" y="14" width="1" height="1" fill="#22406e"/>
<rect x="10" y="14" width="2" height="1" fill="#22406e"/>
<rect x="2" y="15" width="1" height="1" fill="#101018"/>
<rect x="4" y="15" width="1" height="1" fill="#101018"/>
<rect x="9" y="15" width="1" height="1" fill="#101018"/>
<rect x="12" y="15" width="1" height="1" fill="#101018"/>
</svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

View File

@@ -0,0 +1,16 @@
# Frame 1/4 of a tiny walking guy, 8x8. Legs together.
sprite: walk_1
palette:
k = #101018 outline / hair
s = #F2C09A skin
b = #2E5FB7 shirt
d = #22406E pants
grid:
..kkk...
..kss...
..kss...
.kbbbk..
..bbb...
..ddd...
..d.d...
..k.k...

View File

@@ -0,0 +1,16 @@
# Frame 2/4 - right leg forward.
sprite: walk_2
palette:
k = #101018 outline / hair
s = #F2C09A skin
b = #2E5FB7 shirt
d = #22406E pants
grid:
..kkk...
..kss...
..kss...
.kbbbk..
..bbb...
..ddd...
.d...d..
.k...k..

View File

@@ -0,0 +1,16 @@
# Frame 3/4 - legs together again (same pose as 1, arms swung).
sprite: walk_3
palette:
k = #101018 outline / hair
s = #F2C09A skin
b = #2E5FB7 shirt
d = #22406E pants
grid:
..kkk...
..kss...
..kss...
..bbbk..
.kbbb...
..ddd...
..d.d...
..k.k...

View File

@@ -0,0 +1,16 @@
# Frame 4/4 - left leg forward.
sprite: walk_4
palette:
k = #101018 outline / hair
s = #F2C09A skin
b = #2E5FB7 shirt
d = #22406E pants
grid:
..kkk...
..kss...
..kss...
.kbbbk..
..bbb...
..ddd...
..dd....
.k..k...

View File

@@ -0,0 +1,3 @@
module gitea.brasse-pc.eu/brasse/agent-tools/pixel-sprite-maker
go 1.24

313
pixel-sprite-maker/main.go Normal file
View File

@@ -0,0 +1,313 @@
// spritec turns agent-friendly .sprite text files into PNG/JPG/SVG pixel
// art, and combines several sprites into sprite sheets / animation strips.
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"gitea.brasse-pc.eu/brasse/agent-tools/pixel-sprite-maker/sprite"
)
var version = "dev"
const usage = `spritec - pixel sprite maker for agents
Usage:
spritec render <file.sprite> [flags] render one sprite to png/jpg/svg
spritec sheet <a.sprite> <b.sprite> ... [flags]
combine sprites into one sheet image
spritec info <file.sprite> validate a file and print its stats
spritec preview <file.sprite> draw the sprite in the terminal
spritec version print version
Render flags:
-o <path> output file; its extension picks the format (.png .jpg .svg)
--format <f> png | jpg | svg (default: from -o, else png)
--scale <n> integer upscale factor, default 1
--bg <color> jpg background color (jpg has no alpha), default #FFFFFF
--quality <n> jpg quality 1-100, default 90
Sheet flags (in addition to the render flags):
-o <name> output base name; layout is appended automatically
--cols <n> number of columns, row-major order (default: one row)
Sheet output naming:
<name>_<cellW>x<cellH>_<cols>x<rows>.<ext>
e.g. walk_16x16_4x2.png = 16x16 px per frame, 4 columns, 2 rows,
frames are read left-to-right then top-to-bottom (row-major).
The .sprite format:
# comment
sprite: coin optional name
palette:
. = none '.' is transparent by default
k = #000000 hex, rgb(...), CSS names ('gold') and 'none' work
y = gold anything after the color is a comment
grid:
..kk..
.kyyk.
.kyyk.
..kk..
Each grid character is one pixel; every row must be the same width.
Max sprite size: 256x256. Sheets may be bigger, single frames may not.
`
func main() {
if len(os.Args) < 2 {
fmt.Print(usage)
os.Exit(2)
}
switch os.Args[1] {
case "render":
cmdRender(os.Args[2:])
case "sheet":
cmdSheet(os.Args[2:])
case "info":
cmdInfo(os.Args[2:])
case "preview":
cmdPreview(os.Args[2:])
case "version", "--version", "-v":
fmt.Println("spritec", version)
case "help", "--help", "-h":
fmt.Print(usage)
default:
die("unknown command %q — run 'spritec help'", os.Args[1])
}
}
// parseInterspersed lets flags appear before or after positional args
// (stdlib flag stops at the first positional otherwise).
func parseInterspersed(fs *flag.FlagSet, args []string) {
var flags, pos []string
for i := 0; i < len(args); i++ {
a := args[i]
if len(a) > 1 && a[0] == '-' {
flags = append(flags, a)
name := strings.TrimLeft(a, "-")
if !strings.Contains(name, "=") {
f := fs.Lookup(name)
isBool := false
if f != nil {
if bv, ok := f.Value.(interface{ IsBoolFlag() bool }); ok && bv.IsBoolFlag() {
isBool = true
}
}
if !isBool && i+1 < len(args) {
i++
flags = append(flags, args[i])
}
}
} else {
pos = append(pos, a)
}
}
fs.Parse(append(flags, pos...))
}
type renderFlags struct {
out string
format string
scale int
bg string
quality int
}
func addRenderFlags(fs *flag.FlagSet) *renderFlags {
rf := &renderFlags{}
fs.StringVar(&rf.out, "o", "", "output path")
fs.StringVar(&rf.format, "format", "", "png|jpg|svg")
fs.IntVar(&rf.scale, "scale", 1, "integer upscale factor")
fs.StringVar(&rf.bg, "bg", "#FFFFFF", "jpg background color")
fs.IntVar(&rf.quality, "quality", 90, "jpg quality 1-100")
return rf
}
// resolveFormat picks the output format from --format or the -o extension.
func (rf *renderFlags) resolveFormat() (string, error) {
ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(rf.out), "."))
if ext == "jpeg" {
ext = "jpg"
}
f := strings.ToLower(rf.format)
switch {
case f == "" && ext == "":
return "png", nil
case f == "":
f = ext
case ext != "" && ext != f:
return "", fmt.Errorf("--format %s conflicts with output extension .%s", f, ext)
}
switch f {
case "png", "jpg", "svg":
return f, nil
}
return "", fmt.Errorf("unsupported format %q (png, jpg or svg)", f)
}
func writeGrid(path, format string, g sprite.PixelGrid, rf *renderFlags) error {
bg, err := sprite.ParseColor(rf.bg)
if err != nil {
return fmt.Errorf("--bg: %w", err)
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
switch format {
case "png":
err = sprite.WritePNG(f, g, rf.scale)
case "jpg":
err = sprite.WriteJPG(f, g, rf.scale, bg, rf.quality)
case "svg":
err = sprite.WriteSVG(f, g, rf.scale)
}
if err != nil {
return err
}
return f.Close()
}
func cmdRender(args []string) {
fs := flag.NewFlagSet("render", flag.ExitOnError)
rf := addRenderFlags(fs)
parseInterspersed(fs, args)
if fs.NArg() != 1 {
die("render takes exactly one .sprite file")
}
in := fs.Arg(0)
s, err := sprite.ParseFile(in)
if err != nil {
die("%v", err)
}
format, err := rf.resolveFormat()
if err != nil {
die("%v", err)
}
out := rf.out
if out == "" {
out = strings.TrimSuffix(in, filepath.Ext(in)) + "." + format
}
if err := writeGrid(out, format, s, rf); err != nil {
die("%v", err)
}
w, h := s.Bounds()
fmt.Printf("%s (%dx%d px, scale %d -> %dx%d)\n", out, w, h, rf.scale, w*rf.scale, h*rf.scale)
}
func cmdSheet(args []string) {
fs := flag.NewFlagSet("sheet", flag.ExitOnError)
rf := addRenderFlags(fs)
cols := fs.Int("cols", 0, "columns in the sheet (default: all sprites in one row)")
parseInterspersed(fs, args)
if fs.NArg() < 1 {
die("sheet needs at least one .sprite file")
}
var sprites []*sprite.Sprite
for _, path := range fs.Args() {
s, err := sprite.ParseFile(path)
if err != nil {
die("%v", err)
}
sprites = append(sprites, s)
}
sh, err := sprite.NewSheet(sprites, *cols)
if err != nil {
die("%v", err)
}
format, err := rf.resolveFormat()
if err != nil {
die("%v", err)
}
base := rf.out
if base == "" {
base = "sheet"
}
base = strings.TrimSuffix(base, filepath.Ext(base))
out := sh.FileBase(base) + "." + format
if err := writeGrid(out, format, sh, rf); err != nil {
die("%v", err)
}
w, h := sh.Bounds()
fmt.Printf("%s (%d frames of %dx%d px in %dx%d grid, total %dx%d px)\n",
out, len(sprites), sh.CellW, sh.CellH, sh.Cols, sh.Rows, w*rf.scale, h*rf.scale)
}
func cmdInfo(args []string) {
if len(args) != 1 {
die("info takes exactly one .sprite file")
}
s, err := sprite.ParseFile(args[0])
if err != nil {
die("%v", err)
}
fmt.Printf("sprite: %s\n", s.Name)
fmt.Printf("size: %dx%d px\n", s.W, s.H)
fmt.Printf("palette: %d colors\n", len(s.Keys))
usage := s.UsageCount()
for _, k := range s.Keys {
note := ""
if usage[k] == 0 {
note = " (unused)"
}
fmt.Printf(" %s = %-9s %5d px%s\n", string(k), sprite.FormatColor(s.Palette[k]), usage[k], note)
}
if _, defined := usage['.']; defined && !contains(s.Keys, '.') {
fmt.Printf(" . = none %5d px (implicit transparent)\n", usage['.'])
}
fmt.Println("valid: yes")
}
func contains(keys []rune, k rune) bool {
for _, x := range keys {
if x == k {
return true
}
}
return false
}
// cmdPreview draws the sprite with truecolor half-blocks, two pixel rows
// per terminal line. Transparent pixels show the terminal background.
func cmdPreview(args []string) {
if len(args) != 1 {
die("preview takes exactly one .sprite file")
}
s, err := sprite.ParseFile(args[0])
if err != nil {
die("%v", err)
}
const reset = "\x1b[0m"
var b strings.Builder
for y := 0; y < s.H; y += 2 {
for x := 0; x < s.W; x++ {
top, bot := s.At(x, y), sprite.Transparent
if y+1 < s.H {
bot = s.At(x, y+1)
}
topOn, botOn := top.A >= 128, bot.A >= 128
switch {
case topOn && botOn:
fmt.Fprintf(&b, "\x1b[38;2;%d;%d;%dm\x1b[48;2;%d;%d;%dm▀%s", top.R, top.G, top.B, bot.R, bot.G, bot.B, reset)
case topOn:
fmt.Fprintf(&b, "\x1b[38;2;%d;%d;%dm▀%s", top.R, top.G, top.B, reset)
case botOn:
fmt.Fprintf(&b, "\x1b[38;2;%d;%d;%dm▄%s", bot.R, bot.G, bot.B, reset)
default:
b.WriteByte(' ')
}
}
b.WriteByte('\n')
}
fmt.Printf("%s %dx%d px\n%s", s.Name, s.W, s.H, b.String())
}
func die(format string, a ...any) {
fmt.Fprintf(os.Stderr, "spritec: "+format+"\n", a...)
os.Exit(1)
}

View File

@@ -0,0 +1,270 @@
package sprite
import (
"fmt"
"image/color"
"strconv"
"strings"
)
// Transparent is the color used for pixels that should not be drawn.
var Transparent = color.NRGBA{0, 0, 0, 0}
// ParseColor accepts:
//
// none | transparent | - -> fully transparent
// #RGB #RGBA #RRGGBB #RRGGBBAA -> hex
// rgb(r,g,b) rgba(r,g,b,a) -> 0-255 channels, alpha 0-255 or 0.0-1.0
// CSS named colors -> "red", "rebeccapurple", ...
func ParseColor(s string) (color.NRGBA, error) {
t := strings.ToLower(strings.TrimSpace(s))
if t == "" {
return Transparent, fmt.Errorf("empty color value")
}
switch t {
case "none", "transparent", "-":
return Transparent, nil
}
if strings.HasPrefix(t, "#") {
return parseHex(t)
}
if strings.HasPrefix(t, "rgb(") || strings.HasPrefix(t, "rgba(") {
return parseRGBFunc(t)
}
if c, ok := cssColors[t]; ok {
return c, nil
}
return Transparent, fmt.Errorf("unknown color %q (use #RRGGBB, rgb(r,g,b), a CSS color name, or 'none')", s)
}
func parseHex(t string) (color.NRGBA, error) {
h := t[1:]
var r, g, b, a uint64
var err error
dup := func(s string) (uint64, error) {
v, err := strconv.ParseUint(s, 16, 8)
return v*16 + v, err
}
a = 255
switch len(h) {
case 3, 4:
if r, err = dup(h[0:1]); err == nil {
if g, err = dup(h[1:2]); err == nil {
b, err = dup(h[2:3])
}
}
if err == nil && len(h) == 4 {
a, err = dup(h[3:4])
}
case 6, 8:
if r, err = strconv.ParseUint(h[0:2], 16, 8); err == nil {
if g, err = strconv.ParseUint(h[2:4], 16, 8); err == nil {
b, err = strconv.ParseUint(h[4:6], 16, 8)
}
}
if err == nil && len(h) == 8 {
a, err = strconv.ParseUint(h[6:8], 16, 8)
}
default:
return Transparent, fmt.Errorf("hex color %q must be #RGB, #RGBA, #RRGGBB or #RRGGBBAA", t)
}
if err != nil {
return Transparent, fmt.Errorf("invalid hex color %q", t)
}
return color.NRGBA{uint8(r), uint8(g), uint8(b), uint8(a)}, nil
}
func parseRGBFunc(t string) (color.NRGBA, error) {
open := strings.Index(t, "(")
close := strings.Index(t, ")")
if close < open {
return Transparent, fmt.Errorf("invalid color %q: missing ')'", t)
}
parts := strings.Split(t[open+1:close], ",")
if len(parts) != 3 && len(parts) != 4 {
return Transparent, fmt.Errorf("invalid color %q: want rgb(r,g,b) or rgba(r,g,b,a)", t)
}
var ch [4]uint8
ch[3] = 255
for i, p := range parts {
p = strings.TrimSpace(p)
if i == 3 && strings.Contains(p, ".") {
// CSS-style fractional alpha 0.0 - 1.0
f, err := strconv.ParseFloat(p, 64)
if err != nil || f < 0 || f > 1 {
return Transparent, fmt.Errorf("invalid alpha %q in %q (want 0.0-1.0 or 0-255)", p, t)
}
ch[3] = uint8(f*255 + 0.5)
continue
}
v, err := strconv.ParseUint(p, 10, 8)
if err != nil {
return Transparent, fmt.Errorf("invalid channel %q in %q (want 0-255)", p, t)
}
ch[i] = uint8(v)
}
return color.NRGBA{ch[0], ch[1], ch[2], ch[3]}, nil
}
// FormatColor renders a color the way it should appear in a .sprite file.
func FormatColor(c color.NRGBA) string {
if c.A == 0 {
return "none"
}
if c.A == 255 {
return fmt.Sprintf("#%02X%02X%02X", c.R, c.G, c.B)
}
return fmt.Sprintf("#%02X%02X%02X%02X", c.R, c.G, c.B, c.A)
}
// cssColors is the full CSS Color Module Level 4 named-color list.
var cssColors = map[string]color.NRGBA{
"aliceblue": {240, 248, 255, 255},
"antiquewhite": {250, 235, 215, 255},
"aqua": {0, 255, 255, 255},
"aquamarine": {127, 255, 212, 255},
"azure": {240, 255, 255, 255},
"beige": {245, 245, 220, 255},
"bisque": {255, 228, 196, 255},
"black": {0, 0, 0, 255},
"blanchedalmond": {255, 235, 205, 255},
"blue": {0, 0, 255, 255},
"blueviolet": {138, 43, 226, 255},
"brown": {165, 42, 42, 255},
"burlywood": {222, 184, 135, 255},
"cadetblue": {95, 158, 160, 255},
"chartreuse": {127, 255, 0, 255},
"chocolate": {210, 105, 30, 255},
"coral": {255, 127, 80, 255},
"cornflowerblue": {100, 149, 237, 255},
"cornsilk": {255, 248, 220, 255},
"crimson": {220, 20, 60, 255},
"cyan": {0, 255, 255, 255},
"darkblue": {0, 0, 139, 255},
"darkcyan": {0, 139, 139, 255},
"darkgoldenrod": {184, 134, 11, 255},
"darkgray": {169, 169, 169, 255},
"darkgreen": {0, 100, 0, 255},
"darkgrey": {169, 169, 169, 255},
"darkkhaki": {189, 183, 107, 255},
"darkmagenta": {139, 0, 139, 255},
"darkolivegreen": {85, 107, 47, 255},
"darkorange": {255, 140, 0, 255},
"darkorchid": {153, 50, 204, 255},
"darkred": {139, 0, 0, 255},
"darksalmon": {233, 150, 122, 255},
"darkseagreen": {143, 188, 143, 255},
"darkslateblue": {72, 61, 139, 255},
"darkslategray": {47, 79, 79, 255},
"darkslategrey": {47, 79, 79, 255},
"darkturquoise": {0, 206, 209, 255},
"darkviolet": {148, 0, 211, 255},
"deeppink": {255, 20, 147, 255},
"deepskyblue": {0, 191, 255, 255},
"dimgray": {105, 105, 105, 255},
"dimgrey": {105, 105, 105, 255},
"dodgerblue": {30, 144, 255, 255},
"firebrick": {178, 34, 34, 255},
"floralwhite": {255, 250, 240, 255},
"forestgreen": {34, 139, 34, 255},
"fuchsia": {255, 0, 255, 255},
"gainsboro": {220, 220, 220, 255},
"ghostwhite": {248, 248, 255, 255},
"gold": {255, 215, 0, 255},
"goldenrod": {218, 165, 32, 255},
"gray": {128, 128, 128, 255},
"green": {0, 128, 0, 255},
"greenyellow": {173, 255, 47, 255},
"grey": {128, 128, 128, 255},
"honeydew": {240, 255, 240, 255},
"hotpink": {255, 105, 180, 255},
"indianred": {205, 92, 92, 255},
"indigo": {75, 0, 130, 255},
"ivory": {255, 255, 240, 255},
"khaki": {240, 230, 140, 255},
"lavender": {230, 230, 250, 255},
"lavenderblush": {255, 240, 245, 255},
"lawngreen": {124, 252, 0, 255},
"lemonchiffon": {255, 250, 205, 255},
"lightblue": {173, 216, 230, 255},
"lightcoral": {240, 128, 128, 255},
"lightcyan": {224, 255, 255, 255},
"lightgoldenrodyellow": {250, 250, 210, 255},
"lightgray": {211, 211, 211, 255},
"lightgreen": {144, 238, 144, 255},
"lightgrey": {211, 211, 211, 255},
"lightpink": {255, 182, 193, 255},
"lightsalmon": {255, 160, 122, 255},
"lightseagreen": {32, 178, 170, 255},
"lightskyblue": {135, 206, 250, 255},
"lightslategray": {119, 136, 153, 255},
"lightslategrey": {119, 136, 153, 255},
"lightsteelblue": {176, 196, 222, 255},
"lightyellow": {255, 255, 224, 255},
"lime": {0, 255, 0, 255},
"limegreen": {50, 205, 50, 255},
"linen": {250, 240, 230, 255},
"magenta": {255, 0, 255, 255},
"maroon": {128, 0, 0, 255},
"mediumaquamarine": {102, 205, 170, 255},
"mediumblue": {0, 0, 205, 255},
"mediumorchid": {186, 85, 211, 255},
"mediumpurple": {147, 112, 219, 255},
"mediumseagreen": {60, 179, 113, 255},
"mediumslateblue": {123, 104, 238, 255},
"mediumspringgreen": {0, 250, 154, 255},
"mediumturquoise": {72, 209, 204, 255},
"mediumvioletred": {199, 21, 133, 255},
"midnightblue": {25, 25, 112, 255},
"mintcream": {245, 255, 250, 255},
"mistyrose": {255, 228, 225, 255},
"moccasin": {255, 228, 181, 255},
"navajowhite": {255, 222, 173, 255},
"navy": {0, 0, 128, 255},
"oldlace": {253, 245, 230, 255},
"olive": {128, 128, 0, 255},
"olivedrab": {107, 142, 35, 255},
"orange": {255, 165, 0, 255},
"orangered": {255, 69, 0, 255},
"orchid": {218, 112, 214, 255},
"palegoldenrod": {238, 232, 170, 255},
"palegreen": {152, 251, 152, 255},
"paleturquoise": {175, 238, 238, 255},
"palevioletred": {219, 112, 147, 255},
"papayawhip": {255, 239, 213, 255},
"peachpuff": {255, 218, 185, 255},
"peru": {205, 133, 63, 255},
"pink": {255, 192, 203, 255},
"plum": {221, 160, 221, 255},
"powderblue": {176, 224, 230, 255},
"purple": {128, 0, 128, 255},
"rebeccapurple": {102, 51, 153, 255},
"red": {255, 0, 0, 255},
"rosybrown": {188, 143, 143, 255},
"royalblue": {65, 105, 225, 255},
"saddlebrown": {139, 69, 19, 255},
"salmon": {250, 128, 114, 255},
"sandybrown": {244, 164, 96, 255},
"seagreen": {46, 139, 87, 255},
"seashell": {255, 245, 238, 255},
"sienna": {160, 82, 45, 255},
"silver": {192, 192, 192, 255},
"skyblue": {135, 206, 235, 255},
"slateblue": {106, 90, 205, 255},
"slategray": {112, 128, 144, 255},
"slategrey": {112, 128, 144, 255},
"snow": {255, 250, 250, 255},
"springgreen": {0, 255, 127, 255},
"steelblue": {70, 130, 180, 255},
"tan": {210, 180, 140, 255},
"teal": {0, 128, 128, 255},
"thistle": {216, 191, 216, 255},
"tomato": {255, 99, 71, 255},
"turquoise": {64, 224, 208, 255},
"violet": {238, 130, 238, 255},
"wheat": {245, 222, 179, 255},
"white": {255, 255, 255, 255},
"whitesmoke": {245, 245, 245, 255},
"yellow": {255, 255, 0, 255},
"yellowgreen": {154, 205, 50, 255},
}

View File

@@ -0,0 +1,186 @@
package sprite
import (
"bufio"
"fmt"
"image/color"
"io"
"os"
"path/filepath"
"strings"
)
// MaxSize is the maximum width/height of a single sprite in pixels.
const MaxSize = 256
// Sprite is a parsed .sprite file: a palette of single-rune keys and a
// rectangular grid of those keys.
type Sprite struct {
Name string
W, H int
Palette map[rune]color.NRGBA
Keys []rune // palette keys in file order
Rows [][]rune // H rows of exactly W palette keys
}
// At returns the color of pixel (x, y). Out-of-range pixels are transparent.
func (s *Sprite) At(x, y int) color.NRGBA {
if x < 0 || y < 0 || x >= s.W || y >= s.H {
return Transparent
}
return s.Palette[s.Rows[y][x]]
}
// Bounds returns the sprite size in pixels.
func (s *Sprite) Bounds() (w, h int) { return s.W, s.H }
// ParseFile reads a .sprite file from disk. The sprite name defaults to the
// file name without extension when the file has no "sprite:" line.
func ParseFile(path string) (*Sprite, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
s, err := Parse(f)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if s.Name == "" {
s.Name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
}
return s, nil
}
// Parse reads the .sprite text format:
//
// # comment lines start with '#'
// sprite: coin (optional name)
// palette:
// . = none (key '.' is transparent by default)
// k = #000000 text after the color is ignored
// y = gold
// grid:
// ..kk..
// .kyyk.
//
// Palette keys are exactly one character and may not be '#', '=', ':' or
// whitespace. Every grid row must be the same width; max size is 256x256.
func Parse(r io.Reader) (*Sprite, error) {
s := &Sprite{Palette: map[rune]color.NRGBA{}}
const (
secNone = iota
secPalette
secGrid
)
section := secNone
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
lineNo := 0
for sc.Scan() {
lineNo++
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue // comment or blank ('#' is not a legal palette key)
}
lower := strings.ToLower(line)
switch {
case lower == "palette:":
section = secPalette
continue
case lower == "grid:":
section = secGrid
continue
case strings.HasPrefix(lower, "sprite:"):
s.Name = strings.TrimSpace(line[len("sprite:"):])
continue
}
switch section {
case secPalette:
if err := s.parsePaletteLine(line, lineNo); err != nil {
return nil, err
}
case secGrid:
row := []rune(line)
s.Rows = append(s.Rows, row)
default:
return nil, fmt.Errorf("line %d: unexpected %q before a 'palette:' or 'grid:' section", lineNo, line)
}
}
if err := sc.Err(); err != nil {
return nil, err
}
return s, s.validate()
}
func (s *Sprite) parsePaletteLine(line string, lineNo int) error {
eq := strings.Index(line, "=")
if eq < 0 {
return fmt.Errorf("line %d: palette entry %q must look like '<key> = <color>'", lineNo, line)
}
keyPart := []rune(strings.TrimSpace(line[:eq]))
if len(keyPart) != 1 {
return fmt.Errorf("line %d: palette key %q must be exactly one character", lineNo, strings.TrimSpace(line[:eq]))
}
key := keyPart[0]
if key == '#' || key == '=' || key == ':' {
return fmt.Errorf("line %d: %q is not allowed as a palette key", lineNo, key)
}
if _, dup := s.Palette[key]; dup {
return fmt.Errorf("line %d: palette key %q defined twice", lineNo, key)
}
val := strings.TrimSpace(line[eq+1:])
// The color is the first token; anything after it is a free-text comment.
token := val
if strings.HasPrefix(strings.ToLower(val), "rgb") {
if close := strings.Index(val, ")"); close >= 0 {
token = val[:close+1]
}
} else if i := strings.IndexAny(val, " \t"); i >= 0 {
token = val[:i]
}
c, err := ParseColor(token)
if err != nil {
return fmt.Errorf("line %d: %w", lineNo, err)
}
s.Palette[key] = c
s.Keys = append(s.Keys, key)
return nil
}
func (s *Sprite) validate() error {
if len(s.Rows) == 0 {
return fmt.Errorf("no 'grid:' section with at least one row found")
}
// '.' is transparent unless the file overrides it.
if _, ok := s.Palette['.']; !ok {
s.Palette['.'] = Transparent
}
s.H = len(s.Rows)
s.W = len(s.Rows[0])
if s.W > MaxSize || s.H > MaxSize {
return fmt.Errorf("sprite is %dx%d pixels; the maximum is %dx%d", s.W, s.H, MaxSize, MaxSize)
}
for y, row := range s.Rows {
if len(row) != s.W {
return fmt.Errorf("grid row %d is %d pixels wide, expected %d (all rows must match row 1)", y+1, len(row), s.W)
}
for x, key := range row {
if _, ok := s.Palette[key]; !ok {
return fmt.Errorf("grid row %d, column %d: %q is not defined in the palette", y+1, x+1, string(key))
}
}
}
return nil
}
// UsageCount returns how many grid pixels use each palette key.
func (s *Sprite) UsageCount() map[rune]int {
n := map[rune]int{}
for _, row := range s.Rows {
for _, k := range row {
n[k]++
}
}
return n
}

View File

@@ -0,0 +1,75 @@
package sprite
import (
"fmt"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
)
// PixelGrid is anything that can be rendered pixel by pixel: a single
// Sprite or a composed Sheet.
type PixelGrid interface {
Bounds() (w, h int)
At(x, y int) color.NRGBA
}
// Image renders a PixelGrid to an NRGBA image, scaled up by the integer
// factor scale (nearest neighbour, keeps pixels crisp).
func Image(g PixelGrid, scale int) *image.NRGBA {
if scale < 1 {
scale = 1
}
w, h := g.Bounds()
img := image.NewNRGBA(image.Rect(0, 0, w*scale, h*scale))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
c := g.At(x, y)
for dy := 0; dy < scale; dy++ {
for dx := 0; dx < scale; dx++ {
img.SetNRGBA(x*scale+dx, y*scale+dy, c)
}
}
}
}
return img
}
// WritePNG encodes g as PNG with transparency preserved.
func WritePNG(w io.Writer, g PixelGrid, scale int) error {
return png.Encode(w, Image(g, scale))
}
// WriteJPG encodes g as JPEG. JPEG has no alpha channel, so transparent
// pixels are composited over bg first.
func WriteJPG(w io.Writer, g PixelGrid, scale int, bg color.NRGBA, quality int) error {
if quality < 1 || quality > 100 {
return fmt.Errorf("jpg quality %d out of range 1-100", quality)
}
src := Image(g, scale)
b := src.Bounds()
flat := image.NewRGBA(b)
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
flat.Set(x, y, blendOver(src.NRGBAAt(x, y), bg))
}
}
return jpeg.Encode(w, flat, &jpeg.Options{Quality: quality})
}
// blendOver composites src over an opaque background color.
func blendOver(src, bg color.NRGBA) color.NRGBA {
if src.A == 255 {
return src
}
a := uint32(src.A)
inv := 255 - a
return color.NRGBA{
R: uint8((uint32(src.R)*a + uint32(bg.R)*inv) / 255),
G: uint8((uint32(src.G)*a + uint32(bg.G)*inv) / 255),
B: uint8((uint32(src.B)*a + uint32(bg.B)*inv) / 255),
A: 255,
}
}

View File

@@ -0,0 +1,58 @@
package sprite
import (
"fmt"
"image/color"
)
// Sheet lays out several equally sized sprites in a row-major grid:
// index 0 is top-left, then left-to-right, then next row. A 1D strip is
// simply a sheet with one row (or one column).
type Sheet struct {
Sprites []*Sprite
Cols, Rows int
CellW, CellH int
}
// NewSheet composes sprites into a sheet with the given number of columns.
// cols <= 0 puts everything in a single row. Every sprite must have the
// same dimensions so the sheet can be indexed cell by cell.
func NewSheet(sprites []*Sprite, cols int) (*Sheet, error) {
if len(sprites) == 0 {
return nil, fmt.Errorf("a sheet needs at least one sprite")
}
w, h := sprites[0].Bounds()
for _, sp := range sprites[1:] {
sw, sh := sp.Bounds()
if sw != w || sh != h {
return nil, fmt.Errorf("sprite %q is %dx%d but %q is %dx%d — all sprites in a sheet must be the same size",
sp.Name, sw, sh, sprites[0].Name, w, h)
}
}
if cols <= 0 || cols > len(sprites) {
cols = len(sprites)
}
rows := (len(sprites) + cols - 1) / cols
return &Sheet{Sprites: sprites, Cols: cols, Rows: rows, CellW: w, CellH: h}, nil
}
// Bounds returns the total sheet size in pixels.
func (sh *Sheet) Bounds() (w, h int) { return sh.Cols * sh.CellW, sh.Rows * sh.CellH }
// At returns the pixel at (x, y). Cells past the last sprite (when the
// sprite count doesn't fill the grid) are transparent.
func (sh *Sheet) At(x, y int) color.NRGBA {
col, row := x/sh.CellW, y/sh.CellH
idx := row*sh.Cols + col
if idx >= len(sh.Sprites) {
return Transparent
}
return sh.Sprites[idx].At(x%sh.CellW, y%sh.CellH)
}
// FileBase appends the layout to an output name so the file itself
// documents cell size and orientation: <base>_<cellW>x<cellH>_<cols>x<rows>
// e.g. walk_16x16_4x2 = 16x16 cells, 4 columns, 2 rows, read row by row.
func (sh *Sheet) FileBase(base string) string {
return fmt.Sprintf("%s_%dx%d_%dx%d", base, sh.CellW, sh.CellH, sh.Cols, sh.Rows)
}

View File

@@ -0,0 +1,207 @@
package sprite
import (
"bytes"
"encoding/xml"
"image/color"
"strings"
"testing"
)
const coin = `
# a tiny coin
sprite: coin
palette:
k = #000000
y = gold
Y = #FFF3A0 highlight
grid:
.kk.
kyYk
kyyk
.kk.
`
func parseOK(t *testing.T, src string) *Sprite {
t.Helper()
s, err := Parse(strings.NewReader(src))
if err != nil {
t.Fatalf("parse failed: %v", err)
}
return s
}
func TestParseBasics(t *testing.T) {
s := parseOK(t, coin)
if s.Name != "coin" {
t.Errorf("name = %q, want coin", s.Name)
}
if s.W != 4 || s.H != 4 {
t.Errorf("size = %dx%d, want 4x4", s.W, s.H)
}
if got := s.At(0, 0); got.A != 0 {
t.Errorf("(0,0) should be transparent via the implicit '.', got %v", got)
}
if got := s.At(1, 1); got != (color.NRGBA{255, 215, 0, 255}) {
t.Errorf("(1,1) = %v, want gold", got)
}
if got := s.At(2, 1); got != (color.NRGBA{255, 243, 160, 255}) {
t.Errorf("(2,1) = %v, want #FFF3A0", got)
}
}
func TestParseErrors(t *testing.T) {
cases := map[string]string{
"ragged rows": "palette:\n a = red\ngrid:\naa\naaa\n",
"unknown key": "palette:\n a = red\ngrid:\nab\naa\n",
"bad color": "palette:\n a = notacolor\ngrid:\na\n",
"no grid": "palette:\n a = red\n",
"dup key": "palette:\n a = red\n a = blue\ngrid:\na\n",
"multirune key": "palette:\n ab = red\ngrid:\na\n",
"colon key": "palette:\n : = red\ngrid:\n.\n",
}
for name, src := range cases {
if _, err := Parse(strings.NewReader(src)); err == nil {
t.Errorf("%s: expected an error", name)
}
}
}
func TestMaxSize(t *testing.T) {
row := strings.Repeat("a", 257)
src := "palette:\n a = red\ngrid:\n" + row + "\n"
if _, err := Parse(strings.NewReader(src)); err == nil {
t.Error("257 px wide sprite should be rejected")
}
ok := "palette:\n a = red\ngrid:\n" + strings.Repeat(strings.Repeat("a", 256)+"\n", 256)
s := parseOK(t, ok)
if s.W != 256 || s.H != 256 {
t.Errorf("size = %dx%d, want 256x256", s.W, s.H)
}
}
func TestParseColorForms(t *testing.T) {
cases := map[string]color.NRGBA{
"none": {0, 0, 0, 0},
"-": {0, 0, 0, 0},
"#F00": {255, 0, 0, 255},
"#F00A": {255, 0, 0, 170},
"#00FF00": {0, 255, 0, 255},
"#00FF0080": {0, 255, 0, 128},
"rgb(1,2,3)": {1, 2, 3, 255},
"rgba(1,2,3,64)": {1, 2, 3, 64},
"rgba(1, 2, 3, .5)": {1, 2, 3, 128},
"RebeccaPurple": {102, 51, 153, 255},
}
for in, want := range cases {
got, err := ParseColor(in)
if err != nil {
t.Errorf("ParseColor(%q): %v", in, err)
continue
}
if got != want {
t.Errorf("ParseColor(%q) = %v, want %v", in, got, want)
}
}
for _, bad := range []string{"", "#12345", "rgb(300,0,0)", "purpleish"} {
if _, err := ParseColor(bad); err == nil {
t.Errorf("ParseColor(%q): expected error", bad)
}
}
}
func TestImageAndScale(t *testing.T) {
s := parseOK(t, coin)
img := Image(s, 3)
if b := img.Bounds(); b.Dx() != 12 || b.Dy() != 12 {
t.Fatalf("scaled bounds = %v, want 12x12", b)
}
// pixel (1,1) is gold -> block at (3..5, 3..5)
if got := img.NRGBAAt(4, 4); got != (color.NRGBA{255, 215, 0, 255}) {
t.Errorf("scaled gold pixel = %v", got)
}
if got := img.NRGBAAt(0, 0); got.A != 0 {
t.Errorf("corner should stay transparent, got %v", got)
}
}
func TestSVGOutput(t *testing.T) {
s := parseOK(t, coin)
var buf bytes.Buffer
if err := WriteSVG(&buf, s, 10); err != nil {
t.Fatal(err)
}
out := buf.String()
if !strings.Contains(out, `viewBox="0 0 4 4"`) || !strings.Contains(out, `width="40"`) {
t.Errorf("svg header wrong:\n%s", out)
}
// row 2 (y=1) has runs k, yY?, no: k y Y k -> y and Y differ, so no merge.
// row 3 (y=2) k yy k -> the two golds merge into one rect of width 2.
if !strings.Contains(out, `<rect x="1" y="2" width="2" height="1" fill="#ffd700"/>`) {
t.Errorf("expected RLE-merged gold rect:\n%s", out)
}
var doc struct{ XMLName xml.Name }
if err := xml.Unmarshal(buf.Bytes(), &doc); err != nil {
t.Errorf("svg is not valid XML: %v", err)
}
}
func TestSheetLayoutAndNaming(t *testing.T) {
a := parseOK(t, coin)
b := parseOK(t, coin)
c := parseOK(t, coin)
sh, err := NewSheet([]*Sprite{a, b, c}, 2)
if err != nil {
t.Fatal(err)
}
if sh.Cols != 2 || sh.Rows != 2 {
t.Errorf("layout = %dx%d, want 2x2", sh.Cols, sh.Rows)
}
if w, h := sh.Bounds(); w != 8 || h != 8 {
t.Errorf("bounds = %dx%d, want 8x8", w, h)
}
if got := sh.FileBase("walk"); got != "walk_4x4_2x2" {
t.Errorf("FileBase = %q, want walk_4x4_2x2", got)
}
// cell (1,1) in frame 2 (top-right) is gold
if got := sh.At(5, 1); got != (color.NRGBA{255, 215, 0, 255}) {
t.Errorf("sheet pixel in frame 2 = %v, want gold", got)
}
// 4th cell (bottom-right) has no sprite -> transparent
if got := sh.At(7, 7); got.A != 0 {
t.Errorf("empty cell should be transparent, got %v", got)
}
}
func TestSheetSizeMismatch(t *testing.T) {
a := parseOK(t, coin)
b := parseOK(t, "palette:\n a = red\ngrid:\naa\n")
if _, err := NewSheet([]*Sprite{a, b}, 0); err == nil {
t.Error("mismatched sprite sizes should be rejected")
}
}
func TestSheetDefaultSingleRow(t *testing.T) {
a := parseOK(t, coin)
sh, err := NewSheet([]*Sprite{a, a, a}, 0)
if err != nil {
t.Fatal(err)
}
if sh.Cols != 3 || sh.Rows != 1 {
t.Errorf("default layout = %dx%d, want 3x1", sh.Cols, sh.Rows)
}
}
func TestJPGComposite(t *testing.T) {
s := parseOK(t, coin)
var buf bytes.Buffer
if err := WriteJPG(&buf, s, 1, color.NRGBA{255, 255, 255, 255}, 90); err != nil {
t.Fatal(err)
}
if buf.Len() == 0 {
t.Error("empty jpg output")
}
if err := WriteJPG(&buf, s, 1, Transparent, 150); err == nil {
t.Error("quality 150 should be rejected")
}
}

View File

@@ -0,0 +1,46 @@
package sprite
import (
"fmt"
"io"
)
// WriteSVG encodes g as an SVG where each horizontal run of same-colored
// pixels becomes one <rect>. shape-rendering="crispEdges" keeps the pixel
// look at any zoom. scale only affects the document width/height; the
// viewBox stays in pixel units.
func WriteSVG(w io.Writer, g PixelGrid, scale int) error {
if scale < 1 {
scale = 1
}
gw, gh := g.Bounds()
_, err := fmt.Fprintf(w,
`<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 %d %d" shape-rendering="crispEdges">`+"\n",
gw*scale, gh*scale, gw, gh)
if err != nil {
return err
}
for y := 0; y < gh; y++ {
for x := 0; x < gw; {
c := g.At(x, y)
run := 1
for x+run < gw && g.At(x+run, y) == c {
run++
}
if c.A > 0 {
opacity := ""
if c.A < 255 {
opacity = fmt.Sprintf(` fill-opacity="%.3f"`, float64(c.A)/255)
}
_, err = fmt.Fprintf(w, `<rect x="%d" y="%d" width="%d" height="1" fill="#%02x%02x%02x"%s/>`+"\n",
x, y, run, c.R, c.G, c.B, opacity)
if err != nil {
return err
}
}
x += run
}
}
_, err = io.WriteString(w, "</svg>\n")
return err
}

68
sfx-maker/README.md Normal file
View File

@@ -0,0 +1,68 @@
# sfx-maker (`sfxc`)
Synthesizes **retro game sound effects** (sfxr-style) from `.sfx` text
files and writes 16-bit mono **WAV**. Sound design becomes text an agent
can read, tweak and reason about — no DAW needed. Go, zero
dependencies, single static binary.
## Build
```bash
# Arch/Garuda: sudo pacman -S go
cd sfx-maker
go build -o build/sfxc . # or the VS Code task "build sfx-maker"
go test ./...
```
## Quick start
```bash
sfxc preset jump -o jump.sfx # editable text preset
sfxc build jump.sfx # -> jump.wav
mpv jump.wav # listen (or aplay/ffplay)
sfxc preset coin -o coin.wav # straight to WAV
sfxc preset coin --seed 3 -o coin3.wav # deterministic variant
sfxc info laser.sfx # validate + summary
```
Presets: `blip, coin, explosion, hurt, jump, laser, powerup`.
`--seed 0` is the canonical sound; any other seed nudges pitch/length
deterministically — ask for three seeds, keep the one that sounds best.
## The `.sfx` format
```
# comment
sfx: jump name
wave: square square | saw | sine | triangle | noise
volume: 0.7 0..1
attack: 0.01 seconds: fade in
sustain: 0.08 hold at full volume
decay: 0.18 fade out (total length = a+s+d, max 10 s)
freq: 330 start pitch, Hz
freq-slide: 900 Hz/second (positive = rising, negative = falling)
duty: 0.5 square pulse width 0.05..0.95 (thinner = buzzier)
vibrato-depth: 25 pitch wobble, Hz
vibrato-rate: 9 wobbles per second
arpeggio: 1.335 multiply pitch by this...
arpeggio-time: 0.06 ...after this many seconds (classic coin blip)
lowpass: 2200 cutoff Hz (muffle: explosions, thuds)
highpass: 300 cutoff Hz (thin out: lasers, clicks)
sample-rate: 44100 8000-96000
seed: 1 noise randomness — same seed = same sound
```
Unknown keys are **errors**, so typos surface immediately. Everything is
deterministic: same file → byte-identical WAV.
## Recipe intuition for agents
- **Jump**: square wave + rising `freq-slide`.
- **Coin/pickup**: square + `arpeggio` > 1 shortly after the start.
- **Laser**: saw + steep negative `freq-slide` + `highpass`.
- **Explosion**: noise + `lowpass` ~2 kHz + long `decay`.
- **Hurt**: saw, low pitch, quick fall.
- **Power-up**: rising slide + `vibrato`.
[`examples/`](examples/) contains all presets as `.sfx` + rendered `.wav`.

View File

@@ -0,0 +1,9 @@
# blip preset (seed 0) — edit freely, then: sfxc build examples/blip.sfx
sfx: blip
wave: square
volume: 0.7
attack: 0.002
sustain: 0.03
decay: 0.05
freq: 660
duty: 0.4

BIN
sfx-maker/examples/blip.wav Normal file

Binary file not shown.

View File

@@ -0,0 +1,10 @@
# coin preset (seed 0) — edit freely, then: sfxc build examples/coin.sfx
sfx: coin
wave: square
volume: 0.7
attack: 0.005
sustain: 0.08
decay: 0.25
freq: 988
arpeggio: 1.335
arpeggio-time: 0.06

BIN
sfx-maker/examples/coin.wav Normal file

Binary file not shown.

View File

@@ -0,0 +1,9 @@
# explosion preset (seed 0) — edit freely, then: sfxc build examples/explosion.sfx
sfx: explosion
wave: noise
volume: 0.7
attack: 0.01
sustain: 0.15
decay: 0.55
freq-slide: -600
lowpass: 2200

Binary file not shown.

View File

@@ -0,0 +1,9 @@
# hurt preset (seed 0) — edit freely, then: sfxc build examples/hurt.sfx
sfx: hurt
wave: saw
volume: 0.7
attack: 0.005
sustain: 0.04
decay: 0.14
freq: 300
freq-slide: -700

BIN
sfx-maker/examples/hurt.wav Normal file

Binary file not shown.

View File

@@ -0,0 +1,9 @@
# jump preset (seed 0) — edit freely, then: sfxc build examples/jump.sfx
sfx: jump
wave: square
volume: 0.7
attack: 0.01
sustain: 0.08
decay: 0.18
freq: 330
freq-slide: 900

BIN
sfx-maker/examples/jump.wav Normal file

Binary file not shown.

View File

@@ -0,0 +1,10 @@
# laser preset (seed 0) — edit freely, then: sfxc build examples/laser.sfx
sfx: laser
wave: saw
volume: 0.7
attack: 0.005
sustain: 0.05
decay: 0.12
freq: 1400
freq-slide: -6000
highpass: 300

Binary file not shown.

View File

@@ -0,0 +1,12 @@
# powerup preset (seed 0) — edit freely, then: sfxc build examples/powerup.sfx
sfx: powerup
wave: square
volume: 0.7
attack: 0.01
sustain: 0.25
decay: 0.25
freq: 220
freq-slide: 700
duty: 0.4
vibrato-depth: 25
vibrato-rate: 9

Binary file not shown.

3
sfx-maker/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module gitea.brasse-pc.eu/brasse/agent-tools/sfx-maker
go 1.24

212
sfx-maker/main.go Normal file
View File

@@ -0,0 +1,212 @@
// sfxc synthesizes retro game sound effects from .sfx text files
// (sfxr-style parameters) and writes 16-bit mono WAV.
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"gitea.brasse-pc.eu/brasse/agent-tools/sfx-maker/sfx"
)
var version = "dev"
const usage = `sfxc - sound effect maker for agents
Usage:
sfxc build <file.sfx> [-o out.wav] synthesize a .sfx file to WAV
sfxc preset <name> [-o out.sfx|out.wav] [--seed n]
write a preset (editable .sfx text,
or straight to .wav)
sfxc info <file.sfx> validate + print parameters
sfxc version
Presets: blip, coin, explosion, hurt, jump, laser, powerup
--seed 0 (default) is the canonical sound; other seeds give variants.
The .sfx format (all keys optional, '#' comments):
sfx: jump name
wave: square square | saw | sine | triangle | noise
volume: 0.7 0..1
attack: 0.01 seconds: fade in
sustain: 0.08 hold
decay: 0.18 fade out
freq: 330 start pitch, Hz
freq-slide: 900 Hz per second (negative = falling)
duty: 0.5 square pulse width 0.05..0.95
vibrato-depth: 25 Hz
vibrato-rate: 9 Hz
arpeggio: 1.335 pitch multiplier that kicks in at...
arpeggio-time: 0.06 ...this many seconds
lowpass: 2200 filter cutoff Hz
highpass: 300 filter cutoff Hz
sample-rate: 44100
seed: 1 noise randomness (deterministic)
Play the result with e.g.: mpv out.wav or aplay out.wav
`
func main() {
if len(os.Args) < 2 {
fmt.Print(usage)
os.Exit(2)
}
switch os.Args[1] {
case "build":
cmdBuild(os.Args[2:])
case "preset":
cmdPreset(os.Args[2:])
case "info":
cmdInfo(os.Args[2:])
case "version", "--version", "-v":
fmt.Println("sfxc", version)
case "help", "--help", "-h":
fmt.Print(usage)
default:
die("unknown command %q — run 'sfxc help'", os.Args[1])
}
}
// parseInterspersed lets flags appear before or after positional args.
func parseInterspersed(fs *flag.FlagSet, args []string) {
var flags, pos []string
for i := 0; i < len(args); i++ {
a := args[i]
if len(a) > 1 && a[0] == '-' {
flags = append(flags, a)
name := strings.TrimLeft(a, "-")
if !strings.Contains(name, "=") {
f := fs.Lookup(name)
isBool := false
if f != nil {
if bv, ok := f.Value.(interface{ IsBoolFlag() bool }); ok && bv.IsBoolFlag() {
isBool = true
}
}
if !isBool && i+1 < len(args) {
i++
flags = append(flags, args[i])
}
}
} else {
pos = append(pos, a)
}
}
fs.Parse(append(flags, pos...))
}
func writeWAVFile(path string, p *sfx.Params) error {
samples := sfx.Render(p)
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
if err := sfx.WriteWAV(f, samples, p.SampleRate); err != nil {
return err
}
return f.Close()
}
func cmdBuild(args []string) {
fs := flag.NewFlagSet("build", flag.ExitOnError)
out := fs.String("o", "", "output .wav (default: input name with .wav)")
parseInterspersed(fs, args)
if fs.NArg() != 1 {
die("build takes exactly one .sfx file")
}
p, err := sfx.ParseFile(fs.Arg(0))
if err != nil {
die("%v", err)
}
path := *out
if path == "" {
path = strings.TrimSuffix(fs.Arg(0), filepath.Ext(fs.Arg(0))) + ".wav"
}
if err := writeWAVFile(path, p); err != nil {
die("%v", err)
}
fmt.Printf("%s (%s, %.2fs, %d Hz)\n", path, p.Wave, p.Duration(), p.SampleRate)
}
func cmdPreset(args []string) {
fs := flag.NewFlagSet("preset", flag.ExitOnError)
out := fs.String("o", "", "output file: .sfx (editable text) or .wav (rendered)")
seed := fs.Int64("seed", 0, "0 = canonical, other values = variants")
parseInterspersed(fs, args)
if fs.NArg() != 1 {
die("preset takes exactly one preset name (%s)", sfx.PresetNames())
}
name := fs.Arg(0)
p, err := sfx.Preset(name, *seed)
if err != nil {
die("%v", err)
}
path := *out
if path == "" {
path = name + ".sfx"
}
switch strings.ToLower(filepath.Ext(path)) {
case ".wav":
if err := writeWAVFile(path, p); err != nil {
die("%v", err)
}
fmt.Printf("%s (%s preset, seed %d, %.2fs)\n", path, name, *seed, p.Duration())
case ".sfx":
f, err := os.Create(path)
if err != nil {
die("%v", err)
}
defer f.Close()
comment := fmt.Sprintf("%s preset (seed %d) — edit freely, then: sfxc build %s", name, *seed, path)
if err := p.Write(f, comment); err != nil {
die("%v", err)
}
fmt.Printf("%s (%s preset, seed %d — edit then 'sfxc build')\n", path, name, *seed)
default:
die("-o must end in .sfx or .wav")
}
}
func cmdInfo(args []string) {
if len(args) != 1 {
die("info takes exactly one .sfx file")
}
p, err := sfx.ParseFile(args[0])
if err != nil {
die("%v", err)
}
fmt.Printf("sfx: %s\n", p.Name)
fmt.Printf("wave: %s\n", p.Wave)
fmt.Printf("duration: %.3fs (attack %.3g + sustain %.3g + decay %.3g)\n",
p.Duration(), p.Attack, p.Sustain, p.Decay)
if p.Wave != "noise" {
fmt.Printf("freq: %g Hz", p.Freq)
if p.FreqSlide != 0 {
fmt.Printf(" (slide %+g Hz/s)", p.FreqSlide)
}
fmt.Println()
}
if p.ArpFactor != 0 {
fmt.Printf("arpeggio: x%g at %gs\n", p.ArpFactor, p.ArpTime)
}
if p.VibratoDepth > 0 {
fmt.Printf("vibrato: ±%g Hz at %g Hz\n", p.VibratoDepth, p.VibratoRate)
}
if p.LowPass > 0 {
fmt.Printf("lowpass: %g Hz\n", p.LowPass)
}
if p.HighPass > 0 {
fmt.Printf("highpass: %g Hz\n", p.HighPass)
}
fmt.Printf("volume: %g\nsamplerate:%d\n", p.Volume, p.SampleRate)
fmt.Println("valid: yes")
}
func die(format string, a ...any) {
fmt.Fprintf(os.Stderr, "sfxc: "+format+"\n", a...)
os.Exit(1)
}

223
sfx-maker/sfx/params.go Normal file
View File

@@ -0,0 +1,223 @@
// Package sfx synthesizes retro game sound effects (sfxr-style) from
// text parameter files and renders them to 16-bit mono WAV.
package sfx
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
)
// Params describes one sound effect. Zero values mean "off" for the
// optional effects; Defaults() fills the required fields.
type Params struct {
Name string
Wave string // square | saw | sine | triangle | noise
Volume float64 // 0..1 master gain
// envelope, seconds
Attack float64 // 0 -> Volume
Sustain float64 // hold at Volume
Decay float64 // Volume -> 0
Freq float64 // start frequency, Hz
FreqSlide float64 // Hz per second, may be negative
FreqMin float64 // clamp; sound stops below this (default 20 Hz)
Duty float64 // square wave duty cycle 0.05..0.95 (default 0.5)
VibratoDepth float64 // Hz
VibratoRate float64 // Hz
ArpFactor float64 // frequency multiplier applied at ArpTime (0 = off)
ArpTime float64 // seconds
LowPass float64 // cutoff Hz (0 = off)
HighPass float64 // cutoff Hz (0 = off)
SampleRate int // default 44100
Seed int64 // noise seed (default 1)
}
// Defaults returns a Params with sensible base values.
func Defaults() Params {
return Params{
Wave: "square",
Volume: 0.7,
Attack: 0.01,
Sustain: 0.1,
Decay: 0.15,
Freq: 440,
FreqMin: 20,
Duty: 0.5,
SampleRate: 44100,
Seed: 1,
}
}
// Duration is the total length of the sound in seconds.
func (p *Params) Duration() float64 { return p.Attack + p.Sustain + p.Decay }
// Validate checks ranges and returns a helpful error.
func (p *Params) Validate() error {
switch p.Wave {
case "square", "saw", "sine", "triangle", "noise":
default:
return fmt.Errorf("wave %q must be square, saw, sine, triangle or noise", p.Wave)
}
if p.Volume < 0 || p.Volume > 1 {
return fmt.Errorf("volume %g out of range 0-1", p.Volume)
}
if p.Attack < 0 || p.Sustain < 0 || p.Decay < 0 {
return fmt.Errorf("attack/sustain/decay must be >= 0")
}
if p.Duration() <= 0 {
return fmt.Errorf("total duration is 0 — set attack, sustain and/or decay")
}
if p.Duration() > 10 {
return fmt.Errorf("total duration %.2fs is too long (max 10s)", p.Duration())
}
if p.Wave != "noise" && (p.Freq <= 0 || p.Freq > 20000) {
return fmt.Errorf("freq %g out of range 1-20000 Hz", p.Freq)
}
if p.Duty < 0.05 || p.Duty > 0.95 {
return fmt.Errorf("duty %g out of range 0.05-0.95", p.Duty)
}
if p.SampleRate < 8000 || p.SampleRate > 96000 {
return fmt.Errorf("sample-rate %d out of range 8000-96000", p.SampleRate)
}
return nil
}
// ParseFile reads a .sfx file; the name defaults to the file name.
func ParseFile(path string) (*Params, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
p, err := Parse(f)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if p.Name == "" {
p.Name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
}
return p, nil
}
// Parse reads the .sfx text format: one "key: value" per line,
// '#' comments. Unknown keys are errors so typos surface immediately.
func Parse(r io.Reader) (*Params, error) {
p := Defaults()
sc := bufio.NewScanner(r)
lineNo := 0
for sc.Scan() {
lineNo++
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
i := strings.Index(line, ":")
if i < 0 {
return nil, fmt.Errorf("line %d: want 'key: value', got %q", lineNo, line)
}
key := strings.ToLower(strings.TrimSpace(line[:i]))
val := strings.TrimSpace(line[i+1:])
if j := strings.Index(val, " #"); j >= 0 { // trailing comment
val = strings.TrimSpace(val[:j])
}
var err error
switch key {
case "sfx", "name":
p.Name = val
case "wave":
p.Wave = strings.ToLower(val)
case "volume":
p.Volume, err = strconv.ParseFloat(val, 64)
case "attack":
p.Attack, err = strconv.ParseFloat(val, 64)
case "sustain":
p.Sustain, err = strconv.ParseFloat(val, 64)
case "decay":
p.Decay, err = strconv.ParseFloat(val, 64)
case "freq":
p.Freq, err = strconv.ParseFloat(val, 64)
case "freq-slide":
p.FreqSlide, err = strconv.ParseFloat(val, 64)
case "freq-min":
p.FreqMin, err = strconv.ParseFloat(val, 64)
case "duty":
p.Duty, err = strconv.ParseFloat(val, 64)
case "vibrato-depth":
p.VibratoDepth, err = strconv.ParseFloat(val, 64)
case "vibrato-rate":
p.VibratoRate, err = strconv.ParseFloat(val, 64)
case "arpeggio":
p.ArpFactor, err = strconv.ParseFloat(val, 64)
case "arpeggio-time":
p.ArpTime, err = strconv.ParseFloat(val, 64)
case "lowpass":
p.LowPass, err = strconv.ParseFloat(val, 64)
case "highpass":
p.HighPass, err = strconv.ParseFloat(val, 64)
case "sample-rate":
p.SampleRate, err = strconv.Atoi(val)
case "seed":
p.Seed, err = strconv.ParseInt(val, 10, 64)
default:
return nil, fmt.Errorf("line %d: unknown key %q", lineNo, key)
}
if err != nil {
return nil, fmt.Errorf("line %d: %s: bad value %q", lineNo, key, val)
}
}
if err := sc.Err(); err != nil {
return nil, err
}
if err := p.Validate(); err != nil {
return nil, err
}
return &p, nil
}
// Write renders the params back to the .sfx text format (used by the
// preset generator so agents get an editable file).
func (p *Params) Write(w io.Writer, comment string) error {
bw := bufio.NewWriter(w)
if comment != "" {
fmt.Fprintf(bw, "# %s\n", comment)
}
fmt.Fprintf(bw, "sfx: %s\nwave: %s\nvolume: %g\n", p.Name, p.Wave, p.Volume)
fmt.Fprintf(bw, "attack: %g\nsustain: %g\ndecay: %g\n", p.Attack, p.Sustain, p.Decay)
if p.Wave != "noise" {
fmt.Fprintf(bw, "freq: %g\n", p.Freq)
}
if p.FreqSlide != 0 {
fmt.Fprintf(bw, "freq-slide: %g\n", p.FreqSlide)
}
if p.Wave == "square" && p.Duty != 0.5 {
fmt.Fprintf(bw, "duty: %g\n", p.Duty)
}
if p.VibratoDepth > 0 && p.VibratoRate > 0 {
fmt.Fprintf(bw, "vibrato-depth: %g\nvibrato-rate: %g\n", p.VibratoDepth, p.VibratoRate)
}
if p.ArpFactor != 0 {
fmt.Fprintf(bw, "arpeggio: %g\narpeggio-time: %g\n", p.ArpFactor, p.ArpTime)
}
if p.LowPass > 0 {
fmt.Fprintf(bw, "lowpass: %g\n", p.LowPass)
}
if p.HighPass > 0 {
fmt.Fprintf(bw, "highpass: %g\n", p.HighPass)
}
if p.Seed != 1 {
fmt.Fprintf(bw, "seed: %d\n", p.Seed)
}
return bw.Flush()
}

114
sfx-maker/sfx/presets.go Normal file
View File

@@ -0,0 +1,114 @@
package sfx
import (
"fmt"
"math/rand"
"sort"
)
// Preset returns ready-made parameters for classic game sounds.
// seed 0 gives the canonical version; other seeds vary it slightly so
// agents can generate alternatives ("give me three coin variants").
func Preset(name string, seed int64) (*Params, error) {
p := Defaults()
p.Name = name
switch name {
case "jump":
p.Wave = "square"
p.Duty = 0.5
p.Freq = 330
p.FreqSlide = 900
p.Attack = 0.01
p.Sustain = 0.08
p.Decay = 0.18
case "coin":
p.Wave = "square"
p.Duty = 0.5
p.Freq = 988
p.ArpFactor = 1.335 // up a fourth: B5 -> E6
p.ArpTime = 0.06
p.Attack = 0.005
p.Sustain = 0.08
p.Decay = 0.25
case "laser":
p.Wave = "saw"
p.Freq = 1400
p.FreqSlide = -6000
p.Attack = 0.005
p.Sustain = 0.05
p.Decay = 0.12
p.HighPass = 300
case "explosion":
p.Wave = "noise"
p.Freq = 900
p.FreqSlide = -600
p.Attack = 0.01
p.Sustain = 0.15
p.Decay = 0.55
p.LowPass = 2200
case "hurt":
p.Wave = "saw"
p.Freq = 300
p.FreqSlide = -700
p.Attack = 0.005
p.Sustain = 0.04
p.Decay = 0.14
case "powerup":
p.Wave = "square"
p.Duty = 0.4
p.Freq = 220
p.FreqSlide = 700
p.VibratoDepth = 25
p.VibratoRate = 9
p.Attack = 0.01
p.Sustain = 0.25
p.Decay = 0.25
case "blip":
p.Wave = "square"
p.Duty = 0.4
p.Freq = 660
p.Attack = 0.002
p.Sustain = 0.03
p.Decay = 0.05
default:
return nil, fmt.Errorf("unknown preset %q (available: %s)", name, PresetNames())
}
if seed != 0 {
vary(&p, seed)
}
if err := p.Validate(); err != nil {
return nil, fmt.Errorf("preset %s (seed %d): %w", name, seed, err)
}
return &p, nil
}
// vary nudges the tonal parameters deterministically from the seed.
func vary(p *Params, seed int64) {
rng := rand.New(rand.NewSource(seed))
jitter := func(v, amount float64) float64 {
return v * (1 + amount*(rng.Float64()*2-1))
}
p.Freq = jitter(p.Freq, 0.15)
p.FreqSlide = jitter(p.FreqSlide, 0.25)
p.Sustain = jitter(p.Sustain, 0.2)
p.Decay = jitter(p.Decay, 0.2)
if p.ArpFactor != 0 {
p.ArpFactor = jitter(p.ArpFactor, 0.05)
}
p.Seed = seed // noise variation too
}
var presetNames = []string{"blip", "coin", "explosion", "hurt", "jump", "laser", "powerup"}
// PresetNames lists the available presets, sorted.
func PresetNames() string {
sort.Strings(presetNames)
out := ""
for i, n := range presetNames {
if i > 0 {
out += ", "
}
out += n
}
return out
}

164
sfx-maker/sfx/sfx_test.go Normal file
View File

@@ -0,0 +1,164 @@
package sfx
import (
"bytes"
"math"
"strings"
"testing"
)
func TestParseAndValidate(t *testing.T) {
src := `
# a jump
sfx: jump
wave: square
freq: 330
freq-slide: 900
attack: 0.01
sustain: 0.08
decay: 0.18
duty: 0.4
`
p, err := Parse(strings.NewReader(src))
if err != nil {
t.Fatal(err)
}
if p.Name != "jump" || p.Wave != "square" || p.Freq != 330 || p.Duty != 0.4 {
t.Errorf("parsed wrong: %+v", p)
}
if math.Abs(p.Duration()-0.27) > 1e-9 {
t.Errorf("duration = %g, want 0.27", p.Duration())
}
}
func TestParseErrors(t *testing.T) {
cases := map[string]string{
"unknown key": "wat: 3\n",
"bad wave": "wave: wobble\n",
"bad value": "freq: abc\n",
"zero length": "attack: 0\nsustain: 0\ndecay: 0\n",
"volume range": "volume: 2\n",
"duty range": "duty: 0.99\n",
}
for name, src := range cases {
if _, err := Parse(strings.NewReader(src)); err == nil {
t.Errorf("%s: expected error", name)
}
}
}
func TestRenderBasics(t *testing.T) {
p := Defaults()
p.Wave = "sine"
p.Attack, p.Sustain, p.Decay = 0.01, 0.05, 0.05
samples := Render(&p)
want := int(0.11 * 44100)
if len(samples) != want {
t.Errorf("samples = %d, want %d", len(samples), want)
}
var peak float64
for _, s := range samples {
if math.Abs(s) > peak {
peak = math.Abs(s)
}
if s > 1 || s < -1 {
t.Fatalf("sample %g out of range", s)
}
}
if peak < 0.5 {
t.Errorf("peak %g suspiciously quiet", peak)
}
// end of decay should be silent-ish
tail := samples[len(samples)-10:]
for _, s := range tail {
if math.Abs(s) > 0.1 {
t.Errorf("tail sample %g not decayed", s)
}
}
}
func TestRenderDeterministic(t *testing.T) {
p := Defaults()
p.Wave = "noise"
p.Seed = 42
a := Render(&p)
b := Render(&p)
for i := range a {
if a[i] != b[i] {
t.Fatalf("noise render not deterministic at sample %d", i)
}
}
}
func TestAllWavesAndPresets(t *testing.T) {
for _, w := range []string{"square", "saw", "sine", "triangle", "noise"} {
p := Defaults()
p.Wave = w
if s := Render(&p); len(s) == 0 {
t.Errorf("wave %s rendered nothing", w)
}
}
for _, name := range []string{"blip", "coin", "explosion", "hurt", "jump", "laser", "powerup"} {
p, err := Preset(name, 0)
if err != nil {
t.Errorf("preset %s: %v", name, err)
continue
}
s := Render(p)
var sum float64
for _, v := range s {
sum += v * v
}
rms := math.Sqrt(sum / float64(len(s)))
if rms < 0.01 {
t.Errorf("preset %s is nearly silent (rms %g)", name, rms)
}
// variants stay valid
if _, err := Preset(name, 7); err != nil {
t.Errorf("preset %s seed 7: %v", name, err)
}
}
if _, err := Preset("nope", 0); err == nil {
t.Error("unknown preset should error")
}
}
func TestWAVRoundTrip(t *testing.T) {
p := Defaults()
samples := Render(&p)
var buf bytes.Buffer
if err := WriteWAV(&buf, samples, p.SampleRate); err != nil {
t.Fatal(err)
}
sr, bits, ch, dataBytes, err := ReadWAVHeader(&buf)
if err != nil {
t.Fatal(err)
}
if sr != 44100 || bits != 16 || ch != 1 {
t.Errorf("header: sr=%d bits=%d ch=%d", sr, bits, ch)
}
if dataBytes != len(samples)*2 {
t.Errorf("dataBytes = %d, want %d", dataBytes, len(samples)*2)
}
if buf.Len() != dataBytes {
t.Errorf("body length %d != declared %d", buf.Len(), dataBytes)
}
}
func TestParamsWriteRoundTrip(t *testing.T) {
p, err := Preset("coin", 3)
if err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
if err := p.Write(&buf, "test"); err != nil {
t.Fatal(err)
}
back, err := Parse(&buf)
if err != nil {
t.Fatalf("re-parse of written .sfx failed: %v\n%s", err, buf.String())
}
if back.Freq != p.Freq || back.ArpFactor != p.ArpFactor || back.Seed != p.Seed {
t.Errorf("roundtrip mismatch: %+v vs %+v", back, p)
}
}

122
sfx-maker/sfx/synth.go Normal file
View File

@@ -0,0 +1,122 @@
package sfx
import (
"math"
"math/rand"
)
// Render synthesizes the effect into float64 samples in [-1, 1].
func Render(p *Params) []float64 {
sr := float64(p.SampleRate)
n := int(p.Duration() * sr)
out := make([]float64, n)
rng := rand.New(rand.NewSource(p.Seed))
phase := 0.0
noiseVal := 0.0
noiseCounter := 0.0
// one-pole filter states
lpState := 0.0
hpState := 0.0
hpPrevIn := 0.0
dt := 1 / sr
lpAlpha := 0.0
if p.LowPass > 0 {
rc := 1 / (2 * math.Pi * p.LowPass)
lpAlpha = dt / (rc + dt)
}
hpAlpha := 0.0
if p.HighPass > 0 {
rc := 1 / (2 * math.Pi * p.HighPass)
hpAlpha = rc / (rc + dt)
}
for i := 0; i < n; i++ {
t := float64(i) / sr
f := p.Freq + p.FreqSlide*t
if p.ArpFactor != 0 && p.ArpTime > 0 && t >= p.ArpTime {
f *= p.ArpFactor
}
if p.VibratoDepth > 0 && p.VibratoRate > 0 {
f += p.VibratoDepth * math.Sin(2*math.Pi*p.VibratoRate*t)
}
if f < p.FreqMin {
f = p.FreqMin
}
var s float64
if p.Wave == "noise" {
// pitched noise: new random value f*4 times per second
noiseCounter += f * 4 * dt
if noiseCounter >= 1 || i == 0 {
noiseCounter = math.Mod(noiseCounter, 1)
noiseVal = rng.Float64()*2 - 1
}
s = noiseVal
} else {
phase += f * dt
ph := math.Mod(phase, 1)
switch p.Wave {
case "square":
if ph < p.Duty {
s = 1
} else {
s = -1
}
case "saw":
s = 2*ph - 1
case "triangle":
if ph < 0.5 {
s = 4*ph - 1
} else {
s = 3 - 4*ph
}
case "sine":
s = math.Sin(2 * math.Pi * ph)
}
}
s *= envelope(p, t)
if lpAlpha > 0 {
lpState += lpAlpha * (s - lpState)
s = lpState
}
if hpAlpha > 0 {
hpState = hpAlpha * (hpState + s - hpPrevIn)
hpPrevIn = s
s = hpState
}
s *= p.Volume
if s > 1 {
s = 1
} else if s < -1 {
s = -1
}
out[i] = s
}
return out
}
// envelope is a linear attack / sustain / decay gain in 0..1.
func envelope(p *Params, t float64) float64 {
switch {
case t < p.Attack:
return t / p.Attack
case t < p.Attack+p.Sustain:
return 1
default:
d := t - p.Attack - p.Sustain
if p.Decay <= 0 {
return 0
}
g := 1 - d/p.Decay
if g < 0 {
g = 0
}
return g
}
}

54
sfx-maker/sfx/wav.go Normal file
View File

@@ -0,0 +1,54 @@
package sfx
import (
"encoding/binary"
"fmt"
"io"
"math"
)
// WriteWAV encodes samples ([-1,1] floats) as a 16-bit mono PCM WAV.
func WriteWAV(w io.Writer, samples []float64, sampleRate int) error {
dataLen := len(samples) * 2
var hdr [44]byte
copy(hdr[0:4], "RIFF")
binary.LittleEndian.PutUint32(hdr[4:8], uint32(36+dataLen))
copy(hdr[8:12], "WAVE")
copy(hdr[12:16], "fmt ")
binary.LittleEndian.PutUint32(hdr[16:20], 16) // fmt chunk size
binary.LittleEndian.PutUint16(hdr[20:22], 1) // PCM
binary.LittleEndian.PutUint16(hdr[22:24], 1) // mono
binary.LittleEndian.PutUint32(hdr[24:28], uint32(sampleRate)) // sample rate
binary.LittleEndian.PutUint32(hdr[28:32], uint32(sampleRate*2)) // byte rate
binary.LittleEndian.PutUint16(hdr[32:34], 2) // block align
binary.LittleEndian.PutUint16(hdr[34:36], 16) // bits per sample
copy(hdr[36:40], "data")
binary.LittleEndian.PutUint32(hdr[40:44], uint32(dataLen))
if _, err := w.Write(hdr[:]); err != nil {
return err
}
buf := make([]byte, 2*len(samples))
for i, s := range samples {
v := int16(math.Round(s * 32767))
binary.LittleEndian.PutUint16(buf[i*2:], uint16(v))
}
_, err := w.Write(buf)
return err
}
// ReadWAVHeader sanity-parses a WAV header (used in tests and info).
func ReadWAVHeader(r io.Reader) (sampleRate, bits, channels, dataBytes int, err error) {
var hdr [44]byte
if _, err = io.ReadFull(r, hdr[:]); err != nil {
return
}
if string(hdr[0:4]) != "RIFF" || string(hdr[8:12]) != "WAVE" {
err = fmt.Errorf("not a WAV file")
return
}
channels = int(binary.LittleEndian.Uint16(hdr[22:24]))
sampleRate = int(binary.LittleEndian.Uint32(hdr[24:28]))
bits = int(binary.LittleEndian.Uint16(hdr[34:36]))
dataBytes = int(binary.LittleEndian.Uint32(hdr[40:44]))
return
}