use glam::Vec2;
use crate::draw_list::DrawList;
use crate::style::{Declaration, Sides};
use crate::text::FontAtlas;
use crate::tree::{AvailableSpace, Length, LengthAuto, Ui};
#[cfg(any(doc, test))]
use crate::widget::NATURAL_FONT_SIZE;
use crate::widget::PointerInput;
pub const NATURAL_SCALE: f32 = 1.0;
#[derive(Clone, Debug, PartialEq)]
pub struct ReadoutRow {
pub label: String,
pub value: String,
pub colour: [f32; 4],
}
impl ReadoutRow {
#[must_use]
pub fn new(label: impl Into<String>, value: impl Into<String>, colour: [f32; 4]) -> Self {
Self {
label: label.into(),
value: value.into(),
colour,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ReadoutPanel {
pub inset: f32,
pub width: f32,
pub row_height: f32,
pub pad: f32,
pub border_width: f32,
pub background: [f32; 4],
pub border: [f32; 4],
pub label: [f32; 4],
}
impl ReadoutPanel {
#[must_use]
pub fn height(&self, rows: usize) -> f32 {
2.0f32.mul_add(self.pad, rows as f32 * self.row_height)
}
pub fn draw(&self, list: &mut DrawList, atlas: &FontAtlas, rows: &[ReadoutRow]) {
self.draw_at(list, atlas, Vec2::new(self.inset, self.inset), rows);
}
pub fn draw_at(
&self,
list: &mut DrawList,
atlas: &FontAtlas,
origin: Vec2,
rows: &[ReadoutRow],
) {
self.draw_in(Ui::new(), list, atlas, origin, rows);
}
fn draw_in(
&self,
mut ui: Ui,
list: &mut DrawList,
atlas: &FontAtlas,
origin: Vec2,
rows: &[ReadoutRow],
) {
let panel = [
Declaration::Width(LengthAuto::Px(self.width)),
Declaration::BorderWidth(Sides::All, self.border_width),
Declaration::Padding(
Sides::All,
Length::Px((self.pad - self.border_width).max(0.0)),
),
Declaration::Background(self.background),
Declaration::BorderColor(self.border),
];
let row = [Declaration::Height(LengthAuto::Px(self.row_height))];
let label = [Declaration::Color(self.label)];
ui.begin_frame(PointerInput::default());
ui.block("readout", &panel, |ui| {
for (index, reading) in rows.iter().enumerate() {
ui.block_keyed(index, ".readout-row", &row, |ui| {
ui.span(".readout-label", reading.label.as_str(), &label);
ui.span(
".readout-reading",
reading.value.as_str(),
&[Declaration::Color(reading.colour)],
);
});
}
});
ui.layout(origin, AvailableSpace::MAX_CONTENT, atlas);
ui.emit(list);
}
pub fn hint(&self, list: &mut DrawList, atlas: &FontAtlas, extent: (u32, u32), text: &str) {
let size = Vec2::new(extent.0 as f32, extent.1 as f32);
let surface = [
Declaration::Width(LengthAuto::Px(size.x)),
Declaration::Height(LengthAuto::Px(size.y)),
];
let hint = [
Declaration::Height(LengthAuto::Px(self.row_height)),
Declaration::Margin(Sides::Bottom, LengthAuto::Px(self.inset)),
Declaration::Color(self.label),
];
let mut ui = Ui::new();
ui.begin_frame(PointerInput::default());
ui.block("readout-surface", &surface, |ui| {
ui.span(".readout-hint", text, &hint);
});
ui.layout(Vec2::ZERO, AvailableSpace::definite(size), atlas);
ui.emit(list);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::draw_list::DrawCommand;
const PANEL: ReadoutPanel = ReadoutPanel {
inset: 16.0,
width: 180.0,
row_height: 18.0,
pad: 8.0,
border_width: 1.0,
background: [0.06, 0.07, 0.11, 0.80],
border: [0.34, 0.38, 0.48, 1.0],
label: [0.66, 0.70, 0.80, 1.0],
};
const READING: [f32; 4] = [0.95, 0.96, 1.0, 1.0];
fn rows() -> Vec<ReadoutRow> {
vec![
ReadoutRow::new("SHORT", "1", READING),
ReadoutRow::new("A LONGER LABEL", "-12.75 m", READING),
]
}
#[test]
fn a_reading_ends_at_the_panels_right_margin_whatever_it_says() {
let atlas = FontAtlas::built_in();
let mut list = DrawList::new();
let rows = rows();
PANEL.draw(&mut list, &atlas, &rows);
let drawn: Vec<(Vec2, String)> = list
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Text { pos, text, .. } => Some((*pos, text.clone())),
_ => None,
})
.collect();
assert_eq!(drawn.len(), rows.len() * 2, "a label and a reading a row");
let right = PANEL.inset + PANEL.width - PANEL.pad;
for row in &rows {
let (pos, _) = drawn
.iter()
.find(|(_, text)| *text == row.value)
.unwrap_or_else(|| panic!("{} was not drawn", row.value));
let end = pos.x + atlas.text_width(&row.value, NATURAL_SCALE);
assert!(
(end - right).abs() < 1e-3,
"{} ends at {end} rather than the panel's {right}",
row.value,
);
}
}
#[test]
fn every_row_stands_one_row_height_below_the_one_above_it() {
let atlas = FontAtlas::built_in();
let mut list = DrawList::new();
let rows = rows();
PANEL.draw(&mut list, &atlas, &rows);
let labels: Vec<Vec2> = list
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Text { pos, text, .. }
if rows.iter().any(|row| row.label == *text) =>
{
Some(*pos)
}
_ => None,
})
.collect();
assert_eq!(labels.len(), rows.len());
for (index, pos) in labels.iter().enumerate() {
assert!((pos.x - (PANEL.inset + PANEL.pad)).abs() < 1e-3, "{pos:?}");
let want = PANEL.inset + PANEL.pad + index as f32 * PANEL.row_height;
assert!((pos.y - want).abs() < 1e-3, "row {index} at {pos:?}");
}
}
#[test]
fn the_box_is_as_tall_as_the_rows_it_holds() {
let atlas = FontAtlas::built_in();
let mut list = DrawList::new();
let rows = rows();
PANEL.draw(&mut list, &atlas, &rows);
let (min, max) = list
.commands()
.iter()
.find_map(|command| match command {
DrawCommand::Rect { min, max, .. } => Some((*min, *max)),
_ => None,
})
.expect("the panel drew no box");
assert_eq!(min, Vec2::new(PANEL.inset, PANEL.inset));
assert_eq!(max.x, PANEL.inset + PANEL.width);
assert!((max.y - (PANEL.inset + PANEL.height(rows.len()))).abs() < 1e-3);
}
fn arithmetic_draw_at(
panel: &ReadoutPanel,
list: &mut DrawList,
atlas: &FontAtlas,
origin: Vec2,
rows: &[ReadoutRow],
) {
let max = Vec2::new(origin.x + panel.width, origin.y + panel.height(rows.len()));
list.rect(origin, max, panel.background);
list.rect_outline(origin, max, panel.border_width, panel.border);
for (index, row) in rows.iter().enumerate() {
let y = origin.y + panel.pad + index as f32 * panel.row_height;
list.text(
Vec2::new(origin.x + panel.pad, y),
row.label.clone(),
panel.label,
NATURAL_FONT_SIZE,
);
let reading = atlas.text_width(&row.value, NATURAL_SCALE);
list.text(
Vec2::new(max.x - panel.pad - reading, y),
row.value.clone(),
row.colour,
NATURAL_FONT_SIZE,
);
}
}
fn arithmetic_hint(
panel: &ReadoutPanel,
list: &mut DrawList,
atlas: &FontAtlas,
extent: (u32, u32),
text: &str,
) {
let width = extent.0 as f32;
let height = extent.1 as f32;
let measured = atlas.text_width(text, NATURAL_SCALE);
list.text(
Vec2::new(
(width - measured) * 0.5,
height - panel.inset - panel.row_height,
),
text,
panel.label,
NATURAL_FONT_SIZE,
);
}
fn rendering(list: &DrawList) -> Vec<String> {
list.commands()
.iter()
.zip(list.clips())
.map(|(command, clip)| format!("{command:?} under {clip:?}"))
.collect()
}
fn sample_panels() -> [(&'static str, ReadoutPanel); 6] {
let widths = [
("shard", 190.0),
("towers readout", 176.0),
("towers build", 168.0),
("sparks", 196.0),
("puppet", 168.0),
("breach", 180.0),
];
widths.map(|(name, width)| (name, ReadoutPanel { width, ..PANEL }))
}
#[test]
fn the_tree_draws_every_sample_panel_exactly_where_the_arithmetic_did() {
let atlas = FontAtlas::built_in();
let rows = [
ReadoutRow::new("POSITION", "0.0 18.0", READING),
ReadoutRow::new("HEALTH", "100/100", [0.95, 0.40, 0.36, 1.0]),
ReadoutRow::new("TORCHES", "LIT", READING),
ReadoutRow::new("", "", READING),
ReadoutRow::new("W", "-12.75 m", READING),
];
for (name, panel) in sample_panels() {
for count in [0, 1, rows.len()] {
for origin in [Vec2::splat(panel.inset), Vec2::new(16.0, 114.0)] {
let mut tree = DrawList::new();
panel.draw_at(&mut tree, &atlas, origin, &rows[..count]);
let mut arithmetic = DrawList::new();
arithmetic_draw_at(&panel, &mut arithmetic, &atlas, origin, &rows[..count]);
assert_eq!(
rendering(&tree),
rendering(&arithmetic),
"{name}'s panel of {count} rows at {origin:?}"
);
}
}
}
}
#[test]
fn the_hint_lands_where_the_arithmetic_did_and_rounds_a_half_pixel() {
let atlas = FontAtlas::built_in();
let hint = "W/A/S/D walk Q/E turn SPACE strikes";
for extent in [(256, 192), (960, 720), (1920, 1080), (961, 721), (99, 10)] {
let mut tree = DrawList::new();
PANEL.hint(&mut tree, &atlas, extent, hint);
let mut arithmetic = DrawList::new();
arithmetic_hint(&PANEL, &mut arithmetic, &atlas, extent, hint);
if extent.0 % 2 == 0 {
assert_eq!(rendering(&tree), rendering(&arithmetic), "{extent:?}");
continue;
}
let at = |list: &DrawList| match &list.commands()[0] {
DrawCommand::Text { pos, .. } => *pos,
other => panic!("{other:?}"),
};
assert_eq!(
at(&tree),
at(&arithmetic) + Vec2::new(0.5, 0.0),
"{extent:?}"
);
}
}
#[cfg(feature = "parsed-font")]
#[test]
fn a_sheet_selecting_the_parsed_font_right_aligns_readings_in_it() {
use crate::font::Font;
use crate::font::layout::TextLayout;
let atlas = FontAtlas::built_in();
let mut ui = Ui::new();
ui.add_stylesheet("sans.css", "readout { font-family: sans-serif; }");
let mut list = DrawList::new();
let rows = rows();
PANEL.draw_in(ui, &mut list, &atlas, Vec2::splat(PANEL.inset), &rows);
assert!(
!list
.commands()
.iter()
.any(|command| matches!(command, DrawCommand::Text { .. })),
"a span still drew in the bitmap font"
);
let font = Font::sans();
let right = PANEL.inset + PANEL.width - PANEL.pad;
for row in &rows {
let laid = TextLayout::new(
font,
&row.value,
NATURAL_FONT_SIZE,
font.metrics().normal_line_height(NATURAL_FONT_SIZE),
None,
);
let wanted: Vec<_> = laid.glyphs().iter().map(|glyph| glyph.glyph).collect();
let origin = list
.commands()
.iter()
.find_map(|command| match command {
DrawCommand::Glyphs { origin, glyphs, .. }
if glyphs
.iter()
.map(|glyph| glyph.glyph)
.eq(wanted.iter().copied()) =>
{
Some(*origin)
}
_ => None,
})
.unwrap_or_else(|| panic!("{} was not drawn in the parsed font", row.value));
let end = origin.x + laid.width();
assert!(
end <= right && end > right - 1.0,
"{} ends at {end}, not within a pixel inside {right}",
row.value
);
}
}
#[test]
fn the_hint_is_centred_on_whatever_surface_it_was_given() {
let atlas = FontAtlas::built_in();
for extent in [(960u32, 720u32), (1920, 1080)] {
let mut list = DrawList::new();
PANEL.hint(&mut list, &atlas, extent, "W/A/S/D walk");
let pos = list
.commands()
.iter()
.find_map(|command| match command {
DrawCommand::Text { pos, .. } => Some(*pos),
_ => None,
})
.expect("the hint drew nothing");
let measured = atlas.text_width("W/A/S/D walk", NATURAL_SCALE);
assert!(
(pos.x + measured * 0.5 - extent.0 as f32 * 0.5).abs() < 1e-3,
"the hint is off centre on a {extent:?} surface: {pos:?}"
);
assert!(
(pos.y - (extent.1 as f32 - PANEL.inset - PANEL.row_height)).abs() < 1e-3,
"the hint is not one row above the bottom margin: {pos:?}"
);
}
}
}