A no_std, ECS-driven UI framework for embedded, mobile, desktop, Linux, and WebAssembly
Q24.8 fixed-point layout · dirty-region redraw · software, GPU & Web backends
Live Gallery · Manual · Quick Start · Architecture · Examples · Features · Docs
The hero artwork above is the Iris demo — one component tree rendered by mirui at
128×160,240×240,390×844, and1280×800.
Add mirui to Cargo.toml:
[dependencies]
mirui = { version = "0.59", features = ["sdl"] }use mirui::prelude::*;
use mirui::surface::sdl::SdlSurface;
use mirui::ui::widgets::{ParagraphStyle, Text};
fn main() {
let backend = SdlSurface::new("hello mirui", 480, 320);
let mut app = App::new(backend);
app.with_default_widgets().with_default_systems();
// Root fills the viewport with Surface background and Stack + Stretch layout by default.
let root = app.spawn_root().id();
app.compose(root, build_root());
app.run();
}
#[compose]
fn build_root() {
ui! {
Column (grow: 1.0) {
View (
bg_color: ColorToken::Primary,
text_color: ColorToken::OnPrimary,
height: 40,
border_radius: 8,
padding: Padding::all(10)
) {
Text ("Hello mirui!")
}
View (bg_color: ColorToken::SurfaceVariant, grow: 1.0)
Text ("ECS + DSL", height: 30, paragraph: ParagraphStyle::label())
}
};
}mirui::preludeexportsApp, layout types,Color/Dimension/Fixed, ECS roles, theme tokens, and authoring macros. Surface backends, plugins, and widget kinds remain on their canonical module paths.#[compose]builds a stack-held composition executed viaapp.compose(root, build_root()). Inside aui!tree, invoke another compose function directly (status_row(model, "ready")), or viaui!(status_row(model, "ready"))inside a composition body.- Enable
syncwhen sharing textures, pixel guards, byte sources, or immutable cache handles across threads. Seedocs/shared-textures.md.
no_std+alloccore — runs on bare-metal MCUs (ESP32-C3, STM32) with no FPU required.- Q24.8 fixed-point pipeline — Flexbox, absolute positioning, hit testing, HiDPI scaling, and dirty-region partial refresh share integer geometry.
- Subpixel rendering & shaped typography — scanline coverage anti-aliasing on arbitrary
Paths, SDF / 2×2 supersample fast paths for transformed quads, plus bounded Unicode/bidi/curved-path layout via TextFlow. - Zero-
Worldapplication API — declarativeui!DSL (powered by xrune), typed#[model]/#[view]hooks, and ordered ECSSystemSlotscheduling.
| Target | Host / OS | Backend / Feature |
|---|---|---|
| Bare-metal MCU | RISC-V (ESP32-C3), ARM Cortex-M | FramebufSurface (default-features = false) |
| RTOS | NuttX (e.g. 1.28″ round 240×240) | nuttx |
| Embedded Linux | Headless fbdev / KMS-DRM | linux-fb / linux-drm |
| Desktop | macOS, Linux, Windows | sdl, sdl-gpu, wgpu |
| Mobile | Android, iOS | wgpu, wgpu-android, or software rasterizer |
| Browser | WebAssembly | web-canvas (+ web-audio) |
See docs/quickstart.md for mobile, ESP32-C3, and multi-target workspace setup, and docs/backend-targets.md for backend details.
Route selected command classes through hardware accelerators while sharing one output target:
use mirui_macros::compose_backend;
compose_backend! {
pub struct Hybrid {
sw: SwRenderer,
blitter: DmaBlitEngine,
}
route {
default => sw,
blit => blitter,
}
}
let renderer = Hybrid::new(sw_renderer, dma_blitter);The default field owns the target; routed fields implement RenderEngine<Target> with begin/end barriers around submission. See docs/backend-fallback.md and gallery/examples/backends/compose_backend_dsl.rs.
Try interactive browser demos with live Rust source at mirui.rs, or launch native builds from the workspace:
| Demo | Focus | Native Command |
|---|---|---|
| Iris | Adaptive single-tree UI across 4 screen sizes | cargo run -p gallery --example iris_demo --release --features wgpu |
| Orbit Console | Multi-panel telemetry dashboard | cargo run -p gallery --example orbit_console_demo --release --features wgpu |
| Glass Light Toggle | Interactive glass shader, drag & keyboard controls | cargo run -p gallery --example glass_light_toggle_demo --release --no-default-features --features sdl-gpu |
| Pixel Flight | Layered MIRX sprite-stack flight game | cargo run -p gallery --example pixel_flight_demo --release --no-default-features --features wgpu,pixel-flight |
| Flux Run | Fixed-point magnetic-tether harbor salvage game | cargo run -p gallery --example flux_run_demo --release --no-default-features --features wgpu,flux-run |
| Continuum | Zero-float procedural 12-world highway & 8 depth styles | cargo run -p gallery --example continuum_demo --release --no-default-features --features wgpu,continuum |
mirui-examples hosts ready-to-flash ESP32-C3 demos (cargo run --release --features demo-XXX --no-default-features):
demo-threebody (default) · demo-particles · demo-subpixel · demo-shapes · demo-butterfly · demo-coverflow · demo-flipcard · demo-gesture · demo-widgets · demo-hidpi-downscale · demo-hidpi-upscale
#[compose]
fn dashboard(items: &[Item], show_footer: bool) {
ui! {
Column (container: true, grow: 1.0) {
Text (
"Adaptive title",
font_size: @width {
if width < Fixed::from_int(520) { 18_u16 } else { 30_u16 }
},
padding: @(width, height) {
Padding::all(width.min(height) / 24)
}
)
// Enchants attach extra ECS components to the spawned entity
View (width: 16, height: 16) [
PhysicsBody { position: Fixed::ZERO },
Velocity(Fixed::ONE),
]
walk items.iter() with item {
Text (item.name, bg_color: item.color)
}
if show_footer {
Text ("visible")
}
}
};
}$binds signal-driven state;@binds layout-responsive geometry (width/heightfrom the nearestcontainer: trueancestor, orid(name).width/@id(stage).width as stage_width { ... }). Up to 4 dependencies are stored inline and verified at compile time.- Integer literals in attributes (
height: 40) coerce toFixed/DimensionviaInto.
Common widget attributes
| Attribute | Type | Notes |
|---|---|---|
bg_color / text_color / border_color |
Color or ColorToken |
Solid color or theme token |
text |
&str |
Text-bearing widgets |
border_radius / border_width |
Fixed |
Subpixel-accurate |
width / height |
Dimension |
Px, Percent, Auto, Content |
grow / shrink |
f32 |
Flex factors |
direction / justify / align |
FlexDirection / JustifyContent / AlignItems |
Flex axis layout |
padding / gap |
Padding / Fixed |
Inner spacing |
position / left / top |
Position / Dimension |
Flex or Absolute |
src |
ImageSource |
Texture token, Path, or IconAsset |
#[model] registers reactive application state; #[observe] marks small fields watched by $ expressions; model!(T) passes a registered instance without exposing handle internals:
use mirui::prelude::*;
use mirui::ui::widgets::{Button, Text};
#[model]
struct Counter {
#[observe]
value: i32,
}
#[model]
impl Counter {
fn increment(&mut self) { self.value += 1; }
}
#[compose]
fn counter_panel(counter: model!(Counter)) {
ui! {
Row {
Button (text: "+") on Tap { counter.increment(); }
Text (text: ${ format!("count: {}", counter.value()) })
}
};
}
fn install_counter<B: Surface, F: RendererFactory<B>>(app: &mut App<B, F>, root: Entity) {
let counter = app.add_model(Counter { value: 0 }).finish();
app.compose(root, counter_panel(counter));
}- Attach models to entities with
#[component]and consume them in typed#[view(component = T)]paint/attach/input/system hooks (watch(...),view().with_systems([...])). - Nest child state with
child: model!(owned Child): one registration, single-tree atomic notifications, and preserved field identity across data replacement. - Mutable model methods returning
Result<T, E>discard pending notifications and effects onErr. - Deep dives: State management · Model collections · Events & callbacks · Composition.
use mirui::prelude::*;
#[component]
struct PhysicsBody { position: Fixed }
#[component]
struct Velocity(Fixed);
struct MotionStep(Fixed);
#[system(order = Animation)]
fn physics_system(step: res!(MotionStep), bodies: query!(mut PhysicsBody, optional Velocity)) {
for (body, velocity) in bodies {
if let Some(velocity) = velocity {
body.position += velocity.0 * step.0;
}
}
}System parameters declare roles via model!, res!, query!, and commands!. query! supports iteration and generation-checked point lookups (rows.get(entity)). SystemSlot defines standard execution order (SimInput, DeltaTime, InteractionState, Animation, Timer, ScrollInertia, LazyList, TabPages, Normal, PreRender).
// Editable palette with automatic WidgetState (Hovered / Pressed / Error / Disabled) overlays
let theme = Theme::dark()
.with_info(ThemeInfo::new("ocean", "Ocean", "Low-glare cyan palette"))
.with(ColorToken::Primary, Color::rgb(72, 214, 200));
app.register_theme(theme);
app.set_theme("ocean").unwrap();// Images & vector icons scale on the fly without per-frame command allocation;
// Scroll derives bounds from retained layout with inertia, bounce & nested chaining.
ui! {
Scroll (grow: 1.0) {
Image ("avatar")
Image (src: ICON_HOME, color: ColorToken::Primary, viewbox: 24)
walk items.iter() with item {
Text (item.label, height: 60, bg_color: item.color)
}
}
};use mirui::anim::{Spring, SpringConfig};
let mut spring = Spring::new(SpringConfig::new(220, 0.3), Fixed::ZERO);
spring.target(Fixed::from_int(100));
#[animate(component = AnimateOpacity)]
fn apply_opacity(value: motion!(), opacity: component!(mut Opacity)) {
opacity.0 = value;
}
#[timer(every = 1_000)]
fn advance(counter: model!(Counter)) {
counter.increment();
}Register with app.add_system(AnimateOpacity::system()) and app.add_timer(advance::timer(counter)). Multi-touch pinch/rotate gestures and scripted SimAction tests are built in; see docs/scrolling.md and docs/typography.md.
| Plugin | Inserts |
|---|---|
StdInstantClockPlugin |
MonoClock resource (std) |
PerfReportPlugin |
SystemPerfSnapshot, PerfResetFlag, on_timing hook |
FpsSummaryPlugin |
on_timing hook (operation wall time, phase time, callback cadence) |
InputFeedbackPlugin |
InputFeedback resources, cursor + rotary systems/views, on_event & pre_render hooks |
AudioPlugin (audio) |
AudioHandle, AudioStateSignal, lifecycle & frame hooks |
Custom plugins implement mirui::app::plugin::Plugin.
mirx is the checked binary asset format for IMAGE, FONT, and FRAMES timelines, supporting RAW (zero-copy borrowed), native pixel, RLE, LZ4, reversible frequency, and quantized frequency coding with explicit DecodeRequest memory, alignment, and cache contracts:
cargo xtask gen-mirx image --in logo.png --out logo.mirx --format rgba8888 --coding frequency-quantized --quality 75
cargo xtask gen-mirx frames --in frame-000.png --in frame-001.png --out animation.mirx --format rgba8888 --tile 32x32Explicit flash, DMA alignment & cache-boundary CLI options
cargo xtask gen-mirx image --in logo.png --out logo.mirx --format rgba8888 \
--coding frequency-quantized --quality 75 --input-memory flash \
--output-align 64 --stride-multiple 64 --output-memory shared-noncoherent \
--workspace-align 64 --workspace-memory shared-coherent
cargo xtask gen-mirx frames --in frame-000.png --in frame-001.png --out animation.mirx \
--format rgba8888 --tile 32x32 --input-align 64 --input-memory flash \
--output-align 64 --stride-multiple 64 --output-memory shared-noncoherent \
--workspace-align 64 --workspace-memory shared-coherentuse mirui::render::texture::{MirxTextureOptions, Texture};
use mirx::types::ByteAlignment;
let options = MirxTextureOptions::new()
.with_base_alignment(ByteAlignment::new(64).unwrap())
.with_plane_alignment(ByteAlignment::new(64).unwrap())
.with_stride_multiple(64);
let texture = Texture::from_mirx_with(include_bytes!("logo.mirx"), options)?;- Zero-allocation playback & fonts:
Texture::plan_mirx,MirxFramesPlan::open/MirxFramesSession::present, andMirxFontProvider::from_mirx_with_storagebind caller-owned static buffers once and return borrowed rasters without hidden per-frame or per-glyph allocations. - 2.5D Sprite Stack:
extensions/sprite-stackrenders layered MIRX and proceduralSolidStackmodels inPixel Flight,Flux Run, andContinuum. - Contact-sheet tool:
cargo run -p gallery --example mirx_frames_snapshot -- /tmp/mirx-frames.ppm.
ESP32-C3 (RV32IMC 160 MHz, no FPU) + ST7735S 128×128 SPI:
| Demo | Frame Avg | FPS | Notes |
|---|---|---|---|
| Three-body (widgets + dirty rect) | ~13 ms | ~77 | quad-aa off; partial refresh |
| Cover-flow (3D quad transforms) | ~52 ms | ~19 | default-features = false |
- Demand-driven timing: collection runs only when requested by
FpsSummaryPlugin,BudgetReportPlugin, an active trace capture, orapp.request_timings(true)— zero clock cost otherwise. - Perfetto span export: annotate with
mirui::trace_span!("name")or#[mirui::trace_fn("name")], collect viaPerfReportPluginormirui::core::perf::Capture, and export Chrome trace JSON (PerfReportPlugin::with_perfetto_writeronstd, ortools/esp-trace.pyon ESP32). Seedocs/timing-diagnostics.md.
Default features are ["quad-aa", "log-stderr"]. Bare-metal MCU targets should set default-features = false.
| Feature | Adds |
|---|---|
quad-aa (default) |
Anti-aliased 3D-transformed quads (Fixed64 SDF on std; 2×2 supersample on no_std) |
std |
Standard library clock and host integrations |
sdl / sdl-gpu |
Desktop SDL2 CPU framebuffer / SDL2 GPU + Lyon path tessellation |
wgpu / wgpu-android |
Cross-platform GPU renderer (wgpu + winit) |
web-canvas |
WebAssembly HTML Canvas backend |
linux-fb / linux-drm |
Headless Linux framebuffer / KMS-DRM with evdev input |
nuttx |
NuttX RTOS framebuffer and syslog backend |
audio / sdl-audio / web-audio |
Integer PCM mixer, static scores, and SDL/Web Audio sinks |
persistence |
serde + postcard state persistence |
sync |
Thread-safe textures, pixel guards, byte sources, and cache handles |
perf |
Fine-grained performance trace counters |
log-max-level-* / log-bridge / tracing-bridge |
Compile-time log DCE caps and log/tracing bridges |
| Area | Guides |
|---|---|
| Getting Started | Quick Start · Built-in Widgets · Composition · Surface Sizing |
| State & Events | State Management · Model Collections · Events · Widget Events · Resources · Persistence |
| UI, Effects & Text | Effects, Blur & 3D · Vector Drawing & Icons · Theming & I18n · Typography & Text Paths · Text Editing · Scrolling · Navigation · Clipboard |
| Media & Extensions | MIRX Media Assets · Dynamic Modules (mirvm & mircc) · 2.5D Sprite Stack · Audio & PCM Mixing · Shared Textures |
| Backends & Tooling | Backend Targets · Backend Fallback · Porting · Timing Diagnostics · Headless Testing · Logging & Features |
| Contributing | CI & Verification Guide |
cargo xtask ci --list # list selectable checks
cargo xtask ci # run the full verification suiteSee docs/ci.md for test groups, prerequisites, and parallel workflow execution.
MIT