Compare commits

..

33 Commits

Author SHA1 Message Date
5728effcc6 chore: bump to v0.2.0 2025-07-24 12:14:26 -05:00
fa1a0175b0 ci: remove save-always, remove old vcpkg cache key, flush vcpkg caches 2025-07-24 03:29:22 -05:00
85edb18380 ci: drop linux dependencies: build-essential gettext zlib1g-dev 2025-07-24 03:26:05 -05:00
3a535ee04f fix: linux build linking arg, working build 2025-07-24 02:59:58 -05:00
9b31b392d2 fix(wasm): increase asyncify stack size, working wasm build 2025-07-24 02:39:57 -05:00
999fa14059 chore: remove unused config.toml comments 2025-07-24 02:37:49 -05:00
e925376b7a feat: setup emscripten module for api layer 2025-07-24 02:37:41 -05:00
2596034365 feat: use smallrng for emscripten compat 2025-07-24 02:37:27 -05:00
163855b6e7 fix(wasm): increase audio chunksize to 256 minimum for emscripten audio ctx 2025-07-24 01:14:03 -05:00
645d48aeae ci: use updated setup-emsdk from 'pyodide' v15, fixes emsdk caching, always save vcpkg cache 2025-07-24 01:12:45 -05:00
ec800a88fc fix: use sdl2 internal methods for loading resources for emscripten asset handling 2025-07-24 01:07:22 -05:00
abc37dee4e ci: fix vcpkg cache keys to use target for platforms with multiple targets, allow restore oldkey 2025-07-24 01:04:21 -05:00
1ae7839275 ci: install zlib for linux builds, correct deps/.data filepath 2025-07-24 01:04:21 -05:00
d976d1bc59 ci: specify vcpkg triplets for macos targets 2025-07-24 00:49:22 -05:00
531a5b5d05 ci: inline build script contents, shorten assembly process, separate build/assemble steps 2025-07-24 00:48:49 -05:00
67713fab06 ci: add aarch64-apple-drawin target 2025-07-24 00:46:06 -05:00
b572729e9d feat: reorganize assets/ folder into web/ and game/ 2025-07-24 00:46:06 -05:00
cdc6979458 ci: add cache vcpkg step, remove ineffective apt pkgs 2025-07-24 00:09:43 -05:00
564f88fee5 ci: use proper vcpkg triplet for linux, macos 2025-07-24 00:09:43 -05:00
00c99dc05f ci: remove 'stable' from vcpkg target triplet key 2025-07-23 23:55:15 -05:00
1e12940445 docs: remove unused markdown files in root 2025-07-23 23:24:30 -05:00
dc3c4a7580 ci: VCPKG_SYSTEM_LIBRARIES off, cache emsdk, raw jq output 2025-07-23 23:23:41 -05:00
434b62b036 ci: use cargo metadata with jq for acquiring workspace package version, drop binstall 2025-07-23 23:12:58 -05:00
2bd523e58a ci: add build-essential dependency, apt-get update before 2025-07-23 23:05:06 -05:00
7cd6e8005e ci: add names to workflow jobs, configure binstall to have lower timeout 2025-07-23 22:58:09 -05:00
a8a3745ca1 ci: disable fail-fast, ensure linux vcpkg dependencies are installed 2025-07-23 22:46:57 -05:00
cfa26bf146 ci: use build matrix for desktop builds 2025-07-23 22:45:56 -05:00
bfbbb71752 ci: verbose vcpkg builds on linux 2025-07-23 22:30:11 -05:00
979f736f54 ci: drop rust toolchain to 1.86.0 2025-07-23 22:26:08 -05:00
5a7f6a4c10 ci: remove archive assembly steps for statically linked builds 2025-07-23 22:22:55 -05:00
b66c9ce135 fix: emscripten assets 2025-07-23 22:18:54 -05:00
f5363516c3 chore: remove unused sdl2-image vcpkg features 2025-07-23 21:53:55 -05:00
320da36b83 feat: use cargo-vcpkg in build workflow 2025-07-23 21:53:03 -05:00
40 changed files with 312 additions and 383 deletions

View File

@@ -1,12 +1,16 @@
[target.'cfg(target_os = "emscripten")'] [target.'cfg(target_os = "emscripten")']
# TODO: Document what the fuck this is.
rustflags = [ rustflags = [
# "-O", "-C", "link-args=-O2 --profiling", # Stack size is required for this project, it will crash otherwise.
#"-C", "link-args=-O3 --closure 1", "-C", "link-args=-sASYNCIFY=1 -sASYNCIFY_STACK_SIZE=8192 -sALLOW_MEMORY_GROWTH=1",
# "-C", "link-args=-g -gsource-map",
"-C", "link-args=-sASYNCIFY -sALLOW_MEMORY_GROWTH=1",
# "-C", "link-args=-sALLOW_MEMORY_GROWTH=1",
"-C", "link-args=-sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sUSE_SDL_MIXER=2 -sUSE_OGG=1 -sUSE_SDL_GFX=2 -sUSE_SDL_TTF=2 -sSDL2_IMAGE_FORMATS=['png']", "-C", "link-args=-sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sUSE_SDL_MIXER=2 -sUSE_OGG=1 -sUSE_SDL_GFX=2 -sUSE_SDL_TTF=2 -sSDL2_IMAGE_FORMATS=['png']",
# USE_OGG, USE_VORBIS for OGG/VORBIS usage "-C", "link-args=--preload-file assets/game/",
"-C", "link-args=--preload-file assets/", ]
[target.'cfg(target_os = "linux")']
rustflags = [
# Manually link zlib.
# The `sdl2` crate's build script uses `libpng`, which requires `zlib`.
# By adding `-lz` here, we ensure it's passed to the linker after `libpng`,
# which is required for the linker to correctly resolve symbols.
"-C", "link-arg=-lz",
] ]

135
.github/workflows/build.yaml vendored Normal file
View File

@@ -0,0 +1,135 @@
name: Build
on: [push]
permissions:
contents: write
env:
RUST_TOOLCHAIN: 1.86.0
jobs:
build:
name: Build (${{ matrix.target }})
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
artifact_name: pacman
- os: macos-13
target: x86_64-apple-darwin
artifact_name: pacman
- os: macos-latest
target: aarch64-apple-darwin
artifact_name: pacman
- os: windows-latest
target: x86_64-pc-windows-gnu
artifact_name: pacman.exe
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rust Toolchain
uses: dtolnay/rust-toolchain@master
with:
target: ${{ matrix.target }}
toolchain: ${{ env.RUST_TOOLCHAIN }}
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Cache vcpkg
uses: actions/cache@v4
with:
path: target/vcpkg
key: A-vcpkg-${{ runner.os }}-${{ matrix.target }}-${{ hashFiles('Cargo.toml', 'Cargo.lock') }}
restore-keys: |
A-vcpkg-${{ runner.os }}-${{ matrix.target }}-
- name: Vcpkg Linux Dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libltdl-dev
- name: Vcpkg
run: |
cargo install cargo-vcpkg
cargo vcpkg -v build
- name: Build
run: cargo build --release
- name: Acquire Package Version
shell: bash
run: |
PACKAGE_VERSION=$(cargo metadata --format-version 1 --no-deps | jq '.packages[0].version' -r)
echo "PACKAGE_VERSION=${PACKAGE_VERSION}" >> $GITHUB_ENV
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: "pacman-${{ env.PACKAGE_VERSION }}-${{ matrix.target }}"
path: ./target/release/${{ matrix.artifact_name }}
retention-days: 7
if-no-files-found: error
wasm:
name: Build (wasm32-unknown-emscripten)
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Emscripten SDK
uses: pyodide/setup-emsdk@v15
with:
version: 3.1.43
actions-cache-folder: "emsdk-cache"
- name: Setup Rust (WASM32 Emscripten)
uses: dtolnay/rust-toolchain@master
with:
target: wasm32-unknown-emscripten
toolchain: ${{ env.RUST_TOOLCHAIN }}
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Install pnpm
uses: pnpm/action-setup@v3
with:
version: 8
run_install: true
- name: Build with Emscripten
run: |
cargo build --target=wasm32-unknown-emscripten --release
- name: Assemble
run: |
echo "Generating CSS"
pnpx postcss-cli ./assets/site/styles.scss -o ./assets/site/build.css
echo "Copying WASM files"
mkdir -p dist
cp assets/site/{build.css,favicon.ico,index.html} dist
output_folder="target/wasm32-unknown-emscripten/release"
cp $output_folder/pacman.{wasm,js} $output_folder/deps/pacman.data dist
- name: Upload Artifact
uses: actions/upload-pages-artifact@v3
with:
path: "./dist/"
retention-days: 7
- name: Deploy
uses: actions/deploy-pages@v4

View File

@@ -1,231 +0,0 @@
name: Build
on: [push]
permissions:
contents: write
env:
RUST_TOOLCHAIN: 1.88.0
jobs:
wasm:
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Emscripten SDK
uses: mymindstorm/setup-emsdk@v14
with:
version: 3.1.43
- name: Setup Rust (WASM32 Emscripten)
uses: dtolnay/rust-toolchain@master
with:
target: wasm32-unknown-emscripten
toolchain: ${{ env.RUST_TOOLCHAIN }}
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Install pnpm
uses: pnpm/action-setup@v3
with:
version: 8
run_install: true
- name: Build
run: ./build.sh -er # release mode, skip emsdk
- name: Upload Artifact
uses: actions/upload-pages-artifact@v3
with:
path: "./dist/"
retention-days: 7
- name: Deploy
uses: actions/deploy-pages@v4
linux:
runs-on: ubuntu-latest
env:
TARGET: x86_64-unknown-linux-gnu
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install SDL2 Packages
run: sudo apt-get install libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-ttf-dev libsdl2-gfx-dev
- name: Setup Rust Toolchain (Linux)
uses: dtolnay/rust-toolchain@master
with:
target: ${{ env.TARGET }}
toolchain: ${{ env.RUST_TOOLCHAIN }}
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Build
run: cargo build --release
- name: Assemble Archive
run: |
mkdir /tmp/example/
cp ./target/release/pacman /tmp/example/
chmod a+x /tmp/example/pacman
mkdir /tmp/example/assets
cp ./assets/TerminalVector.ttf ./assets/fruit.png /tmp/example/assets
- name: Install Cargo Binstall
uses: cargo-bins/cargo-binstall@main
- name: Acquire Package Version
run: |
cargo binstall toml-cli -y
PACKAGE_VERSION=$(toml get ./Cargo.toml package.version --raw)
echo "PACKAGE_VERSION=${PACKAGE_VERSION}" >> $GITHUB_ENV
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: "pacman-${{ env.PACKAGE_VERSION }}-${{ env.TARGET }}"
path: /tmp/example/
retention-days: 7
if-no-files-found: error
macos:
runs-on: macos-13
env:
TARGET: x86_64-apple-darwin
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install SDL2 Packages
run: brew install sdl2 sdl2_image sdl2_mixer sdl2_ttf sdl2_gfx
- name: Setup Rust Toolchain (MacOS)
uses: dtolnay/rust-toolchain@master
with:
target: ${{ env.TARGET }}
toolchain: ${{ env.RUST_TOOLCHAIN }}
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Build
run: cargo build --release
- name: Assemble Archive
run: |
mkdir /tmp/example/
cp ./target/release/pacman /tmp/example/
mkdir /tmp/example/assets
cp ./assets/TerminalVector.ttf ./assets/fruit.png /tmp/example/assets
- name: Install Cargo Binstall
uses: cargo-bins/cargo-binstall@main
- name: Acquire Package Version
run: |
cargo binstall toml-cli -y
PACKAGE_VERSION=$(toml get ./Cargo.toml package.version --raw)
echo "PACKAGE_VERSION=${PACKAGE_VERSION}" >> $GITHUB_ENV
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: "pacman-${{ env.PACKAGE_VERSION }}-${{ env.TARGET }}"
path: /tmp/example/
retention-days: 7
if-no-files-found: error
windows:
env:
TARGET: x86_64-pc-windows-gnu
SDL2: 2.30.2
SDL2_TTF: 2.22.0
SDL2_MIXER: 2.8.0
SDL2_IMAGE: 2.8.2
# SDL2_GFX: 1.0.4
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Download SDL2 Libraries
run: |
curl -L "https://github.com/libsdl-org/SDL/releases/download/release-${{ env.SDL2 }}/SDL2-devel-${{ env.SDL2 }}-VC.zip" -o "sdl2_devel.zip"
curl -L "https://github.com/libsdl-org/SDL_mixer/releases/download/release-${{ env.SDL2_MIXER }}/SDL2_mixer-devel-${{ env.SDL2_MIXER }}-VC.zip" -o "sdl2_mixer_devel.zip"
curl -L "https://github.com/libsdl-org/SDL_ttf/releases/download/release-${{ env.SDL2_TTF }}/SDL2_ttf-devel-${{ env.SDL2_TTF }}-VC.zip" -o "sdl2_ttf_devel.zip"
curl -L "https://github.com/libsdl-org/SDL_image/releases/download/release-${{ env.SDL2_IMAGE }}/SDL2_image-devel-${{ env.SDL2_IMAGE }}-VC.zip" -o "sdl2_image_devel.zip"
- name: Extract SDL2 DLLs
run: |
7z x ./sdl2_devel.zip -o"./tmp/"
mv ./tmp/SDL2-${{ env.SDL2 }}/lib/x64/SDL2.dll ./
mv ./tmp/SDL2-${{ env.SDL2 }}/lib/x64/SDL2.lib ./
7z x ./sdl2_mixer_devel.zip -o"./tmp/"
mv ./tmp/SDL2_mixer-${{ env.SDL2_MIXER }}/lib/x64/SDL2_mixer.dll ./
mv ./tmp/SDL2_mixer-${{ env.SDL2_MIXER }}/lib/x64/SDL2_mixer.lib ./
7z x ./sdl2_ttf_devel.zip -o"./tmp/"
mv ./tmp/SDL2_ttf-${{ env.SDL2_TTF }}/lib/x64/SDL2_ttf.dll ./
mv ./tmp/SDL2_ttf-${{ env.SDL2_TTF }}/lib/x64/SDL2_ttf.lib ./
7z x ./sdl2_image_devel.zip -o"./tmp/"
mv ./tmp/SDL2_image-${{ env.SDL2_IMAGE }}/lib/x64/SDL2_image.dll ./
mv ./tmp/SDL2_image-${{ env.SDL2_IMAGE }}/lib/x64/SDL2_image.lib ./
- name: Install SDL2_gfx
run: |
C:\vcpkg\vcpkg.exe install sdl2-gfx:x64-windows-release
cp C:\vcpkg\packages\sdl2-gfx_x64-windows-release\bin\SDL2_gfx.dll ./
cp C:\vcpkg\packages\sdl2-gfx_x64-windows-release\lib\SDL2_gfx.lib ./
- name: Setup Rust (Windows)
uses: dtolnay/rust-toolchain@master
with:
target: ${{ env.TARGET }}
toolchain: ${{ env.RUST_TOOLCHAIN }}
- name: Rust Cache
uses: Swatinem/rust-cache@v2
- name: Build
run: cargo build --release
- name: Prepare Archive
run: |
New-Item -Type Directory ./release/
Move-Item -Path ./target/release/pacman.exe -Destination ./release/
Move-Item -Path ./SDL2.dll, ./SDL2_image.dll, ./SDL2_ttf.dll, ./SDL2_mixer.dll, ./SDL2_gfx.dll -Destination ./release/
New-Item -Type Directory ./release/assets/
Move-Item -Path ./assets/TerminalVector.ttf, ./assets/fruit.png -Destination ./release/assets/
- name: Install Cargo Binstall
uses: cargo-bins/cargo-binstall@main
- name: Acquire Package Version
run: |
cargo binstall toml-cli -y
PACKAGE_VERSION=$(toml get ./Cargo.toml package.version --raw)
echo "PACKAGE_VERSION=${PACKAGE_VERSION}" >> $env:GITHUB_ENV
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: "pacman-${{ env.PACKAGE_VERSION }}-${{ env.TARGET }}"
path: ./release/
retention-days: 7
if-no-files-found: error

4
.gitignore vendored
View File

@@ -3,5 +3,5 @@
.idea .idea
*.dll *.dll
rust-sdl2-emscripten/ rust-sdl2-emscripten/
assets/build.css assets/site/build.css
emsdk/ emsdk/

View File

@@ -1,7 +0,0 @@
# Building Pac-Man
## GitHub Actions Workflow
1. Build workflow produces executables & WASM files for all platforms
2. Uploaded as artifacts
3. Deployment workflow downloads artifacts and uploads to GitHub Pages

42
Cargo.lock generated
View File

@@ -174,7 +174,7 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]] [[package]]
name = "pacman" name = "pacman"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"glam", "glam",
@@ -212,15 +212,6 @@ version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.95" version = "1.0.95"
@@ -251,17 +242,6 @@ version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
dependencies = [ dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core", "rand_core",
] ]
@@ -647,23 +627,3 @@ checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
dependencies = [ dependencies = [
"bitflags 2.9.1", "bitflags 2.9.1",
] ]
[[package]]
name = "zerocopy"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
dependencies = [
"proc-macro2",
"quote",
"syn",
]

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "pacman" name = "pacman"
version = "0.1.0" version = "0.2.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -12,7 +12,7 @@ tracing-subscriber = {version = "0.3.17", features = ["env-filter"]}
lazy_static = "1.5.0" lazy_static = "1.5.0"
sdl2 = { version = "0.38.0", features = ["image", "ttf"] } sdl2 = { version = "0.38.0", features = ["image", "ttf"] }
spin_sleep = "1.3.2" spin_sleep = "1.3.2"
rand = "0.9.2" rand = { version = "0.9.2", default-features = false, features = ["small_rng", "os_rng"] }
pathfinding = "4.14" pathfinding = "4.14"
once_cell = "1.21.3" once_cell = "1.21.3"
thiserror = "1.0" thiserror = "1.0"
@@ -35,13 +35,15 @@ default-features = false
features = ["ttf","image","gfx","mixer","static-link","use-vcpkg"] features = ["ttf","image","gfx","mixer","static-link","use-vcpkg"]
[package.metadata.vcpkg] [package.metadata.vcpkg]
dependencies = ["sdl2", "sdl2-image[libjpeg-turbo,tiff,libwebp]", "sdl2-ttf", "sdl2-gfx", "sdl2-mixer"] dependencies = ["sdl2", "sdl2-image", "sdl2-ttf", "sdl2-gfx", "sdl2-mixer"]
git = "https://github.com/microsoft/vcpkg" git = "https://github.com/microsoft/vcpkg"
rev = "2024.05.24" # release 2024.05.24 # to check for a new one, check https://github.com/microsoft/vcpkg/releases rev = "2024.05.24" # release 2024.05.24 # to check for a new one, check https://github.com/microsoft/vcpkg/releases
[package.metadata.vcpkg.target] [package.metadata.vcpkg.target]
x86_64-pc-windows-msvc = { triplet = "x64-windows-static-md" } x86_64-pc-windows-msvc = { triplet = "x64-windows-static-md" }
stable-x86_64-unknown-linux-gnu = { triplet = "x86_64-unknown-linux-gnu" } x86_64-unknown-linux-gnu = { triplet = "x64-linux" }
x86_64-apple-darwin = { triplet = "x64-osx" }
aarch64-apple-darwin = { triplet = "arm64-osx" }
[target.'cfg(target_os = "emscripten")'.dependencies] [target.'cfg(target_os = "emscripten")'.dependencies]
libc = "0.2.16" libc = "0.2.16"

View File

@@ -1,35 +0,0 @@
# Implementation
A document detailing the implementation the project from rendering, to game logic, to build systems.
## Rendering
1. Map
- May require procedural text generation later on (cacheable?)
2. Pacman
3. Ghosts
- Requires colors
4. Items
5. Interface
- Requires fonts
## Grid System
1. How does the grid system work?
The grid is 28 x 36 (although, the map texture is 28 x 37), and each cell is 24x24 (pixels).
Many of the walls in the map texture only occupy a portion of the cell, so some items are able to render across multiple cells.
24x24 assets include pellets, the energizer, and the map itself ()
2. What constraints must be enforced on Ghosts and PacMan?
3. How do movement transitions work?
All entities store a precise position, and a direction. This position is only used for animation, rendering, and collision purposes. Otherwise, a separate 'cell position' (which is 24 times less precise, owing to the fact that it is based on the entity's position within the grid).
When an entity is transitioning between cells, movement directions are acknowledged, but won't take effect until the next cell has been entered completely.
4. Between transitions, how does collision detection work?
It appears the original implementation used cell-level detection.
I worry this may be prone to division errors. Make sure to use rounding (50% >=).

View File

Before

Width:  |  Height:  |  Size: 174 B

After

Width:  |  Height:  |  Size: 174 B

View File

Before

Width:  |  Height:  |  Size: 158 B

After

Width:  |  Height:  |  Size: 158 B

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 528 B

After

Width:  |  Height:  |  Size: 528 B

View File

Before

Width:  |  Height:  |  Size: 394 B

After

Width:  |  Height:  |  Size: 394 B

View File

Before

Width:  |  Height:  |  Size: 228 B

After

Width:  |  Height:  |  Size: 228 B

View File

Before

Width:  |  Height:  |  Size: 370 B

After

Width:  |  Height:  |  Size: 370 B

View File

Before

Width:  |  Height:  |  Size: 90 B

After

Width:  |  Height:  |  Size: 90 B

View File

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

View File

View File

View File

23
assets/site/build.css Normal file
View File

@@ -0,0 +1,23 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@font-face {
font-family: "Liberation Mono";
src:
url("LiberationMono.woff2") format("woff2"),
url("LiberationMono.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
}
canvas {
@apply w-full h-[65vh] min-h-[200px] block mx-auto bg-black;
}
.code {
@apply px-1 rounded font-mono bg-zinc-900 border border-zinc-700 lowercase;
}
/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0eWxlcy5zY3NzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIiwiZmlsZSI6ImJ1aWxkLmNzcyIsInNvdXJjZXNDb250ZW50IjpbIkB0YWlsd2luZCBiYXNlO1xuQHRhaWx3aW5kIGNvbXBvbmVudHM7XG5AdGFpbHdpbmQgdXRpbGl0aWVzO1xuXG5AZm9udC1mYWNlIHtcbiAgICBmb250LWZhbWlseTogXCJMaWJlcmF0aW9uIE1vbm9cIjtcbiAgICBzcmM6XG4gICAgICAgIHVybChcIkxpYmVyYXRpb25Nb25vLndvZmYyXCIpIGZvcm1hdChcIndvZmYyXCIpLFxuICAgICAgICB1cmwoXCJMaWJlcmF0aW9uTW9uby53b2ZmXCIpIGZvcm1hdChcIndvZmZcIik7XG4gICAgZm9udC13ZWlnaHQ6IG5vcm1hbDtcbiAgICBmb250LXN0eWxlOiBub3JtYWw7XG4gICAgZm9udC1kaXNwbGF5OiBzd2FwO1xufVxuXG5jYW52YXMge1xuICAgIEBhcHBseSB3LWZ1bGwgaC1bNjV2aF0gbWluLWgtWzIwMHB4XSBibG9jayBteC1hdXRvIGJnLWJsYWNrO1xufVxuXG4uY29kZSB7XG4gICAgQGFwcGx5IHB4LTEgcm91bmRlZCBmb250LW1vbm8gYmctemluYy05MDAgYm9yZGVyIGJvcmRlci16aW5jLTcwMCBsb3dlcmNhc2U7XG59XG4iXX0= */

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Binary file not shown.

View File

Binary file not shown.

View File

Binary file not shown.

View File

@@ -52,20 +52,18 @@ else
fi fi
echo "Generating CSS" echo "Generating CSS"
pnpx postcss-cli ./assets/styles.scss -o ./assets/build.css pnpx postcss-cli ./assets/site/styles.scss -o ./assets/site/build.css
echo "Copying WASM files" echo "Copying WASM files"
mkdir -p dist mkdir -p dist
output_folder="target/wasm32-unknown-emscripten/$build_type" output_folder="target/wasm32-unknown-emscripten/$build_type"
cp assets/index.html dist
# cp assets/*.woff* dist cp assets/site/{build.css,favicon.ico,index.html} dist
cp assets/build.css dist cp $output_folder/pacman.{wasm,js} dist
cp assets/favicon.ico dist if [ -f $output_folder/deps/pacman.data ]; then
cp $output_folder/pacman.wasm dist cp $output_folder/deps/pacman.data dist
cp $output_folder/pacman.js dist fi
# only if .data file exists
cp $output_folder/deps/pacman.data dist
if [ -f $output_folder/pacman.wasm.map ]; then if [ -f $output_folder/pacman.wasm.map ]; then
cp $output_folder/pacman.wasm.map dist cp $output_folder/pacman.wasm.map dist
fi fi

View File

@@ -56,40 +56,47 @@ async function setupEmscripten() {
async function buildWeb(release: boolean) { async function buildWeb(release: boolean) {
console.log("Building WASM with Emscripten..."); console.log("Building WASM with Emscripten...");
const rustcFlags = [
"-C",
"link-arg=--preload-file",
"-C",
"link-arg=assets",
].join(" ");
if (release) { if (release) {
await $`cargo build --target=wasm32-unknown-emscripten --release`; await $`env RUSTFLAGS=${rustcFlags} cargo build --target=wasm32-unknown-emscripten --release`;
} else { } else {
await $`cargo build --target=wasm32-unknown-emscripten`; await $`env RUSTFLAGS=${rustcFlags} cargo build --target=wasm32-unknown-emscripten`;
} }
console.log("Generating CSS..."); console.log("Generating CSS...");
await $`pnpx postcss-cli ./assets/styles.scss -o ./assets/build.css`; await $`pnpx postcss-cli ./assets/site/styles.scss -o ./assets/site/build.css`;
console.log("Copying WASM files..."); console.log("Copying WASM files...");
const buildType = release ? "release" : "debug"; const buildType = release ? "release" : "debug";
const outputFolder = `target/wasm32-unknown-emscripten/${buildType}`; const outputFolder = `target/wasm32-unknown-emscripten/${buildType}`;
await $`mkdir -p dist`; await $`mkdir -p dist`;
await $`cp assets/index.html dist`; await $`cp assets/site/index.html dist`;
await $`cp assets/*.woff* dist`; await $`cp assets/site/*.woff* dist`;
await $`cp assets/build.css dist`; await $`cp assets/site/build.css dist`;
await $`cp assets/favicon.ico dist`; await $`cp assets/site/favicon.ico dist`;
await $`cp ${outputFolder}/spiritus.wasm dist`; await $`cp ${outputFolder}/pacman.wasm dist`;
await $`cp ${outputFolder}/spiritus.js dist`; await $`cp ${outputFolder}/pacman.js dist`;
// Check if .data file exists before copying // Check if .data file exists before copying
try { try {
await fs.access(`${outputFolder}/deps/spiritus.data`); await fs.access(`${outputFolder}/pacman.data`);
await $`cp ${outputFolder}/deps/spiritus.data dist`; await $`cp ${outputFolder}/pacman.data dist`;
} catch (e) { } catch (e) {
console.log("No spiritus.data file found, skipping copy."); console.log("No pacman.data file found, skipping copy.");
} }
// Check if .map file exists before copying // Check if .map file exists before copying
try { try {
await fs.access(`${outputFolder}/spiritus.wasm.map`); await fs.access(`${outputFolder}/pacman.wasm.map`);
await $`cp ${outputFolder}/spiritus.wasm.map dist`; await $`cp ${outputFolder}/pacman.wasm.map dist`;
} catch (e) { } catch (e) {
console.log("No spiritus.wasm.map file found, skipping copy."); console.log("No pacman.wasm.map file found, skipping copy.");
} }
console.log("WASM files copied."); console.log("WASM files copied.");

View File

@@ -31,23 +31,42 @@ pub enum Asset {
// Add more as needed // Add more as needed
} }
impl Asset {
pub fn path(&self) -> &str {
use Asset::*;
match self {
Wav1 => "wav/1.ogg",
Wav2 => "wav/2.ogg",
Wav3 => "wav/3.ogg",
Wav4 => "wav/4.ogg",
Pacman => "32/pacman.png",
Pellet => "24/pellet.png",
Energizer => "24/energizer.png",
Map => "map.png",
FontKonami => "font/konami.ttf",
GhostBody => "32/ghost_body.png",
GhostEyes => "32/ghost_eyes.png",
}
}
}
#[cfg(not(target_os = "emscripten"))] #[cfg(not(target_os = "emscripten"))]
mod imp { mod imp {
use super::*; use super::*;
macro_rules! asset_bytes_enum { macro_rules! asset_bytes_enum {
( $asset:expr ) => { ( $asset:expr ) => {
match $asset { match $asset {
Asset::Wav1 => Cow::Borrowed(include_bytes!("../assets/wav/1.ogg")), Asset::Wav1 => Cow::Borrowed(include_bytes!("../assets/game/wav/1.ogg")),
Asset::Wav2 => Cow::Borrowed(include_bytes!("../assets/wav/2.ogg")), Asset::Wav2 => Cow::Borrowed(include_bytes!("../assets/game/wav/2.ogg")),
Asset::Wav3 => Cow::Borrowed(include_bytes!("../assets/wav/3.ogg")), Asset::Wav3 => Cow::Borrowed(include_bytes!("../assets/game/wav/3.ogg")),
Asset::Wav4 => Cow::Borrowed(include_bytes!("../assets/wav/4.ogg")), Asset::Wav4 => Cow::Borrowed(include_bytes!("../assets/game/wav/4.ogg")),
Asset::Pacman => Cow::Borrowed(include_bytes!("../assets/32/pacman.png")), Asset::Pacman => Cow::Borrowed(include_bytes!("../assets/game/32/pacman.png")),
Asset::Pellet => Cow::Borrowed(include_bytes!("../assets/24/pellet.png")), Asset::Pellet => Cow::Borrowed(include_bytes!("../assets/game/24/pellet.png")),
Asset::Energizer => Cow::Borrowed(include_bytes!("../assets/24/energizer.png")), Asset::Energizer => Cow::Borrowed(include_bytes!("../assets/game/24/energizer.png")),
Asset::Map => Cow::Borrowed(include_bytes!("../assets/map.png")), Asset::Map => Cow::Borrowed(include_bytes!("../assets/game/map.png")),
Asset::FontKonami => Cow::Borrowed(include_bytes!("../assets/font/konami.ttf")), Asset::FontKonami => Cow::Borrowed(include_bytes!("../assets/game/font/konami.ttf")),
Asset::GhostBody => Cow::Borrowed(include_bytes!("../assets/32/ghost_body.png")), Asset::GhostBody => Cow::Borrowed(include_bytes!("../assets/game/32/ghost_body.png")),
Asset::GhostEyes => Cow::Borrowed(include_bytes!("../assets/32/ghost_eyes.png")), Asset::GhostEyes => Cow::Borrowed(include_bytes!("../assets/game/32/ghost_eyes.png")),
} }
}; };
} }
@@ -59,15 +78,17 @@ mod imp {
#[cfg(target_os = "emscripten")] #[cfg(target_os = "emscripten")]
mod imp { mod imp {
use super::*; use super::*;
use std::fs; use sdl2::rwops::RWops;
use std::path::Path; use std::io::Read;
pub fn get_asset_bytes(asset: Asset) -> Result<Cow<'static, [u8]>, AssetError> { pub fn get_asset_bytes(asset: Asset) -> Result<Cow<'static, [u8]>, AssetError> {
let path = Path::new("assets").join(asset.path()); let path = format!("assets/game/{}", asset.path());
if !path.exists() { let mut rwops = RWops::from_file(&path, "rb").map_err(|_| AssetError::NotFound(asset.path().to_string()))?;
return Err(AssetError::NotFound(asset.path().to_string())); let len = rwops.len().ok_or_else(|| AssetError::NotFound(asset.path().to_string()))?;
} let mut buf = vec![0u8; len];
let bytes = fs::read(&path)?; rwops
Ok(Cow::Owned(bytes)) .read_exact(&mut buf)
.map_err(|e| AssetError::Io(std::io::Error::new(std::io::ErrorKind::Other, e)))?;
Ok(Cow::Owned(buf))
} }
} }

View File

@@ -24,7 +24,7 @@ impl Audio {
let frequency = 44100; let frequency = 44100;
let format = DEFAULT_FORMAT; let format = DEFAULT_FORMAT;
let channels = 4; let channels = 4;
let chunk_size = 128; let chunk_size = 256; // 256 is minimum for emscripten
mixer::open_audio(frequency, format, 1, chunk_size).expect("Failed to open audio"); mixer::open_audio(frequency, format, 1, chunk_size).expect("Failed to open audio");
mixer::allocate_channels(channels); mixer::allocate_channels(channels);

31
src/emscripten.rs Normal file
View File

@@ -0,0 +1,31 @@
#[allow(dead_code)]
#[cfg(target_os = "emscripten")]
pub mod emscripten {
use std::os::raw::c_uint;
extern "C" {
pub fn emscripten_get_now() -> f64;
pub fn emscripten_sleep(ms: c_uint);
pub fn emscripten_get_element_css_size(target: *const u8, width: *mut f64, height: *mut f64) -> i32;
}
// milliseconds since start of program
pub fn now() -> f64 {
unsafe { emscripten_get_now() }
}
pub fn sleep(ms: u32) {
unsafe {
emscripten_sleep(ms);
}
}
pub fn get_canvas_size() -> (u32, u32) {
let mut width = 0.0;
let mut height = 0.0;
unsafe {
emscripten_get_element_css_size("canvas\0".as_ptr(), &mut width, &mut height);
}
(width as u32, height as u32)
}
}

View File

@@ -4,7 +4,9 @@ use std::ops::Not;
use std::rc::Rc; use std::rc::Rc;
use glam::UVec2; use glam::UVec2;
use rand::rngs::SmallRng;
use rand::seq::IteratorRandom; use rand::seq::IteratorRandom;
use rand::SeedableRng;
use sdl2::image::LoadTexture; use sdl2::image::LoadTexture;
use sdl2::keyboard::Keycode; use sdl2::keyboard::Keycode;
use sdl2::render::{Texture, TextureCreator}; use sdl2::render::{Texture, TextureCreator};
@@ -211,7 +213,7 @@ impl<'a> Game<'a> {
{ {
let mut map = self.map.borrow_mut(); let mut map = self.map.borrow_mut();
let valid_positions = map.get_valid_playable_positions(); let valid_positions = map.get_valid_playable_positions();
let mut rng = rand::rng(); let mut rng = SmallRng::from_os_rng();
// Randomize Pac-Man position // Randomize Pac-Man position
if let Some(pos) = valid_positions.iter().choose(&mut rng) { if let Some(pos) = valid_positions.iter().choose(&mut rng) {

View File

@@ -1,4 +1,6 @@
use rand::rngs::SmallRng;
use rand::Rng; use rand::Rng;
use rand::SeedableRng;
use crate::animation::{AnimatedAtlasTexture, FrameDrawn}; use crate::animation::{AnimatedAtlasTexture, FrameDrawn};
use crate::constants::{MapTile, BOARD_WIDTH}; use crate::constants::{MapTile, BOARD_WIDTH};
@@ -117,7 +119,7 @@ impl Ghost<'_> {
/// Gets a random adjacent tile for frightened mode /// Gets a random adjacent tile for frightened mode
fn get_random_target(&self) -> IVec2 { fn get_random_target(&self) -> IVec2 {
let mut rng = rand::rng(); let mut rng = SmallRng::from_os_rng();
let mut possible_moves = Vec::new(); let mut possible_moves = Vec::new();
// Check all four directions // Check all four directions

View File

@@ -59,6 +59,8 @@ mod constants;
mod debug; mod debug;
mod direction; mod direction;
mod edible; mod edible;
#[cfg(target_os = "emscripten")]
mod emscripten;
mod entity; mod entity;
mod game; mod game;
mod ghost; mod ghost;
@@ -68,6 +70,26 @@ mod map;
mod modulation; mod modulation;
mod pacman; mod pacman;
#[cfg(not(target_os = "emscripten"))]
fn sleep(value: Duration) {
spin_sleep::sleep(value);
}
#[cfg(target_os = "emscripten")]
fn sleep(value: Duration) {
emscripten::emscripten::sleep(value.as_millis() as u32);
}
#[cfg(target_os = "emscripten")]
fn now() -> std::time::Instant {
std::time::Instant::now() + std::time::Duration::from_millis(emscripten::emscripten::now() as u64)
}
#[cfg(not(target_os = "emscripten"))]
fn now() -> std::time::Instant {
std::time::Instant::now()
}
/// The main entry point of the application. /// The main entry point of the application.
/// ///
/// This function initializes SDL, the window, the game state, and then enters /// This function initializes SDL, the window, the game state, and then enters
@@ -179,14 +201,7 @@ pub fn main() {
if start.elapsed() < loop_time { if start.elapsed() < loop_time {
let time = loop_time.saturating_sub(start.elapsed()); let time = loop_time.saturating_sub(start.elapsed());
if time != Duration::ZERO { if time != Duration::ZERO {
#[cfg(not(target_os = "emscripten"))] sleep(time);
{
spin_sleep::sleep(time);
}
#[cfg(target_os = "emscripten")]
{
std::thread::sleep(time);
}
} }
} else { } else {
event!( event!(

View File

@@ -1,5 +1,7 @@
//! This module defines the game map and provides functions for interacting with it. //! This module defines the game map and provides functions for interacting with it.
use rand::rngs::SmallRng;
use rand::seq::IteratorRandom; use rand::seq::IteratorRandom;
use rand::SeedableRng;
use crate::constants::{MapTile, BOARD_OFFSET, CELL_SIZE}; use crate::constants::{MapTile, BOARD_OFFSET, CELL_SIZE};
use crate::constants::{BOARD_HEIGHT, BOARD_WIDTH}; use crate::constants::{BOARD_HEIGHT, BOARD_WIDTH};
@@ -120,7 +122,7 @@ impl Map {
} }
} }
} }
let mut rng = rand::rng(); let mut rng = SmallRng::from_os_rng();
let &start = pellet_positions let &start = pellet_positions
.iter() .iter()
.choose(&mut rng) .choose(&mut rng)