summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMica White <botahamec@outlook.com>2026-10-31 10:59:52 -0400
committerMica White <botahamec@outlook.com>2026-10-31 10:59:52 -0400
commitfde01cceb898b944b646a8fed1ce81cb14e523ef (patch)
treed1d5c97350fbbba2cc522c1f539c320ad4c2d1fc /src
parent0c128e472b1b49e32c313874eaeccc8c5f1b1202 (diff)
Testing and optimization
Diffstat (limited to 'src')
-rw-r--r--src/buffer.rs120
-rw-r--r--src/file.rs23
-rw-r--r--src/input.rs36
-rw-r--r--src/lib.rs36
-rw-r--r--src/main.rs12
-rw-r--r--src/scene.rs29
-rw-r--r--src/script.rs221
-rw-r--r--src/script/wasm.rs432
-rw-r--r--src/storage.rs3
-rw-r--r--src/time.rs1
10 files changed, 639 insertions, 274 deletions
diff --git a/src/buffer.rs b/src/buffer.rs
index dcb7b8b..35692b1 100644
--- a/src/buffer.rs
+++ b/src/buffer.rs
@@ -13,6 +13,9 @@ use crossterm::{
LeaveAlternateScreen, WindowSize, disable_raw_mode, enable_raw_mode, window_size,
},
};
+use rustc_hash::FxHashMap;
+
+use crate::input::Position;
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub struct Cell {
@@ -25,7 +28,11 @@ pub struct Cell {
pub struct Buffer {
stdout: Box<dyn Write>,
- pub cells: Vec<Cell>,
+ old_ephemeral_cells: Vec<Cell>,
+ new_eternal_cells: Vec<Cell>,
+ old_eternal_cells: Vec<Cell>,
+ eternal_cells: FxHashMap<Position, Vec<Cell>>,
+ ephemeral_cells: Vec<Cell>,
pub window_size: WindowSize,
}
@@ -51,15 +58,45 @@ impl TryFrom<crossterm::event::Event> for Event {
}
}
+impl Cell {
+ pub fn position(&self) -> Position {
+ Position {
+ x: self.x,
+ y: self.y,
+ }
+ }
+}
+
impl Buffer {
pub fn new(stdout: Box<dyn Write>) -> std::io::Result<Self> {
Ok(Self {
stdout,
- cells: Vec::new(),
+ old_eternal_cells: Vec::new(),
+ new_eternal_cells: Vec::new(),
+ old_ephemeral_cells: Vec::new(),
+ eternal_cells: FxHashMap::default(),
+ ephemeral_cells: Vec::new(),
window_size: window_size()?,
})
}
+ pub fn add_ephemeral_cell(&mut self, cell: Cell) {
+ self.ephemeral_cells.push(cell);
+ }
+
+ pub fn add_eternal_cell(&mut self, cell: Cell) {
+ self.new_eternal_cells.push(cell);
+ }
+
+ pub fn remove_eternal_cell(&mut self, cell: Cell) {
+ self.old_eternal_cells.push(cell);
+ if let Some(cells) = self.eternal_cells.get_mut(&cell.position())
+ && let Some(index) = cells.iter().rposition(|old_cell| *old_cell == cell)
+ {
+ cells.remove(index);
+ }
+ }
+
fn initialize(writer: &mut impl Write) -> std::io::Result<()> {
enable_raw_mode()?;
queue!(
@@ -72,24 +109,84 @@ impl Buffer {
Ok(())
}
+ fn queue_cell(&mut self, cell: Cell) -> std::io::Result<()> {
+ queue!(
+ self.stdout,
+ MoveTo(cell.x, cell.y),
+ PrintStyledContent(StyledContent::new(cell.style, cell.character))
+ )
+ }
+
+ fn queue_delete_cell(&mut self, cell: Cell) -> std::io::Result<()> {
+ if let Some(eternal_cells) = self.eternal_cells.get(&cell.position())
+ && let Some(new_cell) = eternal_cells.last()
+ {
+ if new_cell.z > cell.z {
+ return Ok(());
+ }
+
+ self.queue_cell(*new_cell)
+ } else {
+ self.queue_cell(Cell {
+ character: ' ',
+ style: ContentStyle::default(),
+ x: cell.x,
+ y: cell.y,
+ z: 0,
+ })
+ }
+ }
+
fn render(&mut self) -> std::io::Result<()> {
+ #[cfg(feature = "puffin")]
puffin::profile_function!();
{
+ #[cfg(feature = "puffin")]
puffin::profile_scope!("sort cells");
- self.cells.sort_unstable_by_key(|cell| cell.z);
+ self.ephemeral_cells
+ .sort_unstable_by_key(|cell| u8::MAX - cell.z);
+ self.eternal_cells
+ .values_mut()
+ .for_each(|cells| cells.sort_unstable_by_key(|cell| u8::MAX - cell.z));
}
{
+ #[cfg(feature = "puffin")]
puffin::profile_scope!("queue");
- queue!(self.stdout, BeginSynchronizedUpdate, Clear(ClearType::All))?;
- for cell in &self.cells {
- queue!(
- self.stdout,
- MoveTo(cell.x, cell.y),
- PrintStyledContent(StyledContent::new(cell.style, cell.character))
- )?;
+ queue!(self.stdout, BeginSynchronizedUpdate)?;
+ if self.eternal_cells.is_empty() && self.old_eternal_cells.is_empty() {
+ queue!(self.stdout, Clear(ClearType::All))?;
+ self.old_ephemeral_cells.clear();
+ self.old_eternal_cells.clear();
+ }
+ while let Some(cell) = self.old_ephemeral_cells.pop() {
+ self.queue_delete_cell(cell)?;
+ }
+ while let Some(cell) = self.old_eternal_cells.pop() {
+ self.queue_delete_cell(cell)?;
+ }
+
+ while let Some(cell) = self.new_eternal_cells.pop() {
+ self.eternal_cells
+ .entry(cell.position())
+ .or_default()
+ .push(cell);
+ self.queue_cell(cell)?;
+ }
+ while let Some(cell) = self.ephemeral_cells.pop() {
+ if self
+ .eternal_cells
+ .get(&cell.position())
+ .and_then(|cells| cells.last())
+ .is_some_and(|eternal_cell| eternal_cell.z > cell.z)
+ {
+ continue;
+ }
+ self.queue_cell(cell)?;
+ self.old_ephemeral_cells.push(cell);
}
queue!(self.stdout, EndSynchronizedUpdate)?;
}
+ #[cfg(feature = "puffin")]
puffin::profile_scope!("flush");
self.stdout.flush()?;
Ok(())
@@ -113,6 +210,7 @@ impl Buffer {
) -> std::io::Result<()> {
Self::initialize(&mut self.stdout)?;
loop {
+ #[cfg(feature = "puffin")]
puffin::profile_scope!("frame");
while matches!(event::poll(Duration::ZERO), Ok(true)) {
let Ok(event) = event::read() else { continue };
@@ -122,7 +220,9 @@ impl Buffer {
event_handler(self, event);
}
event_handler(self, Event::Render);
+ self.window_size = window_size()?;
self.render()?;
+ #[cfg(feature = "puffin")]
puffin::GlobalProfiler::lock().new_frame();
}
}
diff --git a/src/file.rs b/src/file.rs
index b8f6610..c2c834e 100644
--- a/src/file.rs
+++ b/src/file.rs
@@ -1,28 +1,30 @@
+use std::{ffi::OsStr, path::Path, sync::Arc, time::Instant};
+#[cfg(feature = "hot-reload")]
use std::{
- ffi::OsStr,
- path::Path,
sync::{
- Arc,
atomic::{AtomicBool, Ordering},
mpsc::{Receiver, Sender},
},
- time::{Duration, Instant, SystemTime},
+ time::{Duration, SystemTime},
};
use rustc_hash::FxHashMap;
use smol::{Task, block_on, unblock};
-use crate::script::{WasmRunner, wasm::WasmModule};
+use crate::script::wasm::{WasmModule, WasmRunner};
type FileTask = Task<std::io::Result<WasmModule>>;
pub struct FileManager {
+ #[cfg(feature = "hot-reload")]
watcher: Notifier,
+ #[cfg(feature = "hot-reload")]
updated_files: Receiver<Box<Path>>,
active_tasks: FxHashMap<Box<Path>, FileTask>,
cache: FxHashMap<Box<Path>, Arc<std::io::Result<WasmModule>>>,
}
+#[cfg(feature = "hot-reload")]
struct Notifier {
paths: Arc<spin::Mutex<Vec<Box<Path>>>>,
cancel_token: Arc<AtomicBool>,
@@ -39,6 +41,7 @@ fn compile_data(path: &Path, data: &[u8], compiler: &WasmRunner) -> std::io::Res
Err(std::io::Error::other("Unrecognized file extension"))
}
+#[cfg(feature = "hot-reload")]
impl Notifier {
pub fn new(channel: Sender<Box<Path>>, interval: Duration) -> Self {
let paths = Arc::new(spin::Mutex::new(Vec::new()));
@@ -84,12 +87,16 @@ impl Notifier {
impl FileManager {
pub fn new() -> Self {
+ #[cfg(feature = "hot-reload")]
let (sender, updated_files) = std::sync::mpsc::channel();
- let watcher = Notifier::new(sender, Duration::from_secs(10));
+ #[cfg(feature = "hot-reload")]
+ let watcher = Notifier::new(sender, Duration::from_secs(2));
Self {
active_tasks: FxHashMap::default(),
cache: FxHashMap::default(),
+ #[cfg(feature = "hot-reload")]
watcher,
+ #[cfg(feature = "hot-reload")]
updated_files,
}
}
@@ -116,6 +123,7 @@ impl FileManager {
self.cache.entry(path.clone()).insert_entry(Arc::new(data));
}
+ #[cfg(feature = "hot-reload")]
self.watcher.watch(path.clone());
self.cache.get(&path).unwrap().clone()
}
@@ -130,10 +138,12 @@ impl FileManager {
&compiler,
)
});
+ #[cfg(feature = "hot-reload")]
self.watcher.watch(path.clone());
self.active_tasks.insert(path, task);
}
+ #[cfg(feature = "hot-reload")]
pub fn reload_files(&mut self, wasm_compiler: &WasmRunner) {
while let Ok(path) = self.updated_files.try_recv() {
log::info!("reloading {}", path.to_string_lossy());
@@ -169,6 +179,7 @@ impl Default for FileManager {
}
}
+#[cfg(feature = "hot-reload")]
impl Drop for Notifier {
fn drop(&mut self) {
self.cancel_token.store(true, Ordering::Release);
diff --git a/src/input.rs b/src/input.rs
index 3eea33c..c12d622 100644
--- a/src/input.rs
+++ b/src/input.rs
@@ -1,11 +1,16 @@
-use std::{collections::VecDeque, fmt::Debug, time::Duration};
+#[cfg(feature = "gilrs")]
+use std::time::Duration;
+use std::{collections::VecDeque, fmt::Debug};
use crossterm::event::KeyCode;
+#[cfg(feature = "gilrs")]
use gilrs::{
Axis, Button, GamepadId, Gilrs, PowerInfo,
ff::{BaseEffect, Replay, Ticks},
};
-use rustc_hash::{FxHashMap, FxHashSet};
+#[cfg(feature = "gilrs")]
+use rustc_hash::FxHashMap;
+use rustc_hash::FxHashSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
@@ -22,6 +27,7 @@ pub struct Position {
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg(feature = "gilrs")]
struct ControllerButton {
gamepad_id: usize,
button: Button,
@@ -36,11 +42,16 @@ pub struct InputManager {
is_focused: bool,
is_focused_this_frame: bool,
is_unfocused_this_frame: bool,
+ #[cfg(feature = "gilrs")]
gil_cx: Option<Gilrs>,
+ #[cfg(feature = "gilrs")]
gamepad_map: FxHashMap<usize, GamepadId>,
+ #[cfg(feature = "gilrs")]
gamepad_map_rev: FxHashMap<GamepadId, usize>,
connected_gamepads: VecDeque<usize>,
+ #[cfg(feature = "gilrs")]
pressed_buttons: FxHashSet<ControllerButton>,
+ #[cfg(feature = "gilrs")]
released_buttons: FxHashSet<ControllerButton>,
}
@@ -54,11 +65,16 @@ impl InputManager {
is_focused: true,
is_focused_this_frame: false,
is_unfocused_this_frame: false,
+ #[cfg(feature = "gilrs")]
gil_cx: Gilrs::new().ok(),
+ #[cfg(feature = "gilrs")]
gamepad_map: FxHashMap::default(),
+ #[cfg(feature = "gilrs")]
gamepad_map_rev: FxHashMap::default(),
connected_gamepads: VecDeque::new(),
+ #[cfg(feature = "gilrs")]
pressed_buttons: FxHashSet::default(),
+ #[cfg(feature = "gilrs")]
released_buttons: FxHashSet::default(),
}
}
@@ -80,13 +96,16 @@ impl InputManager {
}
pub fn reset_next_frame(&mut self) {
+ #[cfg(feature = "puffin")]
puffin::profile_function!();
self.pressed_keys.clear();
self.mouse_clicked = false;
self.scroll_direction = None;
self.is_focused_this_frame = false;
self.is_unfocused_this_frame = false;
+ #[cfg(feature = "gilrs")]
self.pressed_buttons.clear();
+ #[cfg(feature = "gilrs")]
self.released_buttons.clear();
self.connected_gamepads.pop_front();
}
@@ -107,6 +126,10 @@ impl InputManager {
self.scroll_direction
}
+ #[cfg(not(feature = "gilrs"))]
+ pub fn read_gil_events(&mut self) {}
+
+ #[cfg(feature = "gilrs")]
pub fn read_gil_events(&mut self) {
let Some(gil) = self.gil_cx.as_mut() else {
return;
@@ -143,16 +166,19 @@ impl InputManager {
self.connected_gamepads.front().copied()
}
+ #[cfg(feature = "gilrs")]
pub fn is_button_pressed_this_frame(&self, gamepad_id: usize, button: Button) -> bool {
self.pressed_buttons
.contains(&ControllerButton { gamepad_id, button })
}
+ #[cfg(feature = "gilrs")]
pub fn is_button_released_this_frame(&self, gamepad_id: usize, button: Button) -> bool {
self.released_buttons
.contains(&ControllerButton { gamepad_id, button })
}
+ #[cfg(feature = "gilrs")]
pub fn is_button_down(&self, gamepad_id: usize, button: Button) -> bool {
self.gamepad_map.get(&gamepad_id).is_some_and(|id| {
self.gil_cx
@@ -161,12 +187,14 @@ impl InputManager {
})
}
+ #[cfg(feature = "gilrs")]
pub fn axis_value(&self, gamepad_id: usize, axis: Axis) -> Option<f32> {
self.gamepad_map
.get(&gamepad_id)
.and_then(|id| self.gil_cx.as_ref().map(|gil| gil.gamepad(*id).value(axis)))
}
+ #[cfg(feature = "gilrs")]
pub fn is_gamepad_connected(&self, gamepad_id: usize) -> bool {
self.gamepad_map.get(&gamepad_id).is_some_and(|id| {
self.gil_cx
@@ -175,6 +203,7 @@ impl InputManager {
})
}
+ #[cfg(feature = "gilrs")]
pub fn gamepad_power_info(&self, gamepad_id: usize) -> Option<PowerInfo> {
self.gamepad_map.get(&gamepad_id).and_then(|id| {
self.gil_cx
@@ -183,6 +212,7 @@ impl InputManager {
})
}
+ #[cfg(feature = "gilrs")]
pub fn vibrate(&mut self, gamepad_id: usize, intensity: f32, duration: Duration) {
let Some(gamepad_id) = self.gamepad_map.get(&gamepad_id) else {
return;
@@ -202,7 +232,7 @@ impl InputManager {
play_for: Ticks::from_ms(duration.as_millis() as u32),
with_delay: Ticks::from_ms(0),
},
- envelope: todo!(),
+ envelope: gilrs::ff::Envelope::default(),
})
.repeat(gilrs::ff::Repeat::For(Ticks::from_ms(
duration.as_millis() as u32
diff --git a/src/lib.rs b/src/lib.rs
index 1418ebd..4e6f788 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,5 @@
pub mod buffer;
+#[cfg(feature = "tinywasm")]
pub mod file;
pub mod input;
pub mod manifest;
@@ -9,24 +10,26 @@ pub mod time;
use crate::{
buffer::{Buffer, Event},
- file::FileManager,
input::{Direction, InputManager, Position},
manifest::GameManifest,
scene::switch_scenes,
- script::{ScriptContext, ScriptManager, WasmRunner},
+ script::{ScriptContext, ScriptManager},
storage::StorageManager,
time::TimeContext,
};
+#[cfg(feature = "tinywasm")]
+use crate::{file::FileManager, script::wasm::WasmRunner};
use crossterm::event::MouseEventKind;
use etcetera::AppStrategy;
use prologger::{ColorMode, ProLogger, RotationConfig};
+#[cfg(feature = "tinywasm")]
+use std::{fs::File, io::BufRead, path::PathBuf};
use std::{
- fs::File,
- io::{BufRead, BufWriter},
- path::PathBuf,
+ io::BufWriter,
time::{Duration, Instant},
};
+#[cfg(feature = "tinywasm")]
pub fn apply_patches(
manifest: &mut GameManifest,
files: &mut FileManager,
@@ -69,7 +72,11 @@ pub fn init_logger(manifest: &GameManifest) {
.unwrap();
}
-pub fn run_game(mut files: FileManager, wasm_runner: WasmRunner, manifest: GameManifest) {
+pub fn run_game(
+ #[cfg(feature = "tinywasm")] mut files: FileManager,
+ #[cfg(feature = "tinywasm")] wasm_runner: WasmRunner,
+ manifest: GameManifest,
+) {
let start = Instant::now();
let stdout = Box::new(BufWriter::new(std::io::stdout().lock()));
@@ -93,7 +100,9 @@ pub fn run_game(mut files: FileManager, wasm_runner: WasmRunner, manifest: GameM
switch_scenes(
&mut scripts,
&mut context,
+ #[cfg(feature = "tinywasm")]
&mut files,
+ #[cfg(feature = "tinywasm")]
&wasm_runner,
manifest.first_scene,
);
@@ -102,8 +111,11 @@ pub fn run_game(mut files: FileManager, wasm_runner: WasmRunner, manifest: GameM
scene_start.elapsed().as_millis()
);
+ #[cfg(feature = "puffin")]
let server_addr = format!("127.0.0.1:{}", puffin_http::DEFAULT_PORT);
+ #[cfg(feature = "puffin")]
let _puffin_server = puffin_http::Server::new(&server_addr).unwrap();
+ #[cfg(feature = "puffin")]
puffin::set_scopes_on(true);
log::info!("Total startup time: {} ms", start.elapsed().as_millis());
@@ -138,7 +150,6 @@ pub fn run_game(mut files: FileManager, wasm_runner: WasmRunner, manifest: GameM
}
Event::Render => {
input.read_gil_events();
- buffer.cells.clear();
let mut context = ScriptContext {
framerate_limit: &mut framerate_limit,
manifest: &manifest,
@@ -148,13 +159,20 @@ pub fn run_game(mut files: FileManager, wasm_runner: WasmRunner, manifest: GameM
time: &time,
operation_queue: Vec::new(),
};
- scripts.run_scripts(&mut context, &wasm_runner, &mut files);
+ scripts.run_scripts(
+ &mut context,
+ #[cfg(feature = "tinywasm")]
+ &wasm_runner,
+ #[cfg(feature = "tinywasm")]
+ &mut files,
+ );
+ #[cfg(all(feature = "tinywasm", feature = "hot-reload"))]
files.reload_files(&wasm_runner);
input.reset_next_frame();
if let Some(framerate_limit) = framerate_limit
&& let Ok(elapsed) = time.system_now().elapsed()
{
- std::thread::sleep(framerate_limit - elapsed);
+ spin_sleep::sleep(framerate_limit.saturating_sub(elapsed));
}
time.next_frame();
}
diff --git a/src/main.rs b/src/main.rs
index 6f5a695..9c00c67 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,14 +1,19 @@
+#[cfg(feature = "tinywasm")]
use std::path::{Path, PathBuf};
+#[cfg(feature = "tinywasm")]
use bpaf::Bpaf;
-use tortuise::{apply_patches, file::FileManager, init_logger, script::WasmRunner};
+#[cfg(feature = "tinywasm")]
+use tortuise::{apply_patches, file::FileManager, init_logger, script::wasm::WasmRunner};
#[derive(Debug, Clone, Bpaf)]
#[bpaf(options)]
+#[cfg(feature = "tinywasm")]
struct Options {
module: PathBuf,
}
+#[cfg(feature = "tinywasm")]
fn main() {
let mut files = FileManager::default();
let wasm_runner = WasmRunner::new();
@@ -24,3 +29,8 @@ fn main() {
};
tortuise::run_game(files, wasm_runner, manifest);
}
+
+#[cfg(not(feature = "tinywasm"))]
+fn main() {
+ panic!("WebAssembly support is needed for a main runtime.");
+}
diff --git a/src/scene.rs b/src/scene.rs
index aa4a443..cdb3488 100644
--- a/src/scene.rs
+++ b/src/scene.rs
@@ -1,10 +1,9 @@
use rustc_hash::FxHashSet;
use serde::{Deserialize, Serialize};
-use crate::{
- file::FileManager,
- script::{ScriptContext, ScriptManager, WasmRunner},
-};
+use crate::script::{ScriptContext, ScriptManager};
+#[cfg(feature = "tinywasm")]
+use crate::{file::FileManager, script::wasm::WasmRunner};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Scene {
@@ -25,8 +24,8 @@ pub fn scene_id_by_name(scenes: &[Scene], name: &str) -> Option<usize> {
pub fn switch_scenes(
scripts: &mut ScriptManager,
context: &mut ScriptContext<'_>,
- files: &mut FileManager,
- wasm_runner: &WasmRunner,
+ #[cfg(feature = "tinywasm")] files: &mut FileManager,
+ #[cfg(feature = "tinywasm")] wasm_runner: &WasmRunner,
new: usize,
) {
let active_scripts = scripts
@@ -35,13 +34,27 @@ pub fn switch_scenes(
.cloned()
.collect::<Box<[usize]>>();
for script_id in &active_scripts {
- scripts.deactivate_script(*script_id, context, wasm_runner, files);
+ scripts.deactivate_script(
+ *script_id,
+ context,
+ #[cfg(feature = "tinywasm")]
+ wasm_runner,
+ #[cfg(feature = "tinywasm")]
+ files,
+ );
}
let mut needed_scripts = FxHashSet::default();
let scene = &context.manifest.scenes[new];
for script_id in &scene.scripts {
needed_scripts.insert(*script_id);
- scripts.activate_script(*script_id, context, wasm_runner, files);
+ scripts.activate_script(
+ *script_id,
+ context,
+ #[cfg(feature = "tinywasm")]
+ wasm_runner,
+ #[cfg(feature = "tinywasm")]
+ files,
+ );
}
}
diff --git a/src/script.rs b/src/script.rs
index 306ea49..6ebc3f6 100644
--- a/src/script.rs
+++ b/src/script.rs
@@ -1,20 +1,25 @@
-use std::{path::Path, sync::Arc, time::Duration};
+#[cfg(feature = "tinywasm")]
+use std::path::Path;
+use std::{sync::Arc, time::Duration};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
+#[cfg(feature = "tinywasm")]
+use crate::file::FileManager;
use crate::{
buffer::{Buffer, Cell},
- file::FileManager,
input::InputManager,
- manifest::{DeserializedGameManifest, GameManifest, GameManifestPatch},
+ manifest::GameManifest,
scene::switch_scenes,
- script::wasm::WasmModule,
storage::StorageManager,
time::TimeContext,
};
+#[cfg(feature = "tinywasm")]
+use wasm::WasmRunner;
-pub mod lua;
+// pub mod lua;
+#[cfg(feature = "tinywasm")]
pub mod wasm;
pub struct ScriptManager<'a> {
@@ -24,13 +29,6 @@ pub struct ScriptManager<'a> {
script_states: FxHashMap<usize, Box<[u8]>>,
}
-#[derive(Clone)]
-pub struct WasmRunner {
- pub engine: tinywasm::Engine,
- pub store: Arc<spin::Mutex<tinywasm::Store>>,
- pub linker: tinywasm::Imports,
-}
-
pub struct ScriptContext<'a> {
pub framerate_limit: &'a mut Option<Duration>,
pub manifest: &'a GameManifest,
@@ -48,14 +46,16 @@ pub struct FullScriptContext<'a> {
pub input: &'a InputManager,
pub time: &'a TimeContext,
pub scripts: &'a ScriptManager<'a>,
- pub files: Box<[Box<Path>]>,
pub storage: &'a StorageManager,
+ #[cfg(feature = "tinywasm")]
pub wasm_runner: &'a WasmRunner,
pub operation_queue: &'a mut Vec<Operation>,
}
pub enum Operation {
AddCell(Cell),
+ AddEternalCell(Cell),
+ RemoveEternalCell(Cell),
SetFrameLimit(Option<Duration>),
SwitchScene(usize),
ActivateScript(usize),
@@ -89,10 +89,8 @@ pub enum ScriptDeclaration {
update: StaticScriptFunction,
end: StaticScriptFunction,
},
- Wasm {
- name: Box<str>,
- path: Box<Path>,
- },
+ #[cfg(feature = "tinywasm")]
+ Wasm { name: Box<str>, path: Box<Path> },
}
impl<'a> ScriptContext<'a> {
@@ -102,120 +100,11 @@ impl<'a> ScriptContext<'a> {
}
}
-impl Default for WasmRunner {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl WasmRunner {
- pub fn new() -> Self {
- let engine = tinywasm::Engine::default();
- let mut store = tinywasm::Store::new(engine.clone());
- let linker = wasm::linker(&mut store).unwrap();
- let store = Arc::new(spin::Mutex::new(store));
- Self {
- engine,
- store,
- linker,
- }
- }
-
- pub fn compile(&self, data: &[u8]) -> Result<WasmModule, tinywasm::Error> {
- let module = tinywasm::parse_bytes(data)?;
- let instance = tinywasm::ModuleInstance::instantiate(
- &mut self.store.lock(),
- &module,
- Some(self.linker.clone()),
- )?;
- Ok(WasmModule { instance })
- }
-
- pub fn manifest(
- &self,
- path: Box<Path>,
- module: &WasmModule,
- ) -> Result<GameManifest, tinywasm::Error> {
- let mut store = self.store.lock();
- let offset = module
- .instance
- .func::<(), u32>(&store, "manifest_addr")?
- .call(&mut store, ())?;
- let length = module
- .instance
- .func::<(), u32>(&store, "manifest_len")?
- .call(&mut store, ())?;
- let manifest =
- module
- .instance
- .memory("memory")?
- .read_vec(&store, offset as usize, length as usize)?;
- let manifest =
- messagepack_serde::from_slice::<DeserializedGameManifest>(&manifest).unwrap();
- Ok(GameManifest::from_wasm(path, manifest))
- }
-
- pub fn patch(&self, module: &WasmModule) -> Result<GameManifestPatch, tinywasm::Error> {
- let mut store = self.store.lock();
- let offset = module
- .instance
- .func::<(), u32>(&store, "manifest_addr")?
- .call(&mut store, ())?;
- let length = module
- .instance
- .func::<(), u32>(&store, "manifest_len")?
- .call(&mut store, ())?;
- let manifest =
- module
- .instance
- .memory("memory")?
- .read_vec(&store, offset as usize, length as usize)?;
- let manifest = messagepack_serde::from_slice::<GameManifestPatch>(&manifest).unwrap();
- Ok(manifest)
- }
-
- #[expect(clippy::too_many_arguments)]
- pub fn run_function(
- &self,
- script_id: usize,
- module: &WasmModule,
- scripts: &ScriptManager,
- files: Box<[Box<Path>]>,
- wasm_runner: &WasmRunner,
- context: &mut ScriptContext<'_>,
- function_name: &str,
- ) -> Result<(), tinywasm::Error> {
- puffin::profile_function!();
-
- let context = std::ptr::from_mut(Box::leak(Box::new(FullScriptContext {
- script_id,
- manifest: context.manifest,
- buffer: context.buffer,
- input: context.input,
- time: context.time,
- storage: context.storage,
- scripts,
- files,
- wasm_runner,
- operation_queue: &mut context.operation_queue,
- })));
-
- let function = module
- .instance
- .func::<u64, ()>(&wasm_runner.store.lock(), function_name)?;
- let r = function.call(
- &mut wasm_runner.store.lock(),
- context.expose_provenance() as u64,
- );
- drop(unsafe { Box::from_raw(context) });
- r
- }
-}
-
impl ScriptDeclaration {
pub fn name(&self) -> &str {
match self {
Self::Static { name, .. } => name,
+ #[cfg(feature = "tinywasm")]
Self::Wasm { name, .. } => name,
}
}
@@ -239,6 +128,7 @@ impl<'a> ScriptManager<'a> {
return Some(i);
}
}
+ #[cfg(feature = "tinywasm")]
ScriptDeclaration::Wasm { name, .. } => {
if &**name == needle {
return Some(i);
@@ -253,12 +143,14 @@ impl<'a> ScriptManager<'a> {
pub fn handle_queue(
&mut self,
context: &mut ScriptContext<'_>,
- wasm_runner: &WasmRunner,
- files: &mut FileManager,
+ #[cfg(feature = "tinywasm")] wasm_runner: &WasmRunner,
+ #[cfg(feature = "tinywasm")] files: &mut FileManager,
) {
for operation in &context.operation_queue {
match operation {
- Operation::AddCell(cell) => context.buffer.cells.push(*cell),
+ Operation::AddCell(cell) => context.buffer.add_ephemeral_cell(*cell),
+ Operation::AddEternalCell(cell) => context.buffer.add_eternal_cell(*cell),
+ Operation::RemoveEternalCell(cell) => context.buffer.remove_eternal_cell(*cell),
Operation::SetFrameLimit(duration) => *context.framerate_limit = *duration,
Operation::SwitchScene(id) => switch_scenes(
self,
@@ -271,7 +163,9 @@ impl<'a> ScriptManager<'a> {
storage: context.storage,
operation_queue: Vec::new(),
},
+ #[cfg(feature = "tinywasm")]
files,
+ #[cfg(feature = "tinywasm")]
wasm_runner,
*id,
),
@@ -286,7 +180,9 @@ impl<'a> ScriptManager<'a> {
operation_queue: Vec::new(),
framerate_limit: context.framerate_limit,
},
+ #[cfg(feature = "tinywasm")]
wasm_runner,
+ #[cfg(feature = "tinywasm")]
files,
),
Operation::DeactivateScript(id) => self.deactivate_script(
@@ -300,7 +196,9 @@ impl<'a> ScriptManager<'a> {
operation_queue: Vec::new(),
framerate_limit: context.framerate_limit,
},
+ #[cfg(feature = "tinywasm")]
wasm_runner,
+ #[cfg(feature = "tinywasm")]
files,
),
Operation::UpdateState {
@@ -328,8 +226,8 @@ impl<'a> ScriptManager<'a> {
&mut self,
script_id: usize,
context: &mut ScriptContext<'_>,
- wasm_runner: &WasmRunner,
- files: &mut FileManager,
+ #[cfg(feature = "tinywasm")] wasm_runner: &WasmRunner,
+ #[cfg(feature = "tinywasm")] files: &mut FileManager,
) {
let Some(script_declaration) = self.scripts.get(script_id) else {
unreachable!("The active script does not exist");
@@ -337,7 +235,6 @@ impl<'a> ScriptManager<'a> {
match script_declaration {
ScriptDeclaration::Static { start, .. } => {
start.as_ref().inspect(|s| {
- let loaded_files = files.loaded_files();
s(FullScriptContext {
script_id,
manifest: context.manifest,
@@ -345,22 +242,21 @@ impl<'a> ScriptManager<'a> {
input: context.input,
time: context.time,
scripts: self,
- files: loaded_files,
storage: context.storage,
+ #[cfg(feature = "tinywasm")]
wasm_runner,
operation_queue: &mut context.operation_queue,
})
});
}
+ #[cfg(feature = "tinywasm")]
ScriptDeclaration::Wasm { path, .. } => {
let module = files.load_file(path.clone(), wasm_runner);
let module = module.as_ref().as_ref().unwrap();
- let loaded_files = files.loaded_files();
if let Err(e) = wasm_runner.run_function(
script_id,
module,
self,
- loaded_files,
wasm_runner,
context,
"start_script",
@@ -370,15 +266,21 @@ impl<'a> ScriptManager<'a> {
}
}
self.active_scripts.push(script_id);
- self.handle_queue(context, wasm_runner, files);
+ self.handle_queue(
+ context,
+ #[cfg(feature = "tinywasm")]
+ wasm_runner,
+ #[cfg(feature = "tinywasm")]
+ files,
+ );
}
pub fn deactivate_script(
&mut self,
script_id: usize,
context: &mut ScriptContext<'_>,
- wasm_runner: &WasmRunner,
- files: &mut FileManager,
+ #[cfg(feature = "tinywasm")] wasm_runner: &WasmRunner,
+ #[cfg(feature = "tinywasm")] files: &mut FileManager,
) {
for script_id in self
.active_scripts
@@ -393,7 +295,6 @@ impl<'a> ScriptManager<'a> {
match script {
ScriptDeclaration::Static { end, .. } => {
end.as_ref().inspect(|s| {
- let loaded_files = files.loaded_files();
s(FullScriptContext {
script_id,
manifest: context.manifest,
@@ -401,22 +302,21 @@ impl<'a> ScriptManager<'a> {
input: context.input,
time: context.time,
scripts: self,
- files: loaded_files,
storage: context.storage,
+ #[cfg(feature = "tinywasm")]
wasm_runner,
operation_queue: &mut context.operation_queue,
});
});
}
+ #[cfg(feature = "tinywasm")]
ScriptDeclaration::Wasm { path, .. } => {
let module = files.load_file(path.clone(), wasm_runner);
let module = module.as_ref().as_ref().unwrap();
- let loaded_files = files.loaded_files();
if let Err(e) = wasm_runner.run_function(
script_id,
module,
self,
- loaded_files,
wasm_runner,
context,
"end_script",
@@ -427,25 +327,37 @@ impl<'a> ScriptManager<'a> {
};
}
self.active_scripts.retain(|element| *element != script_id);
- self.handle_queue(context, wasm_runner, files);
+ self.handle_queue(
+ context,
+ #[cfg(feature = "tinywasm")]
+ wasm_runner,
+ #[cfg(feature = "tinywasm")]
+ files,
+ );
}
pub fn run_scripts(
&mut self,
context: &mut ScriptContext<'_>,
- wasm_runner: &WasmRunner,
- files: &mut FileManager,
+ #[cfg(feature = "tinywasm")] wasm_runner: &WasmRunner,
+ #[cfg(feature = "tinywasm")] files: &mut FileManager,
) {
+ #[cfg(feature = "puffin")]
puffin::profile_function!();
for script_id in &self.active_scripts {
let Some(script) = self.scripts.get(*script_id) else {
unreachable!("The active script does not exist");
};
match script {
- ScriptDeclaration::Static { name, update, .. } => {
+ ScriptDeclaration::Static {
+ #[cfg(feature = "puffin")]
+ name,
+ update,
+ ..
+ } => {
if let Some(s) = update {
+ #[cfg(feature = "puffin")]
puffin::profile_scope!("run script", name);
- let loaded_files = files.loaded_files();
s(FullScriptContext {
script_id: *script_id,
manifest: context.manifest,
@@ -453,22 +365,21 @@ impl<'a> ScriptManager<'a> {
input: context.input,
time: context.time,
scripts: self,
- files: loaded_files,
storage: context.storage,
+ #[cfg(feature = "tinywasm")]
wasm_runner,
operation_queue: &mut context.operation_queue,
});
}
}
+ #[cfg(feature = "tinywasm")]
ScriptDeclaration::Wasm { path, .. } => {
let module = files.load_file(path.clone(), wasm_runner);
let module = module.as_ref().as_ref().unwrap();
- let loaded_files = files.loaded_files();
if let Err(e) = wasm_runner.run_function(
*script_id,
module,
self,
- loaded_files,
wasm_runner,
context,
"update_script",
@@ -478,6 +389,12 @@ impl<'a> ScriptManager<'a> {
}
}
}
- self.handle_queue(context, wasm_runner, files);
+ self.handle_queue(
+ context,
+ #[cfg(feature = "tinywasm")]
+ wasm_runner,
+ #[cfg(feature = "tinywasm")]
+ files,
+ );
}
}
diff --git a/src/script/wasm.rs b/src/script/wasm.rs
index aaf25cf..cb08ba2 100644
--- a/src/script/wasm.rs
+++ b/src/script/wasm.rs
@@ -1,4 +1,8 @@
-use std::time::{Duration, UNIX_EPOCH};
+use std::{
+ path::Path,
+ sync::Arc,
+ time::{Duration, UNIX_EPOCH},
+};
use crossterm::{
event::KeyCode,
@@ -6,14 +10,139 @@ use crossterm::{
};
use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
-use crate::{buffer::Cell, script::FullScriptContext};
+use crate::{
+ buffer::Cell,
+ manifest::{DeserializedGameManifest, GameManifest, GameManifestPatch},
+ script::{FullScriptContext, ScriptContext, ScriptManager},
+};
use super::Operation;
+#[derive(Clone)]
+pub struct WasmRunner {
+ pub engine: tinywasm::Engine,
+ pub store: Arc<spin::Mutex<tinywasm::Store>>,
+ pub linker: tinywasm::Imports,
+}
+
pub struct WasmModule {
pub instance: ModuleInstance,
}
+macro_rules! profile_function {
+ () => {
+ #[cfg(feature = "puffin")]
+ puffin::profile_function!();
+ };
+}
+
+impl Default for WasmRunner {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl WasmRunner {
+ pub fn new() -> Self {
+ let engine = tinywasm::Engine::default();
+ let mut store = tinywasm::Store::new(engine.clone());
+ let linker = linker(&mut store).unwrap();
+ let store = Arc::new(spin::Mutex::new(store));
+ Self {
+ engine,
+ store,
+ linker,
+ }
+ }
+
+ pub fn compile(&self, data: &[u8]) -> Result<WasmModule, tinywasm::Error> {
+ let module = tinywasm::parse_bytes(data)?;
+ let instance = tinywasm::ModuleInstance::instantiate(
+ &mut self.store.lock(),
+ &module,
+ Some(self.linker.clone()),
+ )?;
+ Ok(WasmModule { instance })
+ }
+
+ pub fn manifest(
+ &self,
+ path: Box<Path>,
+ module: &WasmModule,
+ ) -> Result<GameManifest, tinywasm::Error> {
+ let mut store = self.store.lock();
+ let offset = module
+ .instance
+ .func::<(), u32>(&store, "manifest_addr")?
+ .call(&mut store, ())?;
+ let length = module
+ .instance
+ .func::<(), u32>(&store, "manifest_len")?
+ .call(&mut store, ())?;
+ let manifest =
+ module
+ .instance
+ .memory("memory")?
+ .read_vec(&store, offset as usize, length as usize)?;
+ let manifest =
+ messagepack_serde::from_slice::<DeserializedGameManifest>(&manifest).unwrap();
+ Ok(GameManifest::from_wasm(path, manifest))
+ }
+
+ pub fn patch(&self, module: &WasmModule) -> Result<GameManifestPatch, tinywasm::Error> {
+ let mut store = self.store.lock();
+ let offset = module
+ .instance
+ .func::<(), u32>(&store, "manifest_addr")?
+ .call(&mut store, ())?;
+ let length = module
+ .instance
+ .func::<(), u32>(&store, "manifest_len")?
+ .call(&mut store, ())?;
+ let manifest =
+ module
+ .instance
+ .memory("memory")?
+ .read_vec(&store, offset as usize, length as usize)?;
+ let manifest = messagepack_serde::from_slice::<GameManifestPatch>(&manifest).unwrap();
+ Ok(manifest)
+ }
+
+ pub fn run_function(
+ &self,
+ script_id: usize,
+ module: &WasmModule,
+ scripts: &ScriptManager,
+ wasm_runner: &WasmRunner,
+ context: &mut ScriptContext<'_>,
+ function_name: &str,
+ ) -> Result<(), tinywasm::Error> {
+ profile_function!();
+
+ let context = std::ptr::from_mut(Box::leak(Box::new(FullScriptContext {
+ script_id,
+ manifest: context.manifest,
+ buffer: context.buffer,
+ input: context.input,
+ time: context.time,
+ storage: context.storage,
+ scripts,
+ wasm_runner,
+ operation_queue: &mut context.operation_queue,
+ })));
+
+ let function = module
+ .instance
+ .func::<u64, ()>(&wasm_runner.store.lock(), function_name)?;
+ let r = function.call(
+ &mut wasm_runner.store.lock(),
+ context.expose_provenance() as u64,
+ );
+ drop(unsafe { Box::from_raw(context) });
+ r
+ }
+}
+
fn str_from_memory(caller: &FuncContext<'_>, offset: u32, length: u32) -> tinywasm::Result<String> {
let memory = caller.memory("memory").unwrap();
memory.read_string(caller.store(), offset as usize, length as usize)
@@ -35,6 +164,7 @@ fn context_ref<'b>(address: u64) -> &'b FullScriptContext<'b> {
}
}
+#[cfg(feature = "gilrs")]
fn number_to_button(number: u32) -> gilrs::Button {
match number {
0 => gilrs::Button::Unknown,
@@ -61,6 +191,7 @@ fn number_to_button(number: u32) -> gilrs::Button {
}
}
+#[cfg(feature = "gilrs")]
fn number_to_axis(number: u32) -> gilrs::Axis {
match number {
0 => gilrs::Axis::Unknown,
@@ -76,33 +207,15 @@ fn number_to_axis(number: u32) -> gilrs::Axis {
}
}
-fn set_framerate_limit(
- _caller: FuncContext<'_>,
- (context, limit): (u64, u32),
-) -> tinywasm::Result<()> {
- puffin::profile_function!();
- let context = context_mut(context);
- let duration = (limit != 0).then(|| Duration::from_nanos(1_000_000_000 / limit as u64));
- context
- .operation_queue
- .push(Operation::SetFrameLimit(duration));
- Ok(())
-}
-
-fn add_cell(
- _caller: FuncContext<'_>,
- (
- context,
- character,
- location,
- z,
- foreground_color,
- background_color,
- underline_color,
- attributes,
- ): (u64, u32, u32, u32, u32, u32, u32, u32),
-) -> tinywasm::Result<()> {
- puffin::profile_function!();
+fn create_cell(
+ character: u32,
+ location: u32,
+ z: u32,
+ foreground_color: u32,
+ background_color: u32,
+ underline_color: u32,
+ attributes: u32,
+) -> Cell {
const STANDARD_COLOR: u32 = 1 << 24;
const ANSI_COLOR: u32 = 2 << 24;
const RGB_COLOR: u32 = 3 << 24;
@@ -194,25 +307,119 @@ fn add_cell(
attribute_set.set(Attribute::OverLined);
}
+ Cell {
+ character: char::from_u32(character).unwrap_or_default(),
+ style: ContentStyle {
+ foreground_color: get_color(foreground_color),
+ background_color: get_color(background_color),
+ underline_color: get_color(underline_color),
+ attributes: attribute_set,
+ },
+ x: (location >> 16) as u16,
+ y: (location & 0xffff) as u16,
+ z: z as u8,
+ }
+}
+
+fn set_framerate_limit(
+ _caller: FuncContext<'_>,
+ (context, limit): (u64, u32),
+) -> tinywasm::Result<()> {
+ profile_function!();
+ let context = context_mut(context);
+ let duration = (limit != 0).then(|| Duration::from_nanos(1_000_000_000 / limit as u64));
+ context
+ .operation_queue
+ .push(Operation::SetFrameLimit(duration));
+ Ok(())
+}
+
+fn add_cell(
+ _caller: FuncContext<'_>,
+ (
+ context,
+ character,
+ location,
+ z,
+ foreground_color,
+ background_color,
+ underline_color,
+ attributes,
+ ): (u64, u32, u32, u32, u32, u32, u32, u32),
+) -> tinywasm::Result<()> {
+ profile_function!();
+ context_mut(context)
+ .operation_queue
+ .push(Operation::AddCell(create_cell(
+ character,
+ location,
+ z,
+ foreground_color,
+ background_color,
+ underline_color,
+ attributes,
+ )));
+ Ok(())
+}
+
+fn add_eternal_cell(
+ _caller: FuncContext<'_>,
+ (
+ context,
+ character,
+ location,
+ z,
+ foreground_color,
+ background_color,
+ underline_color,
+ attributes,
+ ): (u64, u32, u32, u32, u32, u32, u32, u32),
+) -> tinywasm::Result<()> {
+ profile_function!();
+ context_mut(context)
+ .operation_queue
+ .push(Operation::AddEternalCell(create_cell(
+ character,
+ location,
+ z,
+ foreground_color,
+ background_color,
+ underline_color,
+ attributes,
+ )));
+ Ok(())
+}
+
+fn remove_eternal_cell(
+ _caller: FuncContext<'_>,
+ (
+ context,
+ character,
+ location,
+ z,
+ foreground_color,
+ background_color,
+ underline_color,
+ attributes,
+ ): (u64, u32, u32, u32, u32, u32, u32, u32),
+) -> tinywasm::Result<()> {
+ profile_function!();
context_mut(context)
.operation_queue
- .push(Operation::AddCell(Cell {
- character: char::from_u32(character).unwrap_or_default(),
- style: ContentStyle {
- foreground_color: get_color(foreground_color),
- background_color: get_color(background_color),
- underline_color: get_color(underline_color),
- attributes: attribute_set,
- },
- x: (location >> 16) as u16,
- y: (location & 0xffff) as u16,
- z: z as u8,
- }));
+ .push(Operation::RemoveEternalCell(create_cell(
+ character,
+ location,
+ z,
+ foreground_color,
+ background_color,
+ underline_color,
+ attributes,
+ )));
Ok(())
}
fn window_size(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
let window_size = &context_ref(context).buffer.window_size;
Ok(((window_size.rows as u32) << 16) | (window_size.columns as u32))
}
@@ -221,7 +428,7 @@ fn is_key_pressed_this_frame(
_caller: FuncContext<'_>,
(context, key_code): (u64, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
const BACKSPACE: u32 = 1 << 24;
const ENTER: u32 = 2 << 24;
const LEFT: u32 = 3 << 24;
@@ -277,7 +484,7 @@ fn is_mouse_clicked_this_frame(
_caller: FuncContext<'_>,
(context,): (u64,),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
if context_ref(context).input.is_mouse_clicked_this_frame() {
Ok(1)
} else {
@@ -286,7 +493,7 @@ fn is_mouse_clicked_this_frame(
}
fn mouse_location(_caller: FuncContext<'_>, (context,): (u64,)) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
let location = context_ref(context).input.mouse_location();
if let Some(location) = location {
@@ -300,13 +507,13 @@ fn scroll_direction_this_frame(
_caller: FuncContext<'_>,
(context,): (u64,),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
let direction = context_ref(context).input.scroll_direction_this_frame();
Ok(direction.map(|d| d as u32).unwrap_or_default())
}
fn is_focused(_caller: FuncContext<'_>, (context,): (u64,)) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(if context_ref(context).input.is_focused() {
1
} else {
@@ -318,18 +525,19 @@ fn is_gamepad_connected_this_frame(
_caller: FuncContext<'_>,
context: u64,
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(context_ref(context)
.input
.is_gamepad_connected_this_frame()
.unwrap_or_default() as u32)
}
+#[cfg(feature = "gilrs")]
fn is_button_pressed_this_frame(
_caller: FuncContext<'_>,
(context, gamepad_id, button): (u64, u32, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(
if context_ref(context)
.input
@@ -342,11 +550,21 @@ fn is_button_pressed_this_frame(
)
}
+#[cfg(not(feature = "gilrs"))]
+fn is_button_pressed_this_frame(
+ _caller: FuncContext<'_>,
+ (_cx, _id, _button): (u64, u32, u32),
+) -> tinywasm::Result<u32> {
+ profile_function!();
+ Ok(0)
+}
+
+#[cfg(feature = "gilrs")]
fn is_button_released_this_frame(
_caller: FuncContext<'_>,
(context, gamepad_id, button): (u64, u32, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(
if context_ref(context)
.input
@@ -359,11 +577,21 @@ fn is_button_released_this_frame(
)
}
+#[cfg(not(feature = "gilrs"))]
+fn is_button_released_this_frame(
+ _caller: FuncContext<'_>,
+ (_cx, _id, _button): (u64, u32, u32),
+) -> tinywasm::Result<u32> {
+ profile_function!();
+ Ok(0)
+}
+
+#[cfg(feature = "gilrs")]
fn is_button_down(
_caller: FuncContext<'_>,
(context, gamepad_id, button): (u64, u32, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(
if context_ref(context)
.input
@@ -376,11 +604,21 @@ fn is_button_down(
)
}
+#[cfg(not(feature = "gilrs"))]
+fn is_button_down(
+ _caller: FuncContext<'_>,
+ (_cx, _id, _button): (u64, u32, u32),
+) -> tinywasm::Result<u32> {
+ profile_function!();
+ Ok(0)
+}
+
+#[cfg(feature = "gilrs")]
fn is_gamepad_connected(
_caller: FuncContext<'_>,
(context, gamepad_id): (u64, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(
if context_ref(context)
.input
@@ -393,22 +631,39 @@ fn is_gamepad_connected(
)
}
+#[cfg(not(feature = "gilrs"))]
+fn is_gamepad_connected(_caller: FuncContext<'_>, (_cx, _id): (u64, u32)) -> tinywasm::Result<u32> {
+ profile_function!();
+ Ok(0)
+}
+
+#[cfg(feature = "gilrs")]
fn axis_value(
_caller: FuncContext<'_>,
(context, gamepad_id, axis): (u64, u32, u32),
) -> tinywasm::Result<f32> {
- puffin::profile_function!();
+ profile_function!();
Ok(context_ref(context)
.input
.axis_value(gamepad_id as usize, number_to_axis(axis))
.unwrap_or_default())
}
+#[cfg(not(feature = "gilrs"))]
+fn axis_value(
+ _caller: FuncContext<'_>,
+ (_cx, _id, _axis): (u64, u32, u32),
+) -> tinywasm::Result<f32> {
+ profile_function!();
+ Ok(0.0)
+}
+
+#[cfg(feature = "gilrs")]
fn gamepad_power_info(
_caller: FuncContext<'_>,
(context, gamepad_id): (u64, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(
match context_ref(context)
.input
@@ -423,8 +678,13 @@ fn gamepad_power_info(
)
}
+#[cfg(not(feature = "gilrs"))]
+fn gamepad_power_info(_caller: FuncContext<'_>, (_cx, _id): (u64, u32)) -> tinywasm::Result<u32> {
+ Ok(0)
+}
+
fn was_focused_this_frame(_caller: FuncContext<'_>, (context,): (u64,)) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(if context_ref(context).input.was_focused_this_frame() {
1
} else {
@@ -433,7 +693,7 @@ fn was_focused_this_frame(_caller: FuncContext<'_>, (context,): (u64,)) -> tinyw
}
fn was_unfocused_this_frame(_caller: FuncContext<'_>, (context,): (u64,)) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(if context_ref(context).input.was_unfocused_this_frame() {
1
} else {
@@ -445,7 +705,7 @@ fn log(
caller: FuncContext<'_>,
(severity, offset, length): (u32, u32, u32),
) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let message = str_from_memory(&caller, offset, length)?;
let severity = match severity {
1 => log::Level::Error,
@@ -460,13 +720,13 @@ fn log(
}
fn exit(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
context_mut(context).operation_queue.push(Operation::Exit);
Ok(())
}
fn random_u64(_caller: FuncContext<'_>, (): ()) -> tinywasm::Result<u64> {
- puffin::profile_function!();
+ profile_function!();
Ok(getrandom::u64().unwrap_or(4))
}
@@ -474,7 +734,7 @@ fn scene_id_by_name(
caller: FuncContext<'_>,
(context, offset, length): (u64, u32, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
let name = str_from_memory(&caller, offset, length)?;
Ok(
crate::scene::scene_id_by_name(&context_ref(context).manifest.scenes, &name)
@@ -484,7 +744,7 @@ fn scene_id_by_name(
}
fn switch_scene(_caller: FuncContext<'_>, (context, id): (u64, u32)) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
context_mut(context)
.operation_queue
.push(Operation::SwitchScene(id as usize));
@@ -492,7 +752,7 @@ fn switch_scene(_caller: FuncContext<'_>, (context, id): (u64, u32)) -> tinywasm
}
fn script_name_size(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
let context = context_ref(context);
Ok(context.scripts.scripts[context.script_id].name().len() as u32)
}
@@ -501,7 +761,7 @@ fn load_script_name(
mut caller: FuncContext<'_>,
(context, offset): (u64, u32),
) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let memory = caller.memory("memory").unwrap();
let context = context_ref(context);
let name = context.scripts.scripts[context.script_id].name();
@@ -515,7 +775,7 @@ fn script_id_by_name(
caller: FuncContext<'_>,
(context, offset, length): (u64, u32, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
let name = str_from_memory(&caller, offset, length)?;
let context = context_ref(context);
Ok(context
@@ -526,7 +786,7 @@ fn script_id_by_name(
}
fn activate_script(_caller: FuncContext<'_>, (context, id): (u64, u32)) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
context_mut(context)
.operation_queue
.push(Operation::ActivateScript(id as usize));
@@ -534,7 +794,7 @@ fn activate_script(_caller: FuncContext<'_>, (context, id): (u64, u32)) -> tinyw
}
fn deactivate_script(_caller: FuncContext<'_>, (context, id): (u64, u32)) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
context_mut(context)
.operation_queue
.push(Operation::DeactivateScript(id as usize));
@@ -542,7 +802,7 @@ fn deactivate_script(_caller: FuncContext<'_>, (context, id): (u64, u32)) -> tin
}
fn state_size(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
let context = context_ref(context);
Ok(context
.scripts
@@ -553,7 +813,7 @@ fn state_size(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
}
fn load_state(mut caller: FuncContext<'_>, (context, offset): (u64, u32)) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let memory = caller.memory("memory").unwrap();
let context = context_ref(context);
let state = context
@@ -570,7 +830,7 @@ fn save_state(
mut caller: FuncContext<'_>,
(context, offset, length): (u64, u32, u32),
) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let offset = offset as usize;
let length = length as usize;
let memory = caller.memory("memory").unwrap();
@@ -590,7 +850,7 @@ fn entity_size(
caller: FuncContext<'_>,
(context, name, name_len): (u64, u32, u32),
) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
let name = str_from_memory(&caller, name, name_len)?;
let context = context_ref(context);
Ok(context
@@ -605,7 +865,7 @@ fn load_entity(
mut caller: FuncContext<'_>,
(context, name, name_len, offset): (u64, u32, u32, u32),
) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let name = str_from_memory(&caller, name, name_len)?;
let memory = caller.memory("memory").unwrap();
let context = context_ref(context);
@@ -623,7 +883,7 @@ fn save_entity(
mut caller: FuncContext<'_>,
(context, name, name_len, offset, length): (u64, u32, u32, u32, u32),
) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let offset = offset as usize;
let length = length as usize;
let memory = caller.memory("memory").unwrap();
@@ -640,7 +900,7 @@ fn save_entity(
}
fn storage_size(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(context_ref(context)
.storage
.data()
@@ -652,7 +912,7 @@ fn load_storage(
mut caller: FuncContext<'_>,
(context, offset): (u64, u32),
) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let memory = caller.memory("memory").unwrap();
let context = context_ref(context);
let state = context.storage.data().unwrap_or(&[]);
@@ -664,7 +924,7 @@ fn save_storage(
mut caller: FuncContext<'_>,
(context, offset, length): (u64, u32, u32),
) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let offset = offset as usize;
let length = length as usize;
let memory = caller.memory("memory").unwrap();
@@ -680,7 +940,7 @@ fn save_storage(
}
fn is_saving_storage(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(if context_ref(context).storage.is_saving_data() {
1
} else {
@@ -689,7 +949,7 @@ fn is_saving_storage(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result
}
fn saving_storage_failed(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(if context_ref(context).storage.saving_data_failed() {
1
} else {
@@ -698,7 +958,7 @@ fn saving_storage_failed(_caller: FuncContext<'_>, context: u64) -> tinywasm::Re
}
fn config_size(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(context_ref(context)
.storage
.config()
@@ -707,7 +967,7 @@ fn config_size(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32>
}
fn load_config(mut caller: FuncContext<'_>, (context, offset): (u64, u32)) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let memory = caller.memory("memory").unwrap();
let context = context_ref(context);
let state = context.storage.config().unwrap_or(&[]);
@@ -719,7 +979,7 @@ fn save_config(
mut caller: FuncContext<'_>,
(context, offset, length): (u64, u32, u32),
) -> tinywasm::Result<()> {
- puffin::profile_function!();
+ profile_function!();
let offset = offset as usize;
let length = length as usize;
let memory = caller.memory("memory").unwrap();
@@ -735,7 +995,7 @@ fn save_config(
}
fn is_saving_config(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(if context_ref(context).storage.is_saving_config() {
1
} else {
@@ -744,7 +1004,7 @@ fn is_saving_config(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<
}
fn saving_config_failed(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u32> {
- puffin::profile_function!();
+ profile_function!();
Ok(if context_ref(context).storage.saving_config_failed() {
1
} else {
@@ -753,7 +1013,7 @@ fn saving_config_failed(_caller: FuncContext<'_>, context: u64) -> tinywasm::Res
}
fn system_now(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u64> {
- puffin::profile_function!();
+ profile_function!();
Ok(context_ref(context)
.time
.system_now()
@@ -763,12 +1023,12 @@ fn system_now(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u64> {
}
fn monotonic_now(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u64> {
- puffin::profile_function!();
+ profile_function!();
Ok(context_ref(context).time.monotonic_now().as_nanos() as u64)
}
fn delta_time(_caller: FuncContext<'_>, context: u64) -> tinywasm::Result<u64> {
- puffin::profile_function!();
+ profile_function!();
Ok(context_ref(context).time.delta_time().as_nanos() as u64)
}
@@ -785,6 +1045,8 @@ pub fn linker(store: &mut Store) -> Result<Imports, tinywasm::Error> {
store,
[
add_cell,
+ add_eternal_cell,
+ remove_eternal_cell,
window_size,
set_framerate_limit,
is_key_pressed_this_frame,
diff --git a/src/storage.rs b/src/storage.rs
index c099481..ba06ab2 100644
--- a/src/storage.rs
+++ b/src/storage.rs
@@ -78,6 +78,9 @@ impl StorageManager {
self.data = Some(data.clone());
unblock(move || {
if let Err(e) = {
+ if let Some(parent) = tmp_file.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
std::fs::write(&tmp_file, &data)?;
let saved_data = std::fs::read(&tmp_file)?;
diff --git a/src/time.rs b/src/time.rs
index 5978b57..d6f9e89 100644
--- a/src/time.rs
+++ b/src/time.rs
@@ -19,6 +19,7 @@ impl TimeContext {
}
pub fn next_frame(&mut self) {
+ #[cfg(feature = "puffin")]
puffin::profile_scope!("update time");
self.last_frame = self.current_frame;
self.current_frame = Instant::now();