Skip to main content

Crate bevy_terminal

Crate bevy_terminal 

Source
Expand description

§bevy_terminal

A low-level terminal cell renderer built on Bevy text and the render world. It has no Ratatui dependency and owns no windows, UI layout, cameras, meshes, or materials.

Terminal cells + configuration → image + validated geometry + status.

§Surface model

TerminalSurface is a cloneable shared handle. update applies a transaction and publishes a revision only when content changes. Dirty tracking supports partial row updates. TerminalSnapshot provides read-only cells, rows, cursor state, and text extraction.

Cells carry symbols, colors, style flags, and explicit wide-cell occupancy. Unicode shaping and fallback remain aligned to the terminal grid. The surface also supports clearing and scrolling; it does not parse escape sequences or manage a PTY.

use bevy_terminal::prelude::*;

let surface = TerminalSurface::new((80, 24));
surface.update(|update| {
    update.set_cell((0, 0), &TerminalCell::new("A")
        .with_style(TerminalStyle::new().fg(TerminalColor::CYAN)));
    update.set_cursor_position((1, 0));
    update.set_cursor_visible(true);
});
assert_eq!(surface.snapshot().row_text(0).trim_end(), "A");

§Rendering and output

Add TerminalPlugin after Bevy’s asset, text, and render plugins, then spawn a TerminalRenderer for each surface. A default TerminalRenderConfig is required and inserted automatically. Supply your own sizing, fonts, theme, cursor, blink, and raster settings when needed.

use bevy::prelude::*;
use bevy_terminal::prelude::*;

fn setup(mut commands: Commands) {
    let surface = TerminalSurface::new((80, 24));
    commands.spawn((
        TerminalRenderer::new(surface),
        TerminalRenderConfig {
            sizing: TerminalSizing::font(18.0),
            raster: RasterConfig { scale: 2.0, ..default() },
            ..default()
        },
    ));
}

The plugin attaches TerminalTexture and TerminalStats as soon as a TerminalRenderer is added. Read output after TerminalSystems::Sync. texture.measured() returns the geometry once the selected fonts and cell metrics are usable; it is recorded by the sync, so Changed<TerminalTexture> fires only when geometry or status change. It describes the surface as of the last Sync: a surface resized after Sync reads as its previous geometry until the next one. Status exposes loading, invalid sizing, font/shaping failures, missing text resources, and device texture limits.

TerminalGeometry provides:

  • grid(): measured columns and rows.
  • size(): physical image dimensions.
  • logical_size(), cell_size(), font_size(): logical pixel measurements; physical_cell_size() and physical_font_size(): the exact physical cell and rasterization size.
  • raster_scale(): physical-to-logical pixel ratio.
  • grid_for(available_size): a bounded grid fitting a logical rectangle.
  • is_current() and matches_surface(...): source/generation validation.

Readiness is persistent, so late consumers need no event history. Retain the last useful application layout while new geometry is unavailable. is_current() and matches_surface(...) check retained geometry against the live surface, rejecting old grid measurements immediately after a shared resize.

The image handle is stable throughout the renderer’s lifetime, including resizes. Output uses Rgba8UnormSrgb, straight alpha, and nearest sampling. Applications bind it to their own UI, sprites, materials, or export targets. Rendering has bounded caches and reuses assets and GPU resources for idle and partial-update workloads.

Measured geometry does not prove GPU completion. Image exports must observe render-world readback and verify the intended content. The static scene export example uses known content to distinguish initial zeroed images from rendered output; that check does not apply to arbitrary animated scenes.

§Application-owned presentation

The renderer does not modify Node, ImageNode, Transform, or material assets. An application presentation system can query TerminalTexture, bind its image, and size its own UI or mesh from measured logical dimensions.

RasterConfig.scale is always explicit and defaults to 1.0. The application chooses its window/camera/UI policy and updates configuration before sync. Non-finite/non-positive values fall back to 1.0; positive values clamp to 1..=8. Physical cells snap to pixels; logical geometry may remain fractional. There is no presentation-dependent or primary-window-dependent scale behavior.

§Sizing and fonts

TerminalSizing supports font-driven cells (FromFont), fitting font advance to a requested cell width (FitCellWidth), and explicit cells/font size (Fixed). Natural and width-fitted rows enclose the configured faces’ typographic metrics in whole pixels. Text and box-drawing alignment are measured separately; faint text-edge pixels are preserved whenever the run fits its cell span. Styled and fallback runs share the configured text baseline. Fallback glyphs do not change cell measurements when the displayed content changes. Font-driven sizing accepts a line-height multiplier; values below one tighten rows, and taller ink overflows into the neighbouring rows. Fixed geometry keeps the specified cells.

Glyph placement follows Ghostty (ported from renderer/generic.zig, font/SharedGrid.zig and font/Glyph.zig; Ghostty is MIT licensed):

  • Ordinary text is drawn as rasterized, with its bearings, on the primary face’s baseline. It is centered in cells wider than the face’s advance. Overhangs and wider runs (a fallback face with a larger advance, Iosevka’s two-cell ∑) overflow into neighbouring cells, later cells drawn on top. Only at the texture’s outer edges, where Ghostty has window padding, is ink pushed back inside.
  • Symbols (arrows, dingbats, miscellaneous symbols, enclosed alphanumerics, pictographs, emoticons, transport, private use) are scaled down uniformly, only as far as needed to fit the primary face’s box over the cells they may use. A symbol before a blank cell may spread into it unless it follows another symbol.
  • Colour (emoji-presentation) glyphs, whatever their codepoint, are scaled up or down to cover that box with 2.5% side padding, centered.
  • Nerd Fonts icons use Ghostty’s per-codepoint table (generated from Ghostty’s nerd_font_attributes.zig): fit, cover or stretch at icon height, centered in the first cell, with padding and scale groups.

Rescaled glyphs are rasterized again at whole-pixel font sizes; stretched glyphs are resampled to their box.

Text is blended like Ghostty’s default alpha-blending = linear-corrected (outside macOS): in linear light, with each glyph’s coverage corrected against the luminance of the cell background under it, so text keeps the weight of a gamma-space blend without its dark fringes. Colour glyphs blend unchanged.

Ink is not confined to its row: accents, stacked marks and tall scripts overflow into the neighbouring rows, and only the texture’s edges clip them. Partial repaints also redraw the rows that changed ink reaches.

Grid graphics are drawn procedurally at the exact cell size, ported from Ghostty’s sprite font, so they tile without seams whatever the font’s outlines look like (or whether it has them at all): box drawing (U+2500–257F), block elements and shades (U+2580–259F), Braille (U+2800–28FF), ◢◣◤◥◸◹◺◿, the geometric Powerline glyphs (U+E0B0–E0BF, E0D2, E0D4), branch drawing (U+F5D0–F60D) and Symbols for Legacy Computing (U+1FB00–1FBEF and its supplement). Their lines use the font’s underline thickness, as in Ghostty. A wide cell holding one is drawn as a single cell spanning its columns. Unlike Ghostty’s translucent fills, shades (░▒▓ and the legacy medium shades) are dithered: opaque dots in the classic VGA patterns, scaled to the cell so they tile seamlessly.

The crate is MIT licensed; the test fonts under assets/fonts are bundled under their own licenses (OFL 1.1) and are used only by tests.

FontFaces selects regular, bold, italic, and bold-italic sources. Missing faces can request weight/style from fallback faces. Supply Bevy Font assets, generic font sources, or a named FontSource::Family. Bevy performs font registration and fallback. Applications implementing family selection should query FontCx.collection directly after registration.

TerminalTheme, CursorConfig, and BlinkConfig control terminal rendering semantics. These do not prescribe application presentation or input behavior.

§Features

  • system_fonts (default): discover host fonts. Disable defaults and supply explicit assets for deterministic font selection.
  • timings (opt-in): record CPU snapshot/scene durations. Work counters remain available without this feature; timing fields are then zero.

There are no UI or 3D presentation features. Applications enable the Bevy features their own presentation requires. This checkout targets Bevy 0.19 and Rust 1.95 or newer.

§Examples and verification

cargo run -p bevy_terminal --example scene_export
cargo test -p bevy_terminal
cargo test -p bevy_terminal --test gpu_readback -- --ignored --test-threads=1

scene_export reads two scenes written through the neutral cell API back into images without a window. The repository’s adapter examples demonstrate UI layout and DPI policy (demo) and application-owned 3D material binding (world_quad).

§License

MIT.

Re-exports§

pub use bevy;

Modules§

prelude
Everything an application needs, for glob import.
render
Rendering: the TerminalPlugin, the TerminalRenderer component and its configuration, the renderer-owned TerminalTexture, per-terminal TerminalStats, and the TerminalTheme. Add the plugin once and spawn a TerminalRenderer per rendered surface; applications present its image.
scene
The renderer-neutral scene model: grid coordinates, cells, symbols, styles, colors, wide-glyph occupancy and owned snapshots. Producers translate their own representation into these types once, when submitting cells to a crate::surface::TerminalSurface.
surface
The thread-safe retained surface producers write into and renderers read from. Every write goes through TerminalSurface::update, which takes the lock once and publishes at most one new revision per call.