8000 GitHub - W-Mai/mirui: A lightweight, no_std ECS-driven UI framework for embedded, desktop, and WebAssembly · GitHub
[go: up one dir, main page]

Skip to content
W-MaiPublic

About

A lightweight, no_std ECS-driven UI framework for embedded, desktop, and WebAssembly

Topics

Resources

Stars

77 stars

Watchers

0 watching

Forks

Repository files navigation

mirui — the Iris lens demo running at 128×160, 240×240, 390×844 and 1280×800

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

Crates.io docs.rs License: MIT no_std + alloc MSRV 1.85

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, and 1280×800.


Quick Start

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::prelude exports App, 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 via app.compose(root, build_root()). Inside a ui! tree, invoke another compose function directly (status_row(model, "ready")), or via ui!(status_row(model, "ready")) inside a composition body.
  • Enable sync when sharing textures, pixel guards, byte sources, or immutable cache handles across threads. See docs/shared-textures.md.

Architecture & Targets

mirui architecture: a retained ui! component tree flows through ECS SystemSlot scheduling, Q24.8 fixed-point Flexbox layout, dirty-region diffing, and unified DrawCommand emission to MCU, NuttX, Linux, Desktop, Mobile, and WebAssembly targets

  • no_std + alloc core — 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-World application API — declarative ui! DSL (powered by xrune), typed #[model] / #[view] hooks, and ordered ECS SystemSlot scheduling.

Backends

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.

Hybrid Routing (compose_backend!)

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.


Live Gallery & Examples

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

ESP32-C3 Hardware Demos

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


Built with mirui

HachimoDock — ESP32-P4 AI Agent desktop companion (480×640 · keys & joystick). Cardputer Zero Pixel Flight — Tilt-controlled Pixel Flight on M5Stack Cardputer Zero (320×170). mirui-kit — Desktop-class #![no_std] UI kit, file manager & Studio prototype. ATK-DNESP32S3 — no_std Rust firmware on ALIENTEK ESP32-S3 (8 MB PSRAM). Howff — R36S handheld game launcher & Wi-Fi Direct nearby netplay UI.


Authoring: DSL, Models & ECS

mirui two-channel reactivity: registered #[model] and owned child state drive $ bindings and #[view] watch selectors, while @ layout queries evaluate responsive geometry, converging into bounded dirty-rect redraws

ui! DSL & Layout Queries (@)

#[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 / height from the nearest container: true ancestor, or id(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 to Fixed / Dimension via Into.
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

Models, Views & Owned Children

#[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 on Err.
  • Deep dives: State management · Model collections · Events & callbacks · Composition.

ECS Systems & Queries

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).


UI Essentials & Plugins

Theme, Images & ScrollView

// 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)
        }
    }
};

Animation & Timers

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.

Built-in Plugins

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 Assets & Sprite Stack

MIRX checked media pipeline: gen-mirx encodes images, fonts, and tile frames into checked MIRX containers planned under DecodeRequest for zero-copy flash borrowing and caller-owned workspace playback

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 32x32
Explicit 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-coherent
use 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, and MirxFontProvider::from_mirx_with_storage bind caller-owned static buffers once and return borrowed rasters without hidden per-frame or per-glyph allocations.
  • 2.5D Sprite Stack: extensions/sprite-stack renders layered MIRX and procedural SolidStack models in Pixel Flight, Flux Run, and Continuum.
  • Contact-sheet tool: cargo run -p gallery --example mirx_frames_snapshot -- /tmp/mirx-frames.ppm.

Performance & Diagnostics

ESP32-C3 160 MHz no-FPU benchmark chart showing ~13 ms (~77 FPS) for Three-body widgets with dirty rects and ~52 ms (~19 FPS) for Cover-flow 3D quads alongside opt-in Perfetto span tracing

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, or app.request_timings(true) — zero clock cost otherwise.
  • Perfetto span export: annotate with mirui::trace_span!("name") or #[mirui::trace_fn("name")], collect via PerfReportPlugin or mirui::core::perf::Capture, and export Chrome trace JSON (PerfReportPlugin::with_perfetto_writer on std, or tools/esp-trace.py on ESP32). See docs/timing-diagnostics.md.

Feature Flags

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

Documentation

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

Development Checks

cargo xtask ci --list   # list selectable checks
cargo xtask ci          # run the full verification suite

See docs/ci.md for test groups, prerequisites, and parallel workflow execution.

License

MIT

About

A lightweight, no_std ECS-driven UI framework for embedded, desktop, and WebAssembly

Topics

Resources

Stars

77 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0