Author SHA1 Message Date
bquarkz 6ef376763c multi-frontend-pvm-neutrality
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-09-18 23:16:26 +01:00
bquarkz f50a3f127f regenerate PBX test cartridges
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
2026-07-15 08:04:29 +01:00
bquarkz f0f3f972ce fix PBX executable format identity 2026-07-15 08:01:47 +01:00
bquarkz b2d2533acb Fix PBX problems 2026-07-15 07:55:52 +01:00
bquarkz 4b499288e2 Portable Host Backend Strategy
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
2026-07-14 16:39:46 +01:00
bquarkz aa3b31deb5 Merge pull request 'dev/runtime-owned-variable-glyph-bank-palette-protocol' (#37) from dev/runtime-owned-variable-glyph-bank-palette-protocol into master
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Reviewed-on: #37
2026-07-14 15:25:05 +00:00
bquarkz f784ccd774 Runtime-Owned Variable Glyph Bank Palette Protocol
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-07-14 16:16:05 +01:00
bquarkz 7cced0709b housekeep DSC-0046 variable glyph palette protocol
Intrepid/Prometeu/Runtime/pipeline/head There was a failure building this commit
Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit
2026-07-14 16:08:17 +01:00
bquarkz e2a5a67621 implements PLN-0172 runtime glyph palette handoff 2026-07-14 15:54:28 +01:00
bquarkz fbe4d0cac0 implements PLN-0171 variable glyph palette test coverage 2026-07-14 15:53:31 +01:00
bquarkz 4c0f1cb9ad implements PLN-0170 palette reference failures 2026-07-14 15:51:44 +01:00
bquarkz 94ffd241bd implements PLN-0169 variable glyph palette decode 2026-07-14 15:48:57 +01:00
bquarkz a415c172c7 implements PLN-0168 variable glyph bank residency 2026-07-14 15:46:50 +01:00
bquarkz c89116b6f8 implements PLN-0167 variable glyph palette specs 2026-07-14 15:46:20 +01:00
bquarkz dc279fe72b Runtime-Owned Variable Glyph Bank Palette Protocol 2026-07-14 15:40:49 +01:00
bquarkz 01221769cd added agendo about background service (music player as example)
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
2026-07-05 19:10:19 +01:00
bquarkz 3cce8a2b25 Merge pull request 'dev/system-os-cartridge-switch-orchestrator' (#36) from dev/system-os-cartridge-switch-orchestrator into master
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Reviewed-on: #36
2026-07-05 17:47:26 +00:00
bquarkz de53eb5ad7 Hub Suspended Game Kill Affordance
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-07-05 16:27:05 +01:00
bquarkz 49cb16b6cb implements PLN-0166 2026-07-05 09:42:57 +01:00
bquarkz 3aec829c70 implements PLN-0165 2026-07-05 09:41:01 +01:00
bquarkz 73c8246c8d implements PLN-0163 2026-07-05 09:36:59 +01:00
bquarkz fa0a768b84 implements PLN-0164 2026-07-05 09:31:27 +01:00
bquarkz 62573e9574 Hub Suspended Game Kill Affordance 2026-07-05 09:25:01 +01:00
bquarkz c814e057dc implements PLN-0162 2026-07-05 01:26:42 +01:00
bquarkz 8d719843c7 implements PLN-0161 2026-07-05 01:24:45 +01:00
bquarkz d6afa6ae6b implements PLN-0160 2026-07-05 01:18:33 +01:00
bquarkz 3df8227ebf implements PLN-0159 2026-07-05 01:14:45 +01:00
bquarkz b30ff73e3d implements PLN-0158 2026-07-05 01:12:09 +01:00
bquarkz dcd3479b1d implements PLN-0157 2026-07-05 01:07:54 +01:00
bquarkz 0ffb3467b1 SystemOS Cartridge Switch Orchestrator 2026-07-05 01:03:02 +01:00
bquarkz 313b896e7b Merge pull request 'dev/foreground-stack-game-pause-shell-vm-backed' (#35) from dev/foreground-stack-game-pause-shell-vm-backed into master
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Reviewed-on: #35
2026-07-04 23:46:58 +00:00
bquarkz 6dc8cb5372 VM Context Ownership for Resident Game and VM-Backed Shell
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-07-05 00:36:15 +01:00
bquarkz c34bbaf936 implements PLN-0156 2026-07-05 00:30:56 +01:00
bquarkz e613ab43c9 implements PLN-0155 2026-07-05 00:26:16 +01:00
bquarkz 4e05daf280 implements PLN-0154 2026-07-05 00:21:10 +01:00
bquarkz 8098dbd7f4 VM Context Ownership for Resident Game and VM-Backed Shell 2026-07-05 00:16:50 +01:00
bquarkz e01b463e1f implements PLN-0153
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-07-04 19:42:59 +01:00
bquarkz b8fc5a0534 implements PLN-0152 2026-07-04 19:41:35 +01:00
bquarkz f26731413f implements PLN-0151 2026-07-04 19:40:05 +01:00
bquarkz fa2e329d4b implements PLN-0150 2026-07-04 19:36:24 +01:00
bquarkz c3d6b70b0c implements PLN-0149 2026-07-04 19:34:04 +01:00
bquarkz 49a676ff86 implements PLN-0148 2026-07-04 19:30:00 +01:00
bquarkz 23a181de46 VM Context Ownership for Resident Game and VM-Backed Shell 2026-07-04 19:25:55 +01:00
bquarkz bd27f5eb63 implements PLN-0147 2026-07-04 18:55:24 +01:00
bquarkz 6646ccfbb5 implements PLN-0146 2026-07-04 18:52:49 +01:00
bquarkz 0ecab2910b implements PLN-0145 2026-07-04 18:52:04 +01:00
bquarkz 3eeda25e97 Foreground Stack, Game Pause, and VM-Backed Shell Coexistence 2026-07-04 18:48:11 +01:00
bquarkz a22215392d fix native shell ticking resident game 2026-07-04 18:32:44 +01:00
bquarkz e19409a2ef fix resident game relaunch from hub 2026-07-04 18:26:25 +01:00
bquarkz a517a24978 implements PLN-0144 2026-07-04 13:26:05 +01:00
bquarkz a771f6320e implements PLN-0143 2026-07-04 13:24:08 +01:00
bquarkz d645bbb7bd implements PLN-0142 2026-07-04 13:20:52 +01:00
bquarkz 5ff273f167 Foreground Stack, Game Pause, and VM-Backed Shell Coexistence 2026-07-04 13:17:30 +01:00
bquarkz 33f70d1c6e implements PLN-0139 2026-07-04 13:10:55 +01:00
bquarkz 999136fef3 implements PLN-0141 2026-07-03 23:15:11 +01:00
bquarkz 1b29b2f985 implements PLN-0140 2026-07-03 23:10:03 +01:00
bquarkz 29e002c5f3 implements PLN-0138 2026-07-03 23:06:35 +01:00
bquarkz 57c9af939b implements PLN-0137 2026-07-03 23:04:23 +01:00
bquarkz d54dadf2a5 implements PLN-0136 2026-07-03 23:00:49 +01:00
bquarkz 126bffa37d Foreground Stack, Game Pause, and VM-Backed Shell Coexistence 2026-07-03 22:52:08 +01:00
bquarkz 4bc9ce2b73 Merge pull request 'dev/system-run-cart' (#34) from dev/system-run-cart into master
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Reviewed-on: #34
2026-07-03 20:43:02 +00:00
bquarkz 95465869b1 fix fragile test
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-07-03 21:35:07 +01:00
bquarkz 377cb41a3f implements PLN-0135
Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit
2026-07-03 17:30:10 +01:00
bquarkz 6593581954 implements PLN-0134 2026-07-03 17:28:54 +01:00
bquarkz badc9b8874 implements PLN-0133 2026-07-03 17:26:00 +01:00
bquarkz f49accc796 implements PLN-0132 2026-07-03 17:23:49 +01:00
bquarkz 46b2fae514 SystemOS Library Root and Home Game Launch 2026-07-03 17:22:35 +01:00
bquarkz 7307870414 fix format and clippy
Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
2026-07-03 10:05:56 +01:00
bquarkz 5137592cdd implements PLN-0131 2026-07-03 09:59:55 +01:00
bquarkz 68fd3bcd65 implements PLN-0130 2026-07-03 09:58:30 +01:00
bquarkz d39e03c7d9 implements PLN-0129 2026-07-03 09:57:11 +01:00
bquarkz 2ab5c43334 System Run Cart 2026-07-03 09:56:02 +01:00
bquarkz 23d3ed641e Merge pull request '[PERF] Async Background Work Lanes for Assets and FS' (#33) from dev/perf-async-background-work-lanes-for-assets-and-fs into master
Intrepid/Prometeu/Runtime/pipeline/head There was a failure building this commit
Reviewed-on: #33
2026-07-01 09:17:23 +00:00
bquarkz 5d3db4c22a [PERF] Async Background Work Lanes for Assets and FS
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-07-01 10:09:33 +01:00
bquarkz b84946a3a0 [PERF] Async Background Work Lanes for Assets and FS 2026-07-01 10:01:51 +01:00
bquarkz 0adec90f23 implements PLN-0128 asset pipeline telemetry tests
Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit
2026-06-28 14:20:53 +01:00
bquarkz 8747c4f4cf implements PLN-0127 async io lane boundaries 2026-06-28 14:14:10 +01:00
bquarkz 961557583b implements PLN-0126 asset backlog public api 2026-06-28 14:08:30 +01:00
bquarkz 30c24a4ea7 implements PLN-0125 asset backlog stable handles 2026-06-28 14:02:53 +01:00
bquarkz 7598a15782 implements PLN-0124 async work lane infrastructure 2026-06-28 13:57:41 +01:00
bquarkz 54dad3b398 implements PLN-0123 async work lane specs 2026-06-28 13:53:53 +01:00
bquarkz 8f37d971cd [PERF] Async Background Work Lanes for Assets and FS
Intrepid/Prometeu/Runtime/pipeline/head There was a failure building this commit
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-06-28 09:35:08 +01:00
bquarkz bd147938a0 README update
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
2026-06-20 17:14:41 +01:00
bquarkz 443b1d7cfb Merge pull request 'dev/render-worker-establishment' (#32) from dev/real-render-worker-establishment into master
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Reviewed-on: #32
2026-06-20 16:11:07 +00:00
bquarkz 21b5d59a7d Real Render Worker Establishment
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-06-20 17:05:25 +01:00
bquarkz aa917cf44e implements PLN-0121
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-06-16 05:49:46 +01:00
bquarkz 850ca8691b implements PLN-0120 2026-06-16 05:46:13 +01:00
bquarkz 67a629dbe4 implements PLN-0119 2026-06-16 05:44:08 +01:00
bquarkz 6b5b27d068 implements PLN-0118 2026-06-16 05:38:02 +01:00
bquarkz cfb5b1ac89 implements PLN-0117 2026-06-15 16:20:46 +01:00
bquarkz 0c6a669e6e implements PLN-0116 2026-06-15 16:17:16 +01:00
bquarkz 4b890850aa implements PLN-0115 2026-06-15 16:13:56 +01:00
bquarkz 28105c2bf2 implements PLN-0114 2026-06-15 16:11:34 +01:00
bquarkz 76d4e9c8ce implements PLN-0113 2026-06-15 16:09:39 +01:00
bquarkz 57bf2b84d3 implements PLN-0112 2026-06-15 16:06:53 +01:00
bquarkz 4c48b92f3b implements PLN-0111 2026-06-15 16:04:36 +01:00
bquarkz 12d314a62d implements PLN-0110 2026-06-15 16:01:47 +01:00
bquarkz 3916a652b2 add real render worker implementation plans 2026-06-15 15:49:17 +01:00
bquarkz cafbc42018 accept real render worker decision 2026-06-15 12:31:01 +01:00
bquarkz 1022750c12 resolve render worker agenda questions 2026-06-15 12:28:25 +01:00
bquarkz 373f842bef align render worker agenda direction 2026-06-15 12:15:57 +01:00
bquarkz a761e73587 update real render worker agenda 2026-06-15 12:04:43 +01:00
bquarkz b4f7b4f3c0 clean up debugger platform tests 2026-06-15 11:59:09 +01:00
bquarkz 9cf9fa6163 implements PLN-0109
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
2026-06-15 10:47:34 +01:00
bquarkz 117a18ee72 implements PLN-0108 2026-06-15 06:04:29 +01:00
bquarkz f45b3a38cb implements PLN-0107 2026-06-15 06:01:49 +01:00
bquarkz 5381ae02b1 implements PLN-0106 2026-06-15 06:00:39 +01:00
bquarkz 1d6b799960 implements PLN-0105 2026-06-15 05:59:06 +01:00
bquarkz d0a2682366 implements PLN-0104 2026-06-15 05:56:15 +01:00
bquarkz c62aef51ba implements PLN-0103 2026-06-15 05:52:48 +01:00
bquarkz d2bace2612 implements PLN-0102 2026-06-15 05:51:07 +01:00
bquarkz 6f3df74e79 implements PLN-0101 2026-06-15 05:48:24 +01:00
bquarkz 18cfeedbff implements PLN-0100 2026-06-15 05:46:28 +01:00
142 changed files with 11788 additions and 3338 deletions
Generated
+10
View File
@@ -1469,6 +1469,16 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pbxgen-dummy-boy"
version = "0.1.0"
dependencies = [
"anyhow",
"prometeu-bytecode",
"prometeu-hal",
"serde_json",
]
[[package]]
name = "pbxgen-stress"
version = "0.1.0"
+1
View File
@@ -8,6 +8,7 @@ members = [
"crates/console/prometeu-vm",
"crates/host/prometeu-host-desktop-winit",
"crates/tools/prometeu-cli",
"crates/tools/pbxgen-dummy-boy",
"crates/tools/pbxgen-stress",
"crates/dev/prometeu-test-support",
"crates/dev/prometeu-layer-tests",
+49 -7
View File
@@ -1,7 +1,7 @@
# PROMETEU Runtime
PROMETEU is an educational and experimental fantasy handheld / fantasy console.
This repository contains the Rust runtime workspace for the machine: VM-facing components, virtual peripherals, host integration, CLI entrypoints, development utilities, specs, and discussion artifacts.
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:
@@ -41,21 +41,29 @@ This repository is a Rust workspace rooted at [Cargo.toml](Cargo.toml) with memb
- `crates/dev`
The main user-facing dispatcher binary is `prometeu`, built from `crates/tools/prometeu-cli`.
The same package also builds `prometeu-runtime`, which embeds the current desktop host runtime.
Current CLI surface:
- `prometeu run <cart>`
- `prometeu debug <cart> --port <port>`
- `prometeu build <project-dir>`
- `prometeu pack <cart-dir>`
- `prometeu verify ...`
Not every command is fully implemented in every distribution path yet. Today, the runtime flow is the most concrete and the dispatcher forwards execution to specialized binaries when they are available.
The dispatcher forwards runtime execution to `prometeu-runtime`.
For lower-level local runs, `prometeu-runtime` also accepts:
- `--run <cart>`
- `--debug <cart> --port <port>`
- `--fs-root <path>`
- `--cap <path>`
Other ecosystem commands, such as build, pack, and verification tooling, are not part of the current dispatcher surface in this workspace.
## Requirements
- Rust toolchain from [rust-toolchain.toml](rust-toolchain.toml)
- `rustup` for toolchain installation and management
- `cargo-llvm-cov` for coverage targets such as `make coverage` and `make ci-domains`
- a local graphical environment for desktop runtime commands
## Quick Start
@@ -77,7 +85,41 @@ Run the current stress cartridge fixture:
cargo run -q -p prometeu-cli --bin prometeu -- run test-cartridges/stress-console
```
The desktop runtime opens a native window through the host layer, so this last command is intended for a local graphical environment.
Run the embedded runtime binary directly:
```bash
cargo run -q -p prometeu-cli --bin prometeu-runtime -- --run test-cartridges/stress-console
```
Regenerate and run the stress cartridge fixture:
```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.
## Validation
Format, lint, and test the workspace:
```bash
make test
```
Run the CI-oriented non-domain gate:
```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
@@ -137,7 +179,7 @@ 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;
- some CLI subcommands still act as dispatcher placeholders for binaries that are not always present in a local build or distribution.
- 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.
+1 -1
View File
@@ -19,6 +19,6 @@ pub use assembler::{assemble, AsmError};
pub use decoder::{decode_next, DecodeError};
pub use disassembler::disassemble;
pub use layout::{compute_function_layouts, FunctionLayout};
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl};
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl, PBX_MAGIC};
pub use program_image::ProgramImage;
pub use value::{string_materialization_count, HeapRef, Value};
+13 -11
View File
@@ -80,9 +80,11 @@ const SECTION_KIND_DEBUG: u32 = 3;
const SECTION_KIND_EXPORTS: u32 = 4;
const SECTION_KIND_SYSCALLS: u32 = 5;
/// Represents the final serialized format of a PBS v0 module.
pub const PBX_MAGIC: [u8; 4] = *b"PBX\0";
/// Represents the final serialized format of a PBX v0 module.
///
/// This structure is a pure data container for the PBS format. It does NOT
/// This structure is a pure data container for the PBX format. It does NOT
/// contain any linker-like logic (symbol resolution, patching, etc.).
/// All multi-module programs must be flattened and linked by the compiler
/// before being serialized into this format.
@@ -126,8 +128,8 @@ impl BytecodeModule {
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
let mut out = Vec::new();
// Magic "PBS\0"
out.extend_from_slice(b"PBS\0");
// Magic "PBX\0"
out.extend_from_slice(&PBX_MAGIC);
// Version 0
out.extend_from_slice(&0u16.to_le_bytes());
// Endianness 0 (Little Endian), Reserved
@@ -272,8 +274,8 @@ impl BytecodeLoader {
return Err(LoadError::UnexpectedEof);
}
// Magic "PBS\0"
if &bytes[0..4] != b"PBS\0" {
// Magic "PBX\0"
if bytes[0..4] != PBX_MAGIC[..] {
return Err(LoadError::InvalidMagic);
}
@@ -708,7 +710,7 @@ mod tests {
fn create_header(section_count: u32) -> Vec<u8> {
let mut h = vec![0u8; 32];
h[0..4].copy_from_slice(b"PBS\0");
h[0..4].copy_from_slice(&PBX_MAGIC);
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
h[6] = 0; // endianness
h[8..12].copy_from_slice(&section_count.to_le_bytes());
@@ -727,7 +729,7 @@ mod tests {
}
}
fn build_pbs_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
fn build_pbx_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
let mut data = create_header(sections.len() as u32);
let mut offset = 32 + (sections.len() as u32 * 12);
@@ -748,7 +750,7 @@ mod tests {
#[test]
fn test_invalid_magic() {
let mut data = create_header(0);
data[0] = b'X';
data[0..4].copy_from_slice(b"PBS\0");
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
}
@@ -897,7 +899,7 @@ mod tests {
#[test]
fn test_malformed_sysc_section_is_rejected() {
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
let data = build_pbx_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MalformedSection));
}
@@ -914,7 +916,7 @@ mod tests {
sysc.extend_from_slice(&0u16.to_le_bytes());
sysc.extend_from_slice(&0u16.to_le_bytes());
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
let data = build_pbx_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidUtf8));
}
@@ -4,7 +4,7 @@ use crate::value::Value;
use std::collections::HashMap;
use std::sync::Arc;
/// Represents a fully linked, executable PBS program image.
/// Represents a fully linked, executable PBX program image.
///
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
/// produced by the compiler. All linking, relocation, and symbol resolution
File diff suppressed because it is too large Load Diff
@@ -8,8 +8,8 @@ use prometeu_hal::scene_viewport_resolver::{
};
use prometeu_hal::sprite::Sprite;
use prometeu_hal::{
BoundScenePacket, Camera2D, ComposerFramePacket, Game2DFramePacket, GameSpritePacket,
GfxBridge, HudPacket,
BoundScenePacket, Camera2D, ComposerFramePacket, ComposerOpStatus, Game2DFrameComposer,
Game2DFramePacket, GameSpritePacket, GfxBridge, HudPacket,
};
use std::sync::Arc;
@@ -452,6 +452,41 @@ impl FrameComposer {
}
}
impl Game2DFrameComposer for FrameComposer {
fn begin_frame(&mut self) {
FrameComposer::begin_frame(self);
}
fn bind_scene(&mut self, scene_bank_id: usize) -> ComposerOpStatus {
if FrameComposer::bind_scene(self, scene_bank_id) {
ComposerOpStatus::Ok
} else {
ComposerOpStatus::SceneUnavailable
}
}
fn unbind_scene(&mut self) {
FrameComposer::unbind_scene(self);
}
fn set_camera(&mut self, x: i32, y: i32) -> ComposerOpStatus {
FrameComposer::set_camera(self, x, y);
ComposerOpStatus::Ok
}
fn emit_sprite(&mut self, sprite: Sprite) -> ComposerOpStatus {
if FrameComposer::emit_sprite(self, sprite) {
ComposerOpStatus::Ok
} else {
ComposerOpStatus::SpriteOverflow
}
}
fn close_game2d_packet(&self) -> Game2DFramePacket {
FrameComposer::close_game2d_packet(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -522,8 +557,9 @@ mod tests {
fn make_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
let size = tile_size as usize;
let mut bank = GlyphBank::new(tile_size, size, size);
bank.palettes[palette_id as usize][1] = color;
let mut bank =
GlyphBank::with_palette_count(tile_size, size, size, palette_id as usize + 1);
bank.palette_mut(palette_id).unwrap()[1] = color;
for pixel in &mut bank.pixel_indices {
*pixel = 1;
}
@@ -896,6 +932,45 @@ mod tests {
assert!(packet.gfx2d.is_empty());
}
#[test]
fn game2d_frame_composer_facade_closes_equivalent_packet() {
let mut frame_composer = FrameComposer::new(
Hardware::W,
Hardware::H,
Arc::new(MemoryBanks::default()),
make_glyph_slot_index(&[]),
);
let composer: &mut dyn Game2DFrameComposer = &mut frame_composer;
assert_eq!(composer.set_camera(10, 20), ComposerOpStatus::Ok);
composer.begin_frame();
assert_eq!(
composer.emit_sprite(Sprite {
glyph: Glyph { glyph_id: 7, palette_id: 3 },
x: 4,
y: 5,
layer: 2,
bank_id: 1,
active: false,
flip_x: true,
flip_y: false,
priority: 9,
}),
ComposerOpStatus::Ok
);
let packet = composer.close_game2d_packet();
assert_eq!(packet.composer.bound_scene, None);
assert_eq!(packet.composer.camera, Camera2D { x: 10, y: 20 });
assert_eq!(packet.composer.sprites.len(), 1);
assert_eq!(packet.composer.sprites[0].glyph_id, 7);
assert_eq!(packet.composer.sprites[0].palette_id, 3);
assert_eq!(packet.composer.sprites[0].layer, 2);
assert!(packet.composer.sprites[0].flip_x);
assert!(packet.gfx2d.is_empty());
}
#[test]
fn composer_buffer_preserves_integer_layer_ordering() {
let mut frame_composer = FrameComposer::new(
+63 -4
View File
@@ -812,7 +812,14 @@ impl Gfx {
let fetch_x = if tile.entry.flip_x() { size - 1 - local_x } else { local_x };
let fetch_y = if tile.entry.flip_y() { size - 1 - local_y } else { local_y };
let px_index = tile.bank.get_pixel_index(tile.entry.glyph_id, fetch_x, fetch_y);
let color = tile.bank.resolve_color(tile.entry.palette_id, px_index);
let color = tile.bank.resolve_color(tile.entry.palette_id, px_index).unwrap_or_else(
|| {
panic!(
"SCENE composition fatal: palette_id {} is not resident for glyph asset {}",
tile.entry.palette_id, tile.entry.glyph_asset_id
)
},
);
if color.alpha() == 0 {
continue;
}
@@ -862,7 +869,14 @@ impl Gfx {
let fetch_y = if sprite.flip_y { size - 1 - local_y } else { local_y };
let px_index = bank.get_pixel_index(sprite.glyph.glyph_id, fetch_x, fetch_y);
let color = bank.resolve_color(sprite.glyph.palette_id, px_index);
let color = bank.resolve_color(sprite.glyph.palette_id, px_index).unwrap_or_else(
|| {
panic!(
"SPRITE composition fatal: palette_id {} is not resident for glyph bank {}",
sprite.glyph.palette_id, sprite.bank_id
)
},
);
if color.alpha() == 0 {
continue;
}
@@ -1010,9 +1024,14 @@ mod tests {
fn make_glyph_bank(tile_size: TileSize, palette_colors: &[(u8, u8, Color)]) -> GlyphBank {
let size = tile_size as usize;
let mut bank = GlyphBank::new(tile_size, size, size);
let palette_count = palette_colors
.iter()
.map(|(palette_id, _, _)| *palette_id as usize + 1)
.max()
.unwrap_or(1);
let mut bank = GlyphBank::with_palette_count(tile_size, size, size, palette_count);
for (palette_id, color_index, color) in palette_colors {
bank.palettes[*palette_id as usize][*color_index as usize] = *color;
bank.palette_mut(*palette_id).unwrap()[*color_index as usize] = *color;
}
bank
}
@@ -1152,6 +1171,26 @@ mod tests {
assert_eq!(back[0], Color::RED.raw());
}
#[test]
#[should_panic(expected = "SPRITE composition fatal: palette_id 1 is not resident")]
fn sprite_draw_panics_for_invalid_palette_reference() {
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
let mut back = vec![Color::BLACK.raw(); 8 * 8];
let sprite = Sprite {
glyph: Glyph { glyph_id: 0, palette_id: 1 },
x: 0,
y: 0,
layer: 0,
flip_x: false,
flip_y: false,
bank_id: 0,
active: true,
priority: 0,
};
Gfx::draw_sprite_pixel_by_pixel(&mut back, 8, 8, &sprite, &bank);
}
#[test]
fn test_cached_tile_draws_opaque_color_index_zero() {
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
@@ -1194,6 +1233,26 @@ mod tests {
assert_eq!(target.back[0], Color::RED.raw());
}
#[test]
#[should_panic(expected = "SCENE composition fatal: palette_id 1 is not resident")]
fn cached_tile_draw_panics_for_invalid_palette_reference() {
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
let mut back = vec![Color::BLACK.raw(); 8 * 8];
let mut target = RenderTarget { back: &mut back, screen_w: 8, screen_h: 8 };
let entry = CachedTileEntry {
active: true,
glyph_id: 0,
palette_id: 1,
flags: 0,
glyph_asset_id: 0,
};
Gfx::draw_cached_tile_pixels(
&mut target,
CachedTileDraw { x: 0, y: 0, entry, bank: &bank, tile_size: TileSize::Size8 },
);
}
#[test]
fn test_draw_rect() {
let banks = Arc::new(MemoryBanks::new());
+145 -55
View File
@@ -10,8 +10,13 @@ use crate::pad::Pad;
use crate::touch::Touch;
use prometeu_hal::cartridge::AssetsPayloadSource;
use prometeu_hal::sprite::Sprite;
use prometeu_hal::{AssetBridge, AudioBridge, GfxBridge, HardwareBridge, PadBridge, TouchBridge};
use prometeu_hal::{Game2DFramePacket, RenderSubmission, RenderSubmissionPacket};
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;
@@ -28,6 +33,8 @@ use std::sync::Arc;
/// - **Audio**: Stereo, Command-based mixing.
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
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.
pub gfx: Gfx,
/// Canonical frame orchestration owner for scene/camera/cache/resolver/sprites.
@@ -48,32 +55,8 @@ impl Default for Hardware {
}
}
impl HardwareBridge for Hardware {
fn begin_frame(&mut self) {
self.frame_composer.begin_frame();
}
fn bind_scene(&mut self, scene_bank_id: usize) -> bool {
self.frame_composer.bind_scene(scene_bank_id)
}
fn unbind_scene(&mut self) {
self.frame_composer.unbind_scene();
}
fn set_camera(&mut self, x: i32, y: i32) {
self.frame_composer.set_camera(x, y);
}
fn emit_sprite(&mut self, sprite: Sprite) -> bool {
self.frame_composer.emit_sprite(sprite)
}
fn close_game2d_packet(&self) -> Game2DFramePacket {
self.frame_composer.close_game2d_packet()
}
fn publish_render_submission(&mut self, submission: &RenderSubmission) {
impl Hardware {
fn consume_render_submission(&mut self, submission: &RenderSubmission) {
match &submission.packet {
RenderSubmissionPacket::Game2D(packet) => {
if packet.composer.bound_scene.is_none() {
@@ -89,7 +72,19 @@ impl HardwareBridge for Hardware {
}
self.gfx.present();
}
}
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();
@@ -98,28 +93,56 @@ impl HardwareBridge for Hardware {
self.frame_composer.render_frame(&mut self.gfx);
}
}
}
fn has_glyph_bank(&self, bank_id: usize) -> bool {
self.gfx.glyph_banks.glyph_bank_slot(bank_id).is_some()
impl Game2DFrameComposer for Hardware {
fn begin_frame(&mut self) {
self.frame_composer.begin_frame();
}
fn gfx(&self) -> &dyn GfxBridge {
&self.gfx
}
fn gfx_mut(&mut self) -> &mut dyn GfxBridge {
&mut self.gfx
fn bind_scene(&mut self, scene_bank_id: usize) -> prometeu_hal::ComposerOpStatus {
if self.frame_composer.bind_scene(scene_bank_id) {
prometeu_hal::ComposerOpStatus::Ok
} else {
prometeu_hal::ComposerOpStatus::SceneUnavailable
}
}
fn audio(&self) -> &dyn AudioBridge {
&self.audio
}
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
&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 {
&self.pad
}
fn pad_mut(&mut self) -> &mut dyn PadBridge {
&mut self.pad
}
@@ -127,25 +150,53 @@ impl HardwareBridge for Hardware {
fn touch(&self) -> &dyn TouchBridge {
&self.touch
}
fn touch_mut(&mut self) -> &mut dyn TouchBridge {
&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 {
&self.assets
}
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
&mut self.assets
}
}
impl RenderSubmissionSink for Hardware {
fn submit_render_submission(
&mut self,
submission: RenderSubmission,
) -> Result<(), RenderSubmitError> {
self.publish_render_submission(&submission);
Ok(())
fn telemetry(&self) -> &dyn TelemetryPlatform {
&NOOP_TELEMETRY
}
}
@@ -171,6 +222,7 @@ impl Hardware {
);
let glyph_slot_index = assets.glyph_asset_slot_index();
Self {
memory_banks: Arc::clone(&memory_banks),
gfx: Gfx::new(
Self::W,
Self::H,
@@ -213,7 +265,7 @@ mod tests {
fn make_glyph_bank() -> GlyphBank {
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
bank.palettes[0][1] = Color::RED;
bank.palette_mut(0).unwrap()[1] = Color::RED;
for pixel in &mut bank.pixel_indices {
*pixel = 1;
}
@@ -294,15 +346,22 @@ mod tests {
let mut glyph_slots = [None; 16];
glyph_slots[0] = Some(0);
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
assert!(hardware.bind_scene(0));
assert_eq!(
Game2DFrameComposer::bind_scene(&mut hardware, 0),
prometeu_hal::ComposerOpStatus::Ok
);
let mut packet = hardware.close_game2d_packet();
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,
}];
hardware.publish_render_submission(&RenderSubmission::game2d(FrameId::ZERO, packet));
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());
}
@@ -317,7 +376,10 @@ mod tests {
let mut glyph_slots = [None; 16];
glyph_slots[0] = Some(0);
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
assert!(hardware.bind_scene(0));
assert_eq!(
Game2DFrameComposer::bind_scene(&mut hardware, 0),
prometeu_hal::ComposerOpStatus::Ok
);
let packet = Game2DFramePacket::new(
ComposerFramePacket {
@@ -339,8 +401,12 @@ mod tests {
Vec::new(),
);
hardware.begin_frame();
hardware.publish_render_submission(&RenderSubmission::game2d(FrameId::ZERO, packet));
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());
}
@@ -371,4 +437,28 @@ mod tests {
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);
}
}
+6 -2
View File
@@ -3,16 +3,20 @@ mod audio;
mod frame_composer;
mod gfx;
pub mod hardware;
mod local_render_backend;
mod memory_banks;
mod pad;
mod test_platform;
mod touch;
pub use crate::asset::AssetManager;
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::local_render_backend::LocalFramebufferRenderBackend;
pub use crate::memory_banks::{
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, RenderResourceAccess,
SceneBankPoolAccess, SceneBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller,
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolAccess,
SceneBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller,
};
pub use crate::pad::Pad;
pub use crate::test_platform::TestPlatform;
@@ -0,0 +1,164 @@
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());
}
}
@@ -2,11 +2,12 @@
//!
//! Render consumers must cross this boundary through small, read-only traits.
//! Frame packets carry resource IDs; large resident resources stay in banks and
//! are returned as `Arc` snapshots of the slot contents. Installation and slot
//! replacement remain separate owner-side operations and are not part of the
//! render read surface.
//! 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 std::sync::{Arc, RwLock};
@@ -23,6 +24,8 @@ pub trait GlyphBankPoolAccess: Send + Sync {
pub trait GlyphBankPoolInstaller: Send + Sync {
/// Atomically swaps the resident GlyphBank in the specified slot.
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>);
/// Clears all resident GlyphBank slots.
fn clear_glyph_banks(&self);
}
/// Non-generic interface for peripherals to access sound banks.
@@ -37,6 +40,8 @@ pub trait SoundBankPoolAccess: Send + Sync {
pub trait SoundBankPoolInstaller: Send + Sync {
/// Atomically swaps the resident SoundBank in the specified slot.
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.
@@ -51,17 +56,10 @@ pub trait SceneBankPoolAccess: Send + Sync {
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);
}
/// Read-only resource surface needed by render consumers.
///
/// This is intentionally narrower than `MemoryBanks`: render code can resolve
/// stable packet IDs to resident glyph/scene banks, but cannot install or swap
/// resources through this trait.
pub trait RenderResourceAccess: GlyphBankPoolAccess + SceneBankPoolAccess {}
impl<T> RenderResourceAccess for T where T: GlyphBankPoolAccess + SceneBankPoolAccess {}
/// Centralized container for all hardware memory banks.
///
/// MemoryBanks represent the actual hardware slot state.
@@ -108,6 +106,10 @@ impl GlyphBankPoolInstaller for MemoryBanks {
pool[slot] = Some(bank);
}
}
fn clear_glyph_banks(&self) {
self.glyph_bank_pool.write().unwrap().fill(None);
}
}
impl SoundBankPoolAccess for MemoryBanks {
@@ -128,6 +130,10 @@ impl SoundBankPoolInstaller for MemoryBanks {
pool[slot] = Some(bank);
}
}
fn clear_sound_banks(&self) {
self.sound_bank_pool.write().unwrap().fill(None);
}
}
impl SceneBankPoolAccess for MemoryBanks {
@@ -148,6 +154,32 @@ impl SceneBankPoolInstaller for MemoryBanks {
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)]
@@ -164,7 +196,7 @@ mod tests {
fn make_glyph_bank() -> GlyphBank {
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
bank.palettes[0][1] = Color::WHITE;
bank.palette_mut(0).unwrap()[1] = Color::WHITE;
bank
}
@@ -193,24 +225,24 @@ mod tests {
assert_send_sync::<MemoryBanks>();
assert_send_sync::<Arc<dyn GlyphBankPoolAccess>>();
assert_send_sync::<Arc<dyn SceneBankPoolAccess>>();
assert_send_sync::<Arc<dyn RenderResourceAccess>>();
}
#[test]
fn render_resource_access_exposes_read_only_glyph_and_scene_banks() {
let banks = Arc::new(MemoryBanks::new());
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 render_resources: Arc<dyn RenderResourceAccess> = banks;
let glyph_bank =
render_resources.glyph_bank_slot(0).expect("glyph bank slot should be readable");
let scene_bank =
render_resources.scene_bank_slot(1).expect("scene bank slot should be readable");
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_bank.tile_size, TileSize::Size8);
assert_eq!(scene_bank.layers[0].tile_size, TileSize::Size8);
assert!(render_resources.glyph_bank_slot(15).is_none());
assert!(render_resources.scene_bank_slot(15).is_none());
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);
}
}
@@ -0,0 +1,100 @@
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
@@ -14,6 +14,7 @@ pub enum FirmwareState {
LaunchHub(LaunchHubStep),
HubHome(HubHomeStep),
LoadCartridge(LoadCartridgeStep),
ResumeResidentGame,
GameRunning(GameRunningStep),
ShellRunning(ShellRunningStep),
AppCrashes(AppCrashesStep),
@@ -21,13 +21,16 @@ impl AppCrashesStep {
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
// Update peripherals for input on the crash screen
ctx.hw.pad_mut().begin_frame(ctx.signals);
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::Clear { color: Color::RED }]);
ctx.hw.publish_render_submission(&RenderSubmission::shell_ui(FrameId::ZERO, packet));
ctx.platform
.render_submission_sink()
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
.expect("firmware crash render submission should publish");
// If START is pressed, return to the Hub
if ctx.hw.pad().start().down {
if ctx.platform.input().pad().start().down {
return Some(FirmwareState::LaunchHub(LaunchHubStep));
}
@@ -1,8 +1,9 @@
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
use crate::firmware::prometeu_context::PrometeuContext;
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::log::{LogLevel, LogSource};
use prometeu_system::CrashReport;
use prometeu_system::task::{TaskId, TaskState};
use prometeu_system::{CrashReport, ResidentGameState};
#[derive(Debug, Clone)]
pub struct GameRunningStep {
@@ -36,13 +37,35 @@ impl GameRunningStep {
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
}
let result = ctx.os.vm().tick(ctx.vm, ctx.signals, ctx.hw);
let pause_requested = matches!(
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
}
@@ -1,5 +1,10 @@
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, ShellRunningStep};
use crate::firmware::firmware_state::{
AppCrashesStep, FirmwareState, LoadCartridgeStep, ShellRunningStep,
};
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::primitives::Rect;
use prometeu_system::SystemProfileAction;
@@ -16,21 +21,104 @@ impl HubHomeStep {
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.vm, ctx.signals, ctx.hw);
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.platform);
if let Some(report) = outcome.crash {
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
}
if let Some(SystemProfileAction::LaunchNativeShell(app)) = outcome.action {
let task_id = ctx.os.sessions().create_native_shell_task(app.app_id(), app.title());
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)));
match outcome.action {
Some(SystemProfileAction::LaunchNativeShell(app)) => {
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 {
return Some(FirmwareState::ResumeResidentGame);
}
if let Err(error) = resident_game_termination::terminate_resident_game(
ctx.os,
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
@@ -1,7 +1,8 @@
use crate::firmware::firmware_state::{
AppCrashesStep, FirmwareState, GameRunningStep, ShellRunningStep,
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep, ShellRunningStep,
};
use crate::firmware::prometeu_context::PrometeuContext;
use crate::firmware::resident_game_termination;
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::cartridge::Cartridge;
use prometeu_hal::color::Color;
@@ -14,11 +15,30 @@ use prometeu_system::windows::WindowOwner;
pub struct LoadCartridgeStep {
pub cartridge: Cartridge,
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 {
pub fn new(cartridge: Cartridge) -> Self {
Self { cartridge, init_error: None }
Self {
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) {
@@ -29,26 +49,75 @@ impl LoadCartridgeStep {
format!("Loading cartridge: {}", self.cartridge.title),
);
ctx.platform.game2d_frame_composer().unbind_scene();
// Initialize Asset Manager
ctx.hw.assets_mut().initialize_for_cartridge(
ctx.platform.assets_mut().initialize_for_cartridge(
self.cartridge.asset_table.clone(),
self.cartridge.preload.clone(),
self.cartridge.assets.clone(),
);
self.init_error = ctx.os.vm().initialize(ctx.vm, &self.cartridge).err();
match ctx.os.sessions().load_vm_cartridge(&self.cartridge) {
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> {
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 }));
}
if self.cartridge.app_mode == AppMode::Shell {
let task_id = ctx
.os
.sessions()
.create_vm_shell_task(self.cartridge.app_id, self.cartridge.title.clone());
let Some(task_id) = self.loaded_task_id.take() else {
let report = CrashReport::VmPanic {
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(),
WindowOwner::Task(task_id),
@@ -59,10 +128,6 @@ impl LoadCartridgeStep {
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
}
let task_id = ctx
.os
.sessions()
.create_vm_game_task(self.cartridge.app_id, self.cartridge.title.clone());
Some(FirmwareState::GameRunning(GameRunningStep::new(task_id)))
}
@@ -9,7 +9,8 @@ pub struct ResetStep;
impl ResetStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
ctx.os.vm().reset(ctx.vm);
ctx.os.sessions().clear_vm_sessions();
ctx.os.vm().reset_global_runtime_state();
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
@@ -1,6 +1,7 @@
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};
@@ -59,7 +60,36 @@ impl ShellRunningStep {
}
}
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.vm, ctx.signals, ctx.hw);
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));
@@ -14,7 +14,7 @@ impl SplashScreenStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
// Play sound on enter
// ctx.hw.audio_mut().play(0, 0, 0, 255, 127, 1.0, 0, LoopMode::Off);
// ctx.platform.audio_mut().play(0, 0, 0, 255, 127, 1.0, 0, LoopMode::Off);
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
@@ -22,10 +22,10 @@ impl SplashScreenStep {
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
// Update peripherals for input
ctx.hw.pad_mut().begin_frame(ctx.signals);
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
// Draw expanding square
let (sw, sh) = ctx.hw.gfx().size();
let (sw, sh) = ctx.platform.display_size();
let max_size = (sw.min(sh) as i32 / 2).max(1);
let current_size = if self.frame < ANIMATION_DURATION {
@@ -44,11 +44,14 @@ impl SplashScreenStep {
color: Color::WHITE,
},
]);
ctx.hw.publish_render_submission(&RenderSubmission::shell_ui(FrameId::ZERO, packet));
ctx.platform
.render_submission_sink()
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
.expect("firmware splash render submission should publish");
// Transition logic
// If any button is pressed at any time after the animation ends
if self.frame >= ANIMATION_DURATION && ctx.hw.pad().any() {
if self.frame >= ANIMATION_DURATION && ctx.platform.input().pad().any() {
return Some(FirmwareState::LaunchHub(LaunchHubStep));
}
@@ -12,6 +12,7 @@ pub(crate) mod firmware_step_reset;
pub(crate) mod firmware_step_shell_running;
pub(crate) mod firmware_step_splash_screen;
mod prometeu_context;
pub(crate) mod resident_game_termination;
pub use boot_target::BootTarget;
pub use firmware::Firmware;
@@ -1,13 +1,11 @@
use crate::firmware::boot_target::BootTarget;
use prometeu_hal::{HardwareBridge, InputSignals};
use prometeu_hal::{InputSignals, RuntimePlatform};
use prometeu_system::{PrometeuHub, SystemOS};
use prometeu_vm::VirtualMachine;
pub struct PrometeuContext<'a> {
pub vm: &'a mut VirtualMachine,
pub os: &'a mut SystemOS,
pub hub: &'a mut PrometeuHub,
pub boot_target: &'a BootTarget,
pub signals: &'a InputSignals,
pub hw: &'a mut dyn HardwareBridge,
pub platform: &'a mut dyn RuntimePlatform,
}
@@ -0,0 +1,42 @@
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 })
}
+36
View File
@@ -112,6 +112,12 @@ pub enum LoadStatus {
CANCELED = 4,
ERROR = 5,
UnknownHandle = 6,
QUEUED = 7,
ACTIVE = 8,
SUPERSEDED = 9,
EMPTY = 10,
INVALID = 11,
BackendUnavailable = 12,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -129,6 +135,36 @@ pub enum AssetOpStatus {
Ok = 0,
UnknownHandle = 1,
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)]
@@ -1,6 +1,7 @@
use crate::asset::{
AssetEntry, AssetId, AssetLoadError, AssetOpStatus, BankTelemetry, HandleId, LoadStatus,
PreloadEntry, SlotRef, SlotStats,
AssetBacklogInfo, AssetBacklogPosition, AssetEntry, AssetId, AssetLoadError, AssetOpStatus,
AssetTargetStatus, BankTelemetry, BankType, HandleId, LoadStatus, PreloadEntry, SlotRef,
SlotStats,
};
use crate::cartridge::AssetsPayloadSource;
@@ -15,6 +16,12 @@ pub trait AssetBridge {
fn status(&self, handle: HandleId) -> LoadStatus;
fn commit(&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 bank_telemetry(&self) -> Vec<BankTelemetry>;
fn slot_info(&self, slot: SlotRef) -> SlotStats;
+1 -1
View File
@@ -297,7 +297,7 @@ pub enum Capability {
All,
}
#[derive(Deserialize)]
#[derive(Debug, Clone, Deserialize)]
pub struct CartridgeManifest {
pub magic: String,
pub cartridge_version: u32,
@@ -203,7 +203,7 @@ mod tests {
use super::*;
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
use crate::glyph_bank::GLYPH_BANK_PALETTE_COUNT_V1;
use crate::glyph_bank::GLYPH_BANK_MAX_PALETTE_COUNT_V1;
use serde_json::json;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
@@ -369,14 +369,14 @@ mod tests {
bank_type: BankType::GLYPH,
offset,
size,
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 4),
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
codec: AssetCodec::None,
metadata: json!({
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
}),
}
}
@@ -452,14 +452,14 @@ mod tests {
bank_type: BankType::GLYPH,
offset: 4,
size: 4,
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 4),
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
codec: AssetCodec::None,
metadata: json!({
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
}),
},
];
@@ -519,8 +519,8 @@ mod tests {
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
}
}],
"preload": []
@@ -561,8 +561,8 @@ mod tests {
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
}
}],
"preload": []
@@ -40,7 +40,7 @@ pub enum DebugResponse {
Breakpoints { pcs: Vec<usize> },
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HandshakeCartridge {
pub app_id: u32,
pub title: String,
+81 -7
View File
@@ -1,7 +1,7 @@
use crate::color::Color;
use serde::{Deserialize, Serialize};
pub const GLYPH_BANK_PALETTE_COUNT_V1: usize = 64;
pub const GLYPH_BANK_MAX_PALETTE_COUNT_V1: usize = 64;
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
/// Standard sizes for square tiles.
@@ -35,22 +35,59 @@ pub struct GlyphBank {
/// 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: 64 palettes of 16 RGBA8888 colors each.
pub palettes: [[Color; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
/// 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 the specified dimensions.
/// 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: [[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
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)
@@ -71,11 +108,48 @@ impl GlyphBank {
}
/// 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) -> Color {
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()
.unwrap_or(Color::TRANSPARENT)
}
}
#[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);
}
}
@@ -1,39 +0,0 @@
use crate::asset_bridge::AssetBridge;
use crate::audio_bridge::AudioBridge;
use crate::gfx_bridge::GfxBridge;
use crate::pad_bridge::PadBridge;
use crate::render_submission::{Game2DFramePacket, RenderSubmission};
use crate::sprite::Sprite;
use crate::touch_bridge::TouchBridge;
/// Legacy migration scaffold for code that has not moved to `platform` facades yet.
///
/// `HardwareBridge` is intentionally not the final runtime-facing contract. New
/// platform boundaries belong in `crate::platform`, and this trait must be
/// removed after runtime, firmware, host, and tests finish migrating.
pub trait HardwareBridge {
fn begin_frame(&mut self);
fn bind_scene(&mut self, scene_bank_id: usize) -> bool;
fn unbind_scene(&mut self);
fn set_camera(&mut self, x: i32, y: i32);
fn emit_sprite(&mut self, sprite: Sprite) -> bool;
fn close_game2d_packet(&self) -> Game2DFramePacket;
fn publish_render_submission(&mut self, submission: &RenderSubmission);
fn render_frame(&mut self);
fn has_glyph_bank(&self, bank_id: usize) -> bool;
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,19 +1,23 @@
use crate::hardware_bridge::HardwareBridge;
use crate::platform::RuntimePlatform;
use crate::vm_fault::VmFault;
pub struct HostContext<'a> {
pub hw: Option<&'a mut dyn HardwareBridge>,
pub platform: Option<&'a mut dyn RuntimePlatform>,
}
impl<'a> HostContext<'a> {
pub fn new(hw: Option<&'a mut dyn HardwareBridge>) -> Self {
Self { hw }
pub fn new(platform: Option<&'a mut dyn RuntimePlatform>) -> Self {
Self { platform }
}
pub fn new_platform(platform: Option<&'a mut dyn RuntimePlatform>) -> Self {
Self::new(platform)
}
#[inline]
pub fn require_hw(&mut self) -> Result<&mut dyn HardwareBridge, VmFault> {
match &mut self.hw {
Some(hw) => Ok(*hw),
pub fn require_platform(&mut self) -> Result<&mut dyn RuntimePlatform, VmFault> {
match &mut self.platform {
Some(platform) => Ok(*platform),
None => Err(VmFault::Unavailable),
}
}
+10 -4
View File
@@ -11,17 +11,19 @@ pub mod debugger_protocol;
pub mod gfx_bridge;
pub mod glyph;
pub mod glyph_bank;
pub mod hardware_bridge;
pub mod host_context;
pub mod host_return;
pub mod input_signals;
pub mod log;
pub mod native_helpers;
pub mod native_interface;
pub mod owned_frame;
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 scene_bank;
pub mod scene_layer;
@@ -40,21 +42,25 @@ pub use asset_bridge::AssetBridge;
pub use audio_bridge::{AudioBridge, AudioOpStatus, LoopMode};
pub use composer_status::ComposerOpStatus;
pub use gfx_bridge::{BlendMode, GfxBridge, GfxOpStatus};
pub use hardware_bridge::HardwareBridge;
pub use host_context::{HostContext, HostContextProvider};
pub use host_return::HostReturn;
pub use input_signals::InputSignals;
pub use native_helpers::{expect_bool, expect_int};
pub use native_interface::{NativeInterface, SyscallId};
pub use owned_frame::{OwnedRgba8888Frame, OwnedRgba8888FrameError};
pub use pad_bridge::PadBridge;
pub use platform::{
AssetStoragePlatform, AudioPlatform, ClockPacingPlatform, Game2DFrameComposer, InputPlatform,
RenderBackend, RenderSubmissionSink, RenderSubmitError, RuntimePlatform, TelemetryPlatform,
TestPlatform,
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;
@@ -0,0 +1,127 @@
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);
}
}
+13 -9
View File
@@ -31,7 +31,6 @@ pub trait Game2DFrameComposer {
fn set_camera(&mut self, x: i32, y: i32) -> ComposerOpStatus;
fn emit_sprite(&mut self, sprite: Sprite) -> ComposerOpStatus;
fn close_game2d_packet(&self) -> Game2DFramePacket;
fn has_glyph_bank(&self, bank_id: usize) -> bool;
}
pub trait AudioPlatform: AudioBridge {}
@@ -55,16 +54,25 @@ pub trait TelemetryPlatform {
}
}
#[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 AudioPlatform;
fn audio_mut(&mut self) -> &mut dyn AudioPlatform;
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 AssetStoragePlatform;
fn assets_mut(&mut self) -> &mut dyn AssetStoragePlatform;
fn assets(&self) -> &dyn AssetBridge;
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
fn telemetry(&self) -> &dyn TelemetryPlatform;
}
@@ -114,10 +122,6 @@ mod tests {
fn close_game2d_packet(&self) -> Game2DFramePacket {
Game2DFramePacket::default()
}
fn has_glyph_bank(&self, _bank_id: usize) -> bool {
false
}
}
#[test]
@@ -0,0 +1,109 @@
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);
}
}
@@ -0,0 +1,203 @@
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);
}
}
+6 -1
View File
@@ -29,7 +29,6 @@ pub use resolver::{
#[repr(u32)]
pub enum Syscall {
SystemHasCart = 0x0001,
SystemRunCart = 0x0002,
GfxClear = 0x1001,
GfxFillRect = 0x1002,
GfxDrawLine = 0x1003,
@@ -69,6 +68,12 @@ pub enum Syscall {
AssetStatus = 0x6002,
AssetCommit = 0x6003,
AssetCancel = 0x6004,
AssetBacklogInfo = 0x6005,
AssetBacklogPosition = 0x6006,
AssetBacklogMove = 0x6007,
AssetBacklogPromote = 0x6008,
AssetBacklogDemote = 0x6009,
AssetTargetStatus = 0x600A,
BankInfo = 0x6101,
}
@@ -24,4 +24,40 @@ pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
.caps(caps::ASSET)
.non_deterministic()
.cost(20),
SyscallRegistryEntry::builder(Syscall::AssetBacklogInfo, "asset", "backlog_info")
.args(0)
.rets(7)
.caps(caps::ASSET)
.non_deterministic()
.cost(5),
SyscallRegistryEntry::builder(Syscall::AssetBacklogPosition, "asset", "backlog_position")
.args(1)
.rets(4)
.caps(caps::ASSET)
.non_deterministic()
.cost(5),
SyscallRegistryEntry::builder(Syscall::AssetBacklogMove, "asset", "backlog_move")
.args(2)
.rets(1)
.caps(caps::ASSET)
.non_deterministic()
.cost(10),
SyscallRegistryEntry::builder(Syscall::AssetBacklogPromote, "asset", "backlog_promote")
.args(1)
.rets(1)
.caps(caps::ASSET)
.non_deterministic()
.cost(10),
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,11 +1,6 @@
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
SyscallRegistryEntry::builder(Syscall::SystemHasCart, "system", "has_cart")
pub(crate) const ENTRIES: &[SyscallRegistryEntry] =
&[SyscallRegistryEntry::builder(Syscall::SystemHasCart, "system", "has_cart")
.rets(1)
.caps(caps::SYSTEM),
SyscallRegistryEntry::builder(Syscall::SystemRunCart, "system", "run_cart")
.caps(caps::SYSTEM)
.non_deterministic()
.cost(50),
];
.caps(caps::SYSTEM)];
@@ -13,7 +13,6 @@ impl Syscall {
pub fn from_u32(id: u32) -> Option<Self> {
match id {
0x0001 => Some(Self::SystemHasCart),
0x0002 => Some(Self::SystemRunCart),
0x1001 => Some(Self::GfxClear),
0x1002 => Some(Self::GfxFillRect),
0x1003 => Some(Self::GfxDrawLine),
@@ -53,6 +52,12 @@ impl Syscall {
0x6002 => Some(Self::AssetStatus),
0x6003 => Some(Self::AssetCommit),
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),
_ => None,
}
@@ -69,7 +74,6 @@ impl Syscall {
pub fn name(&self) -> &'static str {
match self {
Self::SystemHasCart => "SystemHasCart",
Self::SystemRunCart => "SystemRunCart",
Self::GfxClear => "GfxClear",
Self::GfxFillRect => "GfxFillRect",
Self::GfxDrawLine => "GfxDrawLine",
@@ -109,6 +113,12 @@ impl Syscall {
Self::AssetStatus => "AssetStatus",
Self::AssetCommit => "AssetCommit",
Self::AssetCancel => "AssetCancel",
Self::AssetBacklogInfo => "AssetBacklogInfo",
Self::AssetBacklogPosition => "AssetBacklogPosition",
Self::AssetBacklogMove => "AssetBacklogMove",
Self::AssetBacklogPromote => "AssetBacklogPromote",
Self::AssetBacklogDemote => "AssetBacklogDemote",
Self::AssetTargetStatus => "AssetTargetStatus",
Self::BankInfo => "BankInfo",
}
}
@@ -69,9 +69,33 @@ fn resolver_rejects_removed_legacy_gfx_set_sprite_identity() {
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,
LoadError::UnknownSyscall { module: "gfx2d".into(), name: "set_sprite".into(), version: 1 }
DeclaredLoadError::UnknownSyscall {
module: "system".into(),
name: "run_cart".into(),
version: 1,
}
);
}
@@ -261,6 +285,30 @@ fn status_first_syscall_signatures_are_pinned() {
assert_eq!(asset_cancel.arg_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);
@@ -272,10 +320,7 @@ fn resolver_rejects_removed_bank_slot_info_identity() {
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".into(), name: "slot_info".into(), version: 1 }
);
assert_eq!(err, LoadError::UnknownSyscall { module: "bank", name: "slot_info", version: 1 });
}
#[test]
+101 -5
View File
@@ -1,4 +1,5 @@
use crate::log::{LogLevel, LogService, LogSource};
use crate::render_worker::RenderWorkerTelemetry;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
@@ -34,20 +35,51 @@ pub struct TelemetryFrame {
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)]
@@ -84,14 +116,19 @@ pub struct AtomicTelemetry {
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,
@@ -128,14 +165,19 @@ impl AtomicTelemetry {
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),
@@ -165,14 +207,19 @@ impl AtomicTelemetry {
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);
@@ -358,11 +405,13 @@ mod tests {
};
let cert = Certifier::new(config);
let mut tel = TelemetryFrame::default();
tel.cycles_used = 150;
tel.syscalls = 10;
tel.host_cpu_time_us = 500;
tel.glyph_slots_used = 2;
let tel = TelemetryFrame {
cycles_used: 150,
syscalls: 10,
host_cpu_time_us: 500,
glyph_slots_used: 2,
..Default::default()
};
let violations = cert.evaluate(&tel, &mut ls, 1000);
assert_eq!(violations, 3);
@@ -398,4 +447,51 @@ mod tests {
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);
}
}
+26 -3
View File
@@ -4,10 +4,33 @@ mod programs;
mod services;
pub use crash_report::CrashReport;
pub use os::{LifecycleError, LifecycleOperation, SystemOS};
pub use programs::{NativeShellApp, PrometeuHub, SystemProfileAction, SystemProfileUpdate};
pub use os::{
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::game_library::{
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::VirtualMachineRuntime;
pub use services::vm_runtime::{
LatestRenderFrameStore, RenderWorkerConfig, RenderWorkerController, RenderWorkerHandoff,
RenderWorkerHandoffWait, RenderWorkerOwnership, VirtualMachineRuntime,
};
pub use services::vm_session;
pub use services::windows;
@@ -1,8 +1,14 @@
use crate::CrashReport;
use crate::os::SystemOS;
use crate::os::{LifecycleError, LifecycleOperation};
use crate::process::{ProcessId, ProcessState};
use crate::task::{TaskId, TaskState};
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,
@@ -14,28 +20,145 @@ impl<'a> LifecycleFacade<'a> {
}
pub fn process_state_for_task(&self, task_id: TaskId) -> Result<ProcessState, LifecycleError> {
let process_id = process_id_for_task(self.os, task_id)?;
self.os
.process_manager
.get(process_id)
.map(|process| process.state)
.ok_or(LifecycleError::ProcessNotFound(process_id))
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(())
}
@@ -54,8 +177,32 @@ impl<'a> LifecycleFacade<'a> {
let process_id = process_id_for_task(self.os, task_id)?;
self.os.task_manager.set_foreground(task_id);
self.os.process_manager.mark_running(process_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(())
}
@@ -65,10 +212,38 @@ impl<'a> LifecycleFacade<'a> {
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,
@@ -78,11 +253,22 @@ impl<'a> LifecycleFacade<'a> {
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))?;
@@ -92,3 +278,22 @@ fn process_id_for_task(os: &SystemOS, task_id: TaskId) -> Result<ProcessId, Life
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)
}
}
}
@@ -6,6 +6,6 @@ mod window;
pub use fs::FsFacade;
pub use lifecycle::LifecycleFacade;
pub use sessions::SessionsFacade;
pub use sessions::{SessionError, SessionsFacade};
pub use vm::VmFacade;
pub use window::WindowFacade;
@@ -1,44 +1,209 @@
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_foreground_task(task_id)
.expect("newly created game task should have an associated process");
self.os.lifecycle().set_game_foreground_task(task_id)?;
self.try_create_vm_session_for_task(task_id)?;
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_foreground_task(task_id)
.expect("newly created shell task should have an associated process");
self.os.lifecycle().set_shell_foreground_task(task_id)?;
self.try_create_vm_session_for_task(task_id)?;
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_foreground_task(task_id)
.expect("newly created native shell task should have an associated process");
self.os.lifecycle().set_shell_foreground_task(task_id)?;
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,10 +1,15 @@
use crate::CrashReport;
use crate::os::SystemOS;
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::cartridge::Cartridge;
use prometeu_hal::telemetry::{CertificationConfig, TelemetryFrame};
use prometeu_hal::{HardwareBridge, InputSignals};
use prometeu_vm::VirtualMachine;
use prometeu_hal::{
FrameId, InputSignals, RenderOwnership, RenderWorkerBackend, RenderWorkerError,
RenderWorkerFrameSink, RuntimePlatform,
};
use std::sync::atomic::Ordering;
pub struct VmFacade<'a> {
@@ -12,88 +17,252 @@ pub struct VmFacade<'a> {
}
impl<'a> VmFacade<'a> {
pub fn initialize(
pub fn tick_session(
&mut self,
vm: &mut VirtualMachine,
cartridge: &Cartridge,
) -> Result<(), CrashReport> {
self.os.clear_cartridge_service_state();
self.os.vm_runtime.initialize_vm(&mut self.os.log_service, vm, cartridge)
}
pub fn tick(
&mut self,
vm: &mut VirtualMachine,
task_id: TaskId,
signals: &InputSignals,
hw: &mut dyn HardwareBridge,
platform: &mut dyn RuntimePlatform,
) -> Option<CrashReport> {
self.os.vm_runtime.tick(
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 self.os.fs_state,
&mut session.fs_state,
&mut self.os.memcard,
&mut self.os.open_files,
&mut self.os.next_handle,
vm,
&mut session.open_files,
&mut session.next_handle,
&mut session.vm,
signals,
hw,
platform,
)
}
pub fn reset(&mut self, vm: &mut VirtualMachine) {
self.os.vm_runtime.reset(vm);
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 debug_step_instruction(
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,
vm: &mut VirtualMachine,
hw: &mut dyn HardwareBridge,
platform: &mut dyn RuntimePlatform,
) -> Option<CrashReport> {
self.os.vm_runtime.debug_step_instruction(&mut self.os.log_service, vm, hw)
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.os.vm_runtime.paused
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 debug_step_requested(&self) -> bool {
self.os.vm_runtime.debug_step_request
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.os.vm_runtime.logical_frame_active
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.os.vm_runtime.tick_index
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.os.vm_runtime.logical_frame_index
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.os.vm_runtime.last_frame_cpu_time_us
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.os.vm_runtime.atomic_telemetry.completed_logical_frames.load(Ordering::Relaxed).into()
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.os.vm_runtime.atomic_telemetry.snapshot()
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 {
@@ -101,22 +270,61 @@ impl<'a> VmFacade<'a> {
}
pub fn last_crash_report(&self) -> Option<&CrashReport> {
self.os.vm_runtime.last_crash_report.as_ref()
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.os.vm_runtime.current_app_id
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.os.vm_runtime.current_cartridge_title.clone()
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.os.vm_runtime.current_cartridge_app_version.clone()
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.os.vm_runtime.current_cartridge_app_mode
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,6 +1,20 @@
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,
@@ -15,4 +29,7 @@ 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),
}
+7 -2
View File
@@ -2,6 +2,11 @@ mod facades;
mod lifecycle;
mod system_os;
pub use facades::{FsFacade, LifecycleFacade, SessionsFacade, VmFacade, WindowFacade};
pub use lifecycle::{LifecycleError, LifecycleOperation};
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,8 +1,12 @@
use crate::VirtualMachineRuntime;
use crate::fs::{FsState, VirtualFS};
use crate::os::{FsFacade, LifecycleFacade, SessionsFacade, VmFacade, WindowFacade};
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};
@@ -14,6 +18,9 @@ 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,
@@ -33,6 +40,9 @@ impl SystemOS {
),
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(),
@@ -133,15 +143,33 @@ impl SystemOS {
#[cfg(test)]
mod tests {
use super::*;
use crate::os::{LifecycleError, LifecycleOperation};
use crate::process::ProcessState;
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);
@@ -157,6 +185,394 @@ mod tests {
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);
@@ -184,6 +600,10 @@ mod tests {
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]
@@ -1,3 +1,6 @@
mod prometeu_hub;
pub use prometeu_hub::{NativeShellApp, PrometeuHub, SystemProfileAction, SystemProfileUpdate};
pub use prometeu_hub::{
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
SystemProfileUpdate,
};
@@ -1,4 +1,7 @@
#[allow(clippy::module_inception)]
mod prometeu_hub;
pub use prometeu_hub::{NativeShellApp, PrometeuHub, SystemProfileAction, SystemProfileUpdate};
pub use prometeu_hub::{
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
SystemProfileUpdate,
};
@@ -1,17 +1,26 @@
use crate::{CrashReport, SystemOS};
use crate::task::TaskId;
use crate::{CrashReport, GameLibrary, GameSwitchTarget, SystemOS};
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::color::Color;
use prometeu_hal::primitives::Rect;
use prometeu_hal::{
FrameId, GfxUiCommand, HardwareBridge, InputSignals, RenderSubmission, ShellUiFramePacket,
FrameId, GfxUiCommand, InputPlatform, InputSignals, RenderSubmission, RuntimePlatform,
ShellUiFramePacket,
};
use prometeu_vm::VirtualMachine;
const SHELL_A_BUTTON: Rect = Rect { x: 112, y: 108, w: 112, h: 48 };
const SHELL_B_BUTTON: Rect = Rect { x: 256, y: 108, w: 112, h: 48 };
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 };
@@ -24,10 +33,13 @@ 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.
pub struct PrometeuHub {
home_input_armed: bool,
game_library: GameLibrary,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -71,9 +83,11 @@ impl NativeShellApp {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SystemProfileAction {
LaunchNativeShell(NativeShellApp),
LaunchGame { target: GameSwitchTarget },
KillResidentGame,
CloseShell,
}
@@ -90,44 +104,65 @@ impl Default for PrometeuHub {
impl PrometeuHub {
pub fn new() -> Self {
Self { home_input_armed: false }
Self { home_input_armed: false, game_library: GameLibrary::empty() }
}
pub fn init(&mut self) {
self.home_input_armed = false;
}
pub fn set_game_library(&mut self, game_library: GameLibrary) {
self.game_library = game_library;
}
pub fn game_library(&self) -> &GameLibrary {
&self.game_library
}
pub fn gui_update(
&mut self,
os: &mut SystemOS,
hw: &mut dyn HardwareBridge,
platform: &mut dyn RuntimePlatform,
) -> Option<SystemProfileAction> {
let in_shell = os.windows().focused_window().is_some();
if !in_shell {
if !self.home_input_armed {
self.home_input_armed = !activation_input_down(hw);
self.home_input_armed = !activation_input_down(platform.input());
return None;
}
} else {
self.home_input_armed = false;
}
if let Some(action) =
action_for_click(in_shell, hw.touch().x(), hw.touch().y(), hw.touch().f().pressed)
{
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, hw: &mut dyn HardwareBridge) {
let pointer_x = hw.touch().x();
let pointer_y = hw.touch().y();
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 {
render_home_packet(pointer_x, pointer_y)
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() {
@@ -142,34 +177,76 @@ impl PrometeuHub {
}
ShellUiFramePacket::new(commands)
};
hw.publish_render_submission(&RenderSubmission::shell_ui(FrameId::ZERO, packet));
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,
vm: &mut VirtualMachine,
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,
hw: &mut dyn HardwareBridge,
platform: &mut dyn RuntimePlatform,
) -> SystemProfileUpdate {
let mut crash = None;
let mut action = self.gui_update(os, hw);
let mut action = self.gui_update(os, platform);
if os.windows().focused_window().is_some() {
if hw.pad().start().down {
if platform.input().pad().start().down {
action = Some(SystemProfileAction::CloseShell);
} else if action != Some(SystemProfileAction::CloseShell) {
crash = os.vm().tick(vm, signals, hw);
crash = os.vm().tick_session(task_id, signals, platform);
}
}
self.render(os, hw);
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) -> Option<SystemProfileAction> {
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;
}
@@ -178,21 +255,69 @@ fn action_for_click(in_shell: bool, x: i32, y: i32, pressed: bool) -> Option<Sys
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(hw: &dyn HardwareBridge) -> bool {
hw.touch().f().down || hw.pad().a().down || hw.pad().b().down || hw.pad().start().down
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) -> ShellUiFramePacket {
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);
@@ -206,26 +331,36 @@ fn render_home_packet(pointer_x: i32, pointer_y: i32) -> ShellUiFramePacket {
);
draw_panel(&mut commands, HOME_PANEL, COLOR_PANEL, COLOR_BORDER);
draw_buffer_text(
&mut commands,
HOME_PANEL.x + 26,
HOME_PANEL.y + 22,
"Native Shell Apps",
COLOR_TEXT,
);
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,
"first retro ui slice",
"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)
}
@@ -315,9 +450,50 @@ fn draw_button(commands: &mut Vec<GfxUiCommand>, rect: Rect, label: &str, hovere
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 + 12, w: 16, h: 24 }, border);
draw_rect(commands, Rect { x: rect.x + 34, y: rect.y + 12, w: 62, h: 24 }, COLOR_PANEL_DARK);
draw_buffer_text(commands, rect.x + 40, rect.y + 21, label, COLOR_TEXT);
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) {
@@ -327,11 +503,47 @@ fn draw_buffer_text(commands: &mut Vec<GfxUiCommand>, x: i32, y: i32, text: &str
#[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,
);
windows.set_focus(id);
}
platform.input_mut().pad_mut().begin_frame(signals);
platform.input_mut().touch_mut().begin_frame(signals);
(hub, os, platform)
}
#[test]
fn shell_a_button_click_emits_launch_action() {
assert_eq!(
action_for_click(false, HOME_BUTTONS[0].rect.x, HOME_BUTTONS[0].rect.y, true),
action_for_click(
false,
HOME_BUTTONS[0].rect.x,
HOME_BUTTONS[0].rect.y,
true,
&[],
None
),
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellA))
);
}
@@ -343,7 +555,9 @@ mod tests {
false,
SHELL_B_BUTTON.x + SHELL_B_BUTTON.w - 1,
SHELL_B_BUTTON.y,
true
true,
&[],
None
),
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellB))
);
@@ -352,18 +566,35 @@ mod tests {
#[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),
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),
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);
assert_eq!(
action_for_click(false, SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, false, &[], None),
None
);
}
#[test]
@@ -372,13 +603,54 @@ mod tests {
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),
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);
assert_eq!(action_for_click(false, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[], None), None);
}
#[test]
@@ -392,7 +664,7 @@ mod tests {
#[test]
fn home_render_produces_shell_ui_packet_commands() {
let packet = render_home_packet(SHELL_A_BUTTON.x, SHELL_A_BUTTON.y);
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| {
@@ -400,6 +672,123 @@ mod tests {
}));
}
#[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));
@@ -409,4 +798,35 @@ mod tests {
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,601 @@
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);
}
}
@@ -0,0 +1,330 @@
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_error::FsError;
pub use fs_state::FsState;
pub use virtual_fs::VirtualFS;
pub use virtual_fs::{FsAsyncLaneOperation, VirtualFS};
@@ -1,4 +1,5 @@
use crate::fs::{FsBackend, FsEntry, FsError};
use crate::services::async_work::{AsyncWorkJobKind, AsyncWorkPriority};
/// Virtual Filesystem (VFS) interface for Prometeu.
///
@@ -13,6 +14,29 @@ pub struct VirtualFS {
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 {
fn default() -> Self {
Self::new()
@@ -242,4 +266,18 @@ mod tests {
assert!(matches!(vfs.delete("/"), Err(FsError::PermissionDenied)));
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);
}
}
@@ -0,0 +1,336 @@
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")
}));
}
}
@@ -1,4 +1,5 @@
use crate::fs::{FsError, VirtualFS};
use crate::services::async_work::{AsyncWorkJobKind, AsyncWorkPriority};
use std::collections::HashMap;
pub const MEMCARD_SLOT_COUNT: usize = 32;
@@ -50,6 +51,30 @@ pub struct MemcardWriteResult {
pub bytes_written: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemcardAsyncLaneOperation {
SlotWrite,
SlotCommit,
SlotClear,
SlotRead,
SlotStat,
}
impl MemcardAsyncLaneOperation {
pub const fn job_kind(self) -> AsyncWorkJobKind {
AsyncWorkJobKind::Memcard
}
pub const fn priority(self) -> AsyncWorkPriority {
match self {
Self::SlotWrite | Self::SlotCommit | Self::SlotClear => {
AsyncWorkPriority::MemcardCommitWrite
}
Self::SlotRead | Self::SlotStat => AsyncWorkPriority::NonCriticalReadList,
}
}
}
#[derive(Debug, Clone)]
struct SlotImage {
payload: Vec<u8>,
@@ -428,4 +453,29 @@ mod tests {
let stat = mem.slot_stat(&fs, 7, 2);
assert_eq!(stat.state, MemcardSlotState::Corrupt);
}
#[test]
fn memcard_async_lane_operations_classify_priority_without_changing_public_api() {
assert_eq!(MemcardAsyncLaneOperation::SlotWrite.job_kind(), AsyncWorkJobKind::Memcard);
assert_eq!(
MemcardAsyncLaneOperation::SlotWrite.priority(),
AsyncWorkPriority::MemcardCommitWrite
);
assert_eq!(
MemcardAsyncLaneOperation::SlotCommit.priority(),
AsyncWorkPriority::MemcardCommitWrite
);
assert_eq!(
MemcardAsyncLaneOperation::SlotClear.priority(),
AsyncWorkPriority::MemcardCommitWrite
);
assert_eq!(
MemcardAsyncLaneOperation::SlotRead.priority(),
AsyncWorkPriority::NonCriticalReadList
);
assert_eq!(
MemcardAsyncLaneOperation::SlotStat.priority(),
AsyncWorkPriority::NonCriticalReadList
);
}
}
@@ -1,6 +1,10 @@
pub mod async_work;
pub mod foreground;
pub mod fs;
pub mod game_library;
pub mod memcard;
pub mod process;
pub mod task;
pub mod vm_runtime;
pub mod vm_session;
pub mod windows;
@@ -112,7 +112,7 @@ fn matrix_packet_policy_and_pacing_are_mode_specific() {
assert_eq!(game_policy.execution, RenderExecutionPolicy::WorkerCapableWithLocalFallback);
assert_eq!(
game_policy.resolve_consumer_path(RenderRuntimeCapabilities { game_render_worker: true }),
RenderConsumerPath::LocalWorkerPrototype
RenderConsumerPath::RealWorker
);
let shell_policy = RenderPolicy::for_app_mode(AppMode::Shell);
@@ -163,7 +163,7 @@ fn matrix_sync_and_worker_paths_share_latest_wins_handoff_contract() {
let outcome = match path {
RenderConsumerPath::LocalSynchronous => manager.consume_latest(&mut surface),
RenderConsumerPath::LocalWorkerPrototype => {
RenderConsumerPath::RealWorker => {
let mut worker = LocalRenderWorker;
worker.consume_latest(&mut manager, &mut surface)
}
@@ -172,7 +172,7 @@ fn matrix_sync_and_worker_paths_share_latest_wins_handoff_contract() {
(outcome, surface.seen, manager.render_telemetry().replaced_before_consume)
}
for path in [RenderConsumerPath::LocalSynchronous, RenderConsumerPath::LocalWorkerPrototype] {
for path in [RenderConsumerPath::LocalSynchronous, RenderConsumerPath::RealWorker] {
let (outcome, seen, replaced) = consume_with(path);
assert_eq!(outcome, RenderConsumeOutcome::Presented { frame_id: FrameId::new(1) });
assert_eq!(seen, vec![FrameId::new(1)]);
@@ -168,26 +168,20 @@ impl NativeInterface for VmRuntimeHost<'_> {
VmFault::Trap(TRAP_INVALID_SYSCALL, format!("Unknown syscall: 0x{:08X}", id))
})?;
match syscall {
Syscall::SystemHasCart => {
ret.push_bool(true);
return Ok(());
}
Syscall::SystemRunCart => return Ok(()),
_ => {}
if syscall == Syscall::SystemHasCart {
ret.push_bool(true);
return Ok(());
}
self.ensure_game_profile_syscall(syscall)?;
let hw = ctx.require_hw()?;
let platform = ctx.require_platform()?;
match syscall {
Syscall::SystemHasCart => unreachable!(),
Syscall::SystemRunCart => unreachable!(),
Syscall::GfxClear => {
let color = self.get_color(expect_int(args, 0)?)?;
self.gfx2d_commands.push(Gfx2dCommand::Clear { color });
hw.gfx_mut().clear(color);
Ok(())
}
Syscall::GfxUiClear => {
@@ -199,7 +193,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
}
let color = self.get_color(expect_int(args, 0)?)?;
self.gfxui_commands.push(GfxUiCommand::Clear { color });
hw.gfx_mut().clear(color);
Ok(())
}
Syscall::GfxFillRect => {
@@ -210,7 +203,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
let color = self.get_color(expect_int(args, 4)?)?;
self.gfx2d_commands
.push(Gfx2dCommand::FillRect { rect: Rect { x, y, w, h }, color });
hw.gfx_mut().fill_rect(x, y, w, h, color);
Ok(())
}
Syscall::GfxUiFillRect => {
@@ -227,7 +219,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
let color = self.get_color(expect_int(args, 4)?)?;
self.gfxui_commands
.push(GfxUiCommand::FillRect { rect: Rect { x, y, w, h }, color });
hw.gfx_mut().fill_rect(x, y, w, h, color);
Ok(())
}
Syscall::GfxDrawLine => {
@@ -243,7 +234,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
y1: y2,
color,
});
hw.gfx_mut().draw_line(x1, y1, x2, y2, color);
Ok(())
}
Syscall::GfxUiDrawLine => {
@@ -265,7 +255,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
y1: y2,
color,
});
hw.gfx_mut().draw_line(x1, y1, x2, y2, color);
Ok(())
}
Syscall::GfxDrawCircle => {
@@ -274,7 +263,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
let r = expect_int(args, 2)? as i32;
let color = self.get_color(expect_int(args, 3)?)?;
self.gfx2d_commands.push(Gfx2dCommand::DrawCircle { x, y, radius: r, color });
hw.gfx_mut().draw_circle(x, y, r, color);
Ok(())
}
Syscall::GfxUiDrawCircle => {
@@ -289,7 +277,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
let r = expect_int(args, 2)? as i32;
let color = self.get_color(expect_int(args, 3)?)?;
self.gfxui_commands.push(GfxUiCommand::DrawCircle { x, y, radius: r, color });
hw.gfx_mut().draw_circle(x, y, r, color);
Ok(())
}
Syscall::GfxDrawDisc => {
@@ -305,7 +292,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
border_color,
fill_color,
});
hw.gfx_mut().draw_disc(x, y, r, border_color, fill_color);
Ok(())
}
Syscall::GfxUiDrawDisc => {
@@ -327,7 +313,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
border_color,
fill_color,
});
hw.gfx_mut().draw_disc(x, y, r, border_color, fill_color);
Ok(())
}
Syscall::GfxDrawSquare => {
@@ -342,7 +327,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
border_color,
fill_color,
});
hw.gfx_mut().draw_square(x, y, w, h, border_color, fill_color);
Ok(())
}
Syscall::GfxUiDrawSquare => {
@@ -363,7 +347,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
border_color,
fill_color,
});
hw.gfx_mut().draw_square(x, y, w, h, border_color, fill_color);
Ok(())
}
Syscall::GfxDrawText => {
@@ -372,7 +355,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
let msg = expect_string(args, 2, "message")?;
let color = self.get_color(expect_int(args, 3)?)?;
self.gfx2d_commands.push(Gfx2dCommand::DrawText { x, y, text: msg.clone(), color });
hw.gfx_mut().draw_text(x, y, &msg, color);
Ok(())
}
Syscall::GfxUiDrawText => {
@@ -387,7 +369,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
let msg = expect_string(args, 2, "message")?;
let color = self.get_color(expect_int(args, 3)?)?;
self.gfxui_commands.push(GfxUiCommand::DrawText { x, y, text: msg.clone(), color });
hw.gfx_mut().draw_text(x, y, &msg, color);
Ok(())
}
Syscall::ComposerBindScene => {
@@ -399,23 +380,23 @@ impl NativeInterface for VmRuntimeHost<'_> {
}
};
let bound = catch_unwind(AssertUnwindSafe(|| hw.bind_scene(scene_bank_id)))
.map_err(|payload| VmFault::Panic(Self::panic_payload_to_string(payload)))?;
let status = catch_unwind(AssertUnwindSafe(|| {
platform.game2d_frame_composer().bind_scene(scene_bank_id)
}))
.map_err(|payload| VmFault::Panic(Self::panic_payload_to_string(payload)))?;
let status =
if bound { ComposerOpStatus::Ok } else { ComposerOpStatus::SceneUnavailable };
ret.push_int(status as i64);
Ok(())
}
Syscall::ComposerUnbindScene => {
hw.unbind_scene();
platform.game2d_frame_composer().unbind_scene();
ret.push_int(ComposerOpStatus::Ok as i64);
Ok(())
}
Syscall::ComposerSetCamera => {
let x = Self::int_arg_to_i32_trap(expect_int(args, 0)?, "camera x")?;
let y = Self::int_arg_to_i32_trap(expect_int(args, 1)?, "camera y")?;
hw.set_camera(x, y);
platform.game2d_frame_composer().set_camera(x, y);
Ok(())
}
Syscall::ComposerEmitSprite => {
@@ -463,12 +444,7 @@ impl NativeInterface for VmRuntimeHost<'_> {
}
};
if !hw.has_glyph_bank(bank_id as usize) {
ret.push_int(ComposerOpStatus::BankInvalid as i64);
return Ok(());
}
let emitted = hw.emit_sprite(Sprite {
let status = platform.game2d_frame_composer().emit_sprite(Sprite {
glyph: Glyph { glyph_id, palette_id },
x,
y,
@@ -479,8 +455,6 @@ impl NativeInterface for VmRuntimeHost<'_> {
flip_y,
priority,
});
let status =
if emitted { ComposerOpStatus::Ok } else { ComposerOpStatus::SpriteOverflow };
ret.push_int(status as i64);
Ok(())
}
@@ -507,7 +481,7 @@ impl NativeInterface for VmRuntimeHost<'_> {
return Ok(());
}
let status = hw.audio_mut().play(
let status = platform.audio_mut().play(
0,
sample_id_raw as u16,
voice_id_raw as usize,
@@ -537,7 +511,8 @@ impl NativeInterface for VmRuntimeHost<'_> {
return Ok(());
}
if hw.assets().slot_info(SlotRef::audio(bank_id as usize)).asset_id.is_none() {
if platform.assets().slot_info(SlotRef::audio(bank_id as usize)).asset_id.is_none()
{
ret.push_int(AudioOpStatus::BankInvalid as i64);
return Ok(());
}
@@ -553,7 +528,7 @@ impl NativeInterface for VmRuntimeHost<'_> {
return Ok(());
}
let status = hw.audio_mut().play(
let status = platform.audio_mut().play(
bank_id,
sample_id_raw as u16,
voice_id_raw as usize,
@@ -750,7 +725,7 @@ impl NativeInterface for VmRuntimeHost<'_> {
})?;
let slot_index = expect_int(args, 1)? as usize;
match hw.assets().load(asset_id, slot_index) {
match platform.assets().load(asset_id, slot_index) {
Ok(handle) => {
ret.push_int(AssetOpStatus::Ok as i64);
ret.push_int(handle as i64);
@@ -764,26 +739,84 @@ impl NativeInterface for VmRuntimeHost<'_> {
}
}
Syscall::AssetStatus => {
ret.push_int(hw.assets().status(expect_int(args, 0)? as u32) as i64);
ret.push_int(platform.assets().status(expect_int(args, 0)? as u32) as i64);
Ok(())
}
Syscall::AssetCommit => {
let status = hw.assets().commit(expect_int(args, 0)? as u32);
let status = platform.assets().commit(expect_int(args, 0)? as u32);
ret.push_int(status as i64);
Ok(())
}
Syscall::AssetCancel => {
let status = hw.assets().cancel(expect_int(args, 0)? as u32);
let status = platform.assets().cancel(expect_int(args, 0)? as u32);
ret.push_int(status as i64);
Ok(())
}
Syscall::AssetBacklogInfo => {
let info = platform.assets().backlog_info();
ret.push_int(info.status as i64);
ret.push_int(info.pending_count as i64);
ret.push_int(info.active_handle as i64);
ret.push_int(info.active_asset_id.unwrap_or(0) as i64);
ret.push_int(info.active_bank_type.map(|bank| bank as i64).unwrap_or(0));
ret.push_int(info.active_slot.map(|slot| slot as i64).unwrap_or(0));
ret.push_int(info.active_progress as i64);
Ok(())
}
Syscall::AssetBacklogPosition => {
let position = platform.assets().backlog_position(expect_int(args, 0)? as u32);
ret.push_int(position.status as i64);
ret.push_int(position.state as i64);
ret.push_int(position.position as i64);
ret.push_int(position.progress as i64);
Ok(())
}
Syscall::AssetBacklogMove => {
let new_position = expect_non_negative_usize(args, 1, "new_position")?;
let status =
platform.assets().backlog_move(expect_int(args, 0)? as u32, new_position);
ret.push_int(status as i64);
Ok(())
}
Syscall::AssetBacklogPromote => {
let status = platform.assets().backlog_promote(expect_int(args, 0)? as u32);
ret.push_int(status as i64);
Ok(())
}
Syscall::AssetBacklogDemote => {
let status = platform.assets().backlog_demote(expect_int(args, 0)? as u32);
ret.push_int(status as i64);
Ok(())
}
Syscall::AssetTargetStatus => {
let bank_type = match expect_int(args, 0)? {
0 => BankType::GLYPH,
1 => BankType::SOUNDS,
2 => BankType::SCENE,
other => {
return Err(VmFault::Trap(
TRAP_TYPE,
format!("Invalid asset bank type: {}", other),
));
}
};
let slot = expect_non_negative_usize(args, 1, "slot")?;
let target = platform.assets().target_status(bank_type, slot);
ret.push_int(target.status as i64);
ret.push_int(target.asset_id.unwrap_or(0) as i64);
ret.push_int(target.handle as i64);
ret.push_int(target.state as i64);
ret.push_int(target.position as i64);
ret.push_int(target.progress as i64);
Ok(())
}
Syscall::BankInfo => {
let asset_type = match expect_int(args, 0)? as u32 {
0 => BankType::GLYPH,
1 => BankType::SOUNDS,
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
};
let telemetry = hw
let telemetry = platform
.assets()
.bank_telemetry()
.into_iter()
@@ -3,6 +3,7 @@ use crate::CrashReport;
use crate::fs::{FsBackend, FsState, VirtualFS};
use prometeu_hal::cartridge::Cartridge;
use prometeu_hal::log::{LogLevel, LogSource};
use prometeu_hal::{FrameId, RenderWorkerBackend, RenderWorkerError, RenderWorkerFrameSink};
use std::collections::HashMap;
impl VirtualMachineRuntime {
@@ -25,9 +26,13 @@ impl VirtualMachineRuntime {
frame_scheduler: FrameScheduler::default(),
render_capabilities: RenderRuntimeCapabilities::default(),
render_manager: RenderManager::new(AppMode::Game),
render_worker_handoff: Arc::new(RenderWorkerHandoff::default()),
render_worker_ownership: RenderWorkerOwnership::default(),
render_worker_controller: None,
gfx2d_commands: Vec::new(),
gfxui_commands: Vec::new(),
logs_written_this_frame: HashMap::new(),
game_lifecycle_events_delivered: Vec::new(),
atomic_telemetry,
last_crash_report: None,
certifier: Certifier::new(cap_config.unwrap_or_default()),
@@ -124,9 +129,14 @@ impl VirtualMachineRuntime {
self.frame_scheduler = FrameScheduler::default();
self.render_capabilities = RenderRuntimeCapabilities::default();
self.render_manager = RenderManager::new(AppMode::Game);
let _ = self.stop_render_worker();
self.render_worker_handoff = Arc::new(RenderWorkerHandoff::default());
self.render_worker_ownership =
RenderWorkerOwnership::new(self.render_manager.active_ownership());
self.gfx2d_commands.clear();
self.gfxui_commands.clear();
self.logs_written_this_frame.clear();
self.game_lifecycle_events_delivered.clear();
self.last_crash_report = None;
@@ -147,6 +157,57 @@ impl VirtualMachineRuntime {
self.render_capabilities = capabilities;
}
pub fn start_render_worker<B, S>(&mut self, config: RenderWorkerConfig, backend: B, sink: S)
where
B: RenderWorkerBackend,
S: RenderWorkerFrameSink,
{
let _ = self.stop_render_worker();
self.render_worker_handoff = Arc::new(RenderWorkerHandoff::default());
self.render_worker_ownership.set(self.render_manager.active_ownership());
self.render_worker_controller = Some(RenderWorkerController::start(
config,
Arc::clone(&self.render_worker_handoff),
self.render_worker_ownership.clone(),
backend,
sink,
));
self.render_capabilities.game_render_worker = true;
}
pub fn stop_render_worker(&mut self) -> Result<(), RenderWorkerError> {
if let Some(mut controller) = self.render_worker_controller.take() {
controller.stop()
} else {
Ok(())
}
}
pub(crate) fn sync_render_worker_ownership(&self) {
self.render_worker_ownership.set(self.render_manager.active_ownership());
}
pub fn record_repeated_render_worker_frame(&self, frame_id: FrameId) {
if let Some(controller) = self.render_worker_controller.as_ref() {
controller.record_repeated_frame(frame_id);
}
}
pub fn deliver_game_lifecycle_events<I>(&mut self, events: I)
where
I: IntoIterator<Item = GameLifecycleEvent>,
{
self.game_lifecycle_events_delivered.extend(events);
}
pub fn delivered_game_lifecycle_events(&self) -> &[GameLifecycleEvent] {
&self.game_lifecycle_events_delivered
}
pub fn take_delivered_game_lifecycle_events(&mut self) -> Vec<GameLifecycleEvent> {
std::mem::take(&mut self.game_lifecycle_events_delivered)
}
pub fn initialize_vm(
&mut self,
log_service: &mut LogService,
@@ -180,3 +241,26 @@ impl VirtualMachineRuntime {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os::{GameLifecycleEvent, GameLifecycleEventKind};
use crate::task::TaskId;
#[test]
fn vm_runtime_records_and_drains_delivered_game_lifecycle_events() {
let mut runtime = VirtualMachineRuntime::new(None);
let pause = GameLifecycleEvent { task_id: TaskId(7), kind: GameLifecycleEventKind::Pause };
let resume = GameLifecycleEvent {
task_id: TaskId(7),
kind: GameLifecycleEventKind::ResumeForeground,
};
runtime.deliver_game_lifecycle_events([pause, resume]);
assert_eq!(runtime.delivered_game_lifecycle_events(), &[pause, resume]);
assert_eq!(runtime.take_delivered_game_lifecycle_events(), vec![pause, resume]);
assert!(runtime.delivered_game_lifecycle_events().is_empty());
}
}
@@ -4,11 +4,16 @@ mod dispatch;
mod frame_scheduler;
mod lifecycle;
pub mod render_manager;
mod render_worker;
pub mod render_worker_handoff;
#[cfg(test)]
pub(crate) mod render_worker_test_harness;
#[cfg(test)]
mod tests;
mod tick;
use crate::CrashReport;
use crate::os::GameLifecycleEvent;
pub use frame_scheduler::FrameScheduler;
use prometeu_bytecode::string_materialization_count;
use prometeu_hal::app_mode::AppMode;
@@ -17,6 +22,10 @@ use prometeu_hal::telemetry::{AtomicTelemetry, CertificationConfig, Certifier};
use prometeu_hal::{Gfx2dCommand, GfxUiCommand};
use prometeu_vm::VirtualMachine;
pub use render_manager::{RenderManager, RenderRuntimeCapabilities};
pub use render_worker::{
LatestRenderFrameStore, RenderWorkerConfig, RenderWorkerController, RenderWorkerOwnership,
};
pub use render_worker_handoff::{RenderWorkerHandoff, RenderWorkerHandoffWait};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::AtomicU32;
@@ -35,9 +44,13 @@ pub struct VirtualMachineRuntime {
pub frame_scheduler: FrameScheduler,
pub render_capabilities: RenderRuntimeCapabilities,
pub render_manager: RenderManager,
pub render_worker_handoff: Arc<RenderWorkerHandoff>,
pub render_worker_ownership: RenderWorkerOwnership,
pub render_worker_controller: Option<RenderWorkerController>,
pub gfx2d_commands: Vec<Gfx2dCommand>,
pub gfxui_commands: Vec<GfxUiCommand>,
pub logs_written_this_frame: HashMap<u32, u32>,
pub game_lifecycle_events_delivered: Vec<GameLifecycleEvent>,
pub atomic_telemetry: Arc<AtomicTelemetry>,
pub last_crash_report: Option<CrashReport>,
pub certifier: Certifier,
@@ -59,7 +59,7 @@ pub struct RenderRuntimeCapabilities {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderConsumerPath {
LocalSynchronous,
LocalWorkerPrototype,
RealWorker,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -95,7 +95,7 @@ impl RenderPolicy {
) -> RenderConsumerPath {
match (self.execution, capabilities.game_render_worker) {
(RenderExecutionPolicy::WorkerCapableWithLocalFallback, true) => {
RenderConsumerPath::LocalWorkerPrototype
RenderConsumerPath::RealWorker
}
_ => RenderConsumerPath::LocalSynchronous,
}
@@ -107,8 +107,10 @@ pub trait RenderSurface {
}
#[derive(Debug, Default)]
#[cfg(test)]
pub struct LocalRenderWorker;
#[cfg(test)]
impl LocalRenderWorker {
pub fn consume_latest<S: RenderSurface>(
&mut self,
@@ -329,6 +331,12 @@ impl RenderManager {
discarded
}
pub fn take_pending_for_worker(&mut self) -> Option<RenderSubmission> {
let submission = self.handoff.take_latest()?;
self.telemetry.record_consumed(submission.frame_id);
Some(submission)
}
pub fn request_shutdown(&mut self) -> Option<RenderSubmission> {
self.consumer_state = RenderConsumerState::Stopped;
self.discard_pending_submission()
@@ -624,7 +632,7 @@ mod tests {
);
assert_eq!(
policy.resolve_consumer_path(RenderRuntimeCapabilities { game_render_worker: true }),
RenderConsumerPath::LocalWorkerPrototype
RenderConsumerPath::RealWorker
);
}
@@ -0,0 +1,509 @@
use crate::services::vm_runtime::{RenderWorkerHandoff, RenderWorkerHandoffWait};
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::{
FrameId, OwnedRgba8888Frame, RenderOwnership, RenderWorkerBackend, RenderWorkerError,
RenderWorkerFrameSink, RenderWorkerTelemetry,
};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RenderWorkerConfig {
pub shutdown_timeout: Duration,
}
impl Default for RenderWorkerConfig {
fn default() -> Self {
Self { shutdown_timeout: Duration::from_millis(250) }
}
}
#[derive(Debug, Default)]
struct RenderWorkerState {
telemetry: RenderWorkerTelemetry,
last_error: Option<RenderWorkerError>,
}
#[derive(Clone, Debug, Default)]
pub struct LatestRenderFrameStore {
latest: Arc<Mutex<Option<OwnedRgba8888Frame>>>,
}
impl LatestRenderFrameStore {
pub fn publish_frame(&self, frame: OwnedRgba8888Frame) {
*self.latest.lock().unwrap() = Some(frame);
}
pub fn latest_frame(&self) -> Option<OwnedRgba8888Frame> {
self.latest.lock().unwrap().clone()
}
}
impl RenderWorkerFrameSink for LatestRenderFrameStore {
fn publish(&self, frame: OwnedRgba8888Frame) -> Result<(), RenderWorkerError> {
self.publish_frame(frame);
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct RenderWorkerOwnership {
active: Arc<Mutex<RenderOwnership>>,
}
impl Default for RenderWorkerOwnership {
fn default() -> Self {
Self::new(RenderOwnership::new(0, AppMode::Game, 0))
}
}
impl RenderWorkerOwnership {
pub fn new(active: RenderOwnership) -> Self {
Self { active: Arc::new(Mutex::new(active)) }
}
pub fn snapshot(&self) -> RenderOwnership {
*self.active.lock().unwrap()
}
pub fn set(&self, active: RenderOwnership) {
*self.active.lock().unwrap() = active;
}
}
#[derive(Debug)]
pub struct RenderWorkerController {
config: RenderWorkerConfig,
handoff: Arc<RenderWorkerHandoff>,
ownership: RenderWorkerOwnership,
state: Arc<Mutex<RenderWorkerState>>,
handle: Option<JoinHandle<()>>,
done_rx: Receiver<Result<(), RenderWorkerError>>,
}
impl RenderWorkerController {
pub fn start<B, S>(
config: RenderWorkerConfig,
handoff: Arc<RenderWorkerHandoff>,
ownership: RenderWorkerOwnership,
backend: B,
sink: S,
) -> Self
where
B: RenderWorkerBackend,
S: RenderWorkerFrameSink,
{
let state = Arc::new(Mutex::new(RenderWorkerState::default()));
let worker_handoff = Arc::clone(&handoff);
let worker_ownership = ownership.clone();
let worker_state = Arc::clone(&state);
let panic_state = Arc::clone(&state);
let (done_tx, done_rx) = mpsc::channel();
let handle = thread::spawn(move || {
let result = catch_unwind(AssertUnwindSafe(|| {
run_worker_loop(worker_handoff, worker_ownership, worker_state, backend, sink);
}))
.map_err(|_| RenderWorkerError::WorkerPanic);
if let Err(error) = result {
record_error(&panic_state, error, FrameId::ZERO);
}
let _ = done_tx.send(result);
});
Self { config, handoff, ownership, state, handle: Some(handle), done_rx }
}
pub fn stop(&mut self) -> Result<(), RenderWorkerError> {
self.handoff.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()
{
record_error(&self.state, RenderWorkerError::WorkerPanic, FrameId::ZERO);
return Err(RenderWorkerError::WorkerPanic);
}
result
}
Err(RecvTimeoutError::Timeout) => {
record_error(&self.state, RenderWorkerError::ShutdownTimeout, FrameId::ZERO);
Err(RenderWorkerError::ShutdownTimeout)
}
Err(RecvTimeoutError::Disconnected) => {
record_error(&self.state, RenderWorkerError::InternalFailure, FrameId::ZERO);
Err(RenderWorkerError::InternalFailure)
}
}
}
pub fn telemetry(&self) -> RenderWorkerTelemetry {
let mut telemetry = self.handoff.telemetry();
let state = self.state.lock().unwrap();
telemetry.published_frames = state.telemetry.published_frames;
telemetry.render_failures = state.telemetry.render_failures;
telemetry.publish_failures = state.telemetry.publish_failures;
telemetry.present_failures = state.telemetry.present_failures;
telemetry.stale_submission_discards = state.telemetry.stale_submission_discards;
telemetry.repeated_frames = state.telemetry.repeated_frames;
telemetry.shutdown_timeouts = state.telemetry.shutdown_timeouts;
telemetry.worker_panics = state.telemetry.worker_panics;
telemetry.last_presented_frame_id = state.telemetry.last_presented_frame_id;
telemetry.last_dropped_frame_id = state.telemetry.last_dropped_frame_id;
telemetry.last_published_frame_id = state.telemetry.last_published_frame_id;
telemetry.last_error_frame_id = state.telemetry.last_error_frame_id;
telemetry
}
pub fn last_error(&self) -> Option<RenderWorkerError> {
self.state.lock().unwrap().last_error
}
pub fn active_ownership(&self) -> RenderOwnership {
self.ownership.snapshot()
}
pub fn record_repeated_frame(&self, frame_id: FrameId) {
let mut state = self.state.lock().unwrap();
state.telemetry.record_repeated_frame(frame_id.get());
}
}
impl Drop for RenderWorkerController {
fn drop(&mut self) {
if self.handle.is_some() {
let _ = self.stop();
}
}
}
fn run_worker_loop<B, S>(
handoff: Arc<RenderWorkerHandoff>,
ownership: RenderWorkerOwnership,
state: Arc<Mutex<RenderWorkerState>>,
backend: B,
sink: S,
) where
B: RenderWorkerBackend,
S: RenderWorkerFrameSink,
{
loop {
let submission = match handoff.wait_take() {
RenderWorkerHandoffWait::Submission(submission) => submission,
RenderWorkerHandoffWait::Shutdown => return,
};
let frame_id = submission.frame_id;
let render_result = catch_unwind(AssertUnwindSafe(|| backend.render(&submission)))
.map_err(|_| RenderWorkerError::WorkerPanic);
let frame = match render_result {
Ok(Ok(frame)) => frame,
Ok(Err(error)) | Err(error) => {
record_error(&state, error, frame_id);
continue;
}
};
if frame.ownership != ownership.snapshot() {
record_stale_discard(&state, frame_id);
continue;
}
let publish_result = catch_unwind(AssertUnwindSafe(|| sink.publish(frame)))
.map_err(|_| RenderWorkerError::WorkerPanic);
match publish_result {
Ok(Ok(())) => record_published(&state, frame_id),
Ok(Err(error)) | Err(error) => record_error(&state, error, frame_id),
}
}
}
fn record_published(state: &Arc<Mutex<RenderWorkerState>>, frame_id: FrameId) {
let mut state = state.lock().unwrap();
state.telemetry.record_published(frame_id.get());
}
fn record_stale_discard(state: &Arc<Mutex<RenderWorkerState>>, frame_id: FrameId) {
state.lock().unwrap().telemetry.record_stale_submission_discarded(frame_id.get());
}
fn record_error(
state: &Arc<Mutex<RenderWorkerState>>,
error: RenderWorkerError,
frame_id: FrameId,
) {
let mut state = state.lock().unwrap();
state.last_error = Some(error);
state.telemetry.record_error(error, frame_id.get());
}
#[cfg(test)]
mod tests {
use super::*;
use crate::services::vm_runtime::VirtualMachineRuntime;
use crate::services::vm_runtime::render_worker_test_harness::{
FakeRenderBackend, RenderGate, game_submission,
};
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::{
FrameId, Game2DFramePacket, OwnedRgba8888Frame, RenderOwnership, RenderSubmission,
};
#[derive(Clone, Debug)]
struct SharedFakeBackend(Arc<FakeRenderBackend>);
impl RenderWorkerBackend for SharedFakeBackend {
fn render(
&self,
submission: &RenderSubmission,
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
self.0.render(submission)
}
}
impl RenderWorkerFrameSink for SharedFakeBackend {
fn publish(&self, frame: OwnedRgba8888Frame) -> Result<(), RenderWorkerError> {
self.0.publish(frame);
Ok(())
}
}
#[derive(Debug, Default)]
struct PanickingBackend;
impl RenderWorkerBackend for PanickingBackend {
fn render(
&self,
_submission: &RenderSubmission,
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
panic!("backend panic")
}
}
#[derive(Debug, Default)]
struct NoopSink;
impl RenderWorkerFrameSink for NoopSink {
fn publish(&self, _frame: OwnedRgba8888Frame) -> Result<(), RenderWorkerError> {
Ok(())
}
}
#[test]
fn latest_render_frame_store_is_sink_and_observable_publication_source() {
let store = LatestRenderFrameStore::default();
let first = OwnedRgba8888Frame::packed(
FrameId::new(1),
RenderOwnership::new(1, AppMode::Game, 1),
1,
1,
vec![0xFF0000FF],
)
.expect("first frame");
let second = OwnedRgba8888Frame::packed(
FrameId::new(2),
RenderOwnership::new(1, AppMode::Game, 1),
1,
1,
vec![0x00FF00FF],
)
.expect("second frame");
store.publish(first).expect("publish first");
assert_eq!(store.latest_frame().expect("first latest").frame_id, FrameId::new(1));
store.publish(second).expect("publish second");
let latest = store.latest_frame().expect("second latest");
assert_eq!(latest.frame_id, FrameId::new(2));
assert_eq!(latest.pixels, vec![0x00FF00FF]);
}
#[test]
fn render_worker_controller_starts_and_stops_waiting_worker() {
let handoff = Arc::new(RenderWorkerHandoff::default());
let backend = Arc::new(FakeRenderBackend::default());
let mut controller = RenderWorkerController::start(
RenderWorkerConfig::default(),
Arc::clone(&handoff),
RenderWorkerOwnership::default(),
SharedFakeBackend(Arc::clone(&backend)),
SharedFakeBackend(backend),
);
assert_eq!(controller.stop(), Ok(()));
assert_eq!(controller.last_error(), None);
}
#[test]
fn render_worker_controller_renders_and_publishes_submission() {
let handoff = Arc::new(RenderWorkerHandoff::default());
let backend = Arc::new(FakeRenderBackend::default());
let mut controller = RenderWorkerController::start(
RenderWorkerConfig::default(),
Arc::clone(&handoff),
RenderWorkerOwnership::new(RenderOwnership::new(1, AppMode::Game, 1)),
SharedFakeBackend(Arc::clone(&backend)),
SharedFakeBackend(Arc::clone(&backend)),
);
handoff.publish(game_submission(11, 1, 1));
assert_eq!(controller.stop(), Ok(()));
let frames = backend.published_frames();
assert_eq!(frames.len(), 1);
assert_eq!(frames[0].frame_id, FrameId::new(11));
assert_eq!(controller.telemetry().published_frames, 1);
}
#[test]
fn render_worker_controller_reports_shutdown_timeout() {
let handoff = Arc::new(RenderWorkerHandoff::default());
let gate = RenderGate::default();
let backend = Arc::new(FakeRenderBackend::with_gate(gate.clone()));
let mut controller = RenderWorkerController::start(
RenderWorkerConfig { shutdown_timeout: Duration::from_millis(1) },
Arc::clone(&handoff),
RenderWorkerOwnership::default(),
SharedFakeBackend(Arc::clone(&backend)),
SharedFakeBackend(Arc::clone(&backend)),
);
handoff.publish(game_submission(12, 1, 1));
gate.wait_for_entries(1);
assert_eq!(controller.stop(), Err(RenderWorkerError::ShutdownTimeout));
assert_eq!(controller.last_error(), Some(RenderWorkerError::ShutdownTimeout));
assert_eq!(controller.telemetry().shutdown_timeouts, 1);
gate.release_one();
controller.config.shutdown_timeout = Duration::from_millis(250);
assert_eq!(controller.stop(), Ok(()));
}
#[test]
fn render_worker_controller_captures_backend_panic_as_typed_failure() {
let handoff = Arc::new(RenderWorkerHandoff::default());
let mut controller = RenderWorkerController::start(
RenderWorkerConfig::default(),
Arc::clone(&handoff),
RenderWorkerOwnership::default(),
PanickingBackend,
NoopSink,
);
handoff.publish(game_submission(13, 1, 1));
assert_eq!(controller.stop(), Ok(()));
assert_eq!(controller.last_error(), Some(RenderWorkerError::WorkerPanic));
assert_eq!(controller.telemetry().worker_panics, 1);
assert_eq!(controller.telemetry().last_error_frame_id, 13);
}
#[test]
fn render_worker_controller_discards_stale_frame_before_publish() {
let handoff = Arc::new(RenderWorkerHandoff::default());
let gate = RenderGate::default();
let backend = Arc::new(FakeRenderBackend::with_gate(gate.clone()));
let ownership = RenderWorkerOwnership::new(RenderOwnership::new(1, AppMode::Game, 1));
let mut controller = RenderWorkerController::start(
RenderWorkerConfig::default(),
Arc::clone(&handoff),
ownership.clone(),
SharedFakeBackend(Arc::clone(&backend)),
SharedFakeBackend(Arc::clone(&backend)),
);
handoff.publish(game_submission(21, 1, 1));
gate.wait_for_entries(1);
ownership.set(RenderOwnership::new(2, AppMode::Game, 1));
gate.release_one();
assert_eq!(controller.stop(), Ok(()));
assert!(backend.published_frames().is_empty());
assert_eq!(controller.telemetry().stale_submission_discards, 1);
}
#[test]
fn render_worker_controller_repeats_latest_published_frame_without_rendering() {
let handoff = Arc::new(RenderWorkerHandoff::default());
let backend = Arc::new(FakeRenderBackend::default());
let store = LatestRenderFrameStore::default();
let mut controller = RenderWorkerController::start(
RenderWorkerConfig::default(),
Arc::clone(&handoff),
RenderWorkerOwnership::new(RenderOwnership::new(1, AppMode::Game, 1)),
SharedFakeBackend(Arc::clone(&backend)),
store.clone(),
);
handoff.publish(game_submission(22, 1, 1));
assert_eq!(controller.stop(), Ok(()));
let latest = store.latest_frame().expect("latest frame");
controller.record_repeated_frame(latest.frame_id);
let repeated = store.latest_frame().expect("repeated frame");
assert_eq!(latest, repeated);
assert!(backend.published_frames().is_empty());
assert_eq!(controller.telemetry().repeated_frames, 1);
}
#[test]
fn runtime_publishes_game_submissions_to_worker_without_waiting_for_render() {
fn publish_pending(runtime: &mut VirtualMachineRuntime) -> bool {
let Some(submission) = runtime.render_manager.take_pending_for_worker() else {
return false;
};
runtime.render_worker_handoff.publish(submission);
true
}
let gate = RenderGate::default();
let backend = Arc::new(FakeRenderBackend::with_gate(gate.clone()));
let mut runtime = VirtualMachineRuntime::new(None);
runtime.start_render_worker(
RenderWorkerConfig::default(),
SharedFakeBackend(Arc::clone(&backend)),
SharedFakeBackend(Arc::clone(&backend)),
);
runtime
.render_manager
.close_frame_with_packet(prometeu_hal::RenderSubmissionPacket::Game2D(
Game2DFramePacket::default(),
))
.expect("game packet should close");
assert!(publish_pending(&mut runtime));
gate.wait_for_entries(1);
runtime
.render_manager
.close_frame_with_packet(prometeu_hal::RenderSubmissionPacket::Game2D(
Game2DFramePacket::default(),
))
.expect("second game packet should close");
assert!(publish_pending(&mut runtime));
runtime
.render_manager
.close_frame_with_packet(prometeu_hal::RenderSubmissionPacket::Game2D(
Game2DFramePacket::default(),
))
.expect("third game packet should close");
assert!(publish_pending(&mut runtime));
assert_eq!(runtime.render_worker_handoff.telemetry().replaced_before_consume, 1);
gate.release_one();
gate.wait_for_entries(2);
gate.release_one();
assert_eq!(runtime.stop_render_worker(), Ok(()));
let frames = backend.published_frames();
assert_eq!(frames.len(), 2);
assert_eq!(frames[0].frame_id, FrameId::ZERO);
assert_eq!(frames[1].frame_id, FrameId::new(2));
}
}
@@ -0,0 +1,172 @@
use prometeu_hal::{RenderSubmission, RenderWorkerTelemetry};
use std::sync::{Condvar, Mutex};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RenderWorkerHandoffWait {
Submission(RenderSubmission),
Shutdown,
}
#[derive(Debug, Default)]
struct RenderWorkerHandoffState {
pending: Option<RenderSubmission>,
shutdown_requested: bool,
telemetry: RenderWorkerTelemetry,
}
#[derive(Debug, Default)]
pub struct RenderWorkerHandoff {
state: Mutex<RenderWorkerHandoffState>,
ready: Condvar,
}
impl RenderWorkerHandoff {
pub fn publish(&self, submission: RenderSubmission) {
let mut state = self.state.lock().unwrap();
if let Some(replaced) = state.pending.replace(submission) {
state.telemetry.record_replaced_before_consume(replaced.frame_id.get());
}
let frame_id = state.pending.as_ref().expect("submission was just stored").frame_id;
state.telemetry.record_produced(frame_id.get());
self.ready.notify_one();
}
pub fn take_latest(&self) -> Option<RenderSubmission> {
let mut state = self.state.lock().unwrap();
let submission = state.pending.take()?;
state.telemetry.record_consumed(submission.frame_id.get());
Some(submission)
}
pub fn wait_take(&self) -> RenderWorkerHandoffWait {
self.wait_take_with_hook(|| {})
}
pub fn request_shutdown(&self) {
let mut state = self.state.lock().unwrap();
state.shutdown_requested = true;
self.ready.notify_all();
}
pub fn telemetry(&self) -> RenderWorkerTelemetry {
self.state.lock().unwrap().telemetry
}
fn wait_take_with_hook(&self, mut before_wait: impl FnMut()) -> RenderWorkerHandoffWait {
let mut state = self.state.lock().unwrap();
loop {
if let Some(submission) = state.pending.take() {
state.telemetry.record_consumed(submission.frame_id.get());
return RenderWorkerHandoffWait::Submission(submission);
}
if state.shutdown_requested {
return RenderWorkerHandoffWait::Shutdown;
}
before_wait();
state = self.ready.wait(state).unwrap();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use prometeu_hal::{FrameId, Game2DFramePacket};
use std::sync::Arc;
use std::sync::mpsc;
use std::thread;
fn submission(frame_id: u64) -> RenderSubmission {
RenderSubmission::game2d(FrameId::new(frame_id), Game2DFramePacket::default())
}
#[test]
fn render_worker_handoff_takes_owned_submission() {
let handoff = RenderWorkerHandoff::default();
assert!(handoff.take_latest().is_none());
handoff.publish(submission(7));
let taken = handoff.take_latest().expect("pending submission");
assert_eq!(taken.frame_id, FrameId::new(7));
assert!(handoff.take_latest().is_none());
assert_eq!(handoff.telemetry().produced_submissions, 1);
assert_eq!(handoff.telemetry().consumed_submissions, 1);
}
#[test]
fn render_worker_handoff_wait_take_returns_pending_without_blocking() {
let handoff = RenderWorkerHandoff::default();
handoff.publish(submission(8));
assert_eq!(handoff.wait_take(), RenderWorkerHandoffWait::Submission(submission(8)));
assert!(handoff.take_latest().is_none());
}
#[test]
fn render_worker_handoff_is_latest_wins_and_counts_replacements() {
let handoff = RenderWorkerHandoff::default();
handoff.publish(submission(1));
handoff.publish(submission(2));
handoff.publish(submission(3));
let taken = handoff.take_latest().expect("latest submission");
let telemetry = handoff.telemetry();
assert_eq!(taken.frame_id, FrameId::new(3));
assert_eq!(telemetry.produced_submissions, 3);
assert_eq!(telemetry.replaced_before_consume, 2);
assert_eq!(telemetry.consumed_submissions, 1);
assert_eq!(telemetry.last_produced_frame_id, 3);
assert_eq!(telemetry.last_dropped_frame_id, 2);
}
#[test]
fn render_worker_handoff_waits_for_publish_without_timing_delay() {
let handoff = Arc::new(RenderWorkerHandoff::default());
let consumer_handoff = Arc::clone(&handoff);
let (waiting_tx, waiting_rx) = mpsc::channel();
let consumer = thread::spawn(move || {
let mut waiting_tx = Some(waiting_tx);
consumer_handoff.wait_take_with_hook(|| {
if let Some(tx) = waiting_tx.take() {
tx.send(()).unwrap();
}
})
});
waiting_rx.recv().expect("consumer reached condvar wait");
handoff.publish(submission(42));
assert_eq!(
consumer.join().expect("consumer thread should finish"),
RenderWorkerHandoffWait::Submission(submission(42))
);
assert_eq!(handoff.telemetry().consumed_submissions, 1);
}
#[test]
fn render_worker_handoff_wait_returns_shutdown_signal() {
let handoff = Arc::new(RenderWorkerHandoff::default());
let consumer_handoff = Arc::clone(&handoff);
let (waiting_tx, waiting_rx) = mpsc::channel();
let consumer = thread::spawn(move || {
let mut waiting_tx = Some(waiting_tx);
consumer_handoff.wait_take_with_hook(|| {
if let Some(tx) = waiting_tx.take() {
tx.send(()).unwrap();
}
})
});
waiting_rx.recv().expect("consumer reached condvar wait");
handoff.request_shutdown();
assert_eq!(
consumer.join().expect("consumer thread should finish"),
RenderWorkerHandoffWait::Shutdown
);
}
}
@@ -0,0 +1,173 @@
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::{
FrameId, Game2DFramePacket, OwnedRgba8888Frame, RenderOwnership, RenderSubmission,
RenderWorkerError, ShellUiFramePacket,
};
use std::sync::{Arc, Condvar, Mutex};
#[derive(Debug, Default)]
struct RenderGateState {
entered: u64,
released: u64,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct RenderGate {
state: Arc<(Mutex<RenderGateState>, Condvar)>,
}
impl RenderGate {
pub(crate) fn block_until_released(&self) {
let (lock, condvar) = &*self.state;
let mut state = lock.lock().unwrap();
state.entered = state.entered.wrapping_add(1);
let entry = state.entered;
condvar.notify_all();
while state.released < entry {
state = condvar.wait(state).unwrap();
}
}
pub(crate) fn wait_for_entries(&self, count: u64) {
let (lock, condvar) = &*self.state;
let mut state = lock.lock().unwrap();
while state.entered < count {
state = condvar.wait(state).unwrap();
}
}
pub(crate) fn release_one(&self) {
let (lock, condvar) = &*self.state;
let mut state = lock.lock().unwrap();
state.released = state.released.wrapping_add(1);
condvar.notify_all();
}
}
#[derive(Debug, Default)]
pub(crate) struct FakeRenderBackend {
gate: Option<RenderGate>,
next_error: Mutex<Option<RenderWorkerError>>,
published_frames: Mutex<Vec<OwnedRgba8888Frame>>,
}
impl FakeRenderBackend {
pub(crate) fn with_gate(gate: RenderGate) -> Self {
Self { gate: Some(gate), ..Default::default() }
}
pub(crate) fn fail_next(&self, error: RenderWorkerError) {
*self.next_error.lock().unwrap() = Some(error);
}
pub(crate) fn render(
&self,
submission: &RenderSubmission,
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
if let Some(gate) = &self.gate {
gate.block_until_released();
}
if let Some(error) = self.next_error.lock().unwrap().take() {
return Err(error);
}
OwnedRgba8888Frame::packed(
submission.frame_id,
submission.ownership,
1,
1,
vec![0xff00_0000 | submission.frame_id.get() as u32],
)
.map_err(|_| RenderWorkerError::InternalFailure)
}
pub(crate) fn publish(&self, frame: OwnedRgba8888Frame) {
self.published_frames.lock().unwrap().push(frame);
}
pub(crate) fn published_frames(&self) -> Vec<OwnedRgba8888Frame> {
self.published_frames.lock().unwrap().clone()
}
}
pub(crate) fn game_submission(frame_id: u64, epoch: u64, app_id: u32) -> RenderSubmission {
RenderSubmission::game2d(FrameId::new(frame_id), Game2DFramePacket::default())
.with_ownership(RenderOwnership::new(epoch, AppMode::Game, app_id))
}
pub(crate) fn shell_submission(frame_id: u64, epoch: u64, app_id: u32) -> RenderSubmission {
RenderSubmission::shell_ui(FrameId::new(frame_id), ShellUiFramePacket::new(Vec::new()))
.with_ownership(RenderOwnership::new(epoch, AppMode::Shell, app_id))
}
pub(crate) fn owned_frame(frame_id: FrameId, pixel: u32) -> OwnedRgba8888Frame {
OwnedRgba8888Frame::packed(
frame_id,
RenderOwnership::new(0, AppMode::Game, 0),
1,
1,
vec![pixel],
)
.expect("test frame should be valid")
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc;
use std::thread;
#[test]
fn render_worker_harness_blocks_and_releases_render_without_timing_delay() {
let gate = RenderGate::default();
let backend = Arc::new(FakeRenderBackend::with_gate(gate.clone()));
let render_backend = Arc::clone(&backend);
let submission = game_submission(4, 1, 9);
let (done_tx, done_rx) = mpsc::channel();
let worker = thread::spawn(move || {
let frame = render_backend.render(&submission).expect("render should succeed");
done_tx.send(frame.frame_id).unwrap();
});
gate.wait_for_entries(1);
assert!(done_rx.try_recv().is_err());
gate.release_one();
assert_eq!(done_rx.recv().expect("render should finish"), FrameId::new(4));
worker.join().expect("worker thread should finish");
}
#[test]
fn render_worker_harness_records_published_owned_frames() {
let backend = FakeRenderBackend::default();
let frame = owned_frame(FrameId::new(8), 0xff00_ff00);
backend.publish(frame.clone());
assert_eq!(backend.published_frames(), vec![frame]);
}
#[test]
fn render_worker_harness_injects_backend_errors() {
let backend = FakeRenderBackend::default();
backend.fail_next(RenderWorkerError::RenderFailed);
let error = backend.render(&game_submission(5, 1, 1)).expect_err("render should fail");
assert_eq!(error, RenderWorkerError::RenderFailed);
assert!(backend.render(&game_submission(6, 1, 1)).is_ok());
}
#[test]
fn render_worker_harness_builds_game_and_shell_submissions() {
let game = game_submission(1, 2, 3);
let shell = shell_submission(4, 5, 6);
assert_eq!(game.frame_id, FrameId::new(1));
assert_eq!(game.ownership, RenderOwnership::new(2, AppMode::Game, 3));
assert_eq!(shell.frame_id, FrameId::new(4));
assert_eq!(shell.ownership, RenderOwnership::new(5, AppMode::Shell, 6));
}
}
@@ -5,23 +5,23 @@ use prometeu_bytecode::TRAP_TYPE;
use prometeu_bytecode::Value;
use prometeu_bytecode::assembler::assemble;
use prometeu_bytecode::model::{BytecodeModule, ConstantPoolEntry, FunctionMeta, SyscallDecl};
use prometeu_drivers::hardware::Hardware;
use prometeu_drivers::TestPlatform;
use prometeu_drivers::{GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolInstaller};
use prometeu_hal::AudioOpStatus;
use prometeu_hal::ComposerOpStatus;
use prometeu_hal::InputSignals;
use prometeu_hal::asset::{
AssetCodec, AssetEntry, AssetLoadError, AssetOpStatus, BankType, LoadStatus,
};
use prometeu_hal::cartridge::{AssetsPayloadSource, Cartridge};
use prometeu_hal::color::Color;
use prometeu_hal::glyph::Glyph;
use prometeu_hal::glyph_bank::{GLYPH_BANK_PALETTE_COUNT_V1, GlyphBank, TileSize};
use prometeu_hal::glyph_bank::{GLYPH_BANK_MAX_PALETTE_COUNT_V1, GlyphBank, TileSize};
use prometeu_hal::scene_bank::SceneBank;
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
use prometeu_hal::syscalls::caps;
use prometeu_hal::tile::Tile;
use prometeu_hal::tilemap::TileMap;
use prometeu_hal::{InputSignals, RuntimePlatform};
use prometeu_vm::VmInitError;
use std::collections::HashMap;
use std::sync::Arc;
@@ -113,11 +113,12 @@ fn serialized_single_function_module_with_consts(
}
fn test_glyph_payload_size(width: usize, height: usize) -> usize {
(width * height).div_ceil(2) + (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
(width * height).div_ceil(2)
+ (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
}
fn test_glyph_decoded_size(width: usize, height: usize) -> usize {
width * height + (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
width * height + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
}
fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
@@ -133,23 +134,23 @@ fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
}),
}
}
fn test_glyph_asset_data() -> Vec<u8> {
let mut data =
vec![0x11u8; test_glyph_payload_size(16, 16) - (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * 4)];
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_COUNT_V1 * 16 * 4]);
vec![0x11u8; test_glyph_payload_size(16, 16) - (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * 4)];
data.extend_from_slice(&[0u8; GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * 4]);
data
}
fn runtime_test_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
let size = tile_size as usize;
let mut bank = GlyphBank::new(tile_size, size, size);
bank.palettes[palette_id as usize][1] = color;
let mut bank = GlyphBank::with_palette_count(tile_size, size, size, palette_id as usize + 1);
bank.palette_mut(palette_id).unwrap()[1] = color;
for pixel in &mut bank.pixel_indices {
*pixel = 1;
}
@@ -247,7 +248,7 @@ fn tick_returns_error_when_vm_ends_slice_with_trap() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_BOOL 1\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -274,7 +275,7 @@ fn tick_returns_error_when_vm_ends_slice_with_trap() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
)
.expect("trap must surface as runtime error");
@@ -298,7 +299,7 @@ fn tick_system_profile_rejects_gfx_game_surface() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -324,7 +325,7 @@ fn tick_system_profile_rejects_gfx_game_surface() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
)
.expect("system gfx call must trap");
@@ -347,7 +348,7 @@ fn tick_system_profile_rejects_composer_game_surface() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -373,7 +374,7 @@ fn tick_system_profile_rejects_composer_game_surface() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
)
.expect("system composer call must trap");
@@ -398,7 +399,7 @@ fn tick_game_profile_rejects_gfxui_shell_surface() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -424,7 +425,7 @@ fn tick_game_profile_rejects_gfxui_shell_surface() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
)
.expect("game gfxui call must trap");
@@ -447,7 +448,7 @@ fn tick_shell_profile_closes_gfxui_commands_into_shell_packet() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 287454020\nHOSTCALL 0\nFRAME_SYNC\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -472,7 +473,7 @@ fn tick_shell_profile_closes_gfxui_commands_into_shell_packet() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none());
@@ -483,11 +484,110 @@ fn tick_shell_profile_closes_gfxui_commands_into_shell_packet() {
};
assert_eq!(packet.commands.len(), 1);
assert!(matches!(packet.commands[0], prometeu_hal::GfxUiCommand::Clear { .. }));
assert_eq!(hardware.gfx.front_buffer()[0], Color::from_raw(0x11223344).raw());
assert_eq!(platform.local_hardware().gfx.front_buffer()[0], Color::from_raw(0x11223344).raw());
assert_eq!(runtime.frame_scheduler.completed_game_frames(), 0);
assert_eq!(runtime.frame_scheduler.active_game_frame_id(), None);
}
#[test]
fn tick_gfx2d_clear_buffers_without_immediate_pixel_mutation_before_frame_close() {
let mut runtime = VirtualMachineRuntime::new(None);
let mut log_service = LogService::new(4096);
let mut fs = VirtualFS::new();
let mut fs_state = FsState::Unmounted;
let mut memcard = MemcardService::new();
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 287454020\nHOSTCALL 0\nJMP 0").expect("assemble");
let program = serialized_single_function_module(
code,
vec![SyscallDecl {
module: "gfx2d".into(),
name: "clear".into(),
version: 1,
arg_slots: 1,
ret_slots: 0,
}],
);
let cartridge = cartridge_with_program(program, caps::GFX);
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let report = runtime.tick(
&mut log_service,
&mut fs,
&mut fs_state,
&mut memcard,
&mut open_files,
&mut next_handle,
&mut vm,
&signals,
&mut platform,
);
assert!(report.is_none());
assert!(runtime.render_manager.latest_complete_submission().is_none());
assert!(matches!(
runtime.gfx2d_commands.first(),
Some(prometeu_hal::Gfx2dCommand::Clear { color })
if *color == Color::from_raw(0x11223344)
));
assert_ne!(platform.local_hardware().gfx.front_buffer()[0], Color::from_raw(0x11223344).raw());
}
#[test]
fn tick_gfx2d_draw_text_buffers_without_immediate_pixel_mutation_before_frame_close() {
let mut runtime = VirtualMachineRuntime::new(None);
let mut log_service = LogService::new(4096);
let mut fs = VirtualFS::new();
let mut fs_state = FsState::Unmounted;
let mut memcard = MemcardService::new();
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code =
assemble("PUSH_I32 0\nPUSH_I32 0\nPUSH_CONST 0\nPUSH_I32 287454020\nHOSTCALL 0\nJMP 0")
.expect("assemble");
let program = serialized_single_function_module_with_consts(
code,
vec![ConstantPoolEntry::String("I".into())],
vec![SyscallDecl {
module: "gfx2d".into(),
name: "draw_text".into(),
version: 1,
arg_slots: 4,
ret_slots: 0,
}],
);
let cartridge = cartridge_with_program(program, caps::GFX);
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let report = runtime.tick(
&mut log_service,
&mut fs,
&mut fs_state,
&mut memcard,
&mut open_files,
&mut next_handle,
&mut vm,
&signals,
&mut platform,
);
assert!(report.is_none());
assert!(runtime.render_manager.latest_complete_submission().is_none());
assert!(matches!(
runtime.gfx2d_commands.first(),
Some(prometeu_hal::Gfx2dCommand::DrawText { x: 0, y: 0, text, color })
if text == "I" && *color == Color::from_raw(0x11223344)
));
assert_ne!(platform.local_hardware().gfx.front_buffer()[0], Color::from_raw(0x11223344).raw());
}
#[test]
fn tick_system_profile_rejects_bank_game_surface() {
let mut runtime = VirtualMachineRuntime::new(None);
@@ -498,7 +598,7 @@ fn tick_system_profile_rejects_bank_game_surface() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -524,7 +624,7 @@ fn tick_system_profile_rejects_bank_game_surface() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
)
.expect("system bank call must trap");
@@ -547,7 +647,7 @@ fn tick_system_profile_can_use_shared_log_transport() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 2\nPUSH_CONST 0\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module_with_consts(
@@ -573,7 +673,7 @@ fn tick_system_profile_can_use_shared_log_transport() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "system log transport must remain internally shared");
@@ -590,7 +690,7 @@ fn tick_returns_panic_report_distinct_from_trap() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::new(assemble("HOSTCALL 0\nHALT").expect("assemble"), vec![]);
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let report = runtime
@@ -603,7 +703,7 @@ fn tick_returns_panic_report_distinct_from_trap() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
)
.expect("panic must surface as runtime error");
@@ -635,12 +735,12 @@ fn tick_renders_bound_eight_pixel_scene_through_frame_composer_path() {
let banks = Arc::new(MemoryBanks::new());
banks.install_glyph_bank(0, Arc::new(runtime_test_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
banks.install_scene_bank(0, Arc::new(runtime_test_scene(0, 2, TileSize::Size8)));
let mut hardware = Hardware::new_with_memory_banks(Arc::clone(&banks));
let glyph_slot_index = hardware.assets.glyph_asset_slot_index();
let mut platform = TestPlatform::new_with_memory_banks(Arc::clone(&banks));
let glyph_slot_index = platform.local_hardware().assets.glyph_asset_slot_index();
let mut slots = [None; 16];
slots[0] = Some(0);
glyph_slot_index.rebuild_from_slots(&slots);
assert!(hardware.frame_composer.bind_scene(0));
assert!(platform.local_hardware_mut().frame_composer.bind_scene(0));
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let report = runtime.tick(
@@ -652,11 +752,11 @@ fn tick_renders_bound_eight_pixel_scene_through_frame_composer_path() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "frame render path must not crash");
assert_eq!(hardware.gfx.front_buffer()[0], Color::BLUE.raw());
assert_eq!(platform.local_hardware().gfx.front_buffer()[0], Color::BLUE.raw());
}
#[test]
@@ -708,8 +808,8 @@ fn tick_renders_scene_through_public_composer_syscalls() {
let banks = Arc::new(MemoryBanks::new());
banks.install_glyph_bank(0, Arc::new(runtime_test_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
banks.install_scene_bank(0, Arc::new(runtime_test_scene(0, 2, TileSize::Size8)));
let mut hardware = Hardware::new_with_memory_banks(Arc::clone(&banks));
let glyph_slot_index = hardware.assets.glyph_asset_slot_index();
let mut platform = TestPlatform::new_with_memory_banks(Arc::clone(&banks));
let glyph_slot_index = platform.local_hardware().assets.glyph_asset_slot_index();
let mut slots = [None; 16];
slots[0] = Some(0);
glyph_slot_index.rebuild_from_slots(&slots);
@@ -724,12 +824,12 @@ fn tick_renders_scene_through_public_composer_syscalls() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "public composer path must not crash");
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::Ok as i64)]);
assert_eq!(hardware.gfx.front_buffer()[0], Color::BLUE.raw());
assert_eq!(platform.local_hardware().gfx.front_buffer()[0], Color::BLUE.raw());
}
#[test]
@@ -759,7 +859,7 @@ fn tick_draw_text_survives_no_scene_frame_path() {
}],
);
let cartridge = cartridge_with_program(program, caps::GFX);
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let report = runtime.tick(
@@ -771,7 +871,7 @@ fn tick_draw_text_survives_no_scene_frame_path() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "no-scene overlay text must not crash");
@@ -782,7 +882,7 @@ fn tick_draw_text_survives_no_scene_frame_path() {
};
assert_eq!(packet.gfx2d.len(), 1);
assert!(matches!(packet.gfx2d[0], prometeu_hal::Gfx2dCommand::DrawText { .. }));
assert_eq!(hardware.gfx.front_buffer()[0], Color::from_raw(0x11223344).raw());
assert_eq!(platform.local_hardware().gfx.front_buffer()[0], Color::from_raw(0x11223344).raw());
}
#[test]
@@ -808,7 +908,7 @@ fn tick_game_submissions_are_immutable_and_latest_complete_wins() {
}],
);
let cartridge = cartridge_with_program(program, caps::GFX);
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let first_report = runtime.tick(
@@ -820,7 +920,7 @@ fn tick_game_submissions_are_immutable_and_latest_complete_wins() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(first_report.is_none());
let first_submission =
@@ -834,7 +934,7 @@ fn tick_game_submissions_are_immutable_and_latest_complete_wins() {
first_packet.gfx2d[0],
prometeu_hal::Gfx2dCommand::Clear { color } if color == Color::from_raw(0x11223344)
));
assert_eq!(hardware.gfx.front_buffer()[0], Color::from_raw(0x11223344).raw());
assert_eq!(platform.local_hardware().gfx.front_buffer()[0], Color::from_raw(0x11223344).raw());
assert_eq!(runtime.frame_scheduler.completed_game_frames(), 1);
let second_packet = prometeu_hal::Game2DFramePacket::new(
@@ -858,8 +958,11 @@ fn tick_game_submissions_are_immutable_and_latest_complete_wins() {
first_packet.gfx2d[0],
prometeu_hal::Gfx2dCommand::Clear { color } if color == Color::from_raw(0x11223344)
));
prometeu_hal::HardwareBridge::publish_render_submission(&mut hardware, latest);
assert_eq!(hardware.gfx.front_buffer()[0], Color::from_raw(0x55667788).raw());
platform
.render_submission_sink()
.submit_render_submission(latest.clone())
.expect("local sink should publish latest submission");
assert_eq!(platform.local_hardware().gfx.front_buffer()[0], Color::from_raw(0x55667788).raw());
}
#[test]
@@ -961,7 +1064,7 @@ fn tick_numeric_happy_path_records_zero_internal_allocations() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code =
assemble("PUSH_I32 1\nPUSH_I32 2\nADD\nPOP_N 1\nFRAME_SYNC\nHALT").expect("assemble");
@@ -978,7 +1081,7 @@ fn tick_numeric_happy_path_records_zero_internal_allocations() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none());
@@ -997,7 +1100,7 @@ fn tick_already_materialized_string_path_records_zero_internal_allocations() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_CONST 0\nSET_GLOBAL 0\nGET_GLOBAL 0\nPOP_N 1\nFRAME_SYNC\nHALT")
.expect("assemble");
@@ -1018,7 +1121,7 @@ fn tick_already_materialized_string_path_records_zero_internal_allocations() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none());
@@ -1093,7 +1196,7 @@ fn tick_composer_bind_scene_operational_error_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 99\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -1118,7 +1221,7 @@ fn tick_composer_bind_scene_operational_error_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "operational error must not crash");
assert!(vm.is_halted());
@@ -1138,7 +1241,7 @@ fn tick_composer_emit_sprite_operational_error_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 0\nHOSTCALL 0\nHALT",
@@ -1166,13 +1269,60 @@ fn tick_composer_emit_sprite_operational_error_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "operational error must not crash");
assert!(vm.is_halted());
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::BankInvalid as i64)]);
}
#[test]
fn tick_composer_emit_sprite_invalid_palette_returns_bank_invalid() {
let mut runtime = VirtualMachineRuntime::new(None);
let mut log_service = LogService::new(4096);
let mut fs = VirtualFS::new();
let mut fs_state = FsState::Unmounted;
let mut memcard = MemcardService::new();
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let banks = Arc::new(MemoryBanks::new());
banks.install_glyph_bank(0, Arc::new(runtime_test_glyph_bank(TileSize::Size8, 0, Color::BLUE)));
let mut platform = TestPlatform::new_with_memory_banks(banks);
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 0\nPUSH_I32 1\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 0\nHOSTCALL 0\nHALT",
)
.expect("assemble");
let program = serialized_single_function_module(
code,
vec![SyscallDecl {
module: "composer".into(),
name: "emit_sprite".into(),
version: 1,
arg_slots: 9,
ret_slots: 1,
}],
);
let cartridge = cartridge_with_program(program, caps::GFX);
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let report = runtime.tick(
&mut log_service,
&mut fs,
&mut fs_state,
&mut memcard,
&mut open_files,
&mut next_handle,
&mut vm,
&signals,
&mut platform,
);
assert!(report.is_none(), "invalid palette must not crash VM execution");
assert!(vm.is_halted());
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::BankInvalid as i64)]);
}
#[test]
fn tick_composer_emit_sprite_invalid_layer_returns_status_not_crash() {
let mut runtime = VirtualMachineRuntime::new(None);
@@ -1183,7 +1333,7 @@ fn tick_composer_emit_sprite_invalid_layer_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 4\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 0\nHOSTCALL 0\nHALT",
@@ -1211,7 +1361,7 @@ fn tick_composer_emit_sprite_invalid_layer_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "invalid layer must not crash");
assert!(vm.is_halted());
@@ -1228,7 +1378,7 @@ fn tick_composer_emit_sprite_invalid_range_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 0\nPUSH_I32 64\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 0\nHOSTCALL 0\nHALT",
@@ -1247,7 +1397,7 @@ fn tick_composer_emit_sprite_invalid_range_returns_status_not_crash() {
let cartridge = cartridge_with_program(program, caps::GFX);
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
platform.local_hardware().assets.initialize_for_cartridge(
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![prometeu_hal::asset::PreloadEntry { asset_id: 7, slot: 0 }],
AssetsPayloadSource::from_bytes(asset_data),
@@ -1263,7 +1413,7 @@ fn tick_composer_emit_sprite_invalid_range_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "invalid composer parameter range must not crash");
assert!(vm.is_halted());
@@ -1283,7 +1433,7 @@ fn tick_audio_play_sample_operational_error_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 -1\nPUSH_I32 0\nPUSH_I32 255\nPUSH_I32 128\nPUSH_I32 1\nHOSTCALL 0\nHALT",
@@ -1311,7 +1461,7 @@ fn tick_audio_play_sample_operational_error_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "operational error must not crash");
assert!(vm.is_halted());
@@ -1328,7 +1478,7 @@ fn tick_audio_play_voice_invalid_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 0\nPUSH_I32 0\nPUSH_I32 16\nPUSH_I32 255\nPUSH_I32 128\nPUSH_I32 1\nPUSH_I32 0\nHOSTCALL 0\nHALT",
@@ -1356,7 +1506,7 @@ fn tick_audio_play_voice_invalid_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "invalid voice must not crash");
assert!(vm.is_halted());
@@ -1373,7 +1523,7 @@ fn tick_audio_play_missing_asset_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 255\nPUSH_I32 128\nPUSH_I32 1\nPUSH_I32 0\nHOSTCALL 0\nHALT",
@@ -1401,7 +1551,7 @@ fn tick_audio_play_missing_asset_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "missing audio asset must not crash");
assert!(vm.is_halted());
@@ -1418,7 +1568,7 @@ fn tick_audio_play_type_mismatch_surfaces_trap_not_panic() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_BOOL 1\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 255\nPUSH_I32 128\nPUSH_I32 1\nPUSH_I32 0\nHOSTCALL 0\nHALT",
@@ -1447,7 +1597,7 @@ fn tick_audio_play_type_mismatch_surfaces_trap_not_panic() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
)
.expect("type mismatch must surface as trap");
match report {
@@ -1470,7 +1620,7 @@ fn tick_composer_emit_sprite_type_mismatch_surfaces_trap_not_panic() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_BOOL 1\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 0\nHOSTCALL 0\nHALT",
@@ -1499,7 +1649,7 @@ fn tick_composer_emit_sprite_type_mismatch_surfaces_trap_not_panic() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
)
.expect("type mismatch must surface as trap");
match report {
@@ -10,7 +10,7 @@ fn tick_asset_commit_operational_error_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 999\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -35,7 +35,7 @@ fn tick_asset_commit_operational_error_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "operational error must not crash");
assert!(vm.is_halted());
@@ -52,7 +52,7 @@ fn tick_asset_load_missing_asset_returns_status_and_zero_handle() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 999\nPUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -77,7 +77,7 @@ fn tick_asset_load_missing_asset_returns_status_and_zero_handle() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "missing asset must not crash");
assert!(vm.is_halted());
@@ -97,10 +97,10 @@ fn tick_asset_load_invalid_slot_returns_status_and_zero_handle() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
platform.local_hardware().assets.initialize_for_cartridge(
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![],
AssetsPayloadSource::from_bytes(asset_data),
@@ -128,7 +128,7 @@ fn tick_asset_load_invalid_slot_returns_status_and_zero_handle() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "invalid slot must not crash");
assert!(vm.is_halted());
@@ -148,7 +148,7 @@ fn tick_asset_status_unknown_handle_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 999\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -173,13 +173,109 @@ fn tick_asset_status_unknown_handle_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "unknown asset handle must not crash");
assert!(vm.is_halted());
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(LoadStatus::UnknownHandle as i64)]);
}
#[test]
fn tick_asset_target_status_empty_slot_returns_status_first_payload() {
let mut runtime = VirtualMachineRuntime::new(None);
let mut log_service = LogService::new(4096);
let mut fs = VirtualFS::new();
let mut fs_state = FsState::Unmounted;
let mut memcard = MemcardService::new();
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 0\nPUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
code,
vec![SyscallDecl {
module: "asset".into(),
name: "target_status".into(),
version: 1,
arg_slots: 2,
ret_slots: 6,
}],
);
let cartridge = cartridge_with_program(program, caps::ASSET);
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let report = runtime.tick(
&mut log_service,
&mut fs,
&mut fs_state,
&mut memcard,
&mut open_files,
&mut next_handle,
&mut vm,
&signals,
&mut platform,
);
assert!(report.is_none(), "target_status must not crash for empty slots");
assert!(vm.is_halted());
assert_eq!(
vm.operand_stack_top(6),
vec![
Value::Int64(0),
Value::Int64(0),
Value::Int64(LoadStatus::EMPTY as i64),
Value::Int64(1),
Value::Int64(0),
Value::Int64(AssetOpStatus::Ok as i64),
]
);
}
#[test]
fn tick_asset_backlog_promote_unknown_handle_returns_status_not_crash() {
let mut runtime = VirtualMachineRuntime::new(None);
let mut log_service = LogService::new(4096);
let mut fs = VirtualFS::new();
let mut fs_state = FsState::Unmounted;
let mut memcard = MemcardService::new();
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 999\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
code,
vec![SyscallDecl {
module: "asset".into(),
name: "backlog_promote".into(),
version: 1,
arg_slots: 1,
ret_slots: 1,
}],
);
let cartridge = cartridge_with_program(program, caps::ASSET);
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let report = runtime.tick(
&mut log_service,
&mut fs,
&mut fs_state,
&mut memcard,
&mut open_files,
&mut next_handle,
&mut vm,
&signals,
&mut platform,
);
assert!(report.is_none(), "unknown backlog handle must not crash");
assert!(vm.is_halted());
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(AssetOpStatus::UnknownHandle as i64)]);
}
#[test]
fn tick_bank_info_returns_slot_summary_not_json() {
let mut runtime = VirtualMachineRuntime::new(None);
@@ -190,10 +286,10 @@ fn tick_bank_info_returns_slot_summary_not_json() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
platform.local_hardware().assets.initialize_for_cartridge(
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![prometeu_hal::asset::PreloadEntry { asset_id: 7, slot: 0 }],
AssetsPayloadSource::from_bytes(asset_data),
@@ -221,7 +317,7 @@ fn tick_bank_info_returns_slot_summary_not_json() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "bank summary must not crash");
assert!(vm.is_halted());
@@ -261,7 +357,7 @@ fn tick_asset_commit_invalid_transition_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 1\nHOSTCALL 0\nPOP_N 1\nPUSH_I32 1\nHOSTCALL 1\nHALT")
.expect("assemble");
@@ -287,12 +383,13 @@ fn tick_asset_commit_invalid_transition_returns_status_not_crash() {
let cartridge = cartridge_with_program(program, caps::ASSET);
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
platform.local_hardware().assets.initialize_for_cartridge(
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![],
AssetsPayloadSource::from_bytes(asset_data),
);
let handle = hardware.assets.load(7, 0).expect("asset handle must be allocated");
let handle =
platform.local_hardware().assets.load(7, 0).expect("asset handle must be allocated");
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
let report = runtime.tick(
@@ -304,7 +401,7 @@ fn tick_asset_commit_invalid_transition_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "invalid transition must not crash");
assert!(vm.is_halted());
@@ -322,7 +419,7 @@ fn tick_asset_cancel_unknown_handle_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 999\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -347,7 +444,7 @@ fn tick_asset_cancel_unknown_handle_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "unknown handle cancel must not crash");
assert!(vm.is_halted());
@@ -364,7 +461,7 @@ fn tick_asset_cancel_invalid_transition_returns_status_not_crash() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("PUSH_I32 1\nHOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -380,28 +477,29 @@ fn tick_asset_cancel_invalid_transition_returns_status_not_crash() {
let cartridge = cartridge_with_program(program, caps::ASSET);
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
platform.local_hardware().assets.initialize_for_cartridge(
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![],
AssetsPayloadSource::from_bytes(asset_data),
);
let handle = hardware.assets.load(7, 0).expect("asset handle must be allocated");
let handle =
platform.local_hardware().assets.load(7, 0).expect("asset handle must be allocated");
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
loop {
match hardware.assets.status(handle) {
LoadStatus::READY => break,
LoadStatus::PENDING | LoadStatus::LOADING => {
std::thread::sleep(std::time::Duration::from_millis(1));
}
other => panic!("unexpected asset status before commit: {:?}", other),
}
let start = Instant::now();
let mut status = platform.local_hardware().assets.status(handle);
while matches!(status, LoadStatus::PENDING | LoadStatus::LOADING)
&& start.elapsed() < std::time::Duration::from_secs(5)
{
std::thread::sleep(std::time::Duration::from_millis(10));
status = platform.local_hardware().assets.status(handle);
}
assert_eq!(status, LoadStatus::READY, "asset did not become ready before commit");
assert_eq!(hardware.assets.commit(handle), AssetOpStatus::Ok);
hardware.assets.apply_commits();
assert_eq!(hardware.assets.status(handle), LoadStatus::COMMITTED);
assert_eq!(platform.local_hardware().assets.commit(handle), AssetOpStatus::Ok);
platform.local_hardware().assets.apply_commits();
assert_eq!(platform.local_hardware().assets.status(handle), LoadStatus::COMMITTED);
let report = runtime.tick(
&mut log_service,
@@ -412,7 +510,7 @@ fn tick_asset_cancel_invalid_transition_returns_status_not_crash() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "cancel after commit must not crash");
assert!(vm.is_halted());
@@ -429,7 +527,7 @@ fn tick_status_first_surface_smoke_across_composer_audio_and_asset() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 0\nHOSTCALL 0\n\
@@ -476,7 +574,7 @@ fn tick_status_first_surface_smoke_across_composer_audio_and_asset() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "mixed status-first surface must not crash");
assert!(vm.is_halted());
@@ -11,7 +11,7 @@ fn tick_memcard_slot_roundtrip_for_game_profile() {
let mut next_handle = 1;
runtime.mount_fs(&mut log_service, &mut fs, &mut fs_state, Box::new(MemFsBackend::default()));
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble(
"PUSH_I32 0\nPUSH_I32 0\nPUSH_CONST 0\nHOSTCALL 0\nPOP_N 2\nPUSH_I32 0\nHOSTCALL 1\nPOP_N 1\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 10\nHOSTCALL 2\nHALT",
@@ -66,7 +66,7 @@ fn tick_memcard_slot_roundtrip_for_game_profile() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "memcard roundtrip must not crash");
assert!(vm.is_halted());
@@ -86,7 +86,7 @@ fn tick_memcard_access_is_denied_for_non_game_profile() {
let mut open_files: HashMap<u32, String> = HashMap::new();
let mut next_handle = 1;
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
let code = assemble("HOSTCALL 0\nHALT").expect("assemble");
let program = serialized_single_function_module(
@@ -121,7 +121,7 @@ fn tick_memcard_access_is_denied_for_non_game_profile() {
&mut next_handle,
&mut vm,
&signals,
&mut hardware,
&mut platform,
);
assert!(report.is_none(), "non-game memcard call must return status");
assert!(vm.is_halted());
@@ -1,7 +1,5 @@
use super::dispatch::VmRuntimeHost;
use super::render_manager::{
LocalRenderWorker, RenderConsumeOutcome, RenderConsumerPath, RenderSurface,
};
use super::render_manager::{RenderConsumeOutcome, RenderConsumerPath, RenderSurface};
use super::*;
use crate::CrashReport;
use crate::fs::{FsState, VirtualFS};
@@ -9,8 +7,8 @@ use crate::services::memcard::MemcardService;
use prometeu_hal::asset::{BankTelemetry, BankType};
use prometeu_hal::log::{LogLevel, LogService, LogSource};
use prometeu_hal::{
FrameId, HardwareBridge, HostContext, InputSignals, RenderSubmission, RenderSubmissionPacket,
ShellUiFramePacket,
FrameId, HostContext, InputSignals, RenderSubmission, RenderSubmissionPacket,
RenderSubmissionSink, RuntimePlatform, ShellUiFramePacket,
};
use prometeu_vm::LogicalFrameEndingReason;
use std::collections::HashMap;
@@ -18,12 +16,14 @@ use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::Ordering;
struct HardwareRenderSurface<'a> {
hw: &'a mut dyn HardwareBridge,
sink: &'a mut dyn RenderSubmissionSink,
}
impl RenderSurface for HardwareRenderSurface<'_> {
fn consume_submission(&mut self, submission: &RenderSubmission) {
self.hw.publish_render_submission(submission);
self.sink
.submit_render_submission(submission.clone())
.expect("local render submission sink should publish");
}
}
@@ -51,9 +51,9 @@ impl VirtualMachineRuntime {
}
fn bank_telemetry_summary(
hw: &dyn HardwareBridge,
platform: &dyn RuntimePlatform,
) -> (BankTelemetry, BankTelemetry, BankTelemetry) {
let telemetry = hw.assets().bank_telemetry();
let telemetry = platform.assets().bank_telemetry();
let glyph =
telemetry.iter().find(|entry| entry.bank_type == BankType::GLYPH).cloned().unwrap_or(
BankTelemetry { bank_type: BankType::GLYPH, used_slots: 0, total_slots: 0 },
@@ -74,10 +74,10 @@ impl VirtualMachineRuntime {
&mut self,
log_service: &mut LogService,
vm: &mut VirtualMachine,
hw: &mut dyn HardwareBridge,
platform: &mut dyn RuntimePlatform,
) -> Option<CrashReport> {
let step_result = {
let mut ctx = HostContext::new(Some(hw));
let mut ctx = HostContext::new_platform(Some(platform));
let mut fs = VirtualFS::new();
let mut fs_state = FsState::Unmounted;
let mut memcard = MemcardService::new();
@@ -121,6 +121,7 @@ impl VirtualMachineRuntime {
}
}
#[allow(clippy::too_many_arguments)]
pub fn tick(
&mut self,
log_service: &mut LogService,
@@ -131,7 +132,7 @@ impl VirtualMachineRuntime {
next_handle: &mut u32,
vm: &mut VirtualMachine,
signals: &InputSignals,
hw: &mut dyn HardwareBridge,
platform: &mut dyn RuntimePlatform,
) -> Option<CrashReport> {
let start = Instant::now();
self.tick_index += 1;
@@ -141,7 +142,6 @@ impl VirtualMachineRuntime {
}
self.update_fs(log_service, fs, fs_state);
if !self.logical_frame_active {
if RenderManager::policy_for_app_mode(self.current_cartridge_app_mode)
.uses_frame_scheduler()
@@ -152,7 +152,7 @@ impl VirtualMachineRuntime {
}
self.logical_frame_active = true;
self.logical_frame_remaining_cycles = Self::CYCLES_PER_LOGICAL_FRAME;
self.begin_logical_frame(signals, hw);
self.begin_logical_frame(signals, platform);
if self.needs_prepare_entry_call || vm.call_stack_is_empty() {
vm.prepare_boot_call();
@@ -180,7 +180,7 @@ impl VirtualMachineRuntime {
if budget > 0 {
let run_result = {
let mut ctx = HostContext::new(Some(hw));
let mut ctx = HostContext::new_platform(Some(platform));
let mut host = VmRuntimeHost {
runtime: self,
log_service,
@@ -247,8 +247,9 @@ impl VirtualMachineRuntime {
self.current_cartridge_app_mode,
self.current_app_id,
);
self.sync_render_worker_ownership();
if self.current_cartridge_app_mode == AppMode::Game {
let mut packet = hw.close_game2d_packet();
let mut packet = platform.game2d_frame_composer().close_game2d_packet();
packet.gfx2d = std::mem::take(&mut self.gfx2d_commands);
self.render_manager
.close_frame_with_packet(RenderSubmissionPacket::Game2D(packet))
@@ -262,7 +263,8 @@ impl VirtualMachineRuntime {
}
let render_outcome = catch_unwind(AssertUnwindSafe(|| {
let mut surface = HardwareRenderSurface { hw };
let mut surface =
HardwareRenderSurface { sink: platform.render_submission_sink() };
match self
.render_manager
.active_render_policy()
@@ -271,9 +273,14 @@ impl VirtualMachineRuntime {
RenderConsumerPath::LocalSynchronous => {
self.render_manager.consume_latest(&mut surface)
}
RenderConsumerPath::LocalWorkerPrototype => {
let mut worker = LocalRenderWorker;
worker.consume_latest(&mut self.render_manager, &mut surface)
RenderConsumerPath::RealWorker
if self.render_worker_controller.is_some()
&& self.current_cartridge_app_mode == AppMode::Game =>
{
RenderConsumeOutcome::NoSubmission
}
RenderConsumerPath::RealWorker => {
self.render_manager.consume_latest(&mut surface)
}
}
}));
@@ -304,7 +311,8 @@ impl VirtualMachineRuntime {
}
// 1. Snapshot full telemetry at logical frame end
let (glyph_bank, sound_bank, scene_bank) = Self::bank_telemetry_summary(hw);
let (glyph_bank, sound_bank, scene_bank) =
Self::bank_telemetry_summary(platform);
self.atomic_telemetry
.glyph_slots_used
.store(glyph_bank.used_slots as u32, Ordering::Relaxed);
@@ -395,7 +403,7 @@ impl VirtualMachineRuntime {
// 2. High-frequency telemetry update (only if inspection is active)
if self.inspection_active {
let (glyph_bank, sound_bank, scene_bank) = Self::bank_telemetry_summary(hw);
let (glyph_bank, sound_bank, scene_bank) = Self::bank_telemetry_summary(platform);
self.atomic_telemetry
.glyph_slots_used
.store(glyph_bank.used_slots as u32, Ordering::Relaxed);
@@ -432,10 +440,10 @@ impl VirtualMachineRuntime {
pub(crate) fn begin_logical_frame(
&mut self,
_signals: &InputSignals,
hw: &mut dyn HardwareBridge,
platform: &mut dyn RuntimePlatform,
) {
hw.begin_frame();
hw.audio_mut().clear_commands();
platform.game2d_frame_composer().begin_frame();
platform.audio_mut().clear_commands();
self.logs_written_this_frame.clear();
}
}
@@ -0,0 +1,310 @@
use crate::VirtualMachineRuntime;
use crate::fs::FsState;
use crate::process::{Process, ProcessId, ProcessKind};
use crate::task::{Task, TaskId, TaskKind};
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::telemetry::CertificationConfig;
use prometeu_vm::VirtualMachine;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::AtomicU32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VmSessionId(pub TaskId);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VmSessionError {
SessionAlreadyExists(TaskId),
TaskProcessMismatch { task_id: TaskId, task_process: ProcessId, process_id: ProcessId },
TaskKindMismatch { task_id: TaskId, task_kind: TaskKind, process_kind: ProcessKind },
ProcessIsNotVmBacked(ProcessId),
}
pub struct VmSession {
pub id: VmSessionId,
pub task_id: TaskId,
pub process_id: ProcessId,
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
pub vm: VirtualMachine,
pub runtime: VirtualMachineRuntime,
pub fs_state: FsState,
pub open_files: HashMap<u32, String>,
pub next_handle: u32,
}
impl VmSession {
fn new(
task: &Task,
process: &Process,
app_mode: AppMode,
app_version: impl Into<String>,
cap_config: Option<CertificationConfig>,
logs_count: Arc<AtomicU32>,
) -> Self {
Self {
id: VmSessionId(task.id),
task_id: task.id,
process_id: process.id,
app_id: task.app_id,
title: task.title.clone(),
app_version: app_version.into(),
app_mode,
vm: VirtualMachine::default(),
runtime: VirtualMachineRuntime::new_with_log_counter(cap_config, logs_count),
fs_state: FsState::Unmounted,
open_files: HashMap::new(),
next_handle: 1,
}
}
pub fn clear_cartridge_service_state(&mut self) {
self.open_files.clear();
self.next_handle = 1;
}
}
#[derive(Default)]
pub struct VmSessionRegistry {
sessions: HashMap<VmSessionId, VmSession>,
}
impl VmSessionRegistry {
pub fn new() -> Self {
Self { sessions: HashMap::new() }
}
pub fn create_for_task(
&mut self,
task: &Task,
process: &Process,
app_version: impl Into<String>,
cap_config: Option<CertificationConfig>,
logs_count: Arc<AtomicU32>,
) -> Result<VmSessionId, VmSessionError> {
if task.process_id != process.id {
return Err(VmSessionError::TaskProcessMismatch {
task_id: task.id,
task_process: task.process_id,
process_id: process.id,
});
}
let app_mode = app_mode_for_task_and_process(task, process)?;
let id = VmSessionId(task.id);
if self.sessions.contains_key(&id) {
return Err(VmSessionError::SessionAlreadyExists(task.id));
}
self.sessions.insert(
id,
VmSession::new(task, process, app_mode, app_version, cap_config, logs_count),
);
Ok(id)
}
pub fn get(&self, id: VmSessionId) -> Option<&VmSession> {
self.sessions.get(&id)
}
pub fn get_mut(&mut self, id: VmSessionId) -> Option<&mut VmSession> {
self.sessions.get_mut(&id)
}
pub fn for_task(&self, task_id: TaskId) -> Option<&VmSession> {
self.get(VmSessionId(task_id))
}
pub fn for_task_mut(&mut self, task_id: TaskId) -> Option<&mut VmSession> {
self.get_mut(VmSessionId(task_id))
}
pub fn remove_for_task(&mut self, task_id: TaskId) -> Option<VmSession> {
self.sessions.remove(&VmSessionId(task_id))
}
pub fn resident_game(&self) -> Option<&VmSession> {
self.sessions.values().find(|session| session.app_mode == AppMode::Game)
}
pub fn resident_game_for_app(&self, app_id: u32) -> Option<&VmSession> {
self.sessions
.values()
.find(|session| session.app_mode == AppMode::Game && session.app_id == app_id)
}
pub fn len(&self) -> usize {
self.sessions.len()
}
pub fn is_empty(&self) -> bool {
self.sessions.is_empty()
}
pub fn clear(&mut self) {
self.sessions.clear();
}
}
fn app_mode_for_task_and_process(
task: &Task,
process: &Process,
) -> Result<AppMode, VmSessionError> {
match (task.kind, process.kind) {
(TaskKind::Game, ProcessKind::VmGame) => Ok(AppMode::Game),
(TaskKind::Shell, ProcessKind::VmShell) => Ok(AppMode::Shell),
(_, ProcessKind::NativeShell) => Err(VmSessionError::ProcessIsNotVmBacked(process.id)),
_ => Err(VmSessionError::TaskKindMismatch {
task_id: task.id,
task_kind: task.kind,
process_kind: process.kind,
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::process::Process;
use crate::task::Task;
#[test]
fn creates_vm_game_session_for_vm_game_task() {
let process = Process::new(ProcessId(1), 42, "Stress", ProcessKind::VmGame);
let task = Task::new(TaskId(7), process.id, 42, "Stress", TaskKind::Game);
let mut registry = VmSessionRegistry::new();
let id = registry
.create_for_task(&task, &process, "", None, Arc::new(AtomicU32::new(0)))
.expect("session should create");
let session = registry.get(id).expect("session should exist");
assert_eq!(session.id, VmSessionId(task.id));
assert_eq!(session.task_id, task.id);
assert_eq!(session.process_id, process.id);
assert_eq!(session.app_id, 42);
assert_eq!(session.title, "Stress");
assert_eq!(session.app_mode, AppMode::Game);
assert_eq!(session.runtime.current_app_id, 0);
assert_eq!(session.fs_state, FsState::Unmounted);
assert_eq!(session.next_handle, 1);
}
#[test]
fn creates_vm_shell_session_for_vm_shell_task() {
let process = Process::new(ProcessId(1), 7, "Shell", ProcessKind::VmShell);
let task = Task::new(TaskId(3), process.id, 7, "Shell", TaskKind::Shell);
let mut registry = VmSessionRegistry::new();
let id = registry
.create_for_task(&task, &process, "1.0", None, Arc::new(AtomicU32::new(0)))
.expect("session should create");
let session = registry.get(id).expect("session should exist");
assert_eq!(session.app_mode, AppMode::Shell);
assert_eq!(session.app_version, "1.0");
}
#[test]
fn rejects_native_shell_process() {
let process = Process::new(ProcessId(1), 7, "Shell", ProcessKind::NativeShell);
let task = Task::new(TaskId(3), process.id, 7, "Shell", TaskKind::Shell);
let mut registry = VmSessionRegistry::new();
assert_eq!(
registry.create_for_task(&task, &process, "", None, Arc::new(AtomicU32::new(0))),
Err(VmSessionError::ProcessIsNotVmBacked(process.id))
);
}
#[test]
fn finds_resident_game_by_app_id() {
let process = Process::new(ProcessId(1), 42, "Stress", ProcessKind::VmGame);
let task = Task::new(TaskId(7), process.id, 42, "Stress", TaskKind::Game);
let mut registry = VmSessionRegistry::new();
registry
.create_for_task(&task, &process, "", None, Arc::new(AtomicU32::new(0)))
.expect("session should create");
assert_eq!(
registry.resident_game_for_app(42).map(|session| session.task_id),
Some(task.id)
);
assert_eq!(registry.resident_game_for_app(43).map(|session| session.task_id), None);
}
#[test]
fn remove_for_task_removes_only_matching_session() {
let game_process = Process::new(ProcessId(1), 42, "Stress", ProcessKind::VmGame);
let game_task = Task::new(TaskId(7), game_process.id, 42, "Stress", TaskKind::Game);
let shell_process = Process::new(ProcessId(2), 9, "Shell", ProcessKind::VmShell);
let shell_task = Task::new(TaskId(8), shell_process.id, 9, "Shell", TaskKind::Shell);
let mut registry = VmSessionRegistry::new();
registry
.create_for_task(&game_task, &game_process, "", None, Arc::new(AtomicU32::new(0)))
.expect("game session should create");
registry
.create_for_task(&shell_task, &shell_process, "", None, Arc::new(AtomicU32::new(0)))
.expect("shell session should create");
let removed = registry.remove_for_task(game_task.id).expect("game session should remove");
assert_eq!(removed.task_id, game_task.id);
assert_eq!(registry.for_task(game_task.id).map(|session| session.task_id), None);
assert_eq!(
registry.for_task(shell_task.id).map(|session| session.task_id),
Some(shell_task.id)
);
}
#[test]
fn session_runtime_state_is_independent_per_session() {
let game_process = Process::new(ProcessId(1), 42, "Stress", ProcessKind::VmGame);
let game_task = Task::new(TaskId(7), game_process.id, 42, "Stress", TaskKind::Game);
let shell_process = Process::new(ProcessId(2), 9, "Shell", ProcessKind::VmShell);
let shell_task = Task::new(TaskId(8), shell_process.id, 9, "Shell", TaskKind::Shell);
let mut registry = VmSessionRegistry::new();
registry
.create_for_task(&game_task, &game_process, "", None, Arc::new(AtomicU32::new(0)))
.expect("game session should create");
registry
.create_for_task(&shell_task, &shell_process, "", None, Arc::new(AtomicU32::new(0)))
.expect("shell session should create");
registry
.for_task_mut(game_task.id)
.expect("game session should exist")
.runtime
.tick_index = 11;
registry
.for_task_mut(shell_task.id)
.expect("shell session should exist")
.runtime
.tick_index = 3;
registry
.for_task_mut(game_task.id)
.expect("game session should exist")
.open_files
.insert(1, "/game.save".to_string());
assert_eq!(
registry.for_task(game_task.id).map(|session| session.runtime.tick_index),
Some(11)
);
assert_eq!(
registry.for_task(shell_task.id).map(|session| session.runtime.tick_index),
Some(3)
);
assert!(
registry
.for_task(shell_task.id)
.expect("shell session should exist")
.open_files
.is_empty()
);
}
}
+22 -18
View File
@@ -1350,8 +1350,9 @@ fn input_touch_x(
ctx: &mut HostContext<'_>,
) -> Result<Vec<Value>, IntrinsicExecutionError> {
expect_touch_handle(args, "x")?;
let hw = ctx.require_hw().map_err(|_| IntrinsicExecutionError::HardwareUnavailable)?;
Ok(vec![Value::Int64(hw.touch().x() as i64)])
let platform =
ctx.require_platform().map_err(|_| IntrinsicExecutionError::HardwareUnavailable)?;
Ok(vec![Value::Int64(platform.input().touch().x() as i64)])
}
fn input_touch_y(
@@ -1359,8 +1360,9 @@ fn input_touch_y(
ctx: &mut HostContext<'_>,
) -> Result<Vec<Value>, IntrinsicExecutionError> {
expect_touch_handle(args, "y")?;
let hw = ctx.require_hw().map_err(|_| IntrinsicExecutionError::HardwareUnavailable)?;
Ok(vec![Value::Int64(hw.touch().y() as i64)])
let platform =
ctx.require_platform().map_err(|_| IntrinsicExecutionError::HardwareUnavailable)?;
Ok(vec![Value::Int64(platform.input().touch().y() as i64)])
}
fn input_button_pressed(
@@ -1435,9 +1437,11 @@ fn resolve_button(
ctx: &mut HostContext<'_>,
) -> Result<prometeu_hal::button::Button, IntrinsicExecutionError> {
let carrier = expect_builtin_carrier(args, 0)?;
let hw = ctx.require_hw().map_err(|_| IntrinsicExecutionError::HardwareUnavailable)?;
let platform =
ctx.require_platform().map_err(|_| IntrinsicExecutionError::HardwareUnavailable)?;
let input = platform.input();
if carrier == TOUCH_BUTTON_CARRIER {
return Ok(*hw.touch().f());
return Ok(*input.touch().f());
}
let Some(index) = carrier.checked_sub(PAD_BUTTON_BASE) else {
@@ -1448,18 +1452,18 @@ fn resolve_button(
});
};
let button = match index {
0 => *hw.pad().up(),
1 => *hw.pad().down(),
2 => *hw.pad().left(),
3 => *hw.pad().right(),
4 => *hw.pad().a(),
5 => *hw.pad().b(),
6 => *hw.pad().x(),
7 => *hw.pad().y(),
8 => *hw.pad().l(),
9 => *hw.pad().r(),
10 => *hw.pad().start(),
11 => *hw.pad().select(),
0 => *input.pad().up(),
1 => *input.pad().down(),
2 => *input.pad().left(),
3 => *input.pad().right(),
4 => *input.pad().a(),
5 => *input.pad().b(),
6 => *input.pad().x(),
7 => *input.pad().y(),
8 => *input.pad().l(),
9 => *input.pad().r(),
10 => *input.pad().start(),
11 => *input.pad().select(),
_ => {
return Err(IntrinsicExecutionError::InvalidBuiltinCarrier {
owner: "input.button",
+20 -20
View File
@@ -548,17 +548,17 @@ mod tests {
// replace with arrays containing cross-references. Since our simple
// heap doesn't support in-place element edits via API, simulate by
// directly editing stored objects.
if let Some(slot) = heap.objects.get_mut(a.0 as usize) {
if let Some(obj) = slot.as_mut() {
obj.array_elems = Some(vec![Value::HeapRef(b)]);
obj.header.payload_len = 1;
}
if let Some(slot) = heap.objects.get_mut(a.0 as usize)
&& let Some(obj) = slot.as_mut()
{
obj.array_elems = Some(vec![Value::HeapRef(b)]);
obj.header.payload_len = 1;
}
if let Some(slot) = heap.objects.get_mut(b.0 as usize) {
if let Some(obj) = slot.as_mut() {
obj.array_elems = Some(vec![Value::HeapRef(a)]);
obj.header.payload_len = 1;
}
if let Some(slot) = heap.objects.get_mut(b.0 as usize)
&& let Some(obj) = slot.as_mut()
{
obj.array_elems = Some(vec![Value::HeapRef(a)]);
obj.header.payload_len = 1;
}
// Mark from A; should terminate and mark both.
@@ -720,17 +720,17 @@ mod tests {
let b = heap.allocate_array(vec![]);
// Make A point to B and B point to A.
if let Some(slot) = heap.objects.get_mut(a.0 as usize) {
if let Some(obj) = slot.as_mut() {
obj.array_elems = Some(vec![Value::HeapRef(b)]);
obj.header.payload_len = 1;
}
if let Some(slot) = heap.objects.get_mut(a.0 as usize)
&& let Some(obj) = slot.as_mut()
{
obj.array_elems = Some(vec![Value::HeapRef(b)]);
obj.header.payload_len = 1;
}
if let Some(slot) = heap.objects.get_mut(b.0 as usize) {
if let Some(obj) = slot.as_mut() {
obj.array_elems = Some(vec![Value::HeapRef(a)]);
obj.header.payload_len = 1;
}
if let Some(slot) = heap.objects.get_mut(b.0 as usize)
&& let Some(obj) = slot.as_mut()
{
obj.array_elems = Some(vec![Value::HeapRef(a)]);
obj.header.payload_len = 1;
}
// No roots: perform sweep directly; both should be reclaimed.
+10 -15
View File
@@ -1052,12 +1052,13 @@ mod tests {
// 21: Jmp 27
// 27: Nop
let mut code = Vec::new();
code.push(OpCode::PushBool as u8);
code.push(0x00);
code.push(1); // 0: PushBool (3 bytes)
code.push(OpCode::JmpIfTrue as u8);
code.push(0x00);
let mut code = vec![
OpCode::PushBool as u8,
0x00,
1, // 0: PushBool (3 bytes)
OpCode::JmpIfTrue as u8,
0x00,
];
code.extend_from_slice(&15u32.to_le_bytes()); // 3: JmpIfTrue (6 bytes)
code.push(OpCode::Jmp as u8);
code.push(0x00);
@@ -1247,9 +1248,7 @@ mod tests {
#[test]
fn test_function_without_terminator_is_rejected() {
// Single NOP with no RET/JMP/TRAP/HALT at the end → fallthrough to end
let mut code = Vec::new();
code.push(OpCode::Nop as u8);
code.push(0x00);
let code = vec![OpCode::Nop as u8, 0x00];
let functions = vec![FunctionMeta { code_offset: 0, code_len: 2, ..Default::default() }];
let res = Verifier::verify(&code, &functions);
@@ -1259,9 +1258,7 @@ mod tests {
#[test]
fn test_function_with_proper_terminator_passes() {
// Minimal function that returns immediately
let mut code = Vec::new();
code.push(OpCode::Ret as u8);
code.push(0x00);
let code = vec![OpCode::Ret as u8, 0x00];
let functions = vec![FunctionMeta {
code_offset: 0,
@@ -1277,9 +1274,7 @@ mod tests {
fn test_verifier_ret_too_few_slots() {
// Function declares 1 return slot but returns nothing
// 0: Ret
let mut code = Vec::new();
code.push(OpCode::Ret as u8);
code.push(0x00);
let code = vec![OpCode::Ret as u8, 0x00];
let functions = vec![FunctionMeta {
code_offset: 0,
@@ -1596,9 +1596,10 @@ mod tests {
#[test]
fn test_push_f64_immediate() {
let value = 3.125f64;
let mut rom = Vec::new();
rom.extend_from_slice(&(OpCode::PushF64 as u16).to_le_bytes());
rom.extend_from_slice(&3.14f64.to_le_bytes());
rom.extend_from_slice(&value.to_le_bytes());
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
let mut vm = new_test_vm(rom.clone(), vec![]);
@@ -1606,7 +1607,7 @@ mod tests {
let mut ctx = HostContext::new(None);
vm.step(&mut native, &mut ctx).unwrap();
assert_eq!(vm.peek().unwrap(), &Value::Float(3.14));
assert_eq!(vm.peek().unwrap(), &Value::Float(value));
}
#[test]
@@ -2537,9 +2538,8 @@ mod tests {
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
// Any non-trap outcome is considered success here
match report.reason {
LogicalFrameEndingReason::Trap(trap) => panic!("Unexpected trap: {:?}", trap),
_ => {}
if let LogicalFrameEndingReason::Trap(trap) = report.reason {
panic!("Unexpected trap: {:?}", trap);
}
}
@@ -2627,7 +2627,7 @@ mod tests {
fn test_loader_hardening_unsupported_version() {
let mut vm = VirtualMachine::default();
let mut header = vec![0u8; 32];
header[0..4].copy_from_slice(b"PBS\0");
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
header[4..6].copy_from_slice(&1u16.to_le_bytes()); // version 1 (unsupported)
let res = vm.initialize(header);
@@ -2635,16 +2635,16 @@ mod tests {
}
#[test]
fn test_loader_hardening_malformed_pbs_v0() {
fn test_loader_hardening_malformed_pbx_v0() {
let mut vm = VirtualMachine::default();
let mut header = vec![0u8; 32];
header[0..4].copy_from_slice(b"PBS\0");
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
header[8..12].copy_from_slice(&1u32.to_le_bytes()); // 1 section claimed but none provided
let res = vm.initialize(header);
match res {
Err(VmInitError::ImageLoadFailed(prometeu_bytecode::LoadError::UnexpectedEof)) => {}
_ => panic!("Expected PbsV0LoadFailed(UnexpectedEof), got {:?}", res),
_ => panic!("Expected PBX v0 load failure UnexpectedEof, got {:?}", res),
}
}
@@ -2672,8 +2672,7 @@ mod tests {
#[test]
fn test_loader_hardening_successful_init() {
let mut vm = VirtualMachine::default();
vm.pc = 123; // Pollution
let mut vm = VirtualMachine { pc: 123, ..Default::default() };
let code = assemble("HALT").expect("assemble");
let header = prometeu_bytecode::model::BytecodeModule {
@@ -2696,6 +2695,13 @@ mod tests {
assert_eq!(vm.pc, 0);
assert_eq!(vm.program.rom.len(), 2);
assert_eq!(vm.cycles, 0);
vm.prepare_boot_call();
let mut native = MockNative;
let mut ctx = HostContext::new(None);
let report = vm.run_budget(100, &mut native, &mut ctx).expect("run loaded PBX");
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
assert!(vm.is_halted());
}
#[test]
@@ -3085,7 +3091,7 @@ mod tests {
fn test_loader_hardening_missing_sysc_section() {
let mut vm = VirtualMachine::default();
let mut header = vec![0u8; 32];
header[0..4].copy_from_slice(b"PBS\0");
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
let res = vm.initialize(header);
@@ -3978,26 +3984,26 @@ mod tests {
let mut a_href = None;
let mut b_href = None;
// Consider currently running coroutine
if let Some(cur) = vm.current_coro {
if let Some(f) = vm.call_stack.last() {
if f.func_idx == 1 {
a_href = Some(cur);
}
if f.func_idx == 2 {
b_href = Some(cur);
}
if let Some(cur) = vm.current_coro
&& let Some(f) = vm.call_stack.last()
{
if f.func_idx == 1 {
a_href = Some(cur);
}
if f.func_idx == 2 {
b_href = Some(cur);
}
}
// And also consider suspended (Ready/Sleeping) coroutines
for h in vm.heap.suspended_coroutine_handles() {
if let Some(co) = vm.heap.coroutine_data(h) {
if let Some(f) = co.frames.last() {
if f.func_idx == 1 {
a_href = Some(h);
}
if f.func_idx == 2 {
b_href = Some(h);
}
if let Some(co) = vm.heap.coroutine_data(h)
&& let Some(f) = co.frames.last()
{
if f.func_idx == 1 {
a_href = Some(h);
}
if f.func_idx == 2 {
b_href = Some(h);
}
}
}
@@ -4108,25 +4114,25 @@ mod tests {
// Identify A and B coroutine handles (consider both running and suspended)
let mut a_href = None;
let mut b_href = None;
if let Some(cur) = vm.current_coro {
if let Some(f) = vm.call_stack.last() {
if f.func_idx == 1 {
a_href = Some(cur);
}
if f.func_idx == 2 {
b_href = Some(cur);
}
if let Some(cur) = vm.current_coro
&& let Some(f) = vm.call_stack.last()
{
if f.func_idx == 1 {
a_href = Some(cur);
}
if f.func_idx == 2 {
b_href = Some(cur);
}
}
for h in vm.heap.suspended_coroutine_handles() {
if let Some(co) = vm.heap.coroutine_data(h) {
if let Some(f) = co.frames.last() {
if f.func_idx == 1 {
a_href = Some(h);
}
if f.func_idx == 2 {
b_href = Some(h);
}
if let Some(co) = vm.heap.coroutine_data(h)
&& let Some(f) = co.frames.last()
{
if f.func_idx == 1 {
a_href = Some(h);
}
if f.func_idx == 2 {
b_href = Some(h);
}
}
}
@@ -4253,26 +4259,26 @@ mod tests {
let mut a = None;
let mut b = None;
// running
if let Some(cur) = vm.current_coro {
if let Some(f) = vm.call_stack.last() {
if f.func_idx == 1 {
a = Some(cur);
}
if f.func_idx == 2 {
b = Some(cur);
}
if let Some(cur) = vm.current_coro
&& let Some(f) = vm.call_stack.last()
{
if f.func_idx == 1 {
a = Some(cur);
}
if f.func_idx == 2 {
b = Some(cur);
}
}
// suspended
for h in vm.heap.suspended_coroutine_handles() {
if let Some(co) = vm.heap.coroutine_data(h) {
if let Some(f) = co.frames.last() {
if f.func_idx == 1 {
a = Some(h);
}
if f.func_idx == 2 {
b = Some(h);
}
if let Some(co) = vm.heap.coroutine_data(h)
&& let Some(f) = co.frames.last()
{
if f.func_idx == 1 {
a = Some(h);
}
if f.func_idx == 2 {
b = Some(h);
}
}
}
@@ -83,30 +83,32 @@ impl VirtualMachine {
self.scheduler = Scheduler::new();
self.current_coro = None;
let program = if program_bytes.starts_with(b"PBS\0") {
match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
Ok(mut module) => {
patch_module_hostcalls(&mut module, self.capabilities)
.map_err(VmInitError::LoaderPatchFailed)?;
let program = match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
Ok(mut module) => {
patch_module_hostcalls(&mut module, self.capabilities)
.map_err(VmInitError::LoaderPatchFailed)?;
let max_stacks = Verifier::verify(&module.code, &module.functions)
.map_err(|e| VmInitError::VerificationFailed(format!("{:?}", e)))?;
let max_stacks = Verifier::verify(&module.code, &module.functions)
.map_err(|e| VmInitError::VerificationFailed(format!("{:?}", e)))?;
let mut program = ProgramImage::from(module);
let mut functions = program.functions.as_ref().to_vec();
for (func, max_stack) in functions.iter_mut().zip(max_stacks) {
func.max_stack_slots = max_stack;
}
program.functions = std::sync::Arc::from(functions);
program
let mut program = ProgramImage::from(module);
let mut functions = program.functions.as_ref().to_vec();
for (func, max_stack) in functions.iter_mut().zip(max_stacks) {
func.max_stack_slots = max_stack;
}
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
return Err(VmInitError::UnsupportedFormat);
}
Err(e) => return Err(VmInitError::ImageLoadFailed(e)),
program.functions = std::sync::Arc::from(functions);
program
}
} else {
return Err(VmInitError::InvalidFormat);
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
return Err(VmInitError::UnsupportedFormat);
}
Err(prometeu_bytecode::LoadError::InvalidMagic) => {
return Err(VmInitError::InvalidFormat);
}
Err(prometeu_bytecode::LoadError::UnexpectedEof) if program_bytes.len() < 32 => {
return Err(VmInitError::InvalidFormat);
}
Err(e) => return Err(VmInitError::ImageLoadFailed(e)),
};
let pc = program
@@ -2,8 +2,8 @@ use prometeu_vm::{VirtualMachine, VmInitError};
#[test]
fn invalid_image_format_is_rejected_before_execution() {
// Provide bytes that are not a valid PBS image. The VM must reject it with InvalidFormat.
let program_bytes = b"NOT_PBS_IMAGE".to_vec();
// Provide bytes that are not a valid PBX image. The VM must reject it with InvalidFormat.
let program_bytes = b"NOT_PBX_IMAGE".to_vec();
let mut vm = VirtualMachine::default();
let result = vm.initialize(program_bytes);
assert!(matches!(result, Err(VmInitError::InvalidFormat)));
@@ -168,7 +168,7 @@ fn path_segment_violation(path: &Path) -> Option<String> {
}
fn is_forbidden_ident(tok: &str) -> bool {
FORBIDDEN_IDENT_TOKENS.iter().any(|&bad| bad == tok)
FORBIDDEN_IDENT_TOKENS.contains(&tok)
}
fn tokenize_identifiers(text: &str) -> Vec<(String, usize, usize)> {
@@ -0,0 +1,74 @@
use std::fs;
use std::path::{Path, PathBuf};
const TARGET_MANIFESTS: &[&str] =
&["crates/console/prometeu-bytecode/Cargo.toml", "crates/console/prometeu-vm/Cargo.toml"];
const FORBIDDEN_DEPENDENCY_FRAGMENTS: &[&str] = &["compiler", "frontend"];
#[test]
fn pbx_and_pvm_crates_must_not_depend_on_compiler_or_frontend_crates() {
let workspace_root = find_workspace_root().expect("runtime workspace root");
let mut violations = Vec::new();
for relative_path in TARGET_MANIFESTS {
let manifest_path = workspace_root.join(relative_path);
let manifest = fs::read_to_string(&manifest_path)
.unwrap_or_else(|error| panic!("failed to read {}: {error}", manifest_path.display()));
for dependency in dependency_names(&manifest) {
let normalized = dependency.to_ascii_lowercase();
if FORBIDDEN_DEPENDENCY_FRAGMENTS.iter().any(|fragment| normalized.contains(fragment)) {
violations.push(format!("{relative_path}: forbidden dependency `{dependency}`"));
}
}
}
assert!(
violations.is_empty(),
"PBX/PVM crates must remain independent of compiler and frontend crates:\n{}",
violations.join("\n")
);
}
fn dependency_names(manifest: &str) -> Vec<&str> {
let mut names = Vec::new();
let mut in_dependency_section = false;
for raw_line in manifest.lines() {
let line = raw_line.trim();
if line.starts_with('[') && line.ends_with(']') {
let section = &line[1..line.len() - 1];
in_dependency_section = section == "dependencies"
|| section == "dev-dependencies"
|| section == "build-dependencies"
|| section.ends_with(".dependencies")
|| section.ends_with(".dev-dependencies")
|| section.ends_with(".build-dependencies");
continue;
}
if !in_dependency_section || line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((name, _)) = line.split_once('=') {
names.push(name.trim().trim_matches('"'));
}
}
names
}
fn find_workspace_root() -> Option<PathBuf> {
let mut cursor = Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf();
loop {
let manifest = cursor.join("Cargo.toml");
if fs::read_to_string(&manifest).is_ok_and(|contents| contents.contains("[workspace]")) {
return Some(cursor);
}
if !cursor.pop() {
return None;
}
}
}
@@ -1,5 +1,5 @@
use prometeu_drivers::hardware::Hardware;
use prometeu_firmware::{BootTarget, Firmware};
use prometeu_hal::RuntimePlatform;
use prometeu_hal::cartridge_loader::CartridgeLoader;
use prometeu_hal::debugger_protocol::*;
use prometeu_hal::telemetry::{CertificationConfig, TelemetryFrame};
@@ -28,6 +28,8 @@ pub struct HostDebugger {
last_telemetry_frame: u64,
/// Last fault summary sent to the debugger client.
last_fault_summary: Option<String>,
/// Debug cartridge metadata captured before the VM session exists.
debug_cartridge: Option<HandshakeCartridge>,
}
impl Default for HostDebugger {
@@ -46,19 +48,25 @@ impl HostDebugger {
last_log_seq: 0,
last_telemetry_frame: 0,
last_fault_summary: None,
debug_cartridge: None,
}
}
/// Configures the debugger based on the boot target.
/// If debug mode is enabled, it binds to the specified TCP port.
pub fn setup_boot_target(&mut self, boot_target: &BootTarget, firmware: &mut Firmware) {
pub fn setup_boot_target(&mut self, boot_target: &BootTarget, _firmware: &mut Firmware) {
if let BootTarget::Cartridge { path, debug: true, debug_port } = boot_target {
self.waiting_for_start = true;
// Pre-load cartridge metadata so the Handshake message can contain
// valid information about the App being debugged.
// valid information before the VM session is created.
if let Ok(cartridge) = CartridgeLoader::load(path) {
let _ = firmware.os.vm().initialize(&mut firmware.vm, &cartridge);
self.debug_cartridge = Some(HandshakeCartridge {
app_id: cartridge.app_id,
title: cartridge.title,
app_version: cartridge.app_version,
app_mode: cartridge.app_mode,
});
}
match TcpListener::bind(format!("127.0.0.1:{}", debug_port)) {
@@ -99,7 +107,7 @@ impl HostDebugger {
/// Main maintenance method called by the HostRunner every iteration.
/// It handles new connections and processes incoming commands.
pub fn check_commands(&mut self, firmware: &mut Firmware, hardware: &mut Hardware) {
pub fn check_commands(&mut self, firmware: &mut Firmware, platform: &mut dyn RuntimePlatform) {
// 1. Accept new client connections.
if let Some(listener) = &self.listener
&& let Ok((stream, _addr)) = listener.accept()
@@ -116,12 +124,7 @@ impl HostDebugger {
let handshake = DebugResponse::Handshake {
protocol_version: DEVTOOLS_PROTOCOL_VERSION,
runtime_version: "0.1".to_string(),
cartridge: HandshakeCartridge {
app_id: firmware.os.vm().current_app_id(),
title: firmware.os.vm().current_cartridge_title(),
app_version: firmware.os.vm().current_cartridge_app_version(),
app_mode: firmware.os.vm().current_cartridge_app_mode(),
},
cartridge: self.handshake_cartridge(firmware),
};
self.send_response(handshake);
} else {
@@ -154,7 +157,7 @@ impl HostDebugger {
continue;
}
if let Ok(cmd) = serde_json::from_str::<DebugCommand>(trimmed) {
self.handle_command(cmd, firmware, hardware);
self.handle_command(cmd, firmware, platform);
}
}
}
@@ -182,7 +185,7 @@ impl HostDebugger {
&mut self,
cmd: DebugCommand,
firmware: &mut Firmware,
hardware: &mut Hardware,
platform: &mut dyn RuntimePlatform,
) {
match cmd {
DebugCommand::Ok | DebugCommand::Start => {
@@ -201,7 +204,7 @@ impl HostDebugger {
DebugCommand::Step => {
// Execute exactly one instruction and keep paused.
firmware.os.vm().set_paused(true);
let _ = firmware.os.vm().debug_step_instruction(&mut firmware.vm, hardware);
let _ = firmware.os.vm().debug_step_active_session(platform);
}
DebugCommand::StepFrame => {
// Execute until the end of the current logical frame.
@@ -210,10 +213,10 @@ impl HostDebugger {
}
DebugCommand::GetState => {
// Return detailed VM register and stack state.
let stack_top = firmware.vm.operand_stack_top(10);
let stack_top = firmware.os.vm().active_operand_stack_top(10);
let resp = DebugResponse::GetState {
pc: firmware.vm.pc(),
pc: firmware.os.vm().active_pc().unwrap_or(0),
stack_top,
frame_index: firmware.os.vm().logical_frame_index(),
app_id: firmware.os.vm().current_app_id(),
@@ -221,18 +224,37 @@ impl HostDebugger {
self.send_response(resp);
}
DebugCommand::SetBreakpoint { pc } => {
firmware.vm.insert_breakpoint(pc);
let _ = firmware.os.vm().insert_active_breakpoint(pc);
}
DebugCommand::ListBreakpoints => {
let pcs = firmware.vm.breakpoints_list();
let pcs = firmware.os.vm().active_breakpoints_list();
self.send_response(DebugResponse::Breakpoints { pcs });
}
DebugCommand::ClearBreakpoint { pc } => {
firmware.vm.remove_breakpoint(pc);
let _ = firmware.os.vm().remove_active_breakpoint(pc);
}
}
}
fn handshake_cartridge(&self, firmware: &mut Firmware) -> HandshakeCartridge {
let app_id = firmware.os.vm().current_app_id();
if app_id != 0 {
return HandshakeCartridge {
app_id,
title: firmware.os.vm().current_cartridge_title(),
app_version: firmware.os.vm().current_cartridge_app_version(),
app_mode: firmware.os.vm().current_cartridge_app_mode(),
};
}
self.debug_cartridge.clone().unwrap_or_else(|| HandshakeCartridge {
app_id,
title: firmware.os.vm().current_cartridge_title(),
app_version: firmware.os.vm().current_cartridge_app_version(),
app_mode: firmware.os.vm().current_cartridge_app_mode(),
})
}
pub(crate) fn cert_event_from_snapshot(
tag: u16,
telemetry: TelemetryFrame,
@@ -315,7 +337,7 @@ impl HostDebugger {
// Map specific internal log tags to protocol events.
if event.tag == 0xDEB1 {
self.send_event(DebugEvent::BreakpointHit {
pc: firmware.vm.pc(),
pc: firmware.os.vm().active_pc().unwrap_or(0),
frame_index: firmware.os.vm().logical_frame_index(),
});
}
@@ -372,7 +394,7 @@ impl HostDebugger {
#[cfg(test)]
mod tests {
use super::*;
use prometeu_drivers::hardware::Hardware;
use prometeu_drivers::TestPlatform;
use prometeu_hal::debugger_protocol::DebugCommand;
#[test]
@@ -396,29 +418,75 @@ mod tests {
fn handle_command_updates_pause_and_step_flags_without_host_io() {
let mut debugger = HostDebugger::new();
let mut firmware = Firmware::new(None);
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
debugger.handle_command(DebugCommand::Pause, &mut firmware, &mut hardware);
debugger.handle_command(DebugCommand::Pause, &mut firmware, &mut platform);
assert!(firmware.os.vm().paused());
debugger.handle_command(DebugCommand::Resume, &mut firmware, &mut hardware);
debugger.handle_command(DebugCommand::Resume, &mut firmware, &mut platform);
assert!(!firmware.os.vm().paused());
debugger.handle_command(DebugCommand::StepFrame, &mut firmware, &mut hardware);
debugger.handle_command(DebugCommand::StepFrame, &mut firmware, &mut platform);
assert!(!firmware.os.vm().paused());
assert!(firmware.os.vm().debug_step_requested());
}
#[test]
fn breakpoint_commands_mutate_active_vm_session() {
let mut debugger = HostDebugger::new();
let mut firmware = Firmware::new(None);
let mut platform = TestPlatform::new();
let task_id = firmware
.os
.sessions()
.try_create_vm_game_task(42, "Sector Crawl")
.expect("debugger test should create a game session");
debugger.handle_command(
DebugCommand::SetBreakpoint { pc: 123 },
&mut firmware,
&mut platform,
);
assert_eq!(
firmware
.os
.sessions()
.vm_session_for_task(task_id)
.expect("game VM session should exist")
.vm
.breakpoints_list(),
vec![123]
);
debugger.handle_command(
DebugCommand::ClearBreakpoint { pc: 123 },
&mut firmware,
&mut platform,
);
assert!(
firmware
.os
.sessions()
.vm_session_for_task(task_id)
.expect("game VM session should exist")
.vm
.breakpoints_list()
.is_empty()
);
}
#[test]
fn handle_command_start_leaves_waiting_for_start_mode() {
let mut debugger = HostDebugger::new();
let mut firmware = Firmware::new(None);
let mut hardware = Hardware::new();
let mut platform = TestPlatform::new();
debugger.waiting_for_start = true;
firmware.os.vm().set_paused(true);
debugger.handle_command(DebugCommand::Start, &mut firmware, &mut hardware);
debugger.handle_command(DebugCommand::Start, &mut firmware, &mut platform);
assert!(!debugger.waiting_for_start);
assert!(!firmware.os.vm().paused());
@@ -1,4 +1,3 @@
use prometeu_drivers::hardware::Hardware;
use prometeu_hal::InputSignals;
use winit::event::{ElementState, MouseButton, WindowEvent};
use winit::keyboard::{KeyCode, PhysicalKey};
@@ -14,7 +13,7 @@ struct FbViewport {
}
impl FbViewport {
fn framebuffer_viewport(window: &Window) -> Option<FbViewport> {
fn framebuffer_viewport(window: &Window, display_size: (usize, usize)) -> Option<FbViewport> {
let size = window.inner_size();
let win_w = size.width as f32;
@@ -24,8 +23,8 @@ impl FbViewport {
return None;
}
let fb_w = Hardware::W as f32;
let fb_h = Hardware::H as f32;
let fb_w = display_size.0 as f32;
let fb_h = display_size.1 as f32;
let scale_x = (win_w / fb_w).floor();
let scale_y = (win_h / fb_h).floor();
@@ -44,50 +43,87 @@ impl FbViewport {
pub struct HostInputHandler {
pub signals: InputSignals,
system_controls: HostSystemControls,
display_size: (usize, usize),
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct HostSystemControls {
home_requested: bool,
}
impl HostSystemControls {
pub fn request_home(&mut self) {
self.home_requested = true;
}
pub fn take_home_requested(&mut self) -> bool {
let requested = self.home_requested;
self.home_requested = false;
requested
}
}
impl Default for HostInputHandler {
fn default() -> Self {
Self::new()
Self::new((480, 270))
}
}
impl HostInputHandler {
pub fn new() -> Self {
Self { signals: InputSignals::default() }
pub fn new(display_size: (usize, usize)) -> Self {
Self {
signals: InputSignals::default(),
system_controls: HostSystemControls::default(),
display_size,
}
}
pub fn take_home_requested(&mut self) -> bool {
self.system_controls.take_home_requested()
}
pub fn clear_guest_signals(&mut self) {
self.signals = InputSignals::default();
}
pub fn handle_key_code(&mut self, code: KeyCode, state: ElementState) {
let is_down = state == ElementState::Pressed;
match code {
KeyCode::Escape | KeyCode::Home if is_down => self.system_controls.request_home(),
KeyCode::ArrowUp => self.signals.up_signal = is_down,
KeyCode::ArrowDown => self.signals.down_signal = is_down,
KeyCode::ArrowLeft => self.signals.left_signal = is_down,
KeyCode::ArrowRight => self.signals.right_signal = is_down,
KeyCode::KeyA => self.signals.a_signal = is_down,
KeyCode::KeyD => self.signals.b_signal = is_down,
KeyCode::KeyW => self.signals.x_signal = is_down,
KeyCode::KeyS => self.signals.y_signal = is_down,
KeyCode::KeyQ => self.signals.l_signal = is_down,
KeyCode::KeyE => self.signals.r_signal = is_down,
KeyCode::KeyZ => self.signals.start_signal = is_down,
KeyCode::ShiftLeft | KeyCode::ShiftRight => self.signals.select_signal = is_down,
_ => {}
}
}
pub fn handle_event(&mut self, event: &WindowEvent, window: &Window) {
match event {
WindowEvent::KeyboardInput { event, .. } => {
if let PhysicalKey::Code(code) = event.physical_key {
let is_down = event.state == ElementState::Pressed;
match code {
KeyCode::ArrowUp => self.signals.up_signal = is_down,
KeyCode::ArrowDown => self.signals.down_signal = is_down,
KeyCode::ArrowLeft => self.signals.left_signal = is_down,
KeyCode::ArrowRight => self.signals.right_signal = is_down,
KeyCode::KeyA => self.signals.a_signal = is_down,
KeyCode::KeyD => self.signals.b_signal = is_down,
KeyCode::KeyW => self.signals.x_signal = is_down,
KeyCode::KeyS => self.signals.y_signal = is_down,
KeyCode::KeyQ => self.signals.l_signal = is_down,
KeyCode::KeyE => self.signals.r_signal = is_down,
KeyCode::KeyZ => self.signals.start_signal = is_down,
KeyCode::ShiftLeft | KeyCode::ShiftRight => {
self.signals.select_signal = is_down
}
_ => {}
}
self.handle_key_code(code, event.state);
}
}
WindowEvent::CursorMoved { position, .. } => {
if let Some((x, y)) = window_to_fb(position.x as f32, position.y as f32, window) {
if let Some((x, y)) =
window_to_fb(position.x as f32, position.y as f32, window, self.display_size)
{
self.signals.x_pos = x;
self.signals.y_pos = y;
}
@@ -107,8 +143,13 @@ impl HostInputHandler {
_ => {}
}
fn window_to_fb(wx: f32, wy: f32, window: &Window) -> Option<(i32, i32)> {
let viewport = FbViewport::framebuffer_viewport(window)?;
fn window_to_fb(
wx: f32,
wy: f32,
window: &Window,
display_size: (usize, usize),
) -> Option<(i32, i32)> {
let viewport = FbViewport::framebuffer_viewport(window, display_size)?;
let local_x = wx - viewport.x;
let local_y = wy - viewport.y;
@@ -120,7 +161,88 @@ impl HostInputHandler {
let fb_x = (local_x / viewport.scale).floor() as i32;
let fb_y = (local_y / viewport.scale).floor() as i32;
Some((fb_x.clamp(0, Hardware::W as i32 - 1), fb_y.clamp(0, Hardware::H as i32 - 1)))
Some((
fb_x.clamp(0, display_size.0 as i32 - 1),
fb_y.clamp(0, display_size.1 as i32 - 1),
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_no_pad_signal(signals: InputSignals) {
assert!(!signals.up_signal);
assert!(!signals.down_signal);
assert!(!signals.left_signal);
assert!(!signals.right_signal);
assert!(!signals.a_signal);
assert!(!signals.b_signal);
assert!(!signals.x_signal);
assert!(!signals.y_signal);
assert!(!signals.l_signal);
assert!(!signals.r_signal);
assert!(!signals.start_signal);
assert!(!signals.select_signal);
assert!(!signals.f_signal);
}
#[test]
fn escape_requests_home_without_mutating_guest_pad() {
let mut input = HostInputHandler::default();
input.handle_key_code(KeyCode::Escape, ElementState::Pressed);
assert!(input.take_home_requested());
assert!(!input.take_home_requested());
assert_no_pad_signal(input.signals);
}
#[test]
fn physical_home_requests_home_without_mutating_guest_pad() {
let mut input = HostInputHandler::default();
input.handle_key_code(KeyCode::Home, ElementState::Pressed);
assert!(input.take_home_requested());
assert_no_pad_signal(input.signals);
}
#[test]
fn home_release_does_not_emit_a_new_home_request() {
let mut input = HostInputHandler::default();
input.handle_key_code(KeyCode::Home, ElementState::Released);
assert!(!input.take_home_requested());
assert_no_pad_signal(input.signals);
}
#[test]
fn existing_keyboard_pad_mapping_is_preserved() {
let mut input = HostInputHandler::default();
input.handle_key_code(KeyCode::KeyZ, ElementState::Pressed);
input.handle_key_code(KeyCode::ShiftLeft, ElementState::Pressed);
input.handle_key_code(KeyCode::ArrowUp, ElementState::Pressed);
assert!(input.signals.start_signal);
assert!(input.signals.select_signal);
assert!(input.signals.up_signal);
assert!(!input.take_home_requested());
}
#[test]
fn clearing_guest_signals_preserves_system_home_control() {
let mut input = HostInputHandler::default();
input.handle_key_code(KeyCode::ArrowUp, ElementState::Pressed);
input.handle_key_code(KeyCode::Escape, ElementState::Pressed);
input.clear_guest_signals();
assert_no_pad_signal(input.signals);
assert!(input.take_home_requested());
}
}
@@ -33,6 +33,10 @@ struct Cli {
#[arg(long, value_name = "PATH")]
fs_root: Option<String>,
/// Root directory for local game cartridge discovery
#[arg(long, value_name = "PATH")]
games_root: Option<String>,
/// Path to the capability configuration file
#[arg(long, value_name = "PATH")]
cap: Option<String>,
@@ -55,6 +59,9 @@ pub fn run() -> Result<(), Box<dyn std::error::Error>> {
let event_loop = EventLoop::new()?;
let mut runner = HostRunner::new(fs_root, cap_config);
if let Some(games_root) = cli.games_root {
runner.set_games_root(games_root);
}
runner.set_boot_target(boot_target);
event_loop.run_app(&mut runner)?;
@@ -4,13 +4,16 @@ use crate::fs_backend::HostDirBackend;
use crate::input::HostInputHandler;
use crate::log_sink::HostConsoleSink;
use crate::stats::HostStats;
use crate::utilities::draw_rgba8888_to_rgba8;
use crate::utilities::{draw_owned_rgba8888_frame_to_rgba8, draw_rgba8888_to_rgba8};
use pixels::wgpu::PresentMode;
use pixels::{Pixels, PixelsBuilder, SurfaceTexture};
use prometeu_drivers::AudioCommand;
use prometeu_drivers::hardware::Hardware;
use prometeu_drivers::{AudioCommand, LocalFramebufferRenderBackend, MemoryBanks};
use prometeu_firmware::{BootTarget, Firmware, FirmwareState};
use prometeu_hal::telemetry::CertificationConfig;
use prometeu_hal::{OwnedRgba8888Frame, RenderOwnership, RuntimePlatform};
use prometeu_system::{LatestRenderFrameStore, RenderWorkerConfig, discover_games_root};
use std::sync::Arc;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
@@ -23,16 +26,22 @@ const IDLE_HOST_POLL_DT: Duration = Duration::from_millis(100);
#[derive(Debug, Clone)]
struct PresentationState {
latest_published_frame: u64,
last_presented_frame: Option<u64>,
latest_published_frame: Option<PresentationFrameMarker>,
last_presented_frame: Option<PresentationFrameMarker>,
host_invalidated: bool,
redraw_requested: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PresentationFrameMarker {
ownership: RenderOwnership,
frame_id: u64,
}
impl Default for PresentationState {
fn default() -> Self {
Self {
latest_published_frame: 0,
latest_published_frame: None,
last_presented_frame: None,
host_invalidated: true,
redraw_requested: false,
@@ -41,9 +50,10 @@ impl Default for PresentationState {
}
impl PresentationState {
fn note_published_frame(&mut self, frame_index: u64) {
if frame_index > self.latest_published_frame {
self.latest_published_frame = frame_index;
fn note_published_frame(&mut self, ownership: RenderOwnership, frame_id: u64) {
let marker = PresentationFrameMarker { ownership, frame_id };
if self.latest_published_frame != Some(marker) {
self.latest_published_frame = Some(marker);
}
}
@@ -52,7 +62,7 @@ impl PresentationState {
}
fn needs_redraw(&self) -> bool {
self.host_invalidated || self.last_presented_frame != Some(self.latest_published_frame)
self.host_invalidated || self.last_presented_frame != self.latest_published_frame
}
fn should_request_redraw(&mut self) -> bool {
@@ -67,7 +77,7 @@ impl PresentationState {
fn mark_presented(&mut self) {
self.redraw_requested = false;
self.host_invalidated = false;
self.last_presented_frame = Some(self.latest_published_frame);
self.last_presented_frame = self.latest_published_frame;
}
}
@@ -85,6 +95,14 @@ fn desired_control_flow(
}
}
fn should_present_worker_frame(
state: &FirmwareState,
frame: &OwnedRgba8888Frame,
active_ownership: RenderOwnership,
) -> bool {
matches!(state, FirmwareState::GameRunning(_)) && frame.ownership == active_ownership
}
/// The Desktop implementation of the PROMETEU Runtime.
///
/// This struct acts as the physical "chassis" of the virtual console. It is
@@ -131,6 +149,8 @@ pub struct HostRunner {
audio: HostAudio,
/// Last known pause state to sync with audio.
last_paused_state: bool,
/// Worker-published frame store used as the single observable publication source.
render_frame_store: LatestRenderFrameStore,
/// Tracks whether a new logical frame or host-only surface invalidation requires presentation.
presentation: PresentationState,
}
@@ -142,6 +162,18 @@ impl HostRunner {
self.debugger.setup_boot_target(&boot_target, &mut self.firmware);
}
pub(crate) fn set_games_root(&mut self, games_root: String) {
let library = discover_games_root(&games_root);
for diagnostic in library.diagnostics() {
eprintln!(
"games-root: omitted candidate {}: {:?}",
diagnostic.path.display(),
diagnostic.reason
);
}
self.firmware.hub.set_game_library(library);
}
/// Creates a new desktop runner instance.
pub(crate) fn new(fs_root: Option<String>, cap_config: Option<CertificationConfig>) -> Self {
let target_fps = 60;
@@ -152,12 +184,28 @@ impl HostRunner {
firmware.os.fs().mount(Box::new(backend));
}
let memory_banks = Arc::new(MemoryBanks::new());
let hardware = Hardware::new_with_memory_banks(Arc::clone(&memory_banks));
let display_size = hardware.display_size();
let worker_backend = LocalFramebufferRenderBackend::new_with_memory_banks(
display_size.0,
display_size.1,
memory_banks,
hardware.assets.glyph_asset_slot_index(),
);
let render_frame_store = LatestRenderFrameStore::default();
firmware.os.vm().start_render_worker(
RenderWorkerConfig::default(),
worker_backend,
render_frame_store.clone(),
);
Self {
window: None,
pixels: None,
hardware: Hardware::new(),
hardware,
firmware,
input: HostInputHandler::new(),
input: HostInputHandler::new(display_size),
fs_root,
log_sink: HostConsoleSink::new(),
frame_target_dt: Duration::from_nanos(1_000_000_000 / target_fps),
@@ -168,6 +216,7 @@ impl HostRunner {
debugger: HostDebugger::new(),
audio: HostAudio::new(),
last_paused_state: false,
render_frame_store,
presentation: PresentationState::default(),
}
}
@@ -221,18 +270,20 @@ impl ApplicationHandler for HostRunner {
let window = event_loop.create_window(attrs).expect("failed to create window");
// 🔥 Leak: Window becomes &'static Window (bootstrap)
// `pixels` stores a surface tied to the window lifetime. The current
// winit runner owns one process-lifetime window, so we intentionally
// promote it to a static reference for the duration of the host process.
let window: &'static Window = Box::leak(Box::new(window));
self.window = Some(window);
let size = window.inner_size();
let surface_texture = SurfaceTexture::new(size.width, size.height, window);
let mut pixels =
PixelsBuilder::new(Hardware::W as u32, Hardware::H as u32, surface_texture)
.present_mode(PresentMode::Fifo) // activate vsync
.build()
.expect("failed to create Pixels");
let (display_w, display_h) = self.hardware.display_size();
let mut pixels = PixelsBuilder::new(display_w as u32, display_h as u32, surface_texture)
.present_mode(PresentMode::Fifo)
.build()
.expect("failed to create Pixels");
pixels.frame_mut().fill(0);
@@ -267,18 +318,29 @@ impl ApplicationHandler for HostRunner {
}
WindowEvent::RedrawRequested => {
// Get Pixels directly from the field (not via helper that gets the entire &mut self)
let pixels = self.pixels.as_mut().expect("pixels not initialized");
{
// Mutable borrow of the frame (lasts only within this block)
let frame = pixels.frame_mut();
// Immutable borrow of prometeu-core (different field, ok)
let src = self.hardware.gfx.front_buffer();
draw_rgba8888_to_rgba8(src, frame);
} // <- frame borrow ends here
let active_ownership = self.firmware.os.vm().active_render_ownership();
if let Some(worker_frame) = self.render_frame_store.latest_frame()
&& should_present_worker_frame(
&self.firmware.state,
&worker_frame,
active_ownership,
)
{
self.firmware
.os
.vm()
.record_repeated_render_worker_frame(worker_frame.frame_id);
draw_owned_rgba8888_frame_to_rgba8(&worker_frame, frame);
} else {
let src = self.hardware.gfx.front_buffer();
draw_rgba8888_to_rgba8(src, frame);
}
}
if pixels.render().is_err() {
event_loop.exit();
@@ -326,6 +388,13 @@ impl ApplicationHandler for HostRunner {
self.firmware.os.fs().mount(Box::new(backend));
}
if self.input.take_home_requested() {
self.input.clear_guest_signals();
self.firmware.request_home_from_host();
self.invalidate_host_surface();
self.request_redraw_if_needed();
}
// 3. Timing Management (The heart of determinism).
// We measure the elapsed time since the last iteration and add it to an
// accumulator. We then execute exactly as many 60Hz slices as the
@@ -342,7 +411,7 @@ impl ApplicationHandler for HostRunner {
self.last_frame_time = now;
self.accumulator += frame_delta;
// 🔥 Logic Update Loop: consumes time in exact 60Hz (16.66ms) slices.
// Consume time in exact 60Hz slices.
while self.accumulator >= self.frame_target_dt {
// Unless the debugger is waiting for a 'start' command, advance the system.
if !self.debugger.waiting_for_start {
@@ -353,7 +422,10 @@ impl ApplicationHandler for HostRunner {
// Sync pause state with audio.
// We do this AFTER firmware.tick to avoid MasterPause/Resume commands
// being cleared by the OS if a new logical frame starts in this tick.
let is_paused = self.firmware.os.vm().paused() || self.debugger.waiting_for_start;
let lifecycle_audio_paused = self.firmware.game_lifecycle_audio_paused();
let is_paused = lifecycle_audio_paused
|| self.firmware.os.vm().paused()
|| self.debugger.waiting_for_start;
if is_paused != self.last_paused_state {
self.last_paused_state = is_paused;
let cmd =
@@ -368,7 +440,16 @@ impl ApplicationHandler for HostRunner {
self.stats.record_frame();
}
self.presentation.note_published_frame(self.firmware.os.frame_index());
let active_ownership = self.firmware.os.vm().active_render_ownership();
if let Some(worker_frame) = self.render_frame_store.latest_frame()
&& should_present_worker_frame(&self.firmware.state, &worker_frame, active_ownership)
{
self.presentation
.note_published_frame(worker_frame.ownership, worker_frame.frame_id.get());
} else {
self.presentation
.note_published_frame(active_ownership, self.firmware.os.frame_index());
}
if was_debugger_connected != self.debugger.stream.is_some()
|| was_waiting_for_start != self.debugger.waiting_for_start
@@ -381,7 +462,7 @@ impl ApplicationHandler for HostRunner {
self.audio.update_stats(&mut self.stats);
// Update technical statistics displayed in the window title.
self.stats.update(now, self.window, &self.hardware, &mut self.firmware);
self.stats.update(now, self.window, &mut self.firmware);
// Synchronize system logs to the host console.
let last_seq = self.log_sink.last_seq().unwrap_or(u64::MAX);
@@ -408,8 +489,14 @@ impl ApplicationHandler for HostRunner {
mod tests {
use super::*;
use prometeu_firmware::BootTarget;
use prometeu_firmware::firmware::firmware_state::{
GameRunningStep, HubHomeStep, ShellRunningStep,
};
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::debugger_protocol::DEVTOOLS_PROTOCOL_VERSION;
use prometeu_hal::telemetry::{CertificationConfig, TelemetryFrame};
use prometeu_hal::{FrameId, OwnedRgba8888Frame, RenderOwnership, RenderWorkerFrameSink};
use prometeu_system::task::TaskId;
use std::io::{Read, Write};
use std::net::TcpStream;
@@ -427,14 +514,37 @@ mod tests {
#[test]
fn presentation_state_requests_redraw_for_new_frame_publication() {
let ownership = RenderOwnership::new(1, AppMode::Game, 1);
let mut state = PresentationState::default();
state.mark_presented();
state.note_published_frame(1);
state.note_published_frame(ownership, 1);
assert!(state.should_request_redraw());
state.mark_presented();
assert_eq!(state.last_presented_frame, Some(1));
assert_eq!(
state.last_presented_frame,
Some(PresentationFrameMarker { ownership, frame_id: 1 })
);
}
#[test]
fn presentation_state_requests_redraw_when_ownership_changes_with_lower_frame_id() {
let first = RenderOwnership::new(3, AppMode::Game, 1);
let next = RenderOwnership::new(4, AppMode::Game, 2);
let mut state = PresentationState::default();
state.note_published_frame(first, 120);
state.mark_presented();
state.note_published_frame(next, 0);
assert!(state.should_request_redraw());
state.mark_presented();
assert_eq!(
state.last_presented_frame,
Some(PresentationFrameMarker { ownership: next, frame_id: 0 })
);
}
#[test]
@@ -477,6 +587,69 @@ mod tests {
}
}
#[test]
fn worker_frame_presentation_requires_game_state_and_current_ownership() {
let active = RenderOwnership::new(3, AppMode::Game, 1);
let current = OwnedRgba8888Frame::packed(FrameId::new(9), active, 1, 1, vec![0xFF00FFFF])
.expect("test frame");
let stale = OwnedRgba8888Frame::packed(
FrameId::new(8),
RenderOwnership::new(2, AppMode::Game, 1),
1,
1,
vec![0xFF00FFFF],
)
.expect("test frame");
assert!(should_present_worker_frame(
&FirmwareState::GameRunning(GameRunningStep::new(TaskId(1))),
&current,
active,
));
assert!(!should_present_worker_frame(
&FirmwareState::GameRunning(GameRunningStep::new(TaskId(1),)),
&stale,
active,
));
assert!(!should_present_worker_frame(
&FirmwareState::ShellRunning(ShellRunningStep::new(TaskId(2))),
&current,
active,
));
assert!(!should_present_worker_frame(
&FirmwareState::HubHome(HubHomeStep),
&current,
active,
));
}
#[test]
fn host_presentation_observes_worker_publication_store() {
let store = LatestRenderFrameStore::default();
let frame = OwnedRgba8888Frame::packed(
FrameId::new(9),
RenderOwnership::new(1, AppMode::Game, 1),
1,
1,
vec![0xFF00FFFF],
)
.expect("test frame");
store.publish(frame).expect("store publish");
let mut presentation = PresentationState::default();
presentation.mark_presented();
let published = store.latest_frame().expect("published frame");
presentation.note_published_frame(published.ownership, published.frame_id.get());
assert!(presentation.should_request_redraw());
presentation.mark_presented();
assert_eq!(
presentation.last_presented_frame,
Some(PresentationFrameMarker { ownership: published.ownership, frame_id: 9 })
);
}
#[test]
fn host_debugger_maps_cert_events_from_host_owned_sources() {
let telemetry = TelemetryFrame {
@@ -1,4 +1,3 @@
use prometeu_drivers::hardware::Hardware;
use prometeu_firmware::Firmware;
use std::time::{Duration, Instant};
use winit::window::Window;
@@ -60,13 +59,7 @@ impl HostStats {
}
}
pub fn update(
&mut self,
now: Instant,
window: Option<&Window>,
_hardware: &Hardware,
firmware: &mut Firmware,
) {
pub fn update(&mut self, now: Instant, window: Option<&Window>, firmware: &mut Firmware) {
let stats_elapsed = now.duration_since(self.last_stats_update);
if stats_elapsed >= Duration::from_secs(1) {
self.current_fps = self.frames_since_last_update as f64 / stats_elapsed.as_secs_f64();
@@ -1,3 +1,5 @@
use prometeu_hal::OwnedRgba8888Frame;
/// Copies RGBA8888 pixels in canonical RGBA raw order into the `pixels` RGBA8 frame.
pub fn draw_rgba8888_to_rgba8(src: &[u32], dst_rgba: &mut [u8]) {
for (i, &px) in src.iter().enumerate() {
@@ -9,9 +11,15 @@ pub fn draw_rgba8888_to_rgba8(src: &[u32], dst_rgba: &mut [u8]) {
}
}
pub fn draw_owned_rgba8888_frame_to_rgba8(frame: &OwnedRgba8888Frame, dst_rgba: &mut [u8]) {
draw_rgba8888_to_rgba8(&frame.pixels[..frame.required_pixel_len()], dst_rgba);
}
#[cfg(test)]
mod tests {
use super::draw_rgba8888_to_rgba8;
use super::{draw_owned_rgba8888_frame_to_rgba8, draw_rgba8888_to_rgba8};
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::{FrameId, OwnedRgba8888Frame, RenderOwnership};
#[test]
fn draw_rgba8888_to_rgba8_preserves_channel_order_and_alpha() {
@@ -22,4 +30,21 @@ mod tests {
assert_eq!(dst, [0x12, 0x34, 0x56, 0x78, 0xAB, 0xCD, 0xEF, 0x01]);
}
#[test]
fn draw_owned_frame_to_rgba8_uses_owned_rgba8888_pixels() {
let frame = OwnedRgba8888Frame::packed(
FrameId::new(3),
RenderOwnership::new(1, AppMode::Game, 7),
1,
1,
vec![0x10203040],
)
.expect("test frame should be valid");
let mut dst = [0; 4];
draw_owned_rgba8888_frame_to_rgba8(&frame, &mut dst);
assert_eq!(dst, [0x10, 0x20, 0x30, 0x40]);
}
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "pbxgen-dummy-boy"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1"
prometeu-bytecode = { path = "../../console/prometeu-bytecode" }
prometeu-hal = { path = "../../console/prometeu-hal" }
[dev-dependencies]
serde_json = "1"
+147
View File
@@ -0,0 +1,147 @@
use anyhow::Result;
use prometeu_bytecode::assembler::assemble;
use prometeu_bytecode::model::{BytecodeModule, DebugInfo, Export, FunctionMeta, SyscallDecl};
use prometeu_hal::color::Color;
use std::fs;
use std::path::PathBuf;
const APP_ID: u32 = 2;
const TITLE: &str = "Dummy Boy";
const APP_VERSION: &str = "0.1.0";
fn asm(s: &str) -> Vec<u8> {
assemble(s).expect("assemble")
}
pub fn generate() -> Result<()> {
let out_dir = cartridge_dir();
fs::create_dir_all(&out_dir)?;
fs::write(out_dir.join("program.pbx"), build_program())?;
fs::write(out_dir.join("manifest.json"), manifest_json())?;
Ok(())
}
pub fn build_program() -> Vec<u8> {
let mut rom = Vec::new();
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 1\nADD\nSET_GLOBAL 0"));
rom.extend(asm(&format!("PUSH_I64 {}\nHOSTCALL 0", Color::BLACK.raw())));
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 3\nMOD\nPUSH_I32 0\nEQ"));
let jump_to_green_case_offset = rom.len() + 2;
rom.extend(asm("JMP_IF_FALSE 0"));
rom.extend(asm(&format!("PUSH_I64 {}\nSET_LOCAL 0", Color::RED.raw())));
let jump_to_draw_after_red_offset = rom.len() + 2;
rom.extend(asm("JMP 0"));
let green_case = rom.len() as u32;
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 3\nMOD\nPUSH_I32 1\nEQ"));
let jump_to_blue_case_offset = rom.len() + 2;
rom.extend(asm("JMP_IF_FALSE 0"));
rom.extend(asm(&format!("PUSH_I64 {}\nSET_LOCAL 0", Color::GREEN.raw())));
let jump_to_draw_after_green_offset = rom.len() + 2;
rom.extend(asm("JMP 0"));
let blue_case = rom.len() as u32;
rom.extend(asm(&format!("PUSH_I64 {}\nSET_LOCAL 0", Color::BLUE.raw())));
let draw = rom.len() as u32;
rom.extend(asm(&format!(
"PUSH_I32 180\n\
PUSH_I32 75\n\
PUSH_I32 120\n\
PUSH_I32 120\n\
PUSH_I64 {}\n\
GET_LOCAL 0\n\
HOSTCALL 1\n\
FRAME_SYNC\n\
RET",
Color::WHITE.raw()
)));
patch_jump(&mut rom, jump_to_green_case_offset, green_case);
patch_jump(&mut rom, jump_to_draw_after_red_offset, draw);
patch_jump(&mut rom, jump_to_blue_case_offset, blue_case);
patch_jump(&mut rom, jump_to_draw_after_green_offset, draw);
BytecodeModule {
version: 0,
const_pool: vec![],
functions: vec![FunctionMeta {
code_offset: 0,
code_len: rom.len() as u32,
param_slots: 0,
local_slots: 1,
return_slots: 0,
max_stack_slots: 8,
}],
code: rom,
debug_info: Some(DebugInfo {
pc_to_span: vec![],
function_names: vec![(0, "main".into())],
}),
exports: vec![Export { symbol: "main".into(), func_idx: 0 }],
syscalls: vec![
SyscallDecl {
module: "gfx2d".into(),
name: "clear".into(),
version: 1,
arg_slots: 1,
ret_slots: 0,
},
SyscallDecl {
module: "gfx2d".into(),
name: "draw_square".into(),
version: 1,
arg_slots: 6,
ret_slots: 0,
},
],
}
.serialize()
}
pub fn manifest_json() -> Vec<u8> {
format!(
"{{\n \"magic\": \"PMTU\",\n \"cartridge_version\": 1,\n \"app_id\": {APP_ID},\n \"title\": \"{TITLE}\",\n \"app_version\": \"{APP_VERSION}\",\n \"app_mode\": \"Game\",\n \"capabilities\": [\"gfx2d\"]\n}}\n"
)
.into_bytes()
}
fn cartridge_dir() -> PathBuf {
let mut out_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
out_dir.pop();
out_dir.pop();
out_dir.pop();
out_dir.push("test-cartridges");
out_dir.push("dummy-boy");
out_dir
}
fn patch_jump(buf: &mut [u8], imm_offset: usize, target: u32) {
buf[imm_offset..imm_offset + 4].copy_from_slice(&target.to_le_bytes());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generated_program_is_pbx_module_with_expected_syscalls() {
let bytes = build_program();
assert!(bytes.starts_with(&prometeu_bytecode::PBX_MAGIC));
assert!(bytes.len() > 64);
}
#[test]
fn manifest_declares_distinct_game_identity() {
let manifest: serde_json::Value =
serde_json::from_slice(&manifest_json()).expect("manifest should parse");
assert_eq!(manifest["app_id"], APP_ID);
assert_eq!(manifest["title"], TITLE);
assert_eq!(manifest["app_mode"], "Game");
assert_eq!(manifest["capabilities"], serde_json::json!(["gfx2d"]));
}
}
@@ -0,0 +1,5 @@
use anyhow::Result;
fn main() -> Result<()> {
pbxgen_dummy_boy::generate()
}
+6 -6
View File
@@ -14,7 +14,7 @@ use prometeu_hal::cartridge::{
use prometeu_hal::color::Color;
use prometeu_hal::glyph::Glyph;
use prometeu_hal::glyph_bank::{
TileSize, GLYPH_BANK_COLORS_PER_PALETTE, GLYPH_BANK_PALETTE_COUNT_V1,
TileSize, GLYPH_BANK_COLORS_PER_PALETTE, GLYPH_BANK_MAX_PALETTE_COUNT_V1,
};
use prometeu_hal::scene_bank::SceneBank;
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
@@ -275,15 +275,15 @@ fn build_glyph_asset() -> (AssetEntry, Vec<u8>) {
bank_type: BankType::GLYPH,
offset: 0,
size: payload.len() as u64,
decoded_size: (8 * 8 + GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4)
decoded_size: (8 * 8 + GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4)
as u64,
codec: AssetCodec::None,
metadata: serde_json::json!({
"tile_size": 8,
"width": 8,
"height": 8,
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
}),
};
@@ -292,8 +292,8 @@ fn build_glyph_asset() -> (AssetEntry, Vec<u8>) {
fn build_palette_bytes() -> Vec<u8> {
let mut bytes =
Vec::with_capacity(GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4);
for palette_id in 0..GLYPH_BANK_PALETTE_COUNT_V1 {
Vec::with_capacity(GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4);
for palette_id in 0..GLYPH_BANK_MAX_PALETTE_COUNT_V1 {
for color_index in 0..GLYPH_BANK_COLORS_PER_PALETTE {
let color = if color_index == 1 { stress_color(palette_id) } else { Color::BLACK };
bytes.extend_from_slice(&color.raw().to_be_bytes());
View File
+12 -6
View File
@@ -1,8 +1,10 @@
{"type":"meta","next_id":{"DSC":43,"AGD":44,"DEC":33,"PLN":110,"LSN":49,"CLSN":1}}
{"type":"meta","next_id":{"DSC":49,"AGD":52,"DEC":43,"PLN":174,"LSN":57,"CLSN":1}}
{"type":"discussion","id":"DSC-0044","status":"done","ticket":"hub-suspended-game-kill-affordance","title":"Hub Suspended Game Kill Affordance","created_at":"2026-07-05","updated_at":"2026-07-05","tags":["hub","lifecycle","game","ui"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0054","file":"discussion/lessons/DSC-0044-hub-suspended-game-kill-affordance/LSN-0054-manual-hub-kill-must-share-game-termination-cleanup.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
{"type":"discussion","id":"DSC-0043","status":"done","ticket":"system-os-cartridge-switch-orchestrator","title":"SystemOS Cartridge Switch Orchestrator","created_at":"2026-07-03","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","game","cartridge","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0053","file":"discussion/lessons/DSC-0043-system-os-cartridge-switch-orchestrator/LSN-0053-game-switching-is-lifecycle-replacement-not-loader-work.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
{"type":"discussion","id":"DSC-0039","status":"abandoned","ticket":"render-pipeline-family-and-future-3d","title":"Render Pipeline Family and Future 3D","created_at":"2026-06-04","updated_at":"2026-06-04","tags":["gfx","renderer","runtime","architecture","pipeline"],"agendas":[{"id":"AGD-0039","file":"AGD-0039-render-pipeline-family-and-future-3d.md","status":"abandoned","created_at":"2026-06-04","updated_at":"2026-06-04","_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}],"decisions":[],"plans":[],"lessons":[],"_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}
{"type":"discussion","id":"DSC-0040","status":"done","ticket":"vm-render-parallel-execution-boundary","title":"VM and Render Parallel Execution Boundary","created_at":"2026-06-04","updated_at":"2026-06-06","tags":["runtime","renderer","vm","concurrency","architecture","perf"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0048","file":"discussion/lessons/DSC-0040-vm-render-parallel-execution-boundary/LSN-0048-render-workers-need-a-closed-packet-contract.md","status":"done","created_at":"2026-06-06","updated_at":"2026-06-06"}]}
{"type":"discussion","id":"DSC-0041","status":"open","ticket":"foreground-stack-game-pause-shell-vm-backed","title":"Foreground Stack, Game Pause, and VM-Backed Shell Coexistence","created_at":"2026-06-05","updated_at":"2026-06-05","tags":["runtime","os","lifecycle","shell","game","vm","foreground","architecture"],"agendas":[{"id":"AGD-0041","file":"AGD-0041-foreground-stack-game-pause-shell-vm-backed.md","status":"open","created_at":"2026-06-05","updated_at":"2026-06-05"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0042","status":"open","ticket":"real-render-worker-establishment","title":"Real Render Worker Establishment","created_at":"2026-06-06","updated_at":"2026-06-06","tags":["runtime","renderer","worker","concurrency","host","hal","architecture"],"agendas":[{"id":"AGD-0042","file":"AGD-0042-host-hardware-render-boundary-preparation.md","status":"accepted","created_at":"2026-06-06","updated_at":"2026-06-06"},{"id":"AGD-0043","file":"AGD-0043-real-render-worker-establishment.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06"}],"decisions":[{"id":"DEC-0032","file":"DEC-0032-platform-layer-and-hardwarebridge-elimination.md","status":"accepted","created_at":"2026-06-06","updated_at":"2026-06-06","ref_agenda":"AGD-0042"}],"plans":[{"id":"PLN-0098","file":"PLN-0098-define-platform-facade-contracts.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0099","file":"PLN-0099-introduce-owned-render-submission-sink.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0100","file":"PLN-0100-migrate-local-render-publication-to-sink.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0101","file":"PLN-0101-remove-immediate-gfx-syscall-rendering.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0102","file":"PLN-0102-introduce-game2d-frame-composer-service.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0103","file":"PLN-0103-introduce-runtime-platform-and-testplatform.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0104","file":"PLN-0104-migrate-vm-runtime-hostcontext-to-platform.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0105","file":"PLN-0105-migrate-firmware-and-hub-to-platform-services.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0106","file":"PLN-0106-migrate-desktop-host-to-platform-services.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0107","file":"PLN-0107-migrate-remaining-platform-domains.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0108","file":"PLN-0108-migrate-tests-to-testplatform.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]},{"id":"PLN-0109","file":"PLN-0109-remove-hardwarebridge-and-update-specs.md","status":"open","created_at":"2026-06-06","updated_at":"2026-06-06","ref_decisions":["DEC-0032"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0041","status":"done","ticket":"foreground-stack-game-pause-shell-vm-backed","title":"Foreground Stack, Game Pause, and VM-Backed Shell Coexistence","created_at":"2026-06-05","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","shell","game","vm","foreground","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0052","file":"discussion/lessons/DSC-0041-foreground-stack-game-pause-shell-vm-backed/LSN-0052-foreground-ownership-and-vm-session-ownership-are-separate.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
{"type":"discussion","id":"DSC-0042","status":"done","ticket":"real-render-worker-establishment","title":"Real Render Worker Establishment","created_at":"2026-06-06","updated_at":"2026-06-20","tags":["runtime","renderer","worker","concurrency","host","hal","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0049","file":"discussion/lessons/DSC-0042-real-render-worker-establishment/LSN-0049-render-worker-publication-boundary.md","status":"done","created_at":"2026-06-20","updated_at":"2026-06-20"}]}
{"type":"discussion","id":"DSC-0038","status":"done","ticket":"render-frame-packet-boundary","title":"Logical Render Pipelines and Command Packets","created_at":"2026-05-25","updated_at":"2026-06-04","tags":["gfx","renderer","runtime","frame-composer","architecture","ui","pipeline"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0047","file":"discussion/lessons/DSC-0038-render-frame-packet-boundary/LSN-0047-typed-render-submissions-preserve-domain-boundaries.md","status":"done","created_at":"2026-06-04","updated_at":"2026-06-04"}]}
{"type":"discussion","id":"DSC-0035","status":"done","ticket":"task-owned-shell-windows","title":"Agenda - Task-Owned Shell Windows","created_at":"2026-05-15","updated_at":"2026-05-15","tags":["runtime","os","task","window-manager","shell","lifecycle"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0044","file":"discussion/lessons/DSC-0035-task-owned-shell-windows/LSN-0044-task-window-liveness-belongs-to-the-task.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
{"type":"discussion","id":"DSC-0034","status":"done","ticket":"system-os-domain-facades","title":"Agenda - SystemOS Domain Facades","created_at":"2026-05-15","updated_at":"2026-05-15","tags":["runtime","os","services","api-surface","lifecycle","fs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0043","file":"discussion/lessons/DSC-0034-system-os-domain-facades/LSN-0043-systemos-domain-facades.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
@@ -13,14 +15,15 @@
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"legacy-runtime-learn-import","title":"Import legacy runtime learn into discussion lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["migration","tech-debt"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0001-prometeu-learn-index.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0002-historical-asset-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0003-historical-audio-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0004-historical-cartridge-boot-protocol-and-manifest-authority.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0005-historical-game-memcard-slots-surface-and-semantics.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0006-historical-gfx-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0007-historical-retired-fault-and-input-decisions.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0008-historical-vm-core-and-assets.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0009","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0009-mental-model-asset-management.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0010-mental-model-audio.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0011-mental-model-gfx.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0012-mental-model-input.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0013-mental-model-observability-and-debugging.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0014-mental-model-portability-and-cross-platform.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0015-mental-model-save-memory-and-memcard.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0016-mental-model-status-first-and-fault-thinking.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0017-mental-model-time-and-cycles.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0018","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0018-mental-model-touch.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"runtime-edge-test-plan","title":"Agenda - Runtime Edge Test Plan","created_at":"2026-03-27","updated_at":"2026-04-21","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0037","file":"discussion/lessons/DSC-0002-runtime-edge-test-plan/LSN-0037-domain-gates-must-be-owned-by-the-repository.md","status":"done","created_at":"2026-04-21","updated_at":"2026-04-21"}]}
{"type":"discussion","id":"DSC-0003","status":"open","ticket":"packed-cartridge-loader-pmc","title":"Agenda - Packed Cartridge Loader PMC","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0002","file":"AGD-0002-packed-cartridge-loader-pmc.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"system-run-cart","title":"Agenda - System Run Cart","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0003","file":"AGD-0003-system-run-cart.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0004","status":"done","ticket":"system-run-cart","title":"Agenda - System Run Cart","created_at":"2026-03-27","updated_at":"2026-07-03","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0051","file":"discussion/lessons/DSC-0004-system-run-cart/LSN-0051-launch-authority-belongs-to-systemos.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03"}]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"system-fault-semantics-and-control-surface","title":"Agenda - System Fault Semantics and Control Surface","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0004","file":"AGD-0004-system-fault-semantics-and-control-surface.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"open","ticket":"vm-owned-random-service","title":"Agenda - VM-Owned Random Service","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0005","file":"AGD-0005-vm-owned-random-service.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0007","status":"open","ticket":"app-home-filesystem-surface-and-semantics","title":"Agenda - App Home Filesystem Surface and Semantics","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0006","file":"AGD-0006-app-home-filesystem-surface-and-semantics.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0045","status":"open","ticket":"background-service-audio-execution","title":"Background Service and Audio Execution","created_at":"2026-07-05","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","service","audio","background","architecture"],"agendas":[{"id":"AGD-0048","file":"AGD-0048-background-service-audio-execution.md","status":"open","created_at":"2026-07-05","updated_at":"2026-07-05"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"perf-runtime-telemetry-hot-path","title":"Agenda - [PERF] Runtime Telemetry Hot Path","created_at":"2026-03-27","updated_at":"2026-06-04","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0008-perf-runtime-telemetry-hot-path/LSN-0026-push-based-telemetry-model.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0009","status":"open","ticket":"perf-async-background-work-lanes-for-assets-and-fs","title":"Agenda - [PERF] Async Background Work Lanes for Assets and FS","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0008","file":"AGD-0008-perf-async-background-work-lanes-for-assets-and-fs.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"perf-async-background-work-lanes-for-assets-and-fs","title":"Agenda - [PERF] Async Background Work Lanes for Assets and FS","created_at":"2026-03-27","updated_at":"2026-07-01","tags":["perf","asset","fs","async","scheduler","runtime"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0050","file":"discussion/lessons/DSC-0009-perf-async-background-work-lanes-for-assets-and-fs/LSN-0050-serial-async-lanes-bound-backlog-complexity.md","status":"done","created_at":"2026-07-01","updated_at":"2026-07-01"}]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"perf-host-desktop-frame-pacing-and-presentation","title":"Agenda - [PERF] Host Desktop Frame Pacing and Presentation","created_at":"2026-03-27","updated_at":"2026-04-20","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0010-perf-host-desktop-frame-pacing-and-presentation/LSN-0036-frame-publication-and-host-invalidation-must-be-separate.md","status":"done","created_at":"2026-04-20","updated_at":"2026-04-20"}]}
{"type":"discussion","id":"DSC-0011","status":"open","ticket":"perf-gfx-render-pipeline-and-dirty-regions","title":"Agenda - [PERF] GFX Render Pipeline and Dirty Regions","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0010","file":"AGD-0010-perf-gfx-render-pipeline-and-dirty-regions.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0011","status":"abandoned","ticket":"perf-gfx-render-pipeline-and-dirty-regions","title":"Agenda - [PERF] GFX Render Pipeline and Dirty Regions","created_at":"2026-03-27","updated_at":"2026-06-28","tags":[],"agendas":[{"id":"AGD-0010","file":"AGD-0010-perf-gfx-render-pipeline-and-dirty-regions.md","status":"abandoned","created_at":"2026-03-27","updated_at":"2026-06-28","_override_reason":"User explicitly chose to remove this agenda because it no longer applies to the current render scenario; future optimizations can be discussed when needed."}],"decisions":[],"plans":[],"lessons":[],"_override_reason":"User explicitly chose to abandon this discussion because it no longer applies to the current render scenario; future optimizations can be discussed when needed."}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"perf-runtime-introspection-syscalls","title":"Agenda - [PERF] Runtime Introspection Syscalls","created_at":"2026-03-27","updated_at":"2026-04-19","tags":["perf","runtime","syscall","telemetry","debug","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0034","file":"discussion/lessons/DSC-0012-perf-runtime-introspection-syscalls/LSN-0034-host-owned-debug-boundaries.md","status":"done","created_at":"2026-04-19","updated_at":"2026-04-19"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"perf-host-debug-overlay-isolation","title":"Agenda - [PERF] Host Debug Overlay Isolation","created_at":"2026-03-27","updated_at":"2026-04-10","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0013-perf-host-debug-overlay-isolation/LSN-0027-host-debug-overlay-isolation.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0024","status":"done","ticket":"generic-memory-bank-slot-contract","title":"Agenda - Generic Memory Bank Slot Contract","created_at":"2026-04-10","updated_at":"2026-04-10","tags":["runtime","asset","memory-bank","slots","host"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0029","file":"discussion/lessons/DSC-0024-generic-memory-bank-slot-contract/LSN-0029-slot-first-bank-telemetry-belongs-in-asset-manager.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
@@ -41,3 +44,6 @@
{"type":"discussion","id":"DSC-0033","status":"done","ticket":"system-os-service-ownership-and-module-layout","title":"Agenda - SystemOS Service Ownership and Module Layout","created_at":"2026-05-14","updated_at":"2026-05-15","tags":["runtime","os","services","module-layout","vm","window-manager","logging"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
{"type":"discussion","id":"DSC-0036","status":"done","ticket":"prometeu-hub-ui-direction","title":"Agenda - Prometeu Hub UI Direction","created_at":"2026-05-15","updated_at":"2026-05-22","tags":["hub","ui","shell","system-apps","lifecycle","design-system"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0036-prometeu-hub-ui-direction/LSN-0045-hub-ui-slices-should-prove-os-boundaries.md","status":"done","created_at":"2026-05-22","updated_at":"2026-05-22"}]}
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"rgba8888-framebuffer-and-pixel-format-direction","title":"Agenda - RGBA8888 Framebuffer and Pixel Format Direction","created_at":"2026-05-22","updated_at":"2026-05-23","tags":["gfx","framebuffer","rgb565","rgba8888","renderer","assets","host","backend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0037-rgba8888-framebuffer-and-pixel-format-direction/LSN-0046-pixel-format-contracts-must-move-as-one-surface.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23"}]}
{"type":"discussion","id":"DSC-0046","status":"done","ticket":"runtime-owned-variable-glyph-bank-palette-protocol","title":"Runtime-Owned Variable Glyph Bank Palette Protocol","created_at":"2026-07-14","updated_at":"2026-07-14","tags":["runtime","gfx","assets","glyph-bank","palette-serialization","protocol"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0055","file":"discussion/lessons/DSC-0046-runtime-owned-variable-glyph-bank-palette-protocol/LSN-0055-runtime-owned-asset-protocols-must-align-payload-residency-and-lookup.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]}
{"type":"discussion","id":"DSC-0047","status":"open","ticket":"portable-host-backend-strategy","title":"Portable Host Backend Strategy","created_at":"2026-07-14","updated_at":"2026-07-14","tags":["host","desktop","portable","sdl","backend","rendering","input","audio","linux","android","handheld"],"agendas":[{"id":"AGD-0050","file":"AGD-0050-portable-host-backend-strategy.md","status":"open","created_at":"2026-07-14","updated_at":"2026-07-14"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0048","status":"done","ticket":"corrigir-identificacao-formato-pbx","title":"Corrigir Identificacao do Formato PBX","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["runtime","bytecode","pbx","loader","format","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0056","file":"discussion/lessons/DSC-0048-corrigir-identificacao-formato-pbx/LSN-0056-runtime-artifact-identity-must-not-borrow-frontend-names.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
@@ -0,0 +1,118 @@
---
id: LSN-0051
ticket: system-run-cart
title: Launch Authority Belongs to SystemOS
created: 2026-07-03
tags: [runtime, systemos, cartridge, launch, abi, home]
---
## Context
The `system.run_cart` workflow resolved two related questions: whether a guest
should have an app-callable cartridge launch syscall, and how Home should start
games from a local library.
The final model removes `system.run_cart` from the userland ABI while preserving
direct host-controlled cartridge boot. Home launch is restored as a
system-owned path: the host may provide `--games-root <dir>`, SystemOS/Home
discovers valid Game directory cartridges, and selecting an entry routes through
firmware into `LoadCartridge`.
The important distinction is authority. A launch can be a valid product action
without being a guest capability.
## Key Decisions
### Remove Guest Cartridge Launch
**What:** Prometeu removed `system.run_cart` from the public userland syscall
surface, generated guest metadata, and runtime dispatch.
**Why:** A guest syscall made cartridge launch look like app-owned navigation.
That gave userland implied authority over target resolution, lifecycle cleanup,
failure policy, and system navigation.
**Trade-offs:** Obsolete guest code cannot keep a compatibility stub. The
runtime instead keeps direct boot as a host/system entrypoint and lets stale
guest attempts fail through the invalid syscall path.
### Preserve Direct Boot Outside The Guest ABI
**What:** Host, CLI, debugger, tests, and single-game flows continue to boot a
selected cartridge directly.
**Why:** Direct boot is still essential for development, automation, and future
single-game distribution. Those flows start with a host-selected target before
VM execution, so they do not need a guest syscall.
**Trade-offs:** The loader remains reusable, but it is not lifecycle
orchestration authority. Higher-level transitions must be owned by firmware or
SystemOS.
### Model Home Launch As A System Action
**What:** `--games-root <dir>` configures a local games library for Home. V1
discovery scans immediate child directories, keeps only valid Game cartridges,
and exposes enough internal metadata to launch a selected entry.
**Why:** Home needs a product path for "choose a game and start it", but that
action belongs to the system profile. SystemOS can present the library and ask
firmware to enter `LoadCartridge` without reintroducing guest-controlled launch.
**Trade-offs:** V1 intentionally excludes recursive discovery, `.pmc`, non-game
apps, rich catalog metadata, return-to-Home, and game-to-game switching. Those
need separate lifecycle and orchestration decisions.
## Patterns and Algorithms
### Authority-Based API Classification
Before exposing an operation to guest/userland code, classify what authority it
implies. If the operation selects another executable target, changes process
lifecycle, or controls navigation between system-owned modes, it is probably a
SystemOS or firmware action rather than an app syscall.
### Separate Selection From Loading
Home owns user selection and presentation. SystemOS owns the launch request.
Firmware owns the transition into `LoadCartridge`. The cartridge loader remains
the mechanism that validates and materializes a cartridge, not the authority
that decides when navigation is allowed.
### Expandable Internal Catalog Records
Home can render a small v1 list while the internal entry retains manifest data,
title, app id, app version, cartridge path, and discovery metadata. This keeps
the UI simple without reducing the model to a display-only DTO.
## Pitfalls
### Compatibility Stubs Preserve False Contracts
A syscall that returns success without doing real lifecycle work is worse than
an absent syscall. It teaches callers that the platform supports app-driven
launch while hiding that no complete transition happened.
### A Product Flow Is Not Automatically A Guest API
"Home can launch a game" and "a guest can launch a cartridge" are different
claims. Product behavior should be mapped to the component with the correct
authority instead of mirrored into the nearest callable ABI.
### Generic Library Roots Prematurely Expand Scope
The first launcher path is a games library, not a marketplace or full app
catalog. Shell apps, System apps, packages, icons, search, and recursive layouts
carry separate contracts and should not be smuggled into the v1 games-root path.
## Takeaways
- Cartridge launch is system navigation, not a userland syscall.
- Direct boot can remain host-controlled without appearing in guest metadata.
- Home launch should emit a system action and let firmware enter
`LoadCartridge`.
- Loader reuse does not imply loader ownership of lifecycle policy.
- Keep v1 discovery narrow: immediate child directory cartridges with
`app_mode: Game`.
- Preserve internal catalog metadata even when the Home UI renders only a small
subset.
@@ -0,0 +1,100 @@
---
id: LSN-0050
ticket: perf-async-background-work-lanes-for-assets-and-fs
title: Serial Async Lanes Bound Backlog Complexity
created: 2026-07-01
tags: [runtime, asset, async, scheduler, telemetry]
---
## Context
The async asset work moved from request-owned worker creation toward a
runtime-owned serial lane. The important shift is not just "use a worker
thread"; it is the introduction of a third logical execution lane with explicit
ownership, priority, cancellation, progress, and telemetry.
This work followed `DEC-0034` and plans `PLN-0123` through `PLN-0128`. The
published model separates:
- main runtime execution, where guest-visible state is committed;
- render worker execution, where closed render packets are consumed;
- async IO/decode/persistence work, where one background job is active at a
time.
## Key Decisions
### Async Work Lane and Asset Backlog Contract
**What:** Asset IO/decode and compatible persistence work use a runtime-owned
serial async lane. Asset requests are queued by target bank slot, not by
unbounded transient request identity.
**Why:** A serial lane keeps the runtime observable and portable. It preserves
the intended hardware mental model while avoiding a desktop-biased thread pool
or one OS thread per asset request.
**Trade-offs:** The lane intentionally sacrifices parallel decode throughput in
exchange for bounded state, deterministic ownership, simpler telemetry, and
clear priority rules. If future implementations add more physical parallelism,
they still need to preserve the logical serial contract where the spec requires
it.
## Patterns and Algorithms
The asset backlog is bounded by target identity. A request targets a concrete
bank type and slot. A newer request for the same target supersedes the older
pending request, and an older active result is discarded when its generation is
no longer current.
Stable handles observe slots. A handle should not be treated as a worker job or
thread token. The durable identity is the bank slot plus request generation:
slot state says what is resident; request state says what is queued, active,
ready, canceled, superseded, or failed.
Commit remains a main-lane operation. The background lane may read and decode,
but publication into resident runtime state happens at predictable ownership
points. This keeps VM execution, render handoff, and frame observation from
racing with background mutation.
Progress and telemetry are closure-oriented. Use integer progress and update
expensive aggregate telemetry when jobs close, not inside decode loops. Tests
should synchronize on explicit state transitions rather than sleeps.
Priority is part of the lane contract. Memcard commit/write work can outrank
ordinary asset loads, FS write/config work can be represented internally, and
non-critical read/list work belongs below asset loads. Public FS semantics
remain owned by the filesystem discussion; sharing the lane is not permission
to decide the FS API here.
## Pitfalls
Do not hide concurrency behind per-request `thread::spawn`. That appears simple
locally but loses boundedness, priority, cancellation, and telemetry.
Do not let a handle mean "the current background job." Handles must survive
empty slots, completed work, cancellation, superseding, errors, and already
resident fast paths.
Do not install background results directly from the worker. Decode completion is
not the same as publication. Use request generation checks before committing a
result.
Do not turn operational states into traps. Queued, active, canceled,
superseded, error, and backend-unavailable outcomes belong in status-first
surfaces unless the caller violated the structural ABI.
Do not reopen FS public API scope while wiring internal async-lane consumers.
The lane can support FS-style work without deciding request/poll semantics.
## Takeaways
- A runtime async lane is an ownership boundary, not just an implementation
thread.
- Backlog keying by target slot bounds complexity better than queue length
limits exposed to the guest.
- Stable slot handles plus request generations prevent stale async results from
mutating newer state.
- Main-lane commit keeps background IO/decode compatible with deterministic
runtime publication.
- Telemetry belongs at state transitions and job closure, not inside hot decode
loops.
@@ -0,0 +1,145 @@
---
id: LSN-0052
ticket: foreground-stack-game-pause-shell-vm-backed
title: Foreground Ownership and VM Session Ownership Are Separate
created: 2026-07-05
tags: [runtime, os, lifecycle, shell, game, vm, foreground, architecture]
---
# LSN-0052: Foreground Ownership and VM Session Ownership Are Separate
## Context
DSC-0041 closed the `Game -> Home/Shell -> same Game` lifecycle for the first
runtime implementation that supports both native Shell apps and VM-backed Shell
apps. The important architectural shift was not only pausing the Game. The
runtime also had to stop treating one firmware-owned VM as the place where all
guest execution state lives.
The final model separates two questions:
- Who owns the foreground visual/input authority right now?
- Which VM-backed process owns a mutable VM execution context?
Foreground ownership is global SystemOS policy. VM execution state belongs to a
session associated with a task/process. A suspended resident Game is not a saved
snapshot and not a special global VM. It is a live VM session that is temporarily
ineligible for normal foreground ticks, input, frame pacing, and render
publication.
## Key Decisions
### Foreground Stack and Game Pause Contract
**What:** PROMETEU uses a single foreground owner in v1. Hub/Home is the root
Shell owner, a Game may remain resident, and one foreground Shell app may run in
front of the resident Game. Pressing desktop `Esc` is a host/SystemOS Home
request, not guest input.
**Why:** This preserves console-like navigation without turning the runtime into
a general multitasking scheduler. It lets the system pause and suspend a Game,
run Hub or Shell, then resume the same Game deterministically.
**Trade-offs:** The model intentionally rejects multiple resident Games, direct
Shell-to-Game return, background execution, and Game-to-Game switching in v1.
Those features remain future work, but the lifecycle structure now has a place
to add them.
### VM Session Ownership for VM-Backed Processes
**What:** VM-backed mutable execution state is owned by VM sessions. A
VM-backed Game and a VM-backed Shell never share the same VM, stack, heap, PC,
open handles, cartridge identity, or VM-scoped runtime state.
**Why:** A single firmware-owned VM cannot represent a suspended resident Game
and a foreground VM Shell at the same time. Loading the Shell into that global
VM would overwrite the Game context that the lifecycle model says is resident.
**Trade-offs:** Session ownership is more explicit than one global VM, but it
keeps the model simpler than snapshot/restore. It also prepares the runtime for
future background-capable sessions without committing to background scheduling
yet.
## Patterns and Algorithms
### Pause Is Cooperative, Suspension Is OS Authority
The Game receives lifecycle events such as pause and resume, but the OS owns the
actual scheduling state. If the Game does not cooperate within the bounded pause
budget, SystemOS can suspend it anyway. On resume, the Game receives a foreground
restore event and may still keep its internal pause screen while it
synchronizes.
This distinction prevents userland from owning system navigation. The Game may
observe and react. It cannot veto Home.
### Foreground Owner Is Not the Same as Tick Eligibility
Foreground ownership controls input, visual authority, render ownership, and
normal frame pacing. Tick eligibility controls whether a VM session may execute.
In v1, only the foreground VM session receives normal ticks, and the resident
Game does not tick while Shell or Hub is foreground.
The important design detail is that the data model does not assume this must be
true forever. Sessions can later become background-eligible without changing who
owns render/input foreground.
### VM Sessions Are the Unit of Mutable Guest State
Each VM-backed task/process maps to a `VmSession`. The session owns the VM,
runtime state, session-scoped filesystem state, open file handles, next handle
allocation, cartridge identity, lifecycle delivery state, and debug state.
Cartridge loading creates or reuses a VM session through SystemOS session
services. Firmware orchestrates macro states such as `LoadCartridge`,
`GameRunning`, `HubHome`, and `ShellRunning`, but it no longer owns a canonical
guest VM.
### Debugger and Host Inspection Must Follow the Active Session
Host debugging must inspect and mutate the active session VM, not a transitional
global VM. PC, operand stack, breakpoints, debug-step execution, cartridge
identity, and breakpoint-hit events all need to resolve through active session
state.
This keeps debugger behavior aligned with actual execution. A debugger that
observes a different VM than the scheduler ticks is worse than no debugger: it
creates false confidence and hides lifecycle bugs.
### Operational Failures Should Cross Facades as Typed Errors
Session creation and loading are operational boundaries. Missing task, missing
process, duplicate VM session, missing VM session during initialization, and
foreground Shell rejection should be typed errors. Firmware can then choose a
controlled crash report, a launch rejection, or a logged no-transition outcome.
Panics are reserved for test/setup wrappers or impossible internal invariants
that have already been proven by prior checks.
## Pitfalls
- Do not use a global VM as a compatibility bridge after session ownership is
introduced. It will eventually become stale or contradictory.
- Do not let Home/SystemOS be guest input. It changes OS authority, so it must
bypass guest pad state.
- Do not present old frames after foreground ownership changes. Render ownership
and epoch validation are part of lifecycle correctness, not renderer polish.
- Do not model pause and suspension as the same state. Pause is visible to the
Game; suspension is the scheduler mechanism.
- Do not encode v1 limits such as one resident Game or one foreground Shell by
collapsing storage into one VM. Express those limits as lifecycle/session
policy.
- Do not let debugger state drift from scheduler state. The debugger must use
the same active session as normal execution.
## Takeaways
- Foreground ownership is global policy; VM execution state is session-owned.
- A suspended Game is a preserved session, not a serialized VM and not a global
VM waiting to be reused.
- Shell apps can be native or VM-backed, but only VM-backed processes need VM
sessions.
- Session ownership is the foundation for future background-capable processes,
even before background execution exists.
- Typed session/lifecycle errors make launch and recovery behavior explicit at
firmware boundaries.
@@ -0,0 +1,107 @@
---
id: LSN-0049
ticket: real-render-worker-establishment
title: Render Workers Publish Frames, Hosts Present Them
created: 2026-06-20
tags: [runtime, renderer, worker, host, publication, concurrency]
---
## Context
The real render worker work moved Prometeu from local, synchronous rendering toward an asynchronous worker path. The important architectural question was not only how to create a thread, but where ownership of render work, frame publication, and native presentation should live.
The final model keeps the VM producer, render worker, and desktop presenter separated:
- the VM closes logical render submissions;
- the worker consumes owned submissions through a latest-wins handoff;
- the worker publishes an owned `OwnedRgba8888Frame`;
- the desktop host uploads and presents the latest published frame through native window APIs.
This boundary is what makes the worker real without making it desktop-specific.
## Key Decisions
### Platform Boundary Before Worker Boundary
**What:** Prometeu removed the monolithic hardware bridge from runtime-facing contracts and introduced explicit platform services before establishing the real worker.
**Why:** A render worker cannot safely consume `&mut Hardware`, `&mut Gfx`, live `FrameComposer`, or mutable VM state. Those are single-threaded runtime concerns. The worker needs closed data plus read-only resource access.
**Trade-offs:** This required broad preparatory work before the worker could exist. The payoff is that the worker boundary is now testable without a native window and does not depend on host presentation details.
### Closed Submissions Are The Worker Input
**What:** The VM producer closes render work into owned `RenderSubmission` values and publishes them through a single-slot latest-wins handoff.
**Why:** The worker must not observe partially built render state or preserve an unbounded queue of historical frames. If the producer outruns the consumer, the newest complete submission wins.
**Trade-offs:** Some produced frames are intentionally dropped before consumption. That is correct for this runtime because the contract is visual freshness and VM progress, not rendering every intermediate state.
### Publication Store Is The Observable Frame Boundary
**What:** The sink that receives worker-published `OwnedRgba8888Frame` values is also the source the host reads for presentation.
**Why:** A no-op sink with a separate controller-owned latest-frame cache makes publication ambiguous. The controller should own lifecycle, shutdown, handoff, errors, and telemetry. The publication store should own the latest observable frame.
**Trade-offs:** Repeat telemetry remains a runtime concern and is recorded by frame id. Pixel retention stays in the publication store so the host can present without depending on controller internals.
### Host Presentation Remains Native And Single-Threaded
**What:** The worker never imports or calls winit, pixels, SDL, swapchain, native texture, or window APIs. The host event loop remains responsible for upload and present.
**Why:** Native presentation APIs often have thread affinity and backend-specific constraints. Keeping them in the host event loop avoids leaking host constraints into the runtime worker contract.
**Trade-offs:** The worker publishes memory frames rather than presenting directly. The host still performs the final copy/upload step, but the runtime remains portable and testable.
## Patterns and Algorithms
### Latest-Wins Handoff
Use a single pending slot plus a condition variable:
- producer publish replaces pending work if the worker has not consumed it;
- replacement increments telemetry;
- worker wait takes the latest pending submission;
- in-flight work is separate from pending work;
- producer publication never waits for render completion.
This is a bounded backpressure model. It prevents queue growth while keeping VM progress independent from render speed.
### Ownership/Epoch Stale Discard
Each submission and frame carries render ownership metadata. Before publication, the worker compares the completed frame ownership with the active ownership snapshot. If the frame is stale, it is discarded and counted.
This prevents obsolete pixels from being presented after an app, mode, or ownership transition.
### Store-Backed Publication
The publication sink stores the latest `OwnedRgba8888Frame` in owned memory. The desktop host clones or reads that frame before copying pixels into the native framebuffer.
The store is intentionally simpler than the controller. It does not own worker lifecycle. It only answers: "what is the latest worker-published frame?"
## Pitfalls
### A Worker Thread Alone Is Not A Worker Contract
Moving code to another thread is not sufficient. The contract must define input ownership, resource access, publication semantics, shutdown, stale-frame behavior, and telemetry.
### Native Presentation Must Not Leak Back Into Runtime
It is tempting to let the worker call the host presenter directly. That couples runtime execution to desktop window rules and makes deterministic tests harder. Publish owned frames first; present later in the host.
### No-Op Sinks Hide Boundary Ambiguity
A sink that accepts a frame and discards it while another component stores the actual latest frame is a design smell. The object that receives `publish(frame)` should be the observable publication boundary, or the controller should be explicitly documented as that store. Prometeu chose the store-backed sink model.
### Concurrency Tests Must Publish Before Waiting
A deterministic gate only works after work has actually reached the worker. Waiting for backend entry before publishing to the handoff causes a pipeline hang. Tests should explicitly publish pending work before waiting on worker-side synchronization.
## Takeaways
- Render workers should consume closed, owned submissions, not live runtime state.
- Latest-wins handoff is a deliberate bounded backpressure model, not a queue shortcut.
- In-flight render work must be validated against current ownership before publication.
- Worker publication and host presentation are different responsibilities.
- The sink/store that receives published frames should be the single observable source for presentation.
- Deterministic concurrency tests should synchronize on real state transitions, not sleeps or assumed scheduling.

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