7 Commits

14 changed files with 877 additions and 533 deletions

1151
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "uw8" name = "uw8"
version = "0.3.0" version = "0.4.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -11,7 +11,7 @@ native = ["wasmtime", "uw8-window", "cpal", "rubato" ]
browser = ["warp", "tokio", "tokio-stream", "webbrowser"] browser = ["warp", "tokio", "tokio-stream", "webbrowser"]
[dependencies] [dependencies]
wasmtime = { version = "19.0.1", optional = true } wasmtime = { git = "https://github.com/bytecodealliance/wasmtime.git", rev = "0f48f939b9870036562ca02ff21253547a9f1a5c", optional = true }
anyhow = "1" anyhow = "1"
env_logger = "0.11.3" env_logger = "0.11.3"
log = "0.4" log = "0.4"

View File

@@ -15,9 +15,9 @@ See [here](https://exoticorn.github.io/microw8/) for more information and docs.
## Downloads ## Downloads
* [Linux](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.3.0-linux.tgz) * [Linux](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.4.0-linux.tgz)
* [MacOS](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.3.0-macos.tgz) * [MacOS](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.4.0-macos.tgz)
* [Windows](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.3.0-windows.zip) * [Windows](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.4.0-windows.zip)
The download includes The download includes

View File

@@ -3,12 +3,14 @@ include "../include/microw8-api.cwa"
export fn upd() { export fn upd() {
let i: i32; let i: i32;
loop pixels { loop pixels {
let inline t = time() * 63 as f32; let inline t = 16!56;
let lazy x = (i % 320 - 160) as f32; let inline x = (i % 320 - 160) as f32;
let lazy y = (i / 320 - 120) as f32; let inline y = (i #/ 320 - 120) as f32;
let inline d = 40000 as f32 / sqrt(x * x + y * y); let inline d = 0xa000 as f32 / sqrt(x * x + y * y);
let inline u = atan2(x, y) * (512.0 / 3.141); let inline a = atan2(x, y) * 163_f; // (512 / pi)
let inline c = ((i32.trunc_sat_f32_s(d + t * 2 as f32) ^ i32.trunc_sat_f32_s(u + t)) & 255) >> 4; let inline u = i32.trunc_sat_f32_s(a) + t;
let inline v = i32.trunc_sat_f32_s(d) + t * 2;
let inline c = ((v ^ u) #/ 16) % 16;
i?FRAMEBUFFER = c; i?FRAMEBUFFER = c;
branch_if (i := i + 1) < 320*240: pixels; branch_if (i := i + 1) < 320*240: pixels;

Binary file not shown.

View File

@@ -31,19 +31,19 @@ Examplers for older versions:
## Versions ## Versions
### v0.3.0 ### v0.4.0
* [Web runtime](v0.3.0) * [Web runtime](../v0.4.0)
* [Linux](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.3.0-linux.tgz) * [Linux](https://github.com/exoticorn/microw8/releases/download/v0.4.0/microw8-0.4.0-linux.tgz)
* [MacOS](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.3.0-macos.tgz) * [MacOS](https://github.com/exoticorn/microw8/releases/download/v0.4.0/microw8-0.4.0-macos.tgz)
* [Windows](https://github.com/exoticorn/microw8/releases/download/v0.3.0/microw8-0.3.0-windows.zip) * [Windows](https://github.com/exoticorn/microw8/releases/download/v0.4.0/microw8-0.4.0-windows.zip)
Changes: Changes:
* add blitSprite and grabSprite API calls * add support for sound on mono- and surround-only devices
* add support for integer scaling up to 16x for printing text * update wasmtime dependency to fix performance regression in 0.3.0
* fix incompatibility with sound devices only offering 16bit audio formats * add frame counter since module start at location 72
* add support for br_table instruction in packed carts * add 6 and 7 parameter function types to base module
### Older versions ### Older versions

View File

@@ -21,7 +21,7 @@ loaded.
00000-00040: user memory 00000-00040: user memory
00040-00044: time since module start in ms 00040-00044: time since module start in ms
00044-0004c: gamepad state 00044-0004c: gamepad state
0004c-00050: reserved 0004c-00050: number of frames since module start
00050-00070: sound data (synced to sound thread) 00050-00070: sound data (synced to sound thread)
00070-00078: reserved 00070-00078: reserved
00078-12c78: frame buffer 00078-12c78: frame buffer
@@ -594,7 +594,7 @@ a base module provided by MicroW8.
You can generate this base module yourself using You can generate this base module yourself using
`uw8-tool`. As a quick summary, it provides all function `uw8-tool`. As a quick summary, it provides all function
types with up to 5 parameters (i32 or f32) where the types with up to 7 parameters (i32 or f32) where the
`f32` parameters always preceed the `i32` parameters. `f32` parameters always preceed the `i32` parameters.
Then it includes all imports that MicroW8 provides, Then it includes all imports that MicroW8 provides,
a function section with a single function of type a function section with a single function of type

View File

@@ -2,6 +2,20 @@
description = "Versions" description = "Versions"
+++ +++
### v0.4.0
* [Web runtime](../v0.4.0)
* [Linux](https://github.com/exoticorn/microw8/releases/download/v0.4.0/microw8-0.4.0-linux.tgz)
* [MacOS](https://github.com/exoticorn/microw8/releases/download/v0.4.0/microw8-0.4.0-macos.tgz)
* [Windows](https://github.com/exoticorn/microw8/releases/download/v0.4.0/microw8-0.4.0-windows.zip)
Changes:
* add support for sound on mono- and surround-only devices
* update wasmtime dependency to fix performance regression in 0.3.0
* add frame counter since module start at location 72
* add 6 and 7 parameter function types to base module
### v0.3.0 ### v0.3.0
* [Web runtime](../v0.3.0) * [Web runtime](../v0.3.0)

View File

@@ -4,7 +4,7 @@
<section> <section>
<h1 class="text-center heading-text">A WebAssembly based fantasy console</h1> <h1 class="text-center heading-text">A WebAssembly based fantasy console</h1>
</section> </section>
<a href="v0.3.0"> <a href="v0.4.0">
<img class="demonstration-gif" style="width:640px;height:480px;image-rendering:pixelated" src="img/technotunnel.png"></img> <img class="demonstration-gif" style="width:640px;height:480px;image-rendering:pixelated" src="img/technotunnel.png"></img>
</a> </a>
</div> </div>

File diff suppressed because one or more lines are too long

View File

@@ -2,7 +2,7 @@ use std::sync::{mpsc, Arc, Mutex};
use std::time::Duration; use std::time::Duration;
use std::{thread, time::Instant}; use std::{thread, time::Instant};
use anyhow::{anyhow, Result}; use anyhow::{anyhow, bail, Result};
use cpal::traits::*; use cpal::traits::*;
use rubato::Resampler; use rubato::Resampler;
use uw8_window::{Window, WindowConfig}; use uw8_window::{Window, WindowConfig};
@@ -27,6 +27,7 @@ struct UW8Instance {
end_frame: TypedFunc<(), ()>, end_frame: TypedFunc<(), ()>,
update: Option<TypedFunc<(), ()>>, update: Option<TypedFunc<(), ()>>,
start_time: Instant, start_time: Instant,
frame_counter: u32,
watchdog: Arc<Mutex<UW8WatchDog>>, watchdog: Arc<Mutex<UW8WatchDog>>,
sound_tx: Option<mpsc::SyncSender<RegisterUpdate>>, sound_tx: Option<mpsc::SyncSender<RegisterUpdate>>,
} }
@@ -159,6 +160,7 @@ impl super::Runtime for MicroW8 {
end_frame, end_frame,
update, update,
start_time: Instant::now(), start_time: Instant::now(),
frame_counter: 0,
watchdog, watchdog,
sound_tx, sound_tx,
}); });
@@ -191,8 +193,11 @@ impl super::Runtime for MicroW8 {
let mem = instance.memory.data_mut(&mut instance.store); let mem = instance.memory.data_mut(&mut instance.store);
mem[64..68].copy_from_slice(&time.to_le_bytes()); mem[64..68].copy_from_slice(&time.to_le_bytes());
mem[68..72].copy_from_slice(&input.gamepads); mem[68..72].copy_from_slice(&input.gamepads);
mem[72..76].copy_from_slice(&instance.frame_counter.to_le_bytes());
} }
instance.frame_counter = instance.frame_counter.wrapping_add(1);
instance.store.set_epoch_deadline(self.timeout as u64); instance.store.set_epoch_deadline(self.timeout as u64);
if let Some(ref update) = instance.update { if let Some(ref update) = instance.update {
if let Err(err) = update.call(&mut instance.store, ()) { if let Err(err) = update.call(&mut instance.store, ()) {
@@ -328,26 +333,37 @@ fn init_sound(
let mut configs: Vec<_> = device let mut configs: Vec<_> = device
.supported_output_configs()? .supported_output_configs()?
.filter(|config| { .filter(|config| {
config.channels() == 2 config.sample_format() == cpal::SampleFormat::F32
&& (config.sample_format() == cpal::SampleFormat::F32 || config.sample_format() == cpal::SampleFormat::I16
|| config.sample_format() == cpal::SampleFormat::I16)
}) })
.collect(); .collect();
if configs.is_empty() {
eprintln!(
"No suitable audio output config found on device \"{}\", available configs:",
device.name()?
);
for config in device.supported_output_configs()? {
eprintln!(" {}ch {}", config.channels(), config.sample_format());
}
bail!("Failed to configure audio out");
}
configs.sort_by_key(|config| { configs.sort_by_key(|config| {
let rate = 44100 let rate = 44100
.max(config.min_sample_rate().0) .max(config.min_sample_rate().0)
.min(config.max_sample_rate().0); .min(config.max_sample_rate().0);
let prio = if rate >= 44100 { let rate_prio = if rate >= 44100 {
rate - 44100 rate - 44100
} else { } else {
(44100 - rate) * 1000 (44100 - rate) * 1000
}; };
prio + (config.sample_format() == cpal::SampleFormat::I16) as u32 let format_prio = (config.sample_format() == cpal::SampleFormat::I16) as u32;
let channels_prio = (config.channels() != 2) as u32 * 16777216;
rate_prio + format_prio + channels_prio
}); });
let config = configs let config = configs.into_iter().next().unwrap();
.into_iter()
.next()
.ok_or_else(|| anyhow!("Could not find float or 16bit signed output config"))?;
let sample_rate = cpal::SampleRate(44100) let sample_rate = cpal::SampleRate(44100)
.max(config.min_sample_rate()) .max(config.min_sample_rate())
.min(config.max_sample_rate()); .min(config.max_sample_rate());
@@ -359,6 +375,7 @@ fn init_sound(
} }
}; };
let sample_format = config.sample_format(); let sample_format = config.sample_format();
let num_channels = config.channels();
let config = cpal::StreamConfig { let config = cpal::StreamConfig {
buffer_size, buffer_size,
..config.config() ..config.config()
@@ -392,7 +409,7 @@ fn init_sound(
let mut pending_updates: Vec<RegisterUpdate> = Vec::with_capacity(30); let mut pending_updates: Vec<RegisterUpdate> = Vec::with_capacity(30);
let mut current_time = 0; let mut current_time = 0;
let mut callback = move |mut outer_buffer: &mut [f32], _: &_| { let mut callback = move |mut outer_buffer: &mut [f32]| {
let mut first_update = true; let mut first_update = true;
while let Ok(update) = rx.try_recv() { while let Ok(update) = rx.try_recv() {
if first_update { if first_update {
@@ -484,36 +501,126 @@ fn init_sound(
current_time = current_time.wrapping_add((step_size * 500 / sample_rate).max(1) as i32); current_time = current_time.wrapping_add((step_size * 500 / sample_rate).max(1) as i32);
} }
}; };
let stream = if sample_format == cpal::SampleFormat::F32 {
device.build_output_stream(
&config,
callback,
move |err| {
dbg!(err);
},
None,
)?
} else {
device.build_output_stream(
&config,
move |mut buffer: &mut [i16], info| {
let mut float_buffer = [0f32; 256];
while !buffer.is_empty() { fn f32_to_i16<F>(mut buffer: &mut [i16], callback: &mut F)
let step_size = buffer.len().min(float_buffer.len()); where
let step_buffer = &mut float_buffer[..step_size]; F: FnMut(&mut [f32]),
callback(step_buffer, info); {
for (dest, src) in buffer.iter_mut().take(step_size).zip(step_buffer.iter()) { let mut float_buffer = [0f32; 256];
*dest = (src.max(-1.0).min(1.0) * 32767.0) as i16;
} while !buffer.is_empty() {
buffer = &mut buffer[step_size..]; let step_size = buffer.len().min(float_buffer.len());
} let step_buffer = &mut float_buffer[..step_size];
}, callback(step_buffer);
move |err| { for (dest, src) in buffer.iter_mut().take(step_size).zip(step_buffer.iter()) {
dbg!(err); *dest = (src.max(-1.0).min(1.0) * 32767.0) as i16;
}, }
None, buffer = &mut buffer[step_size..];
)? }
}
fn stereo_to_mono<F>(mut buffer: &mut [f32], callback: &mut F)
where
F: FnMut(&mut [f32]),
{
let mut in_buffer = [0f32; 256];
while !buffer.is_empty() {
let step_size = buffer.len().min(in_buffer.len() / 2);
let step_buffer = &mut in_buffer[..step_size * 2];
callback(step_buffer);
for (index, dest) in buffer.iter_mut().take(step_size).enumerate() {
*dest = (step_buffer[index * 2] + step_buffer[index * 2 + 1]) * 0.5;
}
buffer = &mut buffer[step_size..];
}
}
fn stereo_to_surround<F>(mut buffer: &mut [f32], num_channels: usize, callback: &mut F)
where
F: FnMut(&mut [f32]),
{
let mut in_buffer = [0f32; 256];
buffer.fill(0.);
while !buffer.is_empty() {
let step_size = (buffer.len() / num_channels).min(in_buffer.len() / 2);
let step_buffer = &mut in_buffer[..step_size * 2];
callback(step_buffer);
for index in 0..step_size {
buffer[index * num_channels + 0] = step_buffer[index * 2 + 0];
buffer[index * num_channels + 1] = step_buffer[index * 2 + 1];
}
buffer = &mut buffer[step_size * num_channels..];
}
}
let stream = if sample_format == cpal::SampleFormat::F32 {
if num_channels == 2 {
device.build_output_stream(
&config,
move |buffer: &mut [f32], _| callback(buffer),
move |err| {
dbg!(err);
},
None,
)?
} else if num_channels == 1 {
device.build_output_stream(
&config,
move |buffer: &mut [f32], _| stereo_to_mono(buffer, &mut callback),
move |err| {
dbg!(err);
},
None,
)?
} else {
device.build_output_stream(
&config,
move |buffer: &mut [f32], _| {
stereo_to_surround(buffer, num_channels as usize, &mut callback)
},
move |err| {
dbg!(err);
},
None,
)?
}
} else {
if num_channels == 2 {
device.build_output_stream(
&config,
move |buffer: &mut [i16], _| f32_to_i16(buffer, &mut callback),
move |err| {
dbg!(err);
},
None,
)?
} else if num_channels == 1 {
device.build_output_stream(
&config,
move |buffer: &mut [i16], _| {
f32_to_i16(buffer, &mut |b| stereo_to_mono(b, &mut callback))
},
move |err| {
dbg!(err);
},
None,
)?
} else {
device.build_output_stream(
&config,
move |buffer: &mut [i16], _| {
f32_to_i16(buffer, &mut |b| {
stereo_to_surround(b, num_channels as usize, &mut callback)
})
},
move |err| {
dbg!(err);
},
None,
)?
}
}; };
Ok(Uw8Sound { stream, tx }) Ok(Uw8Sound { stream, tx })

View File

@@ -37,7 +37,7 @@ impl BaseModule {
let mut types = vec![]; let mut types = vec![];
let mut type_map = HashMap::new(); let mut type_map = HashMap::new();
for num_params in 0..6 { for num_params in 0..8 {
for num_f32 in 0..=num_params { for num_f32 in 0..=num_params {
for &result in &[None, Some(ValType::I32), Some(ValType::F32)] { for &result in &[None, Some(ValType::I32), Some(ValType::F32)] {
let mut params = vec![]; let mut params = vec![];

View File

@@ -10,7 +10,7 @@
</head> </head>
<body> <body>
<div id="uw8"> <div id="uw8">
<a href="https://exoticorn.github.io/microw8">MicroW8</a> 0.3.0 <a href="https://exoticorn.github.io/microw8">MicroW8</a> 0.3.1
</div> </div>
<div id="centered"> <div id="centered">
<canvas class="screen" id="screen" width="320" height="240"> <canvas class="screen" id="screen" width="320" height="240">

View File

@@ -240,6 +240,7 @@ export default function MicroW8(screen, config = {}) {
await audioReadyPromise; await audioReadyPromise;
let startTime = Date.now(); let startTime = Date.now();
let frameCounter = 0;
const timePerFrame = 1000 / 60; const timePerFrame = 1000 / 60;
@@ -306,6 +307,7 @@ export default function MicroW8(screen, config = {}) {
let time = Date.now() - startTime; let time = Date.now() - startTime;
u32Mem[16] = time; u32Mem[16] = time;
u32Mem[17] = pad | gamepad; u32Mem[17] = pad | gamepad;
u32Mem[18] = frameCounter++;
if(instance.exports.upd) { if(instance.exports.upd) {
instance.exports.upd(); instance.exports.upd();
} }