498 lines
17 KiB
Rust
498 lines
17 KiB
Rust
use std::fmt;
|
|
use std::sync::Arc;
|
|
|
|
use prometeu_bytecode::Value;
|
|
use prometeu_drivers::MemoryBanks;
|
|
use prometeu_drivers::hardware::Hardware;
|
|
use prometeu_firmware::firmware_state::{AppCrashesStep, ResetStep};
|
|
use prometeu_firmware::{BootTarget, Firmware, FirmwareState};
|
|
use prometeu_hal::{
|
|
AssetBridge, AudioBridge, FrameId, Game2DFrameComposer, InputPlatform, InputSignals,
|
|
OwnedRgba8888Frame, RenderBackend, RenderSubmission, RenderSubmissionSink, RenderSubmitError,
|
|
RuntimePlatform, TelemetryPlatform,
|
|
};
|
|
use prometeu_system::{CrashReport, LatestRenderFrameStore};
|
|
|
|
const BOOT_TICK_LIMIT: usize = 64;
|
|
const HOST_FRAME_ADVANCE_TICK_LIMIT: usize = 100_000;
|
|
|
|
/// One published logical frame plus the automation counter.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct CapturedFrame {
|
|
pub logical_frame_index: u64,
|
|
pub frame: OwnedRgba8888Frame,
|
|
}
|
|
|
|
/// Debugger-shaped execution snapshot.
|
|
#[derive(Debug, Clone)]
|
|
pub struct HostState {
|
|
pub pc: usize,
|
|
pub stack_top: Vec<Value>,
|
|
pub frame_index: u64,
|
|
pub tick_index: u64,
|
|
pub app_id: u32,
|
|
pub status: HostExecutionStatus,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum HostExecutionStatus {
|
|
Running,
|
|
Paused,
|
|
Terminated,
|
|
Faulted,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum AdvanceFrameOutcome {
|
|
FrameCompleted { logical_frame_index: u64, frame_id: FrameId },
|
|
Faulted(CrashReport),
|
|
Terminated,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum AdvanceFramesStop {
|
|
Completed,
|
|
Faulted(CrashReport),
|
|
Terminated,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct AdvanceFramesOutcome {
|
|
pub requested: u64,
|
|
pub completed: u64,
|
|
pub stop: AdvanceFramesStop,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum HostError {
|
|
AlreadyBooted,
|
|
BootFailed { reason: String, report: Option<CrashReport> },
|
|
InvalidState { operation: &'static str, status: HostExecutionStatus },
|
|
FrameAdvanceWatchdogExpired { host_tick_limit: usize },
|
|
FrameNotPublished { previous: Option<FrameId> },
|
|
NoFrameAvailable,
|
|
}
|
|
|
|
impl fmt::Display for HostError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::AlreadyBooted => write!(f, "boot requires reset before another attempt"),
|
|
Self::BootFailed { reason, .. } => write!(f, "boot failed: {reason}"),
|
|
Self::InvalidState { operation, status } => {
|
|
write!(f, "{operation} is invalid while execution is {status:?}")
|
|
}
|
|
Self::FrameAdvanceWatchdogExpired { host_tick_limit } => {
|
|
write!(
|
|
f,
|
|
"headless host frame-advance watchdog expired after {host_tick_limit} firmware ticks"
|
|
)
|
|
}
|
|
Self::FrameNotPublished { .. } => {
|
|
write!(f, "logical frame closed without its canonical published frame")
|
|
}
|
|
Self::NoFrameAvailable => write!(f, "no completed frame is available for capture"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for HostError {}
|
|
|
|
/// In-process host. The desktop winit runner is a separate crate and is not linked here.
|
|
pub struct HeadlessHost {
|
|
firmware: Firmware,
|
|
platform: HeadlessPlatform,
|
|
signals: InputSignals,
|
|
boot_attempted: bool,
|
|
last_completed_frame: Option<CompletedFrame>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
struct CompletedFrame {
|
|
logical_frame_index: u64,
|
|
frame_id: FrameId,
|
|
}
|
|
|
|
struct HeadlessPlatform {
|
|
hardware: Hardware,
|
|
store: LatestRenderFrameStore,
|
|
}
|
|
|
|
impl HeadlessHost {
|
|
pub fn new() -> Self {
|
|
let memory_banks = Arc::new(MemoryBanks::new());
|
|
let hardware = Hardware::new_with_memory_banks(Arc::clone(&memory_banks));
|
|
let store = LatestRenderFrameStore::default();
|
|
Self {
|
|
firmware: Firmware::new(None),
|
|
platform: HeadlessPlatform { hardware, store },
|
|
signals: InputSignals::default(),
|
|
boot_attempted: false,
|
|
last_completed_frame: None,
|
|
}
|
|
}
|
|
|
|
/// Load `path` and tick until the firmware is in `GameRunning`.
|
|
///
|
|
/// The transition into `GameRunning` is the last tick. The first game
|
|
/// logical frame stays available for [`Self::advance_frame`].
|
|
pub fn boot(&mut self, path: impl Into<String>) -> Result<(), HostError> {
|
|
if self.boot_attempted {
|
|
return Err(HostError::AlreadyBooted);
|
|
}
|
|
self.boot_attempted = true;
|
|
let path = path.into();
|
|
self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 };
|
|
|
|
for _ in 0..BOOT_TICK_LIMIT {
|
|
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
|
return Ok(());
|
|
}
|
|
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
|
let report = self.get_fault();
|
|
let reason = report
|
|
.as_ref()
|
|
.map(CrashReport::summary)
|
|
.unwrap_or_else(|| "cartridge crashed during boot".to_string());
|
|
return Err(HostError::BootFailed { reason, report });
|
|
}
|
|
if matches!(self.firmware.state, FirmwareState::HubHome(_)) {
|
|
return Err(HostError::BootFailed {
|
|
reason: "cartridge did not load".to_string(),
|
|
report: None,
|
|
});
|
|
}
|
|
self.tick_once();
|
|
}
|
|
|
|
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
|
Ok(())
|
|
} else {
|
|
Err(HostError::BootFailed {
|
|
reason: "boot did not reach the game".to_string(),
|
|
report: self.get_fault(),
|
|
})
|
|
}
|
|
}
|
|
|
|
pub fn reset(&mut self) {
|
|
self.signals = InputSignals::default();
|
|
self.firmware.change_state(
|
|
FirmwareState::Reset(ResetStep),
|
|
&self.signals,
|
|
&mut self.platform,
|
|
);
|
|
self.platform.store = LatestRenderFrameStore::default();
|
|
self.boot_attempted = false;
|
|
self.last_completed_frame = None;
|
|
}
|
|
|
|
pub fn pause(&mut self) -> Result<(), HostError> {
|
|
self.require_active("pause")?;
|
|
self.firmware.os.vm().set_paused(true);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn resume(&mut self) -> Result<(), HostError> {
|
|
self.require_active("resume")?;
|
|
self.firmware.os.vm().set_paused(false);
|
|
Ok(())
|
|
}
|
|
|
|
/// Execute one VM instruction. This does not close a logical frame.
|
|
pub fn step(&mut self) -> Result<Option<CrashReport>, HostError> {
|
|
self.require_active("step")?;
|
|
self.firmware.os.vm().set_paused(true);
|
|
let report = self.firmware.os.vm().debug_step_active_session(&mut self.platform);
|
|
self.platform.hardware.audio.clear_commands();
|
|
Ok(report)
|
|
}
|
|
|
|
pub fn advance_frame(&mut self) -> Result<AdvanceFrameOutcome, HostError> {
|
|
if let Some(report) = self.get_fault() {
|
|
return Ok(AdvanceFrameOutcome::Faulted(report));
|
|
}
|
|
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
|
return Ok(AdvanceFrameOutcome::Terminated);
|
|
}
|
|
|
|
let start = self.firmware.os.vm().logical_frame_index();
|
|
let previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id);
|
|
self.firmware.os.vm().set_paused(false);
|
|
self.firmware.os.vm().request_debug_step();
|
|
|
|
for _ in 0..HOST_FRAME_ADVANCE_TICK_LIMIT {
|
|
self.tick_once();
|
|
if let Some(report) = self.get_fault() {
|
|
self.finish_frame_advance();
|
|
return Ok(AdvanceFrameOutcome::Faulted(report));
|
|
}
|
|
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
|
self.finish_frame_advance();
|
|
return Ok(AdvanceFrameOutcome::Terminated);
|
|
}
|
|
|
|
let logical_frame_index = self.firmware.os.vm().logical_frame_index();
|
|
if logical_frame_index > start {
|
|
self.finish_frame_advance();
|
|
let frame = self
|
|
.platform
|
|
.store
|
|
.latest_frame()
|
|
.ok_or(HostError::FrameNotPublished { previous: previous_frame_id })?;
|
|
if Some(frame.frame_id) == previous_frame_id {
|
|
return Err(HostError::FrameNotPublished { previous: previous_frame_id });
|
|
}
|
|
self.last_completed_frame =
|
|
Some(CompletedFrame { logical_frame_index, frame_id: frame.frame_id });
|
|
return Ok(AdvanceFrameOutcome::FrameCompleted {
|
|
logical_frame_index,
|
|
frame_id: frame.frame_id,
|
|
});
|
|
}
|
|
}
|
|
|
|
self.finish_frame_advance();
|
|
Err(HostError::FrameAdvanceWatchdogExpired {
|
|
host_tick_limit: HOST_FRAME_ADVANCE_TICK_LIMIT,
|
|
})
|
|
}
|
|
|
|
pub fn advance_frames(&mut self, count: u64) -> Result<AdvanceFramesOutcome, HostError> {
|
|
let mut completed = 0;
|
|
for _ in 0..count {
|
|
match self.advance_frame()? {
|
|
AdvanceFrameOutcome::FrameCompleted { .. } => completed += 1,
|
|
AdvanceFrameOutcome::Faulted(report) => {
|
|
return Ok(AdvanceFramesOutcome {
|
|
requested: count,
|
|
completed,
|
|
stop: AdvanceFramesStop::Faulted(report),
|
|
});
|
|
}
|
|
AdvanceFrameOutcome::Terminated => {
|
|
return Ok(AdvanceFramesOutcome {
|
|
requested: count,
|
|
completed,
|
|
stop: AdvanceFramesStop::Terminated,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
Ok(AdvanceFramesOutcome { requested: count, completed, stop: AdvanceFramesStop::Completed })
|
|
}
|
|
|
|
pub fn set_input(&mut self, signals: InputSignals) {
|
|
self.signals = signals;
|
|
}
|
|
|
|
pub fn clear_input(&mut self) {
|
|
self.signals = InputSignals::default();
|
|
}
|
|
|
|
pub fn set_right(&mut self, down: bool) {
|
|
self.signals.right_signal = down;
|
|
}
|
|
|
|
pub fn capture_frame(&self) -> Result<CapturedFrame, HostError> {
|
|
let completed = self.last_completed_frame.ok_or(HostError::NoFrameAvailable)?;
|
|
let frame = self.platform.store.latest_frame().ok_or(HostError::NoFrameAvailable)?;
|
|
if frame.frame_id != completed.frame_id {
|
|
return Err(HostError::FrameNotPublished { previous: Some(completed.frame_id) });
|
|
}
|
|
Ok(CapturedFrame { logical_frame_index: completed.logical_frame_index, frame })
|
|
}
|
|
|
|
pub fn get_state(&mut self) -> HostState {
|
|
let status = self.execution_status();
|
|
HostState {
|
|
pc: self.firmware.os.vm().active_pc().unwrap_or(0),
|
|
stack_top: self.firmware.os.vm().active_operand_stack_top(10),
|
|
frame_index: self.firmware.os.vm().logical_frame_index(),
|
|
tick_index: self.firmware.os.vm().tick_index(),
|
|
app_id: self.firmware.os.vm().current_app_id(),
|
|
status,
|
|
}
|
|
}
|
|
|
|
pub fn get_fault(&mut self) -> Option<CrashReport> {
|
|
if let Some(report) = self.firmware.os.vm().last_crash_report() {
|
|
return Some(report.clone());
|
|
}
|
|
match &self.firmware.state {
|
|
FirmwareState::AppCrashes(AppCrashesStep { report }) => Some(report.clone()),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn tick_once(&mut self) {
|
|
self.firmware.tick(&self.signals, &mut self.platform);
|
|
self.platform.hardware.audio.clear_commands();
|
|
}
|
|
|
|
fn execution_status(&mut self) -> HostExecutionStatus {
|
|
if self.fault_is_visible() {
|
|
HostExecutionStatus::Faulted
|
|
} else if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
|
HostExecutionStatus::Terminated
|
|
} else if self.firmware.os.vm().paused() {
|
|
HostExecutionStatus::Paused
|
|
} else {
|
|
HostExecutionStatus::Running
|
|
}
|
|
}
|
|
|
|
fn fault_is_visible(&mut self) -> bool {
|
|
self.firmware.os.vm().last_crash_report().is_some()
|
|
|| matches!(self.firmware.state, FirmwareState::AppCrashes(_))
|
|
}
|
|
|
|
fn require_active(&mut self, operation: &'static str) -> Result<(), HostError> {
|
|
let status = self.execution_status();
|
|
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused) {
|
|
Ok(())
|
|
} else {
|
|
Err(HostError::InvalidState { operation, status })
|
|
}
|
|
}
|
|
|
|
fn finish_frame_advance(&mut self) {
|
|
self.firmware.os.vm().set_paused(true);
|
|
self.firmware.os.vm().clear_debug_step_request();
|
|
}
|
|
}
|
|
|
|
impl Default for HeadlessHost {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
|
|
impl RenderSubmissionSink for HeadlessPlatform {
|
|
fn submit_render_submission(
|
|
&mut self,
|
|
submission: RenderSubmission,
|
|
) -> Result<(), RenderSubmitError> {
|
|
let frame_id = submission.frame_id;
|
|
let ownership = submission.ownership;
|
|
self.hardware.submit_render_submission(submission)?;
|
|
let (width, height) = self.hardware.gfx.size();
|
|
let pixels = self.hardware.gfx.front_buffer().to_vec();
|
|
let frame = OwnedRgba8888Frame::packed(frame_id, ownership, width, height, pixels)
|
|
.map_err(|_| RenderSubmitError::SubmissionRejected)?;
|
|
self.store.publish_frame(frame);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl RuntimePlatform for HeadlessPlatform {
|
|
fn display_size(&self) -> (usize, usize) {
|
|
(Hardware::W, Hardware::H)
|
|
}
|
|
|
|
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
|
self
|
|
}
|
|
|
|
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
|
&mut self.hardware
|
|
}
|
|
|
|
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
|
&mut self.hardware
|
|
}
|
|
|
|
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 std::fs;
|
|
|
|
use prometeu_bytecode::assembler::assemble;
|
|
use prometeu_bytecode::model::{BytecodeModule, Export, FunctionMeta};
|
|
|
|
use super::{AdvanceFrameOutcome, HeadlessHost};
|
|
|
|
#[test]
|
|
fn termination_during_frame_advance_clears_host_step_control() {
|
|
let cartridge = non_closing_cartridge();
|
|
let mut host = HeadlessHost::new();
|
|
host.boot(cartridge.to_string_lossy()).expect("boot non-closing cartridge");
|
|
host.firmware.request_home_from_host();
|
|
|
|
assert_eq!(
|
|
host.advance_frame().expect("lifecycle termination"),
|
|
AdvanceFrameOutcome::Terminated
|
|
);
|
|
assert!(host.firmware.os.vm().paused());
|
|
assert!(!host.firmware.os.vm().debug_step_requested());
|
|
|
|
fs::remove_dir_all(cartridge).expect("remove test cartridge");
|
|
}
|
|
|
|
fn non_closing_cartridge() -> std::path::PathBuf {
|
|
let directory = std::env::temp_dir().join(format!(
|
|
"prometeu-headless-termination-cleanup-{}-{}",
|
|
std::process::id(),
|
|
std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.expect("system clock")
|
|
.as_nanos()
|
|
));
|
|
fs::create_dir_all(&directory).expect("create test cartridge");
|
|
|
|
let code = assemble("JMP 0\n").expect("assemble non-closing program");
|
|
let module = BytecodeModule {
|
|
version: 0,
|
|
const_pool: vec![],
|
|
functions: vec![FunctionMeta {
|
|
code_offset: 0,
|
|
code_len: code.len() as u32,
|
|
param_slots: 0,
|
|
local_slots: 0,
|
|
return_slots: 0,
|
|
max_stack_slots: 1,
|
|
}],
|
|
code,
|
|
debug_info: None,
|
|
exports: vec![Export { symbol: "main".into(), func_idx: 0 }],
|
|
syscalls: vec![],
|
|
}
|
|
.serialize();
|
|
fs::write(directory.join("program.pbx"), module).expect("write test program");
|
|
fs::write(
|
|
directory.join("manifest.json"),
|
|
"{\n \"magic\": \"PMTU\",\n \"cartridge_version\": 1,\n \"app_id\": 91,\n \"title\": \"Termination Cleanup\",\n \"app_version\": \"0.1.0\",\n \"app_mode\": \"Game\",\n \"capabilities\": []\n}\n",
|
|
)
|
|
.expect("write test manifest");
|
|
|
|
directory
|
|
}
|
|
}
|