Compare commits
7 Commits
dev/mesh-t
...
ec814c373a
| Author | SHA1 | Date | |
|---|---|---|---|
| ec814c373a | |||
| 6b3a493703 | |||
| 6b10c4a57c | |||
| a5b8a249ed | |||
| 3eb4fa0b1d | |||
| 42422be2f7 | |||
| 23135a96d1 |
107
.gitea/workflows/release.yml
Normal file
@@ -0,0 +1,107 @@
|
||||
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"
|
||||
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 ;;
|
||||
*) 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 ;;
|
||||
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
@@ -0,0 +1,3 @@
|
||||
build/
|
||||
*.exe
|
||||
mesh-tool/examples/downloads/
|
||||
60
.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"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": "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"],
|
||||
"dependsOrder": "parallel",
|
||||
"group": { "kind": "build", "isDefault": true },
|
||||
"problemMatcher": []
|
||||
}
|
||||
]
|
||||
}
|
||||
46
README.md
@@ -1,3 +1,47 @@
|
||||
# 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. |
|
||||
|
||||
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
|
||||
|
||||
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
|
After Width: | Height: | Size: 405 B |
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
|
After Width: | Height: | Size: 468 B |
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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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.
|
||||
86
pixel-sprite-maker/README.md
Normal 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/`.
|
||||
17
pixel-sprite-maker/examples/coin.sprite
Normal 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..
|
||||
25
pixel-sprite-maker/examples/heart.sprite
Normal 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........
|
||||
................
|
||||
................
|
||||
BIN
pixel-sprite-maker/examples/out/coin.png
Normal file
|
After Width: | Height: | Size: 344 B |
34
pixel-sprite-maker/examples/out/coin.svg
Normal 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 |
BIN
pixel-sprite-maker/examples/out/heart.jpg
Normal file
|
After Width: | Height: | Size: 1.5 KiB |
BIN
pixel-sprite-maker/examples/out/walk_8x8_4x1.png
Normal file
|
After Width: | Height: | Size: 508 B |
57
pixel-sprite-maker/examples/out/walkgrid_8x8_2x2.svg
Normal 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 |
16
pixel-sprite-maker/examples/walk_1.sprite
Normal 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...
|
||||
16
pixel-sprite-maker/examples/walk_2.sprite
Normal 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..
|
||||
16
pixel-sprite-maker/examples/walk_3.sprite
Normal 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...
|
||||
16
pixel-sprite-maker/examples/walk_4.sprite
Normal 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...
|
||||
3
pixel-sprite-maker/go.mod
Normal 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
@@ -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)
|
||||
}
|
||||
270
pixel-sprite-maker/sprite/color.go
Normal 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},
|
||||
}
|
||||
186
pixel-sprite-maker/sprite/parse.go
Normal 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
|
||||
}
|
||||
75
pixel-sprite-maker/sprite/render.go
Normal 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,
|
||||
}
|
||||
}
|
||||
58
pixel-sprite-maker/sprite/sheet.go
Normal 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)
|
||||
}
|
||||
207
pixel-sprite-maker/sprite/sprite_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
46
pixel-sprite-maker/sprite/svg.go
Normal 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
|
||||
}
|
||||