Compare commits
6 Commits
mesh-tool-
...
sfx-maker-
| Author | SHA1 | Date | |
|---|---|---|---|
| dc78c791df | |||
| d2bf781a71 | |||
| e7ac31b5c8 | |||
| ec814c373a | |||
| 6b3a493703 | |||
| 6b10c4a57c |
@@ -20,7 +20,7 @@ jobs:
|
||||
- name: Detektera ändrade tools
|
||||
id: changed
|
||||
run: |
|
||||
TOOLS="pixel-sprite-maker mesh-tool"
|
||||
TOOLS="pixel-sprite-maker mesh-tool bitmap-font-maker sfx-maker"
|
||||
BEFORE="${{ github.event.before }}"
|
||||
CHANGED=""
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ] \
|
||||
@@ -56,6 +56,8 @@ jobs:
|
||||
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) ==="
|
||||
@@ -82,6 +84,8 @@ jobs:
|
||||
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)."
|
||||
|
||||
34
.vscode/tasks.json
vendored
34
.vscode/tasks.json
vendored
@@ -17,6 +17,38 @@
|
||||
"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",
|
||||
@@ -35,7 +67,7 @@
|
||||
},
|
||||
{
|
||||
"label": "build",
|
||||
"dependsOn": ["build pixel-sprite-maker", "build mesh-tool"],
|
||||
"dependsOn": ["build pixel-sprite-maker", "build mesh-tool", "build bitmap-font-maker", "build sfx-maker"],
|
||||
"dependsOrder": "parallel",
|
||||
"group": { "kind": "build", "isDefault": true },
|
||||
"problemMatcher": []
|
||||
|
||||
@@ -10,6 +10,8 @@ agent understands the result without opening an image viewer.
|
||||
|------|--------|--------------|
|
||||
| [`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>`).
|
||||
|
||||
75
bitmap-font-maker/README.md
Normal file
75
bitmap-font-maker/README.md
Normal 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.
|
||||
BIN
bitmap-font-maker/examples/out/hej.png
Normal file
BIN
bitmap-font-maker/examples/out/hej.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 405 B |
340
bitmap-font-maker/examples/out/tiny5.json
Normal file
340
bitmap-font-maker/examples/out/tiny5.json
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
bitmap-font-maker/examples/out/tiny5.png
Normal file
BIN
bitmap-font-maker/examples/out/tiny5.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 468 B |
334
bitmap-font-maker/examples/tiny5.font
Normal file
334
bitmap-font-maker/examples/tiny5.font
Normal 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 ':
|
||||
#
|
||||
#
|
||||
.
|
||||
.
|
||||
.
|
||||
238
bitmap-font-maker/font/font.go
Normal file
238
bitmap-font-maker/font/font.go
Normal 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
|
||||
}
|
||||
144
bitmap-font-maker/font/font_test.go
Normal file
144
bitmap-font-maker/font/font_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
165
bitmap-font-maker/font/render.go
Normal file
165
bitmap-font-maker/font/render.go
Normal 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
3
bitmap-font-maker/go.mod
Normal 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
258
bitmap-font-maker/main.go
Normal 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)
|
||||
}
|
||||
68
sfx-maker/README.md
Normal file
68
sfx-maker/README.md
Normal 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`.
|
||||
9
sfx-maker/examples/blip.sfx
Normal file
9
sfx-maker/examples/blip.sfx
Normal 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
BIN
sfx-maker/examples/blip.wav
Normal file
Binary file not shown.
10
sfx-maker/examples/coin.sfx
Normal file
10
sfx-maker/examples/coin.sfx
Normal 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
BIN
sfx-maker/examples/coin.wav
Normal file
Binary file not shown.
9
sfx-maker/examples/explosion.sfx
Normal file
9
sfx-maker/examples/explosion.sfx
Normal 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
|
||||
BIN
sfx-maker/examples/explosion.wav
Normal file
BIN
sfx-maker/examples/explosion.wav
Normal file
Binary file not shown.
9
sfx-maker/examples/hurt.sfx
Normal file
9
sfx-maker/examples/hurt.sfx
Normal 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
BIN
sfx-maker/examples/hurt.wav
Normal file
Binary file not shown.
9
sfx-maker/examples/jump.sfx
Normal file
9
sfx-maker/examples/jump.sfx
Normal 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
BIN
sfx-maker/examples/jump.wav
Normal file
Binary file not shown.
10
sfx-maker/examples/laser.sfx
Normal file
10
sfx-maker/examples/laser.sfx
Normal 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
|
||||
BIN
sfx-maker/examples/laser.wav
Normal file
BIN
sfx-maker/examples/laser.wav
Normal file
Binary file not shown.
12
sfx-maker/examples/powerup.sfx
Normal file
12
sfx-maker/examples/powerup.sfx
Normal 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
|
||||
BIN
sfx-maker/examples/powerup.wav
Normal file
BIN
sfx-maker/examples/powerup.wav
Normal file
Binary file not shown.
3
sfx-maker/go.mod
Normal file
3
sfx-maker/go.mod
Normal 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
212
sfx-maker/main.go
Normal 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
223
sfx-maker/sfx/params.go
Normal 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
114
sfx-maker/sfx/presets.go
Normal 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
164
sfx-maker/sfx/sfx_test.go
Normal 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
122
sfx-maker/sfx/synth.go
Normal 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
54
sfx-maker/sfx/wav.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user