Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
130c5fdd57
|
||
|
|
43ea8b80c9
|
||
|
|
3d33a493bf
|
||
|
|
3181891e0a
|
||
|
|
bf0c4c4b94
|
||
|
|
2713dd76e3
|
||
|
|
03886cf6f0
|
||
|
|
44ebae30a9
|
||
|
|
88c75e43ae
|
||
|
|
87c51ba8fc
|
||
|
|
da48c8b116
|
||
|
|
78f087ec13
|
||
|
|
40536f4b30
|
||
|
|
d46f447273
|
||
|
|
b07f2f377a
|
||
|
|
56c59634b2
|
@@ -1,29 +0,0 @@
|
|||||||
name: CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ main, master ]
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
submodules: recursive
|
|
||||||
|
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
|
||||||
with:
|
|
||||||
components: rustfmt, clippy
|
|
||||||
|
|
||||||
- uses: Swatinem/rust-cache@v2
|
|
||||||
|
|
||||||
- name: Format check
|
|
||||||
run: cargo fmt -- --check
|
|
||||||
|
|
||||||
- name: Clippy
|
|
||||||
run: cargo clippy --workspace --all-features
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
run: cargo test --workspace --all-targets --all-features --no-fail-fast
|
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
# This file was autogenerated by dist: https://axodotdev.github.io/cargo-dist
|
|
||||||
#
|
|
||||||
# Copyright 2022-2024, axodotdev
|
|
||||||
# SPDX-License-Identifier: MIT or Apache-2.0
|
|
||||||
#
|
|
||||||
# CI that:
|
|
||||||
#
|
|
||||||
# * checks for a Git Tag that looks like a release
|
|
||||||
# * builds artifacts with dist (archives, installers, hashes)
|
|
||||||
# * uploads those artifacts to temporary workflow zip
|
|
||||||
# * on success, uploads the artifacts to a GitHub Release
|
|
||||||
#
|
|
||||||
# Note that the GitHub Release will be created with a generated
|
|
||||||
# title/body based on your changelogs.
|
|
||||||
|
|
||||||
name: Release
|
|
||||||
permissions:
|
|
||||||
"contents": "write"
|
|
||||||
|
|
||||||
# This task will run whenever you push a git tag that looks like a version
|
|
||||||
# like "1.0.0", "v0.1.0-prerelease.1", "my-app/0.1.0", "releases/v1.0.0", etc.
|
|
||||||
# Various formats will be parsed into a VERSION and an optional PACKAGE_NAME, where
|
|
||||||
# PACKAGE_NAME must be the name of a Cargo package in your workspace, and VERSION
|
|
||||||
# must be a Cargo-style SemVer Version (must have at least major.minor.patch).
|
|
||||||
#
|
|
||||||
# If PACKAGE_NAME is specified, then the announcement will be for that
|
|
||||||
# package (erroring out if it doesn't have the given version or isn't dist-able).
|
|
||||||
#
|
|
||||||
# If PACKAGE_NAME isn't specified, then the announcement will be for all
|
|
||||||
# (dist-able) packages in the workspace with that version (this mode is
|
|
||||||
# intended for workspaces with only one dist-able package, or with all dist-able
|
|
||||||
# packages versioned/released in lockstep).
|
|
||||||
#
|
|
||||||
# If you push multiple tags at once, separate instances of this workflow will
|
|
||||||
# spin up, creating an independent announcement for each one. However, GitHub
|
|
||||||
# will hard limit this to 3 tags per commit, as it will assume more tags is a
|
|
||||||
# mistake.
|
|
||||||
#
|
|
||||||
# If there's a prerelease-style suffix to the version, then the release(s)
|
|
||||||
# will be marked as a prerelease.
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- '**[0-9]+.[0-9]+.[0-9]+*'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
# Run 'dist plan' (or host) to determine what tasks we need to do
|
|
||||||
plan:
|
|
||||||
runs-on: "ubuntu-22.04"
|
|
||||||
outputs:
|
|
||||||
val: ${{ steps.plan.outputs.manifest }}
|
|
||||||
tag: ${{ !github.event.pull_request && github.ref_name || '' }}
|
|
||||||
tag-flag: ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }}
|
|
||||||
publishing: ${{ !github.event.pull_request }}
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
submodules: recursive
|
|
||||||
- name: Install dist
|
|
||||||
# we specify bash to get pipefail; it guards against the `curl` command
|
|
||||||
# failing. otherwise `sh` won't catch that `curl` returned non-0
|
|
||||||
shell: bash
|
|
||||||
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.30.3/cargo-dist-installer.sh | sh"
|
|
||||||
- name: Cache dist
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: cargo-dist-cache
|
|
||||||
path: ~/.cargo/bin/dist
|
|
||||||
# sure would be cool if github gave us proper conditionals...
|
|
||||||
# so here's a doubly-nested ternary-via-truthiness to try to provide the best possible
|
|
||||||
# functionality based on whether this is a pull_request, and whether it's from a fork.
|
|
||||||
# (PRs run on the *source* but secrets are usually on the *target* -- that's *good*
|
|
||||||
# but also really annoying to build CI around when it needs secrets to work right.)
|
|
||||||
- id: plan
|
|
||||||
run: |
|
|
||||||
dist ${{ (!github.event.pull_request && format('host --steps=create --tag={0}', github.ref_name)) || 'plan' }} --output-format=json > plan-dist-manifest.json
|
|
||||||
echo "dist ran successfully"
|
|
||||||
cat plan-dist-manifest.json
|
|
||||||
echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
|
||||||
- name: "Upload dist-manifest.json"
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: artifacts-plan-dist-manifest
|
|
||||||
path: plan-dist-manifest.json
|
|
||||||
|
|
||||||
# Build and packages all the platform-specific things
|
|
||||||
build-local-artifacts:
|
|
||||||
name: build-local-artifacts (${{ join(matrix.targets, ', ') }})
|
|
||||||
# Let the initial task tell us to not run (currently very blunt)
|
|
||||||
needs:
|
|
||||||
- plan
|
|
||||||
if: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix.include != null && (needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload') }}
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
# Target platforms/runners are computed by dist in create-release.
|
|
||||||
# Each member of the matrix has the following arguments:
|
|
||||||
#
|
|
||||||
# - runner: the github runner
|
|
||||||
# - dist-args: cli flags to pass to dist
|
|
||||||
# - install-dist: expression to run to install dist on the runner
|
|
||||||
#
|
|
||||||
# Typically there will be:
|
|
||||||
# - 1 "global" task that builds universal installers
|
|
||||||
# - N "local" tasks that build each platform's binaries and platform-specific installers
|
|
||||||
matrix: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix }}
|
|
||||||
runs-on: ${{ matrix.runner }}
|
|
||||||
container: ${{ matrix.container && matrix.container.image || null }}
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json
|
|
||||||
steps:
|
|
||||||
- name: enable windows longpaths
|
|
||||||
run: |
|
|
||||||
git config --global core.longpaths true
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
submodules: recursive
|
|
||||||
- name: Install Rust non-interactively if not already installed
|
|
||||||
if: ${{ matrix.container }}
|
|
||||||
run: |
|
|
||||||
if ! command -v cargo > /dev/null 2>&1; then
|
|
||||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
|
|
||||||
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
|
|
||||||
fi
|
|
||||||
- name: Install dist
|
|
||||||
run: ${{ matrix.install_dist.run }}
|
|
||||||
# Get the dist-manifest
|
|
||||||
- name: Fetch local artifacts
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: target/distrib/
|
|
||||||
merge-multiple: true
|
|
||||||
- name: Install dependencies
|
|
||||||
run: |
|
|
||||||
${{ matrix.packages_install }}
|
|
||||||
- name: Build artifacts
|
|
||||||
run: |
|
|
||||||
# Actually do builds and make zips and whatnot
|
|
||||||
dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json
|
|
||||||
echo "dist ran successfully"
|
|
||||||
- id: cargo-dist
|
|
||||||
name: Post-build
|
|
||||||
# We force bash here just because github makes it really hard to get values up
|
|
||||||
# to "real" actions without writing to env-vars, and writing to env-vars has
|
|
||||||
# inconsistent syntax between shell and powershell.
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
# Parse out what we just built and upload it to scratch storage
|
|
||||||
echo "paths<<EOF" >> "$GITHUB_OUTPUT"
|
|
||||||
dist print-upload-files-from-manifest --manifest dist-manifest.json >> "$GITHUB_OUTPUT"
|
|
||||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
|
||||||
- name: "Upload artifacts"
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: artifacts-build-local-${{ join(matrix.targets, '_') }}
|
|
||||||
path: |
|
|
||||||
${{ steps.cargo-dist.outputs.paths }}
|
|
||||||
${{ env.BUILD_MANIFEST_NAME }}
|
|
||||||
|
|
||||||
# Build and package all the platform-agnostic(ish) things
|
|
||||||
build-global-artifacts:
|
|
||||||
needs:
|
|
||||||
- plan
|
|
||||||
- build-local-artifacts
|
|
||||||
runs-on: "ubuntu-22.04"
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
submodules: recursive
|
|
||||||
- name: Install cached dist
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: cargo-dist-cache
|
|
||||||
path: ~/.cargo/bin/
|
|
||||||
- run: chmod +x ~/.cargo/bin/dist
|
|
||||||
# Get all the local artifacts for the global tasks to use (for e.g. checksums)
|
|
||||||
- name: Fetch local artifacts
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: target/distrib/
|
|
||||||
merge-multiple: true
|
|
||||||
- id: cargo-dist
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json
|
|
||||||
echo "dist ran successfully"
|
|
||||||
|
|
||||||
# Parse out what we just built and upload it to scratch storage
|
|
||||||
echo "paths<<EOF" >> "$GITHUB_OUTPUT"
|
|
||||||
jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT"
|
|
||||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
|
||||||
- name: "Upload artifacts"
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: artifacts-build-global
|
|
||||||
path: |
|
|
||||||
${{ steps.cargo-dist.outputs.paths }}
|
|
||||||
${{ env.BUILD_MANIFEST_NAME }}
|
|
||||||
# Determines if we should publish/announce
|
|
||||||
host:
|
|
||||||
needs:
|
|
||||||
- plan
|
|
||||||
- build-local-artifacts
|
|
||||||
- build-global-artifacts
|
|
||||||
# Only run if we're "publishing", and only if plan, local and global didn't fail (skipped is fine)
|
|
||||||
if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }}
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
runs-on: "ubuntu-22.04"
|
|
||||||
outputs:
|
|
||||||
val: ${{ steps.host.outputs.manifest }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
submodules: recursive
|
|
||||||
- name: Install cached dist
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: cargo-dist-cache
|
|
||||||
path: ~/.cargo/bin/
|
|
||||||
- run: chmod +x ~/.cargo/bin/dist
|
|
||||||
# Fetch artifacts from scratch-storage
|
|
||||||
- name: Fetch artifacts
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: target/distrib/
|
|
||||||
merge-multiple: true
|
|
||||||
- id: host
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json
|
|
||||||
echo "artifacts uploaded and released successfully"
|
|
||||||
cat dist-manifest.json
|
|
||||||
echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
|
||||||
- name: "Upload dist-manifest.json"
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
# Overwrite the previous copy
|
|
||||||
name: artifacts-dist-manifest
|
|
||||||
path: dist-manifest.json
|
|
||||||
# Create a GitHub Release while uploading all files to it
|
|
||||||
- name: "Download GitHub Artifacts"
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: artifacts
|
|
||||||
merge-multiple: true
|
|
||||||
- name: Cleanup
|
|
||||||
run: |
|
|
||||||
# Remove the granular manifests
|
|
||||||
rm -f artifacts/*-dist-manifest.json
|
|
||||||
- name: Create GitHub Release
|
|
||||||
env:
|
|
||||||
PRERELEASE_FLAG: "${{ fromJson(steps.host.outputs.manifest).announcement_is_prerelease && '--prerelease' || '' }}"
|
|
||||||
ANNOUNCEMENT_TITLE: "${{ fromJson(steps.host.outputs.manifest).announcement_title }}"
|
|
||||||
ANNOUNCEMENT_BODY: "${{ fromJson(steps.host.outputs.manifest).announcement_github_body }}"
|
|
||||||
RELEASE_COMMIT: "${{ github.sha }}"
|
|
||||||
run: |
|
|
||||||
# Write and read notes from a file to avoid quoting breaking things
|
|
||||||
echo "$ANNOUNCEMENT_BODY" > $RUNNER_TEMP/notes.txt
|
|
||||||
|
|
||||||
gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/*
|
|
||||||
|
|
||||||
announce:
|
|
||||||
needs:
|
|
||||||
- plan
|
|
||||||
- host
|
|
||||||
# use "always() && ..." to allow us to wait for all publish jobs while
|
|
||||||
# still allowing individual publish jobs to skip themselves (for prereleases).
|
|
||||||
# "host" however must run to completion, no skipping allowed!
|
|
||||||
if: ${{ always() && needs.host.result == 'success' }}
|
|
||||||
runs-on: "ubuntu-22.04"
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
submodules: recursive
|
|
||||||
+1
-6
@@ -1,5 +1,4 @@
|
|||||||
# ===== Rust / Cargo =====
|
# ===== Rust / Cargo =====
|
||||||
.cargo/config.toml
|
|
||||||
/target/
|
/target/
|
||||||
**/target/
|
**/target/
|
||||||
|
|
||||||
@@ -11,7 +10,6 @@
|
|||||||
# RustRover / IntelliJ
|
# RustRover / IntelliJ
|
||||||
.idea/
|
.idea/
|
||||||
*.iml
|
*.iml
|
||||||
.junie
|
|
||||||
|
|
||||||
# VS Code
|
# VS Code
|
||||||
.vscode/
|
.vscode/
|
||||||
@@ -62,7 +60,4 @@ temp/**
|
|||||||
**/build/**
|
**/build/**
|
||||||
**/node_modules/**
|
**/node_modules/**
|
||||||
|
|
||||||
AGENTS.md
|
AGENTS.md
|
||||||
|
|
||||||
.python-version
|
|
||||||
.venv
|
|
||||||
Generated
-23
@@ -1469,24 +1469,12 @@ version = "1.0.15"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pbxgen-dummy-boy"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"anyhow",
|
|
||||||
"prometeu-bytecode",
|
|
||||||
"prometeu-hal",
|
|
||||||
"serde_json",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pbxgen-stress"
|
name = "pbxgen-stress"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"prometeu-bytecode",
|
"prometeu-bytecode",
|
||||||
"prometeu-hal",
|
|
||||||
"serde_json",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1674,17 +1662,6 @@ dependencies = [
|
|||||||
"winit",
|
"winit",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "prometeu-host-headless"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"prometeu-bytecode",
|
|
||||||
"prometeu-drivers",
|
|
||||||
"prometeu-firmware",
|
|
||||||
"prometeu-hal",
|
|
||||||
"prometeu-system",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "prometeu-layer-tests"
|
name = "prometeu-layer-tests"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|||||||
+4
-3
@@ -1,15 +1,16 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"crates/console/prometeu-bytecode",
|
"crates/console/prometeu-bytecode",
|
||||||
|
|
||||||
"crates/console/prometeu-drivers",
|
"crates/console/prometeu-drivers",
|
||||||
"crates/console/prometeu-firmware",
|
"crates/console/prometeu-firmware",
|
||||||
"crates/console/prometeu-hal",
|
"crates/console/prometeu-hal",
|
||||||
"crates/console/prometeu-system",
|
"crates/console/prometeu-system",
|
||||||
"crates/console/prometeu-vm",
|
"crates/console/prometeu-vm",
|
||||||
|
|
||||||
"crates/host/prometeu-host-desktop-winit",
|
"crates/host/prometeu-host-desktop-winit",
|
||||||
"crates/host/prometeu-host-headless",
|
|
||||||
"crates/tools/prometeu-cli",
|
"crates/tools/prometeu-cli",
|
||||||
"crates/tools/pbxgen-dummy-boy",
|
|
||||||
"crates/tools/pbxgen-stress",
|
"crates/tools/pbxgen-stress",
|
||||||
"crates/dev/prometeu-test-support",
|
"crates/dev/prometeu-test-support",
|
||||||
"crates/dev/prometeu-layer-tests",
|
"crates/dev/prometeu-layer-tests",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
.PHONY: fmt fmt-check clippy test-local test-debugger-socket clean coverage coverage-xml coverage-json coverage-report-json coverage-domain-list coverage-domain-evidence coverage-domain-gate test ci ci-domains cobertura
|
.PHONY: fmt fmt-check clippy tes-local test-debugger-socket test ci cobertura
|
||||||
|
|
||||||
fmt:
|
fmt:
|
||||||
cargo fmt
|
cargo fmt
|
||||||
@@ -19,10 +19,7 @@ clean:
|
|||||||
cargo llvm-cov clean --workspace
|
cargo llvm-cov clean --workspace
|
||||||
|
|
||||||
coverage:
|
coverage:
|
||||||
cargo llvm-cov --workspace --all-features --html --output-dir target/llvm-cov
|
cargo llvm-cov --workspace --all-features --html --output-dir target/llvm-cov/html
|
||||||
|
|
||||||
coverage-report-json:
|
|
||||||
cargo llvm-cov report --json --output-path target/llvm-cov/report.json
|
|
||||||
|
|
||||||
coverage-xml:
|
coverage-xml:
|
||||||
cargo llvm-cov report --cobertura --output-path target/llvm-cov/cobertura.xml
|
cargo llvm-cov report --cobertura --output-path target/llvm-cov/cobertura.xml
|
||||||
@@ -30,20 +27,6 @@ coverage-xml:
|
|||||||
coverage-json:
|
coverage-json:
|
||||||
cargo llvm-cov report --json --summary-only --output-path target/llvm-cov/summary.json
|
cargo llvm-cov report --json --summary-only --output-path target/llvm-cov/summary.json
|
||||||
|
|
||||||
coverage-domain-list:
|
|
||||||
./scripts/coverage-domain-evidence.sh --list
|
|
||||||
|
|
||||||
coverage-domain-evidence:
|
|
||||||
@if [ -z "$(DOMAIN)" ]; then \
|
|
||||||
echo "usage: make coverage-domain-evidence DOMAIN=<domain>"; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
./scripts/coverage-domain-evidence.sh "$(DOMAIN)"
|
|
||||||
|
|
||||||
coverage-domain-gate:
|
|
||||||
./scripts/coverage-domain-evidence.sh --check-all
|
|
||||||
|
|
||||||
test: fmt-check clippy test-local test-debugger-socket
|
test: fmt-check clippy test-local test-debugger-socket
|
||||||
ci: clean fmt-check clippy coverage coverage-report-json
|
ci: clean fmt-check clippy coverage
|
||||||
ci-domains: clean fmt-check clippy coverage coverage-report-json coverage-xml coverage-json coverage-domain-gate
|
|
||||||
cobertura: coverage-xml coverage-json
|
cobertura: coverage-xml coverage-json
|
||||||
|
|||||||
@@ -1,190 +1,95 @@
|
|||||||
# PROMETEU Runtime
|
# PROMETEU
|
||||||
|
|
||||||
PROMETEU is an educational and experimental fantasy handheld / fantasy console.
|
PROMETEU is an **educational and experimental fantasy handheld / fantasy console ecosystem** inspired by classic consoles, focusing on **teaching programming, system architecture, and hardware concepts through software**.
|
||||||
This repository contains the Rust runtime workspace for the machine: VM-facing components, virtual peripherals, firmware/system services, host integration, CLI entrypoints, development utilities, specs, and discussion artifacts.
|
|
||||||
|
|
||||||
The VM is only one subsystem of the machine. The canonical docs in this repository intentionally distinguish:
|
> PROMETEU is a fantasy console with a simple, explicit, and educational VM/runtime inside it.
|
||||||
|
|
||||||
- machine-level specs;
|
---
|
||||||
- VM/runtime internal architecture;
|
|
||||||
- implementation crates;
|
|
||||||
- discussion workflow and lessons learned.
|
|
||||||
|
|
||||||
## What This Repository Contains
|
## 🎯 Project Goals
|
||||||
|
|
||||||
- `crates/console/`: core machine/runtime crates such as `prometeu-vm`, `prometeu-system`, `prometeu-hal`, `prometeu-drivers`, and `prometeu-firmware`
|
- **Simulate simple "logical hardware"**: Create a low entry barrier for understanding how computers work.
|
||||||
- `crates/host/`: host-side execution surfaces, currently including `prometeu-host-desktop-winit`
|
- **Deterministic Loop**: Ensure the same code produces the same result on any platform.
|
||||||
- `crates/tools/`: user-facing and support binaries such as `prometeu` and `pbxgen-stress`
|
- **Total Portability**: The core does not depend on an operating system, allowing it to run from modern computers to dedicated hardware.
|
||||||
- `crates/dev/`: test support, layer tests, and quality-check utilities
|
- **First-Class Tools**: Offer deep debugging and inspection as a central part of the experience.
|
||||||
- `docs/specs/runtime/`: canonical PROMETEU machine specs
|
- **DIY hardware affinity**: Keep the machine model close enough to handheld/console-era hardware that it can inform real embedded and homebrew-style implementations.
|
||||||
- `docs/vm-arch/`: canonical VM/runtime architecture and ISA references
|
|
||||||
- `devtools/`: debugger protocol material
|
|
||||||
- `discussion/`: agendas, decisions, plans, and lessons for architectural work
|
|
||||||
- `test-cartridges/`: cartridge fixtures used for validation and manual runs
|
|
||||||
|
|
||||||
## Canonical Documentation
|
---
|
||||||
|
|
||||||
Use these entrypoints instead of inferring the model from isolated source files:
|
## 🧠 Design Philosophy
|
||||||
|
|
||||||
- [Machine specs](docs/specs/runtime/README.md): authoritative contract for the PROMETEU machine, peripherals, firmware, cartridge format, timing, and host ABI
|
- **No magic**: everything is explicit.
|
||||||
- [VM architecture](docs/vm-arch/ARCHITECTURE.md): authoritative internal architecture for VM/runtime invariants
|
- **No implicit heuristics**: the system doesn't "guess intentions".
|
||||||
- [ISA reference](docs/vm-arch/ISA_CORE.md): bytecode-level instruction set authority
|
- **Deterministic**: same input → same result.
|
||||||
- [Discussion workflow](discussion/index.ndjson): architectural agenda, decision, and execution traceability
|
- **Hardware-first**: APIs model peripherals, not modern frameworks.
|
||||||
|
- **Portable by definition**: if it doesn't work on all platforms, it doesn't exist.
|
||||||
|
- **Console-era sensibility**: PROMETEU carries intentional influence from NES, SNES, Mega Drive, Game Boy, GBA, CPS-2, and adjacent DIY-friendly hardware thinking.
|
||||||
|
|
||||||
## Workspace Layout
|
## 🧭 Canonical Architecture
|
||||||
|
|
||||||
This repository is a Rust workspace rooted at [Cargo.toml](Cargo.toml) with members in:
|
PROMETEU is the machine. The VM/runtime is one subsystem inside that machine.
|
||||||
|
|
||||||
- `crates/console`
|
Authoritative documents:
|
||||||
- `crates/host`
|
|
||||||
- `crates/tools`
|
|
||||||
- `crates/dev`
|
|
||||||
|
|
||||||
The main user-facing dispatcher binary is `prometeu`, built from `crates/tools/prometeu-cli`.
|
- [`docs/runtime/virtual-machine/ARCHITECTURE.md`](docs/vm-arch/ARCHITECTURE.md) is normative for VM/runtime invariants.
|
||||||
The same package also builds `prometeu-runtime`, which embeds the current desktop host runtime.
|
- [`docs/runtime/specs/README.md`](docs/specs/runtime/README.md) describes the broader PROMETEU machine, hardware model, and fantasy console context.
|
||||||
|
- Supporting material under `docs/` may expand, explain, or propose changes, but it must not silently collapse the whole machine into the VM layer.
|
||||||
|
|
||||||
Current CLI surface:
|
---
|
||||||
|
|
||||||
- `prometeu run <cart>`
|
## 📦 Monorepo Structure
|
||||||
- `prometeu debug <cart> --port <port>`
|
|
||||||
|
|
||||||
The dispatcher forwards runtime execution to `prometeu-runtime`.
|
This repository is organized as a Rust workspace and contains several components:
|
||||||
For lower-level local runs, `prometeu-runtime` also accepts:
|
|
||||||
|
|
||||||
- `--run <cart>`
|
- **[crates/](./crates)**: Software implementation in Rust.
|
||||||
- `--debug <cart> --port <port>`
|
- **[prometeu](crates/tools/prometeu)**: Unified command-line interface (CLI).
|
||||||
- `--fs-root <path>`
|
- **[prometeu-drivers](crates/console/prometeu-drivers)**: The virtual hardware (GPU, SPU, Input).
|
||||||
- `--cap <path>`
|
- **[prometeu-host-desktop-winit](crates/host/prometeu-host-desktop-winit)**: Host for execution on Desktop systems.
|
||||||
|
- **[docs/](./docs)**: Technical documentation and system specifications.
|
||||||
|
- **[devtools-protocol/](devtools)**: Definition of the communication protocol for development tools.
|
||||||
|
- **[test-cartridges/](./test-cartridges)**: Cartridge examples and test suites.
|
||||||
|
|
||||||
Other ecosystem commands, such as build, pack, and verification tooling, are not part of the current dispatcher surface in this workspace.
|
---
|
||||||
|
|
||||||
## Requirements
|
## 🛠️ Requirements
|
||||||
|
|
||||||
- Rust toolchain from [rust-toolchain.toml](rust-toolchain.toml)
|
- **Rust**: Version defined in `rust-toolchain.toml`.
|
||||||
- `rustup` for toolchain installation and management
|
- **Installation**: Use [rustup](https://rustup.rs/) to install the required toolchain.
|
||||||
- `cargo-llvm-cov` for coverage targets such as `make coverage` and `make ci-domains`
|
|
||||||
- a local graphical environment for desktop runtime commands
|
|
||||||
|
|
||||||
## Quick Start
|
---
|
||||||
|
|
||||||
Build the workspace:
|
## ▶️ Quick Start
|
||||||
|
|
||||||
|
To compile the full project:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo build
|
cargo build
|
||||||
```
|
```
|
||||||
|
|
||||||
Inspect the CLI:
|
To run an example cartridge:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo run -q -p prometeu-cli --bin prometeu -- --help
|
./target/debug/prometeu run test-cartridges/color-square-ts
|
||||||
```
|
```
|
||||||
|
|
||||||
Run the current stress cartridge fixture:
|
For more details on how to use the CLI, see the **[prometeu](crates/tools/prometeu)** README.
|
||||||
|
|
||||||
```bash
|
---
|
||||||
cargo run -q -p prometeu-cli --bin prometeu -- run test-cartridges/stress-console
|
|
||||||
```
|
|
||||||
|
|
||||||
Run the embedded runtime binary directly:
|
## 🚧 Project Status
|
||||||
|
|
||||||
```bash
|
⚠️ **Early stage (bootstrap)**
|
||||||
cargo run -q -p prometeu-cli --bin prometeu-runtime -- --run test-cartridges/stress-console
|
|
||||||
```
|
|
||||||
|
|
||||||
Regenerate and run the stress cartridge fixture:
|
Currently, the focus is on stabilizing the core architecture and debugging protocol. Nothing here should be considered a stable API yet.
|
||||||
|
|
||||||
```bash
|
---
|
||||||
./scripts/run-stress.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
The desktop runtime opens a native window through the host layer, so runtime commands are intended for a local graphical environment.
|
## 📜 License
|
||||||
|
|
||||||
## Validation
|
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||||
|
|
||||||
Format, lint, and test the workspace:
|
---
|
||||||
|
|
||||||
```bash
|
## ✨ Final Note
|
||||||
make test
|
|
||||||
```
|
|
||||||
|
|
||||||
Run the CI-oriented non-domain gate:
|
PROMETEU is both a technical and pedagogical project. The idea is not to hide complexity, but to **expose the right complexity**, at the right level, so it can be understood, studied, and explored.
|
||||||
|
|
||||||
```bash
|
|
||||||
make ci
|
|
||||||
```
|
|
||||||
|
|
||||||
Run the CI-oriented domain coverage gate:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
make ci-domains
|
|
||||||
```
|
|
||||||
|
|
||||||
The debugger socket tests bind localhost sockets and are marked ignored in Rust test metadata; `make test` includes them through the dedicated `test-debugger-socket` target.
|
|
||||||
|
|
||||||
## Coverage Governance
|
|
||||||
|
|
||||||
The repository uses a two-layer runtime-edge coverage model:
|
|
||||||
|
|
||||||
- a mandatory CI gate based on canonical runtime-edge domains;
|
|
||||||
- domain-oriented review evidence for the canonical runtime-edge domains.
|
|
||||||
|
|
||||||
Current canonical domains:
|
|
||||||
|
|
||||||
- `system/runtime`
|
|
||||||
- `fs`
|
|
||||||
- `asset/bank`
|
|
||||||
- `firmware`
|
|
||||||
- `host-dependent`
|
|
||||||
- `host/headless`
|
|
||||||
|
|
||||||
Global coverage artifacts:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
make ci
|
|
||||||
make cobertura
|
|
||||||
make ci-domains
|
|
||||||
```
|
|
||||||
|
|
||||||
This produces:
|
|
||||||
|
|
||||||
- `target/llvm-cov/html`
|
|
||||||
- `target/llvm-cov/report.json`
|
|
||||||
- `target/llvm-cov/summary.json`
|
|
||||||
- `target/llvm-cov/cobertura.xml`
|
|
||||||
|
|
||||||
Domain-oriented evidence helpers:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
make coverage-domain-list
|
|
||||||
make coverage-domain-evidence DOMAIN=firmware
|
|
||||||
make coverage-domain-evidence DOMAIN=host-dependent
|
|
||||||
make coverage-domain-evidence DOMAIN=host/headless
|
|
||||||
```
|
|
||||||
|
|
||||||
Per-domain baselines currently start around `60`.
|
|
||||||
That does not waive test obligations. It means the project is adopting explicit domain evidence immediately while tightening quantitative expectations incrementally over time.
|
|
||||||
|
|
||||||
`make ci-domains` is the CI entrypoint used by Jenkins.
|
|
||||||
It runs the standard coverage pipeline, produces the HTML/XML/JSON artifacts, and fails when any canonical domain falls below its configured `baseline_percent`.
|
|
||||||
The CI gate currently compares domain `lines` coverage against each domain baseline.
|
|
||||||
|
|
||||||
When a PR changes the observable contract of a canonical domain, it is expected to:
|
|
||||||
|
|
||||||
- add or adjust tests for that domain; or
|
|
||||||
- justify explicitly why the observable contract did not change.
|
|
||||||
|
|
||||||
Improving the global percentage alone is not sufficient review evidence when the changed behavior belongs to a canonical domain.
|
|
||||||
|
|
||||||
## Current State
|
|
||||||
|
|
||||||
The project is still in active architectural and implementation convergence.
|
|
||||||
|
|
||||||
- the machine contract is being clarified through the specs and discussion workflow;
|
|
||||||
- the workspace already contains concrete runtime and host code;
|
|
||||||
- the CLI dispatcher currently exposes the runtime paths that are backed by binaries in this workspace.
|
|
||||||
|
|
||||||
Treat APIs, file formats, and execution flows as evolving unless the relevant spec explicitly defines them as stable.
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
This project is licensed under the [MIT License](LICENSE).
|
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
0.1.0
|
|
||||||
|
|||||||
@@ -6,4 +6,4 @@ license.workspace = true
|
|||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
|||||||
@@ -11,14 +11,14 @@ mod program_image;
|
|||||||
mod value;
|
mod value;
|
||||||
|
|
||||||
pub use abi::{
|
pub use abi::{
|
||||||
SourceSpan, TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT,
|
TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT, TRAP_ILLEGAL_INSTRUCTION,
|
||||||
TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL,
|
TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_OOB,
|
||||||
TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_STACK_UNDERFLOW, TRAP_TYPE,
|
TRAP_STACK_UNDERFLOW, TRAP_TYPE,
|
||||||
};
|
};
|
||||||
pub use assembler::{assemble, AsmError};
|
pub use assembler::{assemble, AsmError};
|
||||||
pub use decoder::{decode_next, DecodeError};
|
pub use decoder::{decode_next, DecodeError};
|
||||||
pub use disassembler::disassemble;
|
pub use disassembler::disassemble;
|
||||||
pub use layout::{compute_function_layouts, FunctionLayout};
|
pub use layout::{compute_function_layouts, FunctionLayout};
|
||||||
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl, PBX_MAGIC};
|
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl};
|
||||||
pub use program_image::ProgramImage;
|
pub use program_image::ProgramImage;
|
||||||
pub use value::{string_materialization_count, HeapRef, Value};
|
pub use value::{HeapRef, Value};
|
||||||
|
|||||||
@@ -80,11 +80,9 @@ const SECTION_KIND_DEBUG: u32 = 3;
|
|||||||
const SECTION_KIND_EXPORTS: u32 = 4;
|
const SECTION_KIND_EXPORTS: u32 = 4;
|
||||||
const SECTION_KIND_SYSCALLS: u32 = 5;
|
const SECTION_KIND_SYSCALLS: u32 = 5;
|
||||||
|
|
||||||
pub const PBX_MAGIC: [u8; 4] = *b"PBX\0";
|
/// Represents the final serialized format of a PBS v0 module.
|
||||||
|
|
||||||
/// Represents the final serialized format of a PBX v0 module.
|
|
||||||
///
|
///
|
||||||
/// This structure is a pure data container for the PBX format. It does NOT
|
/// This structure is a pure data container for the PBS format. It does NOT
|
||||||
/// contain any linker-like logic (symbol resolution, patching, etc.).
|
/// contain any linker-like logic (symbol resolution, patching, etc.).
|
||||||
/// All multi-module programs must be flattened and linked by the compiler
|
/// All multi-module programs must be flattened and linked by the compiler
|
||||||
/// before being serialized into this format.
|
/// before being serialized into this format.
|
||||||
@@ -128,8 +126,8 @@ impl BytecodeModule {
|
|||||||
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
|
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
|
||||||
|
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
// Magic "PBX\0"
|
// Magic "PBS\0"
|
||||||
out.extend_from_slice(&PBX_MAGIC);
|
out.extend_from_slice(b"PBS\0");
|
||||||
// Version 0
|
// Version 0
|
||||||
out.extend_from_slice(&0u16.to_le_bytes());
|
out.extend_from_slice(&0u16.to_le_bytes());
|
||||||
// Endianness 0 (Little Endian), Reserved
|
// Endianness 0 (Little Endian), Reserved
|
||||||
@@ -274,8 +272,8 @@ impl BytecodeLoader {
|
|||||||
return Err(LoadError::UnexpectedEof);
|
return Err(LoadError::UnexpectedEof);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Magic "PBX\0"
|
// Magic "PBS\0"
|
||||||
if bytes[0..4] != PBX_MAGIC[..] {
|
if &bytes[0..4] != b"PBS\0" {
|
||||||
return Err(LoadError::InvalidMagic);
|
return Err(LoadError::InvalidMagic);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -710,7 +708,7 @@ mod tests {
|
|||||||
|
|
||||||
fn create_header(section_count: u32) -> Vec<u8> {
|
fn create_header(section_count: u32) -> Vec<u8> {
|
||||||
let mut h = vec![0u8; 32];
|
let mut h = vec![0u8; 32];
|
||||||
h[0..4].copy_from_slice(&PBX_MAGIC);
|
h[0..4].copy_from_slice(b"PBS\0");
|
||||||
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
|
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
|
||||||
h[6] = 0; // endianness
|
h[6] = 0; // endianness
|
||||||
h[8..12].copy_from_slice(§ion_count.to_le_bytes());
|
h[8..12].copy_from_slice(§ion_count.to_le_bytes());
|
||||||
@@ -729,7 +727,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_pbx_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
|
fn build_pbs_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
|
||||||
let mut data = create_header(sections.len() as u32);
|
let mut data = create_header(sections.len() as u32);
|
||||||
let mut offset = 32 + (sections.len() as u32 * 12);
|
let mut offset = 32 + (sections.len() as u32 * 12);
|
||||||
|
|
||||||
@@ -750,7 +748,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_invalid_magic() {
|
fn test_invalid_magic() {
|
||||||
let mut data = create_header(0);
|
let mut data = create_header(0);
|
||||||
data[0..4].copy_from_slice(b"PBS\0");
|
data[0] = b'X';
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -884,7 +882,7 @@ mod tests {
|
|||||||
fn test_valid_sysc_roundtrip() {
|
fn test_valid_sysc_roundtrip() {
|
||||||
let mut module = minimal_module();
|
let mut module = minimal_module();
|
||||||
module.syscalls = vec![SyscallDecl {
|
module.syscalls = vec![SyscallDecl {
|
||||||
module: "gfx2d".into(),
|
module: "gfx".into(),
|
||||||
name: "draw_line".into(),
|
name: "draw_line".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 4,
|
arg_slots: 4,
|
||||||
@@ -899,7 +897,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_malformed_sysc_section_is_rejected() {
|
fn test_malformed_sysc_section_is_rejected() {
|
||||||
let data = build_pbx_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
|
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
|
||||||
|
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MalformedSection));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MalformedSection));
|
||||||
}
|
}
|
||||||
@@ -916,7 +914,7 @@ mod tests {
|
|||||||
sysc.extend_from_slice(&0u16.to_le_bytes());
|
sysc.extend_from_slice(&0u16.to_le_bytes());
|
||||||
sysc.extend_from_slice(&0u16.to_le_bytes());
|
sysc.extend_from_slice(&0u16.to_le_bytes());
|
||||||
|
|
||||||
let data = build_pbx_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
|
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
|
||||||
|
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidUtf8));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidUtf8));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::value::Value;
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
/// Represents a fully linked, executable PBX program image.
|
/// Represents a fully linked, executable PBS program image.
|
||||||
///
|
///
|
||||||
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
||||||
/// produced by the compiler. All linking, relocation, and symbol resolution
|
/// produced by the compiler. All linking, relocation, and symbol resolution
|
||||||
@@ -75,7 +75,7 @@ impl From<BytecodeModule> for ProgramImage {
|
|||||||
ConstantPoolEntry::Int64(v) => Value::Int64(*v),
|
ConstantPoolEntry::Int64(v) => Value::Int64(*v),
|
||||||
ConstantPoolEntry::Float64(v) => Value::Float(*v),
|
ConstantPoolEntry::Float64(v) => Value::Float(*v),
|
||||||
ConstantPoolEntry::Boolean(v) => Value::Boolean(*v),
|
ConstantPoolEntry::Boolean(v) => Value::Boolean(*v),
|
||||||
ConstantPoolEntry::String(v) => Value::string(v.clone()),
|
ConstantPoolEntry::String(v) => Value::String(v.clone()),
|
||||||
ConstantPoolEntry::Int32(v) => Value::Int32(*v),
|
ConstantPoolEntry::Int32(v) => Value::Int32(*v),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -99,7 +99,7 @@ impl From<ProgramImage> for BytecodeModule {
|
|||||||
Value::Int64(v) => ConstantPoolEntry::Int64(*v),
|
Value::Int64(v) => ConstantPoolEntry::Int64(*v),
|
||||||
Value::Float(v) => ConstantPoolEntry::Float64(*v),
|
Value::Float(v) => ConstantPoolEntry::Float64(*v),
|
||||||
Value::Boolean(v) => ConstantPoolEntry::Boolean(*v),
|
Value::Boolean(v) => ConstantPoolEntry::Boolean(*v),
|
||||||
Value::String(v) => ConstantPoolEntry::String(v.to_string()),
|
Value::String(v) => ConstantPoolEntry::String(v.clone()),
|
||||||
Value::Int32(v) => ConstantPoolEntry::Int32(*v),
|
Value::Int32(v) => ConstantPoolEntry::Int32(*v),
|
||||||
Value::HeapRef(_) => ConstantPoolEntry::Null,
|
Value::HeapRef(_) => ConstantPoolEntry::Null,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,12 +1,5 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::cell::Cell;
|
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
use std::fmt::Write;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
thread_local! {
|
|
||||||
static STRING_MATERIALIZATION_COUNT: Cell<u64> = const { Cell::new(0) };
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Opaque handle that references an object stored in the VM heap.
|
/// Opaque handle that references an object stored in the VM heap.
|
||||||
///
|
///
|
||||||
@@ -33,7 +26,7 @@ pub enum Value {
|
|||||||
/// Boolean value (true/false).
|
/// Boolean value (true/false).
|
||||||
Boolean(bool),
|
Boolean(bool),
|
||||||
/// UTF-8 string. Strings are immutable and usually come from the Constant Pool.
|
/// UTF-8 string. Strings are immutable and usually come from the Constant Pool.
|
||||||
String(Arc<str>),
|
String(String),
|
||||||
/// A handle to an object on the heap (opaque reference).
|
/// A handle to an object on the heap (opaque reference).
|
||||||
HeapRef(HeapRef),
|
HeapRef(HeapRef),
|
||||||
/// Represents the absence of a value (equivalent to `null` or `undefined`).
|
/// Represents the absence of a value (equivalent to `null` or `undefined`).
|
||||||
@@ -81,14 +74,6 @@ impl PartialOrd for Value {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Value {
|
impl Value {
|
||||||
pub fn string<S>(value: S) -> Self
|
|
||||||
where
|
|
||||||
S: Into<Arc<str>>,
|
|
||||||
{
|
|
||||||
STRING_MATERIALIZATION_COUNT.with(|count| count.set(count.get() + 1));
|
|
||||||
Value::String(value.into())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_float(&self) -> Option<f64> {
|
pub fn as_float(&self) -> Option<f64> {
|
||||||
match self {
|
match self {
|
||||||
Value::Int32(i) => Some(*i as f64),
|
Value::Int32(i) => Some(*i as f64),
|
||||||
@@ -107,53 +92,20 @@ impl Value {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn append_to_string(&self, out: &mut String) {
|
|
||||||
match self {
|
|
||||||
Value::Int32(i) => {
|
|
||||||
let _ = write!(out, "{}", i);
|
|
||||||
}
|
|
||||||
Value::Int64(i) => {
|
|
||||||
let _ = write!(out, "{}", i);
|
|
||||||
}
|
|
||||||
Value::Float(f) => {
|
|
||||||
let _ = write!(out, "{}", f);
|
|
||||||
}
|
|
||||||
Value::Boolean(b) => {
|
|
||||||
let _ = write!(out, "{}", b);
|
|
||||||
}
|
|
||||||
Value::String(s) => out.push_str(s),
|
|
||||||
Value::HeapRef(r) => {
|
|
||||||
let _ = write!(out, "[HeapRef {}]", r.0);
|
|
||||||
}
|
|
||||||
Value::Null => out.push_str("null"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn string_len_hint(&self) -> usize {
|
|
||||||
match self {
|
|
||||||
Value::String(s) => s.len(),
|
|
||||||
Value::Null => 4,
|
|
||||||
Value::Boolean(true) => 4,
|
|
||||||
Value::Boolean(false) => 5,
|
|
||||||
Value::Int32(i) => i.to_string().len(),
|
|
||||||
Value::Int64(i) => i.to_string().len(),
|
|
||||||
Value::Float(f) => f.to_string().len(),
|
|
||||||
Value::HeapRef(r) => 11 + r.0.to_string().len(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::inherent_to_string)]
|
#[allow(clippy::inherent_to_string)]
|
||||||
pub fn to_string(&self) -> String {
|
pub fn to_string(&self) -> String {
|
||||||
let mut out = String::with_capacity(self.string_len_hint());
|
match self {
|
||||||
self.append_to_string(&mut out);
|
Value::Int32(i) => i.to_string(),
|
||||||
out
|
Value::Int64(i) => i.to_string(),
|
||||||
|
Value::Float(f) => f.to_string(),
|
||||||
|
Value::Boolean(b) => b.to_string(),
|
||||||
|
Value::String(s) => s.clone(),
|
||||||
|
Value::HeapRef(r) => format!("[HeapRef {}]", r.0),
|
||||||
|
Value::Null => "null".to_string(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn string_materialization_count() -> u64 {
|
|
||||||
STRING_MATERIALIZATION_COUNT.with(Cell::get)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ fn roundtrip_disasm_assemble_byte_equal_with_closures_and_coroutines() {
|
|||||||
emit(CoreOpCode::Sleep, Some(&3u32.to_le_bytes()), &mut prog);
|
emit(CoreOpCode::Sleep, Some(&3u32.to_le_bytes()), &mut prog);
|
||||||
// HOSTCALL sysc[2]
|
// HOSTCALL sysc[2]
|
||||||
emit(CoreOpCode::Hostcall, Some(&2u32.to_le_bytes()), &mut prog);
|
emit(CoreOpCode::Hostcall, Some(&2u32.to_le_bytes()), &mut prog);
|
||||||
// SYSCALL gfx2d.draw_line (0x1003)
|
// SYSCALL gfx.draw_line (0x1003)
|
||||||
emit(CoreOpCode::Syscall, Some(&0x1003u32.to_le_bytes()), &mut prog);
|
emit(CoreOpCode::Syscall, Some(&0x1003u32.to_le_bytes()), &mut prog);
|
||||||
// FRAME_SYNC
|
// FRAME_SYNC
|
||||||
emit(CoreOpCode::FrameSync, None, &mut prog);
|
emit(CoreOpCode::FrameSync, None, &mut prog);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,23 +1,14 @@
|
|||||||
use crate::asset::AssetManager;
|
use crate::asset::AssetManager;
|
||||||
use crate::audio::Audio;
|
use crate::audio::Audio;
|
||||||
use crate::frame_composer::FrameComposer;
|
|
||||||
use crate::gfx::Gfx;
|
use crate::gfx::Gfx;
|
||||||
use crate::memory_banks::{
|
use crate::memory_banks::{
|
||||||
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolAccess,
|
MemoryBanks, SoundBankPoolAccess, SoundBankPoolInstaller, TileBankPoolAccess,
|
||||||
SceneBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller,
|
TileBankPoolInstaller,
|
||||||
};
|
};
|
||||||
use crate::pad::Pad;
|
use crate::pad::Pad;
|
||||||
use crate::touch::Touch;
|
use crate::touch::Touch;
|
||||||
use prometeu_hal::cartridge::AssetsPayloadSource;
|
use prometeu_hal::cartridge::AssetsPayloadSource;
|
||||||
use prometeu_hal::sprite::Sprite;
|
use prometeu_hal::{AssetBridge, AudioBridge, GfxBridge, HardwareBridge, PadBridge, TouchBridge};
|
||||||
use prometeu_hal::{
|
|
||||||
AssetBridge, AudioBridge, InputPlatform, NoopTelemetryPlatform, PadBridge, RenderBackend,
|
|
||||||
RuntimePlatform, TelemetryPlatform, TouchBridge,
|
|
||||||
};
|
|
||||||
use prometeu_hal::{
|
|
||||||
Game2DFrameComposer, Game2DFramePacket, RenderSubmission, RenderSubmissionPacket,
|
|
||||||
};
|
|
||||||
use prometeu_hal::{RenderSubmissionSink, RenderSubmitError};
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
/// Aggregate structure for all virtual hardware peripherals.
|
/// Aggregate structure for all virtual hardware peripherals.
|
||||||
@@ -28,24 +19,20 @@ use std::sync::Arc;
|
|||||||
/// for easier testing and different host implementations (Desktop, Web, etc.).
|
/// for easier testing and different host implementations (Desktop, Web, etc.).
|
||||||
///
|
///
|
||||||
/// ### Console Specifications:
|
/// ### Console Specifications:
|
||||||
/// - **Resolution**: 480x270 (16:9 Aspect Ratio).
|
/// - **Resolution**: 320x180 (16:9 Aspect Ratio).
|
||||||
/// - **Color Format**: RGBA8888.
|
/// - **Color Depth**: RGB565 (16-bit).
|
||||||
/// - **Audio**: Stereo, Command-based mixing.
|
/// - **Audio**: Stereo, Command-based mixing.
|
||||||
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
|
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
|
||||||
pub struct Hardware {
|
pub struct Hardware {
|
||||||
/// Shared physical memory bank ownership used by peripherals and worker backends.
|
|
||||||
pub memory_banks: Arc<MemoryBanks>,
|
|
||||||
/// The Graphics Processing Unit (GPU). Handles drawing primitives, sprites, and tilemaps.
|
/// The Graphics Processing Unit (GPU). Handles drawing primitives, sprites, and tilemaps.
|
||||||
pub gfx: Gfx,
|
pub gfx: Gfx,
|
||||||
/// Canonical frame orchestration owner for scene/camera/cache/resolver/sprites.
|
|
||||||
pub frame_composer: FrameComposer,
|
|
||||||
/// The Sound Processing Unit (SPU). Manages sample playback and volume control.
|
/// The Sound Processing Unit (SPU). Manages sample playback and volume control.
|
||||||
pub audio: Audio,
|
pub audio: Audio,
|
||||||
/// The standard digital gamepad. Provides state for D-Pad, face buttons, and triggers.
|
/// The standard digital gamepad. Provides state for D-Pad, face buttons, and triggers.
|
||||||
pub pad: Pad,
|
pub pad: Pad,
|
||||||
/// The absolute pointer input device (Mouse/Touchscreen).
|
/// The absolute pointer input device (Mouse/Touchscreen).
|
||||||
pub touch: Touch,
|
pub touch: Touch,
|
||||||
/// The Asset Management system (DMA). Handles loading data into VRAM (GlyphBanks) and ARAM (SoundBanks).
|
/// The Asset Management system (DMA). Handles loading data into VRAM (TileBanks) and ARAM (SoundBanks).
|
||||||
pub assets: AssetManager,
|
pub assets: AssetManager,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,94 +42,24 @@ impl Default for Hardware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Hardware {
|
impl HardwareBridge for Hardware {
|
||||||
fn consume_render_submission(&mut self, submission: &RenderSubmission) {
|
fn gfx(&self) -> &dyn GfxBridge {
|
||||||
match &submission.packet {
|
&self.gfx
|
||||||
RenderSubmissionPacket::Game2D(packet) => {
|
|
||||||
if packet.composer.bound_scene.is_none() {
|
|
||||||
self.gfx.render_game2d_frame_packet(packet);
|
|
||||||
} else {
|
|
||||||
self.frame_composer.render_game2d_frame_packet(packet, &mut self.gfx);
|
|
||||||
self.gfx.apply_gfx2d_commands(&packet.gfx2d);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
RenderSubmissionPacket::ShellUi(packet) => {
|
|
||||||
self.gfx.render_shell_ui_frame_packet(packet);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.gfx.present();
|
|
||||||
}
|
}
|
||||||
}
|
fn gfx_mut(&mut self) -> &mut dyn GfxBridge {
|
||||||
|
&mut self.gfx
|
||||||
impl RenderSubmissionSink for Hardware {
|
|
||||||
fn submit_render_submission(
|
|
||||||
&mut self,
|
|
||||||
submission: RenderSubmission,
|
|
||||||
) -> Result<(), RenderSubmitError> {
|
|
||||||
self.consume_render_submission(&submission);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderBackend for Hardware {
|
|
||||||
fn render_frame(&mut self) {
|
|
||||||
if self.frame_composer.active_scene_id().is_none() {
|
|
||||||
let packet = self.frame_composer.close_game2d_packet();
|
|
||||||
self.gfx.render_game2d_frame_packet(&packet);
|
|
||||||
} else {
|
|
||||||
self.frame_composer.render_frame(&mut self.gfx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Game2DFrameComposer for Hardware {
|
|
||||||
fn begin_frame(&mut self) {
|
|
||||||
self.frame_composer.begin_frame();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bind_scene(&mut self, scene_bank_id: usize) -> prometeu_hal::ComposerOpStatus {
|
fn audio(&self) -> &dyn AudioBridge {
|
||||||
if self.frame_composer.bind_scene(scene_bank_id) {
|
&self.audio
|
||||||
prometeu_hal::ComposerOpStatus::Ok
|
}
|
||||||
} else {
|
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||||
prometeu_hal::ComposerOpStatus::SceneUnavailable
|
&mut self.audio
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unbind_scene(&mut self) {
|
|
||||||
self.frame_composer.unbind_scene();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_camera(&mut self, x: i32, y: i32) -> prometeu_hal::ComposerOpStatus {
|
|
||||||
self.frame_composer.set_camera(x, y);
|
|
||||||
prometeu_hal::ComposerOpStatus::Ok
|
|
||||||
}
|
|
||||||
|
|
||||||
fn emit_sprite(&mut self, sprite: Sprite) -> prometeu_hal::ComposerOpStatus {
|
|
||||||
let Some(bank) = self.gfx.glyph_banks.glyph_bank_slot(sprite.bank_id as usize) else {
|
|
||||||
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
|
||||||
};
|
|
||||||
|
|
||||||
if !bank.contains_palette(sprite.glyph.palette_id) {
|
|
||||||
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.frame_composer.emit_sprite(sprite) {
|
|
||||||
prometeu_hal::ComposerOpStatus::Ok
|
|
||||||
} else {
|
|
||||||
prometeu_hal::ComposerOpStatus::SpriteOverflow
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn close_game2d_packet(&self) -> Game2DFramePacket {
|
|
||||||
self.frame_composer.close_game2d_packet()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl InputPlatform for Hardware {
|
|
||||||
fn pad(&self) -> &dyn PadBridge {
|
fn pad(&self) -> &dyn PadBridge {
|
||||||
&self.pad
|
&self.pad
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pad_mut(&mut self) -> &mut dyn PadBridge {
|
fn pad_mut(&mut self) -> &mut dyn PadBridge {
|
||||||
&mut self.pad
|
&mut self.pad
|
||||||
}
|
}
|
||||||
@@ -150,315 +67,42 @@ impl InputPlatform for Hardware {
|
|||||||
fn touch(&self) -> &dyn TouchBridge {
|
fn touch(&self) -> &dyn TouchBridge {
|
||||||
&self.touch
|
&self.touch
|
||||||
}
|
}
|
||||||
|
|
||||||
fn touch_mut(&mut self) -> &mut dyn TouchBridge {
|
fn touch_mut(&mut self) -> &mut dyn TouchBridge {
|
||||||
&mut self.touch
|
&mut self.touch
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
static NOOP_TELEMETRY: NoopTelemetryPlatform = NoopTelemetryPlatform;
|
|
||||||
|
|
||||||
impl RuntimePlatform for Hardware {
|
|
||||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn audio(&self) -> &dyn AudioBridge {
|
|
||||||
&self.audio
|
|
||||||
}
|
|
||||||
|
|
||||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
|
||||||
&mut self.audio
|
|
||||||
}
|
|
||||||
|
|
||||||
fn input(&self) -> &dyn InputPlatform {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assets(&self) -> &dyn AssetBridge {
|
fn assets(&self) -> &dyn AssetBridge {
|
||||||
&self.assets
|
&self.assets
|
||||||
}
|
}
|
||||||
|
|
||||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
||||||
&mut self.assets
|
&mut self.assets
|
||||||
}
|
}
|
||||||
|
|
||||||
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
|
||||||
&NOOP_TELEMETRY
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Hardware {
|
impl Hardware {
|
||||||
/// Internal hardware width in pixels.
|
/// Internal hardware width in pixels.
|
||||||
pub const W: usize = 480;
|
pub const W: usize = 320;
|
||||||
/// Internal hardware height in pixels.
|
/// Internal hardware height in pixels.
|
||||||
pub const H: usize = 270;
|
pub const H: usize = 180;
|
||||||
|
|
||||||
/// Creates a fresh hardware instance with default settings.
|
/// Creates a fresh hardware instance with default settings.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self::new_with_memory_banks(Arc::new(MemoryBanks::new()))
|
let memory_banks = Arc::new(MemoryBanks::new());
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates hardware with explicit shared bank ownership.
|
|
||||||
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
|
|
||||||
let assets = AssetManager::new(
|
|
||||||
vec![],
|
|
||||||
AssetsPayloadSource::empty(),
|
|
||||||
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolInstaller>,
|
|
||||||
Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolInstaller>,
|
|
||||||
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolInstaller>,
|
|
||||||
);
|
|
||||||
let glyph_slot_index = assets.glyph_asset_slot_index();
|
|
||||||
Self {
|
Self {
|
||||||
memory_banks: Arc::clone(&memory_banks),
|
|
||||||
gfx: Gfx::new(
|
gfx: Gfx::new(
|
||||||
Self::W,
|
Self::W,
|
||||||
Self::H,
|
Self::H,
|
||||||
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolAccess>,
|
Arc::clone(&memory_banks) as Arc<dyn TileBankPoolAccess>,
|
||||||
),
|
|
||||||
frame_composer: FrameComposer::new(
|
|
||||||
Self::W,
|
|
||||||
Self::H,
|
|
||||||
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolAccess>,
|
|
||||||
glyph_slot_index,
|
|
||||||
),
|
),
|
||||||
audio: Audio::new(Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolAccess>),
|
audio: Audio::new(Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolAccess>),
|
||||||
pad: Pad::default(),
|
pad: Pad::default(),
|
||||||
touch: Touch::default(),
|
touch: Touch::default(),
|
||||||
assets,
|
assets: AssetManager::new(
|
||||||
|
vec![],
|
||||||
|
AssetsPayloadSource::empty(),
|
||||||
|
Arc::clone(&memory_banks) as Arc<dyn TileBankPoolInstaller>,
|
||||||
|
Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolInstaller>,
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::memory_banks::{
|
|
||||||
GlyphBankPoolInstaller, SceneBankPoolAccess, SceneBankPoolInstaller,
|
|
||||||
};
|
|
||||||
use prometeu_hal::color::Color;
|
|
||||||
use prometeu_hal::glyph::Glyph;
|
|
||||||
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
|
||||||
use prometeu_hal::primitives::Rect;
|
|
||||||
use prometeu_hal::scene_bank::SceneBank;
|
|
||||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
|
||||||
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
|
||||||
use prometeu_hal::scene_viewport_resolver::SceneViewportResolver;
|
|
||||||
use prometeu_hal::tile::Tile;
|
|
||||||
use prometeu_hal::tilemap::TileMap;
|
|
||||||
use prometeu_hal::{
|
|
||||||
BoundScenePacket, Camera2D, ComposerFramePacket, FrameId, GameSpritePacket, Gfx2dCommand,
|
|
||||||
GfxUiCommand, ShellUiFramePacket,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn make_glyph_bank() -> GlyphBank {
|
|
||||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
|
||||||
bank.palette_mut(0).unwrap()[1] = Color::RED;
|
|
||||||
for pixel in &mut bank.pixel_indices {
|
|
||||||
*pixel = 1;
|
|
||||||
}
|
|
||||||
bank
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_scene() -> SceneBank {
|
|
||||||
make_scene_with_glyph_asset_id(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_scene_with_glyph_asset_id(glyph_asset_id: i32) -> SceneBank {
|
|
||||||
let layer = SceneLayer {
|
|
||||||
active: true,
|
|
||||||
glyph_asset_id,
|
|
||||||
tile_size: TileSize::Size8,
|
|
||||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
|
||||||
tilemap: TileMap {
|
|
||||||
width: 4,
|
|
||||||
height: 4,
|
|
||||||
tiles: vec![
|
|
||||||
Tile {
|
|
||||||
active: true,
|
|
||||||
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
|
||||||
flip_x: false,
|
|
||||||
flip_y: false,
|
|
||||||
};
|
|
||||||
16
|
|
||||||
],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hardware_can_render_scene_from_shared_scene_bank_pipeline() {
|
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
|
||||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
|
||||||
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
|
||||||
|
|
||||||
let mut hardware = Hardware::new_with_memory_banks(Arc::clone(&banks));
|
|
||||||
let scene = banks.scene_bank_slot(0).expect("scene bank slot 0 should be resident");
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 4, 4);
|
|
||||||
cache.materialize_all_layers(&scene);
|
|
||||||
|
|
||||||
let mut resolver = SceneViewportResolver::new(16, 16, 4, 4, 12, 20);
|
|
||||||
let update = resolver.update(&scene, 0, 0);
|
|
||||||
|
|
||||||
hardware.gfx.render_scene_from_cache(&cache, &update, &[0, 0, 0, 0]);
|
|
||||||
hardware.gfx.present();
|
|
||||||
|
|
||||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hardware_constructs_frame_composer_with_shared_scene_bank_access() {
|
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
|
||||||
banks.install_scene_bank(2, Arc::new(make_scene()));
|
|
||||||
|
|
||||||
let hardware = Hardware::new_with_memory_banks(banks);
|
|
||||||
let scene = hardware
|
|
||||||
.frame_composer
|
|
||||||
.scene_bank_slot(2)
|
|
||||||
.expect("scene bank slot 2 should be resident");
|
|
||||||
|
|
||||||
assert_eq!(hardware.frame_composer.viewport_size(), (Hardware::W, Hardware::H));
|
|
||||||
assert_eq!(hardware.frame_composer.scene_bank_slot_count(), 16);
|
|
||||||
assert_eq!(scene.layers[0].tile_size, TileSize::Size8);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn publish_game2d_submission_applies_gfx2d_overlay_after_active_scene() {
|
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
|
||||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
|
||||||
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
|
||||||
|
|
||||||
let mut hardware = Hardware::new_with_memory_banks(banks);
|
|
||||||
let mut glyph_slots = [None; 16];
|
|
||||||
glyph_slots[0] = Some(0);
|
|
||||||
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
|
|
||||||
assert_eq!(
|
|
||||||
Game2DFrameComposer::bind_scene(&mut hardware, 0),
|
|
||||||
prometeu_hal::ComposerOpStatus::Ok
|
|
||||||
);
|
|
||||||
|
|
||||||
let mut packet = Game2DFrameComposer::close_game2d_packet(&hardware);
|
|
||||||
packet.gfx2d = vec![Gfx2dCommand::FillRect {
|
|
||||||
rect: Rect { x: 0, y: 0, w: 1, h: 1 },
|
|
||||||
color: Color::BLUE,
|
|
||||||
}];
|
|
||||||
|
|
||||||
RenderSubmissionSink::submit_render_submission(
|
|
||||||
&mut hardware,
|
|
||||||
RenderSubmission::game2d(FrameId::ZERO, packet),
|
|
||||||
)
|
|
||||||
.expect("local sink should publish Game2D packet");
|
|
||||||
|
|
||||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::BLUE.raw());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn publish_game2d_submission_uses_packet_scene_and_sprites_not_live_frame_state() {
|
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
|
||||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
|
||||||
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
|
||||||
|
|
||||||
let mut hardware = Hardware::new_with_memory_banks(banks);
|
|
||||||
let mut glyph_slots = [None; 16];
|
|
||||||
glyph_slots[0] = Some(0);
|
|
||||||
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
|
|
||||||
assert_eq!(
|
|
||||||
Game2DFrameComposer::bind_scene(&mut hardware, 0),
|
|
||||||
prometeu_hal::ComposerOpStatus::Ok
|
|
||||||
);
|
|
||||||
|
|
||||||
let packet = Game2DFramePacket::new(
|
|
||||||
ComposerFramePacket {
|
|
||||||
bound_scene: Some(BoundScenePacket { bank_id: 0 }),
|
|
||||||
camera: Camera2D::default(),
|
|
||||||
sprites: vec![GameSpritePacket {
|
|
||||||
glyph_id: 0,
|
|
||||||
palette_id: 0,
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
layer: 0,
|
|
||||||
bank_id: 0,
|
|
||||||
flip_x: false,
|
|
||||||
flip_y: false,
|
|
||||||
priority: 0,
|
|
||||||
}],
|
|
||||||
hud: Default::default(),
|
|
||||||
},
|
|
||||||
Vec::new(),
|
|
||||||
);
|
|
||||||
|
|
||||||
Game2DFrameComposer::begin_frame(&mut hardware);
|
|
||||||
RenderSubmissionSink::submit_render_submission(
|
|
||||||
&mut hardware,
|
|
||||||
RenderSubmission::game2d(FrameId::ZERO, packet),
|
|
||||||
)
|
|
||||||
.expect("local sink should publish Game2D packet");
|
|
||||||
|
|
||||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_submission_sink_accepts_owned_game2d_submission() {
|
|
||||||
let mut hardware = Hardware::new();
|
|
||||||
let packet = Game2DFramePacket::new(
|
|
||||||
ComposerFramePacket::default(),
|
|
||||||
vec![Gfx2dCommand::Clear { color: Color::BLUE }],
|
|
||||||
);
|
|
||||||
let submission = RenderSubmission::game2d(FrameId::ZERO, packet);
|
|
||||||
|
|
||||||
RenderSubmissionSink::submit_render_submission(&mut hardware, submission)
|
|
||||||
.expect("local sink should accept owned Game2D submissions");
|
|
||||||
|
|
||||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::BLUE.raw());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_submission_sink_accepts_owned_shell_ui_submission() {
|
|
||||||
let mut hardware = Hardware::new();
|
|
||||||
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::Clear { color: Color::RED }]);
|
|
||||||
let submission = RenderSubmission::shell_ui(FrameId::ZERO, packet);
|
|
||||||
|
|
||||||
RenderSubmissionSink::submit_render_submission(&mut hardware, submission)
|
|
||||||
.expect("local sink should accept owned ShellUi submissions");
|
|
||||||
|
|
||||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn emit_sprite_rejects_palette_id_outside_loaded_glyph_bank() {
|
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
|
||||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
|
||||||
let mut hardware = Hardware::new_with_memory_banks(banks);
|
|
||||||
|
|
||||||
let status = Game2DFrameComposer::emit_sprite(
|
|
||||||
&mut hardware,
|
|
||||||
Sprite {
|
|
||||||
glyph: Glyph { glyph_id: 0, palette_id: 1 },
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
layer: 0,
|
|
||||||
bank_id: 0,
|
|
||||||
active: false,
|
|
||||||
flip_x: false,
|
|
||||||
flip_y: false,
|
|
||||||
priority: 0,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(status, prometeu_hal::ComposerOpStatus::BankInvalid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,22 +1,13 @@
|
|||||||
mod asset;
|
mod asset;
|
||||||
mod audio;
|
mod audio;
|
||||||
mod frame_composer;
|
|
||||||
mod gfx;
|
mod gfx;
|
||||||
pub mod hardware;
|
pub mod hardware;
|
||||||
mod local_render_backend;
|
|
||||||
mod memory_banks;
|
mod memory_banks;
|
||||||
mod pad;
|
mod pad;
|
||||||
mod test_platform;
|
|
||||||
mod touch;
|
mod touch;
|
||||||
|
|
||||||
pub use crate::asset::AssetManager;
|
pub use crate::asset::AssetManager;
|
||||||
pub use crate::audio::{Audio, AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
|
pub use crate::audio::{Audio, AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
|
||||||
pub use crate::frame_composer::{ComposerBuffer, FrameComposer, SceneStatus, SpriteController};
|
|
||||||
pub use crate::gfx::Gfx;
|
pub use crate::gfx::Gfx;
|
||||||
pub use crate::local_render_backend::LocalFramebufferRenderBackend;
|
pub use crate::memory_banks::MemoryBanks;
|
||||||
pub use crate::memory_banks::{
|
|
||||||
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolAccess,
|
|
||||||
SceneBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller,
|
|
||||||
};
|
|
||||||
pub use crate::pad::Pad;
|
pub use crate::pad::Pad;
|
||||||
pub use crate::test_platform::TestPlatform;
|
|
||||||
|
|||||||
@@ -1,164 +0,0 @@
|
|||||||
use crate::asset::GlyphAssetSlotIndex;
|
|
||||||
use crate::frame_composer::FrameComposer;
|
|
||||||
use crate::gfx::Gfx;
|
|
||||||
use crate::memory_banks::{GlyphBankPoolAccess, MemoryBanks, SceneBankPoolAccess};
|
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::{
|
|
||||||
OwnedRgba8888Frame, RenderSubmission, RenderSubmissionPacket, RenderWorkerBackend,
|
|
||||||
RenderWorkerError,
|
|
||||||
};
|
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
pub struct LocalFramebufferRenderBackend {
|
|
||||||
gfx: Mutex<Gfx>,
|
|
||||||
frame_composer: Mutex<FrameComposer>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LocalFramebufferRenderBackend {
|
|
||||||
pub fn new(width: usize, height: usize, glyph_banks: Arc<dyn GlyphBankPoolAccess>) -> Self {
|
|
||||||
Self::new_with_parts(
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
glyph_banks,
|
|
||||||
Arc::new(MemoryBanks::new()),
|
|
||||||
GlyphAssetSlotIndex::new(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_with_memory_banks(
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
memory_banks: Arc<MemoryBanks>,
|
|
||||||
glyph_slot_index: GlyphAssetSlotIndex,
|
|
||||||
) -> Self {
|
|
||||||
Self::new_with_parts(
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolAccess>,
|
|
||||||
memory_banks,
|
|
||||||
glyph_slot_index,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new_with_parts(
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
glyph_banks: Arc<dyn GlyphBankPoolAccess>,
|
|
||||||
scene_banks: Arc<dyn SceneBankPoolAccess>,
|
|
||||||
glyph_slot_index: GlyphAssetSlotIndex,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
gfx: Mutex::new(Gfx::new(width, height, glyph_banks)),
|
|
||||||
frame_composer: Mutex::new(FrameComposer::new(
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
scene_banks,
|
|
||||||
glyph_slot_index,
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn render_submission(
|
|
||||||
&self,
|
|
||||||
submission: &RenderSubmission,
|
|
||||||
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
|
|
||||||
let mut gfx = self.gfx.lock().map_err(|_| RenderWorkerError::InternalFailure)?;
|
|
||||||
match &submission.packet {
|
|
||||||
RenderSubmissionPacket::Game2D(packet) if submission.app_mode == AppMode::Game => {
|
|
||||||
if packet.composer.bound_scene.is_none() {
|
|
||||||
gfx.render_game2d_frame_packet(packet);
|
|
||||||
} else {
|
|
||||||
let mut frame_composer = self
|
|
||||||
.frame_composer
|
|
||||||
.lock()
|
|
||||||
.map_err(|_| RenderWorkerError::InternalFailure)?;
|
|
||||||
frame_composer.render_game2d_frame_packet(packet, &mut *gfx);
|
|
||||||
gfx.apply_gfx2d_commands(&packet.gfx2d);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
RenderSubmissionPacket::ShellUi(packet) if submission.app_mode == AppMode::Shell => {
|
|
||||||
gfx.render_shell_ui_frame_packet(packet);
|
|
||||||
}
|
|
||||||
_ => return Err(RenderWorkerError::RenderFailed),
|
|
||||||
}
|
|
||||||
|
|
||||||
gfx.present();
|
|
||||||
let (width, height) = gfx.size();
|
|
||||||
OwnedRgba8888Frame::packed(
|
|
||||||
submission.frame_id,
|
|
||||||
submission.ownership,
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
gfx.front_buffer().to_vec(),
|
|
||||||
)
|
|
||||||
.map_err(|_| RenderWorkerError::InternalFailure)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderWorkerBackend for LocalFramebufferRenderBackend {
|
|
||||||
fn render(
|
|
||||||
&self,
|
|
||||||
submission: &RenderSubmission,
|
|
||||||
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
|
|
||||||
self.render_submission(submission)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::memory_banks::MemoryBanks;
|
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::color::Color;
|
|
||||||
use prometeu_hal::primitives::Rect;
|
|
||||||
use prometeu_hal::{
|
|
||||||
FrameId, Game2DFramePacket, Gfx2dCommand, GfxUiCommand, RenderOwnership, ShellUiFramePacket,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn backend() -> LocalFramebufferRenderBackend {
|
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
|
||||||
LocalFramebufferRenderBackend::new(4, 4, banks)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn local_backend_renders_game2d_submission_to_owned_frame() {
|
|
||||||
let backend = backend();
|
|
||||||
let packet = Game2DFramePacket {
|
|
||||||
gfx2d: vec![Gfx2dCommand::FillRect {
|
|
||||||
rect: Rect { x: 1, y: 1, w: 2, h: 2 },
|
|
||||||
color: Color::RED,
|
|
||||||
}],
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let ownership = RenderOwnership::new(3, AppMode::Game, 9);
|
|
||||||
let submission =
|
|
||||||
RenderSubmission::game2d(FrameId::new(5), packet).with_ownership(ownership);
|
|
||||||
|
|
||||||
let frame = backend.render(&submission).expect("game frame should render");
|
|
||||||
|
|
||||||
assert_eq!(frame.frame_id, FrameId::new(5));
|
|
||||||
assert_eq!(frame.ownership, ownership);
|
|
||||||
assert_eq!(frame.width, 4);
|
|
||||||
assert_eq!(frame.height, 4);
|
|
||||||
assert_eq!(frame.pixels[1 + 4], Color::RED.raw());
|
|
||||||
assert_eq!(frame.pixels[2 + 2 * 4], Color::RED.raw());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn local_backend_renders_shell_ui_submission_to_owned_frame() {
|
|
||||||
let backend = backend();
|
|
||||||
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::FillRect {
|
|
||||||
rect: Rect { x: 0, y: 0, w: 1, h: 1 },
|
|
||||||
color: Color::GREEN,
|
|
||||||
}]);
|
|
||||||
let ownership = RenderOwnership::new(4, AppMode::Shell, 10);
|
|
||||||
let submission =
|
|
||||||
RenderSubmission::shell_ui(FrameId::new(6), packet).with_ownership(ownership);
|
|
||||||
|
|
||||||
let frame = backend.render(&submission).expect("shell frame should render");
|
|
||||||
|
|
||||||
assert_eq!(frame.frame_id, FrameId::new(6));
|
|
||||||
assert_eq!(frame.ownership, ownership);
|
|
||||||
assert_eq!(frame.pixels[0], Color::GREEN.raw());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +1,19 @@
|
|||||||
//! Memory bank access boundary.
|
|
||||||
//!
|
|
||||||
//! Render consumers must cross this boundary through small, read-only traits.
|
|
||||||
//! Frame packets carry resource IDs; large resident resources stay in banks and
|
|
||||||
//! are read in place through a narrow HAL callback contract. Installation and
|
|
||||||
//! slot replacement remain separate owner-side operations and are not part of
|
|
||||||
//! the render read surface.
|
|
||||||
|
|
||||||
use prometeu_hal::glyph_bank::GlyphBank;
|
|
||||||
use prometeu_hal::render_resources::RenderResourceAccess as HalRenderResourceAccess;
|
|
||||||
use prometeu_hal::scene_bank::SceneBank;
|
|
||||||
use prometeu_hal::sound_bank::SoundBank;
|
use prometeu_hal::sound_bank::SoundBank;
|
||||||
|
use prometeu_hal::tile_bank::TileBank;
|
||||||
use std::sync::{Arc, RwLock};
|
use std::sync::{Arc, RwLock};
|
||||||
|
|
||||||
/// Non-generic interface for peripherals to access graphical glyph banks.
|
/// Non-generic interface for peripherals to access graphical tile banks.
|
||||||
pub trait GlyphBankPoolAccess: Send + Sync {
|
pub trait TileBankPoolAccess: Send + Sync {
|
||||||
/// Returns a reference to the resident GlyphBank in the specified slot, if any.
|
/// Returns a reference to the resident TileBank in the specified slot, if any.
|
||||||
fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>>;
|
fn tile_bank_slot(&self, slot: usize) -> Option<Arc<TileBank>>;
|
||||||
/// Returns the total number of slots available in this bank.
|
/// Returns the total number of slots available in this bank.
|
||||||
fn glyph_bank_slot_count(&self) -> usize;
|
fn tile_bank_slot_count(&self) -> usize;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Non-generic interface for the AssetManager to install graphical glyph banks.
|
/// Non-generic interface for the AssetManager to install graphical tile banks.
|
||||||
pub trait GlyphBankPoolInstaller: Send + Sync {
|
pub trait TileBankPoolInstaller: Send + Sync {
|
||||||
/// Atomically swaps the resident GlyphBank in the specified slot.
|
/// Atomically swaps the resident TileBank in the specified slot.
|
||||||
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>);
|
fn install_tile_bank(&self, slot: usize, bank: Arc<TileBank>);
|
||||||
/// Clears all resident GlyphBank slots.
|
|
||||||
fn clear_glyph_banks(&self);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Non-generic interface for peripherals to access sound banks.
|
/// Non-generic interface for peripherals to access sound banks.
|
||||||
@@ -40,24 +28,6 @@ pub trait SoundBankPoolAccess: Send + Sync {
|
|||||||
pub trait SoundBankPoolInstaller: Send + Sync {
|
pub trait SoundBankPoolInstaller: Send + Sync {
|
||||||
/// Atomically swaps the resident SoundBank in the specified slot.
|
/// Atomically swaps the resident SoundBank in the specified slot.
|
||||||
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>);
|
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>);
|
||||||
/// Clears all resident SoundBank slots.
|
|
||||||
fn clear_sound_banks(&self);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Non-generic interface for peripherals to access scene banks.
|
|
||||||
pub trait SceneBankPoolAccess: Send + Sync {
|
|
||||||
/// Returns a reference to the resident SceneBank in the specified slot, if any.
|
|
||||||
fn scene_bank_slot(&self, slot: usize) -> Option<Arc<SceneBank>>;
|
|
||||||
/// Returns the total number of slots available in this bank.
|
|
||||||
fn scene_bank_slot_count(&self) -> usize;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Non-generic interface for the AssetManager to install scene banks.
|
|
||||||
pub trait SceneBankPoolInstaller: Send + Sync {
|
|
||||||
/// Atomically swaps the resident SceneBank in the specified slot.
|
|
||||||
fn install_scene_bank(&self, slot: usize, bank: Arc<SceneBank>);
|
|
||||||
/// Clears all resident SceneBank slots.
|
|
||||||
fn clear_scene_banks(&self);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Centralized container for all hardware memory banks.
|
/// Centralized container for all hardware memory banks.
|
||||||
@@ -66,9 +36,8 @@ pub trait SceneBankPoolInstaller: Send + Sync {
|
|||||||
/// Peripherals consume this state via narrow, non-generic traits.
|
/// Peripherals consume this state via narrow, non-generic traits.
|
||||||
/// AssetManager coordinates residency and installs assets into these slots.
|
/// AssetManager coordinates residency and installs assets into these slots.
|
||||||
pub struct MemoryBanks {
|
pub struct MemoryBanks {
|
||||||
glyph_bank_pool: Arc<RwLock<[Option<Arc<GlyphBank>>; 16]>>,
|
tile_bank_pool: Arc<RwLock<[Option<Arc<TileBank>>; 16]>>,
|
||||||
sound_bank_pool: Arc<RwLock<[Option<Arc<SoundBank>>; 16]>>,
|
sound_bank_pool: Arc<RwLock<[Option<Arc<SoundBank>>; 16]>>,
|
||||||
scene_bank_pool: Arc<RwLock<[Option<Arc<SceneBank>>; 16]>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for MemoryBanks {
|
impl Default for MemoryBanks {
|
||||||
@@ -81,35 +50,30 @@ impl MemoryBanks {
|
|||||||
/// Creates a new set of memory banks with empty slots.
|
/// Creates a new set of memory banks with empty slots.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
glyph_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
|
tile_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
|
||||||
sound_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
|
sound_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
|
||||||
scene_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlyphBankPoolAccess for MemoryBanks {
|
impl TileBankPoolAccess for MemoryBanks {
|
||||||
fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>> {
|
fn tile_bank_slot(&self, slot: usize) -> Option<Arc<TileBank>> {
|
||||||
let pool = self.glyph_bank_pool.read().unwrap();
|
let pool = self.tile_bank_pool.read().unwrap();
|
||||||
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
|
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn glyph_bank_slot_count(&self) -> usize {
|
fn tile_bank_slot_count(&self) -> usize {
|
||||||
16
|
16
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlyphBankPoolInstaller for MemoryBanks {
|
impl TileBankPoolInstaller for MemoryBanks {
|
||||||
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>) {
|
fn install_tile_bank(&self, slot: usize, bank: Arc<TileBank>) {
|
||||||
let mut pool = self.glyph_bank_pool.write().unwrap();
|
let mut pool = self.tile_bank_pool.write().unwrap();
|
||||||
if slot < 16 {
|
if slot < 16 {
|
||||||
pool[slot] = Some(bank);
|
pool[slot] = Some(bank);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn clear_glyph_banks(&self) {
|
|
||||||
self.glyph_bank_pool.write().unwrap().fill(None);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SoundBankPoolAccess for MemoryBanks {
|
impl SoundBankPoolAccess for MemoryBanks {
|
||||||
@@ -130,119 +94,4 @@ impl SoundBankPoolInstaller for MemoryBanks {
|
|||||||
pool[slot] = Some(bank);
|
pool[slot] = Some(bank);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn clear_sound_banks(&self) {
|
|
||||||
self.sound_bank_pool.write().unwrap().fill(None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SceneBankPoolAccess for MemoryBanks {
|
|
||||||
fn scene_bank_slot(&self, slot: usize) -> Option<Arc<SceneBank>> {
|
|
||||||
let pool = self.scene_bank_pool.read().unwrap();
|
|
||||||
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scene_bank_slot_count(&self) -> usize {
|
|
||||||
16
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SceneBankPoolInstaller for MemoryBanks {
|
|
||||||
fn install_scene_bank(&self, slot: usize, bank: Arc<SceneBank>) {
|
|
||||||
let mut pool = self.scene_bank_pool.write().unwrap();
|
|
||||||
if slot < 16 {
|
|
||||||
pool[slot] = Some(bank);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clear_scene_banks(&self) {
|
|
||||||
self.scene_bank_pool.write().unwrap().fill(None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HalRenderResourceAccess for MemoryBanks {
|
|
||||||
fn with_glyph_bank<R>(&self, bank_id: usize, read: impl FnOnce(&GlyphBank) -> R) -> Option<R> {
|
|
||||||
let pool = self.glyph_bank_pool.read().unwrap();
|
|
||||||
let bank = pool.get(bank_id)?.as_deref()?;
|
|
||||||
Some(read(bank))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn glyph_bank_count(&self) -> usize {
|
|
||||||
16
|
|
||||||
}
|
|
||||||
|
|
||||||
fn with_scene_bank<R>(&self, bank_id: usize, read: impl FnOnce(&SceneBank) -> R) -> Option<R> {
|
|
||||||
let pool = self.scene_bank_pool.read().unwrap();
|
|
||||||
let bank = pool.get(bank_id)?.as_deref()?;
|
|
||||||
Some(read(bank))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scene_bank_count(&self) -> usize {
|
|
||||||
16
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use prometeu_hal::color::Color;
|
|
||||||
use prometeu_hal::glyph::Glyph;
|
|
||||||
use prometeu_hal::glyph_bank::TileSize;
|
|
||||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
|
||||||
use prometeu_hal::tile::Tile;
|
|
||||||
use prometeu_hal::tilemap::TileMap;
|
|
||||||
|
|
||||||
fn assert_send_sync<T: Send + Sync>() {}
|
|
||||||
|
|
||||||
fn make_glyph_bank() -> GlyphBank {
|
|
||||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
|
||||||
bank.palette_mut(0).unwrap()[1] = Color::WHITE;
|
|
||||||
bank
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_scene_bank() -> SceneBank {
|
|
||||||
let layer = SceneLayer {
|
|
||||||
active: true,
|
|
||||||
glyph_asset_id: 0,
|
|
||||||
tile_size: TileSize::Size8,
|
|
||||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
|
||||||
tilemap: TileMap {
|
|
||||||
width: 1,
|
|
||||||
height: 1,
|
|
||||||
tiles: vec![Tile {
|
|
||||||
active: true,
|
|
||||||
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
|
||||||
flip_x: false,
|
|
||||||
flip_y: false,
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_resource_access_traits_are_thread_safe() {
|
|
||||||
assert_send_sync::<MemoryBanks>();
|
|
||||||
assert_send_sync::<Arc<dyn GlyphBankPoolAccess>>();
|
|
||||||
assert_send_sync::<Arc<dyn SceneBankPoolAccess>>();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_resource_access_exposes_read_only_glyph_and_scene_banks_without_arc_contract() {
|
|
||||||
let banks = MemoryBanks::new();
|
|
||||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
|
||||||
banks.install_scene_bank(1, Arc::new(make_scene_bank()));
|
|
||||||
|
|
||||||
let glyph_tile_size =
|
|
||||||
HalRenderResourceAccess::with_glyph_bank(&banks, 0, |bank| bank.tile_size);
|
|
||||||
let scene_tile_size =
|
|
||||||
HalRenderResourceAccess::with_scene_bank(&banks, 1, |bank| bank.layers[0].tile_size);
|
|
||||||
|
|
||||||
assert_eq!(glyph_tile_size, Some(TileSize::Size8));
|
|
||||||
assert_eq!(scene_tile_size, Some(TileSize::Size8));
|
|
||||||
assert_eq!(HalRenderResourceAccess::with_glyph_bank(&banks, 15, |_| ()), None);
|
|
||||||
assert_eq!(HalRenderResourceAccess::with_scene_bank(&banks, 15, |_| ()), None);
|
|
||||||
assert_eq!(HalRenderResourceAccess::glyph_bank_count(&banks), 16);
|
|
||||||
assert_eq!(HalRenderResourceAccess::scene_bank_count(&banks), 16);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,100 +0,0 @@
|
|||||||
use crate::hardware::Hardware;
|
|
||||||
use crate::memory_banks::MemoryBanks;
|
|
||||||
use prometeu_hal::{
|
|
||||||
AssetBridge, AudioBridge, Game2DFrameComposer, InputPlatform, RenderBackend,
|
|
||||||
RenderSubmissionSink, RuntimePlatform, TelemetryPlatform,
|
|
||||||
};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub struct TestPlatform {
|
|
||||||
hardware: Hardware,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for TestPlatform {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TestPlatform {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self { hardware: Hardware::new() }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
|
|
||||||
Self { hardware: Hardware::new_with_memory_banks(memory_banks) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn local_hardware(&self) -> &Hardware {
|
|
||||||
&self.hardware
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn local_hardware_mut(&mut self) -> &mut Hardware {
|
|
||||||
&mut self.hardware
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RuntimePlatform for TestPlatform {
|
|
||||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
|
||||||
self.hardware.render_submission_sink()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
|
||||||
self.hardware.render_backend()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
|
||||||
self.hardware.game2d_frame_composer()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn audio(&self) -> &dyn AudioBridge {
|
|
||||||
self.hardware.audio()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
|
||||||
self.hardware.audio_mut()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn input(&self) -> &dyn InputPlatform {
|
|
||||||
self.hardware.input()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
|
||||||
self.hardware.input_mut()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assets(&self) -> &dyn AssetBridge {
|
|
||||||
self.hardware.assets()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
|
||||||
self.hardware.assets_mut()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
|
||||||
self.hardware.telemetry()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use prometeu_hal::{FrameId, Game2DFramePacket, RenderSubmission};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_platform_initializes_required_facades() {
|
|
||||||
let mut platform = TestPlatform::new();
|
|
||||||
|
|
||||||
platform.game2d_frame_composer().begin_frame();
|
|
||||||
platform
|
|
||||||
.render_submission_sink()
|
|
||||||
.submit_render_submission(RenderSubmission::game2d(
|
|
||||||
FrameId::ZERO,
|
|
||||||
Game2DFramePacket::default(),
|
|
||||||
))
|
|
||||||
.expect("test platform render sink should accept local submission");
|
|
||||||
assert!(!platform.audio().is_playing(0));
|
|
||||||
assert!(!platform.input().pad().any());
|
|
||||||
assert!(platform.telemetry().telemetry_snapshot().is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,6 @@ pub use crate::firmware::firmware_step_hub_home::HubHomeStep;
|
|||||||
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
|
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
|
||||||
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
|
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
|
||||||
pub use crate::firmware::firmware_step_reset::ResetStep;
|
pub use crate::firmware::firmware_step_reset::ResetStep;
|
||||||
pub use crate::firmware::firmware_step_shell_running::ShellRunningStep;
|
|
||||||
pub use crate::firmware::firmware_step_splash_screen::SplashScreenStep;
|
pub use crate::firmware::firmware_step_splash_screen::SplashScreenStep;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -14,8 +13,6 @@ pub enum FirmwareState {
|
|||||||
LaunchHub(LaunchHubStep),
|
LaunchHub(LaunchHubStep),
|
||||||
HubHome(HubHomeStep),
|
HubHome(HubHomeStep),
|
||||||
LoadCartridge(LoadCartridgeStep),
|
LoadCartridge(LoadCartridgeStep),
|
||||||
ResumeResidentGame,
|
|
||||||
GameRunning(GameRunningStep),
|
GameRunning(GameRunningStep),
|
||||||
ShellRunning(ShellRunningStep),
|
|
||||||
AppCrashes(AppCrashesStep),
|
AppCrashes(AppCrashesStep),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
|
|||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
use prometeu_hal::{FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket};
|
|
||||||
use prometeu_system::CrashReport;
|
use prometeu_system::CrashReport;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -21,16 +20,16 @@ impl AppCrashesStep {
|
|||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
// Update peripherals for input on the crash screen
|
// Update peripherals for input on the crash screen
|
||||||
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
|
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
||||||
|
|
||||||
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::Clear { color: Color::RED }]);
|
// Error screen: red background, white text
|
||||||
ctx.platform
|
ctx.hw.gfx_mut().clear(Color::RED);
|
||||||
.render_submission_sink()
|
// For now we just log or show something simple
|
||||||
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
|
// In the future, use draw_text
|
||||||
.expect("firmware crash render submission should publish");
|
ctx.hw.gfx_mut().present();
|
||||||
|
|
||||||
// If START is pressed, return to the Hub
|
// If START is pressed, return to the Hub
|
||||||
if ctx.platform.input().pad().start().down {
|
if ctx.hw.pad().start().down {
|
||||||
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,72 +1,23 @@
|
|||||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
|
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
use prometeu_system::task::{TaskId, TaskState};
|
|
||||||
use prometeu_system::{CrashReport, ResidentGameState};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct GameRunningStep {
|
pub struct GameRunningStep;
|
||||||
pub task_id: TaskId,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GameRunningStep {
|
impl GameRunningStep {
|
||||||
pub fn new(task_id: TaskId) -> Self {
|
|
||||||
Self { task_id }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Entering GameRunning".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Entering GameRunning".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
let Some(task_state) = ctx.os.lifecycle().task_state(self.task_id) else {
|
let result = ctx.os.tick(ctx.vm, ctx.signals, ctx.hw);
|
||||||
// TODO: is it panic?
|
|
||||||
let report =
|
|
||||||
CrashReport::VmPanic { message: "task is gone, panic!".to_string(), pc: None };
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
};
|
|
||||||
|
|
||||||
if task_state != TaskState::Foreground {
|
if !ctx.os.logical_frame_active {
|
||||||
// TODO: is it panic?
|
ctx.hw.gfx_mut().present();
|
||||||
let report = CrashReport::VmPanic {
|
|
||||||
message: "should be running as foreground, panic!".to_string(),
|
|
||||||
pc: None,
|
|
||||||
};
|
|
||||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let pause_requested = matches!(
|
result.map(|report| FirmwareState::AppCrashes(AppCrashesStep { report }))
|
||||||
ctx.os.lifecycle().resident_game().map(|game| game.state),
|
|
||||||
Some(ResidentGameState::PauseRequested { .. })
|
|
||||||
);
|
|
||||||
let result = ctx.os.vm().tick_session(self.task_id, ctx.signals, ctx.platform);
|
|
||||||
|
|
||||||
if let Some(report) = result {
|
|
||||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
}
|
|
||||||
|
|
||||||
if pause_requested {
|
|
||||||
match ctx.os.lifecycle().advance_game_pause_budget(self.task_id) {
|
|
||||||
Ok(true) => {
|
|
||||||
ctx.os.vm().transition_render_owner(AppMode::Shell, 0);
|
|
||||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
|
||||||
}
|
|
||||||
Ok(false) => {}
|
|
||||||
Err(_) => {
|
|
||||||
let report = CrashReport::VmPanic {
|
|
||||||
message: "failed to advance game pause budget".to_string(),
|
|
||||||
pc: None,
|
|
||||||
};
|
|
||||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
|
|||||||
@@ -1,14 +1,6 @@
|
|||||||
use crate::firmware::firmware_state::{
|
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
|
||||||
AppCrashesStep, FirmwareState, LoadCartridgeStep, ShellRunningStep,
|
|
||||||
};
|
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use crate::firmware::resident_game_termination;
|
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::cartridge_loader::CartridgeLoader;
|
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
use prometeu_hal::primitives::Rect;
|
|
||||||
use prometeu_system::SystemProfileAction;
|
|
||||||
use prometeu_system::windows::WindowOwner;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct HubHomeStep;
|
pub struct HubHomeStep;
|
||||||
@@ -16,109 +8,30 @@ pub struct HubHomeStep;
|
|||||||
impl HubHomeStep {
|
impl HubHomeStep {
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Hub, 0, "Entering HubHome".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Hub, 0, "Entering HubHome".to_string());
|
||||||
ctx.os.windows().remove_all_windows();
|
|
||||||
ctx.hub.init();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.platform);
|
let mut error = None;
|
||||||
if let Some(report) = outcome.crash {
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
// Always updates the Hub GUI (clears screen and processes input if no focus)
|
||||||
|
ctx.hub.gui_update(ctx.os, ctx.hw);
|
||||||
|
|
||||||
|
if let Some(focused_id) = ctx.hub.window_manager.focused {
|
||||||
|
if ctx.hw.pad().start().down {
|
||||||
|
ctx.hub.window_manager.remove_window(focused_id);
|
||||||
|
} else {
|
||||||
|
// System App runs here, drawing over the Hub background
|
||||||
|
error = ctx.os.tick(ctx.vm, ctx.signals, ctx.hw);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match outcome.action {
|
// Renders the System App window borders
|
||||||
Some(SystemProfileAction::LaunchNativeShell(app)) => {
|
ctx.hub.render(ctx.os, ctx.hw);
|
||||||
let task_id = match ctx
|
|
||||||
.os
|
|
||||||
.sessions()
|
|
||||||
.try_create_native_shell_task(app.app_id(), app.title())
|
|
||||||
{
|
|
||||||
Ok(task_id) => task_id,
|
|
||||||
Err(error) => {
|
|
||||||
ctx.os.log(
|
|
||||||
LogLevel::Warn,
|
|
||||||
LogSource::Hub,
|
|
||||||
0,
|
|
||||||
format!("Failed to launch native shell {}: {:?}", app.title(), error),
|
|
||||||
);
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let id = ctx.os.windows().add_window(
|
|
||||||
app.title().to_string(),
|
|
||||||
WindowOwner::Task(task_id),
|
|
||||||
Rect { x: 40, y: 20, w: 400, h: 220 },
|
|
||||||
app.color(),
|
|
||||||
);
|
|
||||||
ctx.os.windows().set_focus(id);
|
|
||||||
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
|
||||||
}
|
|
||||||
Some(SystemProfileAction::LaunchGame { target }) => {
|
|
||||||
match CartridgeLoader::load(&target.path) {
|
|
||||||
Ok(cartridge) => {
|
|
||||||
if cartridge.app_mode == AppMode::Game
|
|
||||||
&& let Some(resident_task_id) = ctx.os.lifecycle().resident_game_task()
|
|
||||||
{
|
|
||||||
let resident_app_id = ctx
|
|
||||||
.os
|
|
||||||
.sessions()
|
|
||||||
.vm_session_for_task(resident_task_id)
|
|
||||||
.map(|session| session.app_id)
|
|
||||||
.unwrap_or(0);
|
|
||||||
|
|
||||||
if resident_app_id == cartridge.app_id {
|
ctx.hw.gfx_mut().present();
|
||||||
return Some(FirmwareState::ResumeResidentGame);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Err(error) = resident_game_termination::terminate_resident_game(
|
if let Some(report) = error {
|
||||||
ctx.os,
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
ctx.platform,
|
|
||||||
false,
|
|
||||||
) {
|
|
||||||
ctx.os.log(
|
|
||||||
LogLevel::Error,
|
|
||||||
LogSource::Hub,
|
|
||||||
0,
|
|
||||||
format!(
|
|
||||||
"Failed to terminate resident game app_id {} before launching {}: {:?}",
|
|
||||||
resident_app_id, cartridge.title, error
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Some(FirmwareState::LoadCartridge(
|
|
||||||
LoadCartridgeStep::new_game_switch(cartridge),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
ctx.os.log(
|
|
||||||
LogLevel::Error,
|
|
||||||
LogSource::Hub,
|
|
||||||
0,
|
|
||||||
format!(
|
|
||||||
"Failed to launch Home game {}: {:?}",
|
|
||||||
target.path.display(),
|
|
||||||
error
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(SystemProfileAction::KillResidentGame) => {
|
|
||||||
if let Err(error) =
|
|
||||||
resident_game_termination::terminate_resident_game(ctx.os, ctx.platform, true)
|
|
||||||
{
|
|
||||||
ctx.os.log(
|
|
||||||
LogLevel::Error,
|
|
||||||
LogSource::Hub,
|
|
||||||
0,
|
|
||||||
format!("Failed to kill resident game from Hub: {error:?}"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(SystemProfileAction::CloseShell) | None => {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -1,44 +1,22 @@
|
|||||||
use crate::firmware::firmware_state::{
|
use crate::firmware::firmware_state::{
|
||||||
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep, ShellRunningStep,
|
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep,
|
||||||
};
|
};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use crate::firmware::resident_game_termination;
|
use prometeu_hal::cartridge::{AppMode, Cartridge};
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::cartridge::Cartridge;
|
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
use prometeu_hal::primitives::Rect;
|
use prometeu_hal::window::Rect;
|
||||||
use prometeu_system::CrashReport;
|
use prometeu_system::CrashReport;
|
||||||
use prometeu_system::windows::WindowOwner;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct LoadCartridgeStep {
|
pub struct LoadCartridgeStep {
|
||||||
pub cartridge: Cartridge,
|
pub cartridge: Cartridge,
|
||||||
init_error: Option<CrashReport>,
|
init_error: Option<CrashReport>,
|
||||||
loaded_task_id: Option<prometeu_system::task::TaskId>,
|
|
||||||
loaded_app_mode: Option<AppMode>,
|
|
||||||
failure_recovery: LoadCartridgeFailureRecovery,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
enum LoadCartridgeFailureRecovery {
|
|
||||||
AppCrash,
|
|
||||||
ReturnToHub,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LoadCartridgeStep {
|
impl LoadCartridgeStep {
|
||||||
pub fn new(cartridge: Cartridge) -> Self {
|
pub fn new(cartridge: Cartridge) -> Self {
|
||||||
Self {
|
Self { cartridge, init_error: None }
|
||||||
cartridge,
|
|
||||||
init_error: None,
|
|
||||||
loaded_task_id: None,
|
|
||||||
loaded_app_mode: None,
|
|
||||||
failure_recovery: LoadCartridgeFailureRecovery::AppCrash,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_game_switch(cartridge: Cartridge) -> Self {
|
|
||||||
Self { failure_recovery: LoadCartridgeFailureRecovery::ReturnToHub, ..Self::new(cartridge) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
@@ -49,86 +27,35 @@ impl LoadCartridgeStep {
|
|||||||
format!("Loading cartridge: {}", self.cartridge.title),
|
format!("Loading cartridge: {}", self.cartridge.title),
|
||||||
);
|
);
|
||||||
|
|
||||||
ctx.platform.game2d_frame_composer().unbind_scene();
|
|
||||||
|
|
||||||
// Initialize Asset Manager
|
// Initialize Asset Manager
|
||||||
ctx.platform.assets_mut().initialize_for_cartridge(
|
ctx.hw.assets_mut().initialize_for_cartridge(
|
||||||
self.cartridge.asset_table.clone(),
|
self.cartridge.asset_table.clone(),
|
||||||
self.cartridge.preload.clone(),
|
self.cartridge.preload.clone(),
|
||||||
self.cartridge.assets.clone(),
|
self.cartridge.assets.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
match ctx.os.sessions().load_vm_cartridge(&self.cartridge) {
|
self.init_error = ctx.os.initialize_vm(ctx.vm, &self.cartridge).err();
|
||||||
Ok(loaded) => {
|
|
||||||
self.loaded_task_id = Some(loaded.task_id);
|
|
||||||
self.loaded_app_mode = Some(loaded.app_mode);
|
|
||||||
}
|
|
||||||
Err(report) => {
|
|
||||||
self.init_error = Some(report.into_crash_report("load VM cartridge into session"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
if let Some(report) = self.init_error.take() {
|
if let Some(report) = self.init_error.take() {
|
||||||
if self.failure_recovery == LoadCartridgeFailureRecovery::ReturnToHub {
|
|
||||||
if self.cartridge.app_mode == AppMode::Game
|
|
||||||
&& let Some(task_id) = ctx.os.lifecycle().resident_game_task()
|
|
||||||
{
|
|
||||||
let is_partial_target = ctx
|
|
||||||
.os
|
|
||||||
.sessions()
|
|
||||||
.vm_session_for_task(task_id)
|
|
||||||
.map(|session| session.app_id == self.cartridge.app_id)
|
|
||||||
.unwrap_or(false);
|
|
||||||
|
|
||||||
if is_partial_target {
|
|
||||||
let _ = resident_game_termination::terminate_resident_game(
|
|
||||||
ctx.os,
|
|
||||||
ctx.platform,
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.os.log(
|
|
||||||
LogLevel::Error,
|
|
||||||
LogSource::Hub,
|
|
||||||
0,
|
|
||||||
format!(
|
|
||||||
"Failed to switch to game {} app_id {}; returning to Home: {:?}",
|
|
||||||
self.cartridge.title, self.cartridge.app_id, report
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
|
||||||
}
|
|
||||||
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(task_id) = self.loaded_task_id.take() else {
|
if self.cartridge.app_mode == AppMode::System {
|
||||||
let report = CrashReport::VmPanic {
|
let id = ctx.hub.window_manager.add_window(
|
||||||
message: format!(
|
|
||||||
"cartridge {} was not loaded into a VM session",
|
|
||||||
self.cartridge.title
|
|
||||||
),
|
|
||||||
pc: None,
|
|
||||||
};
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
};
|
|
||||||
|
|
||||||
if self.loaded_app_mode == Some(AppMode::Shell) {
|
|
||||||
let id = ctx.os.windows().add_window(
|
|
||||||
self.cartridge.title.clone(),
|
self.cartridge.title.clone(),
|
||||||
WindowOwner::Task(task_id),
|
|
||||||
Rect { x: 40, y: 20, w: 240, h: 140 },
|
Rect { x: 40, y: 20, w: 240, h: 140 },
|
||||||
Color::WHITE,
|
Color::WHITE,
|
||||||
);
|
);
|
||||||
ctx.os.windows().set_focus(id);
|
ctx.hub.window_manager.set_focus(id);
|
||||||
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
|
||||||
|
// System apps do not change the firmware state to GameRunning.
|
||||||
|
// They run in the background or via windows in the Hub.
|
||||||
|
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(FirmwareState::GameRunning(GameRunningStep::new(task_id)))
|
Some(FirmwareState::GameRunning(GameRunningStep))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
|
|||||||
@@ -9,12 +9,7 @@ pub struct ResetStep;
|
|||||||
impl ResetStep {
|
impl ResetStep {
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
|
||||||
// Reset is a cold-boot boundary. Clearing only the VM session leaves
|
ctx.os.reset(ctx.vm);
|
||||||
// the lifecycle registry pointing at the old resident game, which
|
|
||||||
// rejects the next cartridge as a second resident game.
|
|
||||||
let _ = ctx.os.lifecycle().terminate_resident_game();
|
|
||||||
ctx.os.sessions().clear_vm_sessions();
|
|
||||||
ctx.os.vm().reset_global_runtime_state();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
|
|||||||
@@ -1,131 +0,0 @@
|
|||||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
|
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
|
||||||
use prometeu_hal::log::LogSource;
|
|
||||||
use prometeu_system::process::ProcessKind;
|
|
||||||
use prometeu_system::task::{TaskId, TaskState};
|
|
||||||
use prometeu_system::{CrashReport, SystemProfileAction};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct ShellRunningStep {
|
|
||||||
pub task_id: TaskId,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ShellRunningStep {
|
|
||||||
pub fn new(task_id: TaskId) -> Self {
|
|
||||||
Self { task_id }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
|
||||||
ctx.os.info(LogSource::Hub, "Entering ShellRunning".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
|
||||||
let Some(task_state) = ctx.os.lifecycle().task_state(self.task_id) else {
|
|
||||||
let report = CrashReport::VmPanic {
|
|
||||||
message: format!("ShellRunningStep has no task for {:?}", self.task_id),
|
|
||||||
pc: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
};
|
|
||||||
|
|
||||||
match task_state {
|
|
||||||
TaskState::Foreground => {
|
|
||||||
// Continue below.
|
|
||||||
}
|
|
||||||
|
|
||||||
TaskState::Closed => {
|
|
||||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
|
||||||
}
|
|
||||||
|
|
||||||
TaskState::Crashed => {
|
|
||||||
let report = CrashReport::VmPanic {
|
|
||||||
message: format!("Shell task {:?} is already crashed", self.task_id),
|
|
||||||
pc: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
}
|
|
||||||
|
|
||||||
TaskState::Suspended | TaskState::Background => {
|
|
||||||
let report = CrashReport::VmPanic {
|
|
||||||
message: format!(
|
|
||||||
"ShellRunningStep expected foreground task {:?}, got {:?}",
|
|
||||||
self.task_id, task_state,
|
|
||||||
),
|
|
||||||
pc: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let process_kind = match ctx.os.lifecycle().process_kind_for_task(self.task_id) {
|
|
||||||
Ok(process_kind) => process_kind,
|
|
||||||
Err(error) => {
|
|
||||||
let report = CrashReport::VmPanic {
|
|
||||||
message: format!(
|
|
||||||
"ShellRunningStep cannot resolve process for {:?}: {:?}",
|
|
||||||
self.task_id, error,
|
|
||||||
),
|
|
||||||
pc: None,
|
|
||||||
};
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let outcome = match process_kind {
|
|
||||||
ProcessKind::VmShell => {
|
|
||||||
ctx.hub.update_vm_shell_profile(ctx.os, self.task_id, ctx.signals, ctx.platform)
|
|
||||||
}
|
|
||||||
ProcessKind::NativeShell => ctx.hub.update_native_shell_profile(ctx.os, ctx.platform),
|
|
||||||
ProcessKind::VmGame => {
|
|
||||||
let report = CrashReport::VmPanic {
|
|
||||||
message: format!(
|
|
||||||
"ShellRunningStep expected shell process for {:?}, got VmGame",
|
|
||||||
self.task_id,
|
|
||||||
),
|
|
||||||
pc: None,
|
|
||||||
};
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(report) = outcome.crash {
|
|
||||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
|
||||||
}
|
|
||||||
|
|
||||||
if outcome.action == Some(SystemProfileAction::CloseShell) {
|
|
||||||
self.close_current_shell(ctx);
|
|
||||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
|
||||||
}
|
|
||||||
|
|
||||||
if !ctx.os.windows().focused_window_belongs_to_task(self.task_id) {
|
|
||||||
ctx.os.info(
|
|
||||||
LogSource::Hub,
|
|
||||||
format!(
|
|
||||||
"Closing shell task {:?}: focused window does not belong to task",
|
|
||||||
self.task_id,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
self.close_current_shell(ctx);
|
|
||||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn close_current_shell(&mut self, ctx: &mut PrometeuContext) {
|
|
||||||
if let Err(error) = ctx.os.lifecycle().close_task(self.task_id) {
|
|
||||||
ctx.os.error(
|
|
||||||
LogSource::Hub,
|
|
||||||
format!("Failed to close shell task {:?}: {:?}", self.task_id, error),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn on_exit(&mut self, ctx: &mut PrometeuContext) {
|
|
||||||
ctx.os.info(LogSource::Hub, "Exiting ShellRunning".to_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,8 +2,6 @@ use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
|
|||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
use prometeu_hal::primitives::Rect;
|
|
||||||
use prometeu_hal::{FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct SplashScreenStep {
|
pub struct SplashScreenStep {
|
||||||
@@ -14,7 +12,7 @@ impl SplashScreenStep {
|
|||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
|
||||||
// Play sound on enter
|
// Play sound on enter
|
||||||
// ctx.platform.audio_mut().play(0, 0, 0, 255, 127, 1.0, 0, LoopMode::Off);
|
// ctx.hw.audio_mut().play(0, 0, 0, 255, 127, 1.0, 0, LoopMode::Off);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
@@ -22,10 +20,13 @@ impl SplashScreenStep {
|
|||||||
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
|
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
|
||||||
|
|
||||||
// Update peripherals for input
|
// Update peripherals for input
|
||||||
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
|
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
||||||
|
|
||||||
|
// Clear screen
|
||||||
|
ctx.hw.gfx_mut().clear(Color::BLACK);
|
||||||
|
|
||||||
// Draw expanding square
|
// Draw expanding square
|
||||||
let (sw, sh) = ctx.platform.display_size();
|
let (sw, sh) = ctx.hw.gfx().size();
|
||||||
let max_size = (sw.min(sh) as i32 / 2).max(1);
|
let max_size = (sw.min(sh) as i32 / 2).max(1);
|
||||||
|
|
||||||
let current_size = if self.frame < ANIMATION_DURATION {
|
let current_size = if self.frame < ANIMATION_DURATION {
|
||||||
@@ -37,21 +38,12 @@ impl SplashScreenStep {
|
|||||||
let x = (sw as i32 - current_size) / 2;
|
let x = (sw as i32 - current_size) / 2;
|
||||||
let y = (sh as i32 - current_size) / 2;
|
let y = (sh as i32 - current_size) / 2;
|
||||||
|
|
||||||
let packet = ShellUiFramePacket::new(vec![
|
ctx.hw.gfx_mut().fill_rect(x, y, current_size, current_size, Color::WHITE);
|
||||||
GfxUiCommand::Clear { color: Color::ORANGE },
|
ctx.hw.gfx_mut().present();
|
||||||
GfxUiCommand::FillRect {
|
|
||||||
rect: Rect { x, y, w: current_size, h: current_size },
|
|
||||||
color: Color::WHITE,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
ctx.platform
|
|
||||||
.render_submission_sink()
|
|
||||||
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
|
|
||||||
.expect("firmware splash render submission should publish");
|
|
||||||
|
|
||||||
// Transition logic
|
// Transition logic
|
||||||
// If any button is pressed at any time after the animation ends
|
// If any button is pressed at any time after the animation ends
|
||||||
if self.frame >= ANIMATION_DURATION && ctx.platform.input().pad().any() {
|
if self.frame >= ANIMATION_DURATION && ctx.hw.pad().any() {
|
||||||
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,8 @@ pub(crate) mod firmware_step_hub_home;
|
|||||||
pub(crate) mod firmware_step_launch_hub;
|
pub(crate) mod firmware_step_launch_hub;
|
||||||
pub(crate) mod firmware_step_load_cartridge;
|
pub(crate) mod firmware_step_load_cartridge;
|
||||||
pub(crate) mod firmware_step_reset;
|
pub(crate) mod firmware_step_reset;
|
||||||
pub(crate) mod firmware_step_shell_running;
|
|
||||||
pub(crate) mod firmware_step_splash_screen;
|
pub(crate) mod firmware_step_splash_screen;
|
||||||
mod prometeu_context;
|
mod prometeu_context;
|
||||||
pub(crate) mod resident_game_termination;
|
|
||||||
|
|
||||||
pub use boot_target::BootTarget;
|
pub use boot_target::BootTarget;
|
||||||
pub use firmware::Firmware;
|
pub use firmware::Firmware;
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
use crate::firmware::boot_target::BootTarget;
|
use crate::firmware::boot_target::BootTarget;
|
||||||
use prometeu_hal::{InputSignals, RuntimePlatform};
|
use prometeu_hal::{HardwareBridge, InputSignals};
|
||||||
use prometeu_system::{PrometeuHub, SystemOS};
|
use prometeu_system::{PrometeuHub, VirtualMachineRuntime};
|
||||||
|
use prometeu_vm::VirtualMachine;
|
||||||
|
|
||||||
pub struct PrometeuContext<'a> {
|
pub struct PrometeuContext<'a> {
|
||||||
pub os: &'a mut SystemOS,
|
pub vm: &'a mut VirtualMachine,
|
||||||
|
pub os: &'a mut VirtualMachineRuntime,
|
||||||
pub hub: &'a mut PrometeuHub,
|
pub hub: &'a mut PrometeuHub,
|
||||||
pub boot_target: &'a BootTarget,
|
pub boot_target: &'a BootTarget,
|
||||||
pub signals: &'a InputSignals,
|
pub signals: &'a InputSignals,
|
||||||
pub platform: &'a mut dyn RuntimePlatform,
|
pub hw: &'a mut dyn HardwareBridge,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
use prometeu_hal::RuntimePlatform;
|
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::log::LogSource;
|
|
||||||
use prometeu_system::task::TaskId;
|
|
||||||
use prometeu_system::{LifecycleError, SystemOS};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub(crate) enum ResidentGameTerminationOutcome {
|
|
||||||
NoResidentGame,
|
|
||||||
Terminated { task_id: TaskId, title: String },
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn terminate_resident_game(
|
|
||||||
os: &mut SystemOS,
|
|
||||||
platform: &mut dyn RuntimePlatform,
|
|
||||||
log_manual_hub_kill: bool,
|
|
||||||
) -> Result<ResidentGameTerminationOutcome, LifecycleError> {
|
|
||||||
let Some(task_id) = os.lifecycle().resident_game_task() else {
|
|
||||||
return Ok(ResidentGameTerminationOutcome::NoResidentGame);
|
|
||||||
};
|
|
||||||
|
|
||||||
let title = os
|
|
||||||
.sessions()
|
|
||||||
.vm_session_for_task(task_id)
|
|
||||||
.map(|session| session.title.clone())
|
|
||||||
.unwrap_or_else(|| "<unknown>".to_string());
|
|
||||||
|
|
||||||
let terminated = os.lifecycle().terminate_resident_game()?;
|
|
||||||
let Some(task_id) = terminated else {
|
|
||||||
return Ok(ResidentGameTerminationOutcome::NoResidentGame);
|
|
||||||
};
|
|
||||||
|
|
||||||
os.vm().transition_render_owner(AppMode::Shell, 0);
|
|
||||||
platform.game2d_frame_composer().unbind_scene();
|
|
||||||
platform.assets_mut().shutdown();
|
|
||||||
|
|
||||||
if log_manual_hub_kill {
|
|
||||||
os.info(LogSource::Hub, format!("Resident game killed from Hub: {title}"));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(ResidentGameTerminationOutcome::Terminated { task_id, title })
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
|
||||||
pub enum AppMode {
|
|
||||||
Game,
|
|
||||||
Shell,
|
|
||||||
}
|
|
||||||
@@ -6,19 +6,12 @@ pub type AssetId = i32;
|
|||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
||||||
#[allow(non_camel_case_types)]
|
#[allow(non_camel_case_types)]
|
||||||
pub enum BankType {
|
pub enum BankType {
|
||||||
GLYPH,
|
TILES,
|
||||||
SOUNDS,
|
SOUNDS,
|
||||||
SCENE,
|
|
||||||
// TILEMAPS,
|
// TILEMAPS,
|
||||||
// BLOBS,
|
// BLOBS,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
|
||||||
pub enum AssetCodec {
|
|
||||||
#[serde(rename = "NONE")]
|
|
||||||
None,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
pub struct AssetEntry {
|
pub struct AssetEntry {
|
||||||
pub asset_id: AssetId,
|
pub asset_id: AssetId,
|
||||||
@@ -27,75 +20,10 @@ pub struct AssetEntry {
|
|||||||
pub offset: u64,
|
pub offset: u64,
|
||||||
pub size: u64,
|
pub size: u64,
|
||||||
pub decoded_size: u64,
|
pub decoded_size: u64,
|
||||||
pub codec: AssetCodec,
|
pub codec: String, // e.g., "NONE" (legacy alias: "RAW")
|
||||||
pub metadata: serde_json::Value,
|
pub metadata: serde_json::Value,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
||||||
pub struct GlyphBankMetadata {
|
|
||||||
pub tile_size: u32,
|
|
||||||
pub width: u32,
|
|
||||||
pub height: u32,
|
|
||||||
pub palette_count: u32,
|
|
||||||
pub palette_authored: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
||||||
pub struct SoundBankMetadata {
|
|
||||||
pub sample_rate: u32,
|
|
||||||
pub channels: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
|
||||||
pub struct SceneBankMetadata {}
|
|
||||||
|
|
||||||
pub const SCENE_PAYLOAD_MAGIC_V1: [u8; 4] = *b"SCNE";
|
|
||||||
pub const SCENE_PAYLOAD_VERSION_V1: u16 = 1;
|
|
||||||
pub const SCENE_LAYER_COUNT_V1: usize = 4;
|
|
||||||
pub const SCENE_HEADER_BYTES_V1: usize = 12;
|
|
||||||
// Per-layer header:
|
|
||||||
// flags:u8 + glyph_asset_id:i32 + tile_size:u8 + reserved:u16
|
|
||||||
// + parallax_x:f32 + parallax_y:f32 + width:u32 + height:u32
|
|
||||||
// + tile_count:u32 + reserved:u32
|
|
||||||
pub const SCENE_LAYER_HEADER_BYTES_V1: usize = 32;
|
|
||||||
pub const SCENE_TILE_RECORD_BYTES_V1: usize = 4;
|
|
||||||
pub const SCENE_DECODED_LAYER_OVERHEAD_BYTES_V1: usize = 16;
|
|
||||||
|
|
||||||
impl AssetEntry {
|
|
||||||
pub fn metadata_as_glyph_bank(&self) -> Result<GlyphBankMetadata, String> {
|
|
||||||
if self.bank_type != BankType::GLYPH {
|
|
||||||
return Err(format!(
|
|
||||||
"Asset {} is not a GLYPH bank (type: {:?})",
|
|
||||||
self.asset_id, self.bank_type
|
|
||||||
));
|
|
||||||
}
|
|
||||||
serde_json::from_value(self.metadata.clone())
|
|
||||||
.map_err(|e| format!("Invalid GLYPH metadata for asset {}: {}", self.asset_id, e))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn metadata_as_sound_bank(&self) -> Result<SoundBankMetadata, String> {
|
|
||||||
if self.bank_type != BankType::SOUNDS {
|
|
||||||
return Err(format!(
|
|
||||||
"Asset {} is not a SOUNDS bank (type: {:?})",
|
|
||||||
self.asset_id, self.bank_type
|
|
||||||
));
|
|
||||||
}
|
|
||||||
serde_json::from_value(self.metadata.clone())
|
|
||||||
.map_err(|e| format!("Invalid SOUNDS metadata for asset {}: {}", self.asset_id, e))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn metadata_as_scene_bank(&self) -> Result<SceneBankMetadata, String> {
|
|
||||||
if self.bank_type != BankType::SCENE {
|
|
||||||
return Err(format!(
|
|
||||||
"Asset {} is not a SCENE bank (type: {:?})",
|
|
||||||
self.asset_id, self.bank_type
|
|
||||||
));
|
|
||||||
}
|
|
||||||
serde_json::from_value(self.metadata.clone())
|
|
||||||
.map_err(|e| format!("Invalid SCENE metadata for asset {}: {}", self.asset_id, e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
pub struct PreloadEntry {
|
pub struct PreloadEntry {
|
||||||
pub asset_id: AssetId,
|
pub asset_id: AssetId,
|
||||||
@@ -112,12 +40,6 @@ pub enum LoadStatus {
|
|||||||
CANCELED = 4,
|
CANCELED = 4,
|
||||||
ERROR = 5,
|
ERROR = 5,
|
||||||
UnknownHandle = 6,
|
UnknownHandle = 6,
|
||||||
QUEUED = 7,
|
|
||||||
ACTIVE = 8,
|
|
||||||
SUPERSEDED = 9,
|
|
||||||
EMPTY = 10,
|
|
||||||
INVALID = 11,
|
|
||||||
BackendUnavailable = 12,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -135,43 +57,16 @@ pub enum AssetOpStatus {
|
|||||||
Ok = 0,
|
Ok = 0,
|
||||||
UnknownHandle = 1,
|
UnknownHandle = 1,
|
||||||
InvalidState = 2,
|
InvalidState = 2,
|
||||||
Superseded = 3,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct AssetBacklogInfo {
|
|
||||||
pub status: AssetOpStatus,
|
|
||||||
pub pending_count: u32,
|
|
||||||
pub active_handle: HandleId,
|
|
||||||
pub active_asset_id: Option<AssetId>,
|
|
||||||
pub active_bank_type: Option<BankType>,
|
|
||||||
pub active_slot: Option<usize>,
|
|
||||||
pub active_progress: u16,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct AssetBacklogPosition {
|
|
||||||
pub status: AssetOpStatus,
|
|
||||||
pub state: LoadStatus,
|
|
||||||
pub position: u32,
|
|
||||||
pub progress: u16,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct AssetTargetStatus {
|
|
||||||
pub status: AssetOpStatus,
|
|
||||||
pub asset_id: Option<AssetId>,
|
|
||||||
pub handle: HandleId,
|
|
||||||
pub state: LoadStatus,
|
|
||||||
pub position: u32,
|
|
||||||
pub progress: u16,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct BankTelemetry {
|
pub struct BankStats {
|
||||||
pub bank_type: BankType,
|
pub total_bytes: usize,
|
||||||
pub used_slots: usize,
|
pub used_bytes: usize,
|
||||||
pub total_slots: usize,
|
pub free_bytes: usize,
|
||||||
|
pub inflight_bytes: usize,
|
||||||
|
pub slot_count: usize,
|
||||||
|
pub slots_occupied: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
@@ -190,14 +85,10 @@ pub struct SlotRef {
|
|||||||
|
|
||||||
impl SlotRef {
|
impl SlotRef {
|
||||||
pub fn gfx(index: usize) -> Self {
|
pub fn gfx(index: usize) -> Self {
|
||||||
Self { asset_type: BankType::GLYPH, index }
|
Self { asset_type: BankType::TILES, index }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn audio(index: usize) -> Self {
|
pub fn audio(index: usize) -> Self {
|
||||||
Self { asset_type: BankType::SOUNDS, index }
|
Self { asset_type: BankType::SOUNDS, index }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scene(index: usize) -> Self {
|
|
||||||
Self { asset_type: BankType::SCENE, index }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use crate::asset::{
|
use crate::asset::{
|
||||||
AssetBacklogInfo, AssetBacklogPosition, AssetEntry, AssetId, AssetLoadError, AssetOpStatus,
|
AssetEntry, AssetId, AssetLoadError, AssetOpStatus, BankStats, BankType, HandleId, LoadStatus,
|
||||||
AssetTargetStatus, BankTelemetry, BankType, HandleId, LoadStatus, PreloadEntry, SlotRef,
|
PreloadEntry, SlotRef, SlotStats,
|
||||||
SlotStats,
|
|
||||||
};
|
};
|
||||||
use crate::cartridge::AssetsPayloadSource;
|
use crate::cartridge::AssetsPayloadSource;
|
||||||
|
|
||||||
@@ -16,14 +15,8 @@ pub trait AssetBridge {
|
|||||||
fn status(&self, handle: HandleId) -> LoadStatus;
|
fn status(&self, handle: HandleId) -> LoadStatus;
|
||||||
fn commit(&self, handle: HandleId) -> AssetOpStatus;
|
fn commit(&self, handle: HandleId) -> AssetOpStatus;
|
||||||
fn cancel(&self, handle: HandleId) -> AssetOpStatus;
|
fn cancel(&self, handle: HandleId) -> AssetOpStatus;
|
||||||
fn backlog_info(&self) -> AssetBacklogInfo;
|
|
||||||
fn backlog_position(&self, handle: HandleId) -> AssetBacklogPosition;
|
|
||||||
fn backlog_move(&self, handle: HandleId, new_position: usize) -> AssetOpStatus;
|
|
||||||
fn backlog_promote(&self, handle: HandleId) -> AssetOpStatus;
|
|
||||||
fn backlog_demote(&self, handle: HandleId) -> AssetOpStatus;
|
|
||||||
fn target_status(&self, bank_type: BankType, slot: usize) -> AssetTargetStatus;
|
|
||||||
fn apply_commits(&self);
|
fn apply_commits(&self);
|
||||||
fn bank_telemetry(&self) -> Vec<BankTelemetry>;
|
fn bank_info(&self, kind: BankType) -> BankStats;
|
||||||
fn slot_info(&self, slot: SlotRef) -> SlotStats;
|
fn slot_info(&self, slot: SlotRef) -> SlotStats;
|
||||||
fn shutdown(&self);
|
fn shutdown(&self);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
use crate::app_mode::AppMode;
|
|
||||||
use crate::asset::{AssetEntry, PreloadEntry};
|
use crate::asset::{AssetEntry, PreloadEntry};
|
||||||
use crate::syscalls::CapFlags;
|
use crate::syscalls::CapFlags;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -11,6 +10,12 @@ pub const ASSETS_PA_MAGIC: [u8; 4] = *b"ASPA";
|
|||||||
pub const ASSETS_PA_SCHEMA_VERSION: u32 = 1;
|
pub const ASSETS_PA_SCHEMA_VERSION: u32 = 1;
|
||||||
pub const ASSETS_PA_PRELUDE_SIZE: usize = 32;
|
pub const ASSETS_PA_PRELUDE_SIZE: usize = 32;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub enum AppMode {
|
||||||
|
Game,
|
||||||
|
System,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Cartridge {
|
pub struct Cartridge {
|
||||||
pub app_id: u32,
|
pub app_id: u32,
|
||||||
@@ -286,9 +291,6 @@ pub enum Capability {
|
|||||||
None,
|
None,
|
||||||
System,
|
System,
|
||||||
Gfx,
|
Gfx,
|
||||||
Composer,
|
|
||||||
Gfx2d,
|
|
||||||
Gfxui,
|
|
||||||
Audio,
|
Audio,
|
||||||
Fs,
|
Fs,
|
||||||
Log,
|
Log,
|
||||||
@@ -297,7 +299,7 @@ pub enum Capability {
|
|||||||
All,
|
All,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct CartridgeManifest {
|
pub struct CartridgeManifest {
|
||||||
pub magic: String,
|
pub magic: String,
|
||||||
pub cartridge_version: u32,
|
pub cartridge_version: u32,
|
||||||
|
|||||||
@@ -117,9 +117,6 @@ fn normalize_capabilities(capabilities: &[Capability]) -> Result<CapFlags, Cartr
|
|||||||
Capability::None => caps::NONE,
|
Capability::None => caps::NONE,
|
||||||
Capability::System => caps::SYSTEM,
|
Capability::System => caps::SYSTEM,
|
||||||
Capability::Gfx => caps::GFX,
|
Capability::Gfx => caps::GFX,
|
||||||
Capability::Composer => caps::COMPOSER,
|
|
||||||
Capability::Gfx2d => caps::GFX2D,
|
|
||||||
Capability::Gfxui => caps::GFXUI,
|
|
||||||
Capability::Audio => caps::AUDIO,
|
Capability::Audio => caps::AUDIO,
|
||||||
Capability::Fs => caps::FS,
|
Capability::Fs => caps::FS,
|
||||||
Capability::Log => caps::LOG,
|
Capability::Log => caps::LOG,
|
||||||
@@ -201,9 +198,9 @@ fn validate_preload(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
|
use crate::asset::{AssetEntry, BankType, PreloadEntry};
|
||||||
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
||||||
use crate::glyph_bank::GLYPH_BANK_MAX_PALETTE_COUNT_V1;
|
use crate::tile_bank::TILE_BANK_PALETTE_COUNT_V1;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
@@ -366,17 +363,16 @@ mod tests {
|
|||||||
AssetEntry {
|
AssetEntry {
|
||||||
asset_id: 7,
|
asset_id: 7,
|
||||||
asset_name: "tiles".to_string(),
|
asset_name: "tiles".to_string(),
|
||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::TILES,
|
||||||
offset,
|
offset,
|
||||||
size,
|
size,
|
||||||
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
decoded_size: 16 * 16 + (TILE_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
|
||||||
codec: AssetCodec::None,
|
codec: "NONE".to_string(),
|
||||||
metadata: json!({
|
metadata: json!({
|
||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
"palette_count": TILE_BANK_PALETTE_COUNT_V1
|
||||||
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -449,17 +445,16 @@ mod tests {
|
|||||||
AssetEntry {
|
AssetEntry {
|
||||||
asset_id: 8,
|
asset_id: 8,
|
||||||
asset_name: "other_tiles".to_string(),
|
asset_name: "other_tiles".to_string(),
|
||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::TILES,
|
||||||
offset: 4,
|
offset: 4,
|
||||||
size: 4,
|
size: 4,
|
||||||
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
decoded_size: 16 * 16 + (TILE_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
|
||||||
codec: AssetCodec::None,
|
codec: "NONE".to_string(),
|
||||||
metadata: json!({
|
metadata: json!({
|
||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
"palette_count": TILE_BANK_PALETTE_COUNT_V1
|
||||||
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -502,88 +497,4 @@ mod tests {
|
|||||||
|
|
||||||
assert!(matches!(error, CartridgeError::InvalidFormat));
|
assert!(matches!(error, CartridgeError::InvalidFormat));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn load_rejects_unknown_codec_string_in_assets_pa_header() {
|
|
||||||
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
|
||||||
let header = serde_json::json!({
|
|
||||||
"asset_table": [{
|
|
||||||
"asset_id": 7,
|
|
||||||
"asset_name": "tiles",
|
|
||||||
"bank_type": "GLYPH",
|
|
||||||
"offset": 0,
|
|
||||||
"size": 4,
|
|
||||||
"decoded_size": 768,
|
|
||||||
"codec": "LZ4",
|
|
||||||
"metadata": {
|
|
||||||
"tile_size": 16,
|
|
||||||
"width": 16,
|
|
||||||
"height": 16,
|
|
||||||
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
|
||||||
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
|
||||||
}
|
|
||||||
}],
|
|
||||||
"preload": []
|
|
||||||
});
|
|
||||||
let header_bytes = serde_json::to_vec(&header).expect("header must serialize");
|
|
||||||
let prelude = AssetsPackPrelude {
|
|
||||||
magic: ASSETS_PA_MAGIC,
|
|
||||||
schema_version: ASSETS_PA_SCHEMA_VERSION,
|
|
||||||
header_len: header_bytes.len() as u32,
|
|
||||||
payload_offset: (ASSETS_PA_PRELUDE_SIZE + header_bytes.len()) as u64,
|
|
||||||
flags: 0,
|
|
||||||
reserved: 0,
|
|
||||||
header_checksum: 0,
|
|
||||||
};
|
|
||||||
let mut bytes = prelude.to_bytes().to_vec();
|
|
||||||
bytes.extend_from_slice(&header_bytes);
|
|
||||||
bytes.extend_from_slice(&[1_u8, 2, 3, 4]);
|
|
||||||
fs::write(dir.path().join("assets.pa"), bytes).expect("must write assets.pa");
|
|
||||||
|
|
||||||
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
|
||||||
|
|
||||||
assert!(matches!(error, CartridgeError::InvalidFormat));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn load_rejects_legacy_raw_codec_string_in_assets_pa_header() {
|
|
||||||
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
|
||||||
let header = serde_json::json!({
|
|
||||||
"asset_table": [{
|
|
||||||
"asset_id": 7,
|
|
||||||
"asset_name": "tiles",
|
|
||||||
"bank_type": "GLYPH",
|
|
||||||
"offset": 0,
|
|
||||||
"size": 4,
|
|
||||||
"decoded_size": 768,
|
|
||||||
"codec": "RAW",
|
|
||||||
"metadata": {
|
|
||||||
"tile_size": 16,
|
|
||||||
"width": 16,
|
|
||||||
"height": 16,
|
|
||||||
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
|
||||||
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
|
||||||
}
|
|
||||||
}],
|
|
||||||
"preload": []
|
|
||||||
});
|
|
||||||
let header_bytes = serde_json::to_vec(&header).expect("header must serialize");
|
|
||||||
let prelude = AssetsPackPrelude {
|
|
||||||
magic: ASSETS_PA_MAGIC,
|
|
||||||
schema_version: ASSETS_PA_SCHEMA_VERSION,
|
|
||||||
header_len: header_bytes.len() as u32,
|
|
||||||
payload_offset: (ASSETS_PA_PRELUDE_SIZE + header_bytes.len()) as u64,
|
|
||||||
flags: 0,
|
|
||||||
reserved: 0,
|
|
||||||
header_checksum: 0,
|
|
||||||
};
|
|
||||||
let mut bytes = prelude.to_bytes().to_vec();
|
|
||||||
bytes.extend_from_slice(&header_bytes);
|
|
||||||
bytes.extend_from_slice(&[1_u8, 2, 3, 4]);
|
|
||||||
fs::write(dir.path().join("assets.pa"), bytes).expect("must write assets.pa");
|
|
||||||
|
|
||||||
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
|
||||||
|
|
||||||
assert!(matches!(error, CartridgeError::InvalidFormat));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,67 +1,75 @@
|
|||||||
/// Represents a canonical RGBA8888 color in RGBA channel order.
|
/// Represents a 16-bit color in the RGB565 format.
|
||||||
|
///
|
||||||
|
/// The RGB565 format is a common high-color representation for embedded systems:
|
||||||
|
/// - **Red**: 5 bits (0..31)
|
||||||
|
/// - **Green**: 6 bits (0..63)
|
||||||
|
/// - **Blue**: 5 bits (0..31)
|
||||||
|
///
|
||||||
|
/// Prometeu does not have a hardware alpha channel. Transparency is achieved
|
||||||
|
/// by using a specific color key (Magenta / 0xF81F) which the GFX engine
|
||||||
|
/// skips during rendering.
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
pub struct Color(pub u32);
|
pub struct Color(pub u16);
|
||||||
|
|
||||||
impl Color {
|
impl Color {
|
||||||
pub const BLACK: Self = Self::rgb(0, 0, 0);
|
pub const BLACK: Self = Self::rgb(0, 0, 0); // 0x0000
|
||||||
pub const WHITE: Self = Self::rgb(255, 255, 255);
|
pub const WHITE: Self = Self::rgb(255, 255, 255); // 0xFFFF
|
||||||
pub const RED: Self = Self::rgb(255, 0, 0);
|
pub const RED: Self = Self::rgb(255, 0, 0); // 0xF800
|
||||||
pub const GREEN: Self = Self::rgb(0, 255, 0);
|
pub const GREEN: Self = Self::rgb(0, 255, 0); // 0x07E0
|
||||||
pub const BLUE: Self = Self::rgb(0, 0, 255);
|
pub const BLUE: Self = Self::rgb(0, 0, 255); // 0x001F
|
||||||
pub const YELLOW: Self = Self::rgb(255, 255, 0);
|
pub const YELLOW: Self = Self::rgb(255, 255, 0); // 0xFFE0
|
||||||
pub const ORANGE: Self = Self::rgb(255, 128, 0);
|
pub const ORANGE: Self = Self::rgb(255, 128, 0);
|
||||||
pub const INDIGO: Self = Self::rgb(75, 0, 130);
|
pub const INDIGO: Self = Self::rgb(75, 0, 130);
|
||||||
pub const GRAY: Self = Self::rgb(128, 128, 128);
|
pub const GRAY: Self = Self::rgb(128, 128, 128);
|
||||||
pub const CYAN: Self = Self::rgb(0, 255, 255);
|
pub const CYAN: Self = Self::rgb(0, 255, 255); // 0x07FF
|
||||||
pub const MAGENTA: Self = Self::rgb(255, 0, 255);
|
pub const MAGENTA: Self = Self::rgb(255, 0, 255); // 0xF81F
|
||||||
pub const TRANSPARENT: Self = Self::rgba(0, 0, 0, 0);
|
pub const COLOR_KEY: Self = Self::MAGENTA;
|
||||||
#[deprecated(note = "Use RGBA alpha transparency; COLOR_KEY is temporary migration residue.")]
|
pub const TRANSPARENT: Self = Self::MAGENTA;
|
||||||
pub const COLOR_KEY: Self = Self::TRANSPARENT;
|
|
||||||
|
|
||||||
/// Extracts RGBA8888 channels from canonical RGBA raw order.
|
/// Extracts channels in the native RGB565 range:
|
||||||
|
/// R: 0..31, G: 0..63, B: 0..31
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn unpack_to_native(px: u32) -> (u8, u8, u8, u8) {
|
pub const fn unpack_to_native(px: u16) -> (u8, u8, u8) {
|
||||||
let r = ((px >> 24) & 0xFF) as u8;
|
let r = ((px >> 11) & 0x1F) as u8;
|
||||||
let g = ((px >> 16) & 0xFF) as u8;
|
let g = ((px >> 5) & 0x3F) as u8;
|
||||||
let b = ((px >> 8) & 0xFF) as u8;
|
let b = (px & 0x1F) as u8;
|
||||||
let a = (px & 0xFF) as u8;
|
(r, g, b)
|
||||||
(r, g, b, a)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Packs RGBA8888 channels into canonical RGBA raw order.
|
/// Packs channels from the native RGB565 range into a pixel:
|
||||||
|
/// R: 0..31, G: 0..63, B: 0..31
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn pack_from_native(r: u8, g: u8, b: u8, a: u8) -> u32 {
|
pub const fn pack_from_native(r: u8, g: u8, b: u8) -> u16 {
|
||||||
((r as u32) << 24) | ((g as u32) << 16) | ((b as u32) << 8) | a as u32
|
((r as u16 & 0x1F) << 11) | ((g as u16 & 0x3F) << 5) | (b as u16 & 0x1F)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates an opaque RGBA8888 color from 8-bit RGB components.
|
/// Creates an RGB565 color from 8-bit components (0..255).
|
||||||
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
||||||
Self::rgba(r, g, b, 255)
|
let r5 = (r as u16 >> 3) & 0x1F;
|
||||||
}
|
let g6 = (g as u16 >> 2) & 0x3F;
|
||||||
|
let b5 = (b as u16 >> 3) & 0x1F;
|
||||||
|
|
||||||
pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
|
Self((r5 << 11) | (g6 << 5) | b5)
|
||||||
Self(Self::pack_from_native(r, g, b, a))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn gray_scale(c: u8) -> Self {
|
pub const fn gray_scale(c: u8) -> Self {
|
||||||
Self::rgb(c, c, c)
|
Self::rgb(c, c, c)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn from_raw(raw: u32) -> Self {
|
pub const fn from_raw(raw: u16) -> Self {
|
||||||
Self(raw)
|
Self(raw)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn raw(self) -> u32 {
|
pub const fn raw(self) -> u16 {
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn hex(self) -> i32 {
|
pub const fn hex(self) -> i32 {
|
||||||
let (r, g, b, _) = Self::unpack_to_native(self.0);
|
let (r5, g6, b5) = Self::unpack_to_native(self.0);
|
||||||
let hex = (r as u32) << 16 | (g as u32) << 8 | b as u32;
|
let r8 = ((r5 as u32) << 3) | ((r5 as u32) >> 2);
|
||||||
|
let g8 = ((g6 as u32) << 2) | ((g6 as u32) >> 4);
|
||||||
|
let b8 = ((b5 as u32) << 3) | ((b5 as u32) >> 2);
|
||||||
|
let hex = r8 << 16 | g8 << 8 | b8;
|
||||||
hex as i32
|
hex as i32
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn alpha(self) -> u8 {
|
|
||||||
(self.0 & 0xFF) as u8
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
#[repr(i32)]
|
|
||||||
pub enum ComposerOpStatus {
|
|
||||||
Ok = 0,
|
|
||||||
SceneUnavailable = 1,
|
|
||||||
ArgRangeInvalid = 2,
|
|
||||||
BankInvalid = 3,
|
|
||||||
LayerInvalid = 4,
|
|
||||||
SpriteOverflow = 5,
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::app_mode::AppMode;
|
use crate::cartridge::AppMode;
|
||||||
use prometeu_bytecode::Value;
|
use prometeu_bytecode::Value;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ pub enum DebugResponse {
|
|||||||
Breakpoints { pcs: Vec<usize> },
|
Breakpoints { pcs: Vec<usize> },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
pub struct HandshakeCartridge {
|
pub struct HandshakeCartridge {
|
||||||
pub app_id: u32,
|
pub app_id: u32,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
@@ -64,12 +64,12 @@ pub enum DebugEvent {
|
|||||||
cycles_budget: u64,
|
cycles_budget: u64,
|
||||||
host_cpu_time_us: u64,
|
host_cpu_time_us: u64,
|
||||||
violations: u32,
|
violations: u32,
|
||||||
glyph_slots_used: u32,
|
gfx_used_bytes: usize,
|
||||||
glyph_slots_total: u32,
|
gfx_inflight_bytes: usize,
|
||||||
sound_slots_used: u32,
|
gfx_slots_occupied: u32,
|
||||||
sound_slots_total: u32,
|
audio_used_bytes: usize,
|
||||||
scene_slots_used: u32,
|
audio_inflight_bytes: usize,
|
||||||
scene_slots_total: u32,
|
audio_slots_occupied: u32,
|
||||||
},
|
},
|
||||||
#[serde(rename = "fault")]
|
#[serde(rename = "fault")]
|
||||||
Fault {
|
Fault {
|
||||||
@@ -97,12 +97,12 @@ mod tests {
|
|||||||
cycles_budget: 10000,
|
cycles_budget: 10000,
|
||||||
host_cpu_time_us: 1200,
|
host_cpu_time_us: 1200,
|
||||||
violations: 0,
|
violations: 0,
|
||||||
glyph_slots_used: 1,
|
gfx_used_bytes: 1024,
|
||||||
glyph_slots_total: 16,
|
gfx_inflight_bytes: 0,
|
||||||
sound_slots_used: 2,
|
gfx_slots_occupied: 1,
|
||||||
sound_slots_total: 16,
|
audio_used_bytes: 2048,
|
||||||
scene_slots_used: 3,
|
audio_inflight_bytes: 0,
|
||||||
scene_slots_total: 16,
|
audio_slots_occupied: 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
let json = serde_json::to_string(&event).unwrap();
|
let json = serde_json::to_string(&event).unwrap();
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use crate::color::Color;
|
use crate::color::Color;
|
||||||
use crate::scene_viewport_cache::SceneViewportCache;
|
|
||||||
use crate::scene_viewport_resolver::ResolverUpdate;
|
|
||||||
use crate::sprite::Sprite;
|
use crate::sprite::Sprite;
|
||||||
|
use crate::tile_layer::{HudTileLayer, ScrollableTileLayer};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum BlendMode {
|
pub enum BlendMode {
|
||||||
@@ -24,7 +23,7 @@ pub enum GfxOpStatus {
|
|||||||
|
|
||||||
pub trait GfxBridge {
|
pub trait GfxBridge {
|
||||||
fn size(&self) -> (usize, usize);
|
fn size(&self) -> (usize, usize);
|
||||||
fn front_buffer(&self) -> &[u32];
|
fn front_buffer(&self) -> &[u16];
|
||||||
fn clear(&mut self, color: Color);
|
fn clear(&mut self, color: Color);
|
||||||
fn fill_rect_blend(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode);
|
fn fill_rect_blend(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode);
|
||||||
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
|
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
|
||||||
@@ -48,29 +47,25 @@ pub trait GfxBridge {
|
|||||||
fn draw_horizontal_line(&mut self, x0: i32, x1: i32, y: i32, color: Color);
|
fn draw_horizontal_line(&mut self, x0: i32, x1: i32, y: i32, color: Color);
|
||||||
fn draw_vertical_line(&mut self, x: i32, y0: i32, y1: i32, color: Color);
|
fn draw_vertical_line(&mut self, x: i32, y0: i32, y1: i32, color: Color);
|
||||||
fn present(&mut self);
|
fn present(&mut self);
|
||||||
/// Render the canonical game frame with no bound scene.
|
fn render_all(&mut self);
|
||||||
///
|
fn render_layer(&mut self, layer_idx: usize);
|
||||||
/// Deferred `gfx.*` overlay/debug primitives are intentionally outside this
|
fn render_hud(&mut self);
|
||||||
/// contract and are drained by a separate final overlay stage.
|
|
||||||
fn render_no_scene_frame(&mut self);
|
|
||||||
/// Render the canonical scene-backed game frame from cache/resolver state.
|
|
||||||
///
|
|
||||||
/// Deferred `gfx.*` overlay/debug primitives are intentionally outside this
|
|
||||||
/// contract and are drained by a separate final overlay stage.
|
|
||||||
fn render_scene_from_cache(
|
|
||||||
&mut self,
|
|
||||||
cache: &SceneViewportCache,
|
|
||||||
update: &ResolverUpdate,
|
|
||||||
resolved_glyph_slots: &[usize; 4],
|
|
||||||
);
|
|
||||||
fn load_frame_sprites(&mut self, sprites: &[Sprite]);
|
|
||||||
/// Submit text into the `gfx.*` primitive path.
|
|
||||||
///
|
|
||||||
/// Under the accepted runtime contract this is not the canonical game
|
|
||||||
/// composition path; it belongs to the deferred final overlay/debug family.
|
|
||||||
fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Color);
|
fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Color);
|
||||||
fn draw_char(&mut self, x: i32, y: i32, c: char, color: Color);
|
fn draw_char(&mut self, x: i32, y: i32, c: char, color: Color);
|
||||||
|
|
||||||
|
fn layer(&self, index: usize) -> &ScrollableTileLayer;
|
||||||
|
fn layer_mut(&mut self, index: usize) -> &mut ScrollableTileLayer;
|
||||||
|
fn hud(&self) -> &HudTileLayer;
|
||||||
|
fn hud_mut(&mut self) -> &mut HudTileLayer;
|
||||||
fn sprite(&self, index: usize) -> &Sprite;
|
fn sprite(&self, index: usize) -> &Sprite;
|
||||||
fn sprite_mut(&mut self, index: usize) -> &mut Sprite;
|
fn sprite_mut(&mut self, index: usize) -> &mut Sprite;
|
||||||
|
|
||||||
|
fn scene_fade_level(&self) -> u8;
|
||||||
|
fn set_scene_fade_level(&mut self, level: u8);
|
||||||
|
fn scene_fade_color(&self) -> Color;
|
||||||
|
fn set_scene_fade_color(&mut self, color: Color);
|
||||||
|
fn hud_fade_level(&self) -> u8;
|
||||||
|
fn set_hud_fade_level(&mut self, level: u8);
|
||||||
|
fn hud_fade_color(&self) -> Color;
|
||||||
|
fn set_hud_fade_color(&mut self, color: Color);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
|
|
||||||
pub struct Glyph {
|
|
||||||
pub glyph_id: u16,
|
|
||||||
pub palette_id: u8,
|
|
||||||
}
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
use crate::color::Color;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
pub const GLYPH_BANK_MAX_PALETTE_COUNT_V1: usize = 64;
|
|
||||||
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
|
||||||
|
|
||||||
/// Standard sizes for square tiles.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
|
|
||||||
pub enum TileSize {
|
|
||||||
/// 8x8 pixels.
|
|
||||||
Size8 = 8,
|
|
||||||
/// 16x16 pixels.
|
|
||||||
Size16 = 16,
|
|
||||||
/// 32x32 pixels.
|
|
||||||
Size32 = 32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A container for graphical assets.
|
|
||||||
///
|
|
||||||
/// A GlyphBank stores the decoded runtime representation of a glyph-bank asset.
|
|
||||||
///
|
|
||||||
/// Serialized `assets.pa` payloads keep pixel indices packed as `4bpp` nibbles.
|
|
||||||
/// After decode, the runtime expands them to one `u8` palette index per pixel
|
|
||||||
/// while preserving the same `0..15` logical range.
|
|
||||||
pub struct GlyphBank {
|
|
||||||
/// Dimension of each individual tile in the bank.
|
|
||||||
pub tile_size: TileSize,
|
|
||||||
/// Width of the full bank sheet in pixels.
|
|
||||||
pub width: usize,
|
|
||||||
/// Height of the full bank sheet in pixels.
|
|
||||||
pub height: usize,
|
|
||||||
|
|
||||||
/// Decoded pixel data stored as one palette index per pixel.
|
|
||||||
/// Serialized payloads are packed; runtime memory is expanded.
|
|
||||||
/// Palette indices are ordinary indices; transparency is resolved through
|
|
||||||
/// the RGBA alpha channel of the palette entry.
|
|
||||||
pub pixel_indices: Vec<u8>,
|
|
||||||
/// Runtime-facing v1 palette table.
|
|
||||||
///
|
|
||||||
/// Palette identity is the direct index in this vector. A resident glyph
|
|
||||||
/// bank carries exactly the palettes materialized from its payload.
|
|
||||||
pub palettes: Vec<[Color; GLYPH_BANK_COLORS_PER_PALETTE]>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GlyphBank {
|
|
||||||
/// Creates an empty glyph bank with one palette.
|
|
||||||
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
|
|
||||||
Self::with_palette_count(tile_size, width, height, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates an empty glyph bank with the specified resident palette count.
|
|
||||||
pub fn with_palette_count(
|
|
||||||
tile_size: TileSize,
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
palette_count: usize,
|
|
||||||
) -> Self {
|
|
||||||
assert!(
|
|
||||||
(1..=GLYPH_BANK_MAX_PALETTE_COUNT_V1).contains(&palette_count),
|
|
||||||
"glyph bank palette_count must be in 1..={}",
|
|
||||||
GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
|
||||||
);
|
|
||||||
|
|
||||||
Self {
|
|
||||||
tile_size,
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
pixel_indices: vec![0; width * height],
|
|
||||||
palettes: vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the number of resident palettes.
|
|
||||||
pub fn palette_count(&self) -> usize {
|
|
||||||
self.palettes.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true when the palette id is valid for this resident bank.
|
|
||||||
pub fn contains_palette(&self, palette_id: u8) -> bool {
|
|
||||||
(palette_id as usize) < self.palette_count()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a mutable palette slot when the palette exists.
|
|
||||||
pub fn palette_mut(
|
|
||||||
&mut self,
|
|
||||||
palette_id: u8,
|
|
||||||
) -> Option<&mut [Color; GLYPH_BANK_COLORS_PER_PALETTE]> {
|
|
||||||
self.palettes.get_mut(palette_id as usize)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolves a global tile ID and local pixel coordinates to a palette index.
|
|
||||||
/// tile_id: the tile index in the bank
|
|
||||||
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
|
|
||||||
pub fn get_pixel_index(&self, tile_id: u16, local_x: usize, local_y: usize) -> u8 {
|
|
||||||
let size = self.tile_size as usize;
|
|
||||||
let tiles_per_row = self.width / size;
|
|
||||||
let tile_x = (tile_id as usize % tiles_per_row) * size;
|
|
||||||
let tile_y = (tile_id as usize / tiles_per_row) * size;
|
|
||||||
|
|
||||||
let pixel_x = tile_x + local_x;
|
|
||||||
let pixel_y = tile_y + local_y;
|
|
||||||
|
|
||||||
if pixel_x < self.width && pixel_y < self.height {
|
|
||||||
self.pixel_indices[pixel_y * self.width + pixel_x]
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Maps a 4-bit index to a real RGBA8888 Color using the specified palette.
|
|
||||||
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Option<Color> {
|
|
||||||
self.palettes
|
|
||||||
.get(palette_id as usize)
|
|
||||||
.and_then(|palette| palette.get(pixel_index as usize))
|
|
||||||
.copied()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn new_glyph_bank_uses_single_resident_palette() {
|
|
||||||
let bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
|
||||||
|
|
||||||
assert_eq!(bank.palette_count(), 1);
|
|
||||||
assert!(bank.contains_palette(0));
|
|
||||||
assert!(!bank.contains_palette(1));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn glyph_bank_can_materialize_v1_max_palette_count() {
|
|
||||||
let bank =
|
|
||||||
GlyphBank::with_palette_count(TileSize::Size8, 8, 8, GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
|
||||||
|
|
||||||
assert_eq!(bank.palette_count(), GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
|
||||||
assert!(bank.contains_palette((GLYPH_BANK_MAX_PALETTE_COUNT_V1 - 1) as u8));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_palette_lookup_is_distinct_from_transparent_color() {
|
|
||||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
|
||||||
bank.palette_mut(0).unwrap()[1] = Color::TRANSPARENT;
|
|
||||||
|
|
||||||
assert_eq!(bank.resolve_color(0, 1), Some(Color::TRANSPARENT));
|
|
||||||
assert_eq!(bank.resolve_color(1, 1), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[should_panic(expected = "glyph bank palette_count must be in 1..=64")]
|
|
||||||
fn glyph_bank_rejects_zero_resident_palettes() {
|
|
||||||
let _ = GlyphBank::with_palette_count(TileSize::Size8, 8, 8, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
use crate::asset_bridge::AssetBridge;
|
||||||
|
use crate::audio_bridge::AudioBridge;
|
||||||
|
use crate::gfx_bridge::GfxBridge;
|
||||||
|
use crate::pad_bridge::PadBridge;
|
||||||
|
use crate::touch_bridge::TouchBridge;
|
||||||
|
|
||||||
|
pub trait HardwareBridge {
|
||||||
|
fn gfx(&self) -> &dyn GfxBridge;
|
||||||
|
fn gfx_mut(&mut self) -> &mut dyn GfxBridge;
|
||||||
|
|
||||||
|
fn audio(&self) -> &dyn AudioBridge;
|
||||||
|
fn audio_mut(&mut self) -> &mut dyn AudioBridge;
|
||||||
|
|
||||||
|
fn pad(&self) -> &dyn PadBridge;
|
||||||
|
fn pad_mut(&mut self) -> &mut dyn PadBridge;
|
||||||
|
|
||||||
|
fn touch(&self) -> &dyn TouchBridge;
|
||||||
|
fn touch_mut(&mut self) -> &mut dyn TouchBridge;
|
||||||
|
|
||||||
|
fn assets(&self) -> &dyn AssetBridge;
|
||||||
|
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
|
||||||
|
}
|
||||||
@@ -1,23 +1,19 @@
|
|||||||
use crate::platform::RuntimePlatform;
|
use crate::hardware_bridge::HardwareBridge;
|
||||||
use crate::vm_fault::VmFault;
|
use crate::vm_fault::VmFault;
|
||||||
|
|
||||||
pub struct HostContext<'a> {
|
pub struct HostContext<'a> {
|
||||||
pub platform: Option<&'a mut dyn RuntimePlatform>,
|
pub hw: Option<&'a mut dyn HardwareBridge>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> HostContext<'a> {
|
impl<'a> HostContext<'a> {
|
||||||
pub fn new(platform: Option<&'a mut dyn RuntimePlatform>) -> Self {
|
pub fn new(hw: Option<&'a mut dyn HardwareBridge>) -> Self {
|
||||||
Self { platform }
|
Self { hw }
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_platform(platform: Option<&'a mut dyn RuntimePlatform>) -> Self {
|
|
||||||
Self::new(platform)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn require_platform(&mut self) -> Result<&mut dyn RuntimePlatform, VmFault> {
|
pub fn require_hw(&mut self) -> Result<&mut dyn HardwareBridge, VmFault> {
|
||||||
match &mut self.platform {
|
match &mut self.hw {
|
||||||
Some(platform) => Ok(*platform),
|
Some(hw) => Ok(*hw),
|
||||||
None => Err(VmFault::Unavailable),
|
None => Err(VmFault::Unavailable),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,6 @@ impl<'a> HostReturn<'a> {
|
|||||||
self.stack.push(Value::HeapRef(HeapRef(g as u32)));
|
self.stack.push(Value::HeapRef(HeapRef(g as u32)));
|
||||||
}
|
}
|
||||||
pub fn push_string(&mut self, s: String) {
|
pub fn push_string(&mut self, s: String) {
|
||||||
self.stack.push(Value::string(s));
|
self.stack.push(Value::String(s));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
pub mod app_mode;
|
|
||||||
pub mod asset;
|
pub mod asset;
|
||||||
pub mod asset_bridge;
|
pub mod asset_bridge;
|
||||||
pub mod audio_bridge;
|
pub mod audio_bridge;
|
||||||
@@ -6,61 +5,36 @@ pub mod button;
|
|||||||
pub mod cartridge;
|
pub mod cartridge;
|
||||||
pub mod cartridge_loader;
|
pub mod cartridge_loader;
|
||||||
pub mod color;
|
pub mod color;
|
||||||
pub mod composer_status;
|
|
||||||
pub mod debugger_protocol;
|
pub mod debugger_protocol;
|
||||||
pub mod gfx_bridge;
|
pub mod gfx_bridge;
|
||||||
pub mod glyph;
|
pub mod hardware_bridge;
|
||||||
pub mod glyph_bank;
|
|
||||||
pub mod host_context;
|
pub mod host_context;
|
||||||
pub mod host_return;
|
pub mod host_return;
|
||||||
pub mod input_signals;
|
pub mod input_signals;
|
||||||
pub mod log;
|
pub mod log;
|
||||||
pub mod native_helpers;
|
pub mod native_helpers;
|
||||||
pub mod native_interface;
|
pub mod native_interface;
|
||||||
pub mod owned_frame;
|
|
||||||
pub mod pad_bridge;
|
pub mod pad_bridge;
|
||||||
pub mod platform;
|
|
||||||
pub mod primitives;
|
|
||||||
pub mod render_resources;
|
|
||||||
pub mod render_submission;
|
|
||||||
pub mod render_worker;
|
|
||||||
pub mod sample;
|
pub mod sample;
|
||||||
pub mod scene_bank;
|
|
||||||
pub mod scene_layer;
|
|
||||||
pub mod scene_viewport_cache;
|
|
||||||
pub mod scene_viewport_resolver;
|
|
||||||
pub mod sound_bank;
|
pub mod sound_bank;
|
||||||
pub mod sprite;
|
pub mod sprite;
|
||||||
pub mod syscalls;
|
pub mod syscalls;
|
||||||
pub mod telemetry;
|
pub mod telemetry;
|
||||||
pub mod tile;
|
pub mod tile;
|
||||||
pub mod tilemap;
|
pub mod tile_bank;
|
||||||
|
pub mod tile_layer;
|
||||||
pub mod touch_bridge;
|
pub mod touch_bridge;
|
||||||
pub mod vm_fault;
|
pub mod vm_fault;
|
||||||
|
pub mod window;
|
||||||
|
|
||||||
pub use asset_bridge::AssetBridge;
|
pub use asset_bridge::AssetBridge;
|
||||||
pub use audio_bridge::{AudioBridge, AudioOpStatus, LoopMode};
|
pub use audio_bridge::{AudioBridge, AudioOpStatus, LoopMode};
|
||||||
pub use composer_status::ComposerOpStatus;
|
|
||||||
pub use gfx_bridge::{BlendMode, GfxBridge, GfxOpStatus};
|
pub use gfx_bridge::{BlendMode, GfxBridge, GfxOpStatus};
|
||||||
|
pub use hardware_bridge::HardwareBridge;
|
||||||
pub use host_context::{HostContext, HostContextProvider};
|
pub use host_context::{HostContext, HostContextProvider};
|
||||||
pub use host_return::HostReturn;
|
pub use host_return::HostReturn;
|
||||||
pub use input_signals::InputSignals;
|
pub use input_signals::InputSignals;
|
||||||
pub use native_helpers::{expect_bool, expect_int};
|
pub use native_helpers::{expect_bool, expect_int};
|
||||||
pub use native_interface::{NativeInterface, SyscallId};
|
pub use native_interface::{NativeInterface, SyscallId};
|
||||||
pub use owned_frame::{OwnedRgba8888Frame, OwnedRgba8888FrameError};
|
|
||||||
pub use pad_bridge::PadBridge;
|
pub use pad_bridge::PadBridge;
|
||||||
pub use platform::{
|
|
||||||
AssetStoragePlatform, AudioPlatform, ClockPacingPlatform, Game2DFrameComposer, InputPlatform,
|
|
||||||
NoopTelemetryPlatform, RenderBackend, RenderSubmissionSink, RenderSubmitError, RuntimePlatform,
|
|
||||||
TelemetryPlatform, TestPlatform,
|
|
||||||
};
|
|
||||||
pub use render_resources::RenderResourceAccess;
|
|
||||||
pub use render_submission::{
|
|
||||||
BoundScenePacket, Camera2D, ComposerFramePacket, FrameId, Game2DFramePacket, GameSpritePacket,
|
|
||||||
Gfx2dCommand, GfxUiCommand, HudCommand, HudPacket, RenderOwnership, RenderSubmission,
|
|
||||||
RenderSubmissionPacket, ShellUiFramePacket,
|
|
||||||
};
|
|
||||||
pub use render_worker::{
|
|
||||||
RenderWorkerBackend, RenderWorkerError, RenderWorkerFrameSink, RenderWorkerTelemetry,
|
|
||||||
};
|
|
||||||
pub use touch_bridge::TouchBridge;
|
pub use touch_bridge::TouchBridge;
|
||||||
|
|||||||
@@ -1,23 +1,15 @@
|
|||||||
use crate::log::{LogEvent, LogLevel, LogSource};
|
use crate::log::{LogEvent, LogLevel, LogSource};
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
use std::sync::Arc;
|
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
|
||||||
|
|
||||||
pub struct LogService {
|
pub struct LogService {
|
||||||
events: VecDeque<LogEvent>,
|
events: VecDeque<LogEvent>,
|
||||||
capacity: usize,
|
capacity: usize,
|
||||||
next_seq: u64,
|
next_seq: u64,
|
||||||
pub logs_count: Arc<AtomicU32>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LogService {
|
impl LogService {
|
||||||
pub fn new(capacity: usize) -> Self {
|
pub fn new(capacity: usize) -> Self {
|
||||||
Self {
|
Self { events: VecDeque::with_capacity(capacity), capacity, next_seq: 0 }
|
||||||
events: VecDeque::with_capacity(capacity),
|
|
||||||
capacity,
|
|
||||||
next_seq: 0,
|
|
||||||
logs_count: Arc::new(AtomicU32::new(0)),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn log(
|
pub fn log(
|
||||||
@@ -42,11 +34,6 @@ impl LogService {
|
|||||||
msg,
|
msg,
|
||||||
});
|
});
|
||||||
self.next_seq += 1;
|
self.next_seq += 1;
|
||||||
self.logs_count.fetch_add(1, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reset_count(&mut self) {
|
|
||||||
self.logs_count.store(0, Ordering::Relaxed);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_recent(&self, n: usize) -> Vec<LogEvent> {
|
pub fn get_recent(&self, n: usize) -> Vec<LogEvent> {
|
||||||
|
|||||||
@@ -1,127 +0,0 @@
|
|||||||
use crate::render_submission::{FrameId, RenderOwnership};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct OwnedRgba8888Frame {
|
|
||||||
pub frame_id: FrameId,
|
|
||||||
pub ownership: RenderOwnership,
|
|
||||||
pub width: usize,
|
|
||||||
pub height: usize,
|
|
||||||
pub stride_pixels: usize,
|
|
||||||
pub pixels: Vec<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum OwnedRgba8888FrameError {
|
|
||||||
EmptyDimensions,
|
|
||||||
StrideTooSmall,
|
|
||||||
PixelBufferTooSmall,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OwnedRgba8888Frame {
|
|
||||||
pub fn new(
|
|
||||||
frame_id: FrameId,
|
|
||||||
ownership: RenderOwnership,
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
stride_pixels: usize,
|
|
||||||
pixels: Vec<u32>,
|
|
||||||
) -> Result<Self, OwnedRgba8888FrameError> {
|
|
||||||
if width == 0 || height == 0 {
|
|
||||||
return Err(OwnedRgba8888FrameError::EmptyDimensions);
|
|
||||||
}
|
|
||||||
if stride_pixels < width {
|
|
||||||
return Err(OwnedRgba8888FrameError::StrideTooSmall);
|
|
||||||
}
|
|
||||||
let required_len = stride_pixels
|
|
||||||
.checked_mul(height)
|
|
||||||
.ok_or(OwnedRgba8888FrameError::PixelBufferTooSmall)?;
|
|
||||||
if pixels.len() < required_len {
|
|
||||||
return Err(OwnedRgba8888FrameError::PixelBufferTooSmall);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Self { frame_id, ownership, width, height, stride_pixels, pixels })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn packed(
|
|
||||||
frame_id: FrameId,
|
|
||||||
ownership: RenderOwnership,
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
pixels: Vec<u32>,
|
|
||||||
) -> Result<Self, OwnedRgba8888FrameError> {
|
|
||||||
Self::new(frame_id, ownership, width, height, width, pixels)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn required_pixel_len(&self) -> usize {
|
|
||||||
self.stride_pixels * self.height
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn row(&self, y: usize) -> Option<&[u32]> {
|
|
||||||
if y >= self.height {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let start = y * self.stride_pixels;
|
|
||||||
Some(&self.pixels[start..start + self.width])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::app_mode::AppMode;
|
|
||||||
|
|
||||||
fn ownership() -> RenderOwnership {
|
|
||||||
RenderOwnership::new(11, AppMode::Game, 42)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn owned_rgba8888_frame_preserves_metadata_and_pixels() {
|
|
||||||
let pixels = vec![0x11223344, 0x55667788, 0x99AABBCC, 0xDDEEFF00];
|
|
||||||
let frame = OwnedRgba8888Frame::packed(FrameId::new(7), ownership(), 2, 2, pixels.clone())
|
|
||||||
.expect("valid packed RGBA8888 frame");
|
|
||||||
|
|
||||||
assert_eq!(frame.frame_id, FrameId::new(7));
|
|
||||||
assert_eq!(frame.ownership, ownership());
|
|
||||||
assert_eq!(frame.width, 2);
|
|
||||||
assert_eq!(frame.height, 2);
|
|
||||||
assert_eq!(frame.stride_pixels, 2);
|
|
||||||
assert_eq!(frame.pixels, pixels);
|
|
||||||
assert_eq!(frame.required_pixel_len(), 4);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn checked_constructor_rejects_empty_dimensions() {
|
|
||||||
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 0, 1, 1, vec![0])
|
|
||||||
.expect_err("zero width should be rejected");
|
|
||||||
|
|
||||||
assert_eq!(err, OwnedRgba8888FrameError::EmptyDimensions);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn checked_constructor_rejects_stride_smaller_than_width() {
|
|
||||||
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 3, 1, 2, vec![0, 0, 0])
|
|
||||||
.expect_err("stride smaller than width should be rejected");
|
|
||||||
|
|
||||||
assert_eq!(err, OwnedRgba8888FrameError::StrideTooSmall);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn checked_constructor_rejects_short_pixel_buffer() {
|
|
||||||
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 2, 2, 3, vec![0; 5])
|
|
||||||
.expect_err("buffer shorter than stride * height should be rejected");
|
|
||||||
|
|
||||||
assert_eq!(err, OwnedRgba8888FrameError::PixelBufferTooSmall);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn row_returns_visible_width_without_stride_padding() {
|
|
||||||
let frame =
|
|
||||||
OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 2, 2, 3, vec![1, 2, 99, 3, 4, 88])
|
|
||||||
.expect("valid padded frame");
|
|
||||||
|
|
||||||
assert_eq!(frame.row(0), Some(&[1, 2][..]));
|
|
||||||
assert_eq!(frame.row(1), Some(&[3, 4][..]));
|
|
||||||
assert_eq!(frame.row(2), None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
use crate::asset_bridge::AssetBridge;
|
|
||||||
use crate::audio_bridge::AudioBridge;
|
|
||||||
use crate::composer_status::ComposerOpStatus;
|
|
||||||
use crate::pad_bridge::PadBridge;
|
|
||||||
use crate::render_submission::{Game2DFramePacket, RenderSubmission};
|
|
||||||
use crate::sprite::Sprite;
|
|
||||||
use crate::telemetry::TelemetryFrame;
|
|
||||||
use crate::touch_bridge::TouchBridge;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum RenderSubmitError {
|
|
||||||
BackendUnavailable,
|
|
||||||
SubmissionRejected,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait RenderSubmissionSink {
|
|
||||||
fn submit_render_submission(
|
|
||||||
&mut self,
|
|
||||||
submission: RenderSubmission,
|
|
||||||
) -> Result<(), RenderSubmitError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait RenderBackend {
|
|
||||||
fn render_frame(&mut self);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait Game2DFrameComposer {
|
|
||||||
fn begin_frame(&mut self);
|
|
||||||
fn bind_scene(&mut self, scene_bank_id: usize) -> ComposerOpStatus;
|
|
||||||
fn unbind_scene(&mut self);
|
|
||||||
fn set_camera(&mut self, x: i32, y: i32) -> ComposerOpStatus;
|
|
||||||
fn emit_sprite(&mut self, sprite: Sprite) -> ComposerOpStatus;
|
|
||||||
fn close_game2d_packet(&self) -> Game2DFramePacket;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait AudioPlatform: AudioBridge {}
|
|
||||||
impl<T: AudioBridge + ?Sized> AudioPlatform for T {}
|
|
||||||
|
|
||||||
pub trait InputPlatform {
|
|
||||||
fn pad(&self) -> &dyn PadBridge;
|
|
||||||
fn pad_mut(&mut self) -> &mut dyn PadBridge;
|
|
||||||
fn touch(&self) -> &dyn TouchBridge;
|
|
||||||
fn touch_mut(&mut self) -> &mut dyn TouchBridge;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait AssetStoragePlatform: AssetBridge {}
|
|
||||||
impl<T: AssetBridge + ?Sized> AssetStoragePlatform for T {}
|
|
||||||
|
|
||||||
pub trait ClockPacingPlatform {}
|
|
||||||
|
|
||||||
pub trait TelemetryPlatform {
|
|
||||||
fn telemetry_snapshot(&self) -> Option<TelemetryFrame> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct NoopTelemetryPlatform;
|
|
||||||
|
|
||||||
impl TelemetryPlatform for NoopTelemetryPlatform {}
|
|
||||||
|
|
||||||
pub trait RuntimePlatform {
|
|
||||||
fn display_size(&self) -> (usize, usize) {
|
|
||||||
(480, 270)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink;
|
|
||||||
fn render_backend(&mut self) -> &mut dyn RenderBackend;
|
|
||||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer;
|
|
||||||
fn audio(&self) -> &dyn AudioBridge;
|
|
||||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge;
|
|
||||||
fn input(&self) -> &dyn InputPlatform;
|
|
||||||
fn input_mut(&mut self) -> &mut dyn InputPlatform;
|
|
||||||
fn assets(&self) -> &dyn AssetBridge;
|
|
||||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
|
|
||||||
fn telemetry(&self) -> &dyn TelemetryPlatform;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait TestPlatform: RuntimePlatform {}
|
|
||||||
impl<T: RuntimePlatform + ?Sized> TestPlatform for T {}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn assert_render_sink_object(_: &mut dyn RenderSubmissionSink) {}
|
|
||||||
fn assert_backend_object(_: &mut dyn RenderBackend) {}
|
|
||||||
fn assert_composer_object(_: &mut dyn Game2DFrameComposer) {}
|
|
||||||
|
|
||||||
struct CompileOnly;
|
|
||||||
|
|
||||||
impl RenderSubmissionSink for CompileOnly {
|
|
||||||
fn submit_render_submission(
|
|
||||||
&mut self,
|
|
||||||
_submission: RenderSubmission,
|
|
||||||
) -> Result<(), RenderSubmitError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderBackend for CompileOnly {
|
|
||||||
fn render_frame(&mut self) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Game2DFrameComposer for CompileOnly {
|
|
||||||
fn begin_frame(&mut self) {}
|
|
||||||
|
|
||||||
fn bind_scene(&mut self, _scene_bank_id: usize) -> ComposerOpStatus {
|
|
||||||
ComposerOpStatus::Ok
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unbind_scene(&mut self) {}
|
|
||||||
|
|
||||||
fn set_camera(&mut self, _x: i32, _y: i32) -> ComposerOpStatus {
|
|
||||||
ComposerOpStatus::Ok
|
|
||||||
}
|
|
||||||
|
|
||||||
fn emit_sprite(&mut self, _sprite: Sprite) -> ComposerOpStatus {
|
|
||||||
ComposerOpStatus::Ok
|
|
||||||
}
|
|
||||||
|
|
||||||
fn close_game2d_packet(&self) -> Game2DFramePacket {
|
|
||||||
Game2DFramePacket::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn core_platform_facades_are_object_safe() {
|
|
||||||
let mut compile_only = CompileOnly;
|
|
||||||
|
|
||||||
assert_render_sink_object(&mut compile_only);
|
|
||||||
assert_backend_object(&mut compile_only);
|
|
||||||
assert_composer_object(&mut compile_only);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_submit_error_is_typed_and_debuggable() {
|
|
||||||
assert_eq!(format!("{:?}", RenderSubmitError::BackendUnavailable), "BackendUnavailable");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct Rect {
|
|
||||||
pub x: i32,
|
|
||||||
pub y: i32,
|
|
||||||
pub w: i32,
|
|
||||||
pub h: i32,
|
|
||||||
}
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
use crate::glyph_bank::GlyphBank;
|
|
||||||
use crate::scene_bank::SceneBank;
|
|
||||||
|
|
||||||
/// Read-only render resource lookup used by render backends.
|
|
||||||
///
|
|
||||||
/// Resource ids are stable bank slots carried by render submissions. The
|
|
||||||
/// callback shape keeps bank ownership inside the provider while exposing only
|
|
||||||
/// borrowed read access to the caller.
|
|
||||||
pub trait RenderResourceAccess {
|
|
||||||
/// Reads a resident glyph bank by id.
|
|
||||||
fn with_glyph_bank<R>(&self, bank_id: usize, read: impl FnOnce(&GlyphBank) -> R) -> Option<R>;
|
|
||||||
|
|
||||||
/// Returns the number of glyph bank ids accepted by this provider.
|
|
||||||
fn glyph_bank_count(&self) -> usize;
|
|
||||||
|
|
||||||
/// Reads a resident scene bank by id.
|
|
||||||
fn with_scene_bank<R>(&self, bank_id: usize, read: impl FnOnce(&SceneBank) -> R) -> Option<R>;
|
|
||||||
|
|
||||||
/// Returns the number of scene bank ids accepted by this provider.
|
|
||||||
fn scene_bank_count(&self) -> usize;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::glyph::Glyph;
|
|
||||||
use crate::glyph_bank::TileSize;
|
|
||||||
use crate::scene_layer::{ParallaxFactor, SceneLayer};
|
|
||||||
use crate::tile::Tile;
|
|
||||||
use crate::tilemap::TileMap;
|
|
||||||
|
|
||||||
struct TestRenderResources {
|
|
||||||
glyph_banks: Vec<Option<GlyphBank>>,
|
|
||||||
scene_banks: Vec<Option<SceneBank>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderResourceAccess for TestRenderResources {
|
|
||||||
fn with_glyph_bank<R>(
|
|
||||||
&self,
|
|
||||||
bank_id: usize,
|
|
||||||
read: impl FnOnce(&GlyphBank) -> R,
|
|
||||||
) -> Option<R> {
|
|
||||||
self.glyph_banks.get(bank_id)?.as_ref().map(read)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn glyph_bank_count(&self) -> usize {
|
|
||||||
self.glyph_banks.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn with_scene_bank<R>(
|
|
||||||
&self,
|
|
||||||
bank_id: usize,
|
|
||||||
read: impl FnOnce(&SceneBank) -> R,
|
|
||||||
) -> Option<R> {
|
|
||||||
self.scene_banks.get(bank_id)?.as_ref().map(read)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scene_bank_count(&self) -> usize {
|
|
||||||
self.scene_banks.len()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scene_bank(tile_size: TileSize) -> SceneBank {
|
|
||||||
let layer = SceneLayer {
|
|
||||||
active: true,
|
|
||||||
glyph_asset_id: 7,
|
|
||||||
tile_size,
|
|
||||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
|
||||||
tilemap: TileMap {
|
|
||||||
width: 1,
|
|
||||||
height: 1,
|
|
||||||
tiles: vec![Tile {
|
|
||||||
active: true,
|
|
||||||
glyph: Glyph { glyph_id: 3, palette_id: 0 },
|
|
||||||
flip_x: false,
|
|
||||||
flip_y: false,
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn reads_resident_resources_by_id() {
|
|
||||||
let resources = TestRenderResources {
|
|
||||||
glyph_banks: vec![None, Some(GlyphBank::new(TileSize::Size16, 16, 16)), None],
|
|
||||||
scene_banks: vec![Some(scene_bank(TileSize::Size8)), None],
|
|
||||||
};
|
|
||||||
|
|
||||||
assert_eq!(resources.glyph_bank_count(), 3);
|
|
||||||
assert_eq!(resources.scene_bank_count(), 2);
|
|
||||||
assert_eq!(resources.with_glyph_bank(1, |bank| bank.tile_size), Some(TileSize::Size16));
|
|
||||||
assert_eq!(
|
|
||||||
resources.with_scene_bank(0, |bank| bank.layers[0].tile_size),
|
|
||||||
Some(TileSize::Size8)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn missing_resources_return_none() {
|
|
||||||
let resources = TestRenderResources { glyph_banks: vec![None], scene_banks: vec![None] };
|
|
||||||
|
|
||||||
assert_eq!(resources.with_glyph_bank(0, |bank| bank.width), None);
|
|
||||||
assert_eq!(resources.with_glyph_bank(9, |bank| bank.width), None);
|
|
||||||
assert_eq!(resources.with_scene_bank(0, |bank| bank.layers[0].active), None);
|
|
||||||
assert_eq!(resources.with_scene_bank(9, |bank| bank.layers[0].active), None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,241 +0,0 @@
|
|||||||
use crate::app_mode::AppMode;
|
|
||||||
use crate::color::Color;
|
|
||||||
use crate::primitives::Rect;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
|
||||||
pub struct FrameId(pub u64);
|
|
||||||
|
|
||||||
impl FrameId {
|
|
||||||
pub const ZERO: Self = Self(0);
|
|
||||||
|
|
||||||
pub const fn new(value: u64) -> Self {
|
|
||||||
Self(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn get(self) -> u64 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn next(self) -> Self {
|
|
||||||
Self(self.0.wrapping_add(1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct RenderSubmission {
|
|
||||||
pub frame_id: FrameId,
|
|
||||||
pub app_mode: AppMode,
|
|
||||||
pub ownership: RenderOwnership,
|
|
||||||
pub packet: RenderSubmissionPacket,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderSubmission {
|
|
||||||
pub const fn game2d(frame_id: FrameId, packet: Game2DFramePacket) -> Self {
|
|
||||||
Self {
|
|
||||||
frame_id,
|
|
||||||
app_mode: AppMode::Game,
|
|
||||||
ownership: RenderOwnership::new(0, AppMode::Game, 0),
|
|
||||||
packet: RenderSubmissionPacket::Game2D(packet),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn shell_ui(frame_id: FrameId, packet: ShellUiFramePacket) -> Self {
|
|
||||||
Self {
|
|
||||||
frame_id,
|
|
||||||
app_mode: AppMode::Shell,
|
|
||||||
ownership: RenderOwnership::new(0, AppMode::Shell, 0),
|
|
||||||
packet: RenderSubmissionPacket::ShellUi(packet),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn with_ownership(mut self, ownership: RenderOwnership) -> Self {
|
|
||||||
self.ownership = ownership;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn is_coherent(&self) -> bool {
|
|
||||||
matches!(
|
|
||||||
(self.app_mode, &self.packet),
|
|
||||||
(AppMode::Game, RenderSubmissionPacket::Game2D(_))
|
|
||||||
| (AppMode::Shell, RenderSubmissionPacket::ShellUi(_))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct RenderOwnership {
|
|
||||||
pub epoch: u64,
|
|
||||||
pub app_mode: AppMode,
|
|
||||||
pub app_id: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderOwnership {
|
|
||||||
pub const fn new(epoch: u64, app_mode: AppMode, app_id: u32) -> Self {
|
|
||||||
Self { epoch, app_mode, app_id }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum RenderSubmissionPacket {
|
|
||||||
Game2D(Game2DFramePacket),
|
|
||||||
ShellUi(ShellUiFramePacket),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
||||||
pub struct Game2DFramePacket {
|
|
||||||
pub composer: ComposerFramePacket,
|
|
||||||
pub gfx2d: Vec<Gfx2dCommand>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Game2DFramePacket {
|
|
||||||
pub fn new(composer: ComposerFramePacket, gfx2d: Vec<Gfx2dCommand>) -> Self {
|
|
||||||
Self { composer, gfx2d }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct ShellUiFramePacket {
|
|
||||||
pub commands: Vec<GfxUiCommand>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ShellUiFramePacket {
|
|
||||||
pub fn new(commands: Vec<GfxUiCommand>) -> Self {
|
|
||||||
Self { commands }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
||||||
pub struct ComposerFramePacket {
|
|
||||||
pub bound_scene: Option<BoundScenePacket>,
|
|
||||||
pub camera: Camera2D,
|
|
||||||
pub sprites: Vec<GameSpritePacket>,
|
|
||||||
pub hud: HudPacket,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct BoundScenePacket {
|
|
||||||
pub bank_id: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
||||||
pub struct Camera2D {
|
|
||||||
pub x: i32,
|
|
||||||
pub y: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct GameSpritePacket {
|
|
||||||
pub glyph_id: i32,
|
|
||||||
pub palette_id: i32,
|
|
||||||
pub x: i32,
|
|
||||||
pub y: i32,
|
|
||||||
pub layer: i32,
|
|
||||||
pub bank_id: i32,
|
|
||||||
pub flip_x: bool,
|
|
||||||
pub flip_y: bool,
|
|
||||||
pub priority: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
||||||
pub struct HudPacket {
|
|
||||||
pub commands: Vec<HudCommand>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum HudCommand {
|
|
||||||
Clear { color: Color },
|
|
||||||
FillRect { rect: Rect, color: Color },
|
|
||||||
DrawText { x: i32, y: i32, text: String, color: Color },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum Gfx2dCommand {
|
|
||||||
Clear { color: Color },
|
|
||||||
FillRect { rect: Rect, color: Color },
|
|
||||||
DrawLine { x0: i32, y0: i32, x1: i32, y1: i32, color: Color },
|
|
||||||
DrawCircle { x: i32, y: i32, radius: i32, color: Color },
|
|
||||||
DrawDisc { x: i32, y: i32, radius: i32, border_color: Color, fill_color: Color },
|
|
||||||
DrawSquare { rect: Rect, border_color: Color, fill_color: Color },
|
|
||||||
DrawText { x: i32, y: i32, text: String, color: Color },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum GfxUiCommand {
|
|
||||||
Clear { color: Color },
|
|
||||||
FillRect { rect: Rect, color: Color },
|
|
||||||
DrawLine { x0: i32, y0: i32, x1: i32, y1: i32, color: Color },
|
|
||||||
DrawCircle { x: i32, y: i32, radius: i32, color: Color },
|
|
||||||
DrawDisc { x: i32, y: i32, radius: i32, border_color: Color, fill_color: Color },
|
|
||||||
DrawSquare { rect: Rect, border_color: Color, fill_color: Color },
|
|
||||||
DrawText { x: i32, y: i32, text: String, color: Color },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn constructors_pin_app_mode_to_packet_kind() {
|
|
||||||
let game = RenderSubmission::game2d(FrameId::new(7), Game2DFramePacket::default());
|
|
||||||
assert_eq!(game.app_mode, AppMode::Game);
|
|
||||||
assert!(matches!(game.packet, RenderSubmissionPacket::Game2D(_)));
|
|
||||||
assert!(game.is_coherent());
|
|
||||||
|
|
||||||
let shell =
|
|
||||||
RenderSubmission::shell_ui(FrameId::new(8), ShellUiFramePacket::new(Vec::new()));
|
|
||||||
assert_eq!(shell.app_mode, AppMode::Shell);
|
|
||||||
assert!(matches!(shell.packet, RenderSubmissionPacket::ShellUi(_)));
|
|
||||||
assert!(shell.is_coherent());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn coherence_check_rejects_mismatched_envelope() {
|
|
||||||
let submission = RenderSubmission {
|
|
||||||
frame_id: FrameId::new(1),
|
|
||||||
app_mode: AppMode::Game,
|
|
||||||
ownership: RenderOwnership::new(0, AppMode::Game, 0),
|
|
||||||
packet: RenderSubmissionPacket::ShellUi(ShellUiFramePacket::new(Vec::new())),
|
|
||||||
};
|
|
||||||
|
|
||||||
assert!(!submission.is_coherent());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ownership_can_be_stamped_by_runtime() {
|
|
||||||
let submission = RenderSubmission::game2d(FrameId::new(3), Game2DFramePacket::default())
|
|
||||||
.with_ownership(RenderOwnership::new(9, AppMode::Game, 42));
|
|
||||||
|
|
||||||
assert_eq!(submission.ownership, RenderOwnership::new(9, AppMode::Game, 42));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn closed_submission_owns_command_payload() {
|
|
||||||
let mut commands = vec![Gfx2dCommand::DrawText {
|
|
||||||
x: 1,
|
|
||||||
y: 2,
|
|
||||||
text: "before".to_string(),
|
|
||||||
color: Color::WHITE,
|
|
||||||
}];
|
|
||||||
let submission = RenderSubmission::game2d(
|
|
||||||
FrameId::new(2),
|
|
||||||
Game2DFramePacket::new(Default::default(), commands.clone()),
|
|
||||||
);
|
|
||||||
|
|
||||||
commands.push(Gfx2dCommand::Clear { color: Color::BLACK });
|
|
||||||
|
|
||||||
let RenderSubmissionPacket::Game2D(packet) = submission.packet else {
|
|
||||||
panic!("expected game packet");
|
|
||||||
};
|
|
||||||
assert_eq!(packet.gfx2d.len(), 1);
|
|
||||||
assert_eq!(
|
|
||||||
packet.gfx2d[0],
|
|
||||||
Gfx2dCommand::DrawText { x: 1, y: 2, text: "before".to_string(), color: Color::WHITE }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn frame_id_advances_monotonically_with_wrapping_arithmetic() {
|
|
||||||
assert_eq!(FrameId::new(41).next(), FrameId::new(42));
|
|
||||||
assert_eq!(FrameId::new(u64::MAX).next(), FrameId::ZERO);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,203 +0,0 @@
|
|||||||
use std::fmt;
|
|
||||||
|
|
||||||
use crate::{OwnedRgba8888Frame, RenderSubmission};
|
|
||||||
|
|
||||||
/// Typed failure surface for the real render worker and its backend.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum RenderWorkerError {
|
|
||||||
BackendUnavailable,
|
|
||||||
RenderFailed,
|
|
||||||
PublishFailed,
|
|
||||||
PresentFailed,
|
|
||||||
ShutdownTimeout,
|
|
||||||
StaleSubmissionDiscarded,
|
|
||||||
WorkerPanic,
|
|
||||||
InternalFailure,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for RenderWorkerError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
Self::BackendUnavailable => f.write_str("render backend unavailable"),
|
|
||||||
Self::RenderFailed => f.write_str("render failed"),
|
|
||||||
Self::PublishFailed => f.write_str("render publish failed"),
|
|
||||||
Self::PresentFailed => f.write_str("render present failed"),
|
|
||||||
Self::ShutdownTimeout => f.write_str("render worker shutdown timed out"),
|
|
||||||
Self::StaleSubmissionDiscarded => f.write_str("stale render submission discarded"),
|
|
||||||
Self::WorkerPanic => f.write_str("render worker panicked"),
|
|
||||||
Self::InternalFailure => f.write_str("internal render worker failure"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for RenderWorkerError {}
|
|
||||||
|
|
||||||
pub trait RenderWorkerBackend: Send + 'static {
|
|
||||||
fn render(
|
|
||||||
&self,
|
|
||||||
submission: &RenderSubmission,
|
|
||||||
) -> Result<OwnedRgba8888Frame, RenderWorkerError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait RenderWorkerFrameSink: Send + 'static {
|
|
||||||
fn publish(&self, frame: OwnedRgba8888Frame) -> Result<(), RenderWorkerError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Snapshot of render worker handoff, render, publish, and shutdown counters.
|
|
||||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
||||||
pub struct RenderWorkerTelemetry {
|
|
||||||
pub produced_submissions: u64,
|
|
||||||
pub replaced_before_consume: u64,
|
|
||||||
pub consumed_submissions: u64,
|
|
||||||
pub published_frames: u64,
|
|
||||||
pub presented_frames: u64,
|
|
||||||
pub repeated_frames: u64,
|
|
||||||
pub stale_submission_discards: u64,
|
|
||||||
pub render_failures: u64,
|
|
||||||
pub publish_failures: u64,
|
|
||||||
pub present_failures: u64,
|
|
||||||
pub shutdown_timeouts: u64,
|
|
||||||
pub worker_panics: u64,
|
|
||||||
pub last_produced_frame_id: u64,
|
|
||||||
pub last_consumed_frame_id: u64,
|
|
||||||
pub last_published_frame_id: u64,
|
|
||||||
pub last_presented_frame_id: u64,
|
|
||||||
pub last_dropped_frame_id: u64,
|
|
||||||
pub last_error_frame_id: u64,
|
|
||||||
pub active_render_epoch: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderWorkerTelemetry {
|
|
||||||
pub fn record_produced(&mut self, frame_id: u64) {
|
|
||||||
self.produced_submissions += 1;
|
|
||||||
self.last_produced_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_replaced_before_consume(&mut self, frame_id: u64) {
|
|
||||||
self.replaced_before_consume += 1;
|
|
||||||
self.last_dropped_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_consumed(&mut self, frame_id: u64) {
|
|
||||||
self.consumed_submissions += 1;
|
|
||||||
self.last_consumed_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_published(&mut self, frame_id: u64) {
|
|
||||||
self.published_frames += 1;
|
|
||||||
self.last_published_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_presented(&mut self, frame_id: u64) {
|
|
||||||
self.presented_frames += 1;
|
|
||||||
self.last_presented_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_repeated_frame(&mut self, frame_id: u64) {
|
|
||||||
self.repeated_frames += 1;
|
|
||||||
self.last_presented_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_stale_submission_discarded(&mut self, frame_id: u64) {
|
|
||||||
self.stale_submission_discards += 1;
|
|
||||||
self.last_dropped_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_error(&mut self, error: RenderWorkerError, frame_id: u64) {
|
|
||||||
match error {
|
|
||||||
RenderWorkerError::BackendUnavailable | RenderWorkerError::RenderFailed => {
|
|
||||||
self.render_failures += 1;
|
|
||||||
}
|
|
||||||
RenderWorkerError::PublishFailed => {
|
|
||||||
self.publish_failures += 1;
|
|
||||||
}
|
|
||||||
RenderWorkerError::PresentFailed => {
|
|
||||||
self.present_failures += 1;
|
|
||||||
}
|
|
||||||
RenderWorkerError::ShutdownTimeout => {
|
|
||||||
self.shutdown_timeouts += 1;
|
|
||||||
}
|
|
||||||
RenderWorkerError::WorkerPanic => {
|
|
||||||
self.worker_panics += 1;
|
|
||||||
}
|
|
||||||
RenderWorkerError::StaleSubmissionDiscarded => {
|
|
||||||
self.stale_submission_discards += 1;
|
|
||||||
self.last_dropped_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
RenderWorkerError::InternalFailure => {
|
|
||||||
self.render_failures += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.last_error_frame_id = frame_id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_worker_error_is_copy_equatable_and_debuggable() {
|
|
||||||
let error = RenderWorkerError::ShutdownTimeout;
|
|
||||||
let copied = error;
|
|
||||||
|
|
||||||
assert_eq!(copied, RenderWorkerError::ShutdownTimeout);
|
|
||||||
assert_eq!(format!("{:?}", error), "ShutdownTimeout");
|
|
||||||
assert_eq!(error.to_string(), "render worker shutdown timed out");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_worker_telemetry_defaults_to_zero() {
|
|
||||||
assert_eq!(
|
|
||||||
RenderWorkerTelemetry::default(),
|
|
||||||
RenderWorkerTelemetry {
|
|
||||||
produced_submissions: 0,
|
|
||||||
replaced_before_consume: 0,
|
|
||||||
consumed_submissions: 0,
|
|
||||||
published_frames: 0,
|
|
||||||
presented_frames: 0,
|
|
||||||
repeated_frames: 0,
|
|
||||||
stale_submission_discards: 0,
|
|
||||||
render_failures: 0,
|
|
||||||
publish_failures: 0,
|
|
||||||
present_failures: 0,
|
|
||||||
shutdown_timeouts: 0,
|
|
||||||
worker_panics: 0,
|
|
||||||
last_produced_frame_id: 0,
|
|
||||||
last_consumed_frame_id: 0,
|
|
||||||
last_published_frame_id: 0,
|
|
||||||
last_presented_frame_id: 0,
|
|
||||||
last_dropped_frame_id: 0,
|
|
||||||
last_error_frame_id: 0,
|
|
||||||
active_render_epoch: 0,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_worker_telemetry_records_counters_and_frame_ids() {
|
|
||||||
let mut telemetry = RenderWorkerTelemetry::default();
|
|
||||||
|
|
||||||
telemetry.record_produced(10);
|
|
||||||
telemetry.record_replaced_before_consume(10);
|
|
||||||
telemetry.record_consumed(11);
|
|
||||||
telemetry.record_published(11);
|
|
||||||
telemetry.record_presented(11);
|
|
||||||
telemetry.record_repeated_frame(11);
|
|
||||||
telemetry.record_error(RenderWorkerError::PublishFailed, 12);
|
|
||||||
telemetry.record_error(RenderWorkerError::WorkerPanic, 13);
|
|
||||||
telemetry.record_stale_submission_discarded(14);
|
|
||||||
|
|
||||||
assert_eq!(telemetry.produced_submissions, 1);
|
|
||||||
assert_eq!(telemetry.replaced_before_consume, 1);
|
|
||||||
assert_eq!(telemetry.consumed_submissions, 1);
|
|
||||||
assert_eq!(telemetry.published_frames, 1);
|
|
||||||
assert_eq!(telemetry.presented_frames, 1);
|
|
||||||
assert_eq!(telemetry.repeated_frames, 1);
|
|
||||||
assert_eq!(telemetry.publish_failures, 1);
|
|
||||||
assert_eq!(telemetry.worker_panics, 1);
|
|
||||||
assert_eq!(telemetry.stale_submission_discards, 1);
|
|
||||||
assert_eq!(telemetry.last_error_frame_id, 13);
|
|
||||||
assert_eq!(telemetry.last_dropped_frame_id, 14);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
use crate::scene_layer::SceneLayer;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct SceneBank {
|
|
||||||
pub layers: [SceneLayer; 4],
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::asset::AssetId;
|
|
||||||
use crate::glyph::Glyph;
|
|
||||||
use crate::glyph_bank::TileSize;
|
|
||||||
use crate::scene_layer::ParallaxFactor;
|
|
||||||
use crate::tile::Tile;
|
|
||||||
use crate::tilemap::TileMap;
|
|
||||||
|
|
||||||
fn layer(
|
|
||||||
glyph_asset_id: AssetId,
|
|
||||||
parallax_x: f32,
|
|
||||||
parallax_y: f32,
|
|
||||||
glyph_id: u16,
|
|
||||||
) -> SceneLayer {
|
|
||||||
SceneLayer {
|
|
||||||
active: true,
|
|
||||||
glyph_asset_id,
|
|
||||||
tile_size: TileSize::Size16,
|
|
||||||
parallax_factor: ParallaxFactor { x: parallax_x, y: parallax_y },
|
|
||||||
tilemap: TileMap {
|
|
||||||
width: 1,
|
|
||||||
height: 1,
|
|
||||||
tiles: vec![Tile {
|
|
||||||
active: true,
|
|
||||||
glyph: Glyph { glyph_id, palette_id: 1 },
|
|
||||||
flip_x: false,
|
|
||||||
flip_y: false,
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scene_bank_owns_exactly_four_layers() {
|
|
||||||
let scene = SceneBank {
|
|
||||||
layers: [
|
|
||||||
layer(0, 1.0, 1.0, 10),
|
|
||||||
layer(1, 0.5, 1.0, 11),
|
|
||||||
layer(2, 1.0, 0.5, 12),
|
|
||||||
layer(3, 0.25, 0.25, 13),
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
assert_eq!(scene.layers.len(), 4);
|
|
||||||
assert_eq!(scene.layers[3].tilemap.tiles[0].glyph.glyph_id, 13);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
use crate::asset::AssetId;
|
|
||||||
use crate::glyph_bank::TileSize;
|
|
||||||
use crate::tilemap::TileMap;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub struct ParallaxFactor {
|
|
||||||
pub x: f32,
|
|
||||||
pub y: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct SceneLayer {
|
|
||||||
pub active: bool,
|
|
||||||
pub glyph_asset_id: AssetId,
|
|
||||||
pub tile_size: TileSize,
|
|
||||||
pub parallax_factor: ParallaxFactor,
|
|
||||||
pub tilemap: TileMap,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::glyph::Glyph;
|
|
||||||
use crate::tile::Tile;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scene_layer_preserves_parallax_factor_and_tilemap_ownership() {
|
|
||||||
let layer = SceneLayer {
|
|
||||||
active: true,
|
|
||||||
glyph_asset_id: 7,
|
|
||||||
tile_size: TileSize::Size16,
|
|
||||||
parallax_factor: ParallaxFactor { x: 0.5, y: 0.75 },
|
|
||||||
tilemap: TileMap {
|
|
||||||
width: 2,
|
|
||||||
height: 1,
|
|
||||||
tiles: vec![
|
|
||||||
Tile {
|
|
||||||
active: true,
|
|
||||||
glyph: Glyph { glyph_id: 21, palette_id: 3 },
|
|
||||||
flip_x: false,
|
|
||||||
flip_y: false,
|
|
||||||
},
|
|
||||||
Tile {
|
|
||||||
active: false,
|
|
||||||
glyph: Glyph { glyph_id: 22, palette_id: 4 },
|
|
||||||
flip_x: true,
|
|
||||||
flip_y: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
assert_eq!(layer.glyph_asset_id, 7);
|
|
||||||
assert_eq!(layer.parallax_factor.x, 0.5);
|
|
||||||
assert_eq!(layer.parallax_factor.y, 0.75);
|
|
||||||
assert_eq!(layer.tilemap.width, 2);
|
|
||||||
assert_eq!(layer.tilemap.tiles[1].glyph.glyph_id, 22);
|
|
||||||
assert!(layer.tilemap.tiles[1].flip_x);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,562 +0,0 @@
|
|||||||
use crate::asset::AssetId;
|
|
||||||
use crate::glyph_bank::TileSize;
|
|
||||||
use crate::scene_bank::SceneBank;
|
|
||||||
use crate::scene_layer::SceneLayer;
|
|
||||||
use crate::tile::Tile;
|
|
||||||
|
|
||||||
const FLAG_FLIP_X: u8 = 0b0000_0001;
|
|
||||||
const FLAG_FLIP_Y: u8 = 0b0000_0010;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
|
||||||
pub struct CachedTileEntry {
|
|
||||||
pub active: bool,
|
|
||||||
pub glyph_id: u16,
|
|
||||||
pub palette_id: u8,
|
|
||||||
pub flags: u8,
|
|
||||||
pub glyph_asset_id: AssetId,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CachedTileEntry {
|
|
||||||
pub fn flip_x(self) -> bool {
|
|
||||||
(self.flags & FLAG_FLIP_X) != 0
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn flip_y(self) -> bool {
|
|
||||||
(self.flags & FLAG_FLIP_Y) != 0
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_tile(layer: &SceneLayer, tile: Tile) -> Self {
|
|
||||||
let mut flags = 0_u8;
|
|
||||||
if tile.flip_x {
|
|
||||||
flags |= FLAG_FLIP_X;
|
|
||||||
}
|
|
||||||
if tile.flip_y {
|
|
||||||
flags |= FLAG_FLIP_Y;
|
|
||||||
}
|
|
||||||
|
|
||||||
Self {
|
|
||||||
active: tile.active,
|
|
||||||
glyph_id: tile.glyph.glyph_id,
|
|
||||||
palette_id: tile.glyph.palette_id,
|
|
||||||
flags,
|
|
||||||
glyph_asset_id: layer.glyph_asset_id,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub struct ViewportRegion {
|
|
||||||
pub x: usize,
|
|
||||||
pub y: usize,
|
|
||||||
pub width: usize,
|
|
||||||
pub height: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ViewportRegion {
|
|
||||||
pub const fn new(x: usize, y: usize, width: usize, height: usize) -> Self {
|
|
||||||
Self { x, y, width, height }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct SceneViewportLayerCache {
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
logical_origin_x: i32,
|
|
||||||
logical_origin_y: i32,
|
|
||||||
ring_origin_x: usize,
|
|
||||||
ring_origin_y: usize,
|
|
||||||
pub glyph_asset_id: AssetId,
|
|
||||||
pub tile_size: TileSize,
|
|
||||||
entries: Vec<CachedTileEntry>,
|
|
||||||
pub valid: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SceneViewportLayerCache {
|
|
||||||
pub fn new(layer: &SceneLayer, width: usize, height: usize) -> Self {
|
|
||||||
Self {
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
logical_origin_x: 0,
|
|
||||||
logical_origin_y: 0,
|
|
||||||
ring_origin_x: 0,
|
|
||||||
ring_origin_y: 0,
|
|
||||||
glyph_asset_id: layer.glyph_asset_id,
|
|
||||||
tile_size: layer.tile_size,
|
|
||||||
entries: vec![CachedTileEntry::default(); width * height],
|
|
||||||
valid: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn width(&self) -> usize {
|
|
||||||
self.width
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn height(&self) -> usize {
|
|
||||||
self.height
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn logical_origin(&self) -> (i32, i32) {
|
|
||||||
(self.logical_origin_x, self.logical_origin_y)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn ring_origin(&self) -> (usize, usize) {
|
|
||||||
(self.ring_origin_x, self.ring_origin_y)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn entry(&self, cache_x: usize, cache_y: usize) -> CachedTileEntry {
|
|
||||||
self.entries[self.physical_index(cache_x, cache_y)]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn invalidate_all(&mut self) {
|
|
||||||
self.entries.fill(CachedTileEntry::default());
|
|
||||||
self.valid = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn move_window_to(&mut self, origin_x: i32, origin_y: i32) {
|
|
||||||
let delta_x = origin_x - self.logical_origin_x;
|
|
||||||
let delta_y = origin_y - self.logical_origin_y;
|
|
||||||
|
|
||||||
self.logical_origin_x = origin_x;
|
|
||||||
self.logical_origin_y = origin_y;
|
|
||||||
|
|
||||||
self.ring_origin_x = Self::wrapped_origin(self.ring_origin_x, delta_x, self.width);
|
|
||||||
self.ring_origin_y = Self::wrapped_origin(self.ring_origin_y, delta_y, self.height);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn move_window_by(&mut self, delta_x: i32, delta_y: i32) {
|
|
||||||
self.move_window_to(self.logical_origin_x + delta_x, self.logical_origin_y + delta_y);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_line(&mut self, layer: &SceneLayer, cache_y: usize) {
|
|
||||||
self.refresh_region(layer, ViewportRegion::new(0, cache_y, self.width, 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_column(&mut self, layer: &SceneLayer, cache_x: usize) {
|
|
||||||
self.refresh_region(layer, ViewportRegion::new(cache_x, 0, 1, self.height));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_region(&mut self, layer: &SceneLayer, region: ViewportRegion) {
|
|
||||||
self.glyph_asset_id = layer.glyph_asset_id;
|
|
||||||
self.tile_size = layer.tile_size;
|
|
||||||
|
|
||||||
let max_x = region.x.saturating_add(region.width).min(self.width);
|
|
||||||
let max_y = region.y.saturating_add(region.height).min(self.height);
|
|
||||||
|
|
||||||
for cache_y in region.y..max_y {
|
|
||||||
for cache_x in region.x..max_x {
|
|
||||||
let entry = self.materialize_entry(layer, cache_x, cache_y);
|
|
||||||
let idx = self.physical_index(cache_x, cache_y);
|
|
||||||
self.entries[idx] = entry;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.valid = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_all(&mut self, layer: &SceneLayer) {
|
|
||||||
self.refresh_region(layer, ViewportRegion::new(0, 0, self.width, self.height));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn materialize_entry(
|
|
||||||
&self,
|
|
||||||
layer: &SceneLayer,
|
|
||||||
cache_x: usize,
|
|
||||||
cache_y: usize,
|
|
||||||
) -> CachedTileEntry {
|
|
||||||
let scene_x = self.logical_origin_x + cache_x as i32;
|
|
||||||
let scene_y = self.logical_origin_y + cache_y as i32;
|
|
||||||
|
|
||||||
if scene_x < 0 || scene_y < 0 {
|
|
||||||
return CachedTileEntry::default();
|
|
||||||
}
|
|
||||||
|
|
||||||
let tile_x = scene_x as usize;
|
|
||||||
let tile_y = scene_y as usize;
|
|
||||||
if tile_x >= layer.tilemap.width || tile_y >= layer.tilemap.height {
|
|
||||||
return CachedTileEntry::default();
|
|
||||||
}
|
|
||||||
|
|
||||||
let tile = layer.tilemap.tiles[tile_y * layer.tilemap.width + tile_x];
|
|
||||||
CachedTileEntry::from_tile(layer, tile)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn physical_index(&self, cache_x: usize, cache_y: usize) -> usize {
|
|
||||||
let physical_x = (self.ring_origin_x + cache_x) % self.width;
|
|
||||||
let physical_y = (self.ring_origin_y + cache_y) % self.height;
|
|
||||||
physical_y * self.width + physical_x
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wrapped_origin(current: usize, delta: i32, span: usize) -> usize {
|
|
||||||
if span == 0 {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
let span_i32 = span as i32;
|
|
||||||
let current_i32 = current as i32;
|
|
||||||
(current_i32 + delta).rem_euclid(span_i32) as usize
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct SceneViewportCache {
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
pub layers: [SceneViewportLayerCache; 4],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SceneViewportCache {
|
|
||||||
pub fn new(scene: &SceneBank, width: usize, height: usize) -> Self {
|
|
||||||
Self {
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
layers: std::array::from_fn(|i| {
|
|
||||||
SceneViewportLayerCache::new(&scene.layers[i], width, height)
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn width(&self) -> usize {
|
|
||||||
self.width
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn height(&self) -> usize {
|
|
||||||
self.height
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn invalidate_all(&mut self) {
|
|
||||||
for layer in &mut self.layers {
|
|
||||||
layer.invalidate_all();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn move_layer_window_to(&mut self, layer_idx: usize, origin_x: i32, origin_y: i32) {
|
|
||||||
self.layers[layer_idx].move_window_to(origin_x, origin_y);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn move_layer_window_by(&mut self, layer_idx: usize, delta_x: i32, delta_y: i32) {
|
|
||||||
self.layers[layer_idx].move_window_by(delta_x, delta_y);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_layer_line(&mut self, scene: &SceneBank, layer_idx: usize, cache_y: usize) {
|
|
||||||
self.layers[layer_idx].refresh_line(&scene.layers[layer_idx], cache_y);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_layer_column(&mut self, scene: &SceneBank, layer_idx: usize, cache_x: usize) {
|
|
||||||
self.layers[layer_idx].refresh_column(&scene.layers[layer_idx], cache_x);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_layer_region(
|
|
||||||
&mut self,
|
|
||||||
scene: &SceneBank,
|
|
||||||
layer_idx: usize,
|
|
||||||
region: ViewportRegion,
|
|
||||||
) {
|
|
||||||
self.layers[layer_idx].refresh_region(&scene.layers[layer_idx], region);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_layer_all(&mut self, scene: &SceneBank, layer_idx: usize) {
|
|
||||||
self.layers[layer_idx].refresh_all(&scene.layers[layer_idx]);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn materialize_all_layers(&mut self, scene: &SceneBank) {
|
|
||||||
for layer_idx in 0..self.layers.len() {
|
|
||||||
self.refresh_layer_all(scene, layer_idx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::asset::AssetId;
|
|
||||||
use crate::glyph::Glyph;
|
|
||||||
use crate::glyph_bank::TileSize;
|
|
||||||
use crate::scene_layer::ParallaxFactor;
|
|
||||||
use crate::tile::Tile;
|
|
||||||
use crate::tilemap::TileMap;
|
|
||||||
|
|
||||||
fn make_tile(glyph_id: u16, palette_id: u8, flip_x: bool, flip_y: bool) -> Tile {
|
|
||||||
Tile { active: true, glyph: Glyph { glyph_id, palette_id }, flip_x, flip_y }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_layer(glyph_asset_id: AssetId, base_glyph: u16) -> SceneLayer {
|
|
||||||
let mut tiles = Vec::new();
|
|
||||||
for y in 0..4 {
|
|
||||||
for x in 0..4 {
|
|
||||||
tiles.push(make_tile(base_glyph + (y * 4 + x) as u16, 1, x % 2 == 0, y % 2 == 1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SceneLayer {
|
|
||||||
active: true,
|
|
||||||
glyph_asset_id,
|
|
||||||
tile_size: TileSize::Size16,
|
|
||||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
|
||||||
tilemap: TileMap { width: 4, height: 4, tiles },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_scene() -> SceneBank {
|
|
||||||
SceneBank {
|
|
||||||
layers: [
|
|
||||||
make_layer(1, 100),
|
|
||||||
make_layer(2, 200),
|
|
||||||
make_layer(3, 300),
|
|
||||||
make_layer(4, 400),
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn layer_cache_wraps_ring_origin_under_window_movement() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 3, 3);
|
|
||||||
|
|
||||||
cache.move_layer_window_by(0, 1, 2);
|
|
||||||
assert_eq!(cache.layers[0].logical_origin(), (1, 2));
|
|
||||||
assert_eq!(cache.layers[0].ring_origin(), (1, 2));
|
|
||||||
|
|
||||||
cache.move_layer_window_by(0, 3, 2);
|
|
||||||
assert_eq!(cache.layers[0].logical_origin(), (4, 4));
|
|
||||||
assert_eq!(cache.layers[0].ring_origin(), (1, 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn layer_cache_wraps_ring_origin_for_negative_and_large_movements() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 3, 3);
|
|
||||||
|
|
||||||
cache.move_layer_window_by(0, -1, -4);
|
|
||||||
assert_eq!(cache.layers[0].logical_origin(), (-1, -4));
|
|
||||||
assert_eq!(cache.layers[0].ring_origin(), (2, 2));
|
|
||||||
|
|
||||||
cache.move_layer_window_by(0, 7, 8);
|
|
||||||
assert_eq!(cache.layers[0].logical_origin(), (6, 4));
|
|
||||||
assert_eq!(cache.layers[0].ring_origin(), (0, 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn move_window_to_matches_incremental_ring_movement() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut direct = SceneViewportCache::new(&scene, 4, 4);
|
|
||||||
let mut incremental = SceneViewportCache::new(&scene, 4, 4);
|
|
||||||
|
|
||||||
direct.move_layer_window_to(0, 9, -6);
|
|
||||||
incremental.move_layer_window_by(0, 5, -2);
|
|
||||||
incremental.move_layer_window_by(0, 4, -4);
|
|
||||||
|
|
||||||
assert_eq!(direct.layers[0].logical_origin(), incremental.layers[0].logical_origin());
|
|
||||||
assert_eq!(direct.layers[0].ring_origin(), incremental.layers[0].ring_origin());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn cache_entry_fields_are_derived_from_scene_tiles() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 2, 2);
|
|
||||||
|
|
||||||
cache.refresh_layer_all(&scene, 0);
|
|
||||||
let entry = cache.layers[0].entry(1, 1);
|
|
||||||
|
|
||||||
assert!(entry.active);
|
|
||||||
assert_eq!(entry.glyph_id, 105);
|
|
||||||
assert_eq!(entry.palette_id, 1);
|
|
||||||
assert_eq!(entry.glyph_asset_id, 1);
|
|
||||||
assert!(!entry.flip_x());
|
|
||||||
assert!(entry.flip_y());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn line_refresh_only_updates_the_requested_line() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 3, 3);
|
|
||||||
|
|
||||||
cache.refresh_layer_line(&scene, 0, 1);
|
|
||||||
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 0), CachedTileEntry::default());
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 1).glyph_id, 104);
|
|
||||||
assert_eq!(cache.layers[0].entry(2, 1).glyph_id, 106);
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 2), CachedTileEntry::default());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn column_refresh_only_updates_the_requested_column() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 3, 3);
|
|
||||||
|
|
||||||
cache.refresh_layer_column(&scene, 1, 2);
|
|
||||||
|
|
||||||
assert_eq!(cache.layers[1].entry(0, 0), CachedTileEntry::default());
|
|
||||||
assert_eq!(cache.layers[1].entry(2, 0).glyph_id, 202);
|
|
||||||
assert_eq!(cache.layers[1].entry(2, 2).glyph_id, 210);
|
|
||||||
assert_eq!(cache.layers[1].entry(1, 2), CachedTileEntry::default());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn region_refresh_only_updates_the_requested_area() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 3, 3);
|
|
||||||
|
|
||||||
cache.refresh_layer_region(&scene, 2, ViewportRegion::new(1, 1, 2, 2));
|
|
||||||
|
|
||||||
assert_eq!(cache.layers[2].entry(0, 0), CachedTileEntry::default());
|
|
||||||
assert_eq!(cache.layers[2].entry(1, 1).glyph_id, 305);
|
|
||||||
assert_eq!(cache.layers[2].entry(2, 2).glyph_id, 310);
|
|
||||||
assert_eq!(cache.layers[2].entry(0, 2), CachedTileEntry::default());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scene_swap_invalidation_clears_all_layers() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 2, 2);
|
|
||||||
cache.materialize_all_layers(&scene);
|
|
||||||
|
|
||||||
cache.invalidate_all();
|
|
||||||
|
|
||||||
for layer in &cache.layers {
|
|
||||||
assert!(!layer.valid);
|
|
||||||
for y in 0..cache.height() {
|
|
||||||
for x in 0..cache.width() {
|
|
||||||
assert_eq!(layer.entry(x, y), CachedTileEntry::default());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn corner_style_region_update_does_not_touch_outside_tiles() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 4, 4);
|
|
||||||
cache.materialize_all_layers(&scene);
|
|
||||||
|
|
||||||
let before = cache.layers[3].entry(1, 1);
|
|
||||||
cache.layers[3].invalidate_all();
|
|
||||||
cache.refresh_layer_region(&scene, 3, ViewportRegion::new(2, 2, 2, 2));
|
|
||||||
|
|
||||||
assert_eq!(cache.layers[3].entry(0, 0), CachedTileEntry::default());
|
|
||||||
assert_eq!(cache.layers[3].entry(1, 1), CachedTileEntry::default());
|
|
||||||
assert_ne!(cache.layers[3].entry(2, 2), CachedTileEntry::default());
|
|
||||||
assert_eq!(before.glyph_id, 405);
|
|
||||||
assert_eq!(cache.layers[3].entry(3, 3).glyph_id, 415);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn refresh_after_wrapped_window_move_materializes_new_logical_tiles() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 3, 3);
|
|
||||||
|
|
||||||
cache.refresh_layer_all(&scene, 0);
|
|
||||||
cache.move_layer_window_to(0, 1, 2);
|
|
||||||
cache.refresh_layer_all(&scene, 0);
|
|
||||||
|
|
||||||
assert_eq!(cache.layers[0].logical_origin(), (1, 2));
|
|
||||||
assert_eq!(cache.layers[0].ring_origin(), (1, 2));
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 0).glyph_id, 109);
|
|
||||||
assert_eq!(cache.layers[0].entry(1, 0).glyph_id, 110);
|
|
||||||
assert_eq!(cache.layers[0].entry(2, 0).glyph_id, 111);
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 1).glyph_id, 113);
|
|
||||||
assert_eq!(cache.layers[0].entry(2, 1).glyph_id, 115);
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 2), CachedTileEntry::default());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn partial_refresh_uses_wrapped_physical_slots_after_window_move() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 3, 3);
|
|
||||||
|
|
||||||
cache.move_layer_window_to(0, 1, 0);
|
|
||||||
cache.refresh_layer_column(&scene, 0, 0);
|
|
||||||
|
|
||||||
assert_eq!(cache.layers[0].ring_origin(), (1, 0));
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 0).glyph_id, 101);
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 1).glyph_id, 105);
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 2).glyph_id, 109);
|
|
||||||
assert_eq!(cache.layers[0].entry(1, 0), CachedTileEntry::default());
|
|
||||||
assert_eq!(cache.layers[0].entry(2, 0), CachedTileEntry::default());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn out_of_bounds_logical_origins_materialize_default_entries_after_wrap() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 2, 2);
|
|
||||||
|
|
||||||
cache.move_layer_window_to(0, -2, 3);
|
|
||||||
cache.refresh_layer_all(&scene, 0);
|
|
||||||
|
|
||||||
for y in 0..2 {
|
|
||||||
for x in 0..2 {
|
|
||||||
assert_eq!(cache.layers[0].entry(x, y), CachedTileEntry::default());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ringbuffer_preserves_logical_tile_mapping_across_long_mixed_movements() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 3, 3);
|
|
||||||
let motions = [
|
|
||||||
(1, 0),
|
|
||||||
(0, 1),
|
|
||||||
(2, 2),
|
|
||||||
(-1, 0),
|
|
||||||
(0, -2),
|
|
||||||
(4, 1),
|
|
||||||
(-3, 3),
|
|
||||||
(5, -4),
|
|
||||||
(-6, 2),
|
|
||||||
(3, -3),
|
|
||||||
(7, 7),
|
|
||||||
(-8, -5),
|
|
||||||
];
|
|
||||||
|
|
||||||
for &(dx, dy) in &motions {
|
|
||||||
cache.move_layer_window_by(0, dx, dy);
|
|
||||||
cache.refresh_layer_all(&scene, 0);
|
|
||||||
|
|
||||||
let (origin_x, origin_y) = cache.layers[0].logical_origin();
|
|
||||||
for cache_y in 0..cache.height() {
|
|
||||||
for cache_x in 0..cache.width() {
|
|
||||||
let expected_scene_x = origin_x + cache_x as i32;
|
|
||||||
let expected_scene_y = origin_y + cache_y as i32;
|
|
||||||
|
|
||||||
let expected = if expected_scene_x < 0
|
|
||||||
|| expected_scene_y < 0
|
|
||||||
|| expected_scene_x as usize >= scene.layers[0].tilemap.width
|
|
||||||
|| expected_scene_y as usize >= scene.layers[0].tilemap.height
|
|
||||||
{
|
|
||||||
CachedTileEntry::default()
|
|
||||||
} else {
|
|
||||||
let tile_x = expected_scene_x as usize;
|
|
||||||
let tile_y = expected_scene_y as usize;
|
|
||||||
let tile = scene.layers[0].tilemap.tiles
|
|
||||||
[tile_y * scene.layers[0].tilemap.width + tile_x];
|
|
||||||
CachedTileEntry::from_tile(&scene.layers[0], tile)
|
|
||||||
};
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
cache.layers[0].entry(cache_x, cache_y),
|
|
||||||
expected,
|
|
||||||
"mismatch at logical origin ({}, {}), cache ({}, {})",
|
|
||||||
origin_x,
|
|
||||||
origin_y,
|
|
||||||
cache_x,
|
|
||||||
cache_y
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn materialization_populates_all_four_layers() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut cache = SceneViewportCache::new(&scene, 2, 2);
|
|
||||||
|
|
||||||
cache.materialize_all_layers(&scene);
|
|
||||||
|
|
||||||
assert_eq!(cache.layers[0].entry(0, 0).glyph_id, 100);
|
|
||||||
assert_eq!(cache.layers[1].entry(0, 0).glyph_id, 200);
|
|
||||||
assert_eq!(cache.layers[2].entry(1, 1).glyph_id, 305);
|
|
||||||
assert_eq!(cache.layers[3].entry(1, 0).glyph_id, 401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,537 +0,0 @@
|
|||||||
use crate::glyph_bank::TileSize;
|
|
||||||
use crate::scene_bank::SceneBank;
|
|
||||||
use crate::scene_viewport_cache::ViewportRegion;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
|
||||||
pub struct TileAnchor {
|
|
||||||
pub x: i32,
|
|
||||||
pub y: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum CacheRefreshRequest {
|
|
||||||
InvalidateLayer { layer_index: usize },
|
|
||||||
RefreshLine { layer_index: usize, cache_y: usize },
|
|
||||||
RefreshColumn { layer_index: usize, cache_x: usize },
|
|
||||||
RefreshRegion { layer_index: usize, region: ViewportRegion },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub struct LayerCopyRequest {
|
|
||||||
pub layer_index: usize,
|
|
||||||
pub tile_size: TileSize,
|
|
||||||
pub viewport_width_px: i32,
|
|
||||||
pub viewport_height_px: i32,
|
|
||||||
pub source_offset_x_px: i32,
|
|
||||||
pub source_offset_y_px: i32,
|
|
||||||
pub cache_origin_tile_x: i32,
|
|
||||||
pub cache_origin_tile_y: i32,
|
|
||||||
pub camera_x_px: i32,
|
|
||||||
pub camera_y_px: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct ResolverUpdate {
|
|
||||||
pub master_anchor: TileAnchor,
|
|
||||||
pub layer_anchors: [TileAnchor; 4],
|
|
||||||
pub refresh_requests: Vec<CacheRefreshRequest>,
|
|
||||||
pub copy_requests: [LayerCopyRequest; 4],
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct SceneViewportResolver {
|
|
||||||
viewport_width_px: i32,
|
|
||||||
viewport_height_px: i32,
|
|
||||||
cache_width_tiles: usize,
|
|
||||||
cache_height_tiles: usize,
|
|
||||||
hysteresis_safe_px: i32,
|
|
||||||
hysteresis_trigger_px: i32,
|
|
||||||
initialized: bool,
|
|
||||||
master_anchor: TileAnchor,
|
|
||||||
layer_anchors: [TileAnchor; 4],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SceneViewportResolver {
|
|
||||||
pub fn new(
|
|
||||||
viewport_width_px: i32,
|
|
||||||
viewport_height_px: i32,
|
|
||||||
cache_width_tiles: usize,
|
|
||||||
cache_height_tiles: usize,
|
|
||||||
hysteresis_safe_px: i32,
|
|
||||||
hysteresis_trigger_px: i32,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
viewport_width_px,
|
|
||||||
viewport_height_px,
|
|
||||||
cache_width_tiles,
|
|
||||||
cache_height_tiles,
|
|
||||||
hysteresis_safe_px,
|
|
||||||
hysteresis_trigger_px,
|
|
||||||
initialized: false,
|
|
||||||
master_anchor: TileAnchor::default(),
|
|
||||||
layer_anchors: [TileAnchor::default(); 4],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reset_scene(&mut self) -> Vec<CacheRefreshRequest> {
|
|
||||||
self.initialized = false;
|
|
||||||
vec![
|
|
||||||
CacheRefreshRequest::InvalidateLayer { layer_index: 0 },
|
|
||||||
CacheRefreshRequest::InvalidateLayer { layer_index: 1 },
|
|
||||||
CacheRefreshRequest::InvalidateLayer { layer_index: 2 },
|
|
||||||
CacheRefreshRequest::InvalidateLayer { layer_index: 3 },
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update(
|
|
||||||
&mut self,
|
|
||||||
scene: &SceneBank,
|
|
||||||
camera_x_px: i32,
|
|
||||||
camera_y_px: i32,
|
|
||||||
) -> ResolverUpdate {
|
|
||||||
let mut refresh_requests = Vec::new();
|
|
||||||
let camera_center_x = camera_x_px + self.viewport_width_px / 2;
|
|
||||||
let camera_center_y = camera_y_px + self.viewport_height_px / 2;
|
|
||||||
|
|
||||||
let layer_inputs: [(i32, i32, i32, i32, i32); 4] = std::array::from_fn(|i| {
|
|
||||||
let layer = &scene.layers[i];
|
|
||||||
let tile_size_px = layer.tile_size as i32;
|
|
||||||
let layer_camera_x_px = ((camera_x_px as f32) * layer.parallax_factor.x).floor() as i32;
|
|
||||||
let layer_camera_y_px = ((camera_y_px as f32) * layer.parallax_factor.y).floor() as i32;
|
|
||||||
let layer_center_x_px = layer_camera_x_px + self.viewport_width_px / 2;
|
|
||||||
let layer_center_y_px = layer_camera_y_px + self.viewport_height_px / 2;
|
|
||||||
(
|
|
||||||
tile_size_px,
|
|
||||||
layer_camera_x_px,
|
|
||||||
layer_camera_y_px,
|
|
||||||
layer_center_x_px,
|
|
||||||
layer_center_y_px,
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
if !self.initialized {
|
|
||||||
self.master_anchor = self.initial_anchor(
|
|
||||||
scene.layers[0].tilemap.width,
|
|
||||||
scene.layers[0].tilemap.height,
|
|
||||||
scene.layers[0].tile_size as i32,
|
|
||||||
camera_center_x,
|
|
||||||
camera_center_y,
|
|
||||||
);
|
|
||||||
|
|
||||||
for (layer_index, layer) in scene.layers.iter().enumerate() {
|
|
||||||
let (_, _, _, layer_center_x_px, layer_center_y_px) = layer_inputs[layer_index];
|
|
||||||
self.layer_anchors[layer_index] = self.initial_anchor(
|
|
||||||
layer.tilemap.width,
|
|
||||||
layer.tilemap.height,
|
|
||||||
layer.tile_size as i32,
|
|
||||||
layer_center_x_px,
|
|
||||||
layer_center_y_px,
|
|
||||||
);
|
|
||||||
refresh_requests.push(CacheRefreshRequest::RefreshRegion {
|
|
||||||
layer_index,
|
|
||||||
region: ViewportRegion::new(
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
self.cache_width_tiles,
|
|
||||||
self.cache_height_tiles,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
self.initialized = true;
|
|
||||||
} else {
|
|
||||||
let layer0 = &scene.layers[0];
|
|
||||||
self.master_anchor = self.advance_anchor(
|
|
||||||
self.master_anchor,
|
|
||||||
camera_center_x,
|
|
||||||
camera_center_y,
|
|
||||||
layer0.tile_size as i32,
|
|
||||||
layer0.tilemap.width,
|
|
||||||
layer0.tilemap.height,
|
|
||||||
);
|
|
||||||
|
|
||||||
for (layer_index, layer) in scene.layers.iter().enumerate() {
|
|
||||||
let previous = self.layer_anchors[layer_index];
|
|
||||||
let (tile_size_px, _, _, layer_center_x_px, layer_center_y_px) =
|
|
||||||
layer_inputs[layer_index];
|
|
||||||
let next = self.advance_anchor(
|
|
||||||
previous,
|
|
||||||
layer_center_x_px,
|
|
||||||
layer_center_y_px,
|
|
||||||
tile_size_px,
|
|
||||||
layer.tilemap.width,
|
|
||||||
layer.tilemap.height,
|
|
||||||
);
|
|
||||||
self.layer_anchors[layer_index] = next;
|
|
||||||
self.emit_refresh_requests(layer_index, previous, next, &mut refresh_requests);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let copy_requests = std::array::from_fn(|layer_index| {
|
|
||||||
let layer = &scene.layers[layer_index];
|
|
||||||
let (tile_size_px, layer_camera_x_px, layer_camera_y_px, _, _) =
|
|
||||||
layer_inputs[layer_index];
|
|
||||||
let anchor = self.layer_anchors[layer_index];
|
|
||||||
let cache_origin_tile_x = anchor.x - (self.cache_width_tiles as i32 / 2);
|
|
||||||
let cache_origin_tile_y = anchor.y - (self.cache_height_tiles as i32 / 2);
|
|
||||||
let cache_origin_x_px = cache_origin_tile_x * tile_size_px;
|
|
||||||
let cache_origin_y_px = cache_origin_tile_y * tile_size_px;
|
|
||||||
|
|
||||||
LayerCopyRequest {
|
|
||||||
layer_index,
|
|
||||||
tile_size: layer.tile_size,
|
|
||||||
viewport_width_px: self.viewport_width_px,
|
|
||||||
viewport_height_px: self.viewport_height_px,
|
|
||||||
source_offset_x_px: layer_camera_x_px - cache_origin_x_px,
|
|
||||||
source_offset_y_px: layer_camera_y_px - cache_origin_y_px,
|
|
||||||
cache_origin_tile_x,
|
|
||||||
cache_origin_tile_y,
|
|
||||||
camera_x_px: layer_camera_x_px,
|
|
||||||
camera_y_px: layer_camera_y_px,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
ResolverUpdate {
|
|
||||||
master_anchor: self.master_anchor,
|
|
||||||
layer_anchors: self.layer_anchors,
|
|
||||||
refresh_requests,
|
|
||||||
copy_requests,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn initial_anchor(
|
|
||||||
&self,
|
|
||||||
scene_width_tiles: usize,
|
|
||||||
scene_height_tiles: usize,
|
|
||||||
tile_size_px: i32,
|
|
||||||
camera_center_x_px: i32,
|
|
||||||
camera_center_y_px: i32,
|
|
||||||
) -> TileAnchor {
|
|
||||||
let proposed = TileAnchor {
|
|
||||||
x: camera_center_x_px.div_euclid(tile_size_px),
|
|
||||||
y: camera_center_y_px.div_euclid(tile_size_px),
|
|
||||||
};
|
|
||||||
self.clamp_anchor(proposed, scene_width_tiles, scene_height_tiles)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn advance_anchor(
|
|
||||||
&self,
|
|
||||||
current: TileAnchor,
|
|
||||||
camera_center_x_px: i32,
|
|
||||||
camera_center_y_px: i32,
|
|
||||||
tile_size_px: i32,
|
|
||||||
scene_width_tiles: usize,
|
|
||||||
scene_height_tiles: usize,
|
|
||||||
) -> TileAnchor {
|
|
||||||
let mut next = current;
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let center_x_px = next.x * tile_size_px + tile_size_px / 2;
|
|
||||||
let drift_x = camera_center_x_px - center_x_px;
|
|
||||||
if drift_x.abs() <= self.hysteresis_safe_px {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if drift_x > self.hysteresis_trigger_px {
|
|
||||||
next.x += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if drift_x < -self.hysteresis_trigger_px {
|
|
||||||
next.x -= 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let center_y_px = next.y * tile_size_px + tile_size_px / 2;
|
|
||||||
let drift_y = camera_center_y_px - center_y_px;
|
|
||||||
if drift_y.abs() <= self.hysteresis_safe_px {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if drift_y > self.hysteresis_trigger_px {
|
|
||||||
next.y += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if drift_y < -self.hysteresis_trigger_px {
|
|
||||||
next.y -= 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.clamp_anchor(next, scene_width_tiles, scene_height_tiles)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clamp_anchor(
|
|
||||||
&self,
|
|
||||||
proposed: TileAnchor,
|
|
||||||
scene_width_tiles: usize,
|
|
||||||
scene_height_tiles: usize,
|
|
||||||
) -> TileAnchor {
|
|
||||||
TileAnchor {
|
|
||||||
x: self.clamp_axis(proposed.x, scene_width_tiles, self.cache_width_tiles),
|
|
||||||
y: self.clamp_axis(proposed.y, scene_height_tiles, self.cache_height_tiles),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clamp_axis(&self, proposed: i32, scene_tiles: usize, cache_tiles: usize) -> i32 {
|
|
||||||
let half = (cache_tiles / 2) as i32;
|
|
||||||
if scene_tiles <= cache_tiles {
|
|
||||||
return half;
|
|
||||||
}
|
|
||||||
|
|
||||||
let min = half;
|
|
||||||
let max = (scene_tiles - cache_tiles) as i32 + half;
|
|
||||||
proposed.clamp(min, max)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn emit_refresh_requests(
|
|
||||||
&self,
|
|
||||||
layer_index: usize,
|
|
||||||
previous: TileAnchor,
|
|
||||||
next: TileAnchor,
|
|
||||||
requests: &mut Vec<CacheRefreshRequest>,
|
|
||||||
) {
|
|
||||||
let delta_x = next.x - previous.x;
|
|
||||||
let delta_y = next.y - previous.y;
|
|
||||||
|
|
||||||
if delta_x == 0 && delta_y == 0 {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if delta_x == 0 {
|
|
||||||
self.emit_line_requests(layer_index, delta_y, requests);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if delta_y == 0 {
|
|
||||||
self.emit_column_requests(layer_index, delta_x, requests);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.emit_corner_region_requests(layer_index, delta_x, delta_y, requests);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn emit_line_requests(
|
|
||||||
&self,
|
|
||||||
layer_index: usize,
|
|
||||||
delta_y: i32,
|
|
||||||
requests: &mut Vec<CacheRefreshRequest>,
|
|
||||||
) {
|
|
||||||
let count = delta_y.unsigned_abs() as usize;
|
|
||||||
if delta_y > 0 {
|
|
||||||
for offset in 0..count {
|
|
||||||
requests.push(CacheRefreshRequest::RefreshLine {
|
|
||||||
layer_index,
|
|
||||||
cache_y: self.cache_height_tiles - count + offset,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for cache_y in 0..count {
|
|
||||||
requests.push(CacheRefreshRequest::RefreshLine { layer_index, cache_y });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn emit_column_requests(
|
|
||||||
&self,
|
|
||||||
layer_index: usize,
|
|
||||||
delta_x: i32,
|
|
||||||
requests: &mut Vec<CacheRefreshRequest>,
|
|
||||||
) {
|
|
||||||
let count = delta_x.unsigned_abs() as usize;
|
|
||||||
if delta_x > 0 {
|
|
||||||
for offset in 0..count {
|
|
||||||
requests.push(CacheRefreshRequest::RefreshColumn {
|
|
||||||
layer_index,
|
|
||||||
cache_x: self.cache_width_tiles - count + offset,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for cache_x in 0..count {
|
|
||||||
requests.push(CacheRefreshRequest::RefreshColumn { layer_index, cache_x });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn emit_corner_region_requests(
|
|
||||||
&self,
|
|
||||||
layer_index: usize,
|
|
||||||
delta_x: i32,
|
|
||||||
delta_y: i32,
|
|
||||||
requests: &mut Vec<CacheRefreshRequest>,
|
|
||||||
) {
|
|
||||||
let width = delta_x.unsigned_abs() as usize;
|
|
||||||
let height = delta_y.unsigned_abs() as usize;
|
|
||||||
|
|
||||||
let primary_x = if delta_x > 0 { self.cache_width_tiles - width } else { 0 };
|
|
||||||
requests.push(CacheRefreshRequest::RefreshRegion {
|
|
||||||
layer_index,
|
|
||||||
region: ViewportRegion::new(primary_x, 0, width, self.cache_height_tiles),
|
|
||||||
});
|
|
||||||
|
|
||||||
let secondary_y = if delta_y > 0 { self.cache_height_tiles - height } else { 0 };
|
|
||||||
let secondary_x = if delta_x > 0 { 0 } else { width };
|
|
||||||
let secondary_width = self.cache_width_tiles.saturating_sub(width);
|
|
||||||
|
|
||||||
if secondary_width > 0 {
|
|
||||||
requests.push(CacheRefreshRequest::RefreshRegion {
|
|
||||||
layer_index,
|
|
||||||
region: ViewportRegion::new(secondary_x, secondary_y, secondary_width, height),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::asset::AssetId;
|
|
||||||
use crate::glyph::Glyph;
|
|
||||||
use crate::glyph_bank::TileSize;
|
|
||||||
use crate::scene_layer::{ParallaxFactor, SceneLayer};
|
|
||||||
use crate::tile::Tile;
|
|
||||||
use crate::tilemap::TileMap;
|
|
||||||
|
|
||||||
fn make_layer(
|
|
||||||
tile_size: TileSize,
|
|
||||||
parallax_x: f32,
|
|
||||||
parallax_y: f32,
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
) -> SceneLayer {
|
|
||||||
let mut tiles = Vec::new();
|
|
||||||
for i in 0..(width * height) {
|
|
||||||
tiles.push(Tile {
|
|
||||||
active: true,
|
|
||||||
glyph: Glyph { glyph_id: i as u16, palette_id: 0 },
|
|
||||||
flip_x: false,
|
|
||||||
flip_y: false,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
SceneLayer {
|
|
||||||
active: true,
|
|
||||||
glyph_asset_id: 1 as AssetId,
|
|
||||||
tile_size,
|
|
||||||
parallax_factor: ParallaxFactor { x: parallax_x, y: parallax_y },
|
|
||||||
tilemap: TileMap { width, height, tiles },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_scene() -> SceneBank {
|
|
||||||
SceneBank {
|
|
||||||
layers: [
|
|
||||||
make_layer(TileSize::Size16, 1.0, 1.0, 64, 64),
|
|
||||||
make_layer(TileSize::Size16, 0.5, 0.5, 64, 64),
|
|
||||||
make_layer(TileSize::Size16, 1.0, 0.75, 64, 64),
|
|
||||||
make_layer(TileSize::Size16, 0.25, 1.0, 64, 64),
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn first_update_initializes_master_and_layer_anchors() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
|
||||||
|
|
||||||
let update = resolver.update(&scene, 0, 0);
|
|
||||||
|
|
||||||
assert_eq!(update.master_anchor, TileAnchor { x: 17, y: 10 });
|
|
||||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 17, y: 10 });
|
|
||||||
assert_eq!(update.layer_anchors[1], TileAnchor { x: 17, y: 10 });
|
|
||||||
assert_eq!(update.refresh_requests.len(), 4);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn per_layer_copy_requests_follow_parallax_factor() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
|
||||||
|
|
||||||
let update = resolver.update(&scene, 32, 48);
|
|
||||||
|
|
||||||
assert_eq!(update.copy_requests[0].camera_x_px, 32);
|
|
||||||
assert_eq!(update.copy_requests[0].camera_y_px, 48);
|
|
||||||
assert_eq!(update.copy_requests[1].camera_x_px, 16);
|
|
||||||
assert_eq!(update.copy_requests[1].camera_y_px, 24);
|
|
||||||
assert_eq!(update.copy_requests[3].camera_x_px, 8);
|
|
||||||
assert_eq!(update.copy_requests[3].camera_y_px, 48);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hysteresis_prevents_small_back_and_forth_refresh_churn() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
|
||||||
|
|
||||||
let _ = resolver.update(&scene, 0, 0);
|
|
||||||
let update = resolver.update(&scene, 8, 0);
|
|
||||||
|
|
||||||
assert!(update.refresh_requests.is_empty());
|
|
||||||
assert_eq!(update.master_anchor, TileAnchor { x: 17, y: 10 });
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn repeated_high_speed_movement_advances_in_tile_steps() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
|
||||||
|
|
||||||
let _ = resolver.update(&scene, 0, 0);
|
|
||||||
let update = resolver.update(&scene, 64, 0);
|
|
||||||
|
|
||||||
assert!(update.master_anchor.x > 17);
|
|
||||||
assert!(update.refresh_requests.iter().any(|request| matches!(
|
|
||||||
request,
|
|
||||||
CacheRefreshRequest::RefreshColumn { layer_index: 0, .. }
|
|
||||||
| CacheRefreshRequest::RefreshRegion { layer_index: 0, .. }
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn anchors_clamp_near_scene_edges() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
|
||||||
|
|
||||||
let update = resolver.update(&scene, 10_000, 10_000);
|
|
||||||
|
|
||||||
assert_eq!(update.master_anchor, TileAnchor { x: 46, y: 53 });
|
|
||||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 46, y: 53 });
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn corner_trigger_converts_to_non_overlapping_region_requests() {
|
|
||||||
let scene = make_scene();
|
|
||||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
|
||||||
|
|
||||||
let _ = resolver.update(&scene, 0, 0);
|
|
||||||
let update = resolver.update(&scene, 64, 80);
|
|
||||||
|
|
||||||
let regions: Vec<_> = update
|
|
||||||
.refresh_requests
|
|
||||||
.iter()
|
|
||||||
.filter_map(|request| match request {
|
|
||||||
CacheRefreshRequest::RefreshRegion { layer_index: 0, region } => Some(*region),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
assert_eq!(regions.len(), 2);
|
|
||||||
assert_eq!(regions[0].x + regions[0].width, 35);
|
|
||||||
assert_eq!(regions[0].height, 21);
|
|
||||||
assert_eq!(regions[1].width, 34);
|
|
||||||
assert_eq!(regions[1].height, 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn reset_scene_requests_full_invalidation_for_all_layers() {
|
|
||||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
|
||||||
|
|
||||||
let requests = resolver.reset_scene();
|
|
||||||
|
|
||||||
assert_eq!(requests.len(), 4);
|
|
||||||
assert!(
|
|
||||||
requests
|
|
||||||
.iter()
|
|
||||||
.all(|request| matches!(request, CacheRefreshRequest::InvalidateLayer { .. }))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
use crate::glyph::Glyph;
|
use crate::tile::Tile;
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
pub struct Sprite {
|
pub struct Sprite {
|
||||||
pub glyph: Glyph,
|
pub tile: Tile,
|
||||||
pub x: i32,
|
pub x: i32,
|
||||||
pub y: i32,
|
pub y: i32,
|
||||||
pub layer: u8,
|
|
||||||
pub bank_id: u8,
|
pub bank_id: u8,
|
||||||
pub active: bool,
|
pub active: bool,
|
||||||
pub flip_x: bool,
|
pub flip_x: bool,
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ pub use resolver::{
|
|||||||
///
|
///
|
||||||
/// Each Syscall has a unique 32-bit ID. The IDs are grouped by category:
|
/// Each Syscall has a unique 32-bit ID. The IDs are grouped by category:
|
||||||
/// - **0x0xxx**: System & OS Control
|
/// - **0x0xxx**: System & OS Control
|
||||||
/// - **0x1xxx**: Game 2D primitives (`gfx2d`) and Shell UI primitives (`gfxui`)
|
/// - **0x1xxx**: Graphics (GFX)
|
||||||
/// - **0x11xx**: Frame Composer orchestration
|
|
||||||
/// - **0x2xxx**: Reserved for legacy input syscalls (disabled for v1 VM-owned input)
|
/// - **0x2xxx**: Reserved for legacy input syscalls (disabled for v1 VM-owned input)
|
||||||
/// - **0x3xxx**: Audio (PCM & Mixing)
|
/// - **0x3xxx**: Audio (PCM & Mixing)
|
||||||
/// - **0x4xxx**: Filesystem (Sandboxed I/O)
|
/// - **0x4xxx**: Filesystem (Sandboxed I/O)
|
||||||
@@ -29,24 +28,16 @@ pub use resolver::{
|
|||||||
#[repr(u32)]
|
#[repr(u32)]
|
||||||
pub enum Syscall {
|
pub enum Syscall {
|
||||||
SystemHasCart = 0x0001,
|
SystemHasCart = 0x0001,
|
||||||
|
SystemRunCart = 0x0002,
|
||||||
GfxClear = 0x1001,
|
GfxClear = 0x1001,
|
||||||
GfxFillRect = 0x1002,
|
GfxFillRect = 0x1002,
|
||||||
GfxDrawLine = 0x1003,
|
GfxDrawLine = 0x1003,
|
||||||
GfxDrawCircle = 0x1004,
|
GfxDrawCircle = 0x1004,
|
||||||
GfxDrawDisc = 0x1005,
|
GfxDrawDisc = 0x1005,
|
||||||
GfxDrawSquare = 0x1006,
|
GfxDrawSquare = 0x1006,
|
||||||
|
GfxSetSprite = 0x1007,
|
||||||
GfxDrawText = 0x1008,
|
GfxDrawText = 0x1008,
|
||||||
GfxUiClear = 0x1201,
|
GfxClear565 = 0x1010,
|
||||||
GfxUiFillRect = 0x1202,
|
|
||||||
GfxUiDrawLine = 0x1203,
|
|
||||||
GfxUiDrawCircle = 0x1204,
|
|
||||||
GfxUiDrawDisc = 0x1205,
|
|
||||||
GfxUiDrawSquare = 0x1206,
|
|
||||||
GfxUiDrawText = 0x1208,
|
|
||||||
ComposerBindScene = 0x1101,
|
|
||||||
ComposerUnbindScene = 0x1102,
|
|
||||||
ComposerSetCamera = 0x1103,
|
|
||||||
ComposerEmitSprite = 0x1104,
|
|
||||||
AudioPlaySample = 0x3001,
|
AudioPlaySample = 0x3001,
|
||||||
AudioPlay = 0x3002,
|
AudioPlay = 0x3002,
|
||||||
FsOpen = 0x4001,
|
FsOpen = 0x4001,
|
||||||
@@ -68,13 +59,8 @@ pub enum Syscall {
|
|||||||
AssetStatus = 0x6002,
|
AssetStatus = 0x6002,
|
||||||
AssetCommit = 0x6003,
|
AssetCommit = 0x6003,
|
||||||
AssetCancel = 0x6004,
|
AssetCancel = 0x6004,
|
||||||
AssetBacklogInfo = 0x6005,
|
|
||||||
AssetBacklogPosition = 0x6006,
|
|
||||||
AssetBacklogMove = 0x6007,
|
|
||||||
AssetBacklogPromote = 0x6008,
|
|
||||||
AssetBacklogDemote = 0x6009,
|
|
||||||
AssetTargetStatus = 0x600A,
|
|
||||||
BankInfo = 0x6101,
|
BankInfo = 0x6101,
|
||||||
|
BankSlotInfo = 0x6102,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Canonical metadata describing a syscall using the unified slot-based ABI.
|
/// Canonical metadata describing a syscall using the unified slot-based ABI.
|
||||||
@@ -110,62 +96,6 @@ pub struct SyscallRegistryEntry {
|
|||||||
pub meta: SyscallMeta,
|
pub meta: SyscallMeta,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SyscallRegistryEntry {
|
|
||||||
/// Starts the builder with mandatory fields and sensible default values.
|
|
||||||
pub const fn builder(syscall: Syscall, module: &'static str, name: &'static str) -> Self {
|
|
||||||
Self {
|
|
||||||
syscall,
|
|
||||||
meta: SyscallMeta {
|
|
||||||
id: syscall as u32,
|
|
||||||
module,
|
|
||||||
name,
|
|
||||||
version: 1, // Default for new syscalls
|
|
||||||
arg_slots: 0,
|
|
||||||
ret_slots: 0,
|
|
||||||
caps: 0,
|
|
||||||
determinism: Determinism::Deterministic,
|
|
||||||
may_allocate: false,
|
|
||||||
cost_hint: 1,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn version(mut self, n: u16) -> Self {
|
|
||||||
self.meta.version = n;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn args(mut self, n: u8) -> Self {
|
|
||||||
self.meta.arg_slots = n;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn rets(mut self, n: u16) -> Self {
|
|
||||||
self.meta.ret_slots = n;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn caps(mut self, caps: CapFlags) -> Self {
|
|
||||||
self.meta.caps = caps;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn non_deterministic(mut self) -> Self {
|
|
||||||
self.meta.determinism = Determinism::NonDeterministic;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn may_allocate(mut self) -> Self {
|
|
||||||
self.meta.may_allocate = true;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn cost(mut self, cost: u32) -> Self {
|
|
||||||
self.meta.cost_hint = cost;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn meta_for(syscall: Syscall) -> &'static SyscallMeta {
|
pub fn meta_for(syscall: Syscall) -> &'static SyscallMeta {
|
||||||
registry::meta_for(syscall)
|
registry::meta_for(syscall)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,10 @@ use super::CapFlags;
|
|||||||
|
|
||||||
pub const NONE: CapFlags = 0;
|
pub const NONE: CapFlags = 0;
|
||||||
pub const SYSTEM: CapFlags = 1 << 0;
|
pub const SYSTEM: CapFlags = 1 << 0;
|
||||||
pub const COMPOSER: CapFlags = 1 << 1;
|
pub const GFX: CapFlags = 1 << 1;
|
||||||
pub const AUDIO: CapFlags = 1 << 2;
|
pub const AUDIO: CapFlags = 1 << 2;
|
||||||
pub const FS: CapFlags = 1 << 3;
|
pub const FS: CapFlags = 1 << 3;
|
||||||
pub const LOG: CapFlags = 1 << 4;
|
pub const LOG: CapFlags = 1 << 4;
|
||||||
pub const ASSET: CapFlags = 1 << 5;
|
pub const ASSET: CapFlags = 1 << 5;
|
||||||
pub const BANK: CapFlags = 1 << 6;
|
pub const BANK: CapFlags = 1 << 6;
|
||||||
pub const GFX2D: CapFlags = 1 << 7;
|
pub const ALL: CapFlags = SYSTEM | GFX | AUDIO | FS | LOG | ASSET | BANK;
|
||||||
pub const GFXUI: CapFlags = 1 << 8;
|
|
||||||
pub const GFX: CapFlags = COMPOSER | GFX2D;
|
|
||||||
pub const ALL: CapFlags = SYSTEM | COMPOSER | AUDIO | FS | LOG | ASSET | BANK | GFX2D | GFXUI;
|
|
||||||
|
|||||||
@@ -1,63 +1,53 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use super::entry;
|
||||||
|
use crate::syscalls::{Determinism, Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetLoad, "asset", "load")
|
entry(
|
||||||
.args(2)
|
Syscall::AssetLoad,
|
||||||
.rets(2)
|
"asset",
|
||||||
.caps(caps::ASSET)
|
"load",
|
||||||
.non_deterministic()
|
1,
|
||||||
.cost(20),
|
2,
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetStatus, "asset", "status")
|
2,
|
||||||
.args(1)
|
caps::ASSET,
|
||||||
.rets(1)
|
Determinism::NonDeterministic,
|
||||||
.caps(caps::ASSET)
|
false,
|
||||||
.non_deterministic(),
|
20,
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetCommit, "asset", "commit")
|
),
|
||||||
.args(1)
|
entry(
|
||||||
.rets(1)
|
Syscall::AssetStatus,
|
||||||
.caps(caps::ASSET)
|
"asset",
|
||||||
.non_deterministic()
|
"status",
|
||||||
.cost(20),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetCancel, "asset", "cancel")
|
1,
|
||||||
.args(1)
|
1,
|
||||||
.rets(1)
|
caps::ASSET,
|
||||||
.caps(caps::ASSET)
|
Determinism::NonDeterministic,
|
||||||
.non_deterministic()
|
false,
|
||||||
.cost(20),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogInfo, "asset", "backlog_info")
|
),
|
||||||
.args(0)
|
entry(
|
||||||
.rets(7)
|
Syscall::AssetCommit,
|
||||||
.caps(caps::ASSET)
|
"asset",
|
||||||
.non_deterministic()
|
"commit",
|
||||||
.cost(5),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogPosition, "asset", "backlog_position")
|
1,
|
||||||
.args(1)
|
1,
|
||||||
.rets(4)
|
caps::ASSET,
|
||||||
.caps(caps::ASSET)
|
Determinism::NonDeterministic,
|
||||||
.non_deterministic()
|
false,
|
||||||
.cost(5),
|
20,
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogMove, "asset", "backlog_move")
|
),
|
||||||
.args(2)
|
entry(
|
||||||
.rets(1)
|
Syscall::AssetCancel,
|
||||||
.caps(caps::ASSET)
|
"asset",
|
||||||
.non_deterministic()
|
"cancel",
|
||||||
.cost(10),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogPromote, "asset", "backlog_promote")
|
1,
|
||||||
.args(1)
|
1,
|
||||||
.rets(1)
|
caps::ASSET,
|
||||||
.caps(caps::ASSET)
|
Determinism::NonDeterministic,
|
||||||
.non_deterministic()
|
false,
|
||||||
.cost(10),
|
20,
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogDemote, "asset", "backlog_demote")
|
),
|
||||||
.args(1)
|
|
||||||
.rets(1)
|
|
||||||
.caps(caps::ASSET)
|
|
||||||
.non_deterministic()
|
|
||||||
.cost(10),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::AssetTargetStatus, "asset", "target_status")
|
|
||||||
.args(2)
|
|
||||||
.rets(6)
|
|
||||||
.caps(caps::ASSET)
|
|
||||||
.non_deterministic()
|
|
||||||
.cost(5),
|
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,14 +1,29 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use super::entry;
|
||||||
|
use crate::syscalls::{Determinism, Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
SyscallRegistryEntry::builder(Syscall::AudioPlaySample, "audio", "play_sample")
|
entry(
|
||||||
.args(5)
|
Syscall::AudioPlaySample,
|
||||||
.rets(1)
|
"audio",
|
||||||
.caps(caps::AUDIO)
|
"play_sample",
|
||||||
.cost(5),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::AudioPlay, "audio", "play")
|
5,
|
||||||
.args(7)
|
1,
|
||||||
.rets(1)
|
caps::AUDIO,
|
||||||
.caps(caps::AUDIO)
|
Determinism::Deterministic,
|
||||||
.cost(5),
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::AudioPlay,
|
||||||
|
"audio",
|
||||||
|
"play",
|
||||||
|
1,
|
||||||
|
7,
|
||||||
|
1,
|
||||||
|
caps::AUDIO,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,7 +1,29 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use super::entry;
|
||||||
|
use crate::syscalls::{Determinism, Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] =
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
&[SyscallRegistryEntry::builder(Syscall::BankInfo, "bank", "info")
|
entry(
|
||||||
.args(1)
|
Syscall::BankInfo,
|
||||||
.rets(2)
|
"bank",
|
||||||
.caps(caps::BANK)];
|
"info",
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
caps::BANK,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::BankSlotInfo,
|
||||||
|
"bank",
|
||||||
|
"slot_info",
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
caps::BANK,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
|
||||||
SyscallRegistryEntry::builder(Syscall::ComposerBindScene, "composer", "bind_scene")
|
|
||||||
.args(1)
|
|
||||||
.rets(1)
|
|
||||||
.caps(caps::COMPOSER)
|
|
||||||
.cost(5),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::ComposerUnbindScene, "composer", "unbind_scene")
|
|
||||||
.rets(1)
|
|
||||||
.caps(caps::COMPOSER)
|
|
||||||
.cost(2),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::ComposerSetCamera, "composer", "set_camera")
|
|
||||||
.args(2)
|
|
||||||
.caps(caps::COMPOSER)
|
|
||||||
.cost(2),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::ComposerEmitSprite, "composer", "emit_sprite")
|
|
||||||
.args(9)
|
|
||||||
.rets(1)
|
|
||||||
.caps(caps::COMPOSER)
|
|
||||||
.cost(5),
|
|
||||||
];
|
|
||||||
@@ -1,68 +1,150 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use super::entry;
|
||||||
|
use crate::syscalls::{Determinism, Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
SyscallRegistryEntry::builder(Syscall::FsOpen, "fs", "open")
|
entry(
|
||||||
.args(1)
|
Syscall::FsOpen,
|
||||||
.rets(1)
|
"fs",
|
||||||
.caps(caps::FS)
|
"open",
|
||||||
.non_deterministic()
|
1,
|
||||||
.cost(20),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::FsRead, "fs", "read")
|
1,
|
||||||
.args(1)
|
caps::FS,
|
||||||
.rets(1)
|
Determinism::NonDeterministic,
|
||||||
.caps(caps::FS)
|
false,
|
||||||
.non_deterministic()
|
20,
|
||||||
.cost(20),
|
),
|
||||||
SyscallRegistryEntry::builder(Syscall::FsWrite, "fs", "write")
|
entry(
|
||||||
.args(2)
|
Syscall::FsRead,
|
||||||
.rets(1)
|
"fs",
|
||||||
.caps(caps::FS)
|
"read",
|
||||||
.non_deterministic()
|
1,
|
||||||
.cost(20),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::FsClose, "fs", "close").args(1).caps(caps::FS).cost(5),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::FsListDir, "fs", "list_dir")
|
caps::FS,
|
||||||
.args(1)
|
Determinism::NonDeterministic,
|
||||||
.rets(1)
|
false,
|
||||||
.caps(caps::FS)
|
20,
|
||||||
.non_deterministic()
|
),
|
||||||
.cost(20),
|
entry(
|
||||||
SyscallRegistryEntry::builder(Syscall::FsExists, "fs", "exists").args(1).rets(1).caps(caps::FS),
|
Syscall::FsWrite,
|
||||||
SyscallRegistryEntry::builder(Syscall::FsDelete, "fs", "delete")
|
"fs",
|
||||||
.args(1)
|
"write",
|
||||||
.caps(caps::FS)
|
1,
|
||||||
.non_deterministic()
|
2,
|
||||||
.cost(20),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::MemSlotCount, "mem", "slot_count")
|
caps::FS,
|
||||||
.rets(2)
|
Determinism::NonDeterministic,
|
||||||
.caps(caps::FS),
|
false,
|
||||||
SyscallRegistryEntry::builder(Syscall::MemSlotStat, "mem", "slot_stat")
|
20,
|
||||||
.args(1)
|
),
|
||||||
.rets(5)
|
entry(Syscall::FsClose, "fs", "close", 1, 1, 0, caps::FS, Determinism::Deterministic, false, 5),
|
||||||
.caps(caps::FS)
|
entry(
|
||||||
.non_deterministic()
|
Syscall::FsListDir,
|
||||||
.cost(5),
|
"fs",
|
||||||
SyscallRegistryEntry::builder(Syscall::MemSlotRead, "mem", "slot_read")
|
"list_dir",
|
||||||
.args(3)
|
1,
|
||||||
.rets(3)
|
1,
|
||||||
.caps(caps::FS)
|
1,
|
||||||
.non_deterministic()
|
caps::FS,
|
||||||
.cost(20),
|
Determinism::NonDeterministic,
|
||||||
SyscallRegistryEntry::builder(Syscall::MemSlotWrite, "mem", "slot_write")
|
false,
|
||||||
.args(3)
|
20,
|
||||||
.rets(2)
|
),
|
||||||
.caps(caps::FS)
|
entry(
|
||||||
.non_deterministic()
|
Syscall::FsExists,
|
||||||
.cost(20),
|
"fs",
|
||||||
SyscallRegistryEntry::builder(Syscall::MemSlotCommit, "mem", "slot_commit")
|
"exists",
|
||||||
.args(1)
|
1,
|
||||||
.rets(1)
|
1,
|
||||||
.caps(caps::FS)
|
1,
|
||||||
.non_deterministic()
|
caps::FS,
|
||||||
.cost(20),
|
Determinism::Deterministic,
|
||||||
SyscallRegistryEntry::builder(Syscall::MemSlotClear, "mem", "slot_clear")
|
false,
|
||||||
.args(1)
|
1,
|
||||||
.rets(1)
|
),
|
||||||
.caps(caps::FS)
|
entry(
|
||||||
.non_deterministic()
|
Syscall::FsDelete,
|
||||||
.cost(20),
|
"fs",
|
||||||
|
"delete",
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
caps::FS,
|
||||||
|
Determinism::NonDeterministic,
|
||||||
|
false,
|
||||||
|
20,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::MemSlotCount,
|
||||||
|
"mem",
|
||||||
|
"slot_count",
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
2,
|
||||||
|
caps::FS,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::MemSlotStat,
|
||||||
|
"mem",
|
||||||
|
"slot_stat",
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
5,
|
||||||
|
caps::FS,
|
||||||
|
Determinism::NonDeterministic,
|
||||||
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::MemSlotRead,
|
||||||
|
"mem",
|
||||||
|
"slot_read",
|
||||||
|
1,
|
||||||
|
3,
|
||||||
|
3,
|
||||||
|
caps::FS,
|
||||||
|
Determinism::NonDeterministic,
|
||||||
|
false,
|
||||||
|
20,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::MemSlotWrite,
|
||||||
|
"mem",
|
||||||
|
"slot_write",
|
||||||
|
1,
|
||||||
|
3,
|
||||||
|
2,
|
||||||
|
caps::FS,
|
||||||
|
Determinism::NonDeterministic,
|
||||||
|
false,
|
||||||
|
20,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::MemSlotCommit,
|
||||||
|
"mem",
|
||||||
|
"slot_commit",
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
caps::FS,
|
||||||
|
Determinism::NonDeterministic,
|
||||||
|
false,
|
||||||
|
20,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::MemSlotClear,
|
||||||
|
"mem",
|
||||||
|
"slot_clear",
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
caps::FS,
|
||||||
|
Determinism::NonDeterministic,
|
||||||
|
false,
|
||||||
|
20,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,32 +1,113 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use super::entry;
|
||||||
|
use crate::syscalls::{Determinism, Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxClear, "gfx2d", "clear")
|
entry(
|
||||||
.args(1)
|
Syscall::GfxClear,
|
||||||
.caps(caps::GFX2D)
|
"gfx",
|
||||||
.cost(20),
|
"clear",
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxFillRect, "gfx2d", "fill_rect")
|
1,
|
||||||
.args(5)
|
1,
|
||||||
.caps(caps::GFX2D)
|
0,
|
||||||
.cost(20),
|
caps::GFX,
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawLine, "gfx2d", "draw_line")
|
Determinism::Deterministic,
|
||||||
.args(5)
|
false,
|
||||||
.caps(caps::GFX2D)
|
20,
|
||||||
.cost(5),
|
),
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawCircle, "gfx2d", "draw_circle")
|
entry(
|
||||||
.args(4)
|
Syscall::GfxFillRect,
|
||||||
.caps(caps::GFX2D)
|
"gfx",
|
||||||
.cost(5),
|
"fill_rect",
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawDisc, "gfx2d", "draw_disc")
|
1,
|
||||||
.args(5)
|
5,
|
||||||
.caps(caps::GFX2D)
|
0,
|
||||||
.cost(5),
|
caps::GFX,
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawSquare, "gfx2d", "draw_square")
|
Determinism::Deterministic,
|
||||||
.args(6)
|
false,
|
||||||
.caps(caps::GFX2D)
|
20,
|
||||||
.cost(5),
|
),
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawText, "gfx2d", "draw_text")
|
entry(
|
||||||
.args(4)
|
Syscall::GfxDrawLine,
|
||||||
.caps(caps::GFX2D)
|
"gfx",
|
||||||
.cost(20),
|
"draw_line",
|
||||||
|
1,
|
||||||
|
5,
|
||||||
|
0,
|
||||||
|
caps::GFX,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::GfxDrawCircle,
|
||||||
|
"gfx",
|
||||||
|
"draw_circle",
|
||||||
|
1,
|
||||||
|
4,
|
||||||
|
0,
|
||||||
|
caps::GFX,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::GfxDrawDisc,
|
||||||
|
"gfx",
|
||||||
|
"draw_disc",
|
||||||
|
1,
|
||||||
|
5,
|
||||||
|
0,
|
||||||
|
caps::GFX,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::GfxDrawSquare,
|
||||||
|
"gfx",
|
||||||
|
"draw_square",
|
||||||
|
1,
|
||||||
|
6,
|
||||||
|
0,
|
||||||
|
caps::GFX,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::GfxSetSprite,
|
||||||
|
"gfx",
|
||||||
|
"set_sprite",
|
||||||
|
1,
|
||||||
|
10,
|
||||||
|
1,
|
||||||
|
caps::GFX,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::GfxDrawText,
|
||||||
|
"gfx",
|
||||||
|
"draw_text",
|
||||||
|
1,
|
||||||
|
4,
|
||||||
|
0,
|
||||||
|
caps::GFX,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
20,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::GfxClear565,
|
||||||
|
"gfx",
|
||||||
|
"clear_565",
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
caps::GFX,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
20,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxUiClear, "gfxui", "clear")
|
|
||||||
.args(1)
|
|
||||||
.caps(caps::GFXUI)
|
|
||||||
.cost(20),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxUiFillRect, "gfxui", "fill_rect")
|
|
||||||
.args(5)
|
|
||||||
.caps(caps::GFXUI)
|
|
||||||
.cost(20),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawLine, "gfxui", "draw_line")
|
|
||||||
.args(5)
|
|
||||||
.caps(caps::GFXUI)
|
|
||||||
.cost(5),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawCircle, "gfxui", "draw_circle")
|
|
||||||
.args(4)
|
|
||||||
.caps(caps::GFXUI)
|
|
||||||
.cost(5),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawDisc, "gfxui", "draw_disc")
|
|
||||||
.args(5)
|
|
||||||
.caps(caps::GFXUI)
|
|
||||||
.cost(5),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawSquare, "gfxui", "draw_square")
|
|
||||||
.args(6)
|
|
||||||
.caps(caps::GFXUI)
|
|
||||||
.cost(5),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawText, "gfxui", "draw_text")
|
|
||||||
.args(4)
|
|
||||||
.caps(caps::GFXUI)
|
|
||||||
.cost(20),
|
|
||||||
];
|
|
||||||
@@ -1,14 +1,29 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use super::entry;
|
||||||
|
use crate::syscalls::{Determinism, Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
SyscallRegistryEntry::builder(Syscall::LogWrite, "log", "write")
|
entry(
|
||||||
.args(2)
|
Syscall::LogWrite,
|
||||||
.caps(caps::LOG)
|
"log",
|
||||||
.non_deterministic()
|
"write",
|
||||||
.cost(5),
|
1,
|
||||||
SyscallRegistryEntry::builder(Syscall::LogWriteTag, "log", "write_tag")
|
2,
|
||||||
.args(3)
|
0,
|
||||||
.caps(caps::LOG)
|
caps::LOG,
|
||||||
.non_deterministic()
|
Determinism::NonDeterministic,
|
||||||
.cost(5),
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::LogWriteTag,
|
||||||
|
"log",
|
||||||
|
"write_tag",
|
||||||
|
1,
|
||||||
|
3,
|
||||||
|
0,
|
||||||
|
caps::LOG,
|
||||||
|
Determinism::NonDeterministic,
|
||||||
|
false,
|
||||||
|
5,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,21 +1,46 @@
|
|||||||
mod asset;
|
mod asset;
|
||||||
mod audio;
|
mod audio;
|
||||||
mod bank;
|
mod bank;
|
||||||
mod composer;
|
|
||||||
mod fs;
|
mod fs;
|
||||||
mod gfx;
|
mod gfx;
|
||||||
mod gfxui;
|
|
||||||
mod log;
|
mod log;
|
||||||
mod system;
|
mod system;
|
||||||
|
|
||||||
use super::SyscallRegistryEntry;
|
use super::{CapFlags, Determinism, Syscall, SyscallMeta, SyscallRegistryEntry};
|
||||||
|
|
||||||
|
pub(crate) const fn entry(
|
||||||
|
syscall: Syscall,
|
||||||
|
module: &'static str,
|
||||||
|
name: &'static str,
|
||||||
|
version: u16,
|
||||||
|
arg_slots: u8,
|
||||||
|
ret_slots: u16,
|
||||||
|
caps: CapFlags,
|
||||||
|
determinism: Determinism,
|
||||||
|
may_allocate: bool,
|
||||||
|
cost_hint: u32,
|
||||||
|
) -> SyscallRegistryEntry {
|
||||||
|
SyscallRegistryEntry {
|
||||||
|
syscall,
|
||||||
|
meta: SyscallMeta {
|
||||||
|
id: syscall as u32,
|
||||||
|
module,
|
||||||
|
name,
|
||||||
|
version,
|
||||||
|
arg_slots,
|
||||||
|
ret_slots,
|
||||||
|
caps,
|
||||||
|
determinism,
|
||||||
|
may_allocate,
|
||||||
|
cost_hint,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn all_entries() -> impl Iterator<Item = &'static SyscallRegistryEntry> {
|
pub(crate) fn all_entries() -> impl Iterator<Item = &'static SyscallRegistryEntry> {
|
||||||
system::ENTRIES
|
system::ENTRIES
|
||||||
.iter()
|
.iter()
|
||||||
.chain(gfx::ENTRIES.iter())
|
.chain(gfx::ENTRIES.iter())
|
||||||
.chain(gfxui::ENTRIES.iter())
|
|
||||||
.chain(composer::ENTRIES.iter())
|
|
||||||
.chain(audio::ENTRIES.iter())
|
.chain(audio::ENTRIES.iter())
|
||||||
.chain(fs::ENTRIES.iter())
|
.chain(fs::ENTRIES.iter())
|
||||||
.chain(log::ENTRIES.iter())
|
.chain(log::ENTRIES.iter())
|
||||||
|
|||||||
@@ -1,6 +1,29 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use super::entry;
|
||||||
|
use crate::syscalls::{Determinism, Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] =
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
&[SyscallRegistryEntry::builder(Syscall::SystemHasCart, "system", "has_cart")
|
entry(
|
||||||
.rets(1)
|
Syscall::SystemHasCart,
|
||||||
.caps(caps::SYSTEM)];
|
"system",
|
||||||
|
"has_cart",
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
caps::SYSTEM,
|
||||||
|
Determinism::Deterministic,
|
||||||
|
false,
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
entry(
|
||||||
|
Syscall::SystemRunCart,
|
||||||
|
"system",
|
||||||
|
"run_cart",
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
caps::SYSTEM,
|
||||||
|
Determinism::NonDeterministic,
|
||||||
|
false,
|
||||||
|
50,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|||||||
@@ -13,24 +13,16 @@ impl Syscall {
|
|||||||
pub fn from_u32(id: u32) -> Option<Self> {
|
pub fn from_u32(id: u32) -> Option<Self> {
|
||||||
match id {
|
match id {
|
||||||
0x0001 => Some(Self::SystemHasCart),
|
0x0001 => Some(Self::SystemHasCart),
|
||||||
|
0x0002 => Some(Self::SystemRunCart),
|
||||||
0x1001 => Some(Self::GfxClear),
|
0x1001 => Some(Self::GfxClear),
|
||||||
0x1002 => Some(Self::GfxFillRect),
|
0x1002 => Some(Self::GfxFillRect),
|
||||||
0x1003 => Some(Self::GfxDrawLine),
|
0x1003 => Some(Self::GfxDrawLine),
|
||||||
0x1004 => Some(Self::GfxDrawCircle),
|
0x1004 => Some(Self::GfxDrawCircle),
|
||||||
0x1005 => Some(Self::GfxDrawDisc),
|
0x1005 => Some(Self::GfxDrawDisc),
|
||||||
0x1006 => Some(Self::GfxDrawSquare),
|
0x1006 => Some(Self::GfxDrawSquare),
|
||||||
|
0x1007 => Some(Self::GfxSetSprite),
|
||||||
0x1008 => Some(Self::GfxDrawText),
|
0x1008 => Some(Self::GfxDrawText),
|
||||||
0x1201 => Some(Self::GfxUiClear),
|
0x1010 => Some(Self::GfxClear565),
|
||||||
0x1202 => Some(Self::GfxUiFillRect),
|
|
||||||
0x1203 => Some(Self::GfxUiDrawLine),
|
|
||||||
0x1204 => Some(Self::GfxUiDrawCircle),
|
|
||||||
0x1205 => Some(Self::GfxUiDrawDisc),
|
|
||||||
0x1206 => Some(Self::GfxUiDrawSquare),
|
|
||||||
0x1208 => Some(Self::GfxUiDrawText),
|
|
||||||
0x1101 => Some(Self::ComposerBindScene),
|
|
||||||
0x1102 => Some(Self::ComposerUnbindScene),
|
|
||||||
0x1103 => Some(Self::ComposerSetCamera),
|
|
||||||
0x1104 => Some(Self::ComposerEmitSprite),
|
|
||||||
0x3001 => Some(Self::AudioPlaySample),
|
0x3001 => Some(Self::AudioPlaySample),
|
||||||
0x3002 => Some(Self::AudioPlay),
|
0x3002 => Some(Self::AudioPlay),
|
||||||
0x4001 => Some(Self::FsOpen),
|
0x4001 => Some(Self::FsOpen),
|
||||||
@@ -52,13 +44,8 @@ impl Syscall {
|
|||||||
0x6002 => Some(Self::AssetStatus),
|
0x6002 => Some(Self::AssetStatus),
|
||||||
0x6003 => Some(Self::AssetCommit),
|
0x6003 => Some(Self::AssetCommit),
|
||||||
0x6004 => Some(Self::AssetCancel),
|
0x6004 => Some(Self::AssetCancel),
|
||||||
0x6005 => Some(Self::AssetBacklogInfo),
|
|
||||||
0x6006 => Some(Self::AssetBacklogPosition),
|
|
||||||
0x6007 => Some(Self::AssetBacklogMove),
|
|
||||||
0x6008 => Some(Self::AssetBacklogPromote),
|
|
||||||
0x6009 => Some(Self::AssetBacklogDemote),
|
|
||||||
0x600A => Some(Self::AssetTargetStatus),
|
|
||||||
0x6101 => Some(Self::BankInfo),
|
0x6101 => Some(Self::BankInfo),
|
||||||
|
0x6102 => Some(Self::BankSlotInfo),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,24 +61,16 @@ impl Syscall {
|
|||||||
pub fn name(&self) -> &'static str {
|
pub fn name(&self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Self::SystemHasCart => "SystemHasCart",
|
Self::SystemHasCart => "SystemHasCart",
|
||||||
|
Self::SystemRunCart => "SystemRunCart",
|
||||||
Self::GfxClear => "GfxClear",
|
Self::GfxClear => "GfxClear",
|
||||||
Self::GfxFillRect => "GfxFillRect",
|
Self::GfxFillRect => "GfxFillRect",
|
||||||
Self::GfxDrawLine => "GfxDrawLine",
|
Self::GfxDrawLine => "GfxDrawLine",
|
||||||
Self::GfxDrawCircle => "GfxDrawCircle",
|
Self::GfxDrawCircle => "GfxDrawCircle",
|
||||||
Self::GfxDrawDisc => "GfxDrawDisc",
|
Self::GfxDrawDisc => "GfxDrawDisc",
|
||||||
Self::GfxDrawSquare => "GfxDrawSquare",
|
Self::GfxDrawSquare => "GfxDrawSquare",
|
||||||
|
Self::GfxSetSprite => "GfxSetSprite",
|
||||||
Self::GfxDrawText => "GfxDrawText",
|
Self::GfxDrawText => "GfxDrawText",
|
||||||
Self::GfxUiClear => "GfxUiClear",
|
Self::GfxClear565 => "GfxClear565",
|
||||||
Self::GfxUiFillRect => "GfxUiFillRect",
|
|
||||||
Self::GfxUiDrawLine => "GfxUiDrawLine",
|
|
||||||
Self::GfxUiDrawCircle => "GfxUiDrawCircle",
|
|
||||||
Self::GfxUiDrawDisc => "GfxUiDrawDisc",
|
|
||||||
Self::GfxUiDrawSquare => "GfxUiDrawSquare",
|
|
||||||
Self::GfxUiDrawText => "GfxUiDrawText",
|
|
||||||
Self::ComposerBindScene => "ComposerBindScene",
|
|
||||||
Self::ComposerUnbindScene => "ComposerUnbindScene",
|
|
||||||
Self::ComposerSetCamera => "ComposerSetCamera",
|
|
||||||
Self::ComposerEmitSprite => "ComposerEmitSprite",
|
|
||||||
Self::AudioPlaySample => "AudioPlaySample",
|
Self::AudioPlaySample => "AudioPlaySample",
|
||||||
Self::AudioPlay => "AudioPlay",
|
Self::AudioPlay => "AudioPlay",
|
||||||
Self::FsOpen => "FsOpen",
|
Self::FsOpen => "FsOpen",
|
||||||
@@ -113,13 +92,8 @@ impl Syscall {
|
|||||||
Self::AssetStatus => "AssetStatus",
|
Self::AssetStatus => "AssetStatus",
|
||||||
Self::AssetCommit => "AssetCommit",
|
Self::AssetCommit => "AssetCommit",
|
||||||
Self::AssetCancel => "AssetCancel",
|
Self::AssetCancel => "AssetCancel",
|
||||||
Self::AssetBacklogInfo => "AssetBacklogInfo",
|
|
||||||
Self::AssetBacklogPosition => "AssetBacklogPosition",
|
|
||||||
Self::AssetBacklogMove => "AssetBacklogMove",
|
|
||||||
Self::AssetBacklogPromote => "AssetBacklogPromote",
|
|
||||||
Self::AssetBacklogDemote => "AssetBacklogDemote",
|
|
||||||
Self::AssetTargetStatus => "AssetTargetStatus",
|
|
||||||
Self::BankInfo => "BankInfo",
|
Self::BankInfo => "BankInfo",
|
||||||
|
Self::BankSlotInfo => "BankSlotInfo",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,23 +39,23 @@ fn every_syscall_has_metadata() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolver_returns_expected_id_for_known_identity() {
|
fn resolver_returns_expected_id_for_known_identity() {
|
||||||
let id = resolve_syscall("gfx2d", "clear", 1).expect("known identity must resolve");
|
let id = resolve_syscall("gfx", "clear", 1).expect("known identity must resolve");
|
||||||
assert_eq!(id.id, 0x1001);
|
assert_eq!(id.id, 0x1001);
|
||||||
assert_eq!(id.meta.module, "gfx2d");
|
assert_eq!(id.meta.module, "gfx");
|
||||||
assert_eq!(id.meta.name, "clear");
|
assert_eq!(id.meta.name, "clear");
|
||||||
assert_eq!(id.meta.version, 1);
|
assert_eq!(id.meta.version, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolver_rejects_unknown_identity() {
|
fn resolver_rejects_unknown_identity() {
|
||||||
let res = resolve_syscall("gfx2d", "nonexistent", 1);
|
let res = resolve_syscall("gfx", "nonexistent", 1);
|
||||||
assert!(res.is_none());
|
assert!(res.is_none());
|
||||||
|
|
||||||
let requested = [SyscallIdentity { module: "gfx2d", name: "nonexistent", version: 1 }];
|
let requested = [SyscallIdentity { module: "gfx", name: "nonexistent", version: 1 }];
|
||||||
let err = resolve_program_syscalls(&requested, 0).unwrap_err();
|
let err = resolve_program_syscalls(&requested, 0).unwrap_err();
|
||||||
match err {
|
match err {
|
||||||
LoadError::UnknownSyscall { module, name, version } => {
|
LoadError::UnknownSyscall { module, name, version } => {
|
||||||
assert_eq!(module, "gfx2d");
|
assert_eq!(module, "gfx");
|
||||||
assert_eq!(name, "nonexistent");
|
assert_eq!(name, "nonexistent");
|
||||||
assert_eq!(version, 1);
|
assert_eq!(version, 1);
|
||||||
}
|
}
|
||||||
@@ -63,49 +63,13 @@ fn resolver_rejects_unknown_identity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolver_rejects_removed_legacy_gfx_set_sprite_identity() {
|
|
||||||
assert!(resolve_syscall("gfx2d", "set_sprite", 1).is_none());
|
|
||||||
|
|
||||||
let requested = [SyscallIdentity { module: "gfx2d", name: "set_sprite", version: 1 }];
|
|
||||||
let err = resolve_program_syscalls(&requested, caps::ALL).unwrap_err();
|
|
||||||
assert_eq!(err, LoadError::UnknownSyscall { module: "gfx2d", name: "set_sprite", version: 1 });
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolver_rejects_userland_system_run_cart_identity() {
|
|
||||||
assert!(Syscall::from_u32(0x0002).is_none());
|
|
||||||
assert!(resolve_syscall("system", "run_cart", 1).is_none());
|
|
||||||
|
|
||||||
let requested = [SyscallIdentity { module: "system", name: "run_cart", version: 1 }];
|
|
||||||
let err = resolve_program_syscalls(&requested, caps::ALL).unwrap_err();
|
|
||||||
assert_eq!(err, LoadError::UnknownSyscall { module: "system", name: "run_cart", version: 1 });
|
|
||||||
|
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
|
||||||
module: "system".into(),
|
|
||||||
name: "run_cart".into(),
|
|
||||||
version: 1,
|
|
||||||
arg_slots: 0,
|
|
||||||
ret_slots: 0,
|
|
||||||
}];
|
|
||||||
let err = resolve_declared_program_syscalls(&declared, caps::ALL).unwrap_err();
|
|
||||||
assert_eq!(
|
|
||||||
err,
|
|
||||||
DeclaredLoadError::UnknownSyscall {
|
|
||||||
module: "system".into(),
|
|
||||||
name: "run_cart".into(),
|
|
||||||
version: 1,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolver_enforces_capabilities() {
|
fn resolver_enforces_capabilities() {
|
||||||
let requested = [SyscallIdentity { module: "gfx2d", name: "clear", version: 1 }];
|
let requested = [SyscallIdentity { module: "gfx", name: "clear", version: 1 }];
|
||||||
let err = resolve_program_syscalls(&requested, 0).unwrap_err();
|
let err = resolve_program_syscalls(&requested, 0).unwrap_err();
|
||||||
match err {
|
match err {
|
||||||
LoadError::MissingCapability { required, provided, module, name, version } => {
|
LoadError::MissingCapability { required, provided, module, name, version } => {
|
||||||
assert_eq!(module, "gfx2d");
|
assert_eq!(module, "gfx");
|
||||||
assert_eq!(name, "clear");
|
assert_eq!(name, "clear");
|
||||||
assert_eq!(version, 1);
|
assert_eq!(version, 1);
|
||||||
assert_ne!(required, 0);
|
assert_ne!(required, 0);
|
||||||
@@ -114,30 +78,15 @@ fn resolver_enforces_capabilities() {
|
|||||||
_ => panic!("expected MissingCapability error"),
|
_ => panic!("expected MissingCapability error"),
|
||||||
}
|
}
|
||||||
|
|
||||||
let ok = resolve_program_syscalls(&requested, caps::GFX2D).expect("must resolve with caps");
|
let ok = resolve_program_syscalls(&requested, caps::GFX).expect("must resolve with caps");
|
||||||
assert_eq!(ok.len(), 1);
|
assert_eq!(ok.len(), 1);
|
||||||
assert_eq!(ok[0].id, 0x1001);
|
assert_eq!(ok[0].id, 0x1001);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolver_exposes_split_render_capabilities() {
|
|
||||||
let composer = resolve_syscall("composer", "bind_scene", 1).expect("composer resolves");
|
|
||||||
assert_eq!(composer.meta.caps, caps::COMPOSER);
|
|
||||||
|
|
||||||
let gfx2d = resolve_syscall("gfx2d", "clear", 1).expect("gfx2d resolves");
|
|
||||||
assert_eq!(gfx2d.meta.caps, caps::GFX2D);
|
|
||||||
|
|
||||||
let gfxui = resolve_syscall("gfxui", "clear", 1).expect("gfxui resolves");
|
|
||||||
assert_eq!(gfxui.id, 0x1201);
|
|
||||||
assert_eq!(gfxui.meta.caps, caps::GFXUI);
|
|
||||||
|
|
||||||
assert!(resolve_syscall("gfx", "clear", 1).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_returns_expected_id_for_known_identity() {
|
fn declared_resolver_returns_expected_id_for_known_identity() {
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
module: "gfx2d".into(),
|
module: "gfx".into(),
|
||||||
name: "clear".into(),
|
name: "clear".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 1,
|
arg_slots: 1,
|
||||||
@@ -145,7 +94,7 @@ fn declared_resolver_returns_expected_id_for_known_identity() {
|
|||||||
}];
|
}];
|
||||||
|
|
||||||
let ok =
|
let ok =
|
||||||
resolve_declared_program_syscalls(&declared, caps::GFX2D).expect("must resolve with ABI");
|
resolve_declared_program_syscalls(&declared, caps::GFX).expect("must resolve with ABI");
|
||||||
assert_eq!(ok.len(), 1);
|
assert_eq!(ok.len(), 1);
|
||||||
assert_eq!(ok[0].id, 0x1001);
|
assert_eq!(ok[0].id, 0x1001);
|
||||||
}
|
}
|
||||||
@@ -153,18 +102,18 @@ fn declared_resolver_returns_expected_id_for_known_identity() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_rejects_unknown_identity() {
|
fn declared_resolver_rejects_unknown_identity() {
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
module: "gfx2d".into(),
|
module: "gfx".into(),
|
||||||
name: "nonexistent".into(),
|
name: "nonexistent".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 1,
|
arg_slots: 1,
|
||||||
ret_slots: 0,
|
ret_slots: 0,
|
||||||
}];
|
}];
|
||||||
|
|
||||||
let err = resolve_declared_program_syscalls(&declared, caps::GFX2D).unwrap_err();
|
let err = resolve_declared_program_syscalls(&declared, caps::GFX).unwrap_err();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
err,
|
err,
|
||||||
DeclaredLoadError::UnknownSyscall {
|
DeclaredLoadError::UnknownSyscall {
|
||||||
module: "gfx2d".into(),
|
module: "gfx".into(),
|
||||||
name: "nonexistent".into(),
|
name: "nonexistent".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
}
|
}
|
||||||
@@ -174,7 +123,7 @@ fn declared_resolver_rejects_unknown_identity() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_rejects_missing_capability() {
|
fn declared_resolver_rejects_missing_capability() {
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
module: "gfx2d".into(),
|
module: "gfx".into(),
|
||||||
name: "clear".into(),
|
name: "clear".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 1,
|
arg_slots: 1,
|
||||||
@@ -185,9 +134,9 @@ fn declared_resolver_rejects_missing_capability() {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
err,
|
err,
|
||||||
DeclaredLoadError::MissingCapability {
|
DeclaredLoadError::MissingCapability {
|
||||||
required: caps::GFX2D,
|
required: caps::GFX,
|
||||||
provided: caps::NONE,
|
provided: caps::NONE,
|
||||||
module: "gfx2d".into(),
|
module: "gfx".into(),
|
||||||
name: "clear".into(),
|
name: "clear".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
}
|
}
|
||||||
@@ -197,18 +146,18 @@ fn declared_resolver_rejects_missing_capability() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_rejects_abi_mismatch() {
|
fn declared_resolver_rejects_abi_mismatch() {
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
module: "gfx2d".into(),
|
module: "gfx".into(),
|
||||||
name: "draw_line".into(),
|
name: "draw_line".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 4,
|
arg_slots: 4,
|
||||||
ret_slots: 0,
|
ret_slots: 0,
|
||||||
}];
|
}];
|
||||||
|
|
||||||
let err = resolve_declared_program_syscalls(&declared, caps::GFX2D).unwrap_err();
|
let err = resolve_declared_program_syscalls(&declared, caps::GFX).unwrap_err();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
err,
|
err,
|
||||||
DeclaredLoadError::AbiMismatch {
|
DeclaredLoadError::AbiMismatch {
|
||||||
module: "gfx2d".into(),
|
module: "gfx".into(),
|
||||||
name: "draw_line".into(),
|
name: "draw_line".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
declared_arg_slots: 4,
|
declared_arg_slots: 4,
|
||||||
@@ -245,25 +194,17 @@ fn status_first_syscall_signatures_are_pinned() {
|
|||||||
assert_eq!(draw_square.arg_slots, 6);
|
assert_eq!(draw_square.arg_slots, 6);
|
||||||
assert_eq!(draw_square.ret_slots, 0);
|
assert_eq!(draw_square.ret_slots, 0);
|
||||||
|
|
||||||
|
let set_sprite = meta_for(Syscall::GfxSetSprite);
|
||||||
|
assert_eq!(set_sprite.arg_slots, 10);
|
||||||
|
assert_eq!(set_sprite.ret_slots, 1);
|
||||||
|
|
||||||
let draw_text = meta_for(Syscall::GfxDrawText);
|
let draw_text = meta_for(Syscall::GfxDrawText);
|
||||||
assert_eq!(draw_text.arg_slots, 4);
|
assert_eq!(draw_text.arg_slots, 4);
|
||||||
assert_eq!(draw_text.ret_slots, 0);
|
assert_eq!(draw_text.ret_slots, 0);
|
||||||
|
|
||||||
let bind_scene = meta_for(Syscall::ComposerBindScene);
|
let clear_565 = meta_for(Syscall::GfxClear565);
|
||||||
assert_eq!(bind_scene.arg_slots, 1);
|
assert_eq!(clear_565.arg_slots, 1);
|
||||||
assert_eq!(bind_scene.ret_slots, 1);
|
assert_eq!(clear_565.ret_slots, 0);
|
||||||
|
|
||||||
let unbind_scene = meta_for(Syscall::ComposerUnbindScene);
|
|
||||||
assert_eq!(unbind_scene.arg_slots, 0);
|
|
||||||
assert_eq!(unbind_scene.ret_slots, 1);
|
|
||||||
|
|
||||||
let set_camera = meta_for(Syscall::ComposerSetCamera);
|
|
||||||
assert_eq!(set_camera.arg_slots, 2);
|
|
||||||
assert_eq!(set_camera.ret_slots, 0);
|
|
||||||
|
|
||||||
let emit_sprite = meta_for(Syscall::ComposerEmitSprite);
|
|
||||||
assert_eq!(emit_sprite.arg_slots, 9);
|
|
||||||
assert_eq!(emit_sprite.ret_slots, 1);
|
|
||||||
|
|
||||||
let audio_play_sample = meta_for(Syscall::AudioPlaySample);
|
let audio_play_sample = meta_for(Syscall::AudioPlaySample);
|
||||||
assert_eq!(audio_play_sample.arg_slots, 5);
|
assert_eq!(audio_play_sample.arg_slots, 5);
|
||||||
@@ -284,53 +225,16 @@ fn status_first_syscall_signatures_are_pinned() {
|
|||||||
let asset_cancel = meta_for(Syscall::AssetCancel);
|
let asset_cancel = meta_for(Syscall::AssetCancel);
|
||||||
assert_eq!(asset_cancel.arg_slots, 1);
|
assert_eq!(asset_cancel.arg_slots, 1);
|
||||||
assert_eq!(asset_cancel.ret_slots, 1);
|
assert_eq!(asset_cancel.ret_slots, 1);
|
||||||
|
|
||||||
let asset_backlog_info = meta_for(Syscall::AssetBacklogInfo);
|
|
||||||
assert_eq!(asset_backlog_info.arg_slots, 0);
|
|
||||||
assert_eq!(asset_backlog_info.ret_slots, 7);
|
|
||||||
|
|
||||||
let asset_backlog_position = meta_for(Syscall::AssetBacklogPosition);
|
|
||||||
assert_eq!(asset_backlog_position.arg_slots, 1);
|
|
||||||
assert_eq!(asset_backlog_position.ret_slots, 4);
|
|
||||||
|
|
||||||
let asset_backlog_move = meta_for(Syscall::AssetBacklogMove);
|
|
||||||
assert_eq!(asset_backlog_move.arg_slots, 2);
|
|
||||||
assert_eq!(asset_backlog_move.ret_slots, 1);
|
|
||||||
|
|
||||||
let asset_backlog_promote = meta_for(Syscall::AssetBacklogPromote);
|
|
||||||
assert_eq!(asset_backlog_promote.arg_slots, 1);
|
|
||||||
assert_eq!(asset_backlog_promote.ret_slots, 1);
|
|
||||||
|
|
||||||
let asset_backlog_demote = meta_for(Syscall::AssetBacklogDemote);
|
|
||||||
assert_eq!(asset_backlog_demote.arg_slots, 1);
|
|
||||||
assert_eq!(asset_backlog_demote.ret_slots, 1);
|
|
||||||
|
|
||||||
let asset_target_status = meta_for(Syscall::AssetTargetStatus);
|
|
||||||
assert_eq!(asset_target_status.arg_slots, 2);
|
|
||||||
assert_eq!(asset_target_status.ret_slots, 6);
|
|
||||||
|
|
||||||
let bank_info = meta_for(Syscall::BankInfo);
|
|
||||||
assert_eq!(bank_info.arg_slots, 1);
|
|
||||||
assert_eq!(bank_info.ret_slots, 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolver_rejects_removed_bank_slot_info_identity() {
|
|
||||||
assert!(resolve_syscall("bank", "slot_info", 1).is_none());
|
|
||||||
|
|
||||||
let requested = [SyscallIdentity { module: "bank", name: "slot_info", version: 1 }];
|
|
||||||
let err = resolve_program_syscalls(&requested, caps::ALL).unwrap_err();
|
|
||||||
assert_eq!(err, LoadError::UnknownSyscall { module: "bank", name: "slot_info", version: 1 });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_rejects_legacy_status_first_signatures() {
|
fn declared_resolver_rejects_legacy_status_first_signatures() {
|
||||||
let declared = vec![
|
let declared = vec![
|
||||||
prometeu_bytecode::SyscallDecl {
|
prometeu_bytecode::SyscallDecl {
|
||||||
module: "composer".into(),
|
module: "gfx".into(),
|
||||||
name: "bind_scene".into(),
|
name: "set_sprite".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 1,
|
arg_slots: 10,
|
||||||
ret_slots: 0,
|
ret_slots: 0,
|
||||||
},
|
},
|
||||||
prometeu_bytecode::SyscallDecl {
|
prometeu_bytecode::SyscallDecl {
|
||||||
@@ -402,24 +306,10 @@ fn declared_resolver_rejects_legacy_status_first_signatures() {
|
|||||||
fn declared_resolver_accepts_mixed_status_first_surface_as_a_single_module() {
|
fn declared_resolver_accepts_mixed_status_first_surface_as_a_single_module() {
|
||||||
let declared = vec![
|
let declared = vec![
|
||||||
prometeu_bytecode::SyscallDecl {
|
prometeu_bytecode::SyscallDecl {
|
||||||
module: "composer".into(),
|
module: "gfx".into(),
|
||||||
name: "bind_scene".into(),
|
name: "set_sprite".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 1,
|
arg_slots: 10,
|
||||||
ret_slots: 1,
|
|
||||||
},
|
|
||||||
prometeu_bytecode::SyscallDecl {
|
|
||||||
module: "composer".into(),
|
|
||||||
name: "unbind_scene".into(),
|
|
||||||
version: 1,
|
|
||||||
arg_slots: 0,
|
|
||||||
ret_slots: 1,
|
|
||||||
},
|
|
||||||
prometeu_bytecode::SyscallDecl {
|
|
||||||
module: "composer".into(),
|
|
||||||
name: "emit_sprite".into(),
|
|
||||||
version: 1,
|
|
||||||
arg_slots: 9,
|
|
||||||
ret_slots: 1,
|
ret_slots: 1,
|
||||||
},
|
},
|
||||||
prometeu_bytecode::SyscallDecl {
|
prometeu_bytecode::SyscallDecl {
|
||||||
@@ -446,16 +336,14 @@ fn declared_resolver_accepts_mixed_status_first_surface_as_a_single_module() {
|
|||||||
];
|
];
|
||||||
|
|
||||||
let resolved =
|
let resolved =
|
||||||
resolve_declared_program_syscalls(&declared, caps::COMPOSER | caps::AUDIO | caps::ASSET)
|
resolve_declared_program_syscalls(&declared, caps::GFX | caps::AUDIO | caps::ASSET)
|
||||||
.expect("mixed status-first surface must resolve together");
|
.expect("mixed status-first surface must resolve together");
|
||||||
|
|
||||||
assert_eq!(resolved.len(), declared.len());
|
assert_eq!(resolved.len(), declared.len());
|
||||||
assert_eq!(resolved[0].meta.ret_slots, 1);
|
assert_eq!(resolved[0].meta.ret_slots, 1);
|
||||||
assert_eq!(resolved[1].meta.ret_slots, 1);
|
assert_eq!(resolved[1].meta.ret_slots, 1);
|
||||||
assert_eq!(resolved[2].meta.ret_slots, 1);
|
assert_eq!(resolved[2].meta.ret_slots, 2);
|
||||||
assert_eq!(resolved[3].meta.ret_slots, 1);
|
assert_eq!(resolved[3].meta.ret_slots, 1);
|
||||||
assert_eq!(resolved[4].meta.ret_slots, 2);
|
|
||||||
assert_eq!(resolved[5].meta.ret_slots, 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
use crate::log::{LogLevel, LogService, LogSource};
|
use crate::log::{LogLevel, LogService, LogSource};
|
||||||
use crate::render_worker::RenderWorkerTelemetry;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Default)]
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
pub struct TelemetryFrame {
|
pub struct TelemetryFrame {
|
||||||
@@ -14,217 +11,15 @@ pub struct TelemetryFrame {
|
|||||||
pub completed_logical_frames: u32,
|
pub completed_logical_frames: u32,
|
||||||
pub violations: u32,
|
pub violations: u32,
|
||||||
|
|
||||||
// Bank telemetry
|
// GFX Banks
|
||||||
pub glyph_slots_used: u32,
|
pub gfx_used_bytes: usize,
|
||||||
pub glyph_slots_total: u32,
|
pub gfx_inflight_bytes: usize,
|
||||||
pub sound_slots_used: u32,
|
pub gfx_slots_occupied: u32,
|
||||||
pub sound_slots_total: u32,
|
|
||||||
pub scene_slots_used: u32,
|
|
||||||
pub scene_slots_total: u32,
|
|
||||||
|
|
||||||
// RAM (Heap)
|
// Audio Banks
|
||||||
pub heap_used_bytes: usize,
|
pub audio_used_bytes: usize,
|
||||||
pub heap_max_bytes: usize,
|
pub audio_inflight_bytes: usize,
|
||||||
pub vm_heap_allocations: u64,
|
pub audio_slots_occupied: u32,
|
||||||
pub vm_string_materializations: u64,
|
|
||||||
|
|
||||||
// Log Pressure from the last completed logical frame
|
|
||||||
pub logs_count: u32,
|
|
||||||
|
|
||||||
// Render handoff/presentation telemetry
|
|
||||||
pub produced_submissions: u64,
|
|
||||||
pub replaced_before_consume: u64,
|
|
||||||
pub consumed_submissions: u64,
|
|
||||||
pub published_frames: u64,
|
|
||||||
pub presented_frames: u64,
|
|
||||||
pub repeated_presents: u64,
|
|
||||||
pub render_errors: u64,
|
|
||||||
pub publish_errors: u64,
|
|
||||||
pub present_errors: u64,
|
|
||||||
pub stale_epoch_discards: u64,
|
|
||||||
pub shutdown_discards: u64,
|
|
||||||
pub shutdown_timeouts: u64,
|
|
||||||
pub worker_panics: u64,
|
|
||||||
pub last_produced_frame_id: u64,
|
|
||||||
pub last_consumed_frame_id: u64,
|
|
||||||
pub last_published_frame_id: u64,
|
|
||||||
pub last_presented_frame_id: u64,
|
|
||||||
pub last_dropped_frame_id: u64,
|
|
||||||
pub last_error_frame_id: u64,
|
|
||||||
pub active_render_epoch: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TelemetryFrame {
|
|
||||||
pub fn render_worker_telemetry(&self) -> RenderWorkerTelemetry {
|
|
||||||
RenderWorkerTelemetry {
|
|
||||||
produced_submissions: self.produced_submissions,
|
|
||||||
replaced_before_consume: self.replaced_before_consume,
|
|
||||||
consumed_submissions: self.consumed_submissions,
|
|
||||||
published_frames: self.published_frames,
|
|
||||||
presented_frames: self.presented_frames,
|
|
||||||
repeated_frames: self.repeated_presents,
|
|
||||||
stale_submission_discards: self.stale_epoch_discards,
|
|
||||||
render_failures: self.render_errors,
|
|
||||||
publish_failures: self.publish_errors,
|
|
||||||
present_failures: self.present_errors,
|
|
||||||
shutdown_timeouts: self.shutdown_timeouts,
|
|
||||||
worker_panics: self.worker_panics,
|
|
||||||
last_produced_frame_id: self.last_produced_frame_id,
|
|
||||||
last_consumed_frame_id: self.last_consumed_frame_id,
|
|
||||||
last_published_frame_id: self.last_published_frame_id,
|
|
||||||
last_presented_frame_id: self.last_presented_frame_id,
|
|
||||||
last_dropped_frame_id: self.last_dropped_frame_id,
|
|
||||||
last_error_frame_id: self.last_error_frame_id,
|
|
||||||
active_render_epoch: self.active_render_epoch,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Thread-safe, atomic telemetry storage for real-time monitoring by the host.
|
|
||||||
/// This follows the push-based model from DEC-0005 to avoid expensive scans or locks.
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct AtomicTelemetry {
|
|
||||||
pub frame_index: AtomicU64,
|
|
||||||
pub cycles_used: AtomicU64,
|
|
||||||
pub cycles_budget: AtomicU64,
|
|
||||||
pub syscalls: AtomicU32,
|
|
||||||
pub host_cpu_time_us: AtomicU64,
|
|
||||||
pub vm_steps: AtomicU32,
|
|
||||||
pub completed_logical_frames: AtomicU32,
|
|
||||||
pub violations: AtomicU32,
|
|
||||||
|
|
||||||
// Bank telemetry
|
|
||||||
pub glyph_slots_used: AtomicU32,
|
|
||||||
pub glyph_slots_total: AtomicU32,
|
|
||||||
pub sound_slots_used: AtomicU32,
|
|
||||||
pub sound_slots_total: AtomicU32,
|
|
||||||
pub scene_slots_used: AtomicU32,
|
|
||||||
pub scene_slots_total: AtomicU32,
|
|
||||||
|
|
||||||
// RAM (Heap)
|
|
||||||
pub heap_used_bytes: AtomicUsize,
|
|
||||||
pub heap_max_bytes: AtomicUsize,
|
|
||||||
pub vm_heap_allocations: AtomicU64,
|
|
||||||
pub vm_string_materializations: AtomicU64,
|
|
||||||
|
|
||||||
// Transient in-flight log counter for the current logical frame
|
|
||||||
pub current_logs_count: Arc<AtomicU32>,
|
|
||||||
// Persisted log count from the last completed logical frame
|
|
||||||
pub logs_count: AtomicU32,
|
|
||||||
|
|
||||||
// Render handoff/presentation telemetry
|
|
||||||
pub produced_submissions: AtomicU64,
|
|
||||||
pub replaced_before_consume: AtomicU64,
|
|
||||||
pub consumed_submissions: AtomicU64,
|
|
||||||
pub published_frames: AtomicU64,
|
|
||||||
pub presented_frames: AtomicU64,
|
|
||||||
pub repeated_presents: AtomicU64,
|
|
||||||
pub render_errors: AtomicU64,
|
|
||||||
pub publish_errors: AtomicU64,
|
|
||||||
pub present_errors: AtomicU64,
|
|
||||||
pub stale_epoch_discards: AtomicU64,
|
|
||||||
pub shutdown_discards: AtomicU64,
|
|
||||||
pub shutdown_timeouts: AtomicU64,
|
|
||||||
pub worker_panics: AtomicU64,
|
|
||||||
pub last_produced_frame_id: AtomicU64,
|
|
||||||
pub last_consumed_frame_id: AtomicU64,
|
|
||||||
pub last_published_frame_id: AtomicU64,
|
|
||||||
pub last_presented_frame_id: AtomicU64,
|
|
||||||
pub last_dropped_frame_id: AtomicU64,
|
|
||||||
pub last_error_frame_id: AtomicU64,
|
|
||||||
pub active_render_epoch: AtomicU64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AtomicTelemetry {
|
|
||||||
pub fn new(current_logs_count: Arc<AtomicU32>) -> Self {
|
|
||||||
Self { current_logs_count, ..Default::default() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Snapshots the current atomic state into a TelemetryFrame.
|
|
||||||
pub fn snapshot(&self) -> TelemetryFrame {
|
|
||||||
TelemetryFrame {
|
|
||||||
frame_index: self.frame_index.load(Ordering::Relaxed),
|
|
||||||
cycles_used: self.cycles_used.load(Ordering::Relaxed),
|
|
||||||
cycles_budget: self.cycles_budget.load(Ordering::Relaxed),
|
|
||||||
syscalls: self.syscalls.load(Ordering::Relaxed),
|
|
||||||
host_cpu_time_us: self.host_cpu_time_us.load(Ordering::Relaxed),
|
|
||||||
completed_logical_frames: self.completed_logical_frames.load(Ordering::Relaxed),
|
|
||||||
violations: self.violations.load(Ordering::Relaxed),
|
|
||||||
glyph_slots_used: self.glyph_slots_used.load(Ordering::Relaxed),
|
|
||||||
glyph_slots_total: self.glyph_slots_total.load(Ordering::Relaxed),
|
|
||||||
sound_slots_used: self.sound_slots_used.load(Ordering::Relaxed),
|
|
||||||
sound_slots_total: self.sound_slots_total.load(Ordering::Relaxed),
|
|
||||||
scene_slots_used: self.scene_slots_used.load(Ordering::Relaxed),
|
|
||||||
scene_slots_total: self.scene_slots_total.load(Ordering::Relaxed),
|
|
||||||
heap_used_bytes: self.heap_used_bytes.load(Ordering::Relaxed),
|
|
||||||
heap_max_bytes: self.heap_max_bytes.load(Ordering::Relaxed),
|
|
||||||
vm_heap_allocations: self.vm_heap_allocations.load(Ordering::Relaxed),
|
|
||||||
vm_string_materializations: self.vm_string_materializations.load(Ordering::Relaxed),
|
|
||||||
logs_count: self.logs_count.load(Ordering::Relaxed),
|
|
||||||
vm_steps: self.vm_steps.load(Ordering::Relaxed),
|
|
||||||
produced_submissions: self.produced_submissions.load(Ordering::Relaxed),
|
|
||||||
replaced_before_consume: self.replaced_before_consume.load(Ordering::Relaxed),
|
|
||||||
consumed_submissions: self.consumed_submissions.load(Ordering::Relaxed),
|
|
||||||
published_frames: self.published_frames.load(Ordering::Relaxed),
|
|
||||||
presented_frames: self.presented_frames.load(Ordering::Relaxed),
|
|
||||||
repeated_presents: self.repeated_presents.load(Ordering::Relaxed),
|
|
||||||
render_errors: self.render_errors.load(Ordering::Relaxed),
|
|
||||||
publish_errors: self.publish_errors.load(Ordering::Relaxed),
|
|
||||||
present_errors: self.present_errors.load(Ordering::Relaxed),
|
|
||||||
stale_epoch_discards: self.stale_epoch_discards.load(Ordering::Relaxed),
|
|
||||||
shutdown_discards: self.shutdown_discards.load(Ordering::Relaxed),
|
|
||||||
shutdown_timeouts: self.shutdown_timeouts.load(Ordering::Relaxed),
|
|
||||||
worker_panics: self.worker_panics.load(Ordering::Relaxed),
|
|
||||||
last_produced_frame_id: self.last_produced_frame_id.load(Ordering::Relaxed),
|
|
||||||
last_consumed_frame_id: self.last_consumed_frame_id.load(Ordering::Relaxed),
|
|
||||||
last_published_frame_id: self.last_published_frame_id.load(Ordering::Relaxed),
|
|
||||||
last_presented_frame_id: self.last_presented_frame_id.load(Ordering::Relaxed),
|
|
||||||
last_dropped_frame_id: self.last_dropped_frame_id.load(Ordering::Relaxed),
|
|
||||||
last_error_frame_id: self.last_error_frame_id.load(Ordering::Relaxed),
|
|
||||||
active_render_epoch: self.active_render_epoch.load(Ordering::Relaxed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reset(&self) {
|
|
||||||
self.frame_index.store(0, Ordering::Relaxed);
|
|
||||||
self.cycles_used.store(0, Ordering::Relaxed);
|
|
||||||
self.syscalls.store(0, Ordering::Relaxed);
|
|
||||||
self.host_cpu_time_us.store(0, Ordering::Relaxed);
|
|
||||||
self.completed_logical_frames.store(0, Ordering::Relaxed);
|
|
||||||
self.violations.store(0, Ordering::Relaxed);
|
|
||||||
self.glyph_slots_used.store(0, Ordering::Relaxed);
|
|
||||||
self.glyph_slots_total.store(0, Ordering::Relaxed);
|
|
||||||
self.sound_slots_used.store(0, Ordering::Relaxed);
|
|
||||||
self.sound_slots_total.store(0, Ordering::Relaxed);
|
|
||||||
self.scene_slots_used.store(0, Ordering::Relaxed);
|
|
||||||
self.scene_slots_total.store(0, Ordering::Relaxed);
|
|
||||||
self.heap_used_bytes.store(0, Ordering::Relaxed);
|
|
||||||
self.vm_heap_allocations.store(0, Ordering::Relaxed);
|
|
||||||
self.vm_string_materializations.store(0, Ordering::Relaxed);
|
|
||||||
self.vm_steps.store(0, Ordering::Relaxed);
|
|
||||||
self.logs_count.store(0, Ordering::Relaxed);
|
|
||||||
self.current_logs_count.store(0, Ordering::Relaxed);
|
|
||||||
self.produced_submissions.store(0, Ordering::Relaxed);
|
|
||||||
self.replaced_before_consume.store(0, Ordering::Relaxed);
|
|
||||||
self.consumed_submissions.store(0, Ordering::Relaxed);
|
|
||||||
self.published_frames.store(0, Ordering::Relaxed);
|
|
||||||
self.presented_frames.store(0, Ordering::Relaxed);
|
|
||||||
self.repeated_presents.store(0, Ordering::Relaxed);
|
|
||||||
self.render_errors.store(0, Ordering::Relaxed);
|
|
||||||
self.publish_errors.store(0, Ordering::Relaxed);
|
|
||||||
self.present_errors.store(0, Ordering::Relaxed);
|
|
||||||
self.stale_epoch_discards.store(0, Ordering::Relaxed);
|
|
||||||
self.shutdown_discards.store(0, Ordering::Relaxed);
|
|
||||||
self.shutdown_timeouts.store(0, Ordering::Relaxed);
|
|
||||||
self.worker_panics.store(0, Ordering::Relaxed);
|
|
||||||
self.last_produced_frame_id.store(0, Ordering::Relaxed);
|
|
||||||
self.last_consumed_frame_id.store(0, Ordering::Relaxed);
|
|
||||||
self.last_published_frame_id.store(0, Ordering::Relaxed);
|
|
||||||
self.last_presented_frame_id.store(0, Ordering::Relaxed);
|
|
||||||
self.last_dropped_frame_id.store(0, Ordering::Relaxed);
|
|
||||||
self.last_error_frame_id.store(0, Ordering::Relaxed);
|
|
||||||
self.active_render_epoch.store(0, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Default)]
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
@@ -233,10 +28,6 @@ pub struct CertificationConfig {
|
|||||||
pub cycles_budget_per_frame: Option<u64>,
|
pub cycles_budget_per_frame: Option<u64>,
|
||||||
pub max_syscalls_per_frame: Option<u32>,
|
pub max_syscalls_per_frame: Option<u32>,
|
||||||
pub max_host_cpu_us_per_frame: Option<u64>,
|
pub max_host_cpu_us_per_frame: Option<u64>,
|
||||||
pub max_glyph_slots_used: Option<u32>,
|
|
||||||
pub max_sound_slots_used: Option<u32>,
|
|
||||||
pub max_heap_bytes: Option<usize>,
|
|
||||||
pub max_logs_per_frame: Option<u32>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Certifier {
|
pub struct Certifier {
|
||||||
@@ -260,7 +51,6 @@ impl Certifier {
|
|||||||
|
|
||||||
let mut violations = 0;
|
let mut violations = 0;
|
||||||
|
|
||||||
// 1. Cycles
|
|
||||||
if let Some(budget) = self.config.cycles_budget_per_frame
|
if let Some(budget) = self.config.cycles_budget_per_frame
|
||||||
&& telemetry.cycles_used > budget
|
&& telemetry.cycles_used > budget
|
||||||
{
|
{
|
||||||
@@ -278,7 +68,6 @@ impl Certifier {
|
|||||||
violations += 1;
|
violations += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Syscalls
|
|
||||||
if let Some(limit) = self.config.max_syscalls_per_frame
|
if let Some(limit) = self.config.max_syscalls_per_frame
|
||||||
&& telemetry.syscalls > limit
|
&& telemetry.syscalls > limit
|
||||||
{
|
{
|
||||||
@@ -296,7 +85,6 @@ impl Certifier {
|
|||||||
violations += 1;
|
violations += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. CPU Time
|
|
||||||
if let Some(limit) = self.config.max_host_cpu_us_per_frame
|
if let Some(limit) = self.config.max_host_cpu_us_per_frame
|
||||||
&& telemetry.host_cpu_time_us > limit
|
&& telemetry.host_cpu_time_us > limit
|
||||||
{
|
{
|
||||||
@@ -314,75 +102,6 @@ impl Certifier {
|
|||||||
violations += 1;
|
violations += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. GLYPH bank slots
|
|
||||||
if let Some(limit) = self.config.max_glyph_slots_used
|
|
||||||
&& telemetry.glyph_slots_used > limit
|
|
||||||
{
|
|
||||||
log_service.log(
|
|
||||||
ts_ms,
|
|
||||||
telemetry.frame_index,
|
|
||||||
LogLevel::Warn,
|
|
||||||
LogSource::Pos,
|
|
||||||
0xCA04,
|
|
||||||
format!(
|
|
||||||
"Cert: GLYPH bank exceeded slot limit ({} > {})",
|
|
||||||
telemetry.glyph_slots_used, limit
|
|
||||||
),
|
|
||||||
);
|
|
||||||
violations += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. SOUNDS bank slots
|
|
||||||
if let Some(limit) = self.config.max_sound_slots_used
|
|
||||||
&& telemetry.sound_slots_used > limit
|
|
||||||
{
|
|
||||||
log_service.log(
|
|
||||||
ts_ms,
|
|
||||||
telemetry.frame_index,
|
|
||||||
LogLevel::Warn,
|
|
||||||
LogSource::Pos,
|
|
||||||
0xCA05,
|
|
||||||
format!(
|
|
||||||
"Cert: SOUNDS bank exceeded slot limit ({} > {})",
|
|
||||||
telemetry.sound_slots_used, limit
|
|
||||||
),
|
|
||||||
);
|
|
||||||
violations += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 6. Heap Memory
|
|
||||||
if let Some(limit) = self.config.max_heap_bytes
|
|
||||||
&& telemetry.heap_used_bytes > limit
|
|
||||||
{
|
|
||||||
log_service.log(
|
|
||||||
ts_ms,
|
|
||||||
telemetry.frame_index,
|
|
||||||
LogLevel::Warn,
|
|
||||||
LogSource::Pos,
|
|
||||||
0xCA06,
|
|
||||||
format!(
|
|
||||||
"Cert: Heap memory exceeded limit ({} > {})",
|
|
||||||
telemetry.heap_used_bytes, limit
|
|
||||||
),
|
|
||||||
);
|
|
||||||
violations += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 7. Log Pressure
|
|
||||||
if let Some(limit) = self.config.max_logs_per_frame
|
|
||||||
&& telemetry.logs_count > limit
|
|
||||||
{
|
|
||||||
log_service.log(
|
|
||||||
ts_ms,
|
|
||||||
telemetry.frame_index,
|
|
||||||
LogLevel::Warn,
|
|
||||||
LogSource::Pos,
|
|
||||||
0xCA07,
|
|
||||||
format!("Cert: Log pressure exceeded limit ({} > {})", telemetry.logs_count, limit),
|
|
||||||
);
|
|
||||||
violations += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
violations
|
violations
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -394,104 +113,26 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_certifier_violations() {
|
fn test_certifier_violations() {
|
||||||
let mut ls = LogService::new(10);
|
|
||||||
let config = CertificationConfig {
|
let config = CertificationConfig {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
cycles_budget_per_frame: Some(100),
|
cycles_budget_per_frame: Some(100),
|
||||||
max_syscalls_per_frame: Some(5),
|
max_syscalls_per_frame: Some(5),
|
||||||
max_host_cpu_us_per_frame: Some(1000),
|
max_host_cpu_us_per_frame: Some(1000),
|
||||||
max_glyph_slots_used: Some(1),
|
|
||||||
..Default::default()
|
|
||||||
};
|
};
|
||||||
let cert = Certifier::new(config);
|
let cert = Certifier::new(config);
|
||||||
|
let mut ls = LogService::new(10);
|
||||||
|
|
||||||
let tel = TelemetryFrame {
|
let mut tel = TelemetryFrame::default();
|
||||||
cycles_used: 150,
|
tel.cycles_used = 150;
|
||||||
syscalls: 10,
|
tel.syscalls = 10;
|
||||||
host_cpu_time_us: 500,
|
tel.host_cpu_time_us = 500;
|
||||||
glyph_slots_used: 2,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let violations = cert.evaluate(&tel, &mut ls, 1000);
|
let violations = cert.evaluate(&tel, &mut ls, 1000);
|
||||||
assert_eq!(violations, 3);
|
assert_eq!(violations, 2);
|
||||||
|
|
||||||
let logs = ls.get_recent(10);
|
let logs = ls.get_recent(10);
|
||||||
assert_eq!(logs.len(), 3);
|
assert_eq!(logs.len(), 2);
|
||||||
assert!(logs[0].msg.contains("cycles_used"));
|
assert!(logs[0].msg.contains("cycles_used"));
|
||||||
assert!(logs[1].msg.contains("syscalls"));
|
assert!(logs[1].msg.contains("syscalls"));
|
||||||
assert!(logs[2].msg.contains("GLYPH bank"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn snapshot_uses_persisted_last_frame_logs() {
|
|
||||||
let current = Arc::new(AtomicU32::new(7));
|
|
||||||
let tel = AtomicTelemetry::new(Arc::clone(¤t));
|
|
||||||
tel.logs_count.store(3, Ordering::Relaxed);
|
|
||||||
|
|
||||||
let snapshot = tel.snapshot();
|
|
||||||
|
|
||||||
assert_eq!(snapshot.logs_count, 3);
|
|
||||||
assert_eq!(current.load(Ordering::Relaxed), 7);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn snapshot_includes_internal_allocation_evidence() {
|
|
||||||
let current = Arc::new(AtomicU32::new(0));
|
|
||||||
let tel = AtomicTelemetry::new(current);
|
|
||||||
tel.vm_heap_allocations.store(2, Ordering::Relaxed);
|
|
||||||
tel.vm_string_materializations.store(5, Ordering::Relaxed);
|
|
||||||
|
|
||||||
let snapshot = tel.snapshot();
|
|
||||||
|
|
||||||
assert_eq!(snapshot.vm_heap_allocations, 2);
|
|
||||||
assert_eq!(snapshot.vm_string_materializations, 5);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn snapshot_maps_render_worker_telemetry() {
|
|
||||||
let current = Arc::new(AtomicU32::new(0));
|
|
||||||
let tel = AtomicTelemetry::new(current);
|
|
||||||
tel.produced_submissions.store(2, Ordering::Relaxed);
|
|
||||||
tel.replaced_before_consume.store(1, Ordering::Relaxed);
|
|
||||||
tel.consumed_submissions.store(1, Ordering::Relaxed);
|
|
||||||
tel.published_frames.store(1, Ordering::Relaxed);
|
|
||||||
tel.presented_frames.store(1, Ordering::Relaxed);
|
|
||||||
tel.repeated_presents.store(3, Ordering::Relaxed);
|
|
||||||
tel.render_errors.store(4, Ordering::Relaxed);
|
|
||||||
tel.publish_errors.store(5, Ordering::Relaxed);
|
|
||||||
tel.present_errors.store(6, Ordering::Relaxed);
|
|
||||||
tel.stale_epoch_discards.store(7, Ordering::Relaxed);
|
|
||||||
tel.shutdown_timeouts.store(8, Ordering::Relaxed);
|
|
||||||
tel.worker_panics.store(9, Ordering::Relaxed);
|
|
||||||
tel.last_produced_frame_id.store(10, Ordering::Relaxed);
|
|
||||||
tel.last_consumed_frame_id.store(11, Ordering::Relaxed);
|
|
||||||
tel.last_published_frame_id.store(12, Ordering::Relaxed);
|
|
||||||
tel.last_presented_frame_id.store(13, Ordering::Relaxed);
|
|
||||||
tel.last_dropped_frame_id.store(14, Ordering::Relaxed);
|
|
||||||
tel.last_error_frame_id.store(15, Ordering::Relaxed);
|
|
||||||
tel.active_render_epoch.store(16, Ordering::Relaxed);
|
|
||||||
|
|
||||||
let worker = tel.snapshot().render_worker_telemetry();
|
|
||||||
|
|
||||||
assert_eq!(worker.produced_submissions, 2);
|
|
||||||
assert_eq!(worker.replaced_before_consume, 1);
|
|
||||||
assert_eq!(worker.consumed_submissions, 1);
|
|
||||||
assert_eq!(worker.published_frames, 1);
|
|
||||||
assert_eq!(worker.presented_frames, 1);
|
|
||||||
assert_eq!(worker.repeated_frames, 3);
|
|
||||||
assert_eq!(worker.render_failures, 4);
|
|
||||||
assert_eq!(worker.publish_failures, 5);
|
|
||||||
assert_eq!(worker.present_failures, 6);
|
|
||||||
assert_eq!(worker.stale_submission_discards, 7);
|
|
||||||
assert_eq!(worker.shutdown_timeouts, 8);
|
|
||||||
assert_eq!(worker.worker_panics, 9);
|
|
||||||
assert_eq!(worker.last_produced_frame_id, 10);
|
|
||||||
assert_eq!(worker.last_consumed_frame_id, 11);
|
|
||||||
assert_eq!(worker.last_published_frame_id, 12);
|
|
||||||
assert_eq!(worker.last_presented_frame_id, 13);
|
|
||||||
assert_eq!(worker.last_dropped_frame_id, 14);
|
|
||||||
assert_eq!(worker.last_error_frame_id, 15);
|
|
||||||
assert_eq!(worker.active_render_epoch, 16);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
use crate::glyph::Glyph;
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
|
|
||||||
pub struct Tile {
|
pub struct Tile {
|
||||||
pub active: bool,
|
pub id: u16,
|
||||||
pub glyph: Glyph,
|
|
||||||
pub flip_x: bool,
|
pub flip_x: bool,
|
||||||
pub flip_y: bool,
|
pub flip_y: bool,
|
||||||
|
pub palette_id: u8,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
use crate::color::Color;
|
||||||
|
|
||||||
|
pub const TILE_BANK_PALETTE_COUNT_V1: usize = 64;
|
||||||
|
pub const TILE_BANK_COLORS_PER_PALETTE: usize = 16;
|
||||||
|
|
||||||
|
/// Standard sizes for square tiles.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub enum TileSize {
|
||||||
|
/// 8x8 pixels.
|
||||||
|
Size8 = 8,
|
||||||
|
/// 16x16 pixels.
|
||||||
|
Size16 = 16,
|
||||||
|
/// 32x32 pixels.
|
||||||
|
Size32 = 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A container for graphical assets.
|
||||||
|
///
|
||||||
|
/// A TileBank stores the decoded runtime representation of a tile-bank asset.
|
||||||
|
///
|
||||||
|
/// Serialized `assets.pa` payloads keep pixel indices packed as `4bpp` nibbles.
|
||||||
|
/// After decode, the runtime expands them to one `u8` palette index per pixel
|
||||||
|
/// while preserving the same `0..15` logical range.
|
||||||
|
pub struct TileBank {
|
||||||
|
/// Dimension of each individual tile in the bank.
|
||||||
|
pub tile_size: TileSize,
|
||||||
|
/// Width of the full bank sheet in pixels.
|
||||||
|
pub width: usize,
|
||||||
|
/// Height of the full bank sheet in pixels.
|
||||||
|
pub height: usize,
|
||||||
|
|
||||||
|
/// Decoded pixel data stored as one palette index per pixel.
|
||||||
|
/// Serialized payloads are packed; runtime memory is expanded.
|
||||||
|
/// Index 0 is always reserved for transparency.
|
||||||
|
pub pixel_indices: Vec<u8>,
|
||||||
|
/// Runtime-facing v1 palette table: 64 palettes of 16 RGB565 colors each.
|
||||||
|
pub palettes: [[Color; TILE_BANK_COLORS_PER_PALETTE]; TILE_BANK_PALETTE_COUNT_V1],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TileBank {
|
||||||
|
/// Creates an empty tile bank with the specified dimensions.
|
||||||
|
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
tile_size,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
pixel_indices: vec![0; width * height], // Index 0 = Transparent
|
||||||
|
palettes: [[Color::BLACK; TILE_BANK_COLORS_PER_PALETTE]; TILE_BANK_PALETTE_COUNT_V1],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves a global tile ID and local pixel coordinates to a palette index.
|
||||||
|
/// tile_id: the tile index in the bank
|
||||||
|
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
|
||||||
|
pub fn get_pixel_index(&self, tile_id: u16, local_x: usize, local_y: usize) -> u8 {
|
||||||
|
let size = self.tile_size as usize;
|
||||||
|
let tiles_per_row = self.width / size;
|
||||||
|
let tile_x = (tile_id as usize % tiles_per_row) * size;
|
||||||
|
let tile_y = (tile_id as usize / tiles_per_row) * size;
|
||||||
|
|
||||||
|
let pixel_x = tile_x + local_x;
|
||||||
|
let pixel_y = tile_y + local_y;
|
||||||
|
|
||||||
|
if pixel_x < self.width && pixel_y < self.height {
|
||||||
|
self.pixel_indices[pixel_y * self.width + pixel_x]
|
||||||
|
} else {
|
||||||
|
0 // Default to transparent if out of bounds
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps a 4-bit index to a real RGB565 Color using the specified palette.
|
||||||
|
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Color {
|
||||||
|
// Hardware Rule: Index 0 is always transparent.
|
||||||
|
// We use Magenta as the 'transparent' signal color during composition.
|
||||||
|
if pixel_index == 0 {
|
||||||
|
return Color::COLOR_KEY;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.palettes
|
||||||
|
.get(palette_id as usize)
|
||||||
|
.and_then(|palette| palette.get(pixel_index as usize))
|
||||||
|
.copied()
|
||||||
|
.unwrap_or(Color::COLOR_KEY)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
use crate::tile::Tile;
|
||||||
|
use crate::tile_bank::TileSize;
|
||||||
|
use crate::tile_bank::TileSize::Size8;
|
||||||
|
|
||||||
|
pub struct TileMap {
|
||||||
|
pub width: usize,
|
||||||
|
pub height: usize,
|
||||||
|
pub tiles: Vec<Tile>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TileMap {
|
||||||
|
fn create(width: usize, height: usize) -> Self {
|
||||||
|
Self { width, height, tiles: vec![Tile::default(); width * height] }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_tile(&mut self, x: usize, y: usize, tile: Tile) {
|
||||||
|
if x < self.width && y < self.height {
|
||||||
|
self.tiles[y * self.width + x] = tile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TileLayer {
|
||||||
|
pub bank_id: u8,
|
||||||
|
pub tile_size: TileSize,
|
||||||
|
pub map: TileMap,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TileLayer {
|
||||||
|
fn create(width: usize, height: usize, tile_size: TileSize) -> Self {
|
||||||
|
Self { bank_id: 0, tile_size, map: TileMap::create(width, height) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::Deref for TileLayer {
|
||||||
|
type Target = TileMap;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.map
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::DerefMut for TileLayer {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.map
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ScrollableTileLayer {
|
||||||
|
pub layer: TileLayer,
|
||||||
|
pub scroll_x: i32,
|
||||||
|
pub scroll_y: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ScrollableTileLayer {
|
||||||
|
pub fn new(width: usize, height: usize, tile_size: TileSize) -> Self {
|
||||||
|
Self { layer: TileLayer::create(width, height, tile_size), scroll_x: 0, scroll_y: 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::Deref for ScrollableTileLayer {
|
||||||
|
type Target = TileLayer;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.layer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::DerefMut for ScrollableTileLayer {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.layer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct HudTileLayer {
|
||||||
|
pub layer: TileLayer,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HudTileLayer {
|
||||||
|
pub fn new(width: usize, height: usize) -> Self {
|
||||||
|
Self { layer: TileLayer::create(width, height, Size8) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::Deref for HudTileLayer {
|
||||||
|
type Target = TileLayer;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.layer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::DerefMut for HudTileLayer {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.layer
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
use crate::tile::Tile;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
||||||
pub struct TileMap {
|
|
||||||
pub width: usize,
|
|
||||||
pub height: usize,
|
|
||||||
pub tiles: Vec<Tile>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::glyph::Glyph;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tilemap_tile_write_and_read_remain_canonical() {
|
|
||||||
let mut map = TileMap { width: 2, height: 2, tiles: vec![Tile::default(); 4] };
|
|
||||||
|
|
||||||
let index = 3;
|
|
||||||
map.tiles[index] = Tile {
|
|
||||||
active: true,
|
|
||||||
glyph: Glyph { glyph_id: 99, palette_id: 5 },
|
|
||||||
flip_x: true,
|
|
||||||
flip_y: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
assert_eq!(map.tiles[index].glyph.glyph_id, 99);
|
|
||||||
assert_eq!(map.tiles[index].glyph.palette_id, 5);
|
|
||||||
assert!(map.tiles[index].flip_x);
|
|
||||||
assert!(map.tiles[index].active);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+9
-4
@@ -1,6 +1,12 @@
|
|||||||
use crate::windows::WindowOwner;
|
use crate::color::Color;
|
||||||
use prometeu_hal::color::Color;
|
|
||||||
use prometeu_hal::primitives::Rect;
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Rect {
|
||||||
|
pub x: i32,
|
||||||
|
pub y: i32,
|
||||||
|
pub w: i32,
|
||||||
|
pub h: i32,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub struct WindowId(pub u32);
|
pub struct WindowId(pub u32);
|
||||||
@@ -8,7 +14,6 @@ pub struct WindowId(pub u32);
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Window {
|
pub struct Window {
|
||||||
pub id: WindowId,
|
pub id: WindowId,
|
||||||
pub owner: WindowOwner,
|
|
||||||
pub viewport: Rect,
|
pub viewport: Rect,
|
||||||
pub has_focus: bool,
|
pub has_focus: bool,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
@@ -1,36 +1,9 @@
|
|||||||
mod crash_report;
|
mod crash_report;
|
||||||
mod os;
|
|
||||||
mod programs;
|
mod programs;
|
||||||
mod services;
|
mod services;
|
||||||
|
mod virtual_machine_runtime;
|
||||||
|
|
||||||
pub use crash_report::CrashReport;
|
pub use crash_report::CrashReport;
|
||||||
pub use os::{
|
pub use programs::PrometeuHub;
|
||||||
DEFAULT_GAME_PAUSE_BUDGET_TICKS, GameLifecycleEvent, GameLifecycleEventKind, LifecycleError,
|
|
||||||
LifecycleOperation, SessionError, SystemOS,
|
|
||||||
};
|
|
||||||
pub use programs::{
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
|
|
||||||
SystemProfileUpdate,
|
|
||||||
};
|
|
||||||
pub use prometeu_hal::{RenderWorkerBackend, RenderWorkerFrameSink};
|
|
||||||
pub use services::async_work::{
|
|
||||||
AsyncWorkActiveJob, AsyncWorkCancelToken, AsyncWorkJobContext, AsyncWorkJobId,
|
|
||||||
AsyncWorkJobKind, AsyncWorkJobOutcome, AsyncWorkLane, AsyncWorkLaneConfig,
|
|
||||||
AsyncWorkLaneController, AsyncWorkLaneError, AsyncWorkLaneTelemetry, AsyncWorkPriority,
|
|
||||||
};
|
|
||||||
pub use services::foreground::{
|
|
||||||
ForegroundOwner, ForegroundStack, ForegroundStackError, ResidentGame, ResidentGameState,
|
|
||||||
};
|
|
||||||
pub use services::fs;
|
pub use services::fs;
|
||||||
pub use services::game_library::{
|
pub use virtual_machine_runtime::VirtualMachineRuntime;
|
||||||
GameLibrary, GameLibraryDiagnostic, GameLibraryEntry, GameSwitchTarget, discover_games_root,
|
|
||||||
};
|
|
||||||
pub use services::memcard::MemcardAsyncLaneOperation;
|
|
||||||
pub use services::process;
|
|
||||||
pub use services::task;
|
|
||||||
pub use services::vm_runtime::{
|
|
||||||
LatestRenderFrameStore, RenderWorkerConfig, RenderWorkerController, RenderWorkerHandoff,
|
|
||||||
RenderWorkerHandoffWait, RenderWorkerOwnership, VirtualMachineRuntime,
|
|
||||||
};
|
|
||||||
pub use services::vm_session;
|
|
||||||
pub use services::windows;
|
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
use crate::fs::{FsBackend, FsState};
|
|
||||||
use crate::os::SystemOS;
|
|
||||||
|
|
||||||
pub struct FsFacade<'a> {
|
|
||||||
pub(in crate::os) os: &'a mut SystemOS,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> FsFacade<'a> {
|
|
||||||
pub fn needs_mount(&self) -> bool {
|
|
||||||
matches!(self.os.fs_state, FsState::Unmounted | FsState::Error(_))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn mount(&mut self, backend: Box<dyn FsBackend>) {
|
|
||||||
self.os.vm_runtime.mount_fs(
|
|
||||||
&mut self.os.log_service,
|
|
||||||
&mut self.os.fs,
|
|
||||||
&mut self.os.fs_state,
|
|
||||||
backend,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn unmount(&mut self) {
|
|
||||||
self.os.fs.unmount();
|
|
||||||
self.os.fs_state = FsState::Unmounted;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,299 +0,0 @@
|
|||||||
use crate::CrashReport;
|
|
||||||
use crate::os::SystemOS;
|
|
||||||
use crate::os::{
|
|
||||||
DEFAULT_GAME_PAUSE_BUDGET_TICKS, GameLifecycleEvent, GameLifecycleEventKind, LifecycleError,
|
|
||||||
LifecycleOperation,
|
|
||||||
};
|
|
||||||
use crate::process::{Process, ProcessId, ProcessKind, ProcessState};
|
|
||||||
use crate::services::foreground::{
|
|
||||||
ForegroundOwner, ForegroundStackError, ResidentGame, ResidentGameState,
|
|
||||||
};
|
|
||||||
use crate::task::{TaskId, TaskKind, TaskState};
|
|
||||||
|
|
||||||
pub struct LifecycleFacade<'a> {
|
|
||||||
pub(in crate::os) os: &'a mut SystemOS,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> LifecycleFacade<'a> {
|
|
||||||
pub fn task_state(&self, task_id: TaskId) -> Option<TaskState> {
|
|
||||||
self.os.task_manager.get(task_id).map(|task| task.state)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn process_state_for_task(&self, task_id: TaskId) -> Result<ProcessState, LifecycleError> {
|
|
||||||
process_for_task(self.os, task_id).map(|process| process.state)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn process_kind_for_task(&self, task_id: TaskId) -> Result<ProcessKind, LifecycleError> {
|
|
||||||
process_for_task(self.os, task_id).map(|process| process.kind)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_foreground_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
|
||||||
match task_kind_for_task(self.os, task_id)? {
|
|
||||||
TaskKind::Game => self.set_game_foreground_task(task_id),
|
|
||||||
TaskKind::Shell => self.set_shell_foreground_task(task_id),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_game_foreground_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
|
|
||||||
if task_kind_for_task(self.os, task_id)? != TaskKind::Game {
|
|
||||||
return Err(LifecycleError::InvalidTransition {
|
|
||||||
task_id,
|
|
||||||
from: self.task_state(task_id).unwrap_or(TaskState::Closed),
|
|
||||||
operation: LifecycleOperation::SetForeground,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.foreground_stack.set_game_foreground(task_id).map_err(map_foreground_error)?;
|
|
||||||
self.os.task_manager.set_foreground(task_id);
|
|
||||||
self.os.process_manager.mark_running(process_id);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_shell_foreground_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
|
|
||||||
if task_kind_for_task(self.os, task_id)? != TaskKind::Shell {
|
|
||||||
return Err(LifecycleError::InvalidTransition {
|
|
||||||
task_id,
|
|
||||||
from: self.task_state(task_id).unwrap_or(TaskState::Closed),
|
|
||||||
operation: LifecycleOperation::SetForeground,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(game_task_id) = self.os.foreground_stack.resident_game_task()
|
|
||||||
&& game_task_id != task_id
|
|
||||||
&& self.task_state(game_task_id) != Some(TaskState::Suspended)
|
|
||||||
{
|
|
||||||
let game_process_id = process_id_for_task(self.os, game_task_id)?;
|
|
||||||
self.os.task_manager.mark_suspended(game_task_id);
|
|
||||||
self.os.process_manager.mark_suspended(game_process_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.foreground_stack.set_shell_foreground(task_id).map_err(map_foreground_error)?;
|
|
||||||
self.os.task_manager.set_foreground(task_id);
|
|
||||||
self.os.process_manager.mark_running(process_id);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn foreground_owner(&self) -> ForegroundOwner {
|
|
||||||
self.os.foreground_stack.owner()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resident_game(&self) -> Option<ResidentGame> {
|
|
||||||
self.os.foreground_stack.resident_game()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resident_game_task(&self) -> Option<TaskId> {
|
|
||||||
self.os.foreground_stack.resident_game_task()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn request_home_from_game(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
|
||||||
let _process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
let previous = self.os.foreground_stack.resident_game();
|
|
||||||
|
|
||||||
self.os
|
|
||||||
.foreground_stack
|
|
||||||
.request_home_from_game(task_id, DEFAULT_GAME_PAUSE_BUDGET_TICKS)
|
|
||||||
.map_err(map_foreground_error)?;
|
|
||||||
|
|
||||||
if !matches!(
|
|
||||||
previous.map(|game| game.state),
|
|
||||||
Some(ResidentGameState::PauseRequested { .. } | ResidentGameState::PausedSuspended)
|
|
||||||
) {
|
|
||||||
self.os
|
|
||||||
.game_lifecycle_events
|
|
||||||
.push(GameLifecycleEvent { task_id, kind: GameLifecycleEventKind::Pause });
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn advance_game_pause_budget(&mut self, task_id: TaskId) -> Result<bool, LifecycleError> {
|
|
||||||
let expired =
|
|
||||||
self.os.foreground_stack.advance_pause_budget(task_id).map_err(map_foreground_error)?;
|
|
||||||
|
|
||||||
if expired {
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
self.os.task_manager.mark_suspended(task_id);
|
|
||||||
self.os.process_manager.mark_suspended(process_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(expired)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pending_game_lifecycle_events(&self) -> &[GameLifecycleEvent] {
|
|
||||||
&self.os.game_lifecycle_events
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn take_game_lifecycle_events(&mut self) -> Vec<GameLifecycleEvent> {
|
|
||||||
std::mem::take(&mut self.os.game_lifecycle_events)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn return_to_hub(&mut self) {
|
|
||||||
self.os.foreground_stack.return_to_hub();
|
|
||||||
self.os.task_manager.clear_foreground();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn suspend_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
|
|
||||||
self.os.task_manager.mark_suspended(task_id);
|
|
||||||
self.os.process_manager.mark_suspended(process_id);
|
|
||||||
match self.os.foreground_stack.owner() {
|
|
||||||
ForegroundOwner::Game(owner) if owner == task_id => {
|
|
||||||
self.os
|
|
||||||
.foreground_stack
|
|
||||||
.request_home_from_game(task_id, DEFAULT_GAME_PAUSE_BUDGET_TICKS)
|
|
||||||
.map_err(map_foreground_error)?;
|
|
||||||
self.os
|
|
||||||
.foreground_stack
|
|
||||||
.advance_pause_budget(task_id)
|
|
||||||
.map_err(map_foreground_error)?;
|
|
||||||
}
|
|
||||||
ForegroundOwner::Shell(owner) if owner == task_id => {
|
|
||||||
self.os.foreground_stack.return_to_hub();
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resume_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
|
||||||
let task =
|
|
||||||
self.os.task_manager.get(task_id).ok_or(LifecycleError::TaskNotFound(task_id))?;
|
|
||||||
|
|
||||||
if task.state != TaskState::Suspended {
|
|
||||||
return Err(LifecycleError::InvalidTransition {
|
|
||||||
task_id,
|
|
||||||
from: task.state,
|
|
||||||
operation: LifecycleOperation::Resume,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
|
|
||||||
match task_kind_for_task(self.os, task_id)? {
|
|
||||||
TaskKind::Game => {
|
|
||||||
self.os
|
|
||||||
.foreground_stack
|
|
||||||
.request_resume_game(task_id)
|
|
||||||
.map_err(map_foreground_error)?;
|
|
||||||
self.os.task_manager.set_foreground(task_id);
|
|
||||||
self.os.process_manager.mark_running(process_id);
|
|
||||||
self.os.game_lifecycle_events.push(GameLifecycleEvent {
|
|
||||||
task_id,
|
|
||||||
kind: GameLifecycleEventKind::ResumeForeground,
|
|
||||||
});
|
|
||||||
self.os
|
|
||||||
.foreground_stack
|
|
||||||
.complete_resume_game(task_id)
|
|
||||||
.map_err(map_foreground_error)?;
|
|
||||||
}
|
|
||||||
TaskKind::Shell => {
|
|
||||||
self.os
|
|
||||||
.foreground_stack
|
|
||||||
.set_shell_foreground(task_id)
|
|
||||||
.map_err(map_foreground_error)?;
|
|
||||||
self.os.task_manager.set_foreground(task_id);
|
|
||||||
self.os.process_manager.mark_running(process_id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn close_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
|
|
||||||
self.os.task_manager.close_task(task_id);
|
|
||||||
self.os.process_manager.mark_stopped(process_id);
|
|
||||||
if self.os.foreground_stack.resident_game_task() == Some(task_id) {
|
|
||||||
self.os.foreground_stack.clear_resident_game(task_id);
|
|
||||||
} else if matches!(self.os.foreground_stack.owner(), ForegroundOwner::Shell(owner) if owner == task_id)
|
|
||||||
{
|
|
||||||
self.os.foreground_stack.return_to_hub();
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn terminate_resident_game(&mut self) -> Result<Option<TaskId>, LifecycleError> {
|
|
||||||
let Some(task_id) = self.os.foreground_stack.resident_game_task() else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
|
|
||||||
self.os.task_manager.close_task(task_id);
|
|
||||||
self.os.process_manager.mark_stopped(process_id);
|
|
||||||
self.os.foreground_stack.clear_resident_game(task_id);
|
|
||||||
self.os.vm_sessions.remove_for_task(task_id);
|
|
||||||
self.os.game_lifecycle_events.retain(|event| event.task_id != task_id);
|
|
||||||
|
|
||||||
if matches!(self.os.foreground_stack.owner(), ForegroundOwner::Game(owner) if owner == task_id)
|
|
||||||
{
|
|
||||||
self.os.foreground_stack.return_to_hub();
|
|
||||||
self.os.task_manager.clear_foreground();
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Some(task_id))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn crash_task(
|
|
||||||
&mut self,
|
|
||||||
task_id: TaskId,
|
|
||||||
_report: Option<&CrashReport>,
|
|
||||||
) -> Result<(), LifecycleError> {
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
|
||||||
|
|
||||||
self.os.task_manager.mark_crashed(task_id);
|
|
||||||
self.os.process_manager.mark_crashed(process_id);
|
|
||||||
if self.os.foreground_stack.resident_game_task() == Some(task_id) {
|
|
||||||
self.os.foreground_stack.clear_resident_game(task_id);
|
|
||||||
} else if matches!(self.os.foreground_stack.owner(), ForegroundOwner::Shell(owner) if owner == task_id)
|
|
||||||
{
|
|
||||||
self.os.foreground_stack.return_to_hub();
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn task_kind_for_task(os: &SystemOS, task_id: TaskId) -> Result<TaskKind, LifecycleError> {
|
|
||||||
let task = os.task_manager.get(task_id).ok_or(LifecycleError::TaskNotFound(task_id))?;
|
|
||||||
Ok(task.kind)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn process_id_for_task(os: &SystemOS, task_id: TaskId) -> Result<ProcessId, LifecycleError> {
|
|
||||||
let task = os.task_manager.get(task_id).ok_or(LifecycleError::TaskNotFound(task_id))?;
|
|
||||||
|
|
||||||
if !os.process_manager.contains(task.process_id) {
|
|
||||||
return Err(LifecycleError::ProcessNotFound(task.process_id));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(task.process_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn process_for_task(os: &SystemOS, task_id: TaskId) -> Result<&Process, LifecycleError> {
|
|
||||||
let process_id = process_id_for_task(os, task_id)?;
|
|
||||||
os.process_manager.get(process_id).ok_or(LifecycleError::ProcessNotFound(process_id))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn map_foreground_error(error: ForegroundStackError) -> LifecycleError {
|
|
||||||
match error {
|
|
||||||
ForegroundStackError::ResidentGameAlreadyExists { existing, requested } => {
|
|
||||||
LifecycleError::ResidentGameAlreadyExists { existing, requested }
|
|
||||||
}
|
|
||||||
ForegroundStackError::ForegroundShellAlreadyExists { existing, requested } => {
|
|
||||||
LifecycleError::ForegroundShellAlreadyExists { existing, requested }
|
|
||||||
}
|
|
||||||
ForegroundStackError::TaskIsNotResidentGame(task_id) => {
|
|
||||||
LifecycleError::TaskIsNotResidentGame(task_id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
mod fs;
|
|
||||||
mod lifecycle;
|
|
||||||
mod sessions;
|
|
||||||
mod vm;
|
|
||||||
mod window;
|
|
||||||
|
|
||||||
pub use fs::FsFacade;
|
|
||||||
pub use lifecycle::LifecycleFacade;
|
|
||||||
pub use sessions::{SessionError, SessionsFacade};
|
|
||||||
pub use vm::VmFacade;
|
|
||||||
pub use window::WindowFacade;
|
|
||||||
@@ -1,209 +0,0 @@
|
|||||||
use crate::CrashReport;
|
|
||||||
use crate::os::LifecycleError;
|
|
||||||
use crate::os::SystemOS;
|
|
||||||
use crate::process::ProcessId;
|
|
||||||
use crate::task::TaskId;
|
|
||||||
use crate::vm_session::{VmSession, VmSessionError};
|
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::cartridge::Cartridge;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct LoadedVmCartridge {
|
|
||||||
pub task_id: TaskId,
|
|
||||||
pub app_mode: AppMode,
|
|
||||||
pub reused_existing_session: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum SessionError {
|
|
||||||
Lifecycle(LifecycleError),
|
|
||||||
VmSession(VmSessionError),
|
|
||||||
TaskNotFound(TaskId),
|
|
||||||
ProcessNotFound(ProcessId),
|
|
||||||
MissingVmSession(TaskId),
|
|
||||||
Initialization(CrashReport),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SessionError {
|
|
||||||
pub fn into_crash_report(self, operation: &str) -> CrashReport {
|
|
||||||
match self {
|
|
||||||
Self::Initialization(report) => report,
|
|
||||||
error => {
|
|
||||||
CrashReport::VmPanic { message: format!("{operation} failed: {error:?}"), pc: None }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<LifecycleError> for SessionError {
|
|
||||||
fn from(error: LifecycleError) -> Self {
|
|
||||||
Self::Lifecycle(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<VmSessionError> for SessionError {
|
|
||||||
fn from(error: VmSessionError) -> Self {
|
|
||||||
Self::VmSession(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SessionsFacade<'a> {
|
|
||||||
pub(in crate::os) os: &'a mut SystemOS,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> SessionsFacade<'a> {
|
|
||||||
#[cfg(test)]
|
|
||||||
pub fn create_vm_game_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
|
||||||
self.try_create_vm_game_task(app_id, title)
|
|
||||||
.expect("test/setup VM game creation should succeed")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_create_vm_game_task(
|
|
||||||
&mut self,
|
|
||||||
app_id: u32,
|
|
||||||
title: impl Into<String>,
|
|
||||||
) -> Result<TaskId, SessionError> {
|
|
||||||
if let Some(session) = self.os.vm_sessions.resident_game_for_app(app_id) {
|
|
||||||
return Ok(session.task_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
let title = title.into();
|
|
||||||
let process_id = self.os.process_manager.spawn_vm_game(app_id, title.clone());
|
|
||||||
let task_id = self.os.task_manager.create_game_task(process_id, app_id, title);
|
|
||||||
self.os.lifecycle().set_game_foreground_task(task_id)?;
|
|
||||||
self.try_create_vm_session_for_task(task_id)?;
|
|
||||||
|
|
||||||
Ok(task_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub fn create_vm_shell_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
|
||||||
self.try_create_vm_shell_task(app_id, title)
|
|
||||||
.expect("test/setup VM shell creation should succeed")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_create_vm_shell_task(
|
|
||||||
&mut self,
|
|
||||||
app_id: u32,
|
|
||||||
title: impl Into<String>,
|
|
||||||
) -> Result<TaskId, SessionError> {
|
|
||||||
let title = title.into();
|
|
||||||
let process_id = self.os.process_manager.spawn_vm_shell(app_id, title.clone());
|
|
||||||
let task_id = self.os.task_manager.create_shell_task(process_id, app_id, title);
|
|
||||||
self.os.lifecycle().set_shell_foreground_task(task_id)?;
|
|
||||||
self.try_create_vm_session_for_task(task_id)?;
|
|
||||||
|
|
||||||
Ok(task_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub fn create_native_shell_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
|
||||||
self.try_create_native_shell_task(app_id, title)
|
|
||||||
.expect("test/setup native shell creation should succeed")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_create_native_shell_task(
|
|
||||||
&mut self,
|
|
||||||
app_id: u32,
|
|
||||||
title: impl Into<String>,
|
|
||||||
) -> Result<TaskId, SessionError> {
|
|
||||||
let title = title.into();
|
|
||||||
let process_id = self.os.process_manager.spawn_native_shell(app_id, title.clone());
|
|
||||||
let task_id = self.os.task_manager.create_shell_task(process_id, app_id, title);
|
|
||||||
self.os.lifecycle().set_shell_foreground_task(task_id)?;
|
|
||||||
|
|
||||||
Ok(task_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn load_vm_cartridge(
|
|
||||||
&mut self,
|
|
||||||
cartridge: &Cartridge,
|
|
||||||
) -> Result<LoadedVmCartridge, SessionError> {
|
|
||||||
let existing_game_task = if cartridge.app_mode == AppMode::Game {
|
|
||||||
self.os
|
|
||||||
.vm_sessions
|
|
||||||
.resident_game_for_app(cartridge.app_id)
|
|
||||||
.map(|session| session.task_id)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let (task_id, reused_existing_session) = if let Some(task_id) = existing_game_task {
|
|
||||||
(task_id, true)
|
|
||||||
} else if cartridge.app_mode == AppMode::Shell {
|
|
||||||
(self.try_create_vm_shell_task(cartridge.app_id, cartridge.title.clone())?, false)
|
|
||||||
} else {
|
|
||||||
let task_id =
|
|
||||||
self.try_create_vm_game_task(cartridge.app_id, cartridge.title.clone())?;
|
|
||||||
(task_id, false)
|
|
||||||
};
|
|
||||||
|
|
||||||
if !reused_existing_session {
|
|
||||||
self.try_initialize_session_cartridge(task_id, cartridge)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(LoadedVmCartridge { task_id, app_mode: cartridge.app_mode, reused_existing_session })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn vm_session_for_task(&self, task_id: TaskId) -> Option<&VmSession> {
|
|
||||||
self.os.vm_sessions.for_task(task_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn vm_session_for_task_mut(&mut self, task_id: TaskId) -> Option<&mut VmSession> {
|
|
||||||
self.os.vm_sessions.for_task_mut(task_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resident_game_session_for_app(&self, app_id: u32) -> Option<&VmSession> {
|
|
||||||
self.os.vm_sessions.resident_game_for_app(app_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn vm_session_count(&self) -> usize {
|
|
||||||
self.os.vm_sessions.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear_vm_sessions(&mut self) {
|
|
||||||
self.os.vm_sessions.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_create_vm_session_for_task(&mut self, task_id: TaskId) -> Result<(), SessionError> {
|
|
||||||
let task =
|
|
||||||
self.os.task_manager.get(task_id).ok_or(SessionError::TaskNotFound(task_id))?.clone();
|
|
||||||
let process = self
|
|
||||||
.os
|
|
||||||
.process_manager
|
|
||||||
.get(task.process_id)
|
|
||||||
.ok_or(SessionError::ProcessNotFound(task.process_id))?
|
|
||||||
.clone();
|
|
||||||
|
|
||||||
let cap_config = self.os.vm_runtime.certifier.config;
|
|
||||||
let logs_count = Arc::clone(&self.os.log_service.logs_count);
|
|
||||||
self.os
|
|
||||||
.vm_sessions
|
|
||||||
.create_for_task(&task, &process, "", Some(cap_config), logs_count)
|
|
||||||
.map(|_| ())
|
|
||||||
.map_err(SessionError::from)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn try_initialize_session_cartridge(
|
|
||||||
&mut self,
|
|
||||||
task_id: TaskId,
|
|
||||||
cartridge: &Cartridge,
|
|
||||||
) -> Result<(), SessionError> {
|
|
||||||
let session = self
|
|
||||||
.os
|
|
||||||
.vm_sessions
|
|
||||||
.for_task_mut(task_id)
|
|
||||||
.ok_or(SessionError::MissingVmSession(task_id))?;
|
|
||||||
|
|
||||||
session.app_id = cartridge.app_id;
|
|
||||||
session.title = cartridge.title.clone();
|
|
||||||
session.app_version = cartridge.app_version.clone();
|
|
||||||
session.app_mode = cartridge.app_mode;
|
|
||||||
session.clear_cartridge_service_state();
|
|
||||||
session
|
|
||||||
.runtime
|
|
||||||
.initialize_vm(&mut self.os.log_service, &mut session.vm, cartridge)
|
|
||||||
.map_err(SessionError::Initialization)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,339 +0,0 @@
|
|||||||
use crate::CrashReport;
|
|
||||||
use crate::os::{GameLifecycleEvent, SystemOS};
|
|
||||||
use crate::task::TaskId;
|
|
||||||
use crate::vm_session::VmSession;
|
|
||||||
use crate::{RenderWorkerConfig, RenderWorkerController};
|
|
||||||
use prometeu_bytecode::Value;
|
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::telemetry::{CertificationConfig, TelemetryFrame};
|
|
||||||
use prometeu_hal::{
|
|
||||||
FrameId, InputSignals, RenderOwnership, RenderWorkerBackend, RenderWorkerError,
|
|
||||||
RenderWorkerFrameSink, RuntimePlatform,
|
|
||||||
};
|
|
||||||
use std::sync::atomic::Ordering;
|
|
||||||
|
|
||||||
pub struct VmFacade<'a> {
|
|
||||||
pub(in crate::os) os: &'a mut SystemOS,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> VmFacade<'a> {
|
|
||||||
pub fn tick_session(
|
|
||||||
&mut self,
|
|
||||||
task_id: TaskId,
|
|
||||||
signals: &InputSignals,
|
|
||||||
platform: &mut dyn RuntimePlatform,
|
|
||||||
) -> Option<CrashReport> {
|
|
||||||
self.deliver_pending_game_lifecycle_events_to_session(task_id);
|
|
||||||
|
|
||||||
let Some(session) = self.os.vm_sessions.for_task_mut(task_id) else {
|
|
||||||
return Some(CrashReport::VmPanic {
|
|
||||||
message: format!("task {:?} has no VM session", task_id),
|
|
||||||
pc: None,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
session.runtime.tick(
|
|
||||||
&mut self.os.log_service,
|
|
||||||
&mut self.os.fs,
|
|
||||||
&mut session.fs_state,
|
|
||||||
&mut self.os.memcard,
|
|
||||||
&mut session.open_files,
|
|
||||||
&mut session.next_handle,
|
|
||||||
&mut session.vm,
|
|
||||||
signals,
|
|
||||||
platform,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn deliver_pending_game_lifecycle_events_to_session(&mut self, task_id: TaskId) {
|
|
||||||
let Some(session) = self.os.vm_sessions.for_task(task_id) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
if session.runtime.current_cartridge_app_mode != AppMode::Game {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut retained = Vec::new();
|
|
||||||
let mut delivered = Vec::new();
|
|
||||||
|
|
||||||
for event in self.os.game_lifecycle_events.drain(..) {
|
|
||||||
if event.task_id == task_id {
|
|
||||||
delivered.push(event);
|
|
||||||
} else {
|
|
||||||
retained.push(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.game_lifecycle_events = retained;
|
|
||||||
if let Some(session) = self.os.vm_sessions.for_task_mut(task_id) {
|
|
||||||
session.runtime.deliver_game_lifecycle_events(delivered);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reset_global_runtime_state(&mut self) {
|
|
||||||
self.os.clear_cartridge_service_state();
|
|
||||||
self.os.vm_runtime.clear_cartridge_state();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn debug_step_active_session(
|
|
||||||
&mut self,
|
|
||||||
platform: &mut dyn RuntimePlatform,
|
|
||||||
) -> Option<CrashReport> {
|
|
||||||
let Some(task_id) = self.active_session_task_id() else {
|
|
||||||
return Some(CrashReport::VmPanic {
|
|
||||||
message: "debug step requested without an active VM session".to_string(),
|
|
||||||
pc: None,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
let Some(session) = self.os.vm_sessions.for_task_mut(task_id) else {
|
|
||||||
return Some(CrashReport::VmPanic {
|
|
||||||
message: format!("active debug task {:?} has no VM session", task_id),
|
|
||||||
pc: None,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
session.runtime.debug_step_instruction(&mut self.os.log_service, &mut session.vm, platform)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn active_pc(&self) -> Option<usize> {
|
|
||||||
self.active_session().map(|session| session.vm.pc())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn active_operand_stack_top(&self, n: usize) -> Vec<Value> {
|
|
||||||
self.active_session().map(|session| session.vm.operand_stack_top(n)).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn insert_active_breakpoint(&mut self, pc: usize) -> bool {
|
|
||||||
if let Some(session) = self.active_session_mut() {
|
|
||||||
session.vm.insert_breakpoint(pc);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove_active_breakpoint(&mut self, pc: usize) -> bool {
|
|
||||||
if let Some(session) = self.active_session_mut() {
|
|
||||||
session.vm.remove_breakpoint(pc);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn active_breakpoints_list(&self) -> Vec<usize> {
|
|
||||||
self.active_session().map(|session| session.vm.breakpoints_list()).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn paused(&self) -> bool {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.paused)
|
|
||||||
.unwrap_or(self.os.vm_runtime.paused)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_paused(&mut self, paused: bool) {
|
|
||||||
if let Some(session) = self.active_session_mut() {
|
|
||||||
session.runtime.paused = paused;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.vm_runtime.paused = paused;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_inspection_active(&mut self, active: bool) {
|
|
||||||
if let Some(session) = self.active_session_mut() {
|
|
||||||
session.runtime.inspection_active = active;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.vm_runtime.inspection_active = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn request_debug_step(&mut self) {
|
|
||||||
if let Some(session) = self.active_session_mut() {
|
|
||||||
session.runtime.debug_step_request = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.vm_runtime.debug_step_request = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear_debug_step_request(&mut self) {
|
|
||||||
if let Some(session) = self.active_session_mut() {
|
|
||||||
session.runtime.debug_step_request = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.vm_runtime.debug_step_request = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn debug_step_requested(&self) -> bool {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.debug_step_request)
|
|
||||||
.unwrap_or(self.os.vm_runtime.debug_step_request)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn logical_frame_active(&self) -> bool {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.logical_frame_active)
|
|
||||||
.unwrap_or(self.os.vm_runtime.logical_frame_active)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delivered_game_lifecycle_events(&self) -> &[GameLifecycleEvent] {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.delivered_game_lifecycle_events())
|
|
||||||
.unwrap_or_else(|| self.os.vm_runtime.delivered_game_lifecycle_events())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn take_delivered_game_lifecycle_events(&mut self) -> Vec<GameLifecycleEvent> {
|
|
||||||
if let Some(session) = self.active_session_mut() {
|
|
||||||
return session.runtime.take_delivered_game_lifecycle_events();
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.vm_runtime.take_delivered_game_lifecycle_events()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn tick_index(&self) -> u64 {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.tick_index)
|
|
||||||
.unwrap_or(self.os.vm_runtime.tick_index)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn logical_frame_index(&self) -> u64 {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.logical_frame_index)
|
|
||||||
.unwrap_or(self.os.vm_runtime.logical_frame_index)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn last_frame_cpu_time_us(&self) -> u64 {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.last_frame_cpu_time_us)
|
|
||||||
.unwrap_or(self.os.vm_runtime.last_frame_cpu_time_us)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn completed_logical_frames(&self) -> u64 {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| {
|
|
||||||
session
|
|
||||||
.runtime
|
|
||||||
.atomic_telemetry
|
|
||||||
.completed_logical_frames
|
|
||||||
.load(Ordering::Relaxed)
|
|
||||||
.into()
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| {
|
|
||||||
self.os
|
|
||||||
.vm_runtime
|
|
||||||
.atomic_telemetry
|
|
||||||
.completed_logical_frames
|
|
||||||
.load(Ordering::Relaxed)
|
|
||||||
.into()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn telemetry_snapshot(&self) -> TelemetryFrame {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.atomic_telemetry.snapshot())
|
|
||||||
.unwrap_or_else(|| self.os.vm_runtime.atomic_telemetry.snapshot())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn start_render_worker<B, S>(&mut self, config: RenderWorkerConfig, backend: B, sink: S)
|
|
||||||
where
|
|
||||||
B: RenderWorkerBackend,
|
|
||||||
S: RenderWorkerFrameSink,
|
|
||||||
{
|
|
||||||
self.os.vm_runtime.start_render_worker(config, backend, sink);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn stop_render_worker(&mut self) -> Result<(), RenderWorkerError> {
|
|
||||||
self.os.vm_runtime.stop_render_worker()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn render_worker_controller(&self) -> Option<&RenderWorkerController> {
|
|
||||||
self.os.vm_runtime.render_worker_controller.as_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_repeated_render_worker_frame(&self, frame_id: FrameId) {
|
|
||||||
self.os.vm_runtime.record_repeated_render_worker_frame(frame_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn active_render_ownership(&self) -> RenderOwnership {
|
|
||||||
if let Some(task_id) = self.foreground_session_task_id()
|
|
||||||
&& let Some(session) = self.os.vm_sessions.for_task(task_id)
|
|
||||||
{
|
|
||||||
return session.runtime.render_manager.active_ownership();
|
|
||||||
}
|
|
||||||
|
|
||||||
self.os.vm_runtime.render_manager.active_ownership()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn transition_render_owner(&mut self, app_mode: AppMode, app_id: u32) {
|
|
||||||
self.os.vm_runtime.render_manager.transition_render_owner(app_mode, app_id);
|
|
||||||
self.os.vm_runtime.sync_render_worker_ownership();
|
|
||||||
self.os.vm_runtime.render_manager.sync_telemetry(&self.os.vm_runtime.atomic_telemetry);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn cert_config(&self) -> &CertificationConfig {
|
|
||||||
&self.os.vm_runtime.certifier.config
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn last_crash_report(&self) -> Option<&CrashReport> {
|
|
||||||
self.active_session()
|
|
||||||
.and_then(|session| session.runtime.last_crash_report.as_ref())
|
|
||||||
.or(self.os.vm_runtime.last_crash_report.as_ref())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn current_app_id(&self) -> u32 {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.current_app_id)
|
|
||||||
.unwrap_or(self.os.vm_runtime.current_app_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn current_cartridge_title(&self) -> String {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.current_cartridge_title.clone())
|
|
||||||
.unwrap_or_else(|| self.os.vm_runtime.current_cartridge_title.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn current_cartridge_app_version(&self) -> String {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.current_cartridge_app_version.clone())
|
|
||||||
.unwrap_or_else(|| self.os.vm_runtime.current_cartridge_app_version.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn current_cartridge_app_mode(&self) -> AppMode {
|
|
||||||
self.active_session()
|
|
||||||
.map(|session| session.runtime.current_cartridge_app_mode)
|
|
||||||
.unwrap_or(self.os.vm_runtime.current_cartridge_app_mode)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn active_session(&self) -> Option<&VmSession> {
|
|
||||||
self.os
|
|
||||||
.task_manager
|
|
||||||
.foreground_task()
|
|
||||||
.and_then(|task_id| self.os.vm_sessions.for_task(task_id))
|
|
||||||
.or_else(|| {
|
|
||||||
self.os
|
|
||||||
.foreground_stack
|
|
||||||
.resident_game_task()
|
|
||||||
.and_then(|task_id| self.os.vm_sessions.for_task(task_id))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn active_session_mut(&mut self) -> Option<&mut VmSession> {
|
|
||||||
let task_id = self.active_session_task_id()?;
|
|
||||||
self.os.vm_sessions.for_task_mut(task_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn active_session_task_id(&self) -> Option<TaskId> {
|
|
||||||
self.os
|
|
||||||
.task_manager
|
|
||||||
.foreground_task()
|
|
||||||
.or_else(|| self.os.foreground_stack.resident_game_task())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn foreground_session_task_id(&self) -> Option<TaskId> {
|
|
||||||
self.os.task_manager.foreground_task()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
use crate::os::SystemOS;
|
|
||||||
use crate::task::TaskId;
|
|
||||||
use crate::windows::{Window, WindowId, WindowOwner};
|
|
||||||
use prometeu_hal::color::Color;
|
|
||||||
use prometeu_hal::primitives::Rect;
|
|
||||||
|
|
||||||
pub struct WindowFacade<'a> {
|
|
||||||
pub(in crate::os) os: &'a mut SystemOS,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> WindowFacade<'a> {
|
|
||||||
pub fn add_window(
|
|
||||||
&mut self,
|
|
||||||
title: String,
|
|
||||||
owner: WindowOwner,
|
|
||||||
viewport: Rect,
|
|
||||||
color: Color,
|
|
||||||
) -> WindowId {
|
|
||||||
self.os.window_manager.add_window(title, owner, viewport, color)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_focus(&mut self, id: WindowId) {
|
|
||||||
self.os.window_manager.set_focus(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn focused_window(&self) -> Option<WindowId> {
|
|
||||||
self.os.window_manager.focused
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn focused_window_belongs_to_task(&self, task_id: TaskId) -> bool {
|
|
||||||
self.os.window_manager.focused_window_belongs_to_task(task_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn close_window(&mut self, id: WindowId) {
|
|
||||||
self.os.window_manager.remove_window(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove_all_windows(&mut self) {
|
|
||||||
self.os.window_manager.remove_all_windows();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn windows(&self) -> &[Window] {
|
|
||||||
&self.os.window_manager.windows
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn window_count(&self) -> usize {
|
|
||||||
self.os.window_manager.windows.len()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
use crate::process::ProcessId;
|
|
||||||
use crate::task::{TaskId, TaskState};
|
|
||||||
|
|
||||||
pub const DEFAULT_GAME_PAUSE_BUDGET_TICKS: u8 = 1;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum GameLifecycleEventKind {
|
|
||||||
Pause,
|
|
||||||
ResumeForeground,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct GameLifecycleEvent {
|
|
||||||
pub task_id: TaskId,
|
|
||||||
pub kind: GameLifecycleEventKind,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum LifecycleOperation {
|
|
||||||
SetForeground,
|
|
||||||
Suspend,
|
|
||||||
Resume,
|
|
||||||
Close,
|
|
||||||
Crash,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum LifecycleError {
|
|
||||||
TaskNotFound(TaskId),
|
|
||||||
ProcessNotFound(ProcessId),
|
|
||||||
InvalidTransition { task_id: TaskId, from: TaskState, operation: LifecycleOperation },
|
|
||||||
ResidentGameAlreadyExists { existing: TaskId, requested: TaskId },
|
|
||||||
ForegroundShellAlreadyExists { existing: TaskId, requested: TaskId },
|
|
||||||
TaskIsNotResidentGame(TaskId),
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
mod facades;
|
|
||||||
mod lifecycle;
|
|
||||||
mod system_os;
|
|
||||||
|
|
||||||
pub use facades::{
|
|
||||||
FsFacade, LifecycleFacade, SessionError, SessionsFacade, VmFacade, WindowFacade,
|
|
||||||
};
|
|
||||||
pub use lifecycle::{
|
|
||||||
DEFAULT_GAME_PAUSE_BUDGET_TICKS, GameLifecycleEvent, GameLifecycleEventKind, LifecycleError,
|
|
||||||
LifecycleOperation,
|
|
||||||
};
|
|
||||||
pub use system_os::SystemOS;
|
|
||||||
@@ -1,680 +0,0 @@
|
|||||||
use crate::VirtualMachineRuntime;
|
|
||||||
use crate::fs::{FsState, VirtualFS};
|
|
||||||
use crate::os::{
|
|
||||||
FsFacade, GameLifecycleEvent, LifecycleFacade, SessionsFacade, VmFacade, WindowFacade,
|
|
||||||
};
|
|
||||||
use crate::process::ProcessManager;
|
|
||||||
use crate::services::foreground::ForegroundStack;
|
|
||||||
use crate::services::memcard::MemcardService;
|
|
||||||
use crate::services::vm_session::VmSessionRegistry;
|
|
||||||
use crate::services::windows::WindowManager;
|
|
||||||
use crate::task::TaskManager;
|
|
||||||
use prometeu_hal::log::{LogEvent, LogLevel, LogService, LogSource};
|
|
||||||
use prometeu_hal::telemetry::CertificationConfig;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub struct SystemOS {
|
|
||||||
pub(super) vm_runtime: VirtualMachineRuntime,
|
|
||||||
pub(super) process_manager: ProcessManager,
|
|
||||||
pub(super) task_manager: TaskManager,
|
|
||||||
pub(super) foreground_stack: ForegroundStack,
|
|
||||||
pub(super) vm_sessions: VmSessionRegistry,
|
|
||||||
pub(super) game_lifecycle_events: Vec<GameLifecycleEvent>,
|
|
||||||
pub(super) window_manager: WindowManager,
|
|
||||||
pub(super) log_service: LogService,
|
|
||||||
pub(super) fs: VirtualFS,
|
|
||||||
pub(super) fs_state: FsState,
|
|
||||||
pub(super) memcard: MemcardService,
|
|
||||||
pub(super) open_files: HashMap<u32, String>,
|
|
||||||
pub(super) next_handle: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SystemOS {
|
|
||||||
pub fn new(cap_config: Option<CertificationConfig>) -> Self {
|
|
||||||
let log_service = LogService::new(4096);
|
|
||||||
let mut os = Self {
|
|
||||||
vm_runtime: VirtualMachineRuntime::new_with_log_counter(
|
|
||||||
cap_config,
|
|
||||||
Arc::clone(&log_service.logs_count),
|
|
||||||
),
|
|
||||||
process_manager: ProcessManager::new(),
|
|
||||||
task_manager: TaskManager::new(),
|
|
||||||
foreground_stack: ForegroundStack::new(),
|
|
||||||
vm_sessions: VmSessionRegistry::new(),
|
|
||||||
game_lifecycle_events: Vec::new(),
|
|
||||||
window_manager: WindowManager::new(),
|
|
||||||
log_service,
|
|
||||||
fs: VirtualFS::new(),
|
|
||||||
fs_state: FsState::Unmounted,
|
|
||||||
memcard: MemcardService::new(),
|
|
||||||
open_files: HashMap::new(),
|
|
||||||
next_handle: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
os.log(LogLevel::Info, LogSource::Pos, 0, "PrometeuOS starting...".to_string());
|
|
||||||
|
|
||||||
os
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn log(&mut self, level: LogLevel, source: LogSource, tag: u16, msg: String) {
|
|
||||||
self.vm_runtime.log(&mut self.log_service, level, source, tag, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn trace(&mut self, source: LogSource, msg: String) {
|
|
||||||
self.log(LogLevel::Trace, source, 0, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn trace_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
|
||||||
self.log(LogLevel::Trace, source, tag, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn debug(&mut self, source: LogSource, msg: String) {
|
|
||||||
self.log(LogLevel::Debug, source, 0, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn debug_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
|
||||||
self.log(LogLevel::Debug, source, tag, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn info(&mut self, source: LogSource, msg: String) {
|
|
||||||
self.log(LogLevel::Info, source, 0, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn info_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
|
||||||
self.log(LogLevel::Info, source, tag, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn warn(&mut self, source: LogSource, msg: String) {
|
|
||||||
self.log(LogLevel::Warn, source, 0, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn warn_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
|
||||||
self.log(LogLevel::Warn, source, tag, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn error(&mut self, source: LogSource, msg: String) {
|
|
||||||
self.log(LogLevel::Error, source, 0, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn error_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
|
||||||
self.log(LogLevel::Error, source, tag, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn recent_logs(&self, n: usize) -> Vec<LogEvent> {
|
|
||||||
self.log_service.get_recent(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn logs_after(&self, seq: u64) -> Vec<LogEvent> {
|
|
||||||
self.log_service.get_after(seq)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn frame_index(&mut self) -> u64 {
|
|
||||||
self.vm().logical_frame_index()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lifecycle(&mut self) -> LifecycleFacade<'_> {
|
|
||||||
LifecycleFacade { os: self }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn sessions(&mut self) -> SessionsFacade<'_> {
|
|
||||||
SessionsFacade { os: self }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn vm(&mut self) -> VmFacade<'_> {
|
|
||||||
VmFacade { os: self }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn fs(&mut self) -> FsFacade<'_> {
|
|
||||||
FsFacade { os: self }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn windows(&mut self) -> WindowFacade<'_> {
|
|
||||||
WindowFacade { os: self }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn clear_cartridge_service_state(&mut self) {
|
|
||||||
self.open_files.clear();
|
|
||||||
self.next_handle = 1;
|
|
||||||
self.memcard.clear_all_staging();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::os::{GameLifecycleEventKind, LifecycleError, LifecycleOperation, SessionError};
|
|
||||||
use crate::process::{ProcessId, ProcessKind, ProcessState};
|
|
||||||
use crate::services::foreground::{ForegroundOwner, ResidentGame, ResidentGameState};
|
|
||||||
use crate::task::{TaskId, TaskState};
|
|
||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::cartridge::{AssetsPayloadSource, Cartridge};
|
|
||||||
use prometeu_hal::syscalls::caps;
|
|
||||||
|
|
||||||
fn process_state_for_task(os: &SystemOS, task_id: TaskId) -> ProcessState {
|
|
||||||
let task = os.task_manager.get(task_id).expect("task should exist");
|
|
||||||
os.process_manager.get(task.process_id).expect("process should exist").state
|
|
||||||
}
|
|
||||||
|
|
||||||
fn session_test_cartridge(app_mode: AppMode, app_id: u32, title: &str) -> Cartridge {
|
|
||||||
Cartridge {
|
|
||||||
app_id,
|
|
||||||
title: title.to_string(),
|
|
||||||
app_version: "1.0.0".to_string(),
|
|
||||||
app_mode,
|
|
||||||
capabilities: caps::NONE,
|
|
||||||
program: vec![],
|
|
||||||
assets: AssetsPayloadSource::empty(),
|
|
||||||
asset_table: vec![],
|
|
||||||
preload: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn set_foreground_task_marks_task_and_process_running() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
os.lifecycle().suspend_task(task_id).expect("suspend should succeed");
|
|
||||||
os.lifecycle().set_foreground_task(task_id).expect("foreground should succeed");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(task_id).expect("task should exist").state,
|
|
||||||
TaskState::Foreground
|
|
||||||
);
|
|
||||||
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Running);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn foreground_stack_starts_at_hub() {
|
|
||||||
let os = SystemOS::new(None);
|
|
||||||
|
|
||||||
assert_eq!(os.foreground_stack.owner(), ForegroundOwner::Hub);
|
|
||||||
assert_eq!(os.foreground_stack.resident_game(), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn game_session_registers_single_resident_game() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Game(task_id));
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().resident_game(),
|
|
||||||
Some(ResidentGame { task_id, state: ResidentGameState::Foreground })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn second_resident_game_is_rejected() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let first = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
let process_id = os.process_manager.spawn_vm_game(43, "Second");
|
|
||||||
let second = os.task_manager.create_game_task(process_id, 43, "Second");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().set_game_foreground_task(second),
|
|
||||||
Err(LifecycleError::ResidentGameAlreadyExists { existing: first, requested: second })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn terminate_resident_game_closes_task_and_removes_vm_session() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
|
||||||
assert_eq!(os.lifecycle().pending_game_lifecycle_events().len(), 1);
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().terminate_resident_game(), Ok(Some(game)));
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().resident_game(), None);
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Hub);
|
|
||||||
assert_eq!(os.lifecycle().task_state(game), Some(TaskState::Closed));
|
|
||||||
assert_eq!(process_state_for_task(&os, game), ProcessState::Stopped);
|
|
||||||
assert_eq!(os.sessions().vm_session_for_task(game).map(|session| session.task_id), None);
|
|
||||||
assert!(os.lifecycle().pending_game_lifecycle_events().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn terminate_resident_game_preserves_foreground_shell() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
|
||||||
os.lifecycle().advance_game_pause_budget(game).expect("budget should expire");
|
|
||||||
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().terminate_resident_game(), Ok(Some(game)));
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
|
||||||
assert_eq!(os.lifecycle().resident_game(), None);
|
|
||||||
assert_eq!(os.lifecycle().task_state(game), Some(TaskState::Closed));
|
|
||||||
assert_eq!(process_state_for_task(&os, game), ProcessState::Stopped);
|
|
||||||
assert_eq!(os.sessions().vm_session_for_task(game).map(|session| session.task_id), None);
|
|
||||||
assert_eq!(os.lifecycle().task_state(shell), Some(TaskState::Foreground));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vm_game_task_creates_vm_session() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
let sessions = os.sessions();
|
|
||||||
let session = sessions.vm_session_for_task(task_id).expect("VM session should exist");
|
|
||||||
|
|
||||||
assert_eq!(session.task_id, task_id);
|
|
||||||
assert_eq!(session.app_id, 42);
|
|
||||||
assert_eq!(session.title, "Sector Crawl");
|
|
||||||
assert_eq!(session.app_mode, AppMode::Game);
|
|
||||||
assert_eq!(sessions.vm_session_count(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vm_shell_task_creates_vm_session() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
let sessions = os.sessions();
|
|
||||||
let session = sessions.vm_session_for_task(task_id).expect("VM session should exist");
|
|
||||||
|
|
||||||
assert_eq!(session.task_id, task_id);
|
|
||||||
assert_eq!(session.app_id, 7);
|
|
||||||
assert_eq!(session.title, "Settings");
|
|
||||||
assert_eq!(session.app_mode, AppMode::Shell);
|
|
||||||
assert_eq!(sessions.vm_session_count(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn native_shell_task_does_not_create_vm_session() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_native_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
let sessions = os.sessions();
|
|
||||||
|
|
||||||
assert!(sessions.vm_session_for_task(task_id).is_none());
|
|
||||||
assert_eq!(sessions.vm_session_count(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn same_resident_game_app_reuses_existing_vm_session() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let first = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
let second = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
let sessions = os.sessions();
|
|
||||||
|
|
||||||
assert_eq!(second, first);
|
|
||||||
assert_eq!(
|
|
||||||
sessions.resident_game_session_for_app(42).map(|session| session.task_id),
|
|
||||||
Some(first)
|
|
||||||
);
|
|
||||||
assert_eq!(sessions.vm_session_count(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vm_sessions_hold_independent_runtime_state() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
|
||||||
os.lifecycle().advance_game_pause_budget(game).expect("budget should expire");
|
|
||||||
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut sessions = os.sessions();
|
|
||||||
let game_session =
|
|
||||||
sessions.vm_session_for_task_mut(game).expect("game VM session should exist");
|
|
||||||
game_session.runtime.tick_index = 100;
|
|
||||||
game_session.open_files.insert(1, "/game.dat".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut sessions = os.sessions();
|
|
||||||
let shell_session =
|
|
||||||
sessions.vm_session_for_task_mut(shell).expect("shell VM session should exist");
|
|
||||||
shell_session.runtime.tick_index = 5;
|
|
||||||
shell_session.open_files.insert(1, "/shell.dat".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
let sessions = os.sessions();
|
|
||||||
let game_session =
|
|
||||||
sessions.vm_session_for_task(game).expect("game VM session should exist");
|
|
||||||
let shell_session =
|
|
||||||
sessions.vm_session_for_task(shell).expect("shell VM session should exist");
|
|
||||||
|
|
||||||
assert_eq!(game_session.runtime.tick_index, 100);
|
|
||||||
assert_eq!(shell_session.runtime.tick_index, 5);
|
|
||||||
assert_eq!(game_session.open_files.get(&1).map(String::as_str), Some("/game.dat"));
|
|
||||||
assert_eq!(shell_session.open_files.get(&1).map(String::as_str), Some("/shell.dat"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vm_debug_operations_target_foreground_shell_before_resident_game() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
|
||||||
os.lifecycle().advance_game_pause_budget(game).expect("budget should expire");
|
|
||||||
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut sessions = os.sessions();
|
|
||||||
let game_session =
|
|
||||||
sessions.vm_session_for_task_mut(game).expect("game VM session should exist");
|
|
||||||
game_session.vm.insert_breakpoint(10);
|
|
||||||
}
|
|
||||||
|
|
||||||
assert!(os.vm().insert_active_breakpoint(20));
|
|
||||||
assert_eq!(os.vm().active_breakpoints_list(), vec![20]);
|
|
||||||
|
|
||||||
let sessions = os.sessions();
|
|
||||||
assert_eq!(
|
|
||||||
sessions
|
|
||||||
.vm_session_for_task(game)
|
|
||||||
.expect("game VM session should exist")
|
|
||||||
.vm
|
|
||||||
.breakpoints_list(),
|
|
||||||
vec![10]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
sessions
|
|
||||||
.vm_session_for_task(shell)
|
|
||||||
.expect("shell VM session should exist")
|
|
||||||
.vm
|
|
||||||
.breakpoints_list(),
|
|
||||||
vec![20]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn home_request_notifies_game_before_budget_suspends_it() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
os.lifecycle().request_home_from_game(task_id).expect("home request should succeed");
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Game(task_id));
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().resident_game(),
|
|
||||||
Some(ResidentGame {
|
|
||||||
task_id,
|
|
||||||
state: ResidentGameState::PauseRequested { remaining_ticks: 1 },
|
|
||||||
})
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().pending_game_lifecycle_events()[0].kind,
|
|
||||||
GameLifecycleEventKind::Pause
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(task_id).expect("task should exist").state,
|
|
||||||
TaskState::Foreground
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(os.lifecycle().advance_game_pause_budget(task_id).expect("budget should advance"));
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Hub);
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().resident_game(),
|
|
||||||
Some(ResidentGame { task_id, state: ResidentGameState::PausedSuspended })
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(task_id).expect("task should exist").state,
|
|
||||||
TaskState::Suspended
|
|
||||||
);
|
|
||||||
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Suspended);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn shell_foreground_keeps_game_resident_and_marks_it_suspended() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
|
||||||
os.lifecycle().advance_game_pause_budget(game).expect("budget should expire");
|
|
||||||
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().resident_game(),
|
|
||||||
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vm_shell_foreground_suspends_foreground_resident_game() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().resident_game(),
|
|
||||||
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(game).expect("game should exist").state,
|
|
||||||
TaskState::Suspended
|
|
||||||
);
|
|
||||||
assert_eq!(process_state_for_task(&os, game), ProcessState::Suspended);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn native_shell_foreground_suspends_foreground_resident_game() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
let shell = os.sessions().create_native_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().resident_game(),
|
|
||||||
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(game).expect("game should exist").state,
|
|
||||||
TaskState::Suspended
|
|
||||||
);
|
|
||||||
assert_eq!(process_state_for_task(&os, game), ProcessState::Suspended);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn lifecycle_exposes_process_kind_for_shell_tasks() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let vm_shell = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
os.lifecycle().close_task(vm_shell).expect("vm shell should close");
|
|
||||||
|
|
||||||
let native_shell = os.sessions().create_native_shell_task(8, "Files");
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().process_kind_for_task(vm_shell), Ok(ProcessKind::VmShell));
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().process_kind_for_task(native_shell),
|
|
||||||
Ok(ProcessKind::NativeShell)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn second_foreground_shell_is_rejected() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let first = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
let process_id = os.process_manager.spawn_vm_shell(8, "Files");
|
|
||||||
let second = os.task_manager.create_shell_task(process_id, 8, "Files");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().set_shell_foreground_task(second),
|
|
||||||
Err(LifecycleError::ForegroundShellAlreadyExists {
|
|
||||||
existing: first,
|
|
||||||
requested: second,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vm_shell_load_returns_typed_error_when_foreground_shell_exists() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let first = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
let cartridge = session_test_cartridge(AppMode::Shell, 8, "Files");
|
|
||||||
|
|
||||||
let error = os.sessions().load_vm_cartridge(&cartridge).expect_err("load should fail");
|
|
||||||
|
|
||||||
match error {
|
|
||||||
SessionError::Lifecycle(LifecycleError::ForegroundShellAlreadyExists {
|
|
||||||
existing,
|
|
||||||
requested,
|
|
||||||
}) => {
|
|
||||||
assert_eq!(existing, first);
|
|
||||||
assert_ne!(requested, first);
|
|
||||||
}
|
|
||||||
other => panic!("expected foreground shell lifecycle error, got {:?}", other),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vm_session_creation_returns_typed_error_for_missing_task() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.sessions().try_create_vm_session_for_task(TaskId(999)),
|
|
||||||
Err(SessionError::TaskNotFound(TaskId(999)))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vm_session_creation_returns_typed_error_for_missing_process() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.task_manager.create_game_task(ProcessId(999), 42, "Broken");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.sessions().try_create_vm_session_for_task(task_id),
|
|
||||||
Err(SessionError::ProcessNotFound(ProcessId(999)))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn session_cartridge_initialization_returns_typed_error_for_missing_session() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let process_id = os.process_manager.spawn_vm_game(42, "Sector Crawl");
|
|
||||||
let task_id = os.task_manager.create_game_task(process_id, 42, "Sector Crawl");
|
|
||||||
let cartridge = session_test_cartridge(AppMode::Game, 42, "Sector Crawl");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.sessions().try_initialize_session_cartridge(task_id, &cartridge),
|
|
||||||
Err(SessionError::MissingVmSession(task_id))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn closing_foreground_shell_returns_to_hub() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
|
||||||
|
|
||||||
os.lifecycle().close_task(shell).expect("close should succeed");
|
|
||||||
|
|
||||||
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Hub);
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(shell).expect("shell should remain").state,
|
|
||||||
TaskState::Closed
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn suspend_task_marks_task_and_process_suspended() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
os.lifecycle().suspend_task(task_id).expect("suspend should succeed");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(task_id).expect("task should exist").state,
|
|
||||||
TaskState::Suspended
|
|
||||||
);
|
|
||||||
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Suspended);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resume_task_marks_suspended_task_foreground_and_process_running() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
os.lifecycle().suspend_task(task_id).expect("suspend should succeed");
|
|
||||||
os.lifecycle().resume_task(task_id).expect("resume should succeed");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(task_id).expect("task should exist").state,
|
|
||||||
TaskState::Foreground
|
|
||||||
);
|
|
||||||
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Running);
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().pending_game_lifecycle_events().last().map(|event| event.kind),
|
|
||||||
Some(GameLifecycleEventKind::ResumeForeground)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn close_task_marks_task_closed_and_process_stopped_without_removing_entities() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
let process_id = os.task_manager.get(task_id).expect("task should exist").process_id;
|
|
||||||
|
|
||||||
os.lifecycle().close_task(task_id).expect("close should succeed");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(task_id).expect("task should remain").state,
|
|
||||||
TaskState::Closed
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
os.process_manager.get(process_id).expect("process should remain").state,
|
|
||||||
ProcessState::Stopped
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn crash_task_marks_task_and_process_crashed() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
os.lifecycle().crash_task(task_id, None).expect("crash should succeed");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.task_manager.get(task_id).expect("task should exist").state,
|
|
||||||
TaskState::Crashed
|
|
||||||
);
|
|
||||||
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Crashed);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn lifecycle_operation_missing_task_returns_typed_error() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().suspend_task(TaskId(999)),
|
|
||||||
Err(LifecycleError::TaskNotFound(TaskId(999)))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn lifecycle_operation_missing_process_returns_typed_error() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
let process_id = os.task_manager.get(task_id).expect("task should exist").process_id;
|
|
||||||
|
|
||||||
os.process_manager.mark_stopped(process_id);
|
|
||||||
os.process_manager.remove_stopped();
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().suspend_task(task_id),
|
|
||||||
Err(LifecycleError::ProcessNotFound(process_id))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resume_task_from_non_suspended_state_returns_invalid_transition() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
os.lifecycle().resume_task(task_id),
|
|
||||||
Err(LifecycleError::InvalidTransition {
|
|
||||||
task_id,
|
|
||||||
from: TaskState::Foreground,
|
|
||||||
operation: LifecycleOperation::Resume,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,3 @@
|
|||||||
mod prometeu_hub;
|
mod prometeu_hub;
|
||||||
|
|
||||||
pub use prometeu_hub::{
|
pub use prometeu_hub::PrometeuHub;
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
|
|
||||||
SystemProfileUpdate,
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
#[allow(clippy::module_inception)]
|
#[allow(clippy::module_inception)]
|
||||||
mod prometeu_hub;
|
mod prometeu_hub;
|
||||||
|
mod window_manager;
|
||||||
|
|
||||||
pub use prometeu_hub::{
|
pub use prometeu_hub::PrometeuHub;
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
|
|
||||||
SystemProfileUpdate,
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,99 +1,13 @@
|
|||||||
use crate::task::TaskId;
|
use crate::VirtualMachineRuntime;
|
||||||
use crate::{CrashReport, GameLibrary, GameSwitchTarget, SystemOS};
|
use crate::programs::prometeu_hub::window_manager::WindowManager;
|
||||||
use prometeu_hal::app_mode::AppMode;
|
use prometeu_hal::HardwareBridge;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::primitives::Rect;
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
use prometeu_hal::{
|
use prometeu_hal::window::Rect;
|
||||||
FrameId, GfxUiCommand, InputPlatform, InputSignals, RenderSubmission, RuntimePlatform,
|
|
||||||
ShellUiFramePacket,
|
|
||||||
};
|
|
||||||
|
|
||||||
const SHELL_A_BUTTON: Rect = Rect { x: 112, y: 172, w: 112, h: 32 };
|
|
||||||
const SHELL_B_BUTTON: Rect = Rect { x: 256, y: 172, w: 112, h: 32 };
|
|
||||||
const CLOSE_BUTTON: Rect = Rect { x: 420, y: 24, w: 16, h: 16 };
|
|
||||||
const VIEWPORT: Rect = Rect { x: 0, y: 0, w: 480, h: 270 };
|
|
||||||
const HOME_PANEL: Rect = Rect { x: 48, y: 58, w: 384, h: 154 };
|
|
||||||
const TITLE_PANEL: Rect = Rect { x: 72, y: 34, w: 336, h: 28 };
|
|
||||||
const GAME_ROW_X: i32 = 72;
|
|
||||||
const GAME_ROW_Y: i32 = 90;
|
|
||||||
const GAME_ROW_W: i32 = 336;
|
|
||||||
const GAME_ROW_H: i32 = 22;
|
|
||||||
const GAME_ROW_GAP: i32 = 6;
|
|
||||||
const MAX_HOME_GAME_ROWS: usize = 3;
|
|
||||||
pub const HUB_SUSPENDED_GAME_KILL_CONTROL: Rect = Rect { x: 288, y: 230, w: 168, h: 24 };
|
|
||||||
#[cfg(test)]
|
|
||||||
const SHELL_FRAME: Rect = Rect { x: 40, y: 20, w: 400, h: 220 };
|
|
||||||
|
|
||||||
const COLOR_BG: Color = Color::rgb(12, 14, 22);
|
|
||||||
const COLOR_PANEL: Color = Color::rgb(25, 31, 48);
|
|
||||||
const COLOR_PANEL_DARK: Color = Color::rgb(8, 10, 16);
|
|
||||||
const COLOR_BORDER: Color = Color::rgb(180, 218, 222);
|
|
||||||
const COLOR_HILITE: Color = Color::rgb(252, 226, 122);
|
|
||||||
const COLOR_TEXT: Color = Color::rgb(230, 236, 224);
|
|
||||||
const COLOR_MUTED: Color = Color::rgb(91, 112, 128);
|
|
||||||
const COLOR_BUTTON: Color = Color::rgb(45, 59, 82);
|
|
||||||
const COLOR_BUTTON_ACTIVE: Color = Color::rgb(72, 91, 122);
|
|
||||||
const COLOR_KILL: Color = Color::rgb(164, 32, 40);
|
|
||||||
const COLOR_KILL_ACTIVE: Color = Color::rgb(206, 46, 54);
|
|
||||||
|
|
||||||
/// PrometeuHub: Launcher and system UI environment.
|
/// PrometeuHub: Launcher and system UI environment.
|
||||||
pub struct PrometeuHub {
|
pub struct PrometeuHub {
|
||||||
home_input_armed: bool,
|
pub window_manager: WindowManager,
|
||||||
game_library: GameLibrary,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum NativeShellApp {
|
|
||||||
ShellA,
|
|
||||||
ShellB,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
struct HubButtonSpec {
|
|
||||||
app: NativeShellApp,
|
|
||||||
rect: Rect,
|
|
||||||
label: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
const HOME_BUTTONS: [HubButtonSpec; 2] = [
|
|
||||||
HubButtonSpec { app: NativeShellApp::ShellA, rect: SHELL_A_BUTTON, label: "ShellA" },
|
|
||||||
HubButtonSpec { app: NativeShellApp::ShellB, rect: SHELL_B_BUTTON, label: "ShellB" },
|
|
||||||
];
|
|
||||||
|
|
||||||
impl NativeShellApp {
|
|
||||||
pub fn app_id(self) -> u32 {
|
|
||||||
match self {
|
|
||||||
Self::ShellA => 10_001,
|
|
||||||
Self::ShellB => 10_002,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn title(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::ShellA => "ShellA",
|
|
||||||
Self::ShellB => "ShellB",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn color(self) -> Color {
|
|
||||||
match self {
|
|
||||||
Self::ShellA => Color::GREEN,
|
|
||||||
Self::ShellB => Color::BLUE,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum SystemProfileAction {
|
|
||||||
LaunchNativeShell(NativeShellApp),
|
|
||||||
LaunchGame { target: GameSwitchTarget },
|
|
||||||
KillResidentGame,
|
|
||||||
CloseShell,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SystemProfileUpdate {
|
|
||||||
pub crash: Option<CrashReport>,
|
|
||||||
pub action: Option<SystemProfileAction>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for PrometeuHub {
|
impl Default for PrometeuHub {
|
||||||
@@ -104,729 +18,61 @@ impl Default for PrometeuHub {
|
|||||||
|
|
||||||
impl PrometeuHub {
|
impl PrometeuHub {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self { home_input_armed: false, game_library: GameLibrary::empty() }
|
Self { window_manager: WindowManager::new() }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn init(&mut self) {
|
pub fn init(&mut self) {
|
||||||
self.home_input_armed = false;
|
// Initializes the Window System and lists apps
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_game_library(&mut self, game_library: GameLibrary) {
|
pub fn gui_update(&mut self, os: &mut VirtualMachineRuntime, hw: &mut dyn HardwareBridge) {
|
||||||
self.game_library = game_library;
|
hw.gfx_mut().clear(Color::BLACK);
|
||||||
}
|
|
||||||
|
|
||||||
pub fn game_library(&self) -> &GameLibrary {
|
let mut next_window = None;
|
||||||
&self.game_library
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn gui_update(
|
if hw.pad().a().pressed {
|
||||||
&mut self,
|
os.log(LogLevel::Debug, LogSource::Hub, 0, "window A opened".to_string());
|
||||||
os: &mut SystemOS,
|
next_window = Some((
|
||||||
platform: &mut dyn RuntimePlatform,
|
"Green Window".to_string(),
|
||||||
) -> Option<SystemProfileAction> {
|
Rect { x: 0, y: 0, w: 160, h: 90 },
|
||||||
let in_shell = os.windows().focused_window().is_some();
|
|
||||||
|
|
||||||
if !in_shell {
|
|
||||||
if !self.home_input_armed {
|
|
||||||
self.home_input_armed = !activation_input_down(platform.input());
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.home_input_armed = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let input = platform.input();
|
|
||||||
let suspended_game = if in_shell { None } else { resident_game_indicator(os) };
|
|
||||||
if let Some(action) = action_for_click(
|
|
||||||
in_shell,
|
|
||||||
input.touch().x(),
|
|
||||||
input.touch().y(),
|
|
||||||
input.touch().f().pressed,
|
|
||||||
self.game_library.entries(),
|
|
||||||
suspended_game.as_ref(),
|
|
||||||
) {
|
|
||||||
return Some(action);
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn render(&mut self, os: &mut SystemOS, platform: &mut dyn RuntimePlatform) {
|
|
||||||
let pointer_x = platform.input().touch().x();
|
|
||||||
let pointer_y = platform.input().touch().y();
|
|
||||||
|
|
||||||
let packet = if os.windows().window_count() == 0 {
|
|
||||||
let suspended_game = resident_game_indicator(os);
|
|
||||||
render_home_packet(
|
|
||||||
pointer_x,
|
|
||||||
pointer_y,
|
|
||||||
self.game_library.entries(),
|
|
||||||
suspended_game.as_ref(),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
let mut commands = Vec::new();
|
|
||||||
for window in os.windows().windows() {
|
|
||||||
append_shell_window_commands(
|
|
||||||
&mut commands,
|
|
||||||
window.viewport,
|
|
||||||
window.color,
|
|
||||||
&window.title,
|
|
||||||
pointer_x,
|
|
||||||
pointer_y,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
ShellUiFramePacket::new(commands)
|
|
||||||
};
|
|
||||||
platform
|
|
||||||
.render_submission_sink()
|
|
||||||
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
|
|
||||||
.expect("hub render submission should publish");
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update_shell_profile(
|
|
||||||
&mut self,
|
|
||||||
os: &mut SystemOS,
|
|
||||||
platform: &mut dyn RuntimePlatform,
|
|
||||||
) -> SystemProfileUpdate {
|
|
||||||
let mut action = self.gui_update(os, platform);
|
|
||||||
|
|
||||||
if os.windows().focused_window().is_some() && platform.input().pad().start().down {
|
|
||||||
action = Some(SystemProfileAction::CloseShell);
|
|
||||||
}
|
|
||||||
|
|
||||||
self.render(os, platform);
|
|
||||||
|
|
||||||
SystemProfileUpdate { crash: None, action }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update_vm_shell_profile(
|
|
||||||
&mut self,
|
|
||||||
os: &mut SystemOS,
|
|
||||||
task_id: TaskId,
|
|
||||||
signals: &InputSignals,
|
|
||||||
platform: &mut dyn RuntimePlatform,
|
|
||||||
) -> SystemProfileUpdate {
|
|
||||||
let mut crash = None;
|
|
||||||
let mut action = self.gui_update(os, platform);
|
|
||||||
|
|
||||||
if os.windows().focused_window().is_some() {
|
|
||||||
if platform.input().pad().start().down {
|
|
||||||
action = Some(SystemProfileAction::CloseShell);
|
|
||||||
} else if action != Some(SystemProfileAction::CloseShell) {
|
|
||||||
crash = os.vm().tick_session(task_id, signals, platform);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.render(os, platform);
|
|
||||||
|
|
||||||
SystemProfileUpdate { crash, action }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update_native_shell_profile(
|
|
||||||
&mut self,
|
|
||||||
os: &mut SystemOS,
|
|
||||||
platform: &mut dyn RuntimePlatform,
|
|
||||||
) -> SystemProfileUpdate {
|
|
||||||
let mut action = self.gui_update(os, platform);
|
|
||||||
|
|
||||||
if os.windows().focused_window().is_some() && platform.input().pad().start().down {
|
|
||||||
action = Some(SystemProfileAction::CloseShell);
|
|
||||||
}
|
|
||||||
|
|
||||||
self.render(os, platform);
|
|
||||||
|
|
||||||
SystemProfileUpdate { crash: None, action }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn action_for_click(
|
|
||||||
in_shell: bool,
|
|
||||||
x: i32,
|
|
||||||
y: i32,
|
|
||||||
pressed: bool,
|
|
||||||
game_entries: &[crate::GameLibraryEntry],
|
|
||||||
suspended_game: Option<&SuspendedGameIndicator>,
|
|
||||||
) -> Option<SystemProfileAction> {
|
|
||||||
if !pressed {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
if in_shell {
|
|
||||||
return rect_contains(CLOSE_BUTTON, x, y).then_some(SystemProfileAction::CloseShell);
|
|
||||||
}
|
|
||||||
|
|
||||||
if suspended_game.is_some() && rect_contains(HUB_SUSPENDED_GAME_KILL_CONTROL, x, y) {
|
|
||||||
return Some(SystemProfileAction::KillResidentGame);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(entry) = game_entries
|
|
||||||
.iter()
|
|
||||||
.take(MAX_HOME_GAME_ROWS)
|
|
||||||
.enumerate()
|
|
||||||
.find(|(index, _entry)| rect_contains(game_row_rect(*index), x, y))
|
|
||||||
.map(|(_index, entry)| entry)
|
|
||||||
{
|
|
||||||
return Some(SystemProfileAction::LaunchGame { target: entry.switch_target() });
|
|
||||||
}
|
|
||||||
|
|
||||||
HOME_BUTTONS
|
|
||||||
.iter()
|
|
||||||
.find(|button| rect_contains(button.rect, x, y))
|
|
||||||
.map(|button| SystemProfileAction::LaunchNativeShell(button.app))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
struct SuspendedGameIndicator {
|
|
||||||
title: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resident_game_indicator(os: &mut SystemOS) -> Option<SuspendedGameIndicator> {
|
|
||||||
let task_id = os.lifecycle().resident_game_task()?;
|
|
||||||
let sessions = os.sessions();
|
|
||||||
let session = sessions.vm_session_for_task(task_id)?;
|
|
||||||
|
|
||||||
if session.app_mode != AppMode::Game {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(SuspendedGameIndicator { title: session.title.clone() })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn game_row_rect(index: usize) -> Rect {
|
|
||||||
Rect {
|
|
||||||
x: GAME_ROW_X,
|
|
||||||
y: GAME_ROW_Y + (GAME_ROW_H + GAME_ROW_GAP) * index as i32,
|
|
||||||
w: GAME_ROW_W,
|
|
||||||
h: GAME_ROW_H,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn rect_contains(rect: Rect, x: i32, y: i32) -> bool {
|
|
||||||
x >= rect.x && x < rect.x + rect.w && y >= rect.y && y < rect.y + rect.h
|
|
||||||
}
|
|
||||||
|
|
||||||
fn activation_input_down(input: &dyn InputPlatform) -> bool {
|
|
||||||
input.touch().f().down
|
|
||||||
|| input.pad().a().down
|
|
||||||
|| input.pad().b().down
|
|
||||||
|| input.pad().start().down
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_home_packet(
|
|
||||||
pointer_x: i32,
|
|
||||||
pointer_y: i32,
|
|
||||||
game_entries: &[crate::GameLibraryEntry],
|
|
||||||
suspended_game: Option<&SuspendedGameIndicator>,
|
|
||||||
) -> ShellUiFramePacket {
|
|
||||||
let mut commands = Vec::new();
|
|
||||||
commands.push(GfxUiCommand::Clear { color: COLOR_BG });
|
|
||||||
fill_rect(&mut commands, VIEWPORT, COLOR_BG);
|
|
||||||
draw_panel(&mut commands, TITLE_PANEL, COLOR_PANEL_DARK, COLOR_BORDER);
|
|
||||||
draw_buffer_text(
|
|
||||||
&mut commands,
|
|
||||||
TITLE_PANEL.x + 58,
|
|
||||||
TITLE_PANEL.y + 9,
|
|
||||||
"PROMETEU HUB",
|
|
||||||
COLOR_TEXT,
|
|
||||||
);
|
|
||||||
|
|
||||||
draw_panel(&mut commands, HOME_PANEL, COLOR_PANEL, COLOR_BORDER);
|
|
||||||
draw_buffer_text(&mut commands, HOME_PANEL.x + 26, HOME_PANEL.y + 22, "Games", COLOR_TEXT);
|
|
||||||
draw_buffer_text(
|
|
||||||
&mut commands,
|
|
||||||
HOME_PANEL.x + 26,
|
|
||||||
HOME_PANEL.y + 40,
|
|
||||||
"local library",
|
|
||||||
COLOR_MUTED,
|
|
||||||
);
|
|
||||||
|
|
||||||
if game_entries.is_empty() {
|
|
||||||
draw_buffer_text(&mut commands, GAME_ROW_X, GAME_ROW_Y + 6, "No games found", COLOR_MUTED);
|
|
||||||
} else {
|
|
||||||
for (index, entry) in game_entries.iter().take(MAX_HOME_GAME_ROWS).enumerate() {
|
|
||||||
let rect = game_row_rect(index);
|
|
||||||
let hovered = rect_contains(rect, pointer_x, pointer_y);
|
|
||||||
let text = format!("{} #{} {}", entry.title, entry.app_id, entry.app_version);
|
|
||||||
draw_game_row(&mut commands, rect, &text, hovered);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for button in HOME_BUTTONS {
|
|
||||||
let hovered = rect_contains(button.rect, pointer_x, pointer_y);
|
|
||||||
draw_button(&mut commands, button.rect, button.label, hovered);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(suspended_game) = suspended_game {
|
|
||||||
let hovered = rect_contains(HUB_SUSPENDED_GAME_KILL_CONTROL, pointer_x, pointer_y);
|
|
||||||
draw_suspended_game_kill_control(&mut commands, suspended_game, hovered);
|
|
||||||
}
|
|
||||||
|
|
||||||
ShellUiFramePacket::new(commands)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn append_shell_window_commands(
|
|
||||||
commands: &mut Vec<GfxUiCommand>,
|
|
||||||
viewport: Rect,
|
|
||||||
color: Color,
|
|
||||||
title: &str,
|
|
||||||
pointer_x: i32,
|
|
||||||
pointer_y: i32,
|
|
||||||
) {
|
|
||||||
fill_rect(commands, VIEWPORT, COLOR_BG);
|
|
||||||
draw_panel(commands, viewport, COLOR_PANEL_DARK, COLOR_BORDER);
|
|
||||||
fill_rect(
|
|
||||||
commands,
|
|
||||||
Rect { x: viewport.x + 4, y: viewport.y + 24, w: viewport.w - 8, h: viewport.h - 28 },
|
|
||||||
color,
|
|
||||||
);
|
|
||||||
draw_buffer_text(commands, viewport.x + 10, viewport.y + 8, title, COLOR_TEXT);
|
|
||||||
draw_buffer_text(
|
|
||||||
commands,
|
|
||||||
viewport.x + 18,
|
|
||||||
viewport.y + 44,
|
|
||||||
"native fake shell",
|
|
||||||
COLOR_PANEL_DARK,
|
|
||||||
);
|
|
||||||
|
|
||||||
let close_hovered = rect_contains(CLOSE_BUTTON, pointer_x, pointer_y);
|
|
||||||
let close_fill = if close_hovered { COLOR_HILITE } else { COLOR_BUTTON };
|
|
||||||
fill_rect(commands, CLOSE_BUTTON, close_fill);
|
|
||||||
draw_rect(commands, CLOSE_BUTTON, COLOR_BORDER);
|
|
||||||
draw_buffer_text(commands, CLOSE_BUTTON.x + 5, CLOSE_BUTTON.y + 4, "x", COLOR_TEXT);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fill_rect(commands: &mut Vec<GfxUiCommand>, rect: Rect, color: Color) {
|
|
||||||
commands.push(GfxUiCommand::FillRect { rect, color });
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_rect(commands: &mut Vec<GfxUiCommand>, rect: Rect, color: Color) {
|
|
||||||
commands.push(GfxUiCommand::DrawLine {
|
|
||||||
x0: rect.x,
|
|
||||||
y0: rect.y,
|
|
||||||
x1: rect.x + rect.w - 1,
|
|
||||||
y1: rect.y,
|
|
||||||
color,
|
|
||||||
});
|
|
||||||
commands.push(GfxUiCommand::DrawLine {
|
|
||||||
x0: rect.x,
|
|
||||||
y0: rect.y + rect.h - 1,
|
|
||||||
x1: rect.x + rect.w - 1,
|
|
||||||
y1: rect.y + rect.h - 1,
|
|
||||||
color,
|
|
||||||
});
|
|
||||||
commands.push(GfxUiCommand::DrawLine {
|
|
||||||
x0: rect.x,
|
|
||||||
y0: rect.y,
|
|
||||||
x1: rect.x,
|
|
||||||
y1: rect.y + rect.h - 1,
|
|
||||||
color,
|
|
||||||
});
|
|
||||||
commands.push(GfxUiCommand::DrawLine {
|
|
||||||
x0: rect.x + rect.w - 1,
|
|
||||||
y0: rect.y,
|
|
||||||
x1: rect.x + rect.w - 1,
|
|
||||||
y1: rect.y + rect.h - 1,
|
|
||||||
color,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_panel(commands: &mut Vec<GfxUiCommand>, rect: Rect, fill: Color, border: Color) {
|
|
||||||
fill_rect(commands, rect, fill);
|
|
||||||
draw_rect(commands, rect, border);
|
|
||||||
draw_rect(
|
|
||||||
commands,
|
|
||||||
Rect { x: rect.x + 2, y: rect.y + 2, w: rect.w - 4, h: rect.h - 4 },
|
|
||||||
COLOR_MUTED,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_button(commands: &mut Vec<GfxUiCommand>, rect: Rect, label: &str, hovered: bool) {
|
|
||||||
let fill = if hovered { COLOR_BUTTON_ACTIVE } else { COLOR_BUTTON };
|
|
||||||
let border = if hovered { COLOR_HILITE } else { COLOR_BORDER };
|
|
||||||
fill_rect(commands, rect, fill);
|
|
||||||
draw_rect(commands, rect, border);
|
|
||||||
draw_rect(
|
|
||||||
commands,
|
|
||||||
Rect { x: rect.x + 3, y: rect.y + 3, w: rect.w - 6, h: rect.h - 6 },
|
|
||||||
COLOR_MUTED,
|
|
||||||
);
|
|
||||||
fill_rect(commands, Rect { x: rect.x + 12, y: rect.y + 8, w: 14, h: 16 }, border);
|
|
||||||
draw_rect(commands, Rect { x: rect.x + 34, y: rect.y + 8, w: 62, h: 16 }, COLOR_PANEL_DARK);
|
|
||||||
draw_buffer_text(commands, rect.x + 40, rect.y + 13, label, COLOR_TEXT);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_game_row(commands: &mut Vec<GfxUiCommand>, rect: Rect, label: &str, hovered: bool) {
|
|
||||||
let fill = if hovered { COLOR_BUTTON_ACTIVE } else { COLOR_PANEL_DARK };
|
|
||||||
let border = if hovered { COLOR_HILITE } else { COLOR_MUTED };
|
|
||||||
fill_rect(commands, rect, fill);
|
|
||||||
draw_rect(commands, rect, border);
|
|
||||||
draw_buffer_text(commands, rect.x + 8, rect.y + 7, label, COLOR_TEXT);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_suspended_game_kill_control(
|
|
||||||
commands: &mut Vec<GfxUiCommand>,
|
|
||||||
suspended_game: &SuspendedGameIndicator,
|
|
||||||
hovered: bool,
|
|
||||||
) {
|
|
||||||
let fill = if hovered { COLOR_KILL_ACTIVE } else { COLOR_KILL };
|
|
||||||
let border = if hovered { COLOR_HILITE } else { COLOR_BORDER };
|
|
||||||
fill_rect(commands, HUB_SUSPENDED_GAME_KILL_CONTROL, fill);
|
|
||||||
draw_rect(commands, HUB_SUSPENDED_GAME_KILL_CONTROL, border);
|
|
||||||
draw_buffer_text(
|
|
||||||
commands,
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.x + 8,
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.y + 8,
|
|
||||||
&fit_text_to_control(&suspended_game.title, HUB_SUSPENDED_GAME_KILL_CONTROL.w - 16),
|
|
||||||
COLOR_TEXT,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fit_text_to_control(text: &str, max_width: i32) -> String {
|
|
||||||
let max_chars = (max_width / 8).max(0) as usize;
|
|
||||||
if text.chars().count() <= max_chars {
|
|
||||||
return text.to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
if max_chars <= 2 {
|
|
||||||
return text.chars().take(max_chars).collect();
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut fitted: String = text.chars().take(max_chars - 2).collect();
|
|
||||||
fitted.push_str("..");
|
|
||||||
fitted
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_buffer_text(commands: &mut Vec<GfxUiCommand>, x: i32, y: i32, text: &str, color: Color) {
|
|
||||||
commands.push(GfxUiCommand::DrawText { x, y, text: text.to_string(), color });
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::task::TaskId;
|
|
||||||
use crate::windows::WindowOwner;
|
|
||||||
use prometeu_drivers::TestPlatform;
|
|
||||||
use prometeu_hal::{InputSignals, RuntimePlatform};
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
fn focused_native_shell_fixture(
|
|
||||||
signals: &InputSignals,
|
|
||||||
) -> (PrometeuHub, SystemOS, TestPlatform) {
|
|
||||||
let hub = PrometeuHub::new();
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
let mut platform = TestPlatform::new();
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut windows = os.windows();
|
|
||||||
let id = windows.add_window(
|
|
||||||
"ShellA".to_string(),
|
|
||||||
WindowOwner::Task(TaskId(7)),
|
|
||||||
SHELL_FRAME,
|
|
||||||
Color::GREEN,
|
Color::GREEN,
|
||||||
);
|
));
|
||||||
windows.set_focus(id);
|
} else if hw.pad().b().pressed {
|
||||||
|
os.log(LogLevel::Debug, LogSource::Hub, 0, "window B opened".to_string());
|
||||||
|
next_window = Some((
|
||||||
|
"Indigo Window".to_string(),
|
||||||
|
Rect { x: 160, y: 0, w: 160, h: 90 },
|
||||||
|
Color::INDIGO,
|
||||||
|
));
|
||||||
|
} else if hw.pad().x().pressed {
|
||||||
|
os.log(LogLevel::Debug, LogSource::Hub, 0, "window X opened".to_string());
|
||||||
|
next_window = Some((
|
||||||
|
"Yellow Window".to_string(),
|
||||||
|
Rect { x: 0, y: 90, w: 160, h: 90 },
|
||||||
|
Color::YELLOW,
|
||||||
|
));
|
||||||
|
} else if hw.pad().y().pressed {
|
||||||
|
os.log(LogLevel::Debug, LogSource::Hub, 0, "window Y opened".to_string());
|
||||||
|
next_window =
|
||||||
|
Some(("Red Window".to_string(), Rect { x: 160, y: 90, w: 160, h: 90 }, Color::RED));
|
||||||
}
|
}
|
||||||
|
|
||||||
platform.input_mut().pad_mut().begin_frame(signals);
|
if let Some((title, rect, color)) = next_window {
|
||||||
platform.input_mut().touch_mut().begin_frame(signals);
|
self.window_manager.remove_all_windows();
|
||||||
|
let id = self.window_manager.add_window(title, rect, color);
|
||||||
(hub, os, platform)
|
self.window_manager.set_focus(id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
pub fn render(&mut self, _os: &mut VirtualMachineRuntime, hw: &mut dyn HardwareBridge) {
|
||||||
fn shell_a_button_click_emits_launch_action() {
|
for window in &self.window_manager.windows {
|
||||||
assert_eq!(
|
hw.gfx_mut().fill_rect(
|
||||||
action_for_click(
|
window.viewport.x,
|
||||||
false,
|
window.viewport.y,
|
||||||
HOME_BUTTONS[0].rect.x,
|
window.viewport.w,
|
||||||
HOME_BUTTONS[0].rect.y,
|
window.viewport.h,
|
||||||
true,
|
window.color,
|
||||||
&[],
|
);
|
||||||
None
|
}
|
||||||
),
|
|
||||||
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellA))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn shell_b_button_click_emits_launch_action() {
|
|
||||||
assert_eq!(
|
|
||||||
action_for_click(
|
|
||||||
false,
|
|
||||||
SHELL_B_BUTTON.x + SHELL_B_BUTTON.w - 1,
|
|
||||||
SHELL_B_BUTTON.y,
|
|
||||||
true,
|
|
||||||
&[],
|
|
||||||
None
|
|
||||||
),
|
|
||||||
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellB))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn button_hit_test_excludes_right_and_bottom_edges() {
|
|
||||||
assert_eq!(
|
|
||||||
action_for_click(
|
|
||||||
false,
|
|
||||||
SHELL_A_BUTTON.x + SHELL_A_BUTTON.w,
|
|
||||||
SHELL_A_BUTTON.y,
|
|
||||||
true,
|
|
||||||
&[],
|
|
||||||
None
|
|
||||||
),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
action_for_click(
|
|
||||||
false,
|
|
||||||
SHELL_A_BUTTON.x,
|
|
||||||
SHELL_A_BUTTON.y + SHELL_A_BUTTON.h,
|
|
||||||
true,
|
|
||||||
&[],
|
|
||||||
None
|
|
||||||
),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn held_pointer_does_not_emit_click_action() {
|
|
||||||
assert_eq!(
|
|
||||||
action_for_click(false, SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, false, &[], None),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hub_starts_with_home_input_disarmed() {
|
|
||||||
let hub = PrometeuHub::new();
|
|
||||||
assert!(!hub.home_input_armed);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn game_row_click_emits_launch_game_action() {
|
|
||||||
let entry = crate::GameLibraryEntry {
|
|
||||||
manifest: prometeu_hal::cartridge::CartridgeManifest {
|
|
||||||
magic: "PMTU".to_string(),
|
|
||||||
cartridge_version: 1,
|
|
||||||
app_id: 42,
|
|
||||||
title: "Stress".to_string(),
|
|
||||||
app_version: "1.0.0".to_string(),
|
|
||||||
app_mode: prometeu_hal::app_mode::AppMode::Game,
|
|
||||||
capabilities: vec![],
|
|
||||||
},
|
|
||||||
title: "Stress".to_string(),
|
|
||||||
app_id: 42,
|
|
||||||
app_version: "1.0.0".to_string(),
|
|
||||||
path: PathBuf::from("test-cartridges/stress-console"),
|
|
||||||
discovered_at: std::time::SystemTime::UNIX_EPOCH,
|
|
||||||
};
|
|
||||||
|
|
||||||
let action = action_for_click(
|
|
||||||
false,
|
|
||||||
GAME_ROW_X,
|
|
||||||
GAME_ROW_Y,
|
|
||||||
true,
|
|
||||||
std::slice::from_ref(&entry),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
action,
|
|
||||||
Some(SystemProfileAction::LaunchGame {
|
|
||||||
target: GameSwitchTarget {
|
|
||||||
path: entry.path.clone(),
|
|
||||||
app_id: 42,
|
|
||||||
title: "Stress".to_string(),
|
|
||||||
app_version: "1.0.0".to_string(),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn close_button_click_emits_close_only_in_shell() {
|
|
||||||
assert_eq!(
|
|
||||||
action_for_click(true, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[], None),
|
|
||||||
Some(SystemProfileAction::CloseShell)
|
|
||||||
);
|
|
||||||
assert_eq!(action_for_click(false, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[], None), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn home_layout_exposes_exactly_two_manual_shell_buttons() {
|
|
||||||
assert_eq!(HOME_BUTTONS.len(), 2);
|
|
||||||
assert_eq!(HOME_BUTTONS[0].label, "ShellA");
|
|
||||||
assert_eq!(HOME_BUTTONS[0].app, NativeShellApp::ShellA);
|
|
||||||
assert_eq!(HOME_BUTTONS[1].label, "ShellB");
|
|
||||||
assert_eq!(HOME_BUTTONS[1].app, NativeShellApp::ShellB);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn home_render_produces_shell_ui_packet_commands() {
|
|
||||||
let packet = render_home_packet(SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, &[], None);
|
|
||||||
|
|
||||||
assert!(matches!(packet.commands.first(), Some(GfxUiCommand::Clear { .. })));
|
|
||||||
assert!(packet.commands.iter().any(|command| {
|
|
||||||
matches!(command, GfxUiCommand::DrawText { text, .. } if text == "PROMETEU HUB")
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resident_game_indicator_uses_only_resident_game_sessions() {
|
|
||||||
let mut os = SystemOS::new(None);
|
|
||||||
assert_eq!(resident_game_indicator(&mut os), None);
|
|
||||||
|
|
||||||
let shell = os.sessions().create_vm_shell_task(7, "VM Shell");
|
|
||||||
assert_eq!(resident_game_indicator(&mut os), None);
|
|
||||||
os.lifecycle().suspend_task(shell).expect("shell suspend should succeed");
|
|
||||||
assert_eq!(resident_game_indicator(&mut os), None);
|
|
||||||
|
|
||||||
let game = os.sessions().create_vm_game_task(42, "Stress Console");
|
|
||||||
os.lifecycle().suspend_task(game).expect("game suspend should succeed");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
resident_game_indicator(&mut os),
|
|
||||||
Some(SuspendedGameIndicator { title: "Stress Console".to_string() })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn home_render_shows_suspended_game_kill_control_when_game_is_resident() {
|
|
||||||
let suspended_game = SuspendedGameIndicator { title: "Stress Console".to_string() };
|
|
||||||
let packet = render_home_packet(
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.x,
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.y,
|
|
||||||
&[],
|
|
||||||
Some(&suspended_game),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(packet.commands.iter().any(|command| {
|
|
||||||
matches!(
|
|
||||||
command,
|
|
||||||
GfxUiCommand::FillRect { rect, color }
|
|
||||||
if *rect == HUB_SUSPENDED_GAME_KILL_CONTROL && *color == COLOR_KILL_ACTIVE
|
|
||||||
)
|
|
||||||
}));
|
|
||||||
assert!(packet.commands.iter().any(|command| {
|
|
||||||
matches!(
|
|
||||||
command,
|
|
||||||
GfxUiCommand::DrawText { x, y, text, .. }
|
|
||||||
if *x == HUB_SUSPENDED_GAME_KILL_CONTROL.x + 8
|
|
||||||
&& *y == HUB_SUSPENDED_GAME_KILL_CONTROL.y + 8
|
|
||||||
&& text == "Stress Console"
|
|
||||||
)
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn home_render_omits_suspended_game_kill_control_without_resident_game() {
|
|
||||||
let packet = render_home_packet(
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.x,
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.y,
|
|
||||||
&[],
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(!packet.commands.iter().any(|command| {
|
|
||||||
matches!(
|
|
||||||
command,
|
|
||||||
GfxUiCommand::FillRect { rect, color }
|
|
||||||
if *rect == HUB_SUSPENDED_GAME_KILL_CONTROL
|
|
||||||
&& (*color == COLOR_KILL || *color == COLOR_KILL_ACTIVE)
|
|
||||||
)
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn suspended_game_kill_control_click_emits_kill_action() {
|
|
||||||
let suspended_game = SuspendedGameIndicator { title: "Stress Console".to_string() };
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
action_for_click(
|
|
||||||
false,
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.x,
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.y,
|
|
||||||
true,
|
|
||||||
&[],
|
|
||||||
Some(&suspended_game),
|
|
||||||
),
|
|
||||||
Some(SystemProfileAction::KillResidentGame)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
action_for_click(
|
|
||||||
false,
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.x,
|
|
||||||
HUB_SUSPENDED_GAME_KILL_CONTROL.y,
|
|
||||||
true,
|
|
||||||
&[],
|
|
||||||
None,
|
|
||||||
),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn suspended_game_kill_control_truncates_long_titles() {
|
|
||||||
let long_title =
|
|
||||||
SuspendedGameIndicator { title: "Extremely Long Resident Game Title".to_string() };
|
|
||||||
let packet = render_home_packet(0, 0, &[], Some(&long_title));
|
|
||||||
let label = packet
|
|
||||||
.commands
|
|
||||||
.iter()
|
|
||||||
.find_map(|command| match command {
|
|
||||||
GfxUiCommand::DrawText { x, y, text, .. }
|
|
||||||
if *x == HUB_SUSPENDED_GAME_KILL_CONTROL.x + 8
|
|
||||||
&& *y == HUB_SUSPENDED_GAME_KILL_CONTROL.y + 8 =>
|
|
||||||
{
|
|
||||||
Some(text)
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.expect("kill control text should render");
|
|
||||||
|
|
||||||
assert!(label.ends_with(".."));
|
|
||||||
assert!(label.chars().count() <= ((HUB_SUSPENDED_GAME_KILL_CONTROL.w - 16) / 8) as usize);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn shell_close_button_sits_inside_shell_frame() {
|
|
||||||
assert!(rect_contains(SHELL_FRAME, CLOSE_BUTTON.x, CLOSE_BUTTON.y));
|
|
||||||
assert!(rect_contains(
|
|
||||||
SHELL_FRAME,
|
|
||||||
CLOSE_BUTTON.x + CLOSE_BUTTON.w - 1,
|
|
||||||
CLOSE_BUTTON.y + CLOSE_BUTTON.h - 1
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn native_shell_profile_start_close_does_not_tick_vm() {
|
|
||||||
let signals = InputSignals { start_signal: true, ..Default::default() };
|
|
||||||
let (mut hub, mut os, mut platform) = focused_native_shell_fixture(&signals);
|
|
||||||
|
|
||||||
let tick_index_before_update = os.vm().tick_index();
|
|
||||||
let outcome = hub.update_native_shell_profile(&mut os, &mut platform);
|
|
||||||
|
|
||||||
assert_eq!(outcome.action, Some(SystemProfileAction::CloseShell));
|
|
||||||
assert!(outcome.crash.is_none());
|
|
||||||
assert_eq!(os.vm().tick_index(), tick_index_before_update);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn native_shell_profile_close_button_does_not_tick_vm() {
|
|
||||||
let signals = InputSignals {
|
|
||||||
f_signal: true,
|
|
||||||
x_pos: CLOSE_BUTTON.x,
|
|
||||||
y_pos: CLOSE_BUTTON.y,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let (mut hub, mut os, mut platform) = focused_native_shell_fixture(&signals);
|
|
||||||
|
|
||||||
let tick_index_before_update = os.vm().tick_index();
|
|
||||||
let outcome = hub.update_native_shell_profile(&mut os, &mut platform);
|
|
||||||
|
|
||||||
assert_eq!(outcome.action, Some(SystemProfileAction::CloseShell));
|
|
||||||
assert!(outcome.crash.is_none());
|
|
||||||
assert_eq!(os.vm().tick_index(), tick_index_before_update);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
use prometeu_hal::color::Color;
|
||||||
|
use prometeu_hal::window::{Rect, Window, WindowId};
|
||||||
|
|
||||||
|
/// PROMETEU Window Manager.
|
||||||
|
pub struct WindowManager {
|
||||||
|
pub windows: Vec<Window>,
|
||||||
|
pub focused: Option<WindowId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowManager {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { windows: Vec::new(), focused: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_window(&mut self, title: String, viewport: Rect, color: Color) -> WindowId {
|
||||||
|
let id = WindowId(self.windows.len() as u32);
|
||||||
|
let window = Window { id, viewport, has_focus: false, title, color };
|
||||||
|
self.windows.push(window);
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_window(&mut self, id: WindowId) {
|
||||||
|
self.windows.retain(|w| w.id != id);
|
||||||
|
if self.focused == Some(id) {
|
||||||
|
self.focused = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_all_windows(&mut self) {
|
||||||
|
self.windows.clear();
|
||||||
|
self.focused = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_focus(&mut self, id: WindowId) {
|
||||||
|
self.focused = Some(id);
|
||||||
|
for window in &mut self.windows {
|
||||||
|
window.has_focus = window.id == id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_window_manager_focus() {
|
||||||
|
let mut wm = WindowManager::new();
|
||||||
|
let id1 =
|
||||||
|
wm.add_window("Window 1".to_string(), Rect { x: 0, y: 0, w: 10, h: 10 }, Color::WHITE);
|
||||||
|
let id2 = wm.add_window(
|
||||||
|
"Window 2".to_string(),
|
||||||
|
Rect { x: 10, y: 10, w: 10, h: 10 },
|
||||||
|
Color::WHITE,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(wm.windows.len(), 2);
|
||||||
|
assert_eq!(wm.focused, None);
|
||||||
|
|
||||||
|
wm.set_focus(id1);
|
||||||
|
assert_eq!(wm.focused, Some(id1));
|
||||||
|
assert!(wm.windows[0].has_focus);
|
||||||
|
assert!(!wm.windows[1].has_focus);
|
||||||
|
|
||||||
|
wm.set_focus(id2);
|
||||||
|
assert_eq!(wm.focused, Some(id2));
|
||||||
|
assert!(!wm.windows[0].has_focus);
|
||||||
|
assert!(wm.windows[1].has_focus);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_window_manager_remove_window() {
|
||||||
|
let mut wm = WindowManager::new();
|
||||||
|
let id =
|
||||||
|
wm.add_window("Window".to_string(), Rect { x: 0, y: 0, w: 10, h: 10 }, Color::WHITE);
|
||||||
|
wm.set_focus(id);
|
||||||
|
assert_eq!(wm.focused, Some(id));
|
||||||
|
|
||||||
|
wm.remove_window(id);
|
||||||
|
assert_eq!(wm.windows.len(), 0);
|
||||||
|
assert_eq!(wm.focused, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,601 +0,0 @@
|
|||||||
use std::collections::VecDeque;
|
|
||||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
|
|
||||||
use std::sync::{Arc, Condvar, Mutex};
|
|
||||||
use std::thread::{self, JoinHandle};
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
||||||
pub struct AsyncWorkJobId(u64);
|
|
||||||
|
|
||||||
impl AsyncWorkJobId {
|
|
||||||
pub const ZERO: Self = Self(0);
|
|
||||||
|
|
||||||
pub fn new(value: u64) -> Self {
|
|
||||||
Self(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(self) -> u64 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum AsyncWorkJobKind {
|
|
||||||
Asset,
|
|
||||||
Memcard,
|
|
||||||
Fs,
|
|
||||||
Test,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum AsyncWorkPriority {
|
|
||||||
MemcardCommitWrite,
|
|
||||||
FsWriteConfig,
|
|
||||||
AssetLoad,
|
|
||||||
NonCriticalReadList,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsyncWorkPriority {
|
|
||||||
const fn rank(self) -> u8 {
|
|
||||||
match self {
|
|
||||||
Self::MemcardCommitWrite => 0,
|
|
||||||
Self::FsWriteConfig => 1,
|
|
||||||
Self::AssetLoad => 2,
|
|
||||||
Self::NonCriticalReadList => 3,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsyncWorkJobKind {
|
|
||||||
pub const fn default_priority(self) -> AsyncWorkPriority {
|
|
||||||
match self {
|
|
||||||
Self::Memcard => AsyncWorkPriority::MemcardCommitWrite,
|
|
||||||
Self::Fs => AsyncWorkPriority::FsWriteConfig,
|
|
||||||
Self::Asset => AsyncWorkPriority::AssetLoad,
|
|
||||||
Self::Test => AsyncWorkPriority::NonCriticalReadList,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum AsyncWorkJobOutcome {
|
|
||||||
Completed,
|
|
||||||
Canceled,
|
|
||||||
Failed,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum AsyncWorkLaneError {
|
|
||||||
Shutdown,
|
|
||||||
WorkerPanic,
|
|
||||||
ShutdownTimeout,
|
|
||||||
InternalFailure,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct AsyncWorkLaneConfig {
|
|
||||||
pub shutdown_timeout: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for AsyncWorkLaneConfig {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { shutdown_timeout: Duration::from_millis(250) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct AsyncWorkActiveJob {
|
|
||||||
pub id: AsyncWorkJobId,
|
|
||||||
pub kind: AsyncWorkJobKind,
|
|
||||||
pub priority: AsyncWorkPriority,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
||||||
pub struct AsyncWorkLaneTelemetry {
|
|
||||||
pub submitted_jobs: u64,
|
|
||||||
pub started_jobs: u64,
|
|
||||||
pub completed_jobs: u64,
|
|
||||||
pub canceled_jobs: u64,
|
|
||||||
pub failed_jobs: u64,
|
|
||||||
pub shutdown_discards: u64,
|
|
||||||
pub pending_depth: usize,
|
|
||||||
pub max_pending_depth: usize,
|
|
||||||
pub active_job_id: Option<AsyncWorkJobId>,
|
|
||||||
pub last_submitted_job_id: Option<AsyncWorkJobId>,
|
|
||||||
pub last_started_job_id: Option<AsyncWorkJobId>,
|
|
||||||
pub last_closed_job_id: Option<AsyncWorkJobId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsyncWorkLaneTelemetry {
|
|
||||||
fn record_submitted(&mut self, job_id: AsyncWorkJobId, pending_depth: usize) {
|
|
||||||
self.submitted_jobs += 1;
|
|
||||||
self.pending_depth = pending_depth;
|
|
||||||
self.max_pending_depth = self.max_pending_depth.max(pending_depth);
|
|
||||||
self.last_submitted_job_id = Some(job_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn record_started(&mut self, job_id: AsyncWorkJobId, pending_depth: usize) {
|
|
||||||
self.started_jobs += 1;
|
|
||||||
self.pending_depth = pending_depth;
|
|
||||||
self.active_job_id = Some(job_id);
|
|
||||||
self.last_started_job_id = Some(job_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn record_closed(&mut self, job_id: AsyncWorkJobId, outcome: AsyncWorkJobOutcome) {
|
|
||||||
match outcome {
|
|
||||||
AsyncWorkJobOutcome::Completed => self.completed_jobs += 1,
|
|
||||||
AsyncWorkJobOutcome::Canceled => self.canceled_jobs += 1,
|
|
||||||
AsyncWorkJobOutcome::Failed => self.failed_jobs += 1,
|
|
||||||
}
|
|
||||||
self.active_job_id = None;
|
|
||||||
self.last_closed_job_id = Some(job_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn record_shutdown_discards(&mut self, count: usize) {
|
|
||||||
self.shutdown_discards += count as u64;
|
|
||||||
self.pending_depth = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct AsyncWorkCancelToken {
|
|
||||||
canceled: Arc<AtomicBool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsyncWorkCancelToken {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self { canceled: Arc::new(AtomicBool::new(false)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn cancel(&self) {
|
|
||||||
self.canceled.store(true, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_canceled(&self) -> bool {
|
|
||||||
self.canceled.load(Ordering::Relaxed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct AsyncWorkJobContext {
|
|
||||||
pub job_id: AsyncWorkJobId,
|
|
||||||
pub kind: AsyncWorkJobKind,
|
|
||||||
pub priority: AsyncWorkPriority,
|
|
||||||
cancel_token: AsyncWorkCancelToken,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsyncWorkJobContext {
|
|
||||||
pub fn is_canceled(&self) -> bool {
|
|
||||||
self.cancel_token.is_canceled()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type AsyncWorkFn = Box<dyn FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static>;
|
|
||||||
|
|
||||||
struct PendingAsyncWorkJob {
|
|
||||||
id: AsyncWorkJobId,
|
|
||||||
kind: AsyncWorkJobKind,
|
|
||||||
priority: AsyncWorkPriority,
|
|
||||||
cancel_token: AsyncWorkCancelToken,
|
|
||||||
work: AsyncWorkFn,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct RunningAsyncWorkJob {
|
|
||||||
id: AsyncWorkJobId,
|
|
||||||
kind: AsyncWorkJobKind,
|
|
||||||
priority: AsyncWorkPriority,
|
|
||||||
cancel_token: AsyncWorkCancelToken,
|
|
||||||
work: AsyncWorkFn,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
struct AsyncWorkLaneState {
|
|
||||||
next_job_id: u64,
|
|
||||||
pending: VecDeque<PendingAsyncWorkJob>,
|
|
||||||
active: Option<AsyncWorkActiveJob>,
|
|
||||||
active_cancel_token: Option<AsyncWorkCancelToken>,
|
|
||||||
shutdown_requested: bool,
|
|
||||||
telemetry: AsyncWorkLaneTelemetry,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct AsyncWorkLane {
|
|
||||||
state: Mutex<AsyncWorkLaneState>,
|
|
||||||
ready: Condvar,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsyncWorkLane {
|
|
||||||
pub fn submit(
|
|
||||||
&self,
|
|
||||||
kind: AsyncWorkJobKind,
|
|
||||||
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
|
||||||
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
|
||||||
self.submit_with_priority(kind, kind.default_priority(), work)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn submit_with_priority(
|
|
||||||
&self,
|
|
||||||
kind: AsyncWorkJobKind,
|
|
||||||
priority: AsyncWorkPriority,
|
|
||||||
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
|
||||||
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
|
||||||
let mut state = self.state.lock().map_err(|_| AsyncWorkLaneError::InternalFailure)?;
|
|
||||||
if state.shutdown_requested {
|
|
||||||
return Err(AsyncWorkLaneError::Shutdown);
|
|
||||||
}
|
|
||||||
|
|
||||||
state.next_job_id += 1;
|
|
||||||
let id = AsyncWorkJobId::new(state.next_job_id);
|
|
||||||
let cancel_token = AsyncWorkCancelToken::new();
|
|
||||||
let job = PendingAsyncWorkJob { id, kind, priority, cancel_token, work: Box::new(work) };
|
|
||||||
let insert_at = state
|
|
||||||
.pending
|
|
||||||
.iter()
|
|
||||||
.position(|pending| priority.rank() < pending.priority.rank())
|
|
||||||
.unwrap_or(state.pending.len());
|
|
||||||
state.pending.insert(insert_at, job);
|
|
||||||
let pending_depth = state.pending.len();
|
|
||||||
state.telemetry.record_submitted(id, pending_depth);
|
|
||||||
self.ready.notify_one();
|
|
||||||
Ok(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn submit_memcard_commit_write(
|
|
||||||
&self,
|
|
||||||
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
|
||||||
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
|
||||||
self.submit_with_priority(
|
|
||||||
AsyncWorkJobKind::Memcard,
|
|
||||||
AsyncWorkPriority::MemcardCommitWrite,
|
|
||||||
work,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn submit_fs_write_config(
|
|
||||||
&self,
|
|
||||||
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
|
||||||
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
|
||||||
self.submit_with_priority(AsyncWorkJobKind::Fs, AsyncWorkPriority::FsWriteConfig, work)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn submit_asset_load(
|
|
||||||
&self,
|
|
||||||
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
|
||||||
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
|
||||||
self.submit_with_priority(AsyncWorkJobKind::Asset, AsyncWorkPriority::AssetLoad, work)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn submit_non_critical_read_list(
|
|
||||||
&self,
|
|
||||||
kind: AsyncWorkJobKind,
|
|
||||||
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
|
||||||
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
|
||||||
self.submit_with_priority(kind, AsyncWorkPriority::NonCriticalReadList, work)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn request_cancel(&self, job_id: AsyncWorkJobId) -> bool {
|
|
||||||
let state = self.state.lock().unwrap();
|
|
||||||
if let Some(token) = state
|
|
||||||
.active
|
|
||||||
.filter(|active| active.id == job_id)
|
|
||||||
.and(state.active_cancel_token.as_ref())
|
|
||||||
{
|
|
||||||
token.cancel();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
for pending in &state.pending {
|
|
||||||
if pending.id == job_id {
|
|
||||||
pending.cancel_token.cancel();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn active_job(&self) -> Option<AsyncWorkActiveJob> {
|
|
||||||
self.state.lock().unwrap().active
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pending_depth(&self) -> usize {
|
|
||||||
self.state.lock().unwrap().pending.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn telemetry(&self) -> AsyncWorkLaneTelemetry {
|
|
||||||
self.state.lock().unwrap().telemetry
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn request_shutdown(&self) {
|
|
||||||
let mut state = self.state.lock().unwrap();
|
|
||||||
state.shutdown_requested = true;
|
|
||||||
if let Some(token) = &state.active_cancel_token {
|
|
||||||
token.cancel();
|
|
||||||
}
|
|
||||||
self.ready.notify_all();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wait_take(&self) -> Option<RunningAsyncWorkJob> {
|
|
||||||
self.wait_take_with_hook(|| {})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wait_take_with_hook(&self, mut before_wait: impl FnMut()) -> Option<RunningAsyncWorkJob> {
|
|
||||||
let mut state = self.state.lock().unwrap();
|
|
||||||
loop {
|
|
||||||
if state.shutdown_requested {
|
|
||||||
let discarded = state.pending.len();
|
|
||||||
state.pending.clear();
|
|
||||||
state.telemetry.record_shutdown_discards(discarded);
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(pending) = state.pending.pop_front() {
|
|
||||||
let active = AsyncWorkActiveJob {
|
|
||||||
id: pending.id,
|
|
||||||
kind: pending.kind,
|
|
||||||
priority: pending.priority,
|
|
||||||
};
|
|
||||||
state.active = Some(active);
|
|
||||||
state.active_cancel_token = Some(pending.cancel_token.clone());
|
|
||||||
let pending_depth = state.pending.len();
|
|
||||||
state.telemetry.record_started(pending.id, pending_depth);
|
|
||||||
return Some(RunningAsyncWorkJob {
|
|
||||||
id: pending.id,
|
|
||||||
kind: pending.kind,
|
|
||||||
priority: pending.priority,
|
|
||||||
cancel_token: pending.cancel_token,
|
|
||||||
work: pending.work,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
before_wait();
|
|
||||||
state = self.ready.wait(state).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn record_finished(&self, job_id: AsyncWorkJobId, outcome: AsyncWorkJobOutcome) {
|
|
||||||
let mut state = self.state.lock().unwrap();
|
|
||||||
if state.active.is_some_and(|active| active.id == job_id) {
|
|
||||||
state.active = None;
|
|
||||||
state.active_cancel_token = None;
|
|
||||||
}
|
|
||||||
state.telemetry.record_closed(job_id, outcome);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct AsyncWorkLaneController {
|
|
||||||
config: AsyncWorkLaneConfig,
|
|
||||||
lane: Arc<AsyncWorkLane>,
|
|
||||||
handle: Option<JoinHandle<()>>,
|
|
||||||
done_rx: Receiver<Result<(), AsyncWorkLaneError>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsyncWorkLaneController {
|
|
||||||
pub fn start(config: AsyncWorkLaneConfig, lane: Arc<AsyncWorkLane>) -> Self {
|
|
||||||
let worker_lane = Arc::clone(&lane);
|
|
||||||
let (done_tx, done_rx) = mpsc::channel();
|
|
||||||
let handle = thread::spawn(move || {
|
|
||||||
let result = catch_unwind(AssertUnwindSafe(|| run_async_work_loop(worker_lane)))
|
|
||||||
.map_err(|_| AsyncWorkLaneError::WorkerPanic);
|
|
||||||
let _ = done_tx.send(result);
|
|
||||||
});
|
|
||||||
|
|
||||||
Self { config, lane, handle: Some(handle), done_rx }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lane(&self) -> Arc<AsyncWorkLane> {
|
|
||||||
Arc::clone(&self.lane)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn stop(&mut self) -> Result<(), AsyncWorkLaneError> {
|
|
||||||
self.lane.request_shutdown();
|
|
||||||
match self.done_rx.recv_timeout(self.config.shutdown_timeout) {
|
|
||||||
Ok(result) => {
|
|
||||||
if let Some(handle) = self.handle.take()
|
|
||||||
&& handle.join().is_err()
|
|
||||||
{
|
|
||||||
return Err(AsyncWorkLaneError::WorkerPanic);
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
Err(RecvTimeoutError::Timeout) => Err(AsyncWorkLaneError::ShutdownTimeout),
|
|
||||||
Err(RecvTimeoutError::Disconnected) => Err(AsyncWorkLaneError::InternalFailure),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for AsyncWorkLaneController {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if self.handle.is_some() {
|
|
||||||
let _ = self.stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_async_work_loop(lane: Arc<AsyncWorkLane>) {
|
|
||||||
while let Some(job) = lane.wait_take() {
|
|
||||||
let context = AsyncWorkJobContext {
|
|
||||||
job_id: job.id,
|
|
||||||
kind: job.kind,
|
|
||||||
priority: job.priority,
|
|
||||||
cancel_token: job.cancel_token,
|
|
||||||
};
|
|
||||||
let result = catch_unwind(AssertUnwindSafe(|| (job.work)(context)))
|
|
||||||
.unwrap_or(AsyncWorkJobOutcome::Failed);
|
|
||||||
lane.record_finished(job.id, result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use std::sync::mpsc;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn async_work_lane_runs_jobs_in_submission_order() {
|
|
||||||
let lane = Arc::new(AsyncWorkLane::default());
|
|
||||||
let mut controller =
|
|
||||||
AsyncWorkLaneController::start(AsyncWorkLaneConfig::default(), Arc::clone(&lane));
|
|
||||||
let (tx, rx) = mpsc::channel();
|
|
||||||
|
|
||||||
lane.submit(AsyncWorkJobKind::Test, {
|
|
||||||
let tx = tx.clone();
|
|
||||||
move |_| {
|
|
||||||
tx.send(1).unwrap();
|
|
||||||
AsyncWorkJobOutcome::Completed
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
lane.submit(AsyncWorkJobKind::Test, {
|
|
||||||
let tx = tx.clone();
|
|
||||||
move |_| {
|
|
||||||
tx.send(2).unwrap();
|
|
||||||
AsyncWorkJobOutcome::Completed
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
assert_eq!(rx.recv().unwrap(), 1);
|
|
||||||
assert_eq!(rx.recv().unwrap(), 2);
|
|
||||||
controller.stop().unwrap();
|
|
||||||
|
|
||||||
let telemetry = lane.telemetry();
|
|
||||||
assert_eq!(telemetry.submitted_jobs, 2);
|
|
||||||
assert_eq!(telemetry.started_jobs, 2);
|
|
||||||
assert_eq!(telemetry.completed_jobs, 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn async_work_lane_runs_higher_priority_io_before_assets() {
|
|
||||||
let lane = Arc::new(AsyncWorkLane::default());
|
|
||||||
let (tx, rx) = mpsc::channel();
|
|
||||||
|
|
||||||
lane.submit_asset_load({
|
|
||||||
let tx = tx.clone();
|
|
||||||
move |ctx| {
|
|
||||||
tx.send((ctx.kind, ctx.priority)).unwrap();
|
|
||||||
AsyncWorkJobOutcome::Completed
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
lane.submit_non_critical_read_list(AsyncWorkJobKind::Fs, {
|
|
||||||
let tx = tx.clone();
|
|
||||||
move |ctx| {
|
|
||||||
tx.send((ctx.kind, ctx.priority)).unwrap();
|
|
||||||
AsyncWorkJobOutcome::Completed
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
lane.submit_memcard_commit_write({
|
|
||||||
let tx = tx.clone();
|
|
||||||
move |ctx| {
|
|
||||||
tx.send((ctx.kind, ctx.priority)).unwrap();
|
|
||||||
AsyncWorkJobOutcome::Completed
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
lane.submit_fs_write_config({
|
|
||||||
let tx = tx.clone();
|
|
||||||
move |ctx| {
|
|
||||||
tx.send((ctx.kind, ctx.priority)).unwrap();
|
|
||||||
AsyncWorkJobOutcome::Completed
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let mut controller =
|
|
||||||
AsyncWorkLaneController::start(AsyncWorkLaneConfig::default(), Arc::clone(&lane));
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
rx.recv().unwrap(),
|
|
||||||
(AsyncWorkJobKind::Memcard, AsyncWorkPriority::MemcardCommitWrite)
|
|
||||||
);
|
|
||||||
assert_eq!(rx.recv().unwrap(), (AsyncWorkJobKind::Fs, AsyncWorkPriority::FsWriteConfig));
|
|
||||||
assert_eq!(rx.recv().unwrap(), (AsyncWorkJobKind::Asset, AsyncWorkPriority::AssetLoad));
|
|
||||||
assert_eq!(
|
|
||||||
rx.recv().unwrap(),
|
|
||||||
(AsyncWorkJobKind::Fs, AsyncWorkPriority::NonCriticalReadList)
|
|
||||||
);
|
|
||||||
controller.stop().unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn async_work_lane_has_one_active_job() {
|
|
||||||
let lane = Arc::new(AsyncWorkLane::default());
|
|
||||||
let mut controller =
|
|
||||||
AsyncWorkLaneController::start(AsyncWorkLaneConfig::default(), Arc::clone(&lane));
|
|
||||||
let (first_started_tx, first_started_rx) = mpsc::channel();
|
|
||||||
let (release_first_tx, release_first_rx) = mpsc::channel();
|
|
||||||
let (second_started_tx, second_started_rx) = mpsc::channel();
|
|
||||||
|
|
||||||
let first = lane
|
|
||||||
.submit(AsyncWorkJobKind::Test, move |_| {
|
|
||||||
first_started_tx.send(()).unwrap();
|
|
||||||
release_first_rx.recv().unwrap();
|
|
||||||
AsyncWorkJobOutcome::Completed
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
let second = lane
|
|
||||||
.submit(AsyncWorkJobKind::Test, move |_| {
|
|
||||||
second_started_tx.send(()).unwrap();
|
|
||||||
AsyncWorkJobOutcome::Completed
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
first_started_rx.recv().unwrap();
|
|
||||||
assert_eq!(lane.active_job().unwrap().id, first);
|
|
||||||
assert_eq!(lane.pending_depth(), 1);
|
|
||||||
assert!(second_started_rx.try_recv().is_err());
|
|
||||||
|
|
||||||
release_first_tx.send(()).unwrap();
|
|
||||||
second_started_rx.recv().unwrap();
|
|
||||||
assert_eq!(lane.telemetry().last_started_job_id, Some(second));
|
|
||||||
controller.stop().unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn async_work_lane_supports_cooperative_cancellation() {
|
|
||||||
let lane = Arc::new(AsyncWorkLane::default());
|
|
||||||
let mut controller =
|
|
||||||
AsyncWorkLaneController::start(AsyncWorkLaneConfig::default(), Arc::clone(&lane));
|
|
||||||
let (started_tx, started_rx) = mpsc::channel();
|
|
||||||
|
|
||||||
let job_id = lane
|
|
||||||
.submit(AsyncWorkJobKind::Test, move |ctx| {
|
|
||||||
started_tx.send(()).unwrap();
|
|
||||||
while !ctx.is_canceled() {
|
|
||||||
std::thread::yield_now();
|
|
||||||
}
|
|
||||||
AsyncWorkJobOutcome::Canceled
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
started_rx.recv().unwrap();
|
|
||||||
assert!(lane.request_cancel(job_id));
|
|
||||||
controller.stop().unwrap();
|
|
||||||
assert_eq!(lane.telemetry().canceled_jobs, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn async_work_lane_rejects_submit_after_shutdown() {
|
|
||||||
let lane = Arc::new(AsyncWorkLane::default());
|
|
||||||
lane.request_shutdown();
|
|
||||||
|
|
||||||
let result = lane.submit(AsyncWorkJobKind::Test, |_| AsyncWorkJobOutcome::Completed);
|
|
||||||
assert_eq!(result, Err(AsyncWorkLaneError::Shutdown));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn async_work_lane_shutdown_discards_pending_jobs() {
|
|
||||||
let lane = Arc::new(AsyncWorkLane::default());
|
|
||||||
lane.submit(AsyncWorkJobKind::Test, |_| AsyncWorkJobOutcome::Completed).unwrap();
|
|
||||||
assert_eq!(lane.pending_depth(), 1);
|
|
||||||
|
|
||||||
lane.request_shutdown();
|
|
||||||
assert!(lane.wait_take().is_none());
|
|
||||||
assert_eq!(lane.pending_depth(), 0);
|
|
||||||
assert_eq!(lane.telemetry().shutdown_discards, 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,330 +0,0 @@
|
|||||||
use crate::task::TaskId;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum ForegroundOwner {
|
|
||||||
Hub,
|
|
||||||
Game(TaskId),
|
|
||||||
Shell(TaskId),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum ResidentGameState {
|
|
||||||
Foreground,
|
|
||||||
PauseRequested { remaining_ticks: u8 },
|
|
||||||
ResumeRequested,
|
|
||||||
PausedSuspended,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct ResidentGame {
|
|
||||||
pub task_id: TaskId,
|
|
||||||
pub state: ResidentGameState,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum ForegroundStackError {
|
|
||||||
ResidentGameAlreadyExists { existing: TaskId, requested: TaskId },
|
|
||||||
ForegroundShellAlreadyExists { existing: TaskId, requested: TaskId },
|
|
||||||
TaskIsNotResidentGame(TaskId),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct ForegroundStack {
|
|
||||||
owner: ForegroundOwner,
|
|
||||||
resident_game: Option<ResidentGame>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for ForegroundStack {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { owner: ForegroundOwner::Hub, resident_game: None }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ForegroundStack {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn owner(&self) -> ForegroundOwner {
|
|
||||||
self.owner
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resident_game(&self) -> Option<ResidentGame> {
|
|
||||||
self.resident_game
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resident_game_task(&self) -> Option<TaskId> {
|
|
||||||
self.resident_game.map(|game| game.task_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_game_foreground(&mut self, task_id: TaskId) -> Result<(), ForegroundStackError> {
|
|
||||||
if let Some(game) = self.resident_game
|
|
||||||
&& game.task_id != task_id
|
|
||||||
{
|
|
||||||
return Err(ForegroundStackError::ResidentGameAlreadyExists {
|
|
||||||
existing: game.task_id,
|
|
||||||
requested: task_id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
self.resident_game = Some(ResidentGame { task_id, state: ResidentGameState::Foreground });
|
|
||||||
self.owner = ForegroundOwner::Game(task_id);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn request_home_from_game(
|
|
||||||
&mut self,
|
|
||||||
task_id: TaskId,
|
|
||||||
pause_budget_ticks: u8,
|
|
||||||
) -> Result<(), ForegroundStackError> {
|
|
||||||
match self.resident_game {
|
|
||||||
Some(game) if game.task_id == task_id => {
|
|
||||||
if !matches!(
|
|
||||||
game.state,
|
|
||||||
ResidentGameState::PauseRequested { .. } | ResidentGameState::PausedSuspended
|
|
||||||
) {
|
|
||||||
self.resident_game = Some(ResidentGame {
|
|
||||||
task_id,
|
|
||||||
state: ResidentGameState::PauseRequested {
|
|
||||||
remaining_ticks: pause_budget_ticks.max(1),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
_ => Err(ForegroundStackError::TaskIsNotResidentGame(task_id)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn advance_pause_budget(&mut self, task_id: TaskId) -> Result<bool, ForegroundStackError> {
|
|
||||||
match self.resident_game {
|
|
||||||
Some(game)
|
|
||||||
if game.task_id == task_id
|
|
||||||
&& matches!(
|
|
||||||
game.state,
|
|
||||||
ResidentGameState::PauseRequested { remaining_ticks: 1 }
|
|
||||||
) =>
|
|
||||||
{
|
|
||||||
self.resident_game =
|
|
||||||
Some(ResidentGame { task_id, state: ResidentGameState::PausedSuspended });
|
|
||||||
self.owner = ForegroundOwner::Hub;
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
Some(game)
|
|
||||||
if game.task_id == task_id
|
|
||||||
&& matches!(game.state, ResidentGameState::PauseRequested { .. }) =>
|
|
||||||
{
|
|
||||||
let ResidentGameState::PauseRequested { remaining_ticks } = game.state else {
|
|
||||||
unreachable!();
|
|
||||||
};
|
|
||||||
self.resident_game = Some(ResidentGame {
|
|
||||||
task_id,
|
|
||||||
state: ResidentGameState::PauseRequested {
|
|
||||||
remaining_ticks: remaining_ticks.saturating_sub(1).max(1),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
Ok(false)
|
|
||||||
}
|
|
||||||
Some(game) if game.task_id == task_id => Ok(false),
|
|
||||||
_ => Err(ForegroundStackError::TaskIsNotResidentGame(task_id)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn request_resume_game(&mut self, task_id: TaskId) -> Result<(), ForegroundStackError> {
|
|
||||||
match self.resident_game {
|
|
||||||
Some(game) if game.task_id == task_id => {
|
|
||||||
self.resident_game =
|
|
||||||
Some(ResidentGame { task_id, state: ResidentGameState::ResumeRequested });
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
_ => Err(ForegroundStackError::TaskIsNotResidentGame(task_id)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn complete_resume_game(&mut self, task_id: TaskId) -> Result<(), ForegroundStackError> {
|
|
||||||
match self.resident_game {
|
|
||||||
Some(game) if game.task_id == task_id => {
|
|
||||||
self.resident_game =
|
|
||||||
Some(ResidentGame { task_id, state: ResidentGameState::Foreground });
|
|
||||||
self.owner = ForegroundOwner::Game(task_id);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
_ => Err(ForegroundStackError::TaskIsNotResidentGame(task_id)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_shell_foreground(&mut self, task_id: TaskId) -> Result<(), ForegroundStackError> {
|
|
||||||
if let ForegroundOwner::Shell(existing) = self.owner
|
|
||||||
&& existing != task_id
|
|
||||||
{
|
|
||||||
return Err(ForegroundStackError::ForegroundShellAlreadyExists {
|
|
||||||
existing,
|
|
||||||
requested: task_id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(game) = self.resident_game {
|
|
||||||
self.resident_game = Some(ResidentGame {
|
|
||||||
task_id: game.task_id,
|
|
||||||
state: ResidentGameState::PausedSuspended,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
self.owner = ForegroundOwner::Shell(task_id);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn return_to_hub(&mut self) {
|
|
||||||
self.owner = ForegroundOwner::Hub;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear_resident_game(&mut self, task_id: TaskId) {
|
|
||||||
if self.resident_game_task() == Some(task_id) {
|
|
||||||
self.resident_game = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.owner == ForegroundOwner::Game(task_id) {
|
|
||||||
self.owner = ForegroundOwner::Hub;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn foreground_stack_starts_at_hub() {
|
|
||||||
let stack = ForegroundStack::new();
|
|
||||||
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Hub);
|
|
||||||
assert_eq!(stack.resident_game(), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn setting_game_foreground_registers_resident_game() {
|
|
||||||
let mut stack = ForegroundStack::new();
|
|
||||||
let game = TaskId(7);
|
|
||||||
|
|
||||||
stack.set_game_foreground(game).expect("game should become foreground");
|
|
||||||
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Game(game));
|
|
||||||
assert_eq!(
|
|
||||||
stack.resident_game(),
|
|
||||||
Some(ResidentGame { task_id: game, state: ResidentGameState::Foreground })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn second_resident_game_is_rejected() {
|
|
||||||
let mut stack = ForegroundStack::new();
|
|
||||||
|
|
||||||
stack.set_game_foreground(TaskId(1)).expect("first game should be accepted");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
stack.set_game_foreground(TaskId(2)),
|
|
||||||
Err(ForegroundStackError::ResidentGameAlreadyExists {
|
|
||||||
existing: TaskId(1),
|
|
||||||
requested: TaskId(2),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn home_request_moves_resident_game_to_pause_requested() {
|
|
||||||
let mut stack = ForegroundStack::new();
|
|
||||||
let game = TaskId(3);
|
|
||||||
|
|
||||||
stack.set_game_foreground(game).expect("game should be foreground");
|
|
||||||
stack.request_home_from_game(game, 2).expect("home request should pause game");
|
|
||||||
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Game(game));
|
|
||||||
assert_eq!(
|
|
||||||
stack.resident_game(),
|
|
||||||
Some(ResidentGame {
|
|
||||||
task_id: game,
|
|
||||||
state: ResidentGameState::PauseRequested { remaining_ticks: 2 },
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn pause_budget_expiry_suspends_game_and_returns_to_hub() {
|
|
||||||
let mut stack = ForegroundStack::new();
|
|
||||||
let game = TaskId(3);
|
|
||||||
|
|
||||||
stack.set_game_foreground(game).expect("game should be foreground");
|
|
||||||
stack.request_home_from_game(game, 1).expect("home request should pause game");
|
|
||||||
|
|
||||||
assert!(stack.advance_pause_budget(game).expect("budget should advance"));
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Hub);
|
|
||||||
assert_eq!(
|
|
||||||
stack.resident_game(),
|
|
||||||
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn pause_budget_decrements_before_expiry() {
|
|
||||||
let mut stack = ForegroundStack::new();
|
|
||||||
let game = TaskId(3);
|
|
||||||
|
|
||||||
stack.set_game_foreground(game).expect("game should be foreground");
|
|
||||||
stack.request_home_from_game(game, 2).expect("home request should pause game");
|
|
||||||
|
|
||||||
assert!(!stack.advance_pause_budget(game).expect("budget should advance"));
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Game(game));
|
|
||||||
assert_eq!(
|
|
||||||
stack.resident_game(),
|
|
||||||
Some(ResidentGame {
|
|
||||||
task_id: game,
|
|
||||||
state: ResidentGameState::PauseRequested { remaining_ticks: 1 },
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(stack.advance_pause_budget(game).expect("budget should expire"));
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Hub);
|
|
||||||
assert_eq!(
|
|
||||||
stack.resident_game(),
|
|
||||||
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resume_request_precedes_game_foreground_restore() {
|
|
||||||
let mut stack = ForegroundStack::new();
|
|
||||||
let game = TaskId(3);
|
|
||||||
|
|
||||||
stack.set_game_foreground(game).expect("game should be foreground");
|
|
||||||
stack.request_home_from_game(game, 1).expect("home request should pause game");
|
|
||||||
stack.advance_pause_budget(game).expect("budget should expire");
|
|
||||||
|
|
||||||
stack.request_resume_game(game).expect("resume should be requested");
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Hub);
|
|
||||||
assert_eq!(
|
|
||||||
stack.resident_game(),
|
|
||||||
Some(ResidentGame { task_id: game, state: ResidentGameState::ResumeRequested })
|
|
||||||
);
|
|
||||||
|
|
||||||
stack.complete_resume_game(game).expect("resume should complete");
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Game(game));
|
|
||||||
assert_eq!(
|
|
||||||
stack.resident_game(),
|
|
||||||
Some(ResidentGame { task_id: game, state: ResidentGameState::Foreground })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn shell_foreground_keeps_resident_game() {
|
|
||||||
let mut stack = ForegroundStack::new();
|
|
||||||
let game = TaskId(3);
|
|
||||||
let shell = TaskId(4);
|
|
||||||
|
|
||||||
stack.set_game_foreground(game).expect("game should be foreground");
|
|
||||||
stack.request_home_from_game(game, 1).expect("home request should suspend game");
|
|
||||||
stack.advance_pause_budget(game).expect("budget should expire");
|
|
||||||
stack.set_shell_foreground(shell).expect("shell should become foreground");
|
|
||||||
|
|
||||||
assert_eq!(stack.owner(), ForegroundOwner::Shell(shell));
|
|
||||||
assert_eq!(stack.resident_game_task(), Some(game));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,4 +8,4 @@ pub use fs_backend::FsBackend;
|
|||||||
pub use fs_entry::FsEntry;
|
pub use fs_entry::FsEntry;
|
||||||
pub use fs_error::FsError;
|
pub use fs_error::FsError;
|
||||||
pub use fs_state::FsState;
|
pub use fs_state::FsState;
|
||||||
pub use virtual_fs::{FsAsyncLaneOperation, VirtualFS};
|
pub use virtual_fs::VirtualFS;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use crate::fs::{FsBackend, FsEntry, FsError};
|
use crate::fs::{FsBackend, FsEntry, FsError};
|
||||||
use crate::services::async_work::{AsyncWorkJobKind, AsyncWorkPriority};
|
|
||||||
|
|
||||||
/// Virtual Filesystem (VFS) interface for Prometeu.
|
/// Virtual Filesystem (VFS) interface for Prometeu.
|
||||||
///
|
///
|
||||||
@@ -14,29 +13,6 @@ pub struct VirtualFS {
|
|||||||
backend: Option<Box<dyn FsBackend>>,
|
backend: Option<Box<dyn FsBackend>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum FsAsyncLaneOperation {
|
|
||||||
Write,
|
|
||||||
Delete,
|
|
||||||
Config,
|
|
||||||
Read,
|
|
||||||
ListDir,
|
|
||||||
Exists,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FsAsyncLaneOperation {
|
|
||||||
pub const fn job_kind(self) -> AsyncWorkJobKind {
|
|
||||||
AsyncWorkJobKind::Fs
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn priority(self) -> AsyncWorkPriority {
|
|
||||||
match self {
|
|
||||||
Self::Write | Self::Delete | Self::Config => AsyncWorkPriority::FsWriteConfig,
|
|
||||||
Self::Read | Self::ListDir | Self::Exists => AsyncWorkPriority::NonCriticalReadList,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for VirtualFS {
|
impl Default for VirtualFS {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::new()
|
Self::new()
|
||||||
@@ -266,18 +242,4 @@ mod tests {
|
|||||||
assert!(matches!(vfs.delete("/"), Err(FsError::PermissionDenied)));
|
assert!(matches!(vfs.delete("/"), Err(FsError::PermissionDenied)));
|
||||||
assert_eq!(calls.delete.load(Ordering::Relaxed), 0);
|
assert_eq!(calls.delete.load(Ordering::Relaxed), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn fs_async_lane_operations_classify_priority_without_public_api_changes() {
|
|
||||||
assert_eq!(FsAsyncLaneOperation::Write.job_kind(), AsyncWorkJobKind::Fs);
|
|
||||||
assert_eq!(FsAsyncLaneOperation::Write.priority(), AsyncWorkPriority::FsWriteConfig);
|
|
||||||
assert_eq!(FsAsyncLaneOperation::Delete.priority(), AsyncWorkPriority::FsWriteConfig);
|
|
||||||
assert_eq!(FsAsyncLaneOperation::Config.priority(), AsyncWorkPriority::FsWriteConfig);
|
|
||||||
assert_eq!(FsAsyncLaneOperation::Read.priority(), AsyncWorkPriority::NonCriticalReadList);
|
|
||||||
assert_eq!(
|
|
||||||
FsAsyncLaneOperation::ListDir.priority(),
|
|
||||||
AsyncWorkPriority::NonCriticalReadList
|
|
||||||
);
|
|
||||||
assert_eq!(FsAsyncLaneOperation::Exists.priority(), AsyncWorkPriority::NonCriticalReadList);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,336 +0,0 @@
|
|||||||
use prometeu_hal::app_mode::AppMode;
|
|
||||||
use prometeu_hal::cartridge::CartridgeManifest;
|
|
||||||
use std::fs;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::time::SystemTime;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct GameLibraryEntry {
|
|
||||||
pub manifest: CartridgeManifest,
|
|
||||||
pub title: String,
|
|
||||||
pub app_id: u32,
|
|
||||||
pub app_version: String,
|
|
||||||
pub path: PathBuf,
|
|
||||||
pub discovered_at: SystemTime,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GameLibraryEntry {
|
|
||||||
fn new(path: PathBuf, manifest: CartridgeManifest, discovered_at: SystemTime) -> Self {
|
|
||||||
Self {
|
|
||||||
title: manifest.title.clone(),
|
|
||||||
app_id: manifest.app_id,
|
|
||||||
app_version: manifest.app_version.clone(),
|
|
||||||
manifest,
|
|
||||||
path,
|
|
||||||
discovered_at,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn switch_target(&self) -> GameSwitchTarget {
|
|
||||||
GameSwitchTarget::from_entry(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct GameSwitchTarget {
|
|
||||||
pub path: PathBuf,
|
|
||||||
pub app_id: u32,
|
|
||||||
pub title: String,
|
|
||||||
pub app_version: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GameSwitchTarget {
|
|
||||||
pub fn from_entry(entry: &GameLibraryEntry) -> Self {
|
|
||||||
Self {
|
|
||||||
path: entry.path.clone(),
|
|
||||||
app_id: entry.app_id,
|
|
||||||
title: entry.title.clone(),
|
|
||||||
app_version: entry.app_version.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct GameLibraryDiagnostic {
|
|
||||||
pub path: PathBuf,
|
|
||||||
pub reason: GameLibraryDiagnosticReason,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum GameLibraryDiagnosticReason {
|
|
||||||
RootNotDirectory,
|
|
||||||
CandidateReadFailed,
|
|
||||||
MissingManifest,
|
|
||||||
InvalidManifest,
|
|
||||||
UnsupportedVersion,
|
|
||||||
MissingProgram,
|
|
||||||
NonGameAppMode,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct GameLibrary {
|
|
||||||
entries: Vec<GameLibraryEntry>,
|
|
||||||
diagnostics: Vec<GameLibraryDiagnostic>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GameLibrary {
|
|
||||||
pub fn empty() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn entries(&self) -> &[GameLibraryEntry] {
|
|
||||||
&self.entries
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn diagnostics(&self) -> &[GameLibraryDiagnostic] {
|
|
||||||
&self.diagnostics
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_empty(&self) -> bool {
|
|
||||||
self.entries.is_empty()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn discover_games_root(root: impl AsRef<Path>) -> GameLibrary {
|
|
||||||
let root = root.as_ref();
|
|
||||||
let discovered_at = SystemTime::now();
|
|
||||||
|
|
||||||
if !root.is_dir() {
|
|
||||||
return GameLibrary {
|
|
||||||
entries: Vec::new(),
|
|
||||||
diagnostics: vec![GameLibraryDiagnostic {
|
|
||||||
path: root.to_path_buf(),
|
|
||||||
reason: GameLibraryDiagnosticReason::RootNotDirectory,
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let read_dir = match fs::read_dir(root) {
|
|
||||||
Ok(read_dir) => read_dir,
|
|
||||||
Err(_) => {
|
|
||||||
return GameLibrary {
|
|
||||||
entries: Vec::new(),
|
|
||||||
diagnostics: vec![GameLibraryDiagnostic {
|
|
||||||
path: root.to_path_buf(),
|
|
||||||
reason: GameLibraryDiagnosticReason::CandidateReadFailed,
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
|
|
||||||
for item in read_dir {
|
|
||||||
let Ok(item) = item else {
|
|
||||||
diagnostics.push(GameLibraryDiagnostic {
|
|
||||||
path: root.to_path_buf(),
|
|
||||||
reason: GameLibraryDiagnosticReason::CandidateReadFailed,
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
let path = item.path();
|
|
||||||
if !path.is_dir() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
match discover_candidate(&path, discovered_at) {
|
|
||||||
Ok(entry) => entries.push(entry),
|
|
||||||
Err(reason) => diagnostics.push(GameLibraryDiagnostic { path, reason }),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
entries.sort_by(|left, right| {
|
|
||||||
left.title
|
|
||||||
.cmp(&right.title)
|
|
||||||
.then_with(|| left.app_id.cmp(&right.app_id))
|
|
||||||
.then_with(|| left.path.cmp(&right.path))
|
|
||||||
});
|
|
||||||
|
|
||||||
GameLibrary { entries, diagnostics }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn discover_candidate(
|
|
||||||
path: &Path,
|
|
||||||
discovered_at: SystemTime,
|
|
||||||
) -> Result<GameLibraryEntry, GameLibraryDiagnosticReason> {
|
|
||||||
let manifest_path = path.join("manifest.json");
|
|
||||||
if !manifest_path.exists() {
|
|
||||||
return Err(GameLibraryDiagnosticReason::MissingManifest);
|
|
||||||
}
|
|
||||||
|
|
||||||
let manifest_content = fs::read_to_string(manifest_path)
|
|
||||||
.map_err(|_| GameLibraryDiagnosticReason::InvalidManifest)?;
|
|
||||||
let manifest: CartridgeManifest = serde_json::from_str(&manifest_content)
|
|
||||||
.map_err(|_| GameLibraryDiagnosticReason::InvalidManifest)?;
|
|
||||||
|
|
||||||
if manifest.magic != "PMTU" {
|
|
||||||
return Err(GameLibraryDiagnosticReason::InvalidManifest);
|
|
||||||
}
|
|
||||||
if manifest.cartridge_version != 1 {
|
|
||||||
return Err(GameLibraryDiagnosticReason::UnsupportedVersion);
|
|
||||||
}
|
|
||||||
if manifest.app_mode != AppMode::Game {
|
|
||||||
return Err(GameLibraryDiagnosticReason::NonGameAppMode);
|
|
||||||
}
|
|
||||||
if !path.join("program.pbx").exists() {
|
|
||||||
return Err(GameLibraryDiagnosticReason::MissingProgram);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(GameLibraryEntry::new(path.to_path_buf(), manifest, discovered_at))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use serde_json::json;
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
use std::time::UNIX_EPOCH;
|
|
||||||
|
|
||||||
static TEST_DIR_COUNTER: AtomicU64 = AtomicU64::new(0);
|
|
||||||
|
|
||||||
struct TestRoot {
|
|
||||||
path: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TestRoot {
|
|
||||||
fn new() -> Self {
|
|
||||||
let unique = TEST_DIR_COUNTER.fetch_add(1, Ordering::Relaxed);
|
|
||||||
let path = std::env::temp_dir().join(format!(
|
|
||||||
"prometeu-game-library-test-{}-{}",
|
|
||||||
std::process::id(),
|
|
||||||
unique
|
|
||||||
));
|
|
||||||
fs::create_dir_all(&path).expect("test root should be created");
|
|
||||||
Self { path }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_candidate(&self, name: &str, manifest: serde_json::Value, with_program: bool) {
|
|
||||||
let candidate = self.path.join(name);
|
|
||||||
fs::create_dir_all(&candidate).expect("candidate should be created");
|
|
||||||
fs::write(candidate.join("manifest.json"), manifest.to_string())
|
|
||||||
.expect("manifest should be written");
|
|
||||||
if with_program {
|
|
||||||
fs::write(candidate.join("program.pbx"), [0_u8])
|
|
||||||
.expect("program should be written");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for TestRoot {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let _ = fs::remove_dir_all(&self.path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn manifest(title: &str, app_id: u32, app_mode: &str) -> serde_json::Value {
|
|
||||||
json!({
|
|
||||||
"magic": "PMTU",
|
|
||||||
"cartridge_version": 1,
|
|
||||||
"app_id": app_id,
|
|
||||||
"title": title,
|
|
||||||
"app_version": "1.0.0",
|
|
||||||
"app_mode": app_mode
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn discovery_returns_only_immediate_valid_game_directories() {
|
|
||||||
let root = TestRoot::new();
|
|
||||||
root.add_candidate("zeta", manifest("Zeta", 2, "Game"), true);
|
|
||||||
root.add_candidate("alpha", manifest("Alpha", 1, "Game"), true);
|
|
||||||
root.add_candidate("shell", manifest("Shell", 3, "Shell"), true);
|
|
||||||
root.add_candidate("missing-program", manifest("Missing Program", 4, "Game"), false);
|
|
||||||
fs::write(root.path.join("loose-file.txt"), "ignored").expect("file should be written");
|
|
||||||
|
|
||||||
let nested_parent = root.path.join("nested-parent");
|
|
||||||
fs::create_dir_all(nested_parent.join("nested-game")).expect("nested dir should exist");
|
|
||||||
fs::write(
|
|
||||||
nested_parent.join("nested-game").join("manifest.json"),
|
|
||||||
manifest("Nested", 5, "Game").to_string(),
|
|
||||||
)
|
|
||||||
.expect("nested manifest should be written");
|
|
||||||
fs::write(nested_parent.join("nested-game").join("program.pbx"), [0_u8])
|
|
||||||
.expect("nested program should be written");
|
|
||||||
|
|
||||||
let library = discover_games_root(&root.path);
|
|
||||||
|
|
||||||
assert_eq!(library.entries().len(), 2);
|
|
||||||
assert_eq!(library.entries()[0].title, "Alpha");
|
|
||||||
assert_eq!(library.entries()[0].app_id, 1);
|
|
||||||
assert_eq!(library.entries()[0].app_version, "1.0.0");
|
|
||||||
assert_eq!(library.entries()[0].manifest.app_mode, AppMode::Game);
|
|
||||||
assert!(library.entries()[0].path.ends_with("alpha"));
|
|
||||||
assert!(library.entries()[0].discovered_at >= UNIX_EPOCH);
|
|
||||||
assert_eq!(library.entries()[1].title, "Zeta");
|
|
||||||
|
|
||||||
assert!(library.diagnostics().iter().any(|diagnostic| {
|
|
||||||
diagnostic.path.ends_with("shell")
|
|
||||||
&& diagnostic.reason == GameLibraryDiagnosticReason::NonGameAppMode
|
|
||||||
}));
|
|
||||||
assert!(library.diagnostics().iter().any(|diagnostic| {
|
|
||||||
diagnostic.path.ends_with("missing-program")
|
|
||||||
&& diagnostic.reason == GameLibraryDiagnosticReason::MissingProgram
|
|
||||||
}));
|
|
||||||
assert!(library.diagnostics().iter().any(|diagnostic| {
|
|
||||||
diagnostic.path.ends_with("nested-parent")
|
|
||||||
&& diagnostic.reason == GameLibraryDiagnosticReason::MissingManifest
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn switch_target_preserves_resolved_identity() {
|
|
||||||
let path = PathBuf::from("test-cartridges/stress-console");
|
|
||||||
let entry = GameLibraryEntry::new(
|
|
||||||
path.clone(),
|
|
||||||
CartridgeManifest {
|
|
||||||
magic: "PMTU".to_string(),
|
|
||||||
cartridge_version: 1,
|
|
||||||
app_id: 42,
|
|
||||||
title: "Stress".to_string(),
|
|
||||||
app_version: "1.0.0".to_string(),
|
|
||||||
app_mode: AppMode::Game,
|
|
||||||
capabilities: vec![],
|
|
||||||
},
|
|
||||||
UNIX_EPOCH,
|
|
||||||
);
|
|
||||||
|
|
||||||
let target = entry.switch_target();
|
|
||||||
|
|
||||||
assert_eq!(target.path, path);
|
|
||||||
assert_eq!(target.app_id, 42);
|
|
||||||
assert_eq!(target.title, "Stress");
|
|
||||||
assert_eq!(target.app_version, "1.0.0");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn missing_root_returns_diagnostic_and_no_entries() {
|
|
||||||
let root = TestRoot::new();
|
|
||||||
let missing = root.path.join("missing");
|
|
||||||
|
|
||||||
let library = discover_games_root(&missing);
|
|
||||||
|
|
||||||
assert!(library.is_empty());
|
|
||||||
assert_eq!(library.diagnostics().len(), 1);
|
|
||||||
assert_eq!(library.diagnostics()[0].reason, GameLibraryDiagnosticReason::RootNotDirectory);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn repository_test_cartridges_include_stress_and_dummy_boy() {
|
|
||||||
let games_root =
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..").join("test-cartridges");
|
|
||||||
|
|
||||||
let library = discover_games_root(games_root);
|
|
||||||
let entries = library.entries();
|
|
||||||
|
|
||||||
assert!(entries.iter().any(|entry| {
|
|
||||||
entry.app_id == 1
|
|
||||||
&& entry.title == "Stress Console"
|
|
||||||
&& entry.path.ends_with("stress-console")
|
|
||||||
}));
|
|
||||||
assert!(entries.iter().any(|entry| {
|
|
||||||
entry.app_id == 2 && entry.title == "Dummy Boy" && entry.path.ends_with("dummy-boy")
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user