Compare commits

..

3 Commits

Author SHA1 Message Date
ISSOtm
bffe7eb4de Implement new instructions
"Who are you? What are you doing in my commit history?"
~ https://xkcd.com/163/
2022-04-01 12:46:52 +02:00
ISSOtm
cd454d2e9a Hack in new register syntax
Oh my god I want to die x_x
2022-04-01 12:46:52 +02:00
ISSOtm
c814a616d6 Port Gan's work to Mandoc format
Hopefully I didn't forget anything
2022-04-01 12:46:52 +02:00
749 changed files with 8938 additions and 15975 deletions

88
.checkpatch.conf Normal file
View File

@@ -0,0 +1,88 @@
# Configuration for checkpatch.pl
# ===============================
# Enable more tests
--strict
# Quiet
--quiet
# No per-file summary
--no-summary
# Don't expect the Linux kernel tree
--no-tree
# Show file line, not input line
--showfile
# Don't expect SPDX tag in the first line of a file
--ignore SPDX_LICENSE_TAG
# Don't expect Signed-off-by lines in commit messages
--no-signoff
# List of ignored rules
# ---------------------
# There's no BIT macro
--ignore BIT_MACRO
# Don't complain when bools are used in structs
--ignore BOOL_MEMBER
# Allow CamelCase
--ignore CAMELCASE
# Comparing to NULL explicitly isn't a bad thing
--ignore COMPARISON_TO_NULL
# Causes false positives
--ignore COMPLEX_MACRO
# Don't complain about structs not being const
--ignore CONST_STRUCT
# Don't complain about printing "warning:" without the function name, as warning
# printing is relevant to the code being parsed, not RGBDS' code
--ignore EMBEDDED_FUNCTION_NAME
# Do not check the format of commit messages
--ignore GIT_COMMIT_ID
# Do not check for global initializers (this is specific to the kernel)
--ignore GLOBAL_INITIALISERS
# Don't complain about initializing statics (this is specific to the kernel)
--ignore INITIALISED_STATIC
# We don't have a MAINTAINERS file, don't complain about it.
--ignore FILE_PATH_CHANGES
# Writing the continuation on the start of the line can make it clearer
--ignore LOGICAL_CONTINUATIONS
# Don't complain if a line that contains a string is too long. It's better to
# have a really long line that can be found with grep.
--ignore LONG_LINE_STRING
# Don't complain when files are modified in 'include/asm'
--ignore MODIFIED_INCLUDE_ASM
# Allow new typedefs
--ignore NEW_TYPEDEFS
# We allow lines ending with parentheses for the usage prints
--ignore OPEN_ENDED_LINE
# Prefer stdint.h types over kernel types
--ignore PREFER_KERNEL_TYPES
# Don't ask to replace sscanf by kstrto
--ignore SSCANF_TO_KSTRTO
# Parentheses can make the code clearer
--ignore UNNECESSARY_PARENTHESES
# We don't have `fallthrough;` */
--ignore PREFER_FALLTHROUGH

View File

@@ -96,4 +96,4 @@ SpacesInSquareBrackets: false
Standard: c++20
TabWidth: 4
UseCRLF: false
UseTab: ForIndentation
UseTab: AlignWithSpaces

View File

@@ -1,3 +1,7 @@
# This file is part of RGBDS.
#
# Copyright (c) 2018-2019, Phil Smith and RGBDS contributors.
#
# SPDX-License-Identifier: MIT
.git
docs

4
.gitattributes vendored
View File

@@ -1,6 +1,2 @@
# Shell scripts need Unix line endings (see https://github.com/gbdev/rgbds/issues/841)
*.sh text eol=lf
*.bash text eol=lf
# Flags also need Unix line endings (see https://github.com/gbdev/rgbds/issues/955)
*.flags text eol=lf

3
.github/FUNDING.yml vendored
View File

@@ -1,2 +1,3 @@
github: avivace
patreon: gbdev01
open_collective: gbdev
github: gbdev

56
.github/actions/doc_postproc.awk vendored Executable file
View File

@@ -0,0 +1,56 @@
#!/usr/bin/awk -f
/^\s+<td><b class="Sy">.+<\/b><\/td>$/ {
# Assuming that all cells whose contents are bold are heading cells,
# use the HTML tag for those
sub(/td><b class="Sy"/, "th");
sub(/b><\/td/, "th");
}
# The whole page is being generated, so it's not meant to contain any Liquid
BEGIN {
print "{% raw %}"
}
END {
print "{% endraw %}"
}
BEGIN {
in_synopsis = 0
}
/<table class="Nm">/ {
in_synopsis = 1
}
/<\/table>/ {
# Resets synopsis state even when already reset, but whatever
in_synopsis = 0
}
/<code class="Fl">-[a-zA-Z]/ {
# Add links to arg descr in synopsis section
if (in_synopsis) {
while (match($0, /<code class="Fl">-[a-zA-Z]+/)) {
# 123456789012345678 -> 18 chars
optchars = substr($0, RSTART + 18, RLENGTH - 18)
i = length(optchars)
while (i) {
end = RSTART + 18 + i
i -= 1
len = i ? 1 : 2
$0 = sprintf("%s<a href=\"#%s\">%s</a>%s",
substr($0, 0, end - len - 1),
substr($0, end - 1, 1),
substr($0, end - len, len),
substr($0, end))
}
}
}
}
{
# Make long opts (defined using `Fl Fl`) into a single tag
gsub(/<code class="Fl">-<\/code>\s*<code class="Fl">/, "<code class=\"Fl\">-")
}
{
print
}

113
.github/actions/get-pages.sh vendored Executable file
View File

@@ -0,0 +1,113 @@
#!/bin/bash
usage() {
cat <<EOF
Usage: $0 [-h] [-r] <rgbds-www> <version>
Copy renders from RGBDS repository to rgbds-www documentation
Execute from the root folder of the RGBDS repo, checked out at the desired tag
<rgbds-www> : Path to the rgbds-www repository
<version> : Version to be copied, such as 'v0.4.1' or 'master'
-h Display this help message
-r Update "latest stable" redirection pages and add a new entry to the index
(use for releases, not master)
EOF
}
is_release=0
bad_usage=0
while getopts ":hr" opt; do
case $opt in
r)
is_release=1
;;
h)
usage
exit 0
;;
\?)
echo "Unknown option '$OPTARG'"
bad_usage=1
;;
esac
done
if [ $bad_usage -ne 0 ]; then
usage
exit 1
fi
shift $(($OPTIND - 1))
declare -A PAGES
PAGES=(
[rgbasm.1.html]=src/asm/rgbasm.1
[rgbasm.5.html]=src/asm/rgbasm.5
[rgblink.1.html]=src/link/rgblink.1
[rgblink.5.html]=src/link/rgblink.5
[rgbfix.1.html]=src/fix/rgbfix.1
[rgbgfx.1.html]=src/gfx/rgbgfx.1
[rgbds.5.html]=src/rgbds.5
[rgbds.7.html]=src/rgbds.7
[gbz80.7.html]=src/gbz80.7
)
WWWPATH="/docs"
mkdir -p "$1/_documentation/$2"
# `mandoc` uses a different format for referring to man pages present in the **current** directory.
# We want that format for RGBDS man pages, and the other one for the rest;
# we thus need to copy all pages to a temporary directory, and process them there.
# Copy all pages to current dir
cp "${PAGES[@]}" .
for page in "${!PAGES[@]}"; do
stem="${page%.html}"
manpage="${stem%.?}(${stem#*.})"
descr="$(awk -v 'FS=.Nd ' '/.Nd/ { print $2; }' "${PAGES[$page]}")"
cat >"$1/_documentation/$2/$page" <<EOF
---
layout: doc
title: $manpage [$2]
description: RGBDS $2 — $descr
---
EOF
options=fragment,man='%N.%S;https://linux.die.net/man/%S/%N'
if [ $stem = rgbasm.5 ]; then
options+=,toc
fi
mandoc -Thtml -I os=Linux -O$options "${PAGES[$page]##*/}" | .github/actions/doc_postproc.awk >> "$1/_documentation/$2/$page"
groff -Tpdf -mdoc -wall "${PAGES[$page]##*/}" >"$1/_documentation/$2/$stem.pdf"
if [ $is_release -ne 0 ]; then
cat - >"$1/_documentation/$page" <<EOF
---
redirect_to: $WWWPATH/$2/${page%.html}
permalink: $WWWPATH/${page%.html}/
title: $manpage [latest stable]
description: RGBDS latest stable — $descr
---
EOF
fi
done
cat - >"$1/_documentation/$2/index.html" <<EOF
---
layout: doc_index
permalink: /docs/$2/
title: RGBDS online manual [$2]
description: RGBDS $2 - Online manual
---
EOF
# If making a release, add a new entry right after `master`
if [ $is_release -ne 0 ]; then
awk '{ print }
/"name": "master"/ { print "\t\t{\"name\": \"'$2'\", \"text\": \"'$2'\" }," }
' "$1/_data/doc.json" >"$1/_data/doc.json.tmp"
mv "$1/_data/doc.json"{.tmp,}
fi
# Clean up
rm "${PAGES[@]##*/}"

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/bin/bash
set -e
case "${1%-*}" in

17
.github/actions/mingw-configure.sh vendored Normal file
View File

@@ -0,0 +1,17 @@
#!/bin/bash
source mingw-env @TRIPLE@
echo LAST IS: $last
# check if last arg is a path to configure, else use parent
for last; do true; done
if test -x "${last}/configure"; then
config_path="$last"
else
config_path=".."
fi
${config_path}/configure \
--host=@TRIPLE@ --target=@TRIPLE@ --build="$CHOST" \
--prefix=/usr/@TRIPLE@ --libdir=/usr/@TRIPLE@/lib --includedir=/usr/@TRIPLE@/include \
--enable-shared --enable-static "$@"

16
.github/actions/mingw-env.sh vendored Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
_arch=$1
default_mingw_pp_flags="-D_FORTIFY_SOURCE=2"
default_mingw_compiler_flags="$default_mingw_pp_flags -O2 -pipe -fno-plt -fexceptions --param=ssp-buffer-size=4"
default_mingw_linker_flags="-Wl,-O1,--sort-common,--as-needed -fstack-protector"
export CPPFLAGS="${MINGW_CPPFLAGS:-$default_mingw_pp_flags $CPPFLAGS}"
export CFLAGS="${MINGW_CFLAGS:-$default_mingw_compiler_flags $CFLAGS}"
export CXXFLAGS="${MINGW_CXXFLAGS:-$default_mingw_compiler_flags $CXXFLAGS}"
export LDFLAGS="${MINGW_LDFLAGS:-$default_mingw_linker_flags $LDFLAGS}"
mingw_prefix=/usr/${_arch}
export PKG_CONFIG_SYSROOT_DIR="${mingw_prefix}"
export PKG_CONFIG_LIBDIR="${mingw_prefix}/lib/pkgconfig:${mingw_prefix}/share/pkgconfig"

44
.github/actions/mingw-w64-libpng-dev.sh vendored Executable file
View File

@@ -0,0 +1,44 @@
#!/bin/sh
# This script was written by ISSOtm while looking at Arch Linux's PKGBUILD for
# the corresponding package. (And its dependencies)
# https://aur.archlinux.org/packages/mingw-w64-libpng/
set -e
pngver=1.6.37
_apngver=$pngver
_arch="$1"
## Install mingw-configure and mingw-env (both build dependencies)
install -m 755 .github/actions/mingw-env.sh /usr/bin/mingw-env
sed "s|@TRIPLE@|${_arch}|g" .github/actions/mingw-configure.sh > ${_arch}-configure
install -m 755 ${_arch}-configure /usr/bin/
## Grab sources and check them
wget http://downloads.sourceforge.net/sourceforge/libpng/libpng-$pngver.tar.xz
wget http://downloads.sourceforge.net/project/apng/libpng/libpng16/libpng-$_apngver-apng.patch.gz
sha256sum -c .github/actions/mingw-w64-libpng-dev.sha256sums
## Extract sources
tar -xf libpng-$pngver.tar.xz
gunzip libpng-$_apngver-apng.patch.gz
## Start building!
cd libpng-$pngver
# Patch in apng support
patch -p0 ../libpng-$_apngver-apng.patch
mkdir -p build-${_arch}
cd build-${_arch}
${_arch}-configure LDFLAGS=-static-libgcc
make
make install

View File

@@ -1,23 +0,0 @@
function getlibrary ([string] $URI, [string] $filename, [string] $hash, [string] $destdir) {
$wc = New-Object Net.WebClient
[string] $downloadhash = $null
try {
$wc.DownloadFile($URI, $filename)
$downloadhash = $(Get-FileHash $filename -Algorithm SHA256).Hash
} catch {
Write-Host "${filename}: failed to download"
exit 1
}
if ($hash -ne $downloadhash) {
Write-Host "${filename}: SHA256 mismatch ($downloadhash)"
exit 1
}
Expand-Archive -DestinationPath $destdir $filename
}
getlibrary 'https://www.zlib.net/zlib13.zip' 'zlib.zip' 'c561d09347f674f0d72692e7c75d9898919326c532aab7f8c07bb43b07efeb38' .
getlibrary 'https://github.com/glennrp/libpng/archive/refs/tags/v1.6.37.zip' 'libpng.zip' 'c2c50c13a727af73ecd3fc0167d78592cf5e0bca9611058ca414b6493339c784' .
getlibrary 'https://github.com/lexxmark/winflexbison/releases/download/v2.5.24/win_flex_bison-2.5.24.zip' 'winflexbison.zip' '39c6086ce211d5415500acc5ed2d8939861ca1696aee48909c7f6daf5122b505' install_dir
Move-Item zlib-1.3 zlib
Move-Item libpng-1.6.37 libpng

View File

@@ -1,7 +0,0 @@
#!/usr/bin/env bash
install -d /usr/local/bin/ /usr/local/share/man/man1/ /usr/local/share/man/man5/ /usr/local/share/man/man7/
install -s -m 755 rgbasm rgblink rgbfix rgbgfx /usr/local/bin/
install -m 644 rgbasm.1 rgblink.1 rgbfix.1 rgbgfx.1 /usr/local/share/man/man1/
install -m 644 rgbds.5 rgbasm.5 rgblink.5 /usr/local/share/man/man5/
install -m 644 rgbds.7 gbz80.7 /usr/local/share/man/man7/

View File

@@ -1,33 +0,0 @@
#!/bin/sh
set -e
pngver=1.6.37
arch="$1"
## Grab sources and check them
wget http://downloads.sourceforge.net/project/libpng/libpng16/$pngver/libpng-$pngver.tar.xz
wget http://downloads.sourceforge.net/project/apng/libpng/libpng16/libpng-$pngver-apng.patch.gz
sha256sum -c .github/scripts/mingw-w64-libpng-dev.sha256sums
## Extract sources and patch them
tar -xf libpng-$pngver.tar.xz
gunzip libpng-$pngver-apng.patch.gz
# Patch in apng support
env -C libpng-$pngver patch -p0 ../libpng-$pngver-apng.patch
## Start building!
mkdir -p build
cd build
../libpng-$pngver/configure \
--host="$arch" --target="$arch" \
--prefix="/usr/$arch" \
--enable-shared --disable-static \
CPPFLAGS="-D_FORTIFY_SOURCE=2" \
CFLAGS="-O2 -pipe -fno-plt -fexceptions --param=ssp-buffer-size=4" \
LDFLAGS="-Wl,-O1,--sort-common,--as-needed -fstack-protector"
make -kj
make install

25
.github/workflows/checkpatch.yml vendored Normal file
View File

@@ -0,0 +1,25 @@
name: "Code style checking"
on: pull_request
jobs:
checkpatch:
runs-on: ubuntu-latest
steps:
- name: Set up repo
run: |
git clone -b "${{ github.event.pull_request.head.ref }}" "${{ github.event.pull_request.head.repo.clone_url }}" rgbds
cd rgbds
git remote add upstream "${{ github.event.pull_request.base.repo.clone_url }}"
git fetch upstream
- name: Set up checkpatch
working-directory: rgbds
run: |
wget 'https://raw.githubusercontent.com/torvalds/linux/master/scripts/checkpatch.pl'
chmod +x checkpatch.pl
wget 'https://raw.githubusercontent.com/torvalds/linux/master/scripts/const_structs.checkpatch'
wget 'https://raw.githubusercontent.com/torvalds/linux/master/scripts/spelling.txt'
- name: Checkpatch
working-directory: rgbds
run: |
make checkpatch CHECKPATCH=./checkpatch.pl "BASE_REF=${{ github.event.pull_request.base.sha }}" Q= | tee log
if grep -q ERROR: log; then exit 1; else exit 0; fi

View File

@@ -0,0 +1,96 @@
name: "Create release artifacts"
on:
push:
tags:
- v[0-9]*
jobs:
windows:
runs-on: windows-2019
steps:
- uses: actions/checkout@v2
- name: Get version from tag
shell: bash
run: | # Turn "refs/tags/vX.Y.Z" into "X.Y.Z"
VERSION="${{ github.ref }}"
echo "version=${VERSION##*/v}" >> $GITHUB_ENV
- name: Get zlib, libpng and bison
run: | # TODO: use an array
$wc = New-Object System.Net.WebClient
$wc.DownloadFile('https://www.zlib.net/zlib1212.zip', 'zlib.zip')
$hash = (Get-FileHash "zlib.zip" -Algorithm SHA256).Hash
if ($hash -ne '173e89893dcb8b4a150d7731cd72f0602f1d6b45e60e2a54efdf7f3fc3325fd7') {
Write-Host "zlib SHA256 mismatch! ($hash)"
exit 1
}
$wc.DownloadFile('https://download.sourceforge.net/libpng/lpng1637.zip', 'libpng.zip')
$hash = (Get-FileHash "libpng.zip" -Algorithm SHA256).Hash
if ($hash -ne '3b4b1cbd0bae6822f749d39b1ccadd6297f05e2b85a83dd2ce6ecd7d09eabdf2') {
Write-Host "libpng SHA256 mismatch! ($hash)"
exit 1
}
$wc.DownloadFile('https://github.com/lexxmark/winflexbison/releases/download/v2.5.24/win_flex_bison-2.5.24.zip', 'winflexbison.zip')
$hash = (Get-FileHash "winflexbison.zip" -Algorithm SHA256).Hash
if ($hash -ne '39c6086ce211d5415500acc5ed2d8939861ca1696aee48909c7f6daf5122b505') {
Write-Host "bison SHA256 mismatch! ($hash)"
}
Expand-Archive -DestinationPath . "zlib.zip"
Expand-Archive -DestinationPath . "libpng.zip"
Expand-Archive -DestinationPath install_dir "winflexbison.zip"
Move-Item zlib-1.2.12 zlib
Move-Item lpng1637 libpng
- name: Build 32-bit zlib
run: | # BUILD_SHARED_LIBS causes the output DLL to be correctly called `zlib1.dll`
cmake -S zlib -B zbuild32 -A Win32 -DCMAKE_INSTALL_PREFIX=install_dir -DBUILD_SHARED_LIBS=ON
cmake --build zbuild32 --config Release
cmake --install zbuild32
- name: Build 32-bit libpng
run: |
cmake -S libpng -B pngbuild32 -A Win32 -DCMAKE_INSTALL_PREFIX=install_dir -DPNG_SHARED=ON -DPNG_STATIC=ON -DPNG_TESTS=OFF
cmake --build pngbuild32 --config Release
cmake --install pngbuild32
- name: Build 32-bit Windows binaries
run: |
cmake -S . -B build32 -A Win32 -DCMAKE_INSTALL_PREFIX=install_dir -DCMAKE_BUILD_TYPE=Release
cmake --build build32 --config Release
cmake --install build32
- name: Package 32-bit binaries
run: |
Compress-Archive -LiteralPath @("install_dir/bin/rgbasm.exe", "install_dir/bin/rgblink.exe", "install_dir/bin/rgbfix.exe", "install_dir/bin/rgbgfx.exe", "install_dir/bin/zlib1.dll", "install_dir/bin/libpng16.dll") "rgbds-${{ env.version }}-win32.zip"
- name: Build 64-bit zlib
run: | # BUILD_SHARED_LIBS causes the output DLL to be correctly called `zlib1.dll`
cmake -S zlib -B zbuild64 -A x64 -DCMAKE_INSTALL_PREFIX=install_dir -DBUILD_SHARED_LIBS=ON
cmake --build zbuild64 --config Release
cmake --install zbuild64
- name: Build 64-bit libpng
run: |
cmake -S libpng -B pngbuild64 -A x64 -DCMAKE_INSTALL_PREFIX=install_dir -DPNG_SHARED=ON -DPNG_STATIC=ON -DPNG_TESTS=OFF
cmake --build pngbuild64 --config Release
cmake --install pngbuild64
- name: Build 64-bit Windows binaries
run: |
cmake -S . -B build64 -A x64 -DCMAKE_INSTALL_PREFIX=install_dir -DCMAKE_BUILD_TYPE=Release
cmake --build build64 --config Release
cmake --install build64
- name: Package 64-bit binaries
run: |
Compress-Archive -LiteralPath @("install_dir/bin/rgbasm.exe", "install_dir/bin/rgblink.exe", "install_dir/bin/rgbfix.exe", "install_dir/bin/rgbgfx.exe", "install_dir/bin/zlib1.dll", "install_dir/bin/libpng16.dll") "rgbds-${{ env.version }}-win64.zip"
- name: Package sources
run: |
make dist
- name: Release
uses: softprops/action-gh-release@v1
with:
body: |
Please ensure that the three assets below work properly.
Once that's done, replace this text with the changelog, un-draft the release, and update the `release` branch.
By the way, if you forgot to update `include/version.h`, RGBASM's version test is gonna fail in the tag's regression testing! (Use `git push --delete origin <tag>` to delete it)
draft: true # Don't publish the release quite yet...
prerelease: ${{ contains(github.ref, '-rc') }}
files: |
rgbds-${{ env.version }}-win32.zip
rgbds-${{ env.version }}-win64.zip
rgbds-${{ env.version }}.tar.gz
fail_on_unmatched_files: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,153 +0,0 @@
name: "Create release artifacts"
on:
push:
tags:
- v[0-9]*
jobs:
windows:
runs-on: windows-2022
strategy:
matrix:
bits: [32, 64]
include:
- bits: 32
arch: x86
platform: Win32
- bits: 64
arch: x86_x64
platform: x64
fail-fast: false
steps:
- name: Get version from tag
shell: bash
run: | # Turn "vX.Y.Z" into "X.Y.Z"
VERSION="${{ github.ref_name }}"
echo "version=${VERSION#v}" >> $GITHUB_ENV
- uses: actions/checkout@v3
- name: Install deps
run: .github/scripts/get_win_deps.ps1
- uses: actions/cache@v3
id: cache
with:
path: |
zbuild
pngbuild
key: ${{ matrix.arch }}-${{ hashFiles('zlib/**', 'libpng/**') }}
- name: Build zlib
run: | # BUILD_SHARED_LIBS causes the output DLL to be correctly called `zlib1.dll`
cmake -S zlib -B zbuild -A ${{ matrix.platform }} -Wno-dev -DCMAKE_INSTALL_PREFIX=install_dir -DBUILD_SHARED_LIBS=ON
cmake --build zbuild --config Release -j
if: steps.cache.outputs.cache-hit != 'true'
- name: Install zlib
run: |
cmake --install zbuild
- name: Build libpng
shell: bash
run: |
cmake -S libpng -B pngbuild -A ${{ matrix.platform }} -Wno-dev -DCMAKE_INSTALL_PREFIX=install_dir -DPNG_SHARED=ON -DPNG_STATIC=OFF -DPNG_TESTS=OFF -DPNG_BUILD_ZLIB=ON -DZLIB_INCLUDE_DIR="$PWD"/install_dir/include -DZLIB_LIBRARY="$PWD"/install_dir/lib/zlib.lib
cmake --build pngbuild --config Release -j
if: steps.cache.outputs.cache-hit != 'true'
- name: Install libpng
run: |
cmake --install pngbuild
- name: Build Windows binaries
shell: bash
run: |
cmake -S . -B build -A ${{ matrix.platform }} -DCMAKE_INSTALL_PREFIX=install_dir -DCMAKE_BUILD_TYPE=Release -DZLIB_LIBRARY="$PWD"/install_dir/lib/zlib.lib -DZLIB_INCLUDE_DIR="$PWD"/install_dir/include -DPNG_LIBRARY="$PWD"/install_dir/lib/libpng16.lib -DPNG_INCLUDE_DIR="$PWD"/install_dir/include
cmake --build build --config Release -j --verbose
cmake --install build --verbose --prefix install_dir --strip
- name: Package binaries
run: |
Compress-Archive -LiteralPath @("install_dir/bin/rgbasm.exe", "install_dir/bin/rgblink.exe", "install_dir/bin/rgbfix.exe", "install_dir/bin/rgbgfx.exe", "install_dir/bin/zlib1.dll", "install_dir/bin/libpng16.dll") "rgbds-${{ env.version }}-win${{ matrix.bits }}.zip"
- name: Upload Windows binaries
uses: actions/upload-artifact@v3
with:
name: win${{ matrix.bits }}
path: rgbds-${{ env.version }}-win${{ matrix.bits }}.zip
macos:
runs-on: macos-12
steps:
- name: Get version from tag
shell: bash
run: | # Turn "refs/tags/vX.Y.Z" into "X.Y.Z"
VERSION="${{ github.ref_name }}"
echo "version=${VERSION#v}" >> $GITHUB_ENV
- uses: actions/checkout@v3
- name: Install deps
shell: bash
run: |
./.github/scripts/install_deps.sh macos-latest
# We force linking libpng statically; the other libs are provided by macOS itself
- name: Build binaries
run: |
export PATH="/usr/local/opt/bison/bin:$PATH"
make -j CXXFLAGS="-O3 -flto -DNDEBUG -mmacosx-version-min=10.9" PKG_CONFIG="pkg-config --static" PNGLDLIBS="$(pkg-config --static --libs-only-L libpng | cut -c 3-)/libpng.a $(pkg-config --static --libs-only-l libpng | sed s/-lpng[0-9]*//g)" Q=
- name: Package binaries
run: |
zip --junk-paths rgbds-${{ env.version }}-macos-x86_64.zip rgb{asm,link,fix,gfx} man/* .github/scripts/install.sh
- name: Upload macOS binaries
uses: actions/upload-artifact@v3
with:
name: macos
path: rgbds-${{ env.version }}-macos-x86_64.zip
linux:
runs-on: ubuntu-20.04 # Oldest supported, for best glibc compatibility.
steps:
- name: Get version from tag
shell: bash
run: | # Turn "refs/tags/vX.Y.Z" into "X.Y.Z"
VERSION="${{ github.ref_name }}"
echo "version=${VERSION#v}" >> $GITHUB_ENV
- uses: actions/checkout@v3
- name: Install deps
shell: bash
run: |
./.github/scripts/install_deps.sh ubuntu-20.04
- name: Build binaries
run: |
make -j WARNFLAGS="-Wall -Wextra -pedantic -static" PKG_CONFIG="pkg-config --static" Q=
- name: Package binaries
run: |
tar caf rgbds-${{ env.version }}-linux-x86_64.tar.xz --transform='s#.*/##' rgb{asm,link,fix,gfx} man/* .github/scripts/install.sh
- name: Upload Linux binaries
uses: actions/upload-artifact@v3
with:
name: linux
path: rgbds-${{ env.version }}-linux-x86_64.tar.xz
release:
runs-on: ubuntu-latest
needs: [windows, macos, linux]
steps:
- name: Get version from tag
shell: bash
run: | # Turn "refs/tags/vX.Y.Z" into "X.Y.Z"
VERSION="${{ github.ref_name }}"
echo "version=${VERSION#v}" >> $GITHUB_ENV
- uses: actions/checkout@v3
- name: Package sources
run: |
make dist Q=
ls
- uses: actions/download-artifact@v3
- name: Release
uses: softprops/action-gh-release@v1
with:
body: |
Please ensure that the four packages below work properly.
Once that's done, replace this text with the changelog, un-draft the release, and update the `release` branch.
By the way, if you forgot to update `include/version.hpp`, RGBASM's version test is gonna fail in the tag's regression testing! (Use `git push --delete origin <tag>` to delete it)
draft: true # Don't publish the release quite yet...
prerelease: ${{ contains(github.ref, '-rc') }}
files: |
win32/rgbds-${{ env.version }}-win32.zip
win64/rgbds-${{ env.version }}-win64.zip
macos/rgbds-${{ env.version }}-macos-x86_64.zip
linux/rgbds-${{ env.version }}-linux-x86_64.tar.xz
rgbds-${{ env.version }}.tar.gz
fail_on_unmatched_files: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -7,26 +7,32 @@ on:
jobs:
build:
if: github.repository_owner == 'gbdev'
runs-on: ubuntu-22.04
runs-on: ubuntu-18.04
steps:
- name: Checkout rgbds@release
uses: actions/checkout@v3
uses: actions/checkout@v2
with:
path: rgbds
- name: Checkout rgbds-www@master
uses: actions/checkout@v3
uses: actions/checkout@v2
with:
repository: ${{ github.repository_owner }}/rgbds-www
path: rgbds-www
- name: Install groff and mandoc
# `-O toc` was added in 1.14.5, but the repos only have 1.14.4
- name: Build and install mandoc + install groff
run: |
sudo apt-get -qq update
sudo apt-get install -yq groff mandoc
sudo apt-get install -yq groff zlib1g-dev
wget 'http://mandoc.bsd.lv/snapshots/mandoc-1.14.5.tar.gz'
tar xf mandoc-1.14.5.tar.gz
cd mandoc-1.14.5
./configure
make
sudo make install
- name: Update pages
working-directory: rgbds/man
working-directory: rgbds
run: | # The ref appears to be in the format "refs/tags/<version>", so strip that
../../rgbds-www/maintainer/man_to_html.sh ${GITHUB_REF##*/} *
../../rgbds-www/maintainer/new_release.sh ${GITHUB_REF##*/}
./.github/actions/get-pages.sh -r ../rgbds-www ${GITHUB_REF##*/}
- name: Push new pages
working-directory: rgbds-www
run: |

View File

@@ -4,143 +4,61 @@ on:
- pull_request
jobs:
unix:
unix-testing:
strategy:
matrix:
os: [ubuntu-20.04, ubuntu-22.04, macos-11, macos-12]
cxx: [g++, clang++]
os: [ubuntu-20.04, ubuntu-18.04, macos-11.0, macos-10.15]
cc: [gcc, clang]
buildsys: [make, cmake]
exclude:
# Don't use `g++` on macOS; it's just an alias to `clang++`.
- os: macos-11
cxx: g++
- os: macos-12
cxx: g++
# `gcc` is just an alias to `clang` on macOS, don't bother
- os: macos-10.15
cc: gcc
- os: macos-11.0
cc: gcc
fail-fast: false
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v2
- name: Install deps
shell: bash
run: |
./.github/scripts/install_deps.sh ${{ matrix.os }}
# Export `bison` to allow using the version we install from Homebrew,
# instead of the outdated one preinstalled on macOS (which doesn't
# even support `-Wall`...).
./.github/actions/install_deps.sh ${{ matrix.os }}
# The `export` lines are to allow working on macOS...
# Apple's base version is severely outdated, not even supporting -Wall,
# but it overrides Homebrew's version nonetheless...
- name: Build & install using Make
if: matrix.buildsys == 'make'
run: |
export PATH="/usr/local/opt/bison/bin:$PATH"
make develop -j Q= CXX=${{ matrix.cxx }}
make develop -j Q= CC=${{ matrix.cc }}
sudo make install -j Q=
if: matrix.buildsys == 'make'
- name: Build & install using CMake
if: matrix.buildsys == 'cmake'
run: |
export PATH="/usr/local/opt/bison/bin:$PATH"
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} -DSANITIZERS=ON -DMORE_WARNINGS=ON
cmake --build build -j --verbose
cmake -S . -B build -DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=${{ matrix.cc }} -DSANITIZERS=ON -DMORE_WARNINGS=ON
cmake --build build -j
cp build/src/rgb{asm,link,fix,gfx} .
sudo cmake --install build --verbose
cmake --install build --verbose --component "Test support programs"
sudo cmake --install build
if: matrix.buildsys == 'cmake'
- name: Package binaries
run: |
mkdir bins
cp rgb{asm,link,fix,gfx} bins
- name: Upload binaries
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v1
with:
name: rgbds-canary-${{ matrix.os }}-${{ matrix.cxx }}-${{ matrix.buildsys }}
name: rgbds-canary-${{ matrix.os }}-${{ matrix.cc }}-${{ matrix.buildsys }}
path: bins
- name: Compute test dependency cache params
id: test-deps-cache-params
shell: bash
run: |
paths=$(test/fetch-test-deps.sh --get-paths)
hash=$(test/fetch-test-deps.sh --get-hash)
tee -a <<<"paths=\"${paths//,/\\n}\"" $GITHUB_OUTPUT
tee -a <<<"hash=${hash%-}" $GITHUB_OUTPUT
- name: Check test dependency repositories cache
id: test-deps-cache
uses: actions/cache@v3
with:
path: ${{ fromJSON(steps.test-deps-cache-params.outputs.paths) }}
key: ${{ matrix.os }}-${{ steps.test-deps-cache-params.outputs.hash }}
- if: steps.test-deps-cache.outputs.cache-hit != 'true'
name: Fetch test dependency repositories
continue-on-error: true
run: |
test/fetch-test-deps.sh
- name: Install test dependency dependencies
shell: bash
run: |
test/fetch-test-deps.sh --get-deps ${{ matrix.os }}
- name: Run tests
- name: Test
shell: bash
run: |
test/run-tests.sh
macos-static:
strategy:
matrix:
# Don't run on macOS 11; our setup makes clang segfault (YES).
os: [macos-12]
fail-fast: false
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Install deps
shell: bash
run: |
./.github/scripts/install_deps.sh ${{ matrix.os }}
# Export `bison` to allow using the version we install from Homebrew,
# instead of the outdated one preinstalled on macOS (which doesn't
# even support `-Wall`...).
- name: Build & install
run: |
export PATH="/usr/local/opt/bison/bin:$PATH"
make -j CXXFLAGS="-O3 -flto -DNDEBUG -mmacosx-version-min=10.9" PKG_CONFIG="pkg-config --static" PNGLDLIBS="$(pkg-config --static --libs-only-L libpng | cut -c 3-)/libpng.a $(pkg-config --static --libs-only-l libpng | sed s/-lpng[0-9]*//g)" Q=
- name: Package binaries
run: |
mkdir bins
cp rgb{asm,link,fix,gfx} bins
- name: Upload binaries
uses: actions/upload-artifact@v3
with:
name: rgbds-canary-${{ matrix.os }}-${{ matrix.buildsys }}
path: bins
- name: Compute test dependency cache params
id: test-deps-cache-params
shell: bash
run: |
paths=$(test/fetch-test-deps.sh --get-paths)
hash=$(test/fetch-test-deps.sh --get-hash)
tee -a <<<"paths=\"${paths//,/\\n}\"" $GITHUB_OUTPUT
tee -a <<<"hash=${hash%-}" $GITHUB_OUTPUT
- name: Check test dependency repositories cache
id: test-deps-cache
uses: actions/cache@v3
with:
path: ${{ fromJSON(steps.test-deps-cache-params.outputs.paths) }}
key: ${{ matrix.os }}-${{ steps.test-deps-cache-params.outputs.hash }}
- if: steps.test-deps-cache.outputs.cache-hit != 'true'
name: Fetch test dependency repositories
continue-on-error: true
run: |
test/fetch-test-deps.sh
- name: Install test dependency dependencies
shell: bash
run: |
test/fetch-test-deps.sh --get-deps ${{ matrix.os }}
- name: Run tests
shell: bash
run: |
test/run-tests.sh
windows:
windows-testing:
strategy:
matrix:
bits: [32, 64]
os: [windows-2019, windows-2022]
include:
- bits: 32
arch: x86
@@ -149,87 +67,70 @@ jobs:
arch: x86_x64
platform: x64
fail-fast: false
runs-on: ${{ matrix.os }}
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- name: Install deps
run: .github/scripts/get_win_deps.ps1
- uses: actions/cache@v3
id: cache
with:
path: |
zbuild
pngbuild
key: ${{ matrix.arch }}-${{ hashFiles('zlib/**', 'libpng/**') }}
- uses: actions/checkout@v2
- name: Get zlib, libpng and bison
run: | # TODO: use an array
$wc = New-Object System.Net.WebClient
$wc.DownloadFile('https://www.zlib.net/zlib1212.zip', 'zlib.zip')
$hash = (Get-FileHash "zlib.zip" -Algorithm SHA256).Hash
if ($hash -ne '173e89893dcb8b4a150d7731cd72f0602f1d6b45e60e2a54efdf7f3fc3325fd7') {
Write-Host "zlib SHA256 mismatch! ($hash)"
exit 1
}
$wc.DownloadFile('https://download.sourceforge.net/libpng/lpng1637.zip', 'libpng.zip')
$hash = (Get-FileHash "libpng.zip" -Algorithm SHA256).Hash
if ($hash -ne '3b4b1cbd0bae6822f749d39b1ccadd6297f05e2b85a83dd2ce6ecd7d09eabdf2') {
Write-Host "libpng SHA256 mismatch! ($hash)"
exit 1
}
$wc.DownloadFile('https://github.com/lexxmark/winflexbison/releases/download/v2.5.24/win_flex_bison-2.5.24.zip', 'winflexbison.zip')
$hash = (Get-FileHash "winflexbison.zip" -Algorithm SHA256).Hash
if ($hash -ne '39c6086ce211d5415500acc5ed2d8939861ca1696aee48909c7f6daf5122b505') {
Write-Host "bison SHA256 mismatch! ($hash)"
}
Expand-Archive -DestinationPath . "zlib.zip"
Expand-Archive -DestinationPath . "libpng.zip"
Expand-Archive -DestinationPath install_dir "winflexbison.zip"
Move-Item zlib-1.2.12 zlib
Move-Item lpng1637 libpng
- name: Build zlib
run: | # BUILD_SHARED_LIBS causes the output DLL to be correctly called `zlib1.dll`
cmake -S zlib -B zbuild -A ${{ matrix.platform }} -Wno-dev -DCMAKE_INSTALL_PREFIX=install_dir -DBUILD_SHARED_LIBS=ON
cmake -S zlib -B zbuild -A ${{ matrix.platform }} -DCMAKE_INSTALL_PREFIX=install_dir -DBUILD_SHARED_LIBS=ON
cmake --build zbuild --config Release -j
if: steps.cache.outputs.cache-hit != 'true'
- name: Install zlib
run: |
cmake --install zbuild
- name: Build libpng
shell: bash
run: |
cmake -S libpng -B pngbuild -A ${{ matrix.platform }} -Wno-dev -DCMAKE_INSTALL_PREFIX=install_dir -DPNG_SHARED=ON -DPNG_STATIC=OFF -DPNG_TESTS=OFF -DPNG_BUILD_ZLIB=ON -DZLIB_INCLUDE_DIR="$PWD"/install_dir/include -DZLIB_LIBRARY="$PWD"/install_dir/lib/zlib.lib
cmake -S libpng -B pngbuild -A ${{ matrix.platform }} -DCMAKE_INSTALL_PREFIX=install_dir -DPNG_SHARED=ON -DPNG_STATIC=ON -DPNG_TESTS=OFF
cmake --build pngbuild --config Release -j
if: steps.cache.outputs.cache-hit != 'true'
- name: Install libpng
run: |
cmake --install pngbuild
- name: Build Windows binaries
shell: bash
run: |
cmake -S . -B build -A ${{ matrix.platform }} -DCMAKE_INSTALL_PREFIX=install_dir -DCMAKE_BUILD_TYPE=Release -DZLIB_LIBRARY="$PWD"/install_dir/lib/zlib.lib -DZLIB_INCLUDE_DIR="$PWD"/install_dir/include -DPNG_LIBRARY="$PWD"/install_dir/lib/libpng16.lib -DPNG_INCLUDE_DIR="$PWD"/install_dir/include
cmake --build build --config Release -j --verbose
cmake --install build --verbose --prefix install_dir
cmake --install build --verbose --component "Test support programs"
cmake -S . -B build -A ${{ matrix.platform }} -DCMAKE_INSTALL_PREFIX=install_dir -DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release -j
cmake --install build
- name: Package binaries
shell: bash
run: |
mkdir bins
cp install_dir/bin/{rgbasm.exe,rgblink.exe,rgbfix.exe,rgbgfx.exe,zlib1.dll,libpng16.dll} bins
- name: Upload Windows binaries
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v1
with:
name: rgbds-canary-win${{ matrix.bits }}
path: bins
- name: Compute test dependency cache params
id: test-deps-cache-params
shell: bash
run: |
paths=$(test/fetch-test-deps.sh --get-paths)
hash=$(test/fetch-test-deps.sh --get-hash)
tee -a <<<"paths=\"${paths//,/\\n}\"" $GITHUB_OUTPUT
tee -a <<<"hash=${hash%-}" $GITHUB_OUTPUT
- name: Check test dependency repositories cache
id: test-deps-cache
uses: actions/cache@v3
with:
path: ${{ fromJSON(steps.test-deps-cache-params.outputs.paths) }}
key: ${{ matrix.os }}-${{ matrix.bits }}-${{ steps.test-deps-cache-params.outputs.hash }}
- if: steps.test-deps-cache.outputs.cache-hit != 'true'
name: Fetch test dependency repositories
shell: bash
continue-on-error: true
run: |
test/fetch-test-deps.sh
- name: Install test dependency dependencies
shell: bash
run: |
test/fetch-test-deps.sh --get-deps ${{ matrix.os }}
- name: Run tests
- name: Test
shell: bash
run: |
cp bins/* .
cp bins/*.dll test/gfx
test/run-tests.sh
windows-mingw-build:
windows-xbuild:
strategy:
matrix:
bits: [32, 64]
os: [ubuntu-18.04]
include:
- bits: 32
arch: i686
@@ -238,94 +139,58 @@ jobs:
arch: x86-64
triplet: x86_64-w64-mingw32
fail-fast: false
runs-on: ubuntu-22.04
runs-on: ${{ matrix.os }}
env:
DIST_DIR: win${{ matrix.bits }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v2
- name: Install deps
shell: bash
run: |
./.github/scripts/install_deps.sh ${{ matrix.os }}
./.github/actions/install_deps.sh ${{ matrix.os }}
- name: Install MinGW
run: | # dpkg-dev is apparently required for pkg-config for cross-building
sudo apt-get install g++-mingw-w64-${{ matrix.arch }}-win32 mingw-w64-tools libz-mingw-w64-dev dpkg-dev
run: |
sudo apt-get install gcc-mingw-w64-${{ matrix.arch }} mingw-w64-tools libz-mingw-w64-dev
- name: Install libpng dev headers for MinGW
run: |
sudo ./.github/scripts/mingw-w64-libpng-dev.sh ${{ matrix.triplet }}
sudo ./.github/actions/mingw-w64-libpng-dev.sh ${{ matrix.triplet }}
- name: Cross-build Windows binaries
run: |
make mingw${{ matrix.bits }} -j Q=
- name: Package binaries
run: | # DLL dependencies can be figured out using e.g. Dependency Walker or objdump -p
run: |
mkdir bins
mv -v rgb{asm,link,fix,gfx}.exe bins/
cp -v /usr/${{ matrix.triplet }}/lib/zlib1.dll bins
cp -v /usr/${{ matrix.triplet }}/bin/libpng16-16.dll bins
cp -v /usr/lib/gcc/${{ matrix.triplet }}/10-win32/lib{ssp-0,stdc++-6}.dll bins
[ "${{ matrix.bits }}" -ne 32 ] || cp -v /usr/lib/gcc/${{ matrix.triplet }}/10-win32/libgcc_s_dw2-1.dll bins
mv rgbasm bins/rgbasm.exe
mv rgblink bins/rgblink.exe
mv rgbfix bins/rgbfix.exe
mv rgbgfx bins/rgbgfx.exe
cp /usr/${{ matrix.triplet }}/lib/zlib1.dll bins
cp /usr/${{ matrix.triplet }}/bin/libpng16-16.dll bins
if [ ${{ matrix.bits }} -eq 32 ]; then cp /usr/lib/gcc/${{ matrix.triplet }}/7.3-win32/libgcc_s_sjlj-1.dll bins; fi
- name: Upload Windows binaries
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v1
with:
name: rgbds-canary-mingw-win${{ matrix.bits }}
path: bins
- name: Upload Windows test binaries
uses: actions/upload-artifact@v3
with:
name: testing-programs-mingw-win${{ matrix.bits }}
path: |
test/gfx/randtilegen.exe
test/gfx/rgbgfx_test.exe
windows-mingw-testing:
needs: windows-mingw-build
windows-xtesting:
needs: windows-xbuild
strategy:
matrix:
os: [windows-2019, windows-2022]
bits: [32, 64]
fail-fast: false
runs-on: ${{ matrix.os }}
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v2
- name: Retrieve binaries
uses: actions/download-artifact@v3
uses: actions/download-artifact@v1
with:
name: rgbds-canary-mingw-win${{ matrix.bits }}
path: bins
- name: Retrieve test binaries
uses: actions/download-artifact@v3
with:
name: testing-programs-mingw-win${{ matrix.bits }}
path: test/gfx
- name: Extract binaries
shell: bash
run: |
cp bins/* .
cp bins/*.dll test/gfx
- name: Compute test dependency cache params
id: test-deps-cache-params
shell: bash
run: |
paths=$(test/fetch-test-deps.sh --get-paths)
hash=$(test/fetch-test-deps.sh --get-hash)
tee -a <<<"paths=\"${paths//,/\\n}\"" $GITHUB_OUTPUT
tee -a <<<"hash=${hash%-}" $GITHUB_OUTPUT
- name: Check test dependency repositories cache
id: test-deps-cache
uses: actions/cache@v3
with:
path: ${{ fromJSON(steps.test-deps-cache-params.outputs.paths) }}
key: mingw-${{ matrix.bits }}-${{ steps.test-deps-cache-params.outputs.hash }}
- if: steps.test-deps-cache.outputs.cache-hit != 'true'
name: Fetch test dependency repositories
shell: bash
continue-on-error: true
run: |
test/fetch-test-deps.sh
- name: Install test dependency dependencies
shell: bash
run: |
test/fetch-test-deps.sh --get-deps ${{ matrix.os }}
- name: Run tests
shell: bash
run: |

View File

@@ -4,41 +4,48 @@ on:
branches:
- master
paths:
- man/gbz80.7
- man/rgbds.5
- man/rgbds.7
- man/rgbasm.1
- man/rgbasm.5
- man/rgblink.1
- man/rgblink.5
- man/rgbfix.1
- man/rgbgfx.1
- .github/actions/get-pages.sh
- src/gbz80.7
- src/rgbds.5
- src/rgbds.7
- src/asm/rgbasm.1
- src/asm/rgbasm.5
- src/link/rgblink.1
- src/link/rgblink.5
- src/fix/rgbfix.1
- src/gfx/rgbgfx.1
jobs:
build:
if: github.repository_owner == 'gbdev'
runs-on: ubuntu-22.04
runs-on: ubuntu-18.04
steps:
- name: Checkout rgbds@master
uses: actions/checkout@v3
uses: actions/checkout@v2
with:
repository: gbdev/rgbds
ref: master
path: rgbds
- name: Checkout rgbds-www@master
uses: actions/checkout@v3
uses: actions/checkout@v2
with:
repository: gbdev/rgbds-www
ref: master
path: rgbds-www
- name: Install groff and mandoc
- name: Build and install mandoc + install groff
run: |
sudo apt-get -qq update
sudo apt-get install -yq groff mandoc
sudo apt-get install -yq groff zlib1g-dev
wget 'http://mandoc.bsd.lv/snapshots/mandoc-1.14.5.tar.gz'
tar xf mandoc-1.14.5.tar.gz
cd mandoc-1.14.5
./configure
make
sudo make install
- name: Update pages
working-directory: rgbds/man
working-directory: rgbds
run: |
../../rgbds-www/maintainer/man_to_html.sh master *
./.github/actions/get-pages.sh ../rgbds-www master
- name: Push new pages
working-directory: rgbds-www
run: |
@@ -49,7 +56,7 @@ jobs:
ssh-add ~/.ssh/id_ed25519
git config --global user.name "GitHub Action"
git config --global user.email "community@gbdev.io"
git add -A
git add .
git commit -m "Update RGBDS master documentation"
if git remote | grep -q origin; then
git remote set-url origin git@github.com:gbdev/rgbds-www.git

5
.gitignore vendored
View File

@@ -3,13 +3,10 @@
/rgbfix
/rgbgfx
/rgbshim.sh
/coverage/
*.o
*.exe
*.dll
*.gcno
*.gcda
*.gcov
.checkpatch-camelcase.*
CMakeCache.txt
CMakeFiles/
cmake_install.cmake

View File

@@ -1,10 +1,16 @@
#
# This file is part of RGBDS.
#
# Copyright (c) 2020 RGBDS contributors.
#
# SPDX-License-Identifier: MIT
#
# 3.9 required for LTO checks
cmake_minimum_required(VERSION 3.9 FATAL_ERROR)
project(rgbds
LANGUAGES CXX)
LANGUAGES C)
# get real path of source and binary directories
get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH)
@@ -23,22 +29,11 @@ option(MORE_WARNINGS "Turn on more warnings" OFF) # Ignored on MSVC
if(MSVC)
# MSVC's standard library triggers warning C5105,
# "macro expansion producing 'defined' has undefined behavior"
# We also opt into the C++20-conformant preprocessor.
add_compile_options(/MP /wd5105 /Zc:preprocessor)
add_compile_options(/std:c11 /W1 /MP /wd5105)
add_definitions(/D_CRT_SECURE_NO_WARNINGS)
if(SANITIZERS)
set(SAN_FLAGS /fsanitize=address)
add_compile_options(${SAN_FLAGS})
add_link_options(${SAN_FLAGS})
endif()
else()
# TODO: use -pedantic after non-C++ idioms are gone
add_compile_options(-Wall)
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
add_compile_options(-Wno-c99-designator)
endif()
add_definitions(-D_POSIX_C_SOURCE=200809L)
add_compile_options(-Wall -pedantic)
add_definitions(-D_POSIX_C_SOURCE=200809L -D_ISOC11_SOURCE)
if(SANITIZERS)
set(SAN_FLAGS -fsanitize=shift -fsanitize=integer-divide-by-zero
-fsanitize=unreachable -fsanitize=vla-bound
@@ -46,18 +41,18 @@ else()
-fsanitize=object-size -fsanitize=bool -fsanitize=enum
-fsanitize=alignment -fsanitize=null -fsanitize=address)
add_compile_options(${SAN_FLAGS})
add_link_options(${SAN_FLAGS})
add_definitions(-D_GLIBCXX_ASSERTIONS)
link_libraries(${SAN_FLAGS})
# A non-zero optimization level is desired in debug mode, but allow overriding it nonetheless
# TODO: this overrides anything previously set... that's a bit sloppy!
set(CMAKE_CXX_FLAGS_DEBUG "-g -Og -fno-omit-frame-pointer -fno-optimize-sibling-calls" CACHE STRING "" FORCE)
set(CMAKE_C_FLAGS_DEBUG "-g -Og -fno-omit-frame-pointer -fno-optimize-sibling-calls" CACHE STRING "" FORCE)
endif()
if(MORE_WARNINGS)
add_compile_options(-Werror -Wextra
-Walloc-zero -Wcast-align -Wcast-qual -Wduplicated-branches -Wduplicated-cond
-Wfloat-equal -Wlogical-op -Wnull-dereference -Wshift-overflow=2
-Wstringop-overflow=4 -Wstrict-overflow=5 -Wundef -Wuninitialized -Wunused
-Wfloat-equal -Winline -Wlogical-op -Wnested-externs -Wnull-dereference
-Wold-style-definition -Wshift-overflow=2 -Wstrict-overflow=5
-Wstrict-prototypes -Wstringop-overflow=4 -Wundef -Wuninitialized -Wunused
-Wshadow # TODO: -Wshadow=compatible-local ?
-Wformat=2 -Wformat-overflow=2 -Wformat-truncation=1
-Wno-format-nonliteral # We have a couple of "dynamic" prints
@@ -82,21 +77,12 @@ else(GIT)
message(STATUS "Cannot determine RGBDS version (Git not installed), falling back")
endif(GIT)
find_package(PkgConfig)
if(MSVC OR NOT PKG_CONFIG_FOUND)
# fallback to find_package
find_package(PNG REQUIRED)
else()
pkg_check_modules(LIBPNG REQUIRED libpng)
endif()
include_directories("${PROJECT_SOURCE_DIR}/include")
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED True)
add_subdirectory(src)
add_subdirectory(test)
# By default, build in Release mode; Debug mode must be explicitly requested
# (You may want to augment it with the options above)
@@ -111,19 +97,3 @@ if(CMAKE_BUILD_TYPE STREQUAL "Release")
message(CHECK_FAIL "no")
endif()
endif()
set(MANDIR "share/man")
set(man1 "man/rgbasm.1"
"man/rgbfix.1"
"man/rgbgfx.1"
"man/rgblink.1")
set(man5 "man/rgbasm.5"
"man/rgblink.5"
"man/rgbds.5")
set(man7 "man/gbz80.7"
"man/rgbds.7")
foreach(SECTION "man1" "man5" "man7")
set(DEST "${MANDIR}/${SECTION}")
install(FILES ${${SECTION}} DESTINATION ${DEST})
endforeach()

View File

@@ -12,14 +12,14 @@ Bug reports are essential to improve RGBDS and they are always welcome. If you
want to report a bug:
1. Make sure that there isn't a similar issue already reported
`here <https://github.com/gbdev/rgbds/issues>`__.
`here <https://github.com/rednex/rgbds/issues>`__.
2. Figure out a way of reproducing it reliably.
3. If there is a piece of code that triggers the bug, try to reduce it to the
smallest file you can.
4. Create a new `issue <https://github.com/gbdev/rgbds/issues>`__.
4. Create a new `issue <https://github.com/rednex/rgbds/issues>`__.
Of course, it may not always be possible to give an accurate bug report, but it
always helps to fix it.
@@ -30,7 +30,7 @@ Requesting new features
If you come up with a good idea that could be implemented, you can propose it to
be done.
1. Create a new `issue <https://github.com/gbdev/rgbds/issues>`__.
1. Create a new `issue <https://github.com/rednex/rgbds/issues>`__.
2. Try to be as accurate as possible. Describe what you need and why you need
it, maybe with examples.
@@ -49,7 +49,7 @@ if your change is going to be small (and likely to be accepted as-is) or big
(and will have to go through some rework).
Big changes will most likely require some discussion, so open an
`issue <https://github.com/gbdev/rgbds/issues>`__ and explain what you want to
`issue <https://github.com/rednex/rgbds/issues>`__ and explain what you want to
do and how you intend to do it. If you already have a prototype, it's always a
good idea to show it. Tests help, too.
@@ -74,10 +74,22 @@ copyright and the reference to the MIT License.
new warning (but it may be possible to remove some warning checks if it makes
the code much easier).
5. Format your changes according to ``clang-format``, which will reformat the
coding style according to our standards defined in ``.clang-format``.
5. Follow the Linux kernel coding style, which can be found in the file
``Documentation/process/coding-style.rst`` in the Linux kernel repository.
Note that the coding style isn't written in stone, if there is a good reason
to deviate from it, it should be fine.
6. Create a pull request against the branch ``master``.
6. Download the files ``checkpatch.pl``, ``const_structs.checkpatch`` and
``spelling.txt`` from the folder ``scripts`` in the Linux kernel repository.
7. Be prepared to get some comments about your code and to modify it. Tip: Use
7. To use ``checkpatch.pl`` you can use ``make checkpatch``, which will check
the coding style of all patches between the current one and the upstream
code. By default, the Makefile expects the script (and associate files) to be
located in ``../linux/scripts/``, but you can place them anywhere you like as
long as you specify it when executing the command:
``make checkpatch CHECKPATCH=../path/to/folder``.
8. Create a pull request against the branch ``master``.
9. Be prepared to get some comments about your code and to modify it. Tip: Use
``git rebase -i origin/master`` to modify chains of commits.

View File

@@ -21,7 +21,7 @@ Main contributors
- Eldred "ISSOtm" Habert <eldredhabert0@gmail.com>
- Sylvie "Rangi" Oukaour <http://github.com/Rangi42>
- Rangi <http://github.com/Rangi42>
Other contributors
------------------

View File

@@ -1,14 +1,24 @@
FROM debian:11-slim
LABEL org.opencontainers.image.source=https://github.com/gbdev/rgbds
ARG version=0.7.0
# This file is part of RGBDS.
#
# Copyright (c) 2018-2019, Phil Smith and RGBDS contributors.
#
# SPDX-License-Identifier: MIT
# docker build -t rgbds:vX.X.X-alpine
FROM alpine:latest
RUN apk add --update \
build-base \
bison \
libpng-dev
COPY . /rgbds
WORKDIR /rgbds
RUN make Q='' all
COPY . .
RUN apt-get update && \
apt-get install sudo make cmake gcc build-essential -y
RUN ./.github/scripts/install_deps.sh ubuntu-20.04
RUN make -j CXXFLAGS="-O3 -flto -DNDEBUG -static" PKG_CONFIG="pkg-config --static" Q=
RUN tar caf rgbds-${version}-linux-x86_64.tar.xz --transform='s#.*/##' rgbasm rgblink rgbfix rgbgfx man/* .github/scripts/install.sh
FROM alpine:latest
RUN apk add --update \
libpng
COPY --from=0 \
/rgbds/rgbasm \
/rgbds/rgbfix \
/rgbds/rgblink \
/rgbds/rgbgfx \
/bin/

View File

@@ -1,6 +1,6 @@
The MIT License
Copyright (c) 1997-2023, Carsten Sørensen and RGBDS contributors.
Copyright (c) 1997-2020, Carsten Sorensen and RGBDS contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to

199
Makefile
View File

@@ -1,9 +1,13 @@
#
# This file is part of RGBDS.
#
# Copyright (c) 1997-2018, Carsten Sorensen and RGBDS contributors.
#
# SPDX-License-Identifier: MIT
#
.SUFFIXES:
.SUFFIXES: .cpp .y .o
.PHONY: all clean install checkdiff develop debug coverage mingw32 mingw64 wine-shim dist
.SUFFIXES: .h .y .c .o
# User-defined variables
@@ -14,6 +18,7 @@ mandir := ${PREFIX}/share/man
STRIP := -s
BINMODE := 755
MANMODE := 644
CHECKPATCH := ../linux/scripts/checkpatch.pl
# Other variables
@@ -22,26 +27,26 @@ PNGCFLAGS := `${PKG_CONFIG} --cflags libpng`
PNGLDFLAGS := `${PKG_CONFIG} --libs-only-L libpng`
PNGLDLIBS := `${PKG_CONFIG} --libs-only-l libpng`
# Note: if this comes up empty, `version.cpp` will automatically fall back to last release number
# Note: if this comes up empty, `version.c` will automatically fall back to last release number
VERSION_STRING := `git describe --tags --dirty --always 2>/dev/null`
# TODO: use -pedantic after non-C++ idioms are gone
WARNFLAGS := -Wall -Wno-unknown-warning-option -Wno-c99-designator
WARNFLAGS := -Wall -pedantic
# Overridable CXXFLAGS
CXXFLAGS ?= -O3 -flto -DNDEBUG
# Non-overridable CXXFLAGS
REALCXXFLAGS := ${CXXFLAGS} ${WARNFLAGS} -std=c++2a -I include \
-D_POSIX_C_SOURCE=200809L -fno-exceptions -fno-rtti
# Overridable CFLAGS
CFLAGS ?= -O3 -flto -DNDEBUG
# Non-overridable CFLAGS
# _ISOC11_SOURCE is required on certain platforms to get C11 on top of the C99-based POSIX 2008
REALCFLAGS := ${CFLAGS} ${WARNFLAGS} -std=gnu11 -I include \
-D_POSIX_C_SOURCE=200809L -D_ISOC11_SOURCE
# Overridable LDFLAGS
LDFLAGS ?=
# Non-overridable LDFLAGS
REALLDFLAGS := ${LDFLAGS} ${WARNFLAGS} \
-DBUILD_VERSION_STRING=\"${VERSION_STRING}\"
# Wrapper around bison that passes flags depending on what the version supports
BISON := src/bison.sh
YFLAGS ?= -Wall
BISON := bison
RM := rm -rf
# Used for checking pull requests
@@ -65,16 +70,16 @@ rgbasm_obj := \
src/asm/rpn.o \
src/asm/section.o \
src/asm/symbol.o \
src/asm/util.o \
src/asm/warning.o \
src/extern/getopt.o \
src/extern/utf8decoder.o \
src/error.o \
src/hashmap.o \
src/linkdefs.o \
src/opmath.o \
src/util.o
src/opmath.o
src/asm/lexer.o src/asm/main.o: src/asm/parser.hpp
src/asm/lexer.o src/asm/main.o: src/asm/parser.h
rgblink_obj := \
src/link/assign.o \
@@ -83,18 +88,13 @@ rgblink_obj := \
src/link/output.o \
src/link/patch.o \
src/link/script.o \
src/link/sdas_obj.o \
src/link/section.o \
src/link/symbol.o \
src/extern/getopt.o \
src/extern/utf8decoder.o \
src/error.o \
src/hashmap.o \
src/linkdefs.o \
src/opmath.o \
src/util.o
src/link/main.o: src/link/script.hpp
src/opmath.o
rgbfix_obj := \
src/fix/main.o \
@@ -102,69 +102,50 @@ rgbfix_obj := \
src/error.o
rgbgfx_obj := \
src/gfx/gb.o \
src/gfx/main.o \
src/gfx/pal_packing.o \
src/gfx/pal_sorting.o \
src/gfx/pal_spec.o \
src/gfx/process.o \
src/gfx/proto_palette.o \
src/gfx/reverse.o \
src/gfx/rgba.o \
src/gfx/makepng.o \
src/extern/getopt.o \
src/error.o
rgbasm: ${rgbasm_obj}
$Q${CXX} ${REALLDFLAGS} -o $@ ${rgbasm_obj} ${REALCXXFLAGS} src/version.cpp -lm
$Q${CC} ${REALLDFLAGS} -o $@ ${rgbasm_obj} ${REALCFLAGS} src/version.c -lm
rgblink: ${rgblink_obj}
$Q${CXX} ${REALLDFLAGS} -o $@ ${rgblink_obj} ${REALCXXFLAGS} src/version.cpp
$Q${CC} ${REALLDFLAGS} -o $@ ${rgblink_obj} ${REALCFLAGS} src/version.c
rgbfix: ${rgbfix_obj}
$Q${CXX} ${REALLDFLAGS} -o $@ ${rgbfix_obj} ${REALCXXFLAGS} src/version.cpp
$Q${CC} ${REALLDFLAGS} -o $@ ${rgbfix_obj} ${REALCFLAGS} src/version.c
rgbgfx: ${rgbgfx_obj}
$Q${CXX} ${REALLDFLAGS} ${PNGLDFLAGS} -o $@ ${rgbgfx_obj} ${REALCXXFLAGS} ${PNGLDLIBS} src/version.cpp
test/gfx/randtilegen: test/gfx/randtilegen.cpp
$Q${CXX} ${REALLDFLAGS} ${PNGLDFLAGS} -o $@ $^ ${REALCXXFLAGS} ${PNGCFLAGS} ${PNGLDLIBS}
test/gfx/rgbgfx_test: test/gfx/rgbgfx_test.cpp
$Q${CXX} ${REALLDFLAGS} ${PNGLDFLAGS} -o $@ $^ ${REALCXXFLAGS} ${PNGLDLIBS}
$Q${CC} ${REALLDFLAGS} ${PNGLDFLAGS} -o $@ ${rgbgfx_obj} ${REALCFLAGS} src/version.c ${PNGLDLIBS}
# Rules to process files
# We want the Bison invocation to pass through our rules, not default ones
.y.o:
.y.cpp:
$Q${BISON} $@ $<
# Bison-generated C++ files have an accompanying header
src/asm/parser.hpp: src/asm/parser.cpp
$Qtouch $@
src/link/script.hpp: src/link/script.cpp
# Bison-generated C files have an accompanying header
src/asm/parser.h: src/asm/parser.c
$Qtouch $@
# Only RGBGFX uses libpng (POSIX make doesn't support pattern rules to cover all these)
src/gfx/main.o: src/gfx/main.cpp
$Q${CXX} ${REALCXXFLAGS} ${PNGCFLAGS} -c -o $@ $<
src/gfx/pal_packing.o: src/gfx/pal_packing.cpp
$Q${CXX} ${REALCXXFLAGS} ${PNGCFLAGS} -c -o $@ $<
src/gfx/pal_sorting.o: src/gfx/pal_sorting.cpp
$Q${CXX} ${REALCXXFLAGS} ${PNGCFLAGS} -c -o $@ $<
src/gfx/pal_spec.o: src/gfx/pal_spec.cpp
$Q${CXX} ${REALCXXFLAGS} ${PNGCFLAGS} -c -o $@ $<
src/gfx/process.o: src/gfx/process.cpp
$Q${CXX} ${REALCXXFLAGS} ${PNGCFLAGS} -c -o $@ $<
src/gfx/proto_palette.o: src/gfx/proto_palette.cpp
$Q${CXX} ${REALCXXFLAGS} ${PNGCFLAGS} -c -o $@ $<
src/gfx/reverse.o: src/gfx/reverse.cpp
$Q${CXX} ${REALCXXFLAGS} ${PNGCFLAGS} -c -o $@ $<
src/gfx/rgba.o: src/gfx/rgba.cpp
$Q${CXX} ${REALCXXFLAGS} ${PNGCFLAGS} -c -o $@ $<
src/asm/parser.c: src/asm/parser.y
$QDEFS=; \
add_flag(){ \
if src/check_bison_ver.sh $$1 $$2; then \
DEFS="-D$$3 $$DEFS"; \
fi \
}; \
add_flag 3 5 api.token.raw=true; \
add_flag 3 6 parse.error=detailed; \
add_flag 3 0 parse.error=verbose; \
add_flag 3 0 parse.lac=full; \
add_flag 3 0 lr.type=ielr; \
echo "DEFS=$$DEFS"; \
${BISON} $$DEFS -d ${YFLAGS} -o $@ $<
.cpp.o:
$Q${CXX} ${REALCXXFLAGS} -c -o $@ $<
.c.o:
$Q${CC} ${REALCFLAGS} ${PNGCFLAGS} -c -o $@ $<
# Target used to remove all files generated by other Makefile targets
@@ -174,20 +155,51 @@ clean:
$Q${RM} rgbfix rgbfix.exe
$Q${RM} rgbgfx rgbgfx.exe
$Qfind src/ -name "*.o" -exec rm {} \;
$Qfind . -type f \( -name "*.gcno" -o -name "*.gcda" -o -name "*.gcov" \) -exec rm {} \;
$Q${RM} rgbshim.sh
$Q${RM} src/asm/parser.cpp src/asm/parser.hpp
$Q${RM} src/link/script.cpp src/link/script.hpp src/link/stack.hh
$Q${RM} test/gfx/randtilegen test/gfx/rgbgfx_test
$Q${RM} src/asm/parser.c src/asm/parser.h
# Target used to install the binaries and man pages.
install: all
$Qinstall -d ${DESTDIR}${bindir}/ ${DESTDIR}${mandir}/man1/ ${DESTDIR}${mandir}/man5/ ${DESTDIR}${mandir}/man7/
$Qinstall ${STRIP} -m ${BINMODE} rgbasm rgblink rgbfix rgbgfx ${DESTDIR}${bindir}/
$Qinstall -m ${MANMODE} man/rgbasm.1 man/rgblink.1 man/rgbfix.1 man/rgbgfx.1 ${DESTDIR}${mandir}/man1/
$Qinstall -m ${MANMODE} man/rgbds.5 man/rgbasm.5 man/rgblink.5 ${DESTDIR}${mandir}/man5/
$Qinstall -m ${MANMODE} man/rgbds.7 man/gbz80.7 ${DESTDIR}${mandir}/man7/
$Qmkdir -p ${DESTDIR}${bindir}
$Qinstall ${STRIP} -m ${BINMODE} rgbasm ${DESTDIR}${bindir}/rgbasm
$Qinstall ${STRIP} -m ${BINMODE} rgbfix ${DESTDIR}${bindir}/rgbfix
$Qinstall ${STRIP} -m ${BINMODE} rgblink ${DESTDIR}${bindir}/rgblink
$Qinstall ${STRIP} -m ${BINMODE} rgbgfx ${DESTDIR}${bindir}/rgbgfx
$Qmkdir -p ${DESTDIR}${mandir}/man1 ${DESTDIR}${mandir}/man5 ${DESTDIR}${mandir}/man7
$Qinstall -m ${MANMODE} src/rgbds.7 ${DESTDIR}${mandir}/man7/rgbds.7
$Qinstall -m ${MANMODE} src/gbz80.7 ${DESTDIR}${mandir}/man7/gbz80.7
$Qinstall -m ${MANMODE} src/rgbds.5 ${DESTDIR}${mandir}/man5/rgbds.5
$Qinstall -m ${MANMODE} src/asm/rgbasm.1 ${DESTDIR}${mandir}/man1/rgbasm.1
$Qinstall -m ${MANMODE} src/asm/rgbasm.5 ${DESTDIR}${mandir}/man5/rgbasm.5
$Qinstall -m ${MANMODE} src/fix/rgbfix.1 ${DESTDIR}${mandir}/man1/rgbfix.1
$Qinstall -m ${MANMODE} src/link/rgblink.1 ${DESTDIR}${mandir}/man1/rgblink.1
$Qinstall -m ${MANMODE} src/link/rgblink.5 ${DESTDIR}${mandir}/man5/rgblink.5
$Qinstall -m ${MANMODE} src/gfx/rgbgfx.1 ${DESTDIR}${mandir}/man1/rgbgfx.1
# Target used to check the coding style of the whole codebase.
# `extern/` is excluded, as it contains external code that should not be patched
# to meet our coding style, so applying upstream patches is easier.
# `.y` files aren't checked, unfortunately...
checkcodebase:
$Qfor file in `git ls-files | grep -E '(\.c|\.h)$$' | grep -Ev '(src|include)/extern/'`; do \
${CHECKPATCH} -f "$$file"; \
done
# Target used to check the coding style of the patches from the upstream branch
# to the HEAD. Runs checkpatch once for each commit between the current HEAD and
# the first common commit between the HEAD and origin/master.
# `.y` files aren't checked, unfortunately...
checkpatch:
$QCOMMON_COMMIT=`git merge-base HEAD ${BASE_REF}`; \
for commit in `git rev-list $$COMMON_COMMIT..HEAD`; do \
echo "[*] Analyzing commit '$$commit'"; \
git format-patch --stdout "$$commit~..$$commit" \
-- src include '!src/extern' '!include/extern' \
| ${CHECKPATCH} - || true; \
done
# Target used to check for suspiciously missing changed files.
@@ -200,34 +212,24 @@ checkdiff:
# The rationale for some of the flags is documented in the CMakeLists.
develop:
$Q${MAKE} WARNFLAGS="${WARNFLAGS} -Werror -Wextra \
$Qenv ${MAKE} WARNFLAGS="-Werror -Wextra \
-Walloc-zero -Wcast-align -Wcast-qual -Wduplicated-branches -Wduplicated-cond \
-Wfloat-equal -Wlogical-op -Wnull-dereference -Wshift-overflow=2 \
-Wstringop-overflow=4 -Wstrict-overflow=5 -Wundef -Wuninitialized -Wunused \
-Wfloat-equal -Winline -Wlogical-op -Wnested-externs -Wold-style-definition \
-Wshift-overflow=2 \
-Wstrict-overflow=5 -Wstrict-prototypes -Wundef -Wuninitialized -Wunused \
-Wshadow \
-Wnull-dereference -Wstringop-overflow=4 \
-Wformat=2 -Wformat-overflow=2 -Wformat-truncation=1 \
-Wno-format-nonliteral -Wno-strict-overflow \
-Wno-format-nonliteral \
-Wno-type-limits -Wno-tautological-constant-out-of-range-compare \
-Wvla \
-D_GLIBCXX_ASSERTIONS \
-Wno-unknown-warning-option \
-fsanitize=shift -fsanitize=integer-divide-by-zero \
-fsanitize=unreachable -fsanitize=vla-bound \
-fsanitize=signed-integer-overflow -fsanitize=bounds \
-fsanitize=object-size -fsanitize=bool -fsanitize=enum \
-fsanitize=alignment -fsanitize=null -fsanitize=address" \
CXXFLAGS="-ggdb3 -Og -fno-omit-frame-pointer -fno-optimize-sibling-calls"
# This target is used during development in order to more easily debug with gdb.
debug:
$Qenv ${MAKE} \
CXXFLAGS="-ggdb3 -Og -fno-omit-frame-pointer -fno-optimize-sibling-calls"
# This target is used during development in order to inspect code coverage with gcov.
coverage:
$Qenv ${MAKE} \
CXXFLAGS="-ggdb3 -Og --coverage -fno-omit-frame-pointer -fno-optimize-sibling-calls"
CFLAGS="-ggdb3 -Og -fno-omit-frame-pointer -fno-optimize-sibling-calls"
# Targets for the project maintainer to easily create Windows exes.
# This is not for Windows users!
@@ -235,18 +237,15 @@ coverage:
# install instructions instead.
mingw32:
$Q${MAKE} all test/gfx/randtilegen test/gfx/rgbgfx_test \
CXX=i686-w64-mingw32-g++ \
CXXFLAGS="-O3 -flto -DNDEBUG -static-libgcc" \
PKG_CONFIG="PKG_CONFIG_SYSROOT_DIR=/usr/i686-w64-mingw32 pkg-config"
$Q${MAKE} CC=i686-w64-mingw32-gcc BISON=bison \
PKG_CONFIG=i686-w64-mingw32-pkg-config -j
mingw64:
$Q${MAKE} all test/gfx/randtilegen test/gfx/rgbgfx_test \
CXX=x86_64-w64-mingw32-g++ \
PKG_CONFIG="PKG_CONFIG_SYSROOT_DIR=/usr/x86_64-w64-mingw32 pkg-config"
$Q${MAKE} CC=x86_64-w64-mingw32-gcc BISON=bison \
PKG_CONFIG=x86_64-w64-mingw32-pkg-config -j
wine-shim:
$Qecho '#!/usr/bin/env bash' > rgbshim.sh
$Qecho '#!/bin/bash' > rgbshim.sh
$Qecho 'WINEDEBUG=-all wine $$0.exe "$${@:1}"' >> rgbshim.sh
$Qchmod +x rgbshim.sh
$Qln -s rgbshim.sh rgbasm

View File

@@ -12,16 +12,13 @@ for the Game Boy and Game Boy Color. It consists of:
This is a fork of the original RGBDS which aims to make the programs more like
other UNIX tools.
This toolchain is maintained `on GitHub <https://github.com/gbdev/rgbds>`__.
This toolchain is maintained on `GitHub <https://github.com/rednex/rgbds>`__.
The documentation of this toolchain can be viewed online `here <https://rgbds.gbdev.io/docs/>`__.
It is generated from the man pages found in this repository.
The source code of the website itself is on GitHub as well under the repo
`rgbds-www <https://github.com/gbdev/rgbds-www>`__.
The documentation of this toolchain can be viewed online
`here <https://rgbds.gbdev.io/docs/>`__, it is generated from the man pages
found in this repository.
If you want to contribute or maintain RGBDS, and have questions regarding the code, its
organisation, etc. you can find the maintainers `on the gbdev community channels <https://gbdev.io/chat>`__
or via mail at ``rgbds at gbdev dot io``.
If you want to contribute or maintain RGBDS, and have questions regarding the code, its organisation, etc. you can find me `on GBDev <https://gbdev.io/chat>`__ or via mail at ``rgbds at eldred dot fr``.
1. Installing RGBDS
-------------------
@@ -44,13 +41,13 @@ is possible using ``make`` or ``cmake``; follow the link for more detailed instr
2. RGBDS Folder Organization
----------------------------
The RGBDS source code file structure is as follows:
The RGBDS source code file structure somewhat resembles the following:
::
.
├── .github/
│ ├── scripts/
│ ├── actions/
│ │ └── ...
│ └── workflows/
│ └── ...
@@ -60,8 +57,6 @@ The RGBDS source code file structure is as follows:
│ └── ...
├── include/
│ └── ...
├── man/
│ └── ...
├── src/
│ ├── asm/
│ │ └── ...
@@ -80,7 +75,6 @@ The RGBDS source code file structure is as follows:
│ └── run-tests.sh
├── .clang-format
├── CMakeLists.txt
├── Dockerfile
├── Makefile
└── README.rst
@@ -90,82 +84,45 @@ The RGBDS source code file structure is as follows:
- ``.github/`` - files and scripts related to the integration of the RGBDS codebase with
GitHub.
* ``scripts/`` - scripts used by workflow files.
* ``actions/`` - scripts used by workflow files.
* ``workflows/`` - CI workflow description files.
- ``contrib/`` - scripts and other resources which may be useful to users and developers of
RGBDS.
* ``zsh_compl`` contains tab completion scripts for use with zsh. Put them somewhere in
your ``fpath``, and they should auto-load.
* ``zsh_compl`` contains tab completion scripts for use with zsh. Put them somewhere in your ``fpath``, and they should auto-load.
* ``bash_compl`` contains tab completion scripts for use with bash. Run them with ``source``
somewhere in your ``.bashrc``, and they should load every time you open a shell.
* ``bash_compl`` contains tab completion scripts for use with bash. Run them with ``source`` somewhere in your ``.bashrc``, and they should load every time you open a shell.
- ``include/`` - header files for the respective source files in `src`.
- ``include/`` - header files for each respective C files in `src`.
- ``man/`` - manual pages.
- ``src/`` - source code of RGBDS.
- ``src/`` - source code and manual pages for RGBDS.
* Note that the code unique to each RGBDS tool is stored in its respective subdirectory
(rgbasm -> ``src/asm/``, for example). ``src/extern/`` contains code imported from
external sources.
(rgbasm -> ``src/asm/``, for example). ``src/extern/`` contains code imported from external sources.
- ``test/`` - testing framework used to verify that changes to the code don't break or
modify the behavior of RGBDS.
- ``test/`` - testing framework used to verify that changes to the code don't break or modify the behavior of RGBDS.
- ``.clang-format`` - code style for automated C++ formatting with |clang-format|_.
- ``Dockerfile`` - defines how to build RGBDS with Docker.
- ``.clang-format`` - code style for automated formatting with |clang-format|_. The C code does not currently follow this style, but all C++ code should.
3. History
----------
- 1996-10-01: Carsten Sørensen (a.k.a. SurfSmurf) releases
`xAsm <http://otakunozoku.com/RGBDSdocs/asm.htm>`__,
`xLink <http://otakunozoku.com/RGBDSdocs/link.htm>`__, and
`RGBFix <http://otakunozoku.com/RGBDSdocs/fix.htm>`__,
a Game Boy SM83 (GBZ80) assembler/linker system for DOS/Win32.
- Around 1997, Carsten Sørensen (AKA SurfSmurf) writes ASMotor as a
general-purpose assembler/linker system for DOS/Win32
- 1997-07-03: Sørensen releases `ASMotor <http://otakunozoku.com/RGBDSdocs/geninfo.htm>`__,
packaging the three programs together and moving towards making them a
general-purpose target-independent system.
- Around 1999, Justin Lloyd (AKA Otaku no Zoku) adapts ASMotor to read and
produce GBZ80 assembly/machine code, and releases this version as RGBDS.
- 1999-08-01: Justin Lloyd (a.k.a. Otaku no Zoku) adapts ASMotor to re-focus
on SM83 assembly/machine code, and releases this version as
`RGBDS <http://otakunozoku.com/rednex-gameboy-development-system/>`__.
- 2009, Vegard Nossum adapts the code to be more UNIX-like and releases
this version as rgbds-linux on
`GitHub <https://github.com/vegard/rgbds-linux>`__.
- 2009-06-11: Vegard Nossum adapts the code to be more UNIX-like and releases
this version as `rgbds-linux <https://github.com/vegard/rgbds-linux>`__.
- 2010, Anthony J. Bentley forks that repository. The fork becomes the reference
implementation of rgbds.
- 2010-01-12: Anthony J. Bentley `forks <https://github.com/bentley>`__ Nossum's
repository. The fork becomes the reference implementation of RGBDS.
- 2017, Bentley's repository is moved to a neutral name.
- 2015-01-18: stag019 begins implementing `rgbgfx <https://github.com/stag019/rgbgfx>`__,
a PNGtoGame Boy graphics converter, for eventual integration into RGBDS.
- 2018, codebase relicensed under the MIT license.
- 2016-09-05: rgbgfx is `integrated <https://github.com/gbdev/rgbds/commit/c3c31138ddbd8680d4e67957e387f2816798a71b>`__
into Bentley's repository.
- 2017-02-23: Bentley's repository is moved to the `rednex <https://github.com/rednex>`__
organization.
- 2018-01-26: The codebase is `relicensed <https://github.com/gbdev/rgbds/issues/128>`__
under the MIT license.
- 2020-09-15: The repository is `moved <https://github.com/gbdev/rgbds/issues/567>`__
to the `gbdev <https://github.com/gbdev>`__ organization.
- 2022-05-17: The `rgbds.gbdev.io <https://rgbds.gbdev.io>`__ website for RGBDS
documentation and downloads is published.
4. Acknowledgements
-------------------
RGBGFX generates palettes using algorithms found in the paper
`"Algorithms for the Pagination Problem, a Bin Packing with Overlapping Items" <http://arxiv.org/abs/1605.00558>`__
(`GitHub <https://github.com/pagination-problem/pagination>`__, MIT license),
by Aristide Grange, Imed Kacem, and Sébastien Martin.
RGBGFX's color palette was taken from `SameBoy <https://sameboy.github.io>`__, with permission and help by `LIJI <https://github.com/LIJI32>`__.
- 2020, repository is moved to the `gbdev <https://github.com/gbdev>`__ organisation. The `rgbds.gbdev.io <https://rgbds.gbdev.io>`__ website serving documentation and downloads is created.

View File

@@ -4,17 +4,16 @@ Releasing
This describes for the maintainers of RGBDS how to publish a new release on
GitHub.
1. Update, commit, and push `include/version.hpp <include/version.hpp>`__ with
1. Update, commit, and push `include/version.h <include/version.h>`__ with
values for ``PACKAGE_VERSION_MAJOR``, ``PACKAGE_VERSION_MINOR``,
``PACKAGE_VERSION_PATCH``, and ``PACKAGE_VERSION_RC``, as well as
`Dockerfile <Dockerfile>`__ with a value for ``ARG version``. Only define
``PACKAGE_VERSION_PATCH``, and ``PACKAGE_VERSION_RC``. Only define
``PACKAGE_VERSION_RC`` if you are publishing a release candidate! You can
use ``git commit -m "Release <version>"`` and ``git push origin master``.
2. Create a Git tag formatted as ``v<MAJOR>.<MINOR>.<PATCH>``, or
``v<MAJOR>.<MINOR>.<PATCH>-rc<RC>`` for a release candidate. ``MAJOR``,
``MINOR``, ``PATCH``, and ``RC`` should match their values from
`include/version.hpp <include/version.hpp>`__. You can use ``git tag <tag>``.
`include/version.h <include/version.h>`__. You can use ``git tag <tag>``.
3. Push the tag to GitHub. You can use ``git push origin <tag>``.

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#/usr/bin/env bash
# Known bugs:
# - Newlines in file/directory names break this script
@@ -11,7 +11,7 @@
# - Directories are not completed as such in "coalesced" short-opt arguments. For example,
# `rgbasm -M d<tab>` can autocomplete to `rgbasm -M dir/` (no space), but
# `rgbasm -Md<tab>` would autocomplete to `rgbasm -Mdir ` (trailing space) instead.
# This is because directory handling is performed by Readline, whom we can't tell about the short
# This is because dircetory handling is performed by Readline, whom we can't tell about the short
# opt kerfuffle. The user can work around by separating the argument, as shown above.
# (Also, there might be more possible bugs if `-Mdir` is actually a directory. Ugh.)
@@ -20,30 +20,27 @@
# Thus, we don't need to do much to handle that form of argument passing: skip '=' after long opts.
_rgbasm_completions() {
COMPREPLY=()
# Format: "long_opt:state_after"
# Empty long opt = it doesn't exit
# See the `state` variable below for info about `state_after`
declare -A opts=(
[V]="version:normal"
[E]="export-all:normal"
[H]="nop-after-halt:normal"
[h]="halt-without-nop:normal"
[L]="preserve-ld:normal"
[l]="auto-ldh:normal"
[v]="verbose:normal"
[w]=":normal"
[b]="binary-digits:unk"
[D]="define:unk"
[g]="gfx-chars:unk"
[I]="include:dir"
[i]="include:dir"
[M]="dependfile:glob-*.mk *.d"
[o]="output:glob-*.o"
[P]="preinclude:glob-*.asm *.inc"
[p]="pad-value:unk"
[Q]="q-precision:unk"
[r]="recursion-depth:unk"
[W]="warning:warning"
[X]="max-errors:unk"
)
# Parse command-line up to current word
local opt_ena=true
@@ -61,18 +58,6 @@ _rgbasm_completions() {
# "normal" is not returned, `optlen` will be set to the length (dash included) of the "option"
# part of the argument.
parse_short_opt() {
# These options act like a long option (= takes up the entire word), but only use a single dash
# So, they need some special handling
if [[ "$1" = "-M"[GP] ]]; then
state=normal
optlen=${#1}
return;
elif [[ "$1" = "-M"[QT] ]]; then
state='glob-*.d *.mk *.o'
optlen=${#1}
return;
fi
for (( i = 1; i < "${#1}"; i++ )); do
# If the option is not known, assume it doesn't take an argument
local opt="${opts["${1:$i:1}"]:-":normal"}"
@@ -86,7 +71,7 @@ _rgbasm_completions() {
optlen=0
}
for (( i = 1; i < COMP_CWORD; i++ )); do
for (( i = 1; i < $COMP_CWORD; i++ )); do
local word="${COMP_WORDS[$i]}"
# If currently processing an argument, skip this word
@@ -102,7 +87,7 @@ _rgbasm_completions() {
fi
# Check if it's a long option
if [[ "$word" = '--'* ]]; then
if [[ "${word:0:2}" = '--' ]]; then
# If the option is unknown, assume it takes no arguments: keep the state at "normal"
for long_opt in "${opts[@]}"; do
if [[ "$word" = "--${long_opt%%:*}" ]]; then
@@ -118,16 +103,25 @@ _rgbasm_completions() {
fi
done
# Check if it's a short option
elif [[ "$word" = '-'* ]]; then
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
if [[ "$optlen" -ne "${#word}" ]]; then
# If it's contained within the word, we won't complete it, revert to "normal"
state=normal
else
# Otherwise, complete it, but start at the beginning of *that* word
optlen=0
elif [[ "${word:0:1}" = '-' ]]; then
# The `-M?` ones are a mix of short and long, augh
# They must match the *full* word, but only take a single dash
# So, handle them here
if [[ "$1" = "-M"[GP] ]]; then
state=normal
elif [[ "$1" = "-M"[TQ] ]]; then
state='glob-*.d *.mk *.o'
else
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
if [[ "$optlen" -ne "${#word}" ]]; then
# If it's contained within the word, we won't complete it, revert to "normal"
state=normal
else
# Otherwise, complete it, but start at the beginning of *that* word
optlen=0
fi
fi
fi
fi
@@ -135,48 +129,48 @@ _rgbasm_completions() {
# Parse current word
# Careful that it might look like an option, so use `--` aggressively!
local cur_word="${COMP_WORDS[$i]}"
local cur_word="${COMP_WORDS[$COMP_CWORD]}"
# Process options, as short ones may change the state
if $opt_ena && [[ "$state" = 'normal' && "$cur_word" = '-'* ]]; then
if $opt_ena && [[ "$state" = 'normal' && "${cur_word:0:1}" = '-' ]]; then
# We might want to complete to an option or an arg to that option
# Parse the option word to check
# There's no whitespace in the option names, so we can ride a little dirty...
# Is this a long option?
if [[ "$cur_word" = '--'* ]]; then
if [[ "${cur_word:1:1}" = '-' ]]; then
# It is, try to complete one
mapfile -t COMPREPLY < <(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}")
return 0
elif [[ "$cur_word" = '-M'[GPQT] ]]; then
# These options act like long opts with no arguments, so return them and exactly them
COMPREPLY=( "$cur_word" )
COMPREPLY+=( $(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}") )
return 0
else
# Short options may be grouped, parse them to determine what to complete
parse_short_opt "$cur_word"
# The `-M?` ones may not be followed by anything
if [[ "$1" != "-M"[GPTQ] ]]; then
parse_short_opt "$cur_word"
# We got some short options that behave like long ones
COMPREPLY+=( $(compgen -W '-MG -MP -MT -MQ' -- "$cur_word") )
if [[ "$state" = 'normal' ]]; then
mapfile -t COMPREPLY < <(compgen -W "${!opts[*]}" -P "$cur_word" ''; compgen -W '-MG -MP -MQ -MT' "$cur_word")
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
# Post the option group as-is as a reply so that Readline inserts a space,
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY=( "$cur_word" )
return 0
if [[ "$state" = 'normal' ]]; then
COMPREPLY+=( $(compgen -W "${!opts[*]}" -P "$cur_word" '') )
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
# Post the option group as-is as a reply so that Readline inserts a space,
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY+=( "$cur_word" )
return 0
fi
fi
fi
fi
COMPREPLY=()
case "$state" in
unk) # Return with no replies: no idea what to complete!
;;
warning)
mapfile -t COMPREPLY < <(compgen -W "
COMPREPLY+=( $(compgen -W "
assert
backwards-for
builtin-args
@@ -194,12 +188,11 @@ _rgbasm_completions() {
shift
shift-amount
truncation
unmapped-char
user
all
extra
everything
error" -P "${cur_word:0:$optlen}" -- "${cur_word:$optlen}")
error" -P "${cur_word:0:$optlen}" -- "${cur_word:$optlen}") )
;;
normal) # Acts like a glob...
state="glob-*.asm *.inc *.sm83"
@@ -216,10 +209,6 @@ _rgbasm_completions() {
done < <(compgen -A directory -- "${cur_word:$optlen}")
compopt -o filenames
;;
*)
echo >&2 "Internal completion error: invalid state \"$state\", please report this bug"
return 1
;;
esac
}

View File

@@ -1,8 +1,10 @@
#!/usr/bin/env bash
#/usr/bin/env bash
# Same notes as RGBASM
_rgbfix_completions() {
COMPREPLY=()
# Format: "long_opt:state_after"
# Empty long opt = it doesn't exit
# See the `state` variable below for info about `state_after`
@@ -52,7 +54,7 @@ _rgbfix_completions() {
optlen=0
}
for (( i = 1; i < COMP_CWORD; i++ )); do
for (( i = 1; i < $COMP_CWORD; i++ )); do
local word="${COMP_WORDS[$i]}"
# If currently processing an argument, skip this word
@@ -68,7 +70,7 @@ _rgbfix_completions() {
fi
# Check if it's a long option
if [[ "$word" = '--'* ]]; then
if [[ "${word:0:2}" = '--' ]]; then
# If the option is unknown, assume it takes no arguments: keep the state at "normal"
for long_opt in "${opts[@]}"; do
if [[ "$word" = "--${long_opt%%:*}" ]]; then
@@ -84,7 +86,7 @@ _rgbfix_completions() {
fi
done
# Check if it's a short option
elif [[ "$word" = '-'* ]]; then
elif [[ "${word:0:1}" = '-' ]]; then
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
@@ -101,25 +103,25 @@ _rgbfix_completions() {
# Parse current word
# Careful that it might look like an option, so use `--` aggressively!
local cur_word="${COMP_WORDS[$i]}"
local cur_word="${COMP_WORDS[$COMP_CWORD]}"
# Process options, as short ones may change the state
if $opt_ena && [[ "$state" = 'normal' && "$cur_word" = '-'* ]]; then
if $opt_ena && [[ "$state" = 'normal' && "${cur_word:0:1}" = '-' ]]; then
# We might want to complete to an option or an arg to that option
# Parse the option word to check
# There's no whitespace in the option names, so we can ride a little dirty...
# Is this a long option?
if [[ "$cur_word" = '--'* ]]; then
if [[ "${cur_word:1:1}" = '-' ]]; then
# It is, try to complete one
mapfile -t COMPREPLY < <(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}")
COMPREPLY+=( $(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}") )
return 0
else
# Short options may be grouped, parse them to determine what to complete
parse_short_opt "$cur_word"
if [[ "$state" = 'normal' ]]; then
mapfile -t COMPREPLY < <(compgen -W "${!opts[*]}" -P "$cur_word" '')
COMPREPLY+=( $(compgen -W "${!opts[*]}" -P "$cur_word" '') )
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
@@ -127,25 +129,22 @@ _rgbfix_completions() {
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY=( "$cur_word" )
COMPREPLY+=( "$cur_word" )
return 0
fi
fi
fi
COMPREPLY=()
case "$state" in
unk) # Return with no replies: no idea what to complete!
;;
fix-spec)
COMPREPLY=( "${cur_word}"{l,h,g,L,H,G} )
COMPREPLY+=( "${cur_word}"{l,h,g,L,H,G} )
;;
mbc)
local cur_arg="${cur_word:$optlen}"
cur_arg="${cur_arg@U}"
compopt -o nosort # Keep `help` first in the list, mainly
mapfile -t COMPREPLY < <(compgen -W "help" -P "${cur_word:0:$optlen}" -- "${cur_word:$optlen}")
mapfile -t COMPREPLY -O ${#COMPREPLY} < <(compgen -W "
COMPREPLY=( $(compgen -W "
ROM_ONLY
MBC1{,+RAM,+RAM+BATTERY}
MBC2{,+BATTERY}
@@ -158,7 +157,8 @@ _rgbfix_completions() {
BANDAI_TAMA5
HUC3
HUC1+RAM+BATTERY
TPP1_1.0{,+BATTERY}{,+RTC}{,+RUMBLE,+MULTIRUMBLE}" -P "${cur_word:0:$optlen}" -- "${cur_word/ /_}")
TPP1_1.0{,+BATTERY}{,+RTC}{,+RUMBLE,+MULTIRUMBLE}" -P "${cur_word:0:$optlen}" -- "`tr 'a-z ' 'A-Z_' <<<"${cur_word/ /_}"`") )
COMPREPLY+=( $(compgen -W "help" -P "${cur_word:0:$optlen}" -- "${cur_word:$optlen}") )
;;
normal) # Acts like a glob...
state="glob-*.gb *.gbc *.sgb"
@@ -175,10 +175,6 @@ _rgbfix_completions() {
done < <(compgen -A directory -- "${cur_word:$optlen}")
compopt -o filenames
;;
*)
echo >&2 "Internal completion error: invalid state \"$state\", please report this bug"
return 1
;;
esac
}

View File

@@ -1,35 +1,31 @@
#!/usr/bin/env bash
#/usr/bin/env bash
# Same notes as RGBASM
_rgbgfx_completions() {
COMPREPLY=()
# Format: "long_opt:state_after"
# Empty long opt = it doesn't exit
# See the `state` variable below for info about `state_after`
declare -A opts=(
[V]="version:normal"
[C]="color-curve:normal"
[D]="debug:normal"
[h]="horizontal:normal"
[m]="mirror-tiles:normal"
[O]="group-outputs:normal"
[u]="unique-tiles:normal"
[v]="verbose:normal"
[Z]="columns:normal"
[a]="attr-map:glob-*.attrmap"
[A]="auto-attr-map:normal"
[b]="base-tiles:unk"
[f]="fix:normal"
[F]="fix-and-save:normal"
[a]="attr-map:*.attrmap"
[A]="output-attr-map:normal"
[d]="depth:unk"
[L]="slice:unk"
[N]="nb-tiles:unk"
[n]="nb-palettes:unk"
[o]="output:glob-*.2bpp"
[p]="palette:glob-*.pal"
[P]="auto-palette:normal"
[q]="palette-map:glob-*.palmap"
[Q]="auto-palette-map:normal"
[r]="reverse:unk"
[s]="palette-size:unk"
[t]="tilemap:glob-*.tilemap"
[T]="auto-tilemap:normal"
[o]="output:glob *.2bpp"
[p]="palette:glob *.pal"
[P]="output-palette:normal"
[t]="tilemap:glob *.tilemap"
[T]="output-tilemap:normal"
[x]="trim-end:unk"
)
# Parse command-line up to current word
@@ -61,7 +57,7 @@ _rgbgfx_completions() {
optlen=0
}
for (( i = 1; i < COMP_CWORD; i++ )); do
for (( i = 1; i < $COMP_CWORD; i++ )); do
local word="${COMP_WORDS[$i]}"
# If currently processing an argument, skip this word
@@ -77,7 +73,7 @@ _rgbgfx_completions() {
fi
# Check if it's a long option
if [[ "$word" = '--'* ]]; then
if [[ "${word:0:2}" = '--' ]]; then
# If the option is unknown, assume it takes no arguments: keep the state at "normal"
for long_opt in "${opts[@]}"; do
if [[ "$word" = "--${long_opt%%:*}" ]]; then
@@ -93,7 +89,7 @@ _rgbgfx_completions() {
fi
done
# Check if it's a short option
elif [[ "$word" = '-'* ]]; then
elif [[ "${word:0:1}" = '-' ]]; then
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
@@ -110,25 +106,25 @@ _rgbgfx_completions() {
# Parse current word
# Careful that it might look like an option, so use `--` aggressively!
local cur_word="${COMP_WORDS[$i]}"
local cur_word="${COMP_WORDS[$COMP_CWORD]}"
# Process options, as short ones may change the state
if $opt_ena && [[ "$state" = 'normal' && "$cur_word" = '-'* ]]; then
if $opt_ena && [[ "$state" = 'normal' && "${cur_word:0:1}" = '-' ]]; then
# We might want to complete to an option or an arg to that option
# Parse the option word to check
# There's no whitespace in the option names, so we can ride a little dirty...
# Is this a long option?
if [[ "$cur_word" = '--'* ]]; then
if [[ "${cur_word:1:1}" = '-' ]]; then
# It is, try to complete one
mapfile -t COMPREPLY < <(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}")
COMPREPLY+=( $(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}") )
return 0
else
# Short options may be grouped, parse them to determine what to complete
parse_short_opt "$cur_word"
if [[ "$state" = 'normal' ]]; then
mapfile -t COMPREPLY < <(compgen -W "${!opts[*]}" -P "$cur_word" '')
COMPREPLY+=( $(compgen -W "${!opts[*]}" -P "$cur_word" '') )
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
@@ -136,13 +132,12 @@ _rgbgfx_completions() {
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY=( "$cur_word" )
COMPREPLY+=( "$cur_word" )
return 0
fi
fi
fi
COMPREPLY=()
case "$state" in
unk) # Return with no replies: no idea what to complete!
;;
@@ -161,10 +156,6 @@ _rgbgfx_completions() {
done < <(compgen -A directory -- "${cur_word:$optlen}")
compopt -o filenames
;;
*)
echo >&2 "Internal completion error: invalid state \"$state\", please report this bug"
return 1
;;
esac
}

View File

@@ -1,8 +1,10 @@
#!/usr/bin/env bash
#/usr/bin/env bash
# Same notes as RGBASM
_rgblink_completions() {
COMPREPLY=()
# Format: "long_opt:state_after"
# Empty long opt = it doesn't exit
# See the `state` variable below for info about `state_after`
@@ -14,7 +16,6 @@ _rgblink_completions() {
[w]="wramx:normal"
[x]="nopad:normal"
[l]="linkerscript:glob-*"
[M]="no-sym-in-map:normal"
[m]="map:glob-*.map"
[n]="sym:glob-*.sym"
[O]="overlay:glob-*.gb *.gbc *.sgb"
@@ -51,7 +52,7 @@ _rgblink_completions() {
optlen=0
}
for (( i = 1; i < COMP_CWORD; i++ )); do
for (( i = 1; i < $COMP_CWORD; i++ )); do
local word="${COMP_WORDS[$i]}"
# If currently processing an argument, skip this word
@@ -67,7 +68,7 @@ _rgblink_completions() {
fi
# Check if it's a long option
if [[ "$word" = '--'* ]]; then
if [[ "${word:0:2}" = '--' ]]; then
# If the option is unknown, assume it takes no arguments: keep the state at "normal"
for long_opt in "${opts[@]}"; do
if [[ "$word" = "--${long_opt%%:*}" ]]; then
@@ -83,7 +84,7 @@ _rgblink_completions() {
fi
done
# Check if it's a short option
elif [[ "$word" = '-'* ]]; then
elif [[ "${word:0:1}" = '-' ]]; then
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
@@ -100,25 +101,25 @@ _rgblink_completions() {
# Parse current word
# Careful that it might look like an option, so use `--` aggressively!
local cur_word="${COMP_WORDS[$i]}"
local cur_word="${COMP_WORDS[$COMP_CWORD]}"
# Process options, as short ones may change the state
if $opt_ena && [[ "$state" = 'normal' && "$cur_word" = '-'* ]]; then
if $opt_ena && [[ "$state" = 'normal' && "${cur_word:0:1}" = '-' ]]; then
# We might want to complete to an option or an arg to that option
# Parse the option word to check
# There's no whitespace in the option names, so we can ride a little dirty...
# Is this a long option?
if [[ "$cur_word" = '--'* ]]; then
if [[ "${cur_word:1:1}" = '-' ]]; then
# It is, try to complete one
mapfile -t COMPREPLY < <(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}")
COMPREPLY+=( $(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}") )
return 0
else
# Short options may be grouped, parse them to determine what to complete
parse_short_opt "$cur_word"
if [[ "$state" = 'normal' ]]; then
mapfile -t COMPREPLY < <(compgen -W "${!opts[*]}" -P "$cur_word" '')
COMPREPLY+=( $(compgen -W "${!opts[*]}" -P "$cur_word" '') )
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
@@ -126,13 +127,12 @@ _rgblink_completions() {
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY=( "$cur_word" )
COMPREPLY+=( "$cur_word" )
return 0
fi
fi
fi
COMPREPLY=()
case "$state" in
unk) # Return with no replies: no idea what to complete!
;;
@@ -151,10 +151,6 @@ _rgblink_completions() {
done < <(compgen -A directory -- "${cur_word:$optlen}")
compopt -o filenames
;;
*)
echo >&2 "Internal completion error: invalid state \"$state\", please report this bug"
return 1
;;
esac
}

View File

@@ -1,11 +1,31 @@
#!/usr/bin/env bash
#!/bin/bash
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2021 Rangi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
declare -A FILES
while read -r -d '' file; do
FILES["$file"]="true"
done < <(git diff --name-only -z "$1" HEAD)
done < <(git diff --name-only -z $1 HEAD)
edited () {
${FILES["$1"]:-"false"}
@@ -20,49 +40,46 @@ dependency () {
# Pull requests that edit the first file without the second may be correct,
# but are suspicious enough to require review.
dependency include/linkdefs.hpp man/rgbds.5 \
dependency include/linkdefs.h src/rgbds.5 \
"Was the object file format changed?"
dependency src/asm/parser.y man/rgbasm.5 \
dependency src/asm/parser.y src/asm/rgbasm.5 \
"Was the rgbasm grammar changed?"
dependency src/link/script.y man/rgblink.5 \
"Was the linker script grammar changed?"
dependency include/asm/warning.hpp man/rgbasm.1 \
dependency include/asm/warning.h src/asm/rgbasm.1 \
"Were the rgbasm warnings changed?"
dependency src/asm/object.cpp include/linkdefs.hpp \
dependency src/asm/object.c include/linkdefs.h \
"Should the object file revision be bumped?"
dependency src/link/object.cpp include/linkdefs.hpp \
dependency src/link/object.c include/linkdefs.h \
"Should the object file revision be bumped?"
dependency Makefile CMakeLists.txt \
dependency Makefile CMakeLists.txt \
"Did the build process change?"
dependency Makefile src/CMakeLists.txt \
dependency Makefile src/CMakeLists.txt \
"Did the build process change?"
dependency src/asm/main.cpp man/rgbasm.1 \
dependency src/asm/main.c src/asm/rgbasm.1 \
"Did the rgbasm CLI change?"
dependency src/asm/main.cpp contrib/zsh_compl/_rgbasm \
dependency src/asm/main.c contrib/zsh_compl/_rgbasm \
"Did the rgbasm CLI change?"
dependency src/asm/main.cpp contrib/bash_compl/_rgbasm.bash \
dependency src/asm/main.c contrib/bash_compl/_rgbasm.bash \
"Did the rgbasm CLI change?"
dependency src/link/main.cpp man/rgblink.1 \
dependency src/link/main.c src/link/rgblink.1 \
"Did the rgblink CLI change?"
dependency src/link/main.cpp contrib/zsh_compl/_rgblink \
dependency src/link/main.c contrib/zsh_compl/_rgblink \
"Did the rgblink CLI change?"
dependency src/link/main.cpp contrib/bash_compl/_rgblink.bash \
dependency src/link/main.c contrib/bash_compl/_rgblink.bash \
"Did the rgblink CLI change?"
dependency src/fix/main.cpp man/rgbfix.1 \
dependency src/fix/main.c src/fix/rgbfix.1 \
"Did the rgbfix CLI change?"
dependency src/fix/main.cpp contrib/zsh_compl/_rgbfix \
dependency src/fix/main.c contrib/zsh_compl/_rgbfix \
"Did the rgbfix CLI change?"
dependency src/fix/main.cpp contrib/bash_compl/_rgbfix.bash \
dependency src/fix/main.c contrib/bash_compl/_rgbfix.bash \
"Did the rgbfix CLI change?"
dependency src/gfx/main.cpp man/rgbgfx.1 \
dependency src/gfx/main.c src/gfx/rgbgfx.1 \
"Did the rgbgfx CLI change?"
dependency src/gfx/main.cpp contrib/zsh_compl/_rgbgfx \
dependency src/gfx/main.c contrib/zsh_compl/_rgbgfx \
"Did the rgbgfx CLI change?"
dependency src/gfx/main.cpp contrib/bash_compl/_rgbgfx.bash \
dependency src/gfx/main.c contrib/bash_compl/_rgbgfx.bash \
"Did the rgbgfx CLI change?"

View File

@@ -1,27 +0,0 @@
#!/usr/bin/env bash
set -e
# Build RGBDS with gcov support
make coverage -j
# Run the tests
for dir in asm link fix gfx; do
pushd test/$dir
./test.sh
popd
done
# Generate coverage logs
gcov src/**/*.{c,cpp}
mkdir -p coverage
# Generate coverage report
lcov -c --no-external -d . -o coverage/coverage.info
genhtml -f -s -o coverage/ coverage/coverage.info
# Open report in web browser
if [ "$(uname)" == "Darwin" ]; then
open coverage/index.html
else
xdg-open coverage/index.html
fi

View File

@@ -1,53 +1,73 @@
#!/usr/bin/env bash
#!/bin/bash
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2020 Eldred Habert
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
STATE=0
diff <(xxd "$1") <(xxd "$2") | while read -r LINE; do
if [[ $STATE -eq 0 ]]; then
diff <(xxd $1) <(xxd $2) | while read -r LINE; do
if [ $STATE -eq 0 ]; then
# Discard first line (line info)
STATE=1
elif [[ "$LINE" = '---' ]]; then
elif [ "$LINE" = '---' ]; then
# Separator between files switches states
echo "$LINE"
echo $LINE
STATE=3
elif grep -Eq '^[0-9]+(,[0-9]+)?[cd][0-9]+(,[0-9]+)?' <<< "$LINE"; then
# Line info resets the whole thing
STATE=1
elif [[ $STATE -eq 1 || $STATE -eq 3 ]]; then
elif [ $STATE -eq 1 -o $STATE -eq 3 ]; then
# Compute the GB address from the ROM offset
OFS=$(cut -d ' ' -f 2 <<< "$LINE" | tr -d ':')
BANK=$((0x$OFS / 0x4000))
ADDR=$((0x$OFS % 0x4000 + (BANK != 0) * 0x4000))
ADDR=$((0x$OFS % 0x4000 + ($BANK != 0) * 0x4000))
# Try finding the preceding symbol closest to the diff
if [[ $STATE -eq 1 ]]; then
if [ $STATE -eq 1 ]; then
STATE=2
SYMFILE=${1%.*}.sym
else
STATE=4
SYMFILE=${2%.*}.sym
fi
EXTRA=$(if [[ -f "$SYMFILE" ]]; then
EXTRA=$(if [ -f "$SYMFILE" ]; then
# Read the sym file for such a symbol
# Ignore comment lines, only pick matching bank
# (The bank regex ignores comments already, make `cut` and `tr` process less lines)
grep -Ei "$(printf "^%02x:" $BANK)" "$SYMFILE" |
grep -Ei $(printf "^%02x:" $BANK) "$SYMFILE" |
cut -d ';' -f 1 |
tr -d "\r" |
while read -r SYMADDR SYM; do
SYMADDR=$((0x${SYMADDR#*:}))
if [[ $SYMADDR -le $ADDR ]]; then
printf " (%s+0x%x)\n" "$SYM" $((ADDR - SYMADDR))
if [ $SYMADDR -le $ADDR ]; then
printf " (%s+%#x)\n" "$SYM" $(($ADDR - $SYMADDR))
fi
# TODO: assumes sorted sym files
done | tail -n 1
fi)
printf "%02x:%04x %s\n" $BANK $ADDR "$EXTRA"
printf "%02x:%04x %s\n" $BANK $ADDR $EXTRA
fi
if [[ $STATE -eq 2 || $STATE -eq 4 ]]; then
if [ $STATE -eq 2 -o $STATE -eq 4 ]; then
OFS=$(cut -d ' ' -f 2 <<< "$LINE" | tr -d ':')
BANK=$((0x$OFS / 0x4000))
ADDR=$((0x$OFS % 0x4000 + (BANK != 0) * 0x4000))
ADDR=$((0x$OFS % 0x4000 + ($BANK != 0) * 0x4000))
printf "%s %02x:%04x: %s\n" "${LINE:0:1}" $BANK $ADDR "${LINE#*: }"
fi
done

View File

@@ -25,11 +25,10 @@ _rgbasm_warnings() {
'shift:Warn when shifting negative values'
'shift-amount:Warn when a shift'\''s operand it negative or \> 32'
'truncation:Warn when implicit truncation loses bits'
'unmapped-char:Warn on unmapped character'
'user:Warn when executing the WARN built-in'
)
# TODO: handle `no-` and `error=` somehow?
# TODO: handle `=0|1|2` levels for `numeric-string`, `truncation`, and `unmapped-char`?
# TODO: handle `=0|1|2` levels for `numeric-string` and `truncation`?
_describe warning warnings
}
@@ -38,29 +37,24 @@ local args=(
'(- : * options)'{-V,--version}'[Print version number]'
'(-E --export-all)'{-E,--export-all}'[Export all symbols]'
'(-H --nop-after-halt)'{-H,--nop-after-halt}'[Output a `nop` after `halt`]'
'(-h --halt-without-nop)'{-h,--halt-without-nop}'[Prevent outputting a `nop` after `halt`]'
'(-L --preserve-ld)'{-L,--preserve-ld}'[Prevent optimizing `ld` into `ldh`]'
'(-l --auto-ldh)'{-l,--auto-ldh}'[Optimize `ld` into `ldh`]'
'(-h --halt-without-nop)'{-h,--halt-without-nop}'[Avoid outputting a `nop` after `halt`]'
'(-L ---preserve-ld)'{-L,--preserve-ld}'[Prevent auto-optimizing `ld` into `ldh`]'
'(-v --verbose)'{-v,--verbose}'[Print additional messages regarding progression]'
-w'[Disable all warnings]'
'(-b --binary-digits)'{-b,--binary-digits}'+[Change chars for binary constants]:digit spec:'
'*'{-D,--define}'+[Define a string symbol]:name + value (default 1):'
'(-g --gfx-chars)'{-g,--gfx-chars}'+[Change chars for gfx constants]:chars spec:'
'(-I --include)'{-I,--include}'+[Add an include directory]:include path:_files -/'
'(-i --include)'{-i,--include}'+[Add an include directory]:include path:_files -/'
'(-M --dependfile)'{-M,--dependfile}"+[List deps in make format]:output file:_files -g '*.{d,mk}'"
-MG'[Assume missing files should be generated]'
-MP'[Add phony targets to all deps]'
'*'-MT"+[Add a target to the rules]:target:_files -g '*.{d,mk,o}'"
'*'-MQ"+[Add a target to the rules]:target:_files -g '*.{d,mk,o}'"
'(-o --output)'{-o,--output}'+[Output file]:output file:_files'
'(-P --preinclude)'{-P,--preinclude}"+[Pre-include a file]:include file:_files -g '*.{asm,inc}'"
'(-p --pad-value)'{-p,--pad-value}'+[Set padding byte]:padding byte:'
'(-Q --q-precision)'{-Q,--q-precision}'+[Set fixed-point precision]:precision:'
'(-r --recursion-depth)'{-r,--recursion-depth}'+[Set maximum recursion depth]:depth:'
'(-W --warning)'{-W,--warning}'+[Toggle warning flags]:warning flag:_rgbasm_warnings'
'(-X --max-errors)'{-X,--max-errors}'+[Set maximum errors before aborting]:maximum errors:'
":assembly sources:_files -g '*.asm'"
)

View File

@@ -13,29 +13,23 @@ local args=(
# Arguments are listed here in the same order as in the manual, except for the version
'(- : * options)'{-V,--version}'[Print version number]'
'(-a --attr-map -A --auto-attr-map)'{-A,--auto-attr-map}'[Shortcut for -a <file>.attrmap]'
'(-a --attr-map -A --output-attr-map)'{-A,--output-attr-map}'[Shortcut for -a <file>.attrmap]'
'(-C --color-curve)'{-C,--color-curve}'[Generate palettes using GBC color curve]'
'(-D --debug)'{-D,--debug}'[Enable debug features]'
'(-f --fix -F --fix-and-save)'{-f,--fix}'[Fix input PNG into an indexed image]'
'(-f --fix -F --fix-and-save)'{-F,--fix-and-save}'[Like -f but also save CLI params within the PNG]'
'(-h --horizontal)'{-h,--horizontal}'[Lay out tiles horizontally instead of vertically]'
'(-m --mirror-tiles)'{-m,--mirror-tiles}'[Eliminate mirrored tiles from output]'
'(-O --group-outputs)'{-O,--group-outputs}'[Base "shortcut" options on the output path, not input]'
'(-p --palette -P --auto-palette)'{-P,--auto-palette}'[Shortcut for -p <file>.pal]'
'(-q --palette-map -Q --auto-palette-map)'{-Q,--auto-palette-map}'[Shortcut for -p <file>.palmap]'
'(-t --tilemap -T --auto-tilemap)'{-T,--auto-tilemap}'[Shortcut for -t <file>.tilemap]'
'(-p --palette -P --output-palette)'{-P,--output-palette}'[Shortcut for -p <file>.pal]'
'(-t --tilemap -T --output-tilemap)'{-T,--output-tilemap}'[Shortcut for -t <file>.tilemap]'
'(-u --unique-tiles)'{-u,--unique-tiles}'[Eliminate redundant tiles]'
{-v,--verbose}'[Enable verbose output]'
'(-Z --columns)'{-Z,--columns}'[Read the image in column-major order]'
'(-v --verbose)'{-v,--verbose}'[Enable verbose output]'
'(-a --attr-map -A --auto-attr-map)'{-a,--attr-map}'+[Generate a map of tile attributes (mirroring)]:attrmap file:_files'
'(-b --base-tiles)'{-b,--base-tiles}'+[Base tile IDs for tile map output]:base tile IDs:'
'(-a --attr-map -A --output-attr-map)'{-a,--attr-map}'+[Generate a map of tile attributes (mirroring)]:attrmap file:_files'
'(-d --depth)'{-d,--depth}'+[Set bit depth]:bit depth:_depths'
'(-L --slice)'{-L,--slice}'+[Only process a portion of the image]:input slice:'
'(-N --nb-tiles)'{-N,--nb-tiles}'+[Limit number of tiles]:tile count:'
'(-n --nb-palettes)'{-n,--nb-palettes}'+[Limit number of palettes]:palette count:'
'(-o --output)'{-o,--output}'+[Set output file]:output file:_files'
'(-p --palette -P --auto-palette)'{-p,--palette}"+[Output the image's palette in little-endian native RGB555 format]:palette file:_files"
'(-q --palette-map -Q --auto-palette-map)'{-q,--palette-map}"+[Output the image's palette map]:palette map file:_files"
'(-r --reverse)'{-r,--reverse}'+[Yield an image from binary data]:image width (in tiles):'
'(-s --palette-size)'{-s,--palette-size}'+[Limit palette size]:palette size:'
'(-t --tilemap -T --auto-tilemap)'{-t,--tilemap}'+[Generate a map of tile indices]:tilemap file:_files'
'(-p --palette -P --output-palette)'{-p,--palette}"+[Output the image's palette in little-endian native RGB555 format]:palette file:_files"
'(-t --tilemap -T --output-tilemap)'{-t,--tilemap}'+[Generate a map of tile indices]:tilemap file:_files'
'(-x --trim-end)'{-x,--trim-end}'+[Trim end of output by this many tiles]:tile count:'
":input png file:_files -g '*.png'"

View File

@@ -11,7 +11,6 @@ local args=(
'(-x --nopad)'{-x,--nopad}'[Disable padding the end of the final file]'
'(-l --linkerscript)'{-l,--linkerscript}"+[Use a linker script]:linker script:_files -g '*.link'"
'(-M --no-sym-in-map)'{-M,--no-sym-in-map}'[Do not output symbol names in map file]'
'(-m --map)'{-m,--map}"+[Produce a map file]:map file:_files -g '*.map'"
'(-n --sym)'(-n,--sym)"+[Produce a symbol file]:sym file:_files -g '*.sym'"
'(-O --overlay)'{-O,--overlay}'+[Overlay sections over on top of bin file]:base overlay:_files'

View File

@@ -1,20 +1,23 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2018, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_ASM_CHARMAP_H
#define RGBDS_ASM_CHARMAP_H
#include <stdbool.h>
#include <stdint.h>
#define DEFAULT_CHARMAP_NAME "main"
struct Charmap *charmap_New(char const *name, char const *baseName);
void charmap_Delete(struct Charmap *charmap);
void charmap_Set(char const *name);
void charmap_Push(void);
void charmap_Pop(void);
void charmap_Add(char *mapping, uint8_t value);
bool charmap_HasChar(char const *input);
size_t charmap_Convert(char const *input, uint8_t *output);
size_t charmap_ConvertNext(char const **input, uint8_t **output);
#endif // RGBDS_ASM_CHARMAP_H
#endif /* RGBDS_ASM_CHARMAP_H */

31
include/asm/fixpoint.h Normal file
View File

@@ -0,0 +1,31 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2021, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_ASM_FIXPOINT_H
#define RGBDS_ASM_FIXPOINT_H
#include <stdint.h>
int32_t fix_Callback_PI(void);
void fix_Print(int32_t i);
int32_t fix_Sin(int32_t i);
int32_t fix_Cos(int32_t i);
int32_t fix_Tan(int32_t i);
int32_t fix_ASin(int32_t i);
int32_t fix_ACos(int32_t i);
int32_t fix_ATan(int32_t i);
int32_t fix_ATan2(int32_t i, int32_t j);
int32_t fix_Mul(int32_t i, int32_t j);
int32_t fix_Div(int32_t i, int32_t j);
int32_t fix_Pow(int32_t i, int32_t j);
int32_t fix_Log(int32_t i, int32_t j);
int32_t fix_Round(int32_t i);
int32_t fix_Ceil(int32_t i);
int32_t fix_Floor(int32_t i);
#endif /* RGBDS_ASM_FIXPOINT_H */

View File

@@ -1,28 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_ASM_FIXPOINT_H
#define RGBDS_ASM_FIXPOINT_H
#include <stdint.h>
extern uint8_t fixPrecision;
uint8_t fix_Precision(void);
double fix_PrecisionFactor(void);
int32_t fix_Sin(int32_t i, int32_t q);
int32_t fix_Cos(int32_t i, int32_t q);
int32_t fix_Tan(int32_t i, int32_t q);
int32_t fix_ASin(int32_t i, int32_t q);
int32_t fix_ACos(int32_t i, int32_t q);
int32_t fix_ATan(int32_t i, int32_t q);
int32_t fix_ATan2(int32_t i, int32_t j, int32_t q);
int32_t fix_Mul(int32_t i, int32_t j, int32_t q);
int32_t fix_Mod(int32_t i, int32_t j, int32_t q);
int32_t fix_Div(int32_t i, int32_t j, int32_t q);
int32_t fix_Pow(int32_t i, int32_t j, int32_t q);
int32_t fix_Log(int32_t i, int32_t j, int32_t q);
int32_t fix_Round(int32_t i, int32_t q);
int32_t fix_Ceil(int32_t i, int32_t q);
int32_t fix_Floor(int32_t i, int32_t q);
#endif // RGBDS_ASM_FIXPOINT_H

View File

@@ -1,4 +1,10 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 2020, RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_FORMAT_SPEC_H
#define RGBDS_FORMAT_SPEC_H
@@ -54,4 +60,4 @@ void fmt_FinishCharacters(struct FormatSpec *fmt);
void fmt_PrintString(char *buf, size_t bufLen, struct FormatSpec const *fmt, char const *value);
void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uint32_t value);
#endif // RGBDS_FORMAT_SPEC_H
#endif /* RGBDS_FORMAT_SPEC_H */

View File

@@ -1,6 +1,14 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2018, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Contains some assembler-wide defines and externs
/*
* Contains some assembler-wide defines and externs
*/
#ifndef RGBDS_ASM_FSTACK_H
#define RGBDS_ASM_FSTACK_H
@@ -9,35 +17,37 @@
#include <stdint.h>
#include <stdio.h>
#include "asm/lexer.hpp"
#include "asm/lexer.h"
#include "linkdefs.hpp"
struct FileStackNode {
struct FileStackNode *parent; // Pointer to parent node, for error reporting
// Line at which the parent context was exited; meaningless for the root level
struct FileStackNode *parent; /* Pointer to parent node, for error reporting */
/* Line at which the parent context was exited; meaningless for the root level */
uint32_t lineNo;
struct FileStackNode *next; // Next node in the output linked list
bool referenced; // If referenced, don't free!
uint32_t ID; // Set only if referenced: ID within the object file, -1 if not output yet
struct FileStackNode *next; /* Next node in the output linked list */
bool referenced; /* If referenced, don't free! */
uint32_t ID; /* Set only if referenced: ID within the object file, -1 if not output yet */
enum FileStackNodeType type;
enum {
NODE_REPT,
NODE_FILE,
NODE_MACRO,
} type;
};
struct FileStackReptNode { // NODE_REPT
struct FileStackReptNode { /* NODE_REPT */
struct FileStackNode node;
uint32_t reptDepth;
// WARNING: if changing this type, change overflow check in `fstk_Init`
uint32_t iters[]; // REPT iteration counts since last named node, in reverse depth order
/* WARNING: if changing this type, change overflow check in `fstk_Init` */
uint32_t iters[]; /* REPT iteration counts since last named node, in reverse depth order */
};
struct FileStackNamedNode { // NODE_FILE, NODE_MACRO
struct FileStackNamedNode { /* NODE_FILE, NODE_MACRO */
struct FileStackNode node;
char name[]; // File name for files, file::macro name for macros
char name[]; /* File name for files, file::macro name for macros */
};
#define DEFAULT_MAX_DEPTH 64
extern size_t maxRecursionDepth;
struct MacroArgs;
@@ -45,12 +55,11 @@ struct MacroArgs;
void fstk_Dump(struct FileStackNode const *node, uint32_t lineNo);
void fstk_DumpCurrent(void);
struct FileStackNode *fstk_GetFileStack(void);
// The lifetime of the returned chars is until reaching the end of that file
/* The lifetime of the returned chars is until reaching the end of that file */
char const *fstk_GetFileName(void);
void fstk_AddIncludePath(char const *s);
void fstk_SetPreIncludeFile(char const *s);
/*
/**
* @param path The user-provided file name
* @param fullPath The address of a pointer, which will be made to point at the full path
* The pointer's value must be a valid argument to `realloc`, including NULL
@@ -71,4 +80,4 @@ bool fstk_Break(void);
void fstk_NewRecursionDepth(size_t newDepth);
void fstk_Init(char const *mainPath, size_t maxDepth);
#endif // RGBDS_ASM_FSTACK_H
#endif /* RGBDS_ASM_FSTACK_H */

View File

@@ -1,11 +1,17 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2018, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_ASM_LEXER_H
#define RGBDS_ASM_LEXER_H
#include <stdbool.h>
#define MAXSTRLEN 255
#define MAXSTRLEN 255
struct LexerState;
extern struct LexerState *lexerState;
@@ -43,7 +49,9 @@ static inline void lexer_SetGfxDigits(char const digits[4])
gfxDigits[3] = digits[3];
}
// `path` is referenced, but not held onto..!
/*
* `path` is referenced, but not held onto..!
*/
struct LexerState *lexer_OpenFile(char const *path);
struct LexerState *lexer_OpenFileView(char const *path, char *buf, size_t size, uint32_t lineNo);
void lexer_RestartRept(uint32_t lineNo);
@@ -84,11 +92,6 @@ int yylex(void);
bool lexer_CaptureRept(struct CaptureBody *capture);
bool lexer_CaptureMacroBody(struct CaptureBody *capture);
struct AlignmentSpec {
uint8_t alignment;
uint16_t alignOfs;
};
#define INITIAL_DS_ARG_SIZE 2
struct DsArgList {
size_t nbArgs;
@@ -96,11 +99,4 @@ struct DsArgList {
struct Expression *args;
};
#define INITIAL_PURGE_ARG_SIZE 2
struct PurgeArgList {
size_t nbArgs;
size_t capacity;
char **args;
};
#endif // RGBDS_ASM_LEXER_H
#endif /* RGBDS_ASM_LEXER_H */

View File

@@ -1,4 +1,10 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 2020, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_MACRO_H
#define RGBDS_MACRO_H
@@ -7,9 +13,9 @@
#include <stdbool.h>
#include <stdlib.h>
#include "asm/warning.hpp"
#include "asm/warning.h"
#include "helpers.hpp"
#include "helpers.h"
struct MacroArgs;
@@ -25,8 +31,7 @@ uint32_t macro_GetUniqueID(void);
char const *macro_GetUniqueIDStr(void);
void macro_SetUniqueID(uint32_t id);
uint32_t macro_UseNewUniqueID(void);
uint32_t macro_UndefUniqueID(void);
void macro_ShiftCurrentArgs(int32_t count);
uint32_t macro_NbArgs(void);
#endif // RGBDS_MACRO_H
#endif

View File

@@ -1,4 +1,10 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2021, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_MAIN_H
#define RGBDS_MAIN_H
@@ -7,14 +13,12 @@
#include <stdint.h>
#include <stdio.h>
#include "helpers.hpp"
#include "helpers.h"
extern bool haltNop;
extern bool warnOnHaltNop;
extern bool haltnop;
extern bool optimizeLoads;
extern bool warnOnLdOpt;
extern bool verbose;
extern bool warnings; // True to enable warnings, false to disable them.
extern bool warnings; /* True to enable warnings, false to disable them. */
extern FILE *dependfile;
extern char *targetFileName;
@@ -22,4 +26,4 @@ extern bool generatedMissingIncludes;
extern bool failedOnMissingInclude;
extern bool generatePhonyDeps;
#endif // RGBDS_MAIN_H
#endif /* RGBDS_MAIN_H */

25
include/asm/opt.h Normal file
View File

@@ -0,0 +1,25 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2021, Eldred Habert and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_OPT_H
#define RGBDS_OPT_H
#include <stdbool.h>
#include <stdint.h>
void opt_B(char const chars[2]);
void opt_G(char const chars[4]);
void opt_P(uint8_t fill);
void opt_L(bool optimize);
void opt_W(char const *flag);
void opt_Parse(char const *option);
void opt_Push(void);
void opt_Pop(void);
#endif

View File

@@ -1,20 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_OPT_H
#define RGBDS_OPT_H
#include <stdbool.h>
#include <stdint.h>
void opt_B(char const chars[2]);
void opt_G(char const chars[4]);
void opt_P(uint8_t padByte);
void opt_Q(uint8_t precision);
void opt_L(bool optimize);
void opt_W(char *flag);
void opt_Parse(char *option);
void opt_Push(void);
void opt_Pop(void);
#endif // RGBDS_OPT_H

View File

@@ -1,11 +1,17 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2018, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_ASM_OUTPUT_H
#define RGBDS_ASM_OUTPUT_H
#include <stdint.h>
#include "linkdefs.hpp"
#include "linkdefs.h"
struct Expression;
struct FileStackNode;
@@ -21,4 +27,4 @@ bool out_CreateAssert(enum AssertionType type, struct Expression const *expr,
char const *message, uint32_t ofs);
void out_WriteObject(void);
#endif // RGBDS_ASM_OUTPUT_H
#endif /* RGBDS_ASM_OUTPUT_H */

View File

@@ -1,4 +1,10 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2018, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_ASM_RPN_H
#define RGBDS_ASM_RPN_H
@@ -6,7 +12,7 @@
#include <stdint.h>
#include <stdbool.h>
#include "linkdefs.hpp"
#include "linkdefs.h"
#define MAXRPNLEN 1048576
@@ -21,13 +27,17 @@ struct Expression {
uint32_t rpnPatchSize; // Size the expression will take in the object file
};
// Determines if an expression is known at assembly time
/*
* Determines if an expression is known at assembly time
*/
static inline bool rpn_isKnown(struct Expression const *expr)
{
return expr->isKnown;
}
// Determines if an expression is a symbol suitable for const diffing
/*
* Determines if an expression is a symbol suitable for const diffing
*/
static inline bool rpn_isSymbol(const struct Expression *expr)
{
return expr->isSymbol;
@@ -44,19 +54,17 @@ void rpn_BinaryOp(enum RPNCommand op, struct Expression *expr,
void rpn_HIGH(struct Expression *expr, const struct Expression *src);
void rpn_LOW(struct Expression *expr, const struct Expression *src);
void rpn_ISCONST(struct Expression *expr, const struct Expression *src);
void rpn_NEG(struct Expression *expr, const struct Expression *src);
void rpn_NOT(struct Expression *expr, const struct Expression *src);
void rpn_UNNEG(struct Expression *expr, const struct Expression *src);
void rpn_UNNOT(struct Expression *expr, const struct Expression *src);
void rpn_BankSymbol(struct Expression *expr, char const *symName);
void rpn_BankSection(struct Expression *expr, char const *sectionName);
void rpn_BankSelf(struct Expression *expr);
void rpn_SizeOfSection(struct Expression *expr, char const *sectionName);
void rpn_StartOfSection(struct Expression *expr, char const *sectionName);
void rpn_SizeOfSectionType(struct Expression *expr, enum SectionType type);
void rpn_StartOfSectionType(struct Expression *expr, enum SectionType type);
void rpn_Free(struct Expression *expr);
void rpn_CheckHRAM(struct Expression *expr, const struct Expression *src);
void rpn_CheckRST(struct Expression *expr, const struct Expression *src);
void rpn_CheckNBit(struct Expression const *expr, uint8_t n);
int32_t rpn_GetConstVal(struct Expression const *expr);
#endif // RGBDS_ASM_RPN_H
#endif /* RGBDS_ASM_RPN_H */

View File

@@ -1,4 +1,10 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 2020, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_SECTION_H
#define RGBDS_SECTION_H
@@ -6,8 +12,8 @@
#include <stdint.h>
#include <stdbool.h>
#include "linkdefs.hpp"
#include "platform.hpp" // NONNULL
#include "linkdefs.h"
#include "platform.h" // NONNULL
extern uint8_t fillByte;
@@ -17,8 +23,8 @@ struct Section {
char *name;
enum SectionType type;
enum SectionModifier modifier;
struct FileStackNode *src; // Where the section was defined
uint32_t fileLine; // Line where the section was defined
struct FileStackNode *src; /* Where the section was defined */
uint32_t fileLine; /* Line where the section was defined */
uint32_t size;
uint32_t org;
uint32_t bank;
@@ -38,16 +44,15 @@ struct SectionSpec {
extern struct Section *currentSection;
struct Section *sect_FindSectionByName(char const *name);
void sect_NewSection(char const *name, enum SectionType type, uint32_t org,
void sect_NewSection(char const *name, uint32_t secttype, uint32_t org,
struct SectionSpec const *attributes, enum SectionModifier mod);
void sect_SetLoadSection(char const *name, enum SectionType type, uint32_t org,
void sect_SetLoadSection(char const *name, uint32_t secttype, uint32_t org,
struct SectionSpec const *attributes, enum SectionModifier mod);
void sect_EndLoadSection(void);
struct Section *sect_GetSymbolSection(void);
uint32_t sect_GetSymbolOffset(void);
uint32_t sect_GetOutputOffset(void);
uint32_t sect_GetAlignBytes(uint8_t alignment, uint16_t offset);
void sect_AlignPC(uint8_t alignment, uint16_t offset);
void sect_StartUnion(void);
@@ -60,6 +65,7 @@ void sect_AbsByteGroup(uint8_t const *s, size_t length);
void sect_AbsWordGroup(uint8_t const *s, size_t length);
void sect_AbsLongGroup(uint8_t const *s, size_t length);
void sect_Skip(uint32_t skip, bool ds);
void sect_String(char const *s);
void sect_RelByte(struct Expression *expr, uint32_t pcShift);
void sect_RelBytes(uint32_t n, struct Expression *exprs, size_t size);
void sect_RelWord(struct Expression *expr, uint32_t pcShift);
@@ -68,10 +74,9 @@ void sect_PCRelByte(struct Expression *expr, uint32_t pcShift);
void sect_BinaryFile(char const *s, int32_t startPos);
void sect_BinaryFileSlice(char const *s, int32_t start_pos, int32_t length);
void sect_EndSection(void);
void sect_PushSection(void);
void sect_PopSection(void);
bool sect_IsSizeKnown(struct Section const NONNULL(name));
#endif // RGBDS_SECTION_H
#endif

View File

@@ -1,4 +1,10 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2020, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_SYMBOL_H
#define RGBDS_SYMBOL_H
@@ -8,9 +14,9 @@
#include <string.h>
#include <time.h>
#include "asm/section.hpp"
#include "asm/section.h"
#include "platform.hpp" // MIN_NB_ELMS
#include "platform.h" // MIN_NB_ELMS
#define MAXSYMLEN 255
@@ -26,28 +32,28 @@ enum SymbolType {
struct Symbol {
char name[MAXSYMLEN + 1];
enum SymbolType type;
bool isExported; // Whether the symbol is to be exported
bool isBuiltin; // Whether the symbol is a built-in
bool isExported; /* Whether the symbol is to be exported */
bool isBuiltin; /* Whether the symbol is a built-in */
struct Section *section;
struct FileStackNode *src; // Where the symbol was defined
uint32_t fileLine; // Line where the symbol was defined
struct FileStackNode *src; /* Where the symbol was defined */
uint32_t fileLine; /* Line where the symbol was defined */
bool hasCallback;
union {
// If sym_IsNumeric
/* If sym_IsNumeric */
int32_t value;
int32_t (*numCallback)(void);
// For SYM_MACRO and SYM_EQUS; TODO: have separate fields
/* For SYM_MACRO and SYM_EQUS; TODO: have separate fields */
struct {
size_t macroSize;
char *macro;
};
// For SYM_EQUS
/* For SYM_EQUS */
char const *(*strCallback)(void);
};
uint32_t ID; // ID of the symbol in the object file (-1 if none)
struct Symbol *next; // Next object to output in the object file
uint32_t ID; /* ID of the symbol in the object file (-1 if none) */
struct Symbol *next; /* Next object to output in the object file */
};
bool sym_IsPC(struct Symbol const *sym);
@@ -92,7 +98,9 @@ static inline bool sym_IsExported(struct Symbol const *sym)
return sym->isExported;
}
// Get a string equate's value
/*
* Get a string equate's value
*/
static inline char const *sym_GetStringValue(struct Symbol const *sym)
{
if (sym->hasCallback)
@@ -115,12 +123,18 @@ struct Symbol *sym_AddVar(char const *symName, int32_t value);
uint32_t sym_GetPCValue(void);
uint32_t sym_GetConstantSymValue(struct Symbol const *sym);
uint32_t sym_GetConstantValue(char const *symName);
// Find a symbol by exact name, bypassing expansion checks
/*
* Find a symbol by exact name, bypassing expansion checks
*/
struct Symbol *sym_FindExactSymbol(char const *symName);
// Find a symbol, possibly scoped, by name
/*
* Find a symbol by exact name; may not be scoped, produces an error if it is
*/
struct Symbol *sym_FindUnscopedSymbol(char const *symName);
/*
* Find a symbol, possibly scoped, by name
*/
struct Symbol *sym_FindScopedSymbol(char const *symName);
// Find a scoped symbol by name; do not return `@` or `_NARG` when they have no value
struct Symbol *sym_FindScopedValidSymbol(char const *symName);
struct Symbol const *sym_GetPC(void);
struct Symbol *sym_AddMacro(char const *symName, int32_t defLineNo, char *body, size_t size);
struct Symbol *sym_Ref(char const *symName);
@@ -129,8 +143,8 @@ struct Symbol *sym_RedefString(char const *symName, char const *value);
void sym_Purge(char const *symName);
void sym_Init(time_t now);
// Functions to save and restore the current symbol scope.
/* Functions to save and restore the current symbol scope. */
char const *sym_GetCurrentSymbolScope(void);
void sym_SetCurrentSymbolScope(char const *newScope);
#endif // RGBDS_SYMBOL_H
#endif /* RGBDS_SYMBOL_H */

View File

@@ -1,9 +1,14 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_UTIL_H
#define RGBDS_UTIL_H
#include <stddef.h>
#include <stdint.h>
char const *printChar(int c);
@@ -13,4 +18,4 @@ char const *printChar(int c);
*/
size_t readUTF8Char(uint8_t *dest, char const *src);
#endif // RGBDS_UTIL_H
#endif /* RGBDS_UTIL_H */

View File

@@ -1,11 +1,17 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 2019, Eldred Habert and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef WARNING_H
#define WARNING_H
#include "helpers.hpp"
#include "helpers.h"
extern unsigned int nbErrors, maxErrors;
extern unsigned int nbErrors;
enum WarningState {
WARNING_DEFAULT,
@@ -18,7 +24,7 @@ enum WarningID {
WARNING_ASSERT, // Assertions
WARNING_BACKWARDS_FOR, // `for` loop with backwards range
WARNING_BUILTIN_ARG, // Invalid args to builtins
WARNING_CHARMAP_REDEF, // Charmap entry re-definition
WARNING_CHARMAP_REDEF, // Charmap entry re-definition
WARNING_DIV, // Division undefined behavior
WARNING_EMPTY_DATA_DIRECTIVE, // `db`, `dw` or `dl` directive without data in ROM
WARNING_EMPTY_MACRO_ARG, // Empty macro argument
@@ -42,9 +48,6 @@ enum WarningID {
// Implicit truncation loses some bits
WARNING_TRUNCATION_1,
WARNING_TRUNCATION_2,
// Character without charmap entry
WARNING_UNMAPPED_CHAR_1,
WARNING_UNMAPPED_CHAR_2,
NB_PLAIN_AND_PARAM_WARNINGS,
#define NB_PARAM_WARNINGS (NB_PLAIN_AND_PARAM_WARNINGS - PARAM_WARNINGS_START)
@@ -77,7 +80,7 @@ void warning(enum WarningID id, char const *fmt, ...) format_(printf, 2, 3);
* It is also used when the assembler goes into an invalid state (for example,
* when it fails to allocate memory).
*/
[[noreturn]] void fatalerror(char const *fmt, ...) format_(printf, 1, 2);
_Noreturn void fatalerror(char const *fmt, ...) format_(printf, 1, 2);
/*
* Used for errors that make it impossible to assemble correctly, but don't
@@ -87,4 +90,4 @@ void warning(enum WarningID id, char const *fmt, ...) format_(printf, 2, 3);
*/
void error(char const *fmt, ...) format_(printf, 1, 2);
#endif // WARNING_H
#endif

View File

@@ -1,39 +0,0 @@
/*
* Allocator adaptor that interposes construct() calls to convert value-initialization
* (which is what you get with e.g. `vector::resize`) into default-initialization (which does not
* zero out non-class types).
* From
* https://stackoverflow.com/questions/21028299/is-this-behavior-of-vectorresizesize-type-n-under-c11-and-boost-container/21028912#21028912
*/
#ifndef DEFAULT_INIT_ALLOC_H
#define DEFAULT_INIT_ALLOC_H
#include <memory>
#include <vector>
template<typename T, typename A = std::allocator<T>>
class default_init_allocator : public A {
using a_t = std::allocator_traits<A>;
public:
template<typename U>
struct rebind {
using other = default_init_allocator<U, typename a_t::template rebind_alloc<U>>;
};
using A::A; // Inherit the allocator's constructors
template<typename U>
void construct(U *ptr) noexcept(std::is_nothrow_default_constructible_v<U>) {
::new (static_cast<void *>(ptr)) U;
}
template<typename U, typename... Args>
void construct(U *ptr, Args &&...args) {
a_t::construct(static_cast<A &>(*this), ptr, std::forward<Args>(args)...);
}
};
template<typename T>
using DefaultInitVec = std::vector<T, default_init_allocator<T>>;
#endif // DEFAULT_INIT_ALLOC_H

21
include/error.h Normal file
View File

@@ -0,0 +1,21 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2021, RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_ERROR_H
#define RGBDS_ERROR_H
#include "helpers.h"
#include "platform.h"
void warn(char const NONNULL(fmt), ...) format_(printf, 1, 2);
void warnx(char const NONNULL(fmt), ...) format_(printf, 1, 2);
_Noreturn void err(char const NONNULL(fmt), ...) format_(printf, 1, 2);
_Noreturn void errx(char const NONNULL(fmt), ...) format_(printf, 1, 2);
#endif /* RGBDS_ERROR_H */

View File

@@ -1,19 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_ERROR_H
#define RGBDS_ERROR_H
#include "helpers.hpp"
#include "platform.hpp"
extern "C" {
void warn(char const NONNULL(fmt), ...) format_(printf, 1, 2);
void warnx(char const NONNULL(fmt), ...) format_(printf, 1, 2);
[[noreturn]] void err(char const NONNULL(fmt), ...) format_(printf, 1, 2);
[[noreturn]] void errx(char const NONNULL(fmt), ...) format_(printf, 1, 2);
}
#endif // RGBDS_ERROR_H

46
include/extern/getopt.h vendored Normal file
View File

@@ -0,0 +1,46 @@
/*
* Copyright © 2005-2020 Rich Felker, et al.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* This implementation was taken from musl and modified for RGBDS */
#ifndef RGBDS_EXTERN_GETOPT_H
#define RGBDS_EXTERN_GETOPT_H
extern char *musl_optarg;
extern int musl_optind, musl_opterr, musl_optopt, musl_optreset;
struct option {
char const *name;
int has_arg;
int *flag;
int val;
};
int musl_getopt_long_only(int argc, char **argv, char const *optstring,
const struct option *longopts, int *idx);
#define no_argument 0
#define required_argument 1
#define optional_argument 2
#endif

View File

@@ -1,29 +0,0 @@
/* SPDX-License-Identifier: MIT */
/* This implementation was taken from musl and modified for RGBDS */
#ifndef RGBDS_EXTERN_GETOPT_H
#define RGBDS_EXTERN_GETOPT_H
extern "C" {
extern char *musl_optarg;
extern int musl_optind, musl_opterr, musl_optopt, musl_optreset;
struct option {
char const *name;
int has_arg;
int *flag;
int val;
};
int musl_getopt_long_only(int argc, char **argv, char const *optstring,
const struct option *longopts, int *idx);
#define no_argument 0
#define required_argument 1
#define optional_argument 2
} // extern "C"
#endif

14
include/extern/utf8decoder.h vendored Normal file
View File

@@ -0,0 +1,14 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2018, Antonio Nino Diaz and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef EXTERN_UTF8DECODER_H
#define EXTERN_UTF8DECODER_H
uint32_t decode(uint32_t *state, uint32_t *codep, uint8_t byte);
#endif /* EXTERN_UTF8DECODER_H */

View File

@@ -1,8 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef EXTERN_UTF8DECODER_H
#define EXTERN_UTF8DECODER_H
uint32_t decode(uint32_t *state, uint32_t *codep, uint8_t byte);
#endif // EXTERN_UTF8DECODER_H

View File

@@ -1,98 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_FILE_HPP
#define RGBDS_FILE_HPP
#include <array>
#include <assert.h>
#include <cassert>
#include <fcntl.h>
#include <fstream>
#include <ios>
#include <iostream>
#include <streambuf>
#include <string>
#include <string.h>
#include <string_view>
#include <variant>
#include "helpers.hpp"
#include "platform.hpp"
#include "gfx/main.hpp"
// Convenience feature for visiting the below.
template<typename... Ts>
struct Visitor : Ts... {
using Ts::operator()...;
};
template<typename... Ts>
Visitor(Ts...) -> Visitor<Ts...>;
class File {
// Construct a `std::streambuf *` by default, since it's probably lighter than a `filebuf`.
std::variant<std::streambuf *, std::filebuf> _file;
public:
File() {}
~File() { close(); }
/**
* This should only be called once, and before doing any `->` operations.
* Returns `nullptr` on error, and a non-null pointer otherwise.
*/
File *open(std::string const &path, std::ios_base::openmode mode) {
if (path != "-") {
return _file.emplace<std::filebuf>().open(path, mode) ? this : nullptr;
} else if (mode & std::ios_base::in) {
assert(!(mode & std::ios_base::out));
_file.emplace<std::streambuf *>(std::cin.rdbuf());
if (setmode(STDIN_FILENO, mode & std::ios_base::binary ? O_BINARY : O_TEXT) == -1) {
fatal("Failed to set stdin to %s mode: %s",
mode & std::ios_base::binary ? "binary" : "text", strerror(errno));
}
} else {
assert(mode & std::ios_base::out);
_file.emplace<std::streambuf *>(std::cout.rdbuf());
}
return this;
}
std::streambuf &operator*() {
return std::visit(Visitor{[](std::filebuf &file) -> std::streambuf & { return file; },
[](std::streambuf *buf) -> std::streambuf & { return *buf; }},
_file);
}
std::streambuf const &operator*() const {
// The non-`const` version does not perform any modifications, so it's okay.
return **const_cast<File *>(this);
}
std::streambuf *operator->() { return &**this; }
std::streambuf const *operator->() const {
// See the `operator*` equivalent.
return const_cast<File *>(this)->operator->();
}
File *close() {
return std::visit(Visitor{[this](std::filebuf &file) {
// This is called by the destructor, and an explicit `close`
// shouldn't close twice.
_file.emplace<std::streambuf *>(nullptr);
return file.close() != nullptr;
},
[](std::streambuf *buf) { return buf != nullptr; }},
_file)
? this
: nullptr;
}
char const *c_str(std::string const &path) const {
return std::visit(Visitor{[&path](std::filebuf const &) { return path.c_str(); },
[](std::streambuf const *buf) {
return buf == std::cin.rdbuf()
? "<stdin>" : "<stdout>";
}},
_file);
}
};
#endif // RGBDS_FILE_HPP

36
include/gfx/gb.h Normal file
View File

@@ -0,0 +1,36 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2013-2018, stag019 and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_GFX_GB_H
#define RGBDS_GFX_GB_H
#include <stdint.h>
#include "gfx/main.h"
#define XFLIP 0x40
#define YFLIP 0x20
void raw_to_gb(const struct RawIndexedImage *raw_image, struct GBImage *gb);
void output_file(const struct Options *opts, const struct GBImage *gb);
int get_tile_index(uint8_t *tile, uint8_t **tiles, int num_tiles,
int tile_size);
uint8_t reverse_bits(uint8_t b);
void xflip(uint8_t *tile, uint8_t *tile_xflip, int tile_size);
void yflip(uint8_t *tile, uint8_t *tile_yflip, int tile_size);
int get_mirrored_tile_index(uint8_t *tile, uint8_t **tiles, int num_tiles,
int tile_size, int *flags);
void create_mapfiles(const struct Options *opts, struct GBImage *gb,
struct Mapfile *tilemap, struct Mapfile *attrmap);
void output_tilemap_file(const struct Options *opts,
const struct Mapfile *tilemap);
void output_attrmap_file(const struct Options *opts,
const struct Mapfile *attrmap);
void output_palette_file(const struct Options *opts,
const struct RawIndexedImage *raw_image);
#endif

91
include/gfx/main.h Normal file
View File

@@ -0,0 +1,91 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2013-2018, stag019 and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_GFX_MAIN_H
#define RGBDS_GFX_MAIN_H
#include <png.h>
#include <stdbool.h>
#include <stdint.h>
#include "error.h"
struct Options {
bool debug;
bool verbose;
bool hardfix;
bool fix;
bool horizontal;
bool mirror;
bool unique;
bool colorcurve;
unsigned int trim;
char *tilemapfile;
bool tilemapout;
char *attrmapfile;
bool attrmapout;
char *palfile;
bool palout;
char *outfile;
char *infile;
};
struct RGBColor {
uint8_t red;
uint8_t green;
uint8_t blue;
};
struct ImageOptions {
bool horizontal;
unsigned int trim;
char *tilemapfile;
bool tilemapout;
char *attrmapfile;
bool attrmapout;
char *palfile;
bool palout;
};
struct PNGImage {
png_struct *png;
png_info *info;
png_byte **data;
int width;
int height;
png_byte depth;
png_byte type;
};
struct RawIndexedImage {
uint8_t **data;
struct RGBColor *palette;
int num_colors;
unsigned int width;
unsigned int height;
};
struct GBImage {
uint8_t *data;
int size;
bool horizontal;
int trim;
};
struct Mapfile {
uint8_t *data;
int size;
};
extern int depth, colors;
#include "gfx/makepng.h"
#include "gfx/gb.h"
#endif /* RGBDS_GFX_MAIN_H */

View File

@@ -1,118 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_GFX_MAIN_HPP
#define RGBDS_GFX_MAIN_HPP
#include <array>
#include <limits.h>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
#include "helpers.hpp"
#include "gfx/rgba.hpp"
struct Options {
uint16_t reversedWidth = 0; // -r, in tiles
bool reverse() const { return reversedWidth != 0; }
bool useColorCurve = false; // -C
bool allowMirroring = false; // -m
bool allowDedup = false; // -u
bool columnMajor = false; // -Z, previously -h
uint8_t verbosity = 0; // -v
std::string attrmap{}; // -a, -A
std::array<uint8_t, 2> baseTileIDs{0, 0}; // -b
enum {
NO_SPEC,
EXPLICIT,
EMBEDDED,
} palSpecType = NO_SPEC; // -c
std::vector<std::array<Rgba, 4>> palSpec{};
uint8_t bitDepth = 2; // -d
struct {
uint16_t left;
uint16_t top;
uint16_t width;
uint16_t height;
} inputSlice{0, 0, 0, 0}; // -L (margins in clockwise order, like CSS)
std::array<uint16_t, 2> maxNbTiles{UINT16_MAX, 0}; // -N
uint8_t nbPalettes = 8; // -n
std::string output{}; // -o
std::string palettes{}; // -p, -P
std::string palmap{}; // -q, -Q
uint8_t nbColorsPerPal = 0; // -s; 0 means "auto" = 1 << bitDepth;
std::string tilemap{}; // -t, -T
uint64_t trim = 0; // -x
std::string input{}; // positional arg
static constexpr uint8_t VERB_NONE = 0; // Normal, no extra output
static constexpr uint8_t VERB_CFG = 1; // Print configuration after parsing options
static constexpr uint8_t VERB_LOG_ACT = 2; // Log actions before doing them
static constexpr uint8_t VERB_INTERM = 3; // Print some intermediate results
static constexpr uint8_t VERB_DEBUG = 4; // Internals are logged
static constexpr uint8_t VERB_UNMAPPED = 5; // Unused so far
static constexpr uint8_t VERB_VVVVVV = 6; // What, can't I have a little fun?
format_(printf, 3, 4) void verbosePrint(uint8_t level, char const *fmt, ...) const;
mutable bool hasTransparentPixels = false;
uint8_t maxOpaqueColors() const { return nbColorsPerPal - hasTransparentPixels; }
};
extern Options options;
/*
* Prints the error count, and exits with failure
*/
[[noreturn]] void giveUp();
/*
* Prints a warning, and does not change the error count
*/
void warning(char const *fmt, ...);
/*
* Prints an error, and increments the error count
*/
void error(char const *fmt, ...);
/*
* Prints a fatal error, increments the error count, and gives up
*/
[[noreturn]] void fatal(char const *fmt, ...);
struct Palette {
// An array of 4 GBC-native (RGB555) colors
std::array<uint16_t, 4> colors{UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX};
void addColor(uint16_t color);
uint8_t indexOf(uint16_t color) const;
uint16_t &operator[](size_t index) { return colors[index]; }
uint16_t const &operator[](size_t index) const { return colors[index]; }
decltype(colors)::iterator begin();
decltype(colors)::iterator end();
decltype(colors)::const_iterator begin() const;
decltype(colors)::const_iterator end() const;
uint8_t size() const;
};
namespace detail {
template<typename T, T... i>
static constexpr auto flipTable(std::integer_sequence<T, i...>) {
return std::array{[](uint8_t byte) {
// To flip all the bits, we'll flip both nibbles, then each nibble half, etc.
byte = (byte & 0b0000'1111) << 4 | (byte & 0b1111'0000) >> 4;
byte = (byte & 0b0011'0011) << 2 | (byte & 0b1100'1100) >> 2;
byte = (byte & 0b0101'0101) << 1 | (byte & 0b1010'1010) >> 1;
return byte;
}(i)...};
}
} // namespace detail
// Flipping tends to happen fairly often, so take a bite out of dcache to speed it up
static constexpr auto flipTable = detail::flipTable(std::make_integer_sequence<uint16_t, 256>());
#endif // RGBDS_GFX_MAIN_HPP

21
include/gfx/makepng.h Normal file
View File

@@ -0,0 +1,21 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2013-2018, stag019 and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_GFX_PNG_H
#define RGBDS_GFX_PNG_H
#include "gfx/main.h"
struct RawIndexedImage *input_png_file(const struct Options *opts,
struct ImageOptions *png_options);
void output_png_file(const struct Options *opts,
const struct ImageOptions *png_options,
const struct RawIndexedImage *raw_image);
void destroy_raw_image(struct RawIndexedImage **raw_image_ptr_ptr);
#endif /* RGBDS_GFX_PNG_H */

View File

@@ -1,26 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_GFX_PAL_PACKING_HPP
#define RGBDS_GFX_PAL_PACKING_HPP
#include <tuple>
#include <vector>
#include "defaultinitalloc.hpp"
#include "gfx/main.hpp"
struct Palette;
class ProtoPalette;
namespace packing {
/*
* Returns which palette each proto-palette maps to, and how many palettes are necessary
*/
std::tuple<DefaultInitVec<size_t>, size_t>
overloadAndRemove(std::vector<ProtoPalette> const &protoPalettes);
} // namespace packing
#endif // RGBDS_GFX_PAL_PACKING_HPP

View File

@@ -1,26 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_GFX_PAL_SORTING_HPP
#define RGBDS_GFX_PAL_SORTING_HPP
#include <array>
#include <assert.h>
#include <optional>
#include <png.h>
#include <vector>
#include "gfx/rgba.hpp"
struct Palette;
namespace sorting {
void indexed(std::vector<Palette> &palettes, int palSize, png_color const *palRGB,
int palAlphaSize, png_byte *palAlpha);
void grayscale(std::vector<Palette> &palettes,
std::array<std::optional<Rgba>, 0x8001> const &colors);
void rgb(std::vector<Palette> &palettes);
} // namespace sorting
#endif // RGBDS_GFX_PAL_SORTING_HPP

View File

@@ -1,9 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_GFX_PAL_SPEC_HPP
#define RGBDS_GFX_PAL_SPEC_HPP
void parseInlinePalSpec(char const * const arg);
void parseExternalPalSpec(char const *arg);
#endif // RGBDS_GFX_PAL_SPEC_HPP

View File

@@ -1,9 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_GFX_CONVERT_HPP
#define RGBDS_GFX_CONVERT_HPP
void processPalettes();
void process();
#endif // RGBDS_GFX_CONVERT_HPP

View File

@@ -1,43 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_GFX_PROTO_PALETTE_HPP
#define RGBDS_GFX_PROTO_PALETTE_HPP
#include <algorithm>
#include <array>
#include <stddef.h>
#include <stdint.h>
class ProtoPalette {
public:
static constexpr size_t capacity = 4;
private:
// Up to 4 colors, sorted, and where SIZE_MAX means the slot is empty
// (OK because it's not a valid color index)
// Sorting is done on the raw numerical values to lessen `compare`'s complexity
std::array<uint16_t, capacity> _colorIndices{UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX};
public:
/*
* Adds the specified color to the set, or **silently drops it** if the set is full.
*
* Returns whether the color was unique.
*/
bool add(uint16_t color);
enum ComparisonResult {
NEITHER,
WE_BIGGER,
THEY_BIGGER = -1,
};
ComparisonResult compare(ProtoPalette const &other) const;
size_t size() const;
bool empty() const;
decltype(_colorIndices)::const_iterator begin() const;
decltype(_colorIndices)::const_iterator end() const;
};
#endif // RGBDS_GFX_PROTO_PALETTE_HPP

View File

@@ -1,8 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_GFX_REVERSE_HPP
#define RGBDS_GFX_REVERSE_HPP
void reverse();
#endif // RGBDS_GFX_REVERSE_HPP

View File

@@ -1,62 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_GFX_RGBA_HPP
#define RGBDS_GFX_RGBA_HPP
#include <cstdint>
#include <stdint.h>
struct Rgba {
uint8_t red;
uint8_t green;
uint8_t blue;
uint8_t alpha;
constexpr Rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
: red(r), green(g), blue(b), alpha(a) {}
/*
* Constructs the color from a "packed" RGBA representation (0xRRGGBBAA)
*/
explicit constexpr Rgba(uint32_t rgba = 0)
: red(rgba >> 24), green(rgba >> 16), blue(rgba >> 8), alpha(rgba) {}
static constexpr Rgba fromCGBColor(uint16_t cgbColor) {
constexpr auto _5to8 = [](uint8_t fiveBpp) -> uint8_t {
fiveBpp &= 0b11111; // For caller's convenience
return fiveBpp << 3 | fiveBpp >> 2;
};
return {_5to8(cgbColor), _5to8(cgbColor >> 5), _5to8(cgbColor >> 10),
(uint8_t)(cgbColor & 0x8000 ? 0x00 : 0xFF)};
}
/*
* Returns this RGBA as a 32-bit number that can be printed in hex (`%08x`) to yield its CSS
* representation
*/
uint32_t toCSS() const {
auto shl = [](uint8_t val, unsigned shift) { return static_cast<uint32_t>(val) << shift; };
return shl(red, 24) | shl(green, 16) | shl(blue, 8) | shl(alpha, 0);
}
friend bool operator==(Rgba const &lhs, Rgba const &rhs) { return lhs.toCSS() == rhs.toCSS(); }
friend bool operator!=(Rgba const &lhs, Rgba const &rhs) { return lhs.toCSS() != rhs.toCSS(); }
/*
* CGB colors are RGB555, so we use bit 15 to signify that the color is transparent instead
* Since the rest of the bits don't matter then, we return 0x8000 exactly.
*/
static constexpr uint16_t transparent = 0b1'00000'00000'00000;
static constexpr uint8_t transparency_threshold = 0x10;
bool isTransparent() const { return alpha < transparency_threshold; }
static constexpr uint8_t opacity_threshold = 0xF0;
bool isOpaque() const { return alpha >= opacity_threshold; }
/*
* Computes the equivalent CGB color, respects the color curve depending on options
*/
uint16_t cgbColor() const;
bool isGray() const { return red == green && green == blue; }
uint8_t grayIndex() const;
};
#endif // RGBDS_GFX_RGBA_HPP

View File

@@ -1,6 +1,12 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Generic hashmap implementation (C++ templates are calling...)
/* Generic hashmap implementation (C++ templates are calling...) */
#ifndef RGBDS_LINK_HASHMAP_H
#define RGBDS_LINK_HASHMAP_H
@@ -12,10 +18,10 @@
static_assert(HALF_HASH_NB_BITS * 2 == HASH_NB_BITS, "");
#define HASHMAP_NB_BUCKETS (1 << HALF_HASH_NB_BITS)
// HashMapEntry is internal, please do not attempt to use it
/* HashMapEntry is internal, please do not attempt to use it */
typedef struct HashMapEntry *HashMap[HASHMAP_NB_BUCKETS];
/*
/**
* Adds an element to a hashmap.
* @warning Adding a new element with an already-present key will not cause an
* error, this must be handled externally.
@@ -27,7 +33,7 @@ typedef struct HashMapEntry *HashMap[HASHMAP_NB_BUCKETS];
*/
void **hash_AddElement(HashMap map, char const *key, void *element);
/*
/**
* Removes an element from a hashmap.
* @param map The HashMap to remove the element from
* @param key The key to search the element with
@@ -35,7 +41,7 @@ void **hash_AddElement(HashMap map, char const *key, void *element);
*/
bool hash_RemoveElement(HashMap map, char const *key);
/*
/**
* Finds an element in a hashmap, and returns a pointer to its value field.
* @param map The map to consider the elements of
* @param key The key to search an element for
@@ -43,7 +49,7 @@ bool hash_RemoveElement(HashMap map, char const *key);
*/
void **hash_GetNode(HashMap const map, char const *key);
/*
/**
* Finds an element in a hashmap.
* @param map The map to consider the elements of
* @param key The key to search an element for
@@ -52,7 +58,7 @@ void **hash_GetNode(HashMap const map, char const *key);
*/
void *hash_GetElement(HashMap const map, char const *key);
/*
/**
* Executes a function on each element in a hashmap.
* @param map The map to consider the elements of
* @param func The function to run. The first argument will be the element,
@@ -61,11 +67,11 @@ void *hash_GetElement(HashMap const map, char const *key);
*/
void hash_ForEach(HashMap const map, void (*func)(void *, void *), void *arg);
/*
/**
* Cleanly empties a hashmap from its contents.
* This does not `free` the data structure itself!
* @param map The map to empty
*/
void hash_EmptyMap(HashMap map);
#endif // RGBDS_LINK_HASHMAP_H
#endif /* RGBDS_LINK_HASHMAP_H */

View File

@@ -1,8 +1,19 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 2014-2020, RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef HELPERS_H
#define HELPERS_H
// Of course, MSVC does not support C11, so no _Noreturn there...
#ifdef _MSC_VER
#define _Noreturn __declspec(noreturn)
#endif
// Ideally, we'd use `__has_attribute` and `__has_builtin`, but these were only introduced in GCC 9
#ifdef __GNUC__ // GCC or compatible
#define format_(archetype, str_index, first_arg) \
@@ -19,8 +30,8 @@
#define format_(archetype, str_index, first_arg)
#define attr_(...)
// This seems to generate similar code to __builtin_unreachable, despite different semantics
// Note that executing this is undefined behavior (declared [[noreturn]], but does return)
[[noreturn]] static inline void unreachable_(void) {}
// Note that executing this is undefined behavior (declared _Noreturn, but does return)
static inline _Noreturn unreachable_(void) {}
#endif
// Use builtins whenever possible, and shim them otherwise
@@ -82,7 +93,4 @@
// (Having two instances of `arr` is OK because the contents of `sizeof` are not evaluated.)
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof *(arr))
// For lack of <ranges>, this adds some more brevity
#define RANGE(s) std::begin(s), std::end(s)
#endif // HELPERS_H
#endif /* HELPERS_H */

View File

@@ -1,120 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef RGBDS_ITERTOOLS_HPP
#define RGBDS_ITERTOOLS_HPP
#include <tuple>
#include <utility>
#include "platform.hpp" // __PRETTY_FUNCTION__
template<typename... Ts>
static inline void report() {
puts(__PRETTY_FUNCTION__);
}
template<typename T>
class EnumSeqIterator {
T _value;
public:
explicit EnumSeqIterator(T value) : _value(value) {}
EnumSeqIterator &operator++() {
_value = (T)(_value + 1);
return *this;
}
auto operator*() const { return _value; }
friend auto operator==(EnumSeqIterator const &lhs, EnumSeqIterator const &rhs) {
return lhs._value == rhs._value;
}
friend auto operator!=(EnumSeqIterator const &lhs, EnumSeqIterator const &rhs) {
return lhs._value != rhs._value;
}
};
template<typename T>
class EnumSeq {
T _start;
T _stop;
public:
explicit EnumSeq(T stop) : _start((T)0), _stop(stop) {}
explicit EnumSeq(T start, T stop) : _start(start), _stop(stop) {}
EnumSeqIterator<T> begin() { return EnumSeqIterator(_start); }
EnumSeqIterator<T> end() { return EnumSeqIterator(_stop); }
};
// This is not a fully generic implementation; its current use cases only require for-loop behavior.
// We also assume that all iterators have the same length.
template<typename... Iters>
class Zip {
std::tuple<Iters...> _iters;
public:
explicit Zip(std::tuple<Iters...> &&iters) : _iters(iters) {}
Zip &operator++() {
std::apply([](auto &&...it) { (++it, ...); }, _iters);
return *this;
}
auto operator*() const {
return std::apply([](auto &&...it) { return std::tuple<decltype(*it)...>(*it...); },
_iters);
}
friend auto operator==(Zip const &lhs, Zip const &rhs) {
return std::get<0>(lhs._iters) == std::get<0>(rhs._iters);
}
friend auto operator!=(Zip const &lhs, Zip const &rhs) {
return std::get<0>(lhs._iters) != std::get<0>(rhs._iters);
}
};
namespace detail {
template<typename... Containers>
class ZipContainer {
std::tuple<Containers...> _containers;
public:
ZipContainer(Containers &&...containers)
: _containers(std::forward<Containers>(containers)...) {}
auto begin() {
return Zip(std::apply(
[](auto &&...containers) {
using std::begin;
return std::make_tuple(begin(containers)...);
},
_containers));
}
auto end() {
return Zip(std::apply(
[](auto &&...containers) {
using std::end;
return std::make_tuple(end(containers)...);
},
_containers));
}
};
// Take ownership of objects and rvalue refs passed to us, but not lvalue refs
template<typename T>
using Holder = std::conditional_t<std::is_lvalue_reference_v<T>, T,
std::remove_cv_t<std::remove_reference_t<T>>>;
} // namespace detail
// Does the same number of iterations as the first container's iterator!
template<typename... Containers>
static constexpr auto zip(Containers &&...cs) {
return detail::ZipContainer<detail::Holder<Containers>...>(std::forward<Containers>(cs)...);
}
#endif // RGBDS_ITERTOOLS_HPP

27
include/link/assign.h Normal file
View File

@@ -0,0 +1,27 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
/* Assigning all sections a place */
#ifndef RGBDS_LINK_ASSIGN_H
#define RGBDS_LINK_ASSIGN_H
#include <stdint.h>
extern uint64_t nbSectionsToAssign;
/**
* Assigns all sections a slice of the address space
*/
void assign_AssignSections(void);
/**
* `free`s all assignment memory that was allocated.
*/
void assign_Cleanup(void);
#endif /* RGBDS_LINK_ASSIGN_H */

View File

@@ -1,17 +0,0 @@
/* SPDX-License-Identifier: MIT */
// Assigning all sections a place
#ifndef RGBDS_LINK_ASSIGN_H
#define RGBDS_LINK_ASSIGN_H
#include <stdint.h>
extern uint64_t nbSectionsToAssign;
// Assigns all sections a slice of the address space
void assign_AssignSections(void);
// `free`s all assignment memory that was allocated
void assign_Cleanup(void);
#endif // RGBDS_LINK_ASSIGN_H

View File

@@ -1,6 +1,12 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Declarations that all modules use, as well as `main` and related
/* Declarations that all modules use, as well as `main` and related */
#ifndef RGBDS_LINK_MAIN_H
#define RGBDS_LINK_MAIN_H
@@ -8,14 +14,12 @@
#include <stdbool.h>
#include <stdio.h>
#include "helpers.hpp"
#include "linkdefs.hpp"
#include "helpers.h"
// Variables related to CLI options
/* Variables related to CLI options */
extern bool isDmgMode;
extern char *linkerScriptName;
extern char const *mapFileName;
extern bool noSymInMap;
extern char const *symFileName;
extern char const *overlayFileName;
extern char const *outputFileName;
@@ -30,26 +34,30 @@ extern bool disablePadding;
struct FileStackNode {
struct FileStackNode *parent;
// Line at which the parent context was exited; meaningless for the root level
/* Line at which the parent context was exited; meaningless for the root level */
uint32_t lineNo;
enum FileStackNodeType type;
enum {
NODE_REPT,
NODE_FILE,
NODE_MACRO,
} type;
union {
char *name; // NODE_FILE, NODE_MACRO
struct { // NODE_REPT
char *name; /* NODE_FILE, NODE_MACRO */
struct { /* NODE_REPT */
uint32_t reptDepth;
uint32_t *iters;
};
};
};
// Helper macro for printing verbose-mode messages
/* Helper macro for printing verbose-mode messages */
#define verbosePrint(...) do { \
if (beVerbose) \
fprintf(stderr, __VA_ARGS__); \
} while (0)
/*
/**
* Dump a file stack to stderr
* @param node The leaf node to dump the context of
*/
@@ -61,10 +69,10 @@ void warning(struct FileStackNode const *where, uint32_t lineNo,
void error(struct FileStackNode const *where, uint32_t lineNo,
char const *fmt, ...) format_(printf, 3, 4);
[[noreturn]] void fatal(struct FileStackNode const *where, uint32_t lineNo,
_Noreturn void fatal(struct FileStackNode const *where, uint32_t lineNo,
char const *fmt, ...) format_(printf, 3, 4);
/*
/**
* Opens a file if specified, and aborts on error.
* @param fileName The name of the file to open; if NULL, no file will be opened
* @param mode The mode to open the file with
@@ -78,4 +86,4 @@ FILE *openFile(char const *fileName, char const *mode);
fclose(tmp); \
} while (0)
#endif // RGBDS_LINK_MAIN_H
#endif /* RGBDS_LINK_MAIN_H */

View File

@@ -1,36 +1,42 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Declarations related to processing of object (.o) files
/* Declarations related to processing of object (.o) files */
#ifndef RGBDS_LINK_OBJECT_H
#define RGBDS_LINK_OBJECT_H
/*
/**
* Read an object (.o) file, and add its info to the data structures.
* @param fileName A path to the object file to be read
* @param i The ID of the file
*/
void obj_ReadFile(char const *fileName, unsigned int i);
/*
/**
* Perform validation on the object files' contents
*/
void obj_DoSanityChecks(void);
/*
/**
* Evaluate all assertions
*/
void obj_CheckAssertions(void);
/*
/**
* Sets up object file reading
* @param nbFiles The number of object files that will be read
*/
void obj_Setup(unsigned int nbFiles);
/*
/**
* `free`s all object memory that was allocated.
*/
void obj_Cleanup(void);
#endif // RGBDS_LINK_OBJECT_H
#endif /* RGBDS_LINK_OBJECT_H */

View File

@@ -1,29 +1,35 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Outputting the result of linking
/* Outputting the result of linking */
#ifndef RGBDS_LINK_OUTPUT_H
#define RGBDS_LINK_OUTPUT_H
#include <stdint.h>
#include "link/section.hpp"
#include "link/section.h"
/*
/**
* Registers a section for output.
* @param section The section to add
*/
void out_AddSection(struct Section const *section);
/*
/**
* Finds an assigned section overlapping another one.
* @param section The section that is being overlapped
* @return A section overlapping it
*/
struct Section const *out_OverlappingSection(struct Section const *section);
/*
/**
* Writes all output (bin, sym, map) files.
*/
void out_WriteFiles(void);
#endif // RGBDS_LINK_OUTPUT_H
#endif /* RGBDS_LINK_OUTPUT_H */

View File

@@ -1,15 +1,21 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Applying patches to SECTIONs
/* Applying patches to SECTIONs */
#ifndef RGBDS_LINK_PATCH_H
#define RGBDS_LINK_PATCH_H
#include <stdbool.h>
#include <stdint.h>
#include "link/section.hpp"
#include "link/section.h"
#include "linkdefs.hpp"
#include "linkdefs.h"
struct Assertion {
struct Patch patch;
@@ -21,15 +27,15 @@ struct Assertion {
struct Assertion *next;
};
/*
/**
* Checks all assertions
* @return true if assertion failed
*/
void patch_CheckAssertions(struct Assertion *assertion);
/*
/**
* Applies all SECTIONs' patches to them
*/
void patch_ApplyPatches(void);
#endif // RGBDS_LINK_PATCH_H
#endif /* RGBDS_LINK_PATCH_H */

36
include/link/script.h Normal file
View File

@@ -0,0 +1,36 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
/* Parsing a linker script */
#ifndef RGBDS_LINK_SCRIPT_H
#define RGBDS_LINK_SCRIPT_H
#include <stdint.h>
extern FILE * linkerScript;
struct SectionPlacement {
struct Section *section;
uint16_t org;
uint32_t bank;
};
extern uint64_t script_lineNo;
/**
* Parses the linker script to return the next section constraint
* @return A pointer to a struct, or NULL on EOF. The pointer shouldn't be freed
*/
struct SectionPlacement *script_NextSection(void);
/**
* `free`s all assignment memory that was allocated.
*/
void script_Cleanup(void);
#endif /* RGBDS_LINK_SCRIPT_H */

View File

@@ -1,13 +0,0 @@
/* SPDX-License-Identifier: MIT */
// Assigning all sections a place
#ifndef RGBDS_LINK_SDAS_OBJ_H
#define RGBDS_LINK_SDAS_OBJ_H
#include <stdio.h>
struct FileStackNode;
void sdobj_ReadFile(struct FileStackNode const *fileName, FILE *file);
#endif // RGBDS_LINK_SDAS_OBJ_H

View File

@@ -1,17 +1,23 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Declarations manipulating symbols
/* Declarations manipulating symbols */
#ifndef RGBDS_LINK_SECTION_H
#define RGBDS_LINK_SECTION_H
// GUIDELINE: external code MUST NOT BE AWARE of the data structure used!
/* GUIDELINE: external code MUST NOT BE AWARE of the data structure used!! */
#include <stdint.h>
#include <stdbool.h>
#include "link/main.hpp"
#include "link/main.h"
#include "linkdefs.hpp"
#include "linkdefs.h"
struct FileStackNode;
struct Section;
@@ -35,29 +41,27 @@ struct Patch {
};
struct Section {
// Info contained in the object files
/* Info contained in the object files */
char *name;
uint16_t size;
uint16_t offset;
enum SectionType type;
enum SectionModifier modifier;
bool isAddressFixed;
// This `struct`'s address in ROM.
// Importantly for fragments, this does not include `offset`!
uint16_t org;
bool isBankFixed;
uint32_t bank;
bool isAlignFixed;
uint16_t alignMask;
uint16_t alignOfs;
uint8_t *data; // Array of size `size`
uint8_t *data; /* Array of size `size`*/
uint32_t nbPatches;
struct Patch *patches;
// Extra info computed during linking
/* Extra info computed during linking */
struct Symbol **fileSymbols;
uint32_t nbSymbols;
struct Symbol **symbols;
struct Section *nextu; // The next "component" of this unionized sect
struct Symbol const **symbols;
struct Section *nextu; /* The next "component" of this unionized sect */
};
/*
@@ -70,27 +74,27 @@ struct Section {
*/
void sect_ForEach(void (*callback)(struct Section *, void *), void *arg);
/*
/**
* Registers a section to be processed.
* @param section The section to register.
*/
void sect_AddSection(struct Section *section);
/*
/**
* Finds a section by its name.
* @param name The name of the section to look for
* @return A pointer to the section, or NULL if it wasn't found
*/
struct Section *sect_GetSection(char const *name);
/*
/**
* `free`s all section memory that was allocated.
*/
void sect_CleanupSections(void);
/*
/**
* Checks if all sections meet reasonable criteria, such as max size
*/
void sect_DoSanityChecks(void);
#endif // RGBDS_LINK_SECTION_H
#endif /* RGBDS_LINK_SECTION_H */

View File

@@ -1,19 +1,25 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2019, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Declarations manipulating symbols
/* Declarations manipulating symbols */
#ifndef RGBDS_LINK_SYMBOL_H
#define RGBDS_LINK_SYMBOL_H
// GUIDELINE: external code MUST NOT BE AWARE of the data structure used!
/* GUIDELINE: external code MUST NOT BE AWARE of the data structure used!! */
#include <stdint.h>
#include "linkdefs.hpp"
#include "linkdefs.h"
struct FileStackNode;
struct Symbol {
// Info contained in the object files
/* Info contained in the object files */
char *name;
enum ExportLevel type;
char const *objFileName;
@@ -21,11 +27,10 @@ struct Symbol {
int32_t lineNo;
int32_t sectionID;
union {
// Both types must be identical
int32_t offset;
int32_t value;
};
// Extra info computed during linking
/* Extra info computed during linking */
struct Section *section;
};
@@ -41,16 +46,16 @@ void sym_ForEach(void (*callback)(struct Symbol *, void *), void *arg);
void sym_AddSymbol(struct Symbol *symbol);
/*
/**
* Finds a symbol in all the defined symbols.
* @param name The name of the symbol to look for
* @return A pointer to the symbol, or NULL if not found.
*/
struct Symbol *sym_GetSymbol(char const *name);
/*
/**
* `free`s all symbol memory that was allocated.
*/
void sym_CleanupSymbols(void);
#endif // RGBDS_LINK_SYMBOL_H
#endif /* RGBDS_LINK_SYMBOL_H */

View File

@@ -1,14 +1,19 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2018, Carsten Sorensen and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_LINKDEFS_H
#define RGBDS_LINKDEFS_H
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <string>
#define RGBDS_OBJECT_VERSION_STRING "RGB9"
#define RGBDS_OBJECT_VERSION_STRING "RGB%1u"
#define RGBDS_OBJECT_VERSION_NUMBER 9U
#define RGBDS_OBJECT_REV 9U
enum AssertionType {
@@ -23,17 +28,17 @@ enum RPNCommand {
RPN_MUL = 0x02,
RPN_DIV = 0x03,
RPN_MOD = 0x04,
RPN_NEG = 0x05,
RPN_UNSUB = 0x05, // FIXME: should be renamed to "NEG" for consistency
RPN_EXP = 0x06,
RPN_OR = 0x10,
RPN_AND = 0x11,
RPN_XOR = 0x12,
RPN_NOT = 0x13,
RPN_UNNOT = 0x13, // FIXME: should be renamed to "NOT" for consistency
RPN_LOGAND = 0x21,
RPN_LOGOR = 0x22,
RPN_LOGNOT = 0x23,
RPN_LOGUNNOT = 0x23, // FIXME: should be renamed to "LOGNOT" for consistency
RPN_LOGEQ = 0x30,
RPN_LOGNE = 0x31,
@@ -51,8 +56,6 @@ enum RPNCommand {
RPN_BANK_SELF = 0x52,
RPN_SIZEOF_SECT = 0x53,
RPN_STARTOF_SECT = 0x54,
RPN_SIZEOF_SECTTYPE = 0x55,
RPN_STARTOF_SECTTYPE = 0x56,
RPN_HRAM = 0x60,
RPN_RST = 0x61,
@@ -71,56 +74,9 @@ enum SectionType {
SECTTYPE_SRAM,
SECTTYPE_OAM,
// In RGBLINK, this is used for "indeterminate" sections; this is primarily for SDCC
// areas, which do not carry any section type info and must be told from the linker script
SECTTYPE_INVALID
};
enum FileStackNodeType {
NODE_REPT,
NODE_FILE,
NODE_MACRO,
};
// Nont-`const` members may be patched in RGBLINK depending on CLI flags
extern struct SectionTypeInfo {
std::string const name;
uint16_t const startAddr;
uint16_t size;
uint32_t const firstBank;
uint32_t lastBank;
} sectionTypeInfo[SECTTYPE_INVALID];
/*
* Tells whether a section has data in its object file definition,
* depending on type.
* @param type The section's type
* @return `true` if the section's definition includes data
*/
static inline bool sect_HasData(enum SectionType type)
{
assert(type != SECTTYPE_INVALID);
return type == SECTTYPE_ROM0 || type == SECTTYPE_ROMX;
}
/*
* Computes a memory region's end address (last byte), eg. 0x7FFF
* @return The address of the last byte in that memory region
*/
static inline uint16_t endaddr(enum SectionType type)
{
return sectionTypeInfo[type].startAddr + sectionTypeInfo[type].size - 1;
}
/*
* Computes a memory region's number of banks
* @return The number of banks, 1 for regions without banking
*/
static inline uint32_t nbbanks(enum SectionType type)
{
return sectionTypeInfo[type].lastBank - sectionTypeInfo[type].firstBank + 1;
}
enum SectionModifier {
SECTION_NORMAL,
SECTION_UNION,
@@ -129,6 +85,17 @@ enum SectionModifier {
extern char const * const sectionModNames[];
/**
* Tells whether a section has data in its object file definition,
* depending on type.
* @param type The section's type
* @return `true` if the section's definition includes data
*/
static inline bool sect_HasData(enum SectionType type)
{
return type == SECTTYPE_ROM0 || type == SECTTYPE_ROMX;
}
enum ExportLevel {
SYMTYPE_LOCAL,
SYMTYPE_IMPORT,
@@ -144,4 +111,45 @@ enum PatchType {
PATCHTYPE_INVALID
};
#endif // RGBDS_LINKDEFS_H
#define BANK_MIN_ROM0 0
#define BANK_MAX_ROM0 0
#define BANK_MIN_ROMX 1
#define BANK_MAX_ROMX 511
#define BANK_MIN_VRAM 0
#define BANK_MAX_VRAM 1
#define BANK_MIN_SRAM 0
#define BANK_MAX_SRAM 15
#define BANK_MIN_WRAM0 0
#define BANK_MAX_WRAM0 0
#define BANK_MIN_WRAMX 1
#define BANK_MAX_WRAMX 7
#define BANK_MIN_OAM 0
#define BANK_MAX_OAM 0
#define BANK_MIN_HRAM 0
#define BANK_MAX_HRAM 0
extern uint16_t startaddr[];
extern uint16_t maxsize[];
extern uint32_t bankranges[][2];
/**
* Computes a memory region's end address (last byte), eg. 0x7FFF
* @return The address of the last byte in that memory region
*/
static inline uint16_t endaddr(enum SectionType type)
{
return startaddr[type] + maxsize[type] - 1;
}
/**
* Computes a memory region's number of banks
* @return The number of banks, 1 for regions without banking
*/
static inline uint32_t nbbanks(enum SectionType type)
{
return bankranges[type][1] - bankranges[type][0] + 1;
}
extern char const * const typeNames[SECTTYPE_INVALID];
#endif /* RGBDS_LINKDEFS_H */

View File

@@ -1,4 +1,10 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 1997-2021, RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGBDS_OP_MATH_H
#define RGBDS_OP_MATH_H
@@ -12,4 +18,4 @@ int32_t op_shift_left(int32_t value, int32_t amount);
int32_t op_shift_right(int32_t value, int32_t amount);
int32_t op_shift_right_unsigned(int32_t value, int32_t amount);
#endif // RGBDS_OP_MATH_H
#endif /* RGBDS_OP_MATH_H */

View File

@@ -1,6 +1,12 @@
/* SPDX-License-Identifier: MIT */
/*
* This file is part of RGBDS.
*
* Copyright (c) 2020 RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// platform-specific hacks
/* platform-specific hacks */
#ifndef RGBDS_PLATFORM_H
#define RGBDS_PLATFORM_H
@@ -14,29 +20,20 @@
# include <strings.h>
#endif
// MSVC has deprecated strdup in favor of _strdup
/* MSVC has deprecated strdup in favor of _strdup */
#ifdef _MSC_VER
# define strdup _strdup
#endif
// MSVC prefixes the names of S_* macros with underscores,
// and doesn't define any S_IS* macros; define them ourselves
/* MSVC prefixes the names of S_* macros with underscores,
and doesn't define any S_IS* macros. Define them ourselves */
#ifdef _MSC_VER
# define S_IFMT _S_IFMT
# define S_IFDIR _S_IFDIR
# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
// gcc has __PRETTY_FUNCTION__, MSVC has __FUNCSIG__, __func__ is standard
#ifndef __PRETTY_FUNCTION__
# ifdef __FUNCSIG__
# define __PRETTY_FUNCTION__ __FUNCSIG__
# else
# define __PRETTY_FUNCTION__ __func__
# endif
#endif
// MSVC doesn't use POSIX types or defines for `read`
/* MSVC doesn't use POSIX types or defines for `read` */
#ifdef _MSC_VER
# include <io.h>
# define STDIN_FILENO 0
@@ -49,17 +46,13 @@
# include <unistd.h>
#endif
// C++ doesn't support `[static N]` for array arguments from C99 or C11
#define MIN_NB_ELMS(N) // static (N)
#define ARR_QUALS(...) // __VA_ARGS__
#define NONNULL(ptr) *ptr // ptr[static 1]
#define restrict
// C++ doesn't support designated array initializers, but they're a gcc extension
#ifdef __GNUC__
# define AT(index) [index] =
/* MSVC doesn't support `[static N]` for array arguments from C99 */
#ifdef _MSC_VER
# define MIN_NB_ELMS(N)
# define NONNULL(ptr) *ptr
#else
# define AT(index)
# define MIN_NB_ELMS(N) static (N)
# define NONNULL(ptr) ptr[static 1]
#endif
// MSVC uses a different name for O_RDWR, and needs an additional _O_BINARY flag
@@ -68,10 +61,8 @@
# define O_RDWR _O_RDWR
# define S_ISREG(field) ((field) & _S_IFREG)
# define O_BINARY _O_BINARY
# define O_TEXT _O_TEXT
#elif !defined(O_BINARY) // Cross-compilers define O_BINARY
# define O_BINARY 0 // POSIX says we shouldn't care!
# define O_TEXT 0 // Assume that it's not defined either
#endif // _MSC_VER
// Windows has stdin and stdout open as text by default, which we may not want
@@ -79,7 +70,7 @@
# include <io.h>
# define setmode(fd, mode) _setmode(fd, mode)
#else
# define setmode(fd, mode) (0)
# define setmode(fd, mode) ((void)0)
#endif
#endif // RGBDS_PLATFORM_H
#endif /* RGBDS_PLATFORM_H */

18
include/version.h Normal file
View File

@@ -0,0 +1,18 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2017-2021, Antonio Nino Diaz and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#ifndef EXTERN_VERSION_H
#define EXTERN_VERSION_H
#define PACKAGE_VERSION_MAJOR 0
#define PACKAGE_VERSION_MINOR 5
#define PACKAGE_VERSION_PATCH 2
char const *get_package_version_string(void);
#endif /* EXTERN_VERSION_H */

View File

@@ -1,16 +0,0 @@
/* SPDX-License-Identifier: MIT */
#ifndef EXTERN_VERSION_H
#define EXTERN_VERSION_H
extern "C" {
#define PACKAGE_VERSION_MAJOR 0
#define PACKAGE_VERSION_MINOR 7
#define PACKAGE_VERSION_PATCH 0
char const *get_package_version_string(void);
}
#endif // EXTERN_VERSION_H

View File

@@ -1,416 +0,0 @@
.\" SPDX-License-Identifier: MIT
.\"
.Dd December 22, 2023
.Dt RGBDS 5
.Os
.Sh NAME
.Nm rgbds
.Nd object file format documentation
.Sh DESCRIPTION
This is the description of the object files used by
.Xr rgbasm 1
and
.Xr rgblink 1 .
.Em Please note that the specification is not stable yet.
RGBDS is still in active development, and some new features require adding more information to the object file, or modifying some fields, both of which break compatibility with older versions.
.Sh FILE STRUCTURE
The following types are used:
.Pp
.Cm LONG
is a 32-bit integer stored in little-endian format.
.Cm BYTE
is an 8-bit integer.
.Cm STRING
is a 0-terminated string of
.Cm BYTE .
Brackets after a type
.Pq e.g. Cm LONG Ns Bq Ar n
indicate
.Ar n
consecutive elements
.Pq here, Cm LONG Ns s .
All items are contiguous, with no padding anywhere\(emthis also means that they may not be aligned in the file!
.Pp
.Cm REPT Ar n
indicates that the fields between the
.Cm REPT
and corresponding
.Cm ENDR
are repeated
.Ar n
times.
.Pp
All IDs refer to objects within the file; for example, symbol ID $0001 refers to the second symbol defined in
.Em this
object file's
.Sx Symbols
array.
The only exception is the
.Sx Source file info
nodes, whose IDs are backwards, i.e. source node ID $0000 refers to the
.Em last
node in the array, not the first one.
References to other object files are made by imports (symbols), by name (sections), etc.\(embut never by ID.
.Ss Header
.Bl -tag -width Ds -compact
.It Cm BYTE Ar Magic[4]
"RGB9"
.It Cm LONG Ar RevisionNumber
The format's revision number this file uses.
.Pq This is always in the same place in all revisions.
.It Cm LONG Ar NumberOfSymbols
How many symbols are defined in this object file.
.It Cm LONG Ar NumberOfSections
How many sections are defined in this object file.
.El
.Ss Source file info
.Bl -tag -width Ds -compact
.It Cm LONG Ar NumberOfNodes
The number of source context nodes contained in this file.
.It Cm REPT Ar NumberOfNodes
.Bl -tag -width Ds -compact
.It Cm LONG Ar ParentID
ID of the parent node, -1 meaning that this is the root node.
.Pp
.Sy Important :
the nodes are actually written in
.Sy reverse
order, meaning the node with ID 0 is the last one in the list!
.It Cm LONG Ar ParentLineNo
Line at which the parent node's context was exited; meaningless for the root node.
.It Cm BYTE Ar Type
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta REPT node
.It 1 Ta File node
.It 2 Ta Macro node
.El
.It Cm IF Ar Type No \(!= 0
If the node is not a REPT node...
.Pp
.Bl -tag -width Ds -compact
.It Cm STRING Ar Name
The node's name: either a file name, or the macro's name prefixes by its definition's file name
.Pq e.g. Ql src/includes/defines.asm::error .
.El
.It Cm ELSE
If the node is a REPT, it also contains the iteration counter of all parent REPTs.
.Pp
.Bl -tag -width Ds -compact
.It Cm LONG Ar Depth
.It Cm LONG Ar Iter Ns Bq Ar Depth
The number of REPT iterations, by increasing depth.
.El
.It Cm ENDC
.El
.It Cm ENDR
.El
.Ss Symbols
.Bl -tag -width Ds -compact
.It Cm REPT Ar NumberOfSymbols
.Bl -tag -width Ds -compact
.It Cm STRING Ar Name
This symbol's name.
Local symbols are stored as their full name
.Pq Ql Scope.symbol .
.It Cm BYTE Ar Type
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta Sy Local No symbol only used in this file .
.It 1 Ta Sy Import No of an exported symbol (by name) from another object file .
.It 2 Ta Sy Exported No symbol visible from other object files .
.El
.It Cm IF Ar Type No \(!= 1
If the symbol is defined in this object file...
.Pp
.Bl -tag -width Ds -compact
.It Cm LONG Ar NodeID
Context in which the symbol was defined.
.It Cm LONG Ar LineNo
Line number in the context at which the symbol was defined.
.It Cm LONG Ar SectionID
The ID of the section in which the symbol is defined.
If the symbol doesn't belong to any specific section (i.e. it's a constant), this field contains -1.
.It Cm LONG Ar Value
The symbol's value.
If the symbol belongs to a section, this is the offset within that symbol's section.
.El
.It Cm ENDC
.El
.It Cm ENDR
.El
.Ss Sections
.Bl -tag -width Ds -compact
.It Cm REPT Ar NumberOfSections
.Bl -tag -width Ds -compact
.It Cm STRING Ar Name
The section's name.
.It Cm LONG Ar Size
The section's size, in bytes.
.It Cm BYTE Ar Type
Bits 0\(en2 indicate the section's type:
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta WRAM0
.It 1 Ta VRAM
.It 2 Ta ROMX
.It 3 Ta ROM0
.It 4 Ta HRAM
.It 5 Ta WRAMX
.It 6 Ta SRAM
.It 7 Ta OAM
.El
.Pp
Bit\ 7 being set means that the section is a "union"
.Pq see Do Unionized sections Dc in Xr rgbasm 5 .
Bit\ 6 being set means that the section is a "fragment"
.Pq see Do Section fragments Dc in Xr rgbasm 5 .
These two bits are mutually exclusive.
.It Cm LONG Ar Address
Address this section must be placed at.
This must either be valid for the section's
.Ar Type
(as affected by flags like
.Fl t
or
.Fl d
in
.Xr rgblink 1 ) ,
or -1 to indicate that the linker should automatically decide
.Pq the section is Dq floating .
.It Cm LONG Ar Bank
ID of the bank this section must be placed in.
This must either be valid for the section's
.Ar Type
(with the same caveats as for the
.Ar Address ) ,
or -1 to indicate that the linker should automatically decide.
.It Cm BYTE Ar Alignment
How many bits of the section's address should be equal to
.Ar AlignOfs ,
starting from the least-significant bit.
.It Cm LONG Ar AlignOfs
Alignment offset.
Must be strictly less than
.Ql 1 << Ar Alignment .
.It Cm IF Ar Type No \(eq 2 || Ar Type No \(eq 3
If the section has ROM type, it contains data.
.Pp
.Bl -tag -width Ds -compact
.It Cm BYTE Ar Data Ns Bq Size
The section's raw data.
Bytes that will be patched over must be present, even though their contents will be overwritten.
.It Cm LONG Ar NumberOfPatches
How many patches must be applied to this section's
.Ar Data .
.It Cm REPT Ar NumberOfPatches
.Bl -tag -width Ds -compact
.It Cm LONG Ar NodeID
Context in which the patch was defined.
.It Cm LONG Ar LineNo
Line number in the context at which the patch was defined.
.It Cm LONG Ar Offset
Offset within the section's
.Ar Data
at which the patch should be applied.
Must not be greater than the section's
.Ar Size
minus the patch's size
.Pq see Ar Type No below .
.It Cm LONG Ar PCSectionID
ID of the section in which PC is located.
(This is usually the same section within which the patch is applied, except for e.g.\&
.Ql LOAD
blocks, see
.Do RAM code Dc in Xr rgbasm 5 . )
.It Cm LONG Ar PCOffset
Offset of the PC symbol within the section designated by
.Ar PCSectionID .
It is expected that PC points to the instruction's first byte for instruction operands (i.e.\&
.Ql jp @
must be an infinite loop), and to the patch's first byte otherwise
.Ql ( db ,
.Ql dw ,
.Ql dl ) .
.It Cm BYTE Ar Type
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta Single-byte patch
.It 1 Ta Little-endian two-byte patch
.It 2 Ta Little-endian four-byte patch
.It 3 Ta Single-byte Ql jr
patch; the patch's value will be subtracted to PC + 2 (i.e.\&
.Ql jr @
must be the infinite loop
.Ql 18 FE ) .
.El
.It Cm LONG Ar RPNSize
Size of the
.Ar RPNExpr
below.
.It Cm BYTE Ar RPNExpr Ns Bq RPNSize
The patch's value, encoded as a RPN expression
.Pq see Sx RPN EXPRESSIONS .
.El
.It Cm ENDR
.El
.It Cm ENDC
.El
.El
.Ss Assertions
.Bl -tag -width Ds -compact
.It Cm LONG Ar NumberOfAssertions
How many assertions this object file contains.
.It Cm REPT Ar NumberOfAssertions
Assertions are essentially patches with a message.
.Pp
.Bl -tag -width Ds -compact
.It Cm LONG Ar NodeID
Context in which the assertions was defined.
.It Cm LONG Ar LineNo
Line number in the context at which the assertion was defined.
.It Cm LONG Ar Offset
Unused leftover from the patch structure.
.It Cm LONG Ar PCSectionID
ID of the section in which PC is located.
.It Cm LONG Ar PCOffset
Offset of the PC symbol within the section designated by
.Ar PCSectionID .
.It Cm BYTE Ar Type
Describes what should happen if the expression evaluates to a non-zero value.
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta Print a warning message, and continue linking normally.
.It 1 Ta Print an error message, so linking will fail, but allow other assertions to be evaluated.
.It 2 Ta Print a fatal error message, and abort immediately.
.El
.It Cm LONG Ar RPNSize
Size of the
.Ar RPNExpr
below.
.It Cm BYTE Ar RPNExpr Ns Bq RPNSize
The patch's value, encoded as a RPN expression
.Pq see Sx RPN EXPRESSIONS .
.It Cm STRING Ar Message
The message displayed if the expression evaluates to a non-zero value.
If empty, a generic message is displayed instead.
.El
.It Cm ENDR
.El
.Ss RPN EXPRESSIONS
Expressions in the object file are stored as RPN, or
.Dq Reverse Polish Notation ,
which is a notation that allows computing arbitrary expressions with just a simple stack.
For example, the expression
.Ql 2 5 -
will first push the value
.Dq 2
to the stack, then
.Dq 5 .
The
.Ql -
operator pops two arguments from the stack, subtracts them, and then pushes back the result
.Pq Dq 3
on the stack.
A well-formed RPN expression never tries to pop from an empty stack, and leaves exactly one value in it at the end.
.Pp
RGBDS encodes RPN expressions as an array of
.Cm BYTE Ns s .
The first byte encodes either an operator, or a literal, which consumes more
.Cm BYTE Ns s
after it:
.Bl -column "Value"
.It Sy Value Ta Sy Meaning
.It Li $00 Ta Addition operator Pq Ql +
.It Li $01 Ta Subtraction operator Pq Ql -
.It Li $02 Ta Multiplication operator Pq Ql *
.It Li $03 Ta Division operator Pq Ql /
.It Li $04 Ta Modulo operator Pq Ql %
.It Li $05 Ta Negation Pq unary Ql -
.It Li $06 Ta Exponent operator Pq Ql **
.It Li $10 Ta Bitwise OR operator Pq Ql \&|
.It Li $11 Ta Bitwise AND operator Pq Ql &
.It Li $12 Ta Bitwise XOR operator Pq Ql ^
.It Li $13 Ta Bitwise complement operator Pq unary Ql ~
.It Li $21 Ta Logical AND operator Pq Ql &&
.It Li $22 Ta Logical OR operator Pq Ql ||
.It Li $23 Ta Logical complement operator Pq unary Ql \&!
.It Li $30 Ta Equality operator Pq Ql ==
.It Li $31 Ta Non-equality operator Pq Ql !=
.It Li $32 Ta Greater-than operator Pq Ql >
.It Li $33 Ta Less-than operator Pq Ql <
.It Li $34 Ta Greater-than-or-equal operator Pq Ql >=
.It Li $35 Ta Less-than-or-equal operator Pq Ql <=
.It Li $40 Ta Left shift operator Pq Ql <<
.It Li $41 Ta Arithmetic/signed right shift operator Pq Ql >>
.It Li $42 Ta Logical/unsigned right shift operator Pq Ql >>>
.It Li $50 Ta Fn BANK symbol ;
followed by the
.Ar symbol Ap s Cm LONG
ID.
.It Li $51 Ta Fn BANK section ;
followed by the
.Ar section Ap s Cm STRING
name.
.It Li $52 Ta PC's Fn BANK Pq i.e. Ql BANK(@) .
.It Li $53 Ta Fn SIZEOF section ;
followed by the
.Ar section Ap s Cm STRING
name.
.It Li $54 Ta Fn STARTOF section ;
followed by the
.Ar section Ap s Cm STRING
name.
.It Li $55 Ta Fn SIZEOF sectiontype ;
followed by the
.Ar sectiontype Ap s Cm BYTE
value
.Pq see the Ar Type No values in Sx Sections .
.It Li $56 Ta Fn STARTOF sectiontype ;
followed by the
.Ar sectiontype Ap s Cm BYTE
value
.Pq see the Ar Type No values in Sx Sections .
.It Li $60 Ta Ql ldh
check.
Checks if the value is a valid
.Ql ldh
operand
.Pq see Do Load Instructions Dc in Xr gbz80 7 ,
i.e. that it is between either $00 and $FF, or $FF00 and $FFFF, both inclusive.
The value is then ANDed with $00FF
.Pq Ql & $FF .
.It Li $61 Ta Ql rst
check.
Checks if the value is a valid
.Ql rst
.Pq see Do RST vec Dc in Xr gbz80 7
vector, that is one of $00, $08, $10, $18, $20, $28, $30, or $38.
The value is then ORed with $C7
.Pq Ql \&| $C7 .
.It Li $80 Ta Integer literal; followed by the
.Cm LONG
integer.
.It Li $81 Ta A symbol's value; followed by the symbol's
.Cm LONG
ID.
.El
.Sh SEE ALSO
.Xr rgbasm 1 ,
.Xr rgbasm 5 ,
.Xr rgblink 1 ,
.Xr rgblink 5 ,
.Xr rgbfix 1 ,
.Xr rgbgfx 1 ,
.Xr gbz80 7 ,
.Xr rgbds 7
.Sh HISTORY
.Xr rgbasm 1
and
.Xr rgblink 1
were originally written by
.An Carsten S\(/orensen
as part of the ASMotor package, and was later repackaged in RGBDS by
.An Justin Lloyd .
It is now maintained by a number of contributors at
.Lk https://github.com/gbdev/rgbds .

View File

@@ -1,73 +0,0 @@
.\" SPDX-License-Identifier: MIT
.\"
.Dd December 22, 2023
.Dt RGBDS 7
.Os
.Sh NAME
.Nm rgbds
.Nd Rednex Game Boy Development System
.Sh EXAMPLES
To get a working ROM image from a single assembly source file:
.Bd -literal -offset indent
$ rgbasm \-o game.o game.asm
$ rgblink \-o game.gb game.o
$ rgbfix \-v \-p 0 game.gb
.Ed
.Pp
Or in a single command line, without creating an intermediate object file:
.Bd -literal -offset indent
$ (rgbasm -o - - | rgblink -o - - | rgbfix -v -p 0) < game.asm > game.gb
.Ed
.Sh SEE ALSO
.Xr rgbasm 1 ,
.Xr rgbasm 5 ,
.Xr rgblink 1 ,
.Xr rgblink 5 ,
.Xr rgbfix 1 ,
.Xr rgbgfx 1 ,
.Xr gbz80 7 ,
.Xr rgbds 5
.Sh HISTORY
.Bl -item
.It
1996-10-01:
.An Carsten S\(/orensen
.Pq a.k.a. SurfSmurf
releases xAsm, xLink, and RGBFix, a Game Boy SM83 (GBZ80) assembler/linker system for DOS/Win32.
.It
1997-07-03: S\(/orensen releases ASMotor, packaging the three programs together and moving towards making them a general-purpose target-independent system.
.It
1999-08-01:
.An Justin Lloyd
.Pq a.k.a. Otaku no Zoku
adapts ASMotor to re-focus on SM83 assembly/machine code, and releases this version as RGBDS.
.It
2009-06-11:
.An Vegard Nossum
adapts the code to be more UNIX-like and releases this version as rgbds-linux.
.It
2010-01-12:
.An Anthony J. Bentley
forks Nossum's repository.
The fork becomes the reference implementation of RGBDS.
.It
2015-01-18:
.An stag019
begins implementing rgbgfx, a PNGtoGame Boy graphics converter, for eventual integration into RGBDS.
.It
2016-09-05: rgbgfx is integrated into Bentley's repository.
.It
2017-02-23: Bentley's repository is moved to the
.Lk https://github.com/rednex/rgbds rednex
organization.
.It
2018-01-26: The codebase is relicensed under the MIT license.
.It
2020-09-15: The repository is moved to the
.Lk https://github.com/gbdev/rgbds gbdev
organization.
.It
2022-05-17: The
.Lk https://rgbds.gbdev.io
website for RGBDS documentation and downloads is published.
.El

View File

@@ -1,667 +0,0 @@
'\" e
.\"
.\" SPDX-License-Identifier: MIT
.\"
.Dd December 22, 2023
.Dt RGBGFX 1
.Os
.Sh NAME
.Nm rgbgfx
.Nd Game Boy graphics converter
.Sh SYNOPSIS
.Nm
.Op Fl CmOuVZ
.Op Fl v Op Fl v No ...
.Op Fl a Ar attrmap | Fl A
.Op Fl b Ar base_ids
.Op Fl c Ar color_spec
.Op Fl d Ar depth
.Op Fl L Ar slice
.Op Fl N Ar nb_tiles
.Op Fl n Ar nb_pals
.Op Fl o Ar out_file
.Op Fl p Ar pal_file | Fl P
.Op Fl q Ar pal_map | Fl Q
.Op Fl r Ar stride
.Op Fl s Ar nb_colors
.Op Fl t Ar tilemap | Fl T
.Op Fl x Ar quantity
.Ar file
.Sh DESCRIPTION
The
.Nm
program converts PNG images into data suitable for display on the Game Boy and Game Boy Color, or vice-versa.
.Pp
The main function of
.Nm
is to divide the input PNG into 8\[tmu]8 pixel
.Em squares ,
convert each of those squares into 1bpp or 2bpp tile data, and save all of the tile data in a file.
It also has options to generate a tile map, attribute map, and/or palette set as well; more on that and how the conversion process can be tweaked below.
.Sh ARGUMENTS
Note that options can be abbreviated as long as the abbreviation is unambiguous:
.Fl \-verb
is
.Fl \-verbose ,
but
.Fl \-ver
is invalid because it could also be
.Fl \-version .
.Pp
.Nm
accepts decimal, binary, and hexadecimal numbers in option arguments.
Decimal numbers are written as usual; binary numbers must be prefixed with either
.Ql %
or
.Ql 0b ,
and hexadecimal numbers must be prefixed with either
.Ql $
(which will likely need escaping or quoting to avoid being interpreted by the shell), or
.Ql 0x .
Leading zeros (after the base prefix, if any) are accepted, and letters are not case-sensitive.
All of these are equivalent:
.Ql 42 ,
.Ql 042 ,
.Ql 0b00101010 ,
.Ql 0B101010 ,
.Ql 0x2A ,
.Ql 0X2A ,
.Ql 0x2a .
.Pp
Unless otherwise noted, passing
.Ql -
(a single dash) as a file name makes
.Nm
use standard input (for input files) or standard output (for output files).
To suppress this behavior, and open a file in the current directory actually called
.Ql - ,
pass
.Ql ./-
instead.
Using standard input or output more than once in a single command will likely produce unexpected results.
.Pp
The following options are accepted:
.Bl -tag -width Ds
.It Fl a Ar attrmap , Fl \-attr-map Ar attrmap
Generate an attribute map, which is a file containing tile
.Dq attributes .
For each square of the input image, its corresponding attribute map byte contains the mirroring bits (if
.Fl m
was specified), the bank bit
.Pq see Fl N ,
and the palette index.
See
.Lk https://gbdev.io/pandocs/Tile_Maps#bg-map-attributes-cgb-mode-only Pan Docs
for the individual bytes' format.
The output is written just like the tile map (see
.Fl t ) ,
follows the same order
.Pq Fl Z ,
and has the same size.
.It Fl A , Fl \-auto-attr-map
Same as
.Fl a Ar base_path Ns .attrmap
.Pq see Sx Automatic output paths .
.It Fl b Ar base_ids , Fl \-base-tiles Ar base_ids
Set the base IDs for tile map output.
.Ar base_ids
should be one or two numbers between 0 and 255, separated by a comma; they are for bank 0 and bank 1 respectively.
Both default to 0.
.It Fl C , Fl \-color-curve
When generating palettes, use a color curve mimicking the Game Boy Color's screen.
The resulting colors may look closer to the input image's
.Sy on hardware and accurate emulators .
.It Fl c Ar color_spec , Fl \-colors Ar color_spec
Use the specified color palettes instead of having
.Nm
automatically determine some.
.Ar color_spec
can be one of the following:
.Bl -tag -width Ds
.It Sy inline palette spec
If
.Ar color_spec
begins with a hash character
.Ql # ,
it is treated as an inline palette specification.
It should contain a comma-separated list of hexadecimal colors, each beginning with a hash.
Colors in are accepted either as
.Ql #rgb
or
.Ql #rrggbb
format.
Palettes must be separated by a colon or semicolon (the latter may require quoting to avoid special handling by the shell), and spaces are allowed around colons, semicolons and commas; trailing commas and semicolons are allowed.
See
.Sx EXAMPLES
for an example of an inline palette specification.
.It Sy embedded palette spec
If
.Ar color_spec
is the case-insensitive word
.Cm embedded ,
then the first four colors of the input PNG's embedded palette are used.
It is an error if the PNG is not indexed, or if colors other than these 4 are used.
.Pq This is different from the default behavior of indexed PNGs, as then unused entries in the embedded palette are ignored, whereas they are not with Fl c Cm embedded .
.It Sy external palette spec
Otherwise,
.Ar color_spec
is assumed to be an external palette specification.
The expected format is
.Ql format:path ,
where
.Ar path
is a path to a file
.Ql ( -
is not treated specially), which will be processed according to the
.Ar format .
See
.Sx PALETTE SPECIFICATION FORMATS
for a list of formats and their descriptions.
.El
.It Fl d Ar depth , Fl \-depth Ar depth
Set the bit depth of the output tile data, in bits per pixel (bpp), either 1 or 2 (the default).
This changes how tile data is output, and the maximum number of colors per palette (2 and 4 respectively).
.It Fl L Ar slice , Fl \-slice Ar slice
Only process a given rectangle of the image.
This is useful for example if the input image is a sheet of some sort, and you want to convert each cel individually.
The default is to process the whole image as-is.
.Pp
.Ar slice
must be two number pairs, separated by a colon.
The numbers must be separated by commas; space is allowed around all punctuation.
The first number pair specifies the X and Y coordinates of the top-left pixel that will be processed (anything above it or to its left will be ignored).
The second number pair specifies how many tiles to process horizontally and vertically, respectively.
.Pp
.Fl L Sy is ignored in reverse mode , No no padding is inserted .
.It Fl m , Fl \-mirror-tiles
Deduplicate tiles that are symmetrical mirror images of each other.
Only one of each unique tile will be saved in the tile data file, with mirror images counting as duplicates.
Tiles are checked for horizontal, vertical, and horizontal-vertical mirroring.
Useful with a tile map and attribute map together (see
.Fl a
and
.Fl t )
to keep track of the duplicated tiles and the dimension(s) mirrored.
Implies
.Fl u .
.It Fl N Ar nb_tiles , Fl \-nb-tiles Ar nb_tiles
Set a maximum number of tiles that can be placed in each VRAM bank.
.Ar nb_tiles
should be one or two numbers between 0 and 256, separated by a comma; if the latter is omitted, it defaults to 0.
Setting either number to 0 prevents any tiles from being output in that bank.
.Pp
If more tiles are generated than can fit in the two banks combined,
.Nm
will abort.
If
.Fl N
is not specified, no limit will be set on the amount of tiles placed in bank 0, and tiles will not be placed in bank 1.
.It Fl n Ar nb_pals , Fl \-nb-palettes Ar nb_pals
Abort if more than
.Ar nb_pals
palettes are generated.
This may not be more than 256.
.Pp
Note that attribute map output only has 3 bits for the palette ID, so a limit higher than 8 may yield incomplete data unless relying on a palette map
.Pq see Fl q .
.It Fl O , Fl \-group-outputs
Sets the
.Sq base path
to be the output tile data path from
.Fl o
instead of the input image path
.Pq see Sx Automatic output paths .
.It Fl o Ar out_file , Fl \-output Ar out_file
Output the tile data in native 2bpp format or in 1bpp
.Pq depending on Fl d
to this file.
.It Fl p Ar pal_file , Fl \-palette Ar pal_file
Output the image's palette set to this file.
.It Fl P , Fl \-auto-palette
Same as
.Fl p Ar base_path Ns .pal
.Pq see Sx Automatic output paths .
.It Fl q Ar pal_file , Fl \-palette-map Ar pal_file
Output the image's palette map to this file.
This is useful if the input image contains more than 8 palettes, as the attribute map only contains the lower 3 bits of the palette indices.
.It Fl Q , Fl \-auto-palette-map
Same as
.Fl q Ar base_path Ns .palmap
.Pq see Sx Automatic output paths .
.It Fl r Ar width , Fl \-reverse Ar width
Switches
.Nm
into
.Dq Sy reverse
mode.
In this mode, instead of converting a PNG image into Game Boy data,
.Nm
will attempt to reverse the process, and render Game Boy data into an image.
See
.Sx REVERSE MODE
below for details.
.Pp
.Ar width
is the width of the image to generate, in tiles.
.It Fl s Ar nb_colors , Fl \-palette-size Ar nb_colors
Specify how many colors each palette contains, including the transparent one if any.
.Ar nb_colors
cannot be more than
.Ql 1 << Ar depth
.Pq see Fl d .
.It Fl t Ar tilemap , Fl \-tilemap Ar tilemap
Generate a file of tile indices.
For each square of the input image, its corresponding tile map byte contains the index of the associated tile in the tile data file.
The IDs wrap around from 255 back to 0, and do not include the bank bit; use
.Fl a
for that.
Useful in combination with
.Fl u
and/or
.Fl m
to keep track of duplicate tiles.
.It Fl T , Fl \-auto-tilemap
Same as
.Fl t Ar base_path Ns .tilemap
.Pq see Sx Automatic output paths .
.It Fl u , Fl \-unique-tiles
Deduplicate identical tiles.
Only one of each unique tile will be saved in the tile data file.
Useful with a tile map
.Pq see Fl t
to keep track of the duplicated tiles.
.Pp
Note that if this option is enabled, no guarantee is made on the order in which tiles are output; while it
.Em should
be consistent across identical runs of a given
.Nm
release, the same is not true for different releases.
.It Fl V , Fl \-version
Print the version of the program and exit.
.It Fl v , Fl \-verbose
Be verbose.
The verbosity level is increased by one each time the flag is specified, with each level including the previous:
.Bl -enum -compact
.It
.Nm
prints out its configuration before doing anything.
.It
A generic message is printed before doing most actions.
.It
Some of the actions' intermediate results are printed.
.It
Some internal debug printing is enabled.
.El
The verbosity level does not go past 6.
.Pp
Note that verbose output is only intended to be consumed by humans, and may change without notice between RGBDS releases; relying on those for scripts is not advised.
.It Fl x Ar quantity , Fl \-trim-end Ar quantity
Do not output the last
.Ar quantity
tiles to the tile data file; no other output is affected.
This is useful for trimming
.Dq filler
/ blank squares at the end of an image.
If fewer than
.Ar quantity
tiles would have been emitted, the file will be empty.
.Pp
Note that this is done
.Em after
deduplication if
.Fl u
was enabled, so you probably don't want to use this option in combination with
.Fl u .
Note also that the tiles that don't get output will not count towards
.Fl N Ap s
limit.
.It Fl Z , Fl \-columns
Read squares from the PNG in column-major order (column by column), instead of the default row-major order (line by line).
This primarily affects tile map and attribute map output, although it may also change generated tile data and palettes.
.El
.Ss At-files
In a given project, many images are to be converted with different flags.
The traditional way of solving this problem has been to specify the different flags for each image in the Makefile / build script; this can be inconvenient, as it centralizes all those flags away from the images they concern.
.Pp
To avoid these drawbacks,
.Nm
supports
.Dq at-files :
any command-line argument that begins with an at sign
.Pq Ql @
is interpreted as one.
The rest of the argument (without the @, that is) is interpreted as the path to a file, whose contents are interpreted as if given on the command line.
At-files can be stored right next to the corresponding image, for example:
.Pp
.Dl $ rgbgfx -o image.2bpp -t image.tilemap @image.flags image.png
.Pp
This will read additional flags from file
.Ql image.flags ,
which could contains for example
.Ql -b 128
to specify a base offset for the image's tiles.
The above command could be generated from the following
.Xr make 1
rule, for example:
.Bd -literal -offset indent
%.2bpp %.tilemap: %.flags %.png
rgbgfx -o $*.2bpp -t $*.tilemap @$*.flags $*.png
.Ed
.Pp
Since the contents of at-files are interpreted by
.Nm ,
.Sy no shell processing is performed ;
for example, shell variables are not expanded
.Ql ( $PWD ,
.Ql %WINDIR% ,
etc.).
In at-files, lines that are empty or contain only whitespace are ignored; lines that begin with a hash sign
.Pq Ql # ,
optionally preceded by whitespace, are considered comments and also ignored.
Each line can contain any number of arguments, which are separated by whitespace.
.Pq \&No quoting feature to prevent this is provided.
.Pp
Note that a leading
.Ql @
has no special meaning on option arguments, and that the standard
.Ql --
to stop option processing also disables at-file processing.
For example, the following command line reads command-line options from
.Ql tilesets/town.flags
then
.Ql tilesets.flags ,
but processes
.Ql @tilesets/town.png
as the input image and outputs tile data to
.Ql @tilesets/town.2bpp :
.Pp
.Dl $ rgbgfx -o @tilesets/town.2bpp @tilesets/town.flags @tilesets.flags -- @tilesets/town.png
.Pp
At-files can also specify the input image directly, and call for more at-files, both using the regular syntax.
Note that while
.Ql --
can be used in an at-file (with identical semantics), it is only effective inside of it\(emnormal option processing continues in the parent scope.
.Sh PALETTE SPECIFICATION FORMATS
The following formats are supported:
.Bl -tag -width Ds
.It Cm act
.Lk https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577411_pgfId-1070626 Adobe Photoshop color table .
.It Cm aco
.Lk https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577411_pgfId-1055819 Adobe Photoshop color swatch .
.It Cm gbc
A GBC palette memory dump, as emitted by
.Nm Fl p .
Useful to force several images to share the same palette.
.It Cm gpl
.Lk https://docs.gimp.org/2.10/en/gimp-concepts-palettes.html GIMP palette .
.It Cm hex
Plaintext lines of hexadecimal colors in
.Ql rrggbb
format.
.It Cm psp
.Lk https://www.selapa.net/swatches/colors/fileformats.php#psp_pal Paint Shop Pro palette .
.El
.Pp
If you wish for another format to be supported, please open an issue (see
.Sx BUGS
below) or contact us, and supply a few sample files.
.Sh PALETTE GENERATION
.Nm
must generate palettes from the colors in the input image, unless
.Fl c
was used; in that case, the provided palettes will be used.
.Sy If the order of colors in the palettes is important to you ,
for example because you want to use palette swaps, please use
.Fl c
to specify the palette explicitly.
.Pp
First, if the image contains
.Em any
transparent pixel, color #0 of
.Em all
palettes will be allocated to it.
This is done
.Sy even if palettes were explicitly specified using Fl c ;
then the specification only covers color #1 onwards.
.Pq If you do not want this, ask your image editor to remove the alpha channel.
.Pp
After generating palettes,
.Nm
sorts colors within those palettes using the following rules:
.EQ
delim $$
.EN
.Bl -bullet -offset indent
.It
If the PNG file internally contains a palette (often dubbed an
.Dq indexed
PNG), then colors in each output palette will be sorted according to their order in the PNG's palette.
Any unused entries will be ignored, and only the first entry is considered if there are any duplicates.
.Po If you want a given color to appear more than once, or an unused color to appear at all, you should specify the palettes explicitly instead using Fl c ;
.Fl c Cm embedded
may be appropriate.
.Pc
.It
Otherwise, if the PNG only contains shades of gray, they will be categorized into as many
.Dq bins
as there are colors per palette, and the palette is set to these bins.
The darkest gray will end up in bin #0, and so on; note that this is the opposite of the RGB method below.
If two distinct grays end up in the same bin, the RGB method is used instead.
.Pp
Be careful that
.Nm
is picky about what it considers
.Dq grays :
the red, green, and blue components of each color must
.Em all
be
.Em exactly
the same.
.It
If none of the above apply, colors are sorted from lightest (first) to darkest (last).
The definition of luminance that
.Nm
uses is
.Do
$2126 times red + 7152 times green + 722 times blue$
.Dc .
.El
.EQ
delim off
.EN
.Pp
Note that the
.Dq indexed
behavior depends on an internal detail of how the PNG is saved, specifically its
.Ql PLTE
chunk.
Since few image editors (such as GIMP) expose that detail, this behavior is only kept for compatibility and should be considered deprecated.
.Sh OUTPUT FILES
All files output by
.Nm
are binary files, and designed to follow the Game Boy and Game Boy Color's native formats.
What follows is succinct descriptions of those formats, including
.Nm Ns -specific
details.
For more complete, beginner-friendly descriptions of the native formats with illustrations, please check out
.Lk https://gbdev.io/pandocs/Graphics Pan Docs .
.Ss Tile data
Tile data is output like a binary dump of VRAM, with no padding between tiles.
Each tile is 16 bytes, 2 per row of 8 pixels; the bits of color IDs are split into each byte
.Pq or Dq bitplane .
The leftmost pixel's color ID is stored in the two bytes' most significant bits, and the rightmost pixel's color ID in their least significant bits.
.Pp
When the bit depth
.Pq Fl d
is set to 1, the most significant bitplane (second byte) of each row, being all zeros, is simply not output.
.Ss Palette data
Palette data is output like a dump of palette memory.
Each color is written as GBC-native little-endian RGB555, with the unused bit 15 set to 0.
There is no padding between colors, nor between palettes; however, empty colors in the palettes are output as 0xFFFF.
.EQ
delim $$
.EN
For example, if 5 palettes are generated with
.Fl s Cm 4 ,
the palette data file will be $2 times 4 times 5 = 40$ bytes long, even if some palettes contain less than 3 colors.
.EQ
delim off
.EN
Note that
.Fl n
only caps how many palettes are generated (and thus this file's size), but fewer may be generated still.
.Ss Tile map data
A tile map is an array of tile IDs, with one byte per tile ID.
The first byte always corresponds to the ID of the tile in top-left corner of the input image; the second byte is either the ID of the tile to its right (by default), or below it
.Pq with Fl Z ;
and so on, continuing in the same direction.
Rows / columns (respectively) are stored consecutively, with no padding.
.Ss Attribute map data
Attribute maps mirror the format of tile maps, like on the GBC, especially the order in which bytes are output.
The contents of individual bytes follows the GBC's native format:
.Bl -column "Bit 2\(en0" "Background Palette number"
.It Bit 7 Ta BG-to-OAM Priority Ta Set to 0
.It Bit 6 Ta Vertical Flip Ta 0=Normal, 1=Mirror vertically
.It Bit 5 Ta Horizontal Flip Ta 0=Normal, 1=Mirror horizontally
.It Bit 4 Ta Not used Ta Set to 0
.It Bit 3 Ta Tile VRAM Bank number Ta 0=Bank 0, 1=Bank 1
.It Bit 2\(en0 Ta Background Palette number Ta BGP0-7
.El
.Pp
Note that if more than 8 palettes are used, only the lowest 3 bits of the palette ID are output.
.Ss Automatic output paths
For convenience,
.Nm
provides shortcuts to generate all files in the same directory.
This is done by using the uppercase version of a flag
.Pq for example, Fl A No instead of Fl a .
The
.Ar base_path
is the input image path
.Pq or the output tile data path from Fl o , No if Fl O No was given
with its extension, if any, removed.
.Pp
For example, these two commands are equivalent:
.Bd -literal -offset indent
$ rgbgfx img/player.png -o build/player.2bpp -P
$ rgbgfx img/player.png -o build/player.2bpp -p img/player.pal
.Ed
.Pp
And so are these two:
.Bd -literal -offset indent
$ rgbgfx img/player.png -o build/player.2bpp -O -P
$ rgbgfx img/player.png -o build/player.2bpp -p build/player.pal
.Ed
.Sh REVERSE MODE
.Nm
can produce a PNG image from valid data.
This may be useful for ripping graphics, recovering lost source images, etc.
An important caveat on that last one, though: the conversion process is
.Sy lossy
both ways, so the
.Do reversed Dc image won't be perfectly identical to the original\(embut it should be close to a Game Boy's output .
.Pq Keep in mind that many of consoles output different colors, so there is no true reference rendering.
.Pp
When using reverse mode, make sure to pass the same flags that were given when generating the data, especially
.Fl C , d , N , s , x ,
and
.Fl Z .
.Do Sx At-files Dc may help with this .
.Nm
will warn about any inconsistencies it detects.
.Pp
Files that are normally outputs
.Pq Fl a , p , t
become inputs, and
.Ar file
will be written to instead of read from, and thus needs not exist beforehand.
Any of these inputs not passed is assumed to be some default:
.Bl -column "attribute map"
.It palettes Ta Unspecified palette data makes
.Nm
assume DMG (monochrome Game Boy) mode: a single palette of 4 grays.
It is possible to pass palettes using
.Fl c
instead of
.Fl p .
.It tile data Ta Tile data must be provided, as there is no reasonable assumption to fall back on.
.It tile map Ta A missing tile map makes
.Nm
assume that tiles were not deduplicated, and should be laid out in the order they are stored.
.It attribute map Ta Without an attribute map,
.Nm
assumes that no tiles were mirrored.
.El
.Sh NOTES
Some flags have had their functionality removed.
.Fl D , f ,
and
.Fl F
are now ignored, and
.Fl h
is an alias for the new (and less confusingly named)
.Fl Z .
These will be removed and/or repurposed in future versions of
.Nm ,
so relying on them is not recommended.
The same applies to the corresponding long options.
.Pp
If you are curious, you may find out that palette generation is an NP-complete problem, so
.Nm
does not attempt to find the optimal solution, but instead to find a good one in a reasonable amount of time.
It is possible to compute the optimal solution externally (using a solver, for example), and then provide it to
.Nm
via
.Fl c .
.Sh EXAMPLES
The following will only validate the
.Ql tileset.png
image (check its size, that all tiles have a suitable amount of colors, etc.), but output nothing:
.Pp
.Dl $ rgbgfx src/res/maps/overworld/tileset.png
.Pp
The following will convert the
.Ql tileset.png
image using the two given palettes (and only those), and store the generated 2bpp tile data in
.Ql tileset.2bpp ,
and the attribute map in
.Ql tileset.attrmap .
.Pp
.Dl $ rgbgfx -c '#ffffff,#8d05de, #dc7905,#000000 ; #fff,#8d05de, #7e0000 \&, #000' -A -o tileset.2bpp tileset.png
.Pp
The following will deduplicate the tiles in the
.Ql title_screen.png
image, keeping only one of each unique tile, and store the generated 2bpp tile data in
.Ql title_screen.2bpp ,
and the tile map in
.Ql title_screen.tilemap .
.Pp
.Dl $ rgbgfx -u title_screen.png -o title_screen.2bpp -t title_screen.tilemap
.Pp
The following will convert the given inline palette specification to a palette set, and store the palette set in
.Ql colors.pal ,
without needing an input image.
.Pp
.Dl $ rgbgfx -c '#fff,#ff0,#f80,#000' -p colors.pal
.Pp
TODO: more examples.
.Sh BUGS
Please report bugs and mistakes in this man page on
.Lk https://github.com/gbdev/rgbds/issues GitHub .
Bug reports and feature requests about RGBDS are also welcome!
.Sh SEE ALSO
.Xr rgbasm 1 ,
.Xr rgblink 1 ,
.Xr rgbfix 1 ,
.Xr rgbds 7
.Pp
The Game Boy hardware reference
.Lk https://gbdev.io/pandocs/Graphics Pan Docs ,
particularly the section about graphics.
.Sh HISTORY
.Nm
was originally written by stag019 as a program to be packaged in RGBDS.
It was later rewritten by
.An ISSOtm ,
and is now maintained by a number of contributors at
.Lk https://github.com/gbdev/rgbds .

View File

@@ -1,175 +0,0 @@
.\" SPDX-License-Identifier: MIT
.\"
.Dd December 22, 2023
.Dt RGBLINK 5
.Os
.Sh NAME
.Nm rgblink
.Nd linker script file format
.Sh DESCRIPTION
The linker script is a file that allows specifying attributes for sections at link time, and in a centralized manner.
There can only be one linker script per invocation of
.Nm ,
but it can be split into several files
.Pq using the Ic INCLUDE No directive .
.Ss Basic syntax
The linker script syntax is line-based.
Each line may have a directive or section name, a comment, both, or neither.
Whitespace (space and tab characters) is used to separate syntax elements, but is otherwise ignored.
.Pp
Comments begin with a semicolon
.Ql \&;
character, until the end of the line.
They are simply ignored.
.Pp
Keywords are composed of letters and digits (but they can't start with a digit); they are all case-insensitive.
.Pp
Numbers can be written in decimal format, or in binary using the
.Ql %
prefix, or in hexadecimal using the
.Ql $
prefix (hexadecimal digits are case-insensitive).
Note that unlike
.Xr rgbasm 5 ,
an octal
.Ql &
prefix is not supported, nor are
.Ql _
digit separators.
.Pp
Strings begin with a double quote, and end at the next (non-escaped) double quote.
Strings must not contain literal newline characters.
Most of the same character escapes as
.Xr rgbasm 5
are supported, specifically
.Ql \e\e ,
.Ql \e" ,
.Ql \en ,
.Ql \er ,
and
.Ql \et .
Other backslash escape sequences in
.Xr rgbasm 5
are only relevant to assembly code and do not apply in linker scripts.
.Ss Directives
.Bl -tag -width Ds
.It Including other files
.Ql Ic INCLUDE Ar path
acts as if the contents of the file at
.Ar path
were copy-pasted in place of the
.Ic INCLUDE
directive.
.Ar path
must be a string.
.It Specifying the active bank
The active bank can be set by specifying its type (memory region) and number.
The possible types are:
.Ic ROM0 , ROMX , VRAM , SRAM , WRAM0 , WRAMX , OAM ,
and
.Ic HRAM .
The bank number can be omitted from the types that only contain a single bank, which are:
.Ic ROM0 ,
.Ic ROMX No if Fl t No is passed to Xr rgblink 1 ,
.Ic VRAM No if Fl d No is passed to Xr rgblink 1 ,
.Ic WRAM0 ,
.Ic WRAMX No if Fl w No is passed to Xr rgblink 1 ,
.Ic OAM ,
and
.Ic HRAM .
.Pq Ic SRAM No is the only type that can never have its bank number omitted.
.Pp
After a bank specification, the
.Dq current address
is set to the last value it had for that bank.
If the bank has never been active thus far, the
.Dq current address
defaults to the beginning of the bank
.Pq e.g. Ad $4000 No for Ic ROMX No sections .
.It Changing the current address
A bank must be active for any of these directives to be used.
.Pp
.Ql Ic ORG Ar addr
sets the
.Dq current address
to
.Ar addr .
This directive cannot be used to move the address backwards:
.Ar addr
must be greater than or equal to the
.Dq current address .
.Pp
.Ql Ic FLOATING
causes all sections between it and the next
.Ic ORG
or bank specification to be placed at addresses automatically determined by
.Nm .
.Pp
.Ql Ic ALIGN Ar addr , Ar offset
increases the
.Dq current address
until it is aligned to the specified boundary (i.e. the
.Ar align
lowest bits of the address are equal to
.Ar offset ) .
If
.Ar offset
is omitted, it is implied to be 0.
For example, if the
.Dq current address
is $0007,
.Ql ALIGN 8
would set it to $0100, and
.Ql ALIGN 8 , 10
would set it to $000A.
.Pp
.Ql Ic DS Ar size
increases the
.Dq current address
by
.Ar size .
The gap is not allocated, so smaller floating sections can later be placed there.
.El
.Ss Section placement
A section can be placed simply by naming it (with a string).
Its bank is set to the active bank, and its address to the
.Dq current address .
Any constraints the section already possesses (whether from earlier in the linker script, or from the object files being linked) must be consistent with what the linker script specifies: the section's type must match, the section's bank number (if set) must match the active bank, etc.
In particular, if the section has an alignment constraint, the address at which it is placed by the linker script must obey that constraint; otherwise, an error will occur.
.Pp
After a section is placed, the
.Dq current address
is increased by the section's size.
This must not increase it past the end of the active memory region.
.Pp
The section must have been defined in the object files being linked, unless the section name is followed by the keyword
.Ic OPTIONAL .
.Sh EXAMPLES
.Bd -literal -offset indent
; This line contains only a comment
ROMX $F ; start a bank
"Some functions" ; a section name
ALIGN 8 ; a directive
"Some \e"array\e""
WRAMX 2 ; start another bank
org $d123 ; another directive
"Some variables"
.Ed
.Sh SEE ALSO
.Xr rgbasm 1 ,
.Xr rgbasm 5 ,
.Xr rgblink 1 ,
.Xr rgbfix 1 ,
.Xr rgbgfx 1 ,
.Xr gbz80 7 ,
.Xr rgbds 5 ,
.Xr rgbds 7
.Sh HISTORY
.Xr rgblink 1
was originally written by
.An Carsten S\(/orensen
as part of the ASMotor package, and was later repackaged in RGBDS by
.An Justin Lloyd .
It is now maintained by a number of contributors at
.Lk https://github.com/gbdev/rgbds .

2
src/.gitignore vendored
View File

@@ -1,2 +1,2 @@
# Generated by CMake
/.version.cpp
/.version.c

View File

@@ -1,93 +1,92 @@
#
# This file is part of RGBDS.
#
# Copyright (c) 2020 RGBDS contributors.
#
# SPDX-License-Identifier: MIT
#
configure_file(version.cpp _version.cpp ESCAPE_QUOTES)
configure_file(version.c _version.c ESCAPE_QUOTES)
set(common_src
"error.cpp"
"extern/getopt.cpp"
"_version.cpp"
"error.c"
"extern/getopt.c"
"_version.c"
)
find_package(BISON 3.0.0 REQUIRED)
find_package(PkgConfig)
if(MSVC OR NOT PKG_CONFIG_FOUND)
# fallback to find_package
find_package(PNG REQUIRED)
else()
pkg_check_modules(LIBPNG REQUIRED libpng)
endif()
find_package(BISON REQUIRED)
set(BISON_FLAGS "-Wall")
# Set some optimization flags on versions that support them
# Set sompe optimization flags on versions that support them
if(BISON_VERSION VERSION_GREATER_EQUAL "3.5")
set(BISON_FLAGS "${BISON_FLAGS} -Dapi.token.raw=true")
endif()
if(BISON_VERSION VERSION_GREATER_EQUAL "3.6")
set(BISON_FLAGS "${BISON_FLAGS} -Dparse.error=detailed")
else()
elseif(BISON_VERSION VERSION_GREATER_EQUAL "3.0")
set(BISON_FLAGS "${BISON_FLAGS} -Dparse.error=verbose")
endif()
set(BISON_FLAGS "${BISON_FLAGS} -Dparse.lac=full")
set(BISON_FLAGS "${BISON_FLAGS} -Dlr.type=ielr")
BISON_TARGET(ASM_PARSER "asm/parser.y"
"${PROJECT_SOURCE_DIR}/src/asm/parser.cpp"
if(BISON_VERSION VERSION_GREATER_EQUAL "3.0")
set(BISON_FLAGS "${BISON_FLAGS} -Dparse.lac=full")
set(BISON_FLAGS "${BISON_FLAGS} -Dlr.type=ielr")
endif()
BISON_TARGET(PARSER "asm/parser.y"
"${PROJECT_SOURCE_DIR}/src/asm/parser.c"
COMPILE_FLAGS "${BISON_FLAGS}"
DEFINES_FILE "${PROJECT_SOURCE_DIR}/src/asm/parser.hpp"
)
BISON_TARGET(LINKER_SCRIPT_PARSER "link/script.y"
"${PROJECT_SOURCE_DIR}/src/link/script.cpp"
COMPILE_FLAGS "${BISON_FLAGS}"
DEFINES_FILE "${PROJECT_SOURCE_DIR}/src/link/script.hpp"
DEFINES_FILE "${PROJECT_SOURCE_DIR}/src/asm/parser.h"
)
set(rgbasm_src
"${BISON_ASM_PARSER_OUTPUT_SOURCE}"
"asm/charmap.cpp"
"asm/fixpoint.cpp"
"asm/format.cpp"
"asm/fstack.cpp"
"asm/lexer.cpp"
"asm/macro.cpp"
"asm/main.cpp"
"asm/opt.cpp"
"asm/output.cpp"
"asm/rpn.cpp"
"asm/section.cpp"
"asm/symbol.cpp"
"asm/warning.cpp"
"extern/utf8decoder.cpp"
"hashmap.cpp"
"linkdefs.cpp"
"opmath.cpp"
"util.cpp"
"${BISON_PARSER_OUTPUT_SOURCE}"
"asm/charmap.c"
"asm/fixpoint.c"
"asm/format.c"
"asm/fstack.c"
"asm/lexer.c"
"asm/macro.c"
"asm/main.c"
"asm/opt.c"
"asm/output.c"
"asm/rpn.c"
"asm/section.c"
"asm/symbol.c"
"asm/util.c"
"asm/warning.c"
"extern/utf8decoder.c"
"hashmap.c"
"linkdefs.c"
"opmath.c"
)
set(rgbfix_src
"fix/main.cpp"
"fix/main.c"
)
set(rgbgfx_src
"gfx/main.cpp"
"gfx/pal_packing.cpp"
"gfx/pal_sorting.cpp"
"gfx/pal_spec.cpp"
"gfx/process.cpp"
"gfx/proto_palette.cpp"
"gfx/reverse.cpp"
"gfx/rgba.cpp"
"extern/getopt.cpp"
"error.cpp"
"gfx/gb.c"
"gfx/main.c"
"gfx/makepng.c"
)
set(rgblink_src
"${BISON_LINKER_SCRIPT_PARSER_OUTPUT_SOURCE}"
"link/assign.cpp"
"link/main.cpp"
"link/object.cpp"
"link/output.cpp"
"link/patch.cpp"
"link/sdas_obj.cpp"
"link/section.cpp"
"link/symbol.cpp"
"extern/utf8decoder.cpp"
"hashmap.cpp"
"linkdefs.cpp"
"opmath.cpp"
"util.cpp"
"link/assign.c"
"link/main.c"
"link/object.c"
"link/output.c"
"link/patch.c"
"link/script.c"
"link/section.c"
"link/symbol.c"
"hashmap.c"
"linkdefs.c"
"opmath.c"
)
foreach(PROG "asm" "fix" "gfx" "link")
@@ -98,6 +97,22 @@ foreach(PROG "asm" "fix" "gfx" "link")
install(TARGETS rgb${PROG} RUNTIME DESTINATION bin)
endforeach()
set(MANDIR "share/man")
set(man1 "asm/rgbasm.1"
"fix/rgbfix.1"
"gfx/rgbgfx.1"
"link/rgblink.1")
set(man5 "asm/rgbasm.5"
"link/rgblink.5"
"rgbds.5")
set(man7 "gbz80.7"
"rgbds.7")
foreach(SECTION "man1" "man5" "man7")
set(DEST "${MANDIR}/${SECTION}")
install(FILES ${${SECTION}} DESTINATION ${DEST})
endforeach()
if(LIBPNG_FOUND) # pkg-config
target_include_directories(rgbgfx PRIVATE ${LIBPNG_INCLUDE_DIRS})
target_link_directories(rgbgfx PRIVATE ${LIBPNG_LIBRARY_DIRS})

4
src/asm/.gitignore vendored
View File

@@ -1,2 +1,2 @@
/parser.cpp
/parser.hpp
/parser.c
/parser.h

Some files were not shown because too many files have changed in this diff Show More