use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{DEFAULT_SEED, TerminalEffect, seeded_rng};
use crate::render::braille::{BrailleGrid, DOTS_X, DOTS_Y};
use crate::render::dither::Dither;
use crate::render::glyph_ramp::{self, GlyphRamp};
use crate::render::palette::Palette;
use crossterm::style::{Attribute, Color};
use rand::RngExt;
use serde::{Deserialize, Serialize};
use std::time::Duration;
#[derive(Clone, Copy, Debug)]
struct Point3D {
x: f32,
y: f32,
z: f32,
}
#[derive(Clone, Copy, Debug)]
struct Point2D {
x: f32,
y: f32,
}
struct Edge {
v1: usize,
v2: usize,
faces: [usize; 2],
}
struct Face {
corners: [usize; 4],
}
const FACES: [Face; 6] = [
Face {
corners: [0, 3, 2, 1],
},
Face {
corners: [4, 5, 6, 7],
},
Face {
corners: [1, 2, 6, 5],
},
Face {
corners: [0, 4, 7, 3],
},
Face {
corners: [3, 7, 6, 2],
},
Face {
corners: [0, 1, 5, 4],
},
];
const EDGES: [Edge; 12] = [
Edge {
v1: 0,
v2: 1,
faces: [0, 5],
},
Edge {
v1: 1,
v2: 2,
faces: [0, 2],
},
Edge {
v1: 2,
v2: 3,
faces: [0, 4],
},
Edge {
v1: 3,
v2: 0,
faces: [0, 3],
},
Edge {
v1: 4,
v2: 5,
faces: [1, 5],
},
Edge {
v1: 5,
v2: 6,
faces: [1, 2],
},
Edge {
v1: 6,
v2: 7,
faces: [1, 4],
},
Edge {
v1: 7,
v2: 4,
faces: [1, 3],
},
Edge {
v1: 0,
v2: 4,
faces: [3, 5],
},
Edge {
v1: 1,
v2: 5,
faces: [2, 5],
},
Edge {
v1: 2,
v2: 6,
faces: [2, 4],
},
Edge {
v1: 3,
v2: 7,
faces: [3, 4],
},
];
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CubeOptions {
pub cube_size: f32,
pub rotation_speed_x: f32,
pub rotation_speed_y: f32,
pub rotation_speed_z: f32,
pub distance: f32,
pub use_braille: bool,
pub fit: f32,
pub filled: bool,
pub vertex_markers: bool,
pub glyphs: String,
pub seed: u64,
}
impl Default for CubeOptions {
fn default() -> Self {
Self {
cube_size: DEFAULT_CUBE_SIZE,
seed: DEFAULT_SEED,
rotation_speed_x: DEFAULT_SPEED_X,
rotation_speed_y: DEFAULT_SPEED_Y,
rotation_speed_z: DEFAULT_SPEED_Z,
distance: DEFAULT_DISTANCE,
use_braille: true,
fit: DEFAULT_FIT,
filled: DEFAULT_FILLED,
vertex_markers: true,
glyphs: DEFAULT_GLYPHS.to_string(),
}
}
}
const DEFAULT_SPEED_X: f32 = 0.25;
const DEFAULT_SPEED_Y: f32 = 0.35;
const DEFAULT_SPEED_Z: f32 = 0.18;
const SPEED_BAND: (f32, f32) = (0.6, 1.8);
const PHASE_SPAN: f32 = std::f32::consts::FRAC_PI_2;
#[derive(Clone, Copy, Debug, PartialEq)]
struct Motion {
speeds: (f32, f32, f32),
phase: (f32, f32, f32),
}
const DEFAULT_CUBE_SIZE: f32 = 1.0;
const DEFAULT_DISTANCE: f32 = 3.5;
const MAX_CAMERA_FILL: f32 = 0.8;
const MIN_DISTANCE: f32 = 0.1;
const MAX_DISTANCE: f32 = 1000.0;
const DEFAULT_FIT: f32 = 0.95;
const DEFAULT_FILLED: bool = false;
const Y_SQUASH: f32 = 0.8;
const EDGE_ON_EPSILON: f32 = 1.0e-3;
const MIN_FACE_DENSITY: f32 = 0.22;
const FAR_SIDE_BAND: f32 = 0.15;
const VERTEX_GLYPH: char = '\u{25C6}';
const ASCII_EDGE_GLYPH: char = '\u{2588}';
const VERTEX_COLOUR: Color = Color::Rgb {
r: 255,
g: 255,
b: 255,
};
const FACE_RAMP: &[Color] = &[
Color::Rgb {
r: 10,
g: 34,
b: 58,
},
Color::Rgb {
r: 20,
g: 92,
b: 128,
},
Color::Rgb {
r: 46,
g: 190,
b: 168,
},
Color::Rgb {
r: 190,
g: 255,
b: 226,
},
];
const EDGE_RAMP: &[Color] = &[
Color::Rgb {
r: 62,
g: 130,
b: 176,
},
Color::Rgb {
r: 120,
g: 210,
b: 216,
},
Color::Rgb {
r: 236,
g: 255,
b: 250,
},
Color::Rgb {
r: 255,
g: 255,
b: 255,
},
];
const DEFAULT_GLYPHS: &str = glyph_ramp::presets::BLOCKS;
const NO_DEPTH: u8 = 0;
#[derive(Clone, Copy)]
struct Rect {
left: usize,
top: usize,
right: usize,
bottom: usize,
}
impl Rect {
fn empty() -> Self {
Self {
left: usize::MAX,
top: usize::MAX,
right: 0,
bottom: 0,
}
}
fn is_empty(&self) -> bool {
self.right <= self.left || self.bottom <= self.top
}
fn grow(&mut self, x: usize, y: usize) {
self.left = self.left.min(x);
self.top = self.top.min(y);
self.right = self.right.max(x + 1);
self.bottom = self.bottom.max(y + 1);
}
}
#[derive(Clone)]
struct Field {
faces: BrailleGrid,
edges: BrailleGrid,
face_depth: Vec<u8>,
edge_depth: Vec<u8>,
vertex_depth: Vec<u8>,
dirty: Rect,
}
impl Field {
fn new(width: u16, height: u16) -> Self {
let (w, h) = (width.max(1) as usize, height.max(1) as usize);
Self {
faces: BrailleGrid::new(w, h),
edges: BrailleGrid::new(w, h),
face_depth: vec![NO_DEPTH; w * h],
edge_depth: vec![NO_DEPTH; w * h],
vertex_depth: vec![NO_DEPTH; w * h],
dirty: Rect::empty(),
}
}
fn resize(&mut self, width: u16, height: u16) {
let (w, h) = (width.max(1) as usize, height.max(1) as usize);
if (w, h) == (self.faces.width(), self.faces.height()) {
return;
}
*self = Self::new(width, height);
}
fn clear(&mut self) {
self.faces.clear();
self.edges.clear();
self.face_depth.fill(NO_DEPTH);
self.edge_depth.fill(NO_DEPTH);
self.vertex_depth.fill(NO_DEPTH);
self.dirty = Rect::empty();
}
#[inline]
fn mark_face(&mut self, x: usize, y: usize, depth: u8) {
let index = y * self.faces.width() + x;
if depth > self.face_depth[index] {
self.face_depth[index] = depth;
}
self.dirty.grow(x, y);
}
#[inline]
fn mark_edge_cell(&mut self, x: usize, y: usize, depth: u8) {
let index = y * self.faces.width() + x;
if depth > self.edge_depth[index] {
self.edge_depth[index] = depth;
}
self.dirty.grow(x, y);
}
#[inline]
fn mark_vertex(&mut self, x: usize, y: usize, depth: u8) {
let index = y * self.faces.width() + x;
if self.vertex_depth[index] == NO_DEPTH || depth < self.vertex_depth[index]
{
self.vertex_depth[index] = depth;
}
self.dirty.grow(x, y);
}
#[inline]
fn raise_edge_dot(&mut self, dot_x: usize, dot_y: usize, depth: u8) {
let (cx, cy) = (dot_x / DOTS_X, dot_y / DOTS_Y);
if cx >= self.edges.width() || cy >= self.edges.height() {
return;
}
self.edges.raise_dot(dot_x, dot_y);
let index = cy * self.edges.width() + cx;
if depth > self.edge_depth[index] {
self.edge_depth[index] = depth;
}
self.dirty.grow(cx, cy);
}
#[inline]
fn raise_face_dot(&mut self, dot_x: usize, dot_y: usize, depth: u8) {
let (cx, cy) = (dot_x / DOTS_X, dot_y / DOTS_Y);
if cx >= self.faces.width() || cy >= self.faces.height() {
return;
}
self.faces.raise_dot(dot_x, dot_y);
let index = cy * self.faces.width() + cx;
if depth > self.face_depth[index] {
self.face_depth[index] = depth;
}
self.dirty.grow(cx, cy);
}
}
#[inline]
fn quantise(depth: f32) -> u8 {
let depth = if depth.is_nan() {
0.0
} else {
depth.clamp(0.0, 1.0)
};
1 + (depth * 254.0).round() as u8
}
#[inline]
fn dequantise(packed: u8) -> f32 {
if packed == NO_DEPTH {
return 0.0;
}
(packed as f32 - 1.0) / 254.0
}
#[inline]
fn finite_or(value: f32, fallback: f32) -> f32 {
if value.is_finite() { value } else { fallback }
}
fn glyph_ramp(configured: &str) -> GlyphRamp {
let glyphs: Vec<char> = configured
.chars()
.filter(|glyph| {
!glyph.is_control() && glyph_ramp::is_ambiguous_or_narrow(*glyph)
})
.collect();
if glyphs.is_empty() {
GlyphRamp::from_text(DEFAULT_GLYPHS)
} else {
GlyphRamp::new(glyphs)
}
}
pub struct Cube {
pub screen_size: (u16, u16),
options: CubeOptions,
canvas: Canvas,
vertices: Vec<Point3D>,
rotation: (f32, f32, f32),
motion: Motion,
simulation_time: Duration,
field: Field,
ramp: GlyphRamp,
face_palette: Palette,
edge_palette: Palette,
rotated: Vec<Point3D>,
projected: Vec<Point2D>,
}
impl TerminalEffect for Cube {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.canvas.clear();
self.render();
let Self {
canvas,
field,
options,
ramp,
face_palette,
edge_palette,
..
} = self;
Self::flush(field, options, ramp, face_palette, edge_palette, canvas);
canvas.commit()
}
fn update(&mut self) {
self.simulation_time += Duration::from_secs_f64(1.0 / 60.0);
self.update_rotation();
}
fn update_with_context(&mut self, context: &crate::runtime::FrameContext) {
self.simulation_time += context.delta;
self.update_rotation();
}
fn update_size(&mut self, width: u16, height: u16) {
self.screen_size = (width, height);
self.canvas.resize(self.screen_size.0, self.screen_size.1);
self.field.resize(self.screen_size.0, self.screen_size.1);
}
fn reset(&mut self) {
*self = Self::new(self.options.clone(), self.screen_size);
}
}
impl Cube {
fn update_rotation(&mut self) {
let elapsed = self.simulation_time.as_secs_f32();
let motion = self.motion;
self.rotation = (
motion.phase.0 + elapsed * motion.speeds.0,
motion.phase.1 + elapsed * motion.speeds.1,
motion.phase.2 + elapsed * motion.speeds.2,
);
}
pub fn new(options: CubeOptions, screen_size: (u16, u16)) -> Self {
let canvas = Canvas::new(screen_size.0, screen_size.1);
let size = options.effective_cube_size();
let vertices = vec![
Point3D {
x: -size,
y: -size,
z: -size,
}, Point3D {
x: size,
y: -size,
z: -size,
}, Point3D {
x: size,
y: size,
z: -size,
}, Point3D {
x: -size,
y: size,
z: -size,
}, Point3D {
x: -size,
y: -size,
z: size,
}, Point3D {
x: size,
y: -size,
z: size,
}, Point3D {
x: size,
y: size,
z: size,
}, Point3D {
x: -size,
y: size,
z: size,
}, ];
let face_palette = Palette::new(FACE_RAMP.to_vec());
let edge_palette = Palette::new(EDGE_RAMP.to_vec());
let motion = options.motion();
Self {
screen_size,
rotated: vec![
Point3D {
x: 0.0,
y: 0.0,
z: 0.0
};
vertices.len()
],
projected: vec![Point2D { x: 0.0, y: 0.0 }; vertices.len()],
field: Field::new(screen_size.0, screen_size.1),
ramp: glyph_ramp(&options.glyphs),
face_palette,
edge_palette,
options,
canvas,
vertices,
rotation: motion.phase,
motion,
simulation_time: Duration::ZERO,
}
}
fn rotate_point(rotation: (f32, f32, f32), p: Point3D) -> Point3D {
let (rx, ry, rz) = rotation;
let cos_x = rx.cos();
let sin_x = rx.sin();
let y1 = p.y * cos_x - p.z * sin_x;
let z1 = p.y * sin_x + p.z * cos_x;
let cos_y = ry.cos();
let sin_y = ry.sin();
let x2 = p.x * cos_y + z1 * sin_y;
let z2 = -p.x * sin_y + z1 * cos_y;
let cos_z = rz.cos();
let sin_z = rz.sin();
let x3 = x2 * cos_z - y1 * sin_z;
let y3 = x2 * sin_z + y1 * cos_z;
Point3D {
x: x3,
y: y3,
z: z2,
}
}
fn effective_cube_size(&self) -> f32 {
let size = finite_or(self.options.cube_size, DEFAULT_CUBE_SIZE);
if size <= 0.0 {
return DEFAULT_CUBE_SIZE;
}
let distance = self.effective_distance();
size.min(MAX_CAMERA_FILL * distance / 3.0f32.sqrt())
}
fn effective_distance(&self) -> f32 {
let distance = finite_or(self.options.distance, DEFAULT_DISTANCE);
if distance <= 0.0 {
return DEFAULT_DISTANCE;
}
distance.clamp(MIN_DISTANCE, MAX_DISTANCE)
}
fn bounding_radius(&self) -> f32 {
self.effective_cube_size() * 3.0f32.sqrt()
}
fn projected_radius(radius: f32, distance: f32) -> f32 {
let inside = (distance * distance - radius * radius).max(0.0);
if inside <= 0.0 {
return 0.0;
}
radius / inside.sqrt()
}
fn projection_scale(&self) -> f32 {
let radius = self.bounding_radius();
let distance = self.effective_distance();
let unit_x = Self::projected_radius(radius, distance);
if unit_x <= 0.0 {
return 0.0;
}
let unit_y = unit_x * Y_SQUASH;
let half_width = self.screen_size.0 as f32 * 0.5;
let half_height = self.screen_size.1 as f32 * 0.5;
if half_width <= 0.0 || half_height <= 0.0 {
return 0.0;
}
let fit = finite_or(self.options.fit, DEFAULT_FIT);
let fit = if fit <= 0.0 {
DEFAULT_FIT
} else {
fit.min(1.0)
};
(half_width / unit_x).min(half_height / unit_y) * fit
}
fn project(p: Point3D, scale: f32, size: (u16, u16), distance: f32) -> Point2D {
let z_factor = 1.0 / (distance + p.z);
let width = size.0 as f32;
let height = size.1 as f32;
let screen_x = width / 2.0 + p.x * z_factor * scale;
let screen_y = height / 2.0 + p.y * z_factor * scale * Y_SQUASH;
Point2D {
x: screen_x,
y: screen_y,
}
}
fn face_depth_range(&self, visible: &[bool; FACES.len()]) -> (f32, f32) {
let mut low = f32::INFINITY;
let mut high = f32::NEG_INFINITY;
let mut farthest = f32::NEG_INFINITY;
for (index, face) in FACES.iter().enumerate() {
let z = self.face_centroid_z(face);
if !z.is_finite() {
continue;
}
farthest = farthest.max(z);
if !visible[index] {
continue;
}
low = low.min(z);
high = high.max(z);
}
if low.is_finite() && high.is_finite() {
let beyond = (farthest - high).max(0.0);
let far = high + FAR_SIDE_BAND * beyond;
if far.is_finite() && far - low > 0.0 {
return (low, far);
}
}
let near = if low.is_finite() { low } else { 0.0 };
let width =
(1.0 + FAR_SIDE_BAND) * 2.0 * self.bounding_radius().max(1.0e-3);
(near, near + width)
}
#[inline]
fn depth_of(&self, z: f32, range: (f32, f32)) -> f32 {
if !z.is_finite() {
return 0.0;
}
let span = range.1 - range.0;
let span = if span > 0.0 { span } else { 1.0 };
((range.1 - z) / span).clamp(0.0, 1.0)
}
fn face_is_front_facing(&self, face: &Face) -> bool {
let c = &self.rotated;
let (a, b, d, e) = (
c[face.corners[0]],
c[face.corners[1]],
c[face.corners[2]],
c[face.corners[3]],
);
let u = Point3D {
x: b.x - a.x,
y: b.y - a.y,
z: b.z - a.z,
};
let v = Point3D {
x: d.x - a.x,
y: d.y - a.y,
z: d.z - a.z,
};
let normal = Point3D {
x: u.y * v.z - u.z * v.y,
y: u.z * v.x - u.x * v.z,
z: u.x * v.y - u.y * v.x,
};
let centroid = Point3D {
x: (a.x + b.x + d.x + e.x) * 0.25,
y: (a.y + b.y + d.y + e.y) * 0.25,
z: (a.z + b.z + d.z + e.z) * 0.25,
};
let to_eye = Point3D {
x: -centroid.x,
y: -centroid.y,
z: -self.effective_distance() - centroid.z,
};
let dot = normal.x * to_eye.x + normal.y * to_eye.y + normal.z * to_eye.z;
let scale = Self::length(&normal) * Self::length(&to_eye);
dot > scale * EDGE_ON_EPSILON
}
fn length(p: &Point3D) -> f32 {
(p.x * p.x + p.y * p.y + p.z * p.z).sqrt()
}
fn row_span(quad: &[Point2D; 4], y: f32) -> Option<(f32, f32)> {
let mut low = f32::INFINITY;
let mut high = f32::NEG_INFINITY;
let mut crossings = 0;
for index in 0..4 {
let a = quad[index];
let b = quad[(index + 1) % 4];
if (a.y <= y) == (b.y <= y) {
continue;
}
let t = (y - a.y) / (b.y - a.y);
let x = a.x + t * (b.x - a.x);
if x < low {
low = x;
}
if x > high {
high = x;
}
crossings += 1;
}
if crossings < 2 {
return None;
}
Some((low, high))
}
fn fill_face_dots(&mut self, quad: [Point2D; 4], depth: u8) {
let density =
MIN_FACE_DENSITY + (1.0 - MIN_FACE_DENSITY) * dequantise(depth);
let mut min_x = f32::INFINITY;
let mut max_x = f32::NEG_INFINITY;
let mut min_y = f32::INFINITY;
let mut max_y = f32::NEG_INFINITY;
for p in &quad {
min_x = min_x.min(p.x);
max_x = max_x.max(p.x);
min_y = min_y.min(p.y);
max_y = max_y.max(p.y);
}
let dot_width = self.field.faces.dot_width() as i32;
let dot_height = self.field.faces.dot_height() as i32;
let first_y = ((min_y * DOTS_Y as f32 - 0.5).ceil() as i32).max(0);
let last_y =
((max_y * DOTS_Y as f32 - 0.5).floor() as i32).min(dot_height - 1);
for dot_y in first_y..=last_y {
let y = (dot_y as f32 + 0.5) / DOTS_Y as f32;
let Some((low, high)) = Self::row_span(&quad, y) else {
continue;
};
let first_x = ((low * DOTS_X as f32 - 0.5).ceil() as i32).max(0);
let last_x =
((high * DOTS_X as f32 - 0.5).floor() as i32).min(dot_width - 1);
for dot_x in first_x..=last_x {
let dither = Dither::Bayer4.at(dot_x as usize, dot_y as usize);
if density > dither {
self.field.raise_face_dot(
dot_x as usize,
dot_y as usize,
depth,
);
}
}
}
}
fn fill_face_cells(&mut self, quad: [Point2D; 4], depth: u8) {
let density =
MIN_FACE_DENSITY + (1.0 - MIN_FACE_DENSITY) * dequantise(depth);
let width = self.field.faces.width() as i32;
let height = self.field.faces.height() as i32;
let mut min_y = f32::INFINITY;
let mut max_y = f32::NEG_INFINITY;
for p in &quad {
min_y = min_y.min(p.y);
max_y = max_y.max(p.y);
}
let first_y = ((min_y - 0.5).ceil() as i32).max(0);
let last_y = ((max_y - 0.5).floor() as i32).min(height - 1);
for cell_y in first_y..=last_y {
let y = cell_y as f32 + 0.5;
let Some((low, high)) = Self::row_span(&quad, y) else {
continue;
};
let first_x = ((low - 0.5).ceil() as i32).max(0);
let last_x = ((high - 0.5).floor() as i32).min(width - 1);
for cell_x in first_x..=last_x {
if density > Dither::Bayer4.at(cell_x as usize, cell_y as usize) {
self.field
.mark_face(cell_x as usize, cell_y as usize, depth);
}
}
}
}
fn draw_edge_dots(&mut self, from: Point2D, to: Point2D, depth: u8) {
let mut x0 = (from.x * DOTS_X as f32) as i32;
let mut y0 = (from.y * DOTS_Y as f32) as i32;
let x1 = (to.x * DOTS_X as f32) as i32;
let y1 = (to.y * DOTS_Y as f32) as i32;
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 - y0).abs();
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy;
loop {
if x0 >= 0 && y0 >= 0 {
self.field.raise_edge_dot(x0 as usize, y0 as usize, depth);
}
if x0 == x1 && y0 == y1 {
break;
}
let e2 = 2 * err;
if e2 >= dy {
if x0 == x1 {
break;
}
err += dy;
x0 += sx;
}
if e2 <= dx {
if y0 == y1 {
break;
}
err += dx;
y0 += sy;
}
}
}
fn draw_edge_cells(&mut self, from: Point2D, to: Point2D, depth: u8) {
let width = self.field.faces.width() as i32;
let height = self.field.faces.height() as i32;
let mut x0 = from.x as i32;
let mut y0 = from.y as i32;
let x1 = to.x as i32;
let y1 = to.y as i32;
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 - y0).abs();
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy;
loop {
if x0 >= 0 && x0 < width && y0 >= 0 && y0 < height {
self.field.mark_edge_cell(x0 as usize, y0 as usize, depth);
}
if x0 == x1 && y0 == y1 {
break;
}
let e2 = 2 * err;
if e2 >= dy {
if x0 == x1 {
break;
}
err += dy;
x0 += sx;
}
if e2 <= dx {
if y0 == y1 {
break;
}
err += dx;
y0 += sy;
}
}
}
fn render(&mut self) {
self.field.clear();
let scale = self.projection_scale();
let size = self.screen_size;
let distance = self.effective_distance();
let rotation = self.rotation;
let braille = self.options.use_braille;
let filled = self.options.filled;
let markers = self.options.vertex_markers;
for index in 0..self.vertices.len() {
self.rotated[index] =
Self::rotate_point(rotation, self.vertices[index]);
}
for index in 0..self.rotated.len() {
self.projected[index] =
Self::project(self.rotated[index], scale, size, distance);
}
let mut visible = [false; FACES.len()];
for (index, face) in FACES.iter().enumerate() {
visible[index] = self.face_is_front_facing(face);
}
let range = self.face_depth_range(&visible);
let mut face_depth = [NO_DEPTH; FACES.len()];
for (index, face) in FACES.iter().enumerate() {
face_depth[index] =
quantise(self.depth_of(self.face_centroid_z(face), range));
}
for (index, face) in FACES.iter().enumerate() {
if !visible[index] || !filled {
continue;
}
let corners = face.corners;
let quad = [
self.projected[corners[0]],
self.projected[corners[1]],
self.projected[corners[2]],
self.projected[corners[3]],
];
if braille {
self.fill_face_dots(quad, face_depth[index]);
} else {
self.fill_face_cells(quad, face_depth[index]);
}
}
let drawn: Vec<(Point2D, Point2D, u8)> = EDGES
.iter()
.map(|edge| {
let mut depth = NO_DEPTH;
for face in edge.faces {
depth = depth.max(face_depth[face]);
}
(edge, depth)
})
.map(|(edge, depth)| {
(self.projected[edge.v1], self.projected[edge.v2], depth)
})
.collect();
for (from, to, depth) in drawn {
if braille {
self.draw_edge_dots(from, to, depth);
} else {
self.draw_edge_cells(from, to, depth);
}
}
if !markers {
return;
}
let width = self.field.faces.width();
let height = self.field.faces.height();
for index in 0..self.projected.len() {
let mut depth = NO_DEPTH;
for edge in EDGES.iter() {
if edge.v1 != index && edge.v2 != index {
continue;
}
for face in edge.faces {
if !visible[face] {
continue;
}
depth = depth.max(face_depth[face]);
}
}
if depth == NO_DEPTH {
continue;
}
let point = self.projected[index];
let (dot_x, dot_y) = (
(point.x * DOTS_X as f32) as i32,
(point.y * DOTS_Y as f32) as i32,
);
if dot_x < 0 || dot_y < 0 {
continue;
}
let (cell_x, cell_y) =
(dot_x as usize / DOTS_X, dot_y as usize / DOTS_Y);
if cell_x >= width || cell_y >= height {
continue;
}
self.field.mark_vertex(cell_x, cell_y, depth);
}
}
fn face_centroid_z(&self, face: &Face) -> f32 {
face.corners.iter().map(|c| self.rotated[*c].z).sum::<f32>() * 0.25
}
fn flush(
field: &Field,
options: &CubeOptions,
ramp: &GlyphRamp,
face_palette: &Palette,
edge_palette: &Palette,
canvas: &mut Canvas,
) {
if field.dirty.is_empty() {
return;
}
let rect = field.dirty;
let width = field.faces.width();
let (canvas_width, canvas_height) = (canvas.width(), canvas.height());
let surface = canvas.surface_mut();
for y in rect.top..rect.bottom.min(canvas_height) {
for x in rect.left..rect.right.min(canvas_width) {
let index = y * width + x;
if field.vertex_depth[index] != NO_DEPTH {
surface.set(
x,
y,
Cell::new(VERTEX_GLYPH, VERTEX_COLOUR, Attribute::Reset),
);
continue;
}
if options.use_braille {
let edge_bits = field.edges.cell_bits(x, y);
let bits = field.faces.cell_bits(x, y) | edge_bits;
if bits == 0 {
continue;
}
let (depth, palette) = if edge_bits != 0 {
(field.edge_depth[index], edge_palette)
} else {
(field.face_depth[index], face_palette)
};
let Some(symbol) = char::from_u32(0x2800 + bits as u32) else {
continue;
};
surface.set(
x,
y,
Cell::new(
symbol,
palette.sample(dequantise(depth)),
Attribute::Reset,
),
);
continue;
}
let (symbol, depth, palette) =
if field.edge_depth[index] != NO_DEPTH {
(ASCII_EDGE_GLYPH, field.edge_depth[index], edge_palette)
} else if field.face_depth[index] != NO_DEPTH {
(
ramp.sample(dequantise(field.face_depth[index])),
field.face_depth[index],
face_palette,
)
} else {
continue;
};
surface.set(
x,
y,
Cell::new(
symbol,
palette.sample(dequantise(depth)),
Attribute::Reset,
),
);
}
}
}
}
impl CubeOptions {
fn effective_cube_size(&self) -> f32 {
let size = finite_or(self.cube_size, DEFAULT_CUBE_SIZE);
if size <= 0.0 {
return DEFAULT_CUBE_SIZE;
}
let distance = finite_or(self.distance, DEFAULT_DISTANCE);
if !distance.is_finite() || distance <= 0.0 {
return size;
}
size.min(
MAX_CAMERA_FILL * distance.clamp(MIN_DISTANCE, MAX_DISTANCE)
/ 3.0f32.sqrt(),
)
}
fn motion(&self) -> Motion {
let mut rng = seeded_rng(self.seed, "cube.motion");
let mut rate = |configured: f32, fallback: f32| {
finite_or(configured, fallback)
* rng.random_range(SPEED_BAND.0..SPEED_BAND.1)
};
Motion {
speeds: (
rate(self.rotation_speed_x, DEFAULT_SPEED_X),
rate(self.rotation_speed_y, DEFAULT_SPEED_Y),
rate(self.rotation_speed_z, DEFAULT_SPEED_Z),
),
phase: (
rng.random_range(0.0..PHASE_SPAN),
rng.random_range(0.0..PHASE_SPAN),
rng.random_range(0.0..PHASE_SPAN),
),
}
}
}
impl Cube {
#[cfg(test)]
fn project_vertex(&self, vertex: Point3D) -> Point2D {
Self::project(
Self::rotate_point(self.rotation, vertex),
self.projection_scale(),
self.screen_size,
self.effective_distance(),
)
}
#[cfg(test)]
fn depth_and_luminance(&self) -> Vec<(f32, f32)> {
let mut out = Vec::new();
if self.field.dirty.is_empty() {
return out;
}
let rect = self.field.dirty;
let width = self.field.faces.width();
for y in rect.top..rect.bottom {
for x in rect.left..rect.right {
let index = y * width + x;
if self.field.vertex_depth[index] != NO_DEPTH {
continue;
}
if self.options.use_braille {
if self.field.edges.cell_bits(x, y) == 0
&& self.field.faces.cell_bits(x, y) == 0
{
continue;
}
let from_edge = self.field.edges.cell_bits(x, y) != 0;
let (depth, palette) = if from_edge {
(self.field.edge_depth[index], &self.edge_palette)
} else {
(self.field.face_depth[index], &self.face_palette)
};
out.push((
dequantise(depth),
Self::luminance(palette.sample(dequantise(depth))),
));
} else if self.field.edge_depth[index] != NO_DEPTH {
out.push((
dequantise(self.field.edge_depth[index]),
Self::luminance(
self.edge_palette
.sample(dequantise(self.field.edge_depth[index])),
),
));
} else if self.field.face_depth[index] != NO_DEPTH {
let depth = dequantise(self.field.face_depth[index]);
out.push((
depth,
Self::luminance(self.face_palette.sample(depth)),
));
}
}
}
out
}
#[cfg(test)]
fn luminance(colour: Color) -> f32 {
match colour {
Color::Rgb { r, g, b } => {
0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32
}
_ => 0.0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::render::braille::braille_bit;
use std::collections::{HashMap, HashSet};
const GENERIC: (f32, f32, f32) = (0.41, 0.73, 0.19);
fn placed(cube_size: f32, size: (u16, u16)) -> Cube {
let options = CubeOptions {
cube_size,
..Default::default()
};
Cube::new(options, size)
}
fn filled(cube_size: f32, size: (u16, u16)) -> Cube {
Cube::new(
CubeOptions {
cube_size,
filled: true,
..Default::default()
},
size,
)
}
fn frame(
cube: &mut Cube,
rotation: (f32, f32, f32),
) -> Vec<(usize, usize, Cell)> {
cube.rotation = rotation;
cube.get_diff()
}
fn dot_patterns(
diff: &[(usize, usize, Cell)],
) -> std::collections::HashMap<(usize, usize), u8> {
diff.iter()
.filter(|(_, _, cell)| cell.symbol != ' ')
.map(|(x, y, cell)| {
let bits = (cell.symbol as u32).saturating_sub(0x2800) as u8;
((*x, *y), bits)
})
.collect()
}
fn edge_dots(
projected: &[Point2D],
edge: &Edge,
size: (u16, u16),
) -> HashSet<(i32, i32, u8)> {
let mut x0 = (projected[edge.v1].x * DOTS_X as f32) as i32;
let mut y0 = (projected[edge.v1].y * DOTS_Y as f32) as i32;
let x1 = (projected[edge.v2].x * DOTS_X as f32) as i32;
let y1 = (projected[edge.v2].y * DOTS_Y as f32) as i32;
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 - y0).abs();
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy;
let width = size.0 as i32 * DOTS_X as i32;
let height = size.1 as i32 * DOTS_Y as i32;
let mut out = HashSet::new();
loop {
if x0 >= 0 && x0 < width && y0 >= 0 && y0 < height {
out.insert((
x0 / DOTS_X as i32,
y0 / DOTS_Y as i32,
braille_bit(x0 as usize % DOTS_X, y0 as usize % DOTS_Y),
));
}
if x0 == x1 && y0 == y1 {
break;
}
let e2 = 2 * err;
if e2 >= dy {
if x0 == x1 {
break;
}
err += dy;
x0 += sx;
}
if e2 <= dx {
if y0 == y1 {
break;
}
err += dx;
y0 += sy;
}
}
out
}
fn painted(diff: &[(usize, usize, Cell)]) -> HashMap<(usize, usize), Cell> {
diff.iter().map(|(x, y, cell)| ((*x, *y), *cell)).collect()
}
fn disagreement(
a: &HashMap<(usize, usize), Cell>,
b: &HashMap<(usize, usize), Cell>,
) -> f32 {
let union: HashSet<(usize, usize)> =
a.keys().chain(b.keys()).copied().collect();
if union.is_empty() {
return 1.0;
}
let differing = union
.iter()
.filter(|key| a.get(*key) != b.get(*key))
.count();
differing as f32 / union.len() as f32
}
fn seeded(seed: u64) -> Cube {
Cube::new(
CubeOptions {
seed,
..Default::default()
},
(200, 50),
)
}
fn seeded_after(seed: u64, steps: u32) -> Cube {
let mut cube = seeded(seed);
for _ in 0..steps {
cube.update();
}
cube
}
fn cell_of(point: Point2D) -> (usize, usize) {
let dot_x = (point.x * DOTS_X as f32) as i32;
let dot_y = (point.y * DOTS_Y as f32) as i32;
(
dot_x.max(0) as usize / DOTS_X,
dot_y.max(0) as usize / DOTS_Y,
)
}
fn edge_luminances(
cube: &Cube,
diff: &[(usize, usize, Cell)],
) -> Vec<(bool, f32)> {
let by_cell: HashMap<(usize, usize), Cell> =
diff.iter().map(|(x, y, cell)| ((*x, *y), *cell)).collect();
let projected: Vec<Point2D> = cube
.vertices
.iter()
.map(|v| cube.project_vertex(*v))
.collect();
let per_edge: Vec<HashSet<(i32, i32)>> = EDGES
.iter()
.map(|edge| {
edge_dots(&projected, edge, cube.screen_size)
.into_iter()
.map(|(x, y, _)| (x, y))
.collect()
})
.collect();
let mut reachers: HashMap<(i32, i32), usize> = HashMap::new();
for cells in &per_edge {
for cell in cells {
*reachers.entry(*cell).or_insert(0) += 1;
}
}
let front: Vec<bool> = FACES
.iter()
.map(|face| cube.face_is_front_facing(face))
.collect();
let mut out = Vec::new();
for (index, cells) in per_edge.iter().enumerate() {
let edge = &EDGES[index];
let far_side = !front[edge.faces[0]] && !front[edge.faces[1]];
let mut lums: Vec<f32> = Vec::new();
for (x, y) in cells {
if *x < 0 || *y < 0 || reachers[&(*x, *y)] != 1 {
continue;
}
let Some(cell) = by_cell.get(&(*x as usize, *y as usize)) else {
continue;
};
if cell.symbol == VERTEX_GLYPH {
continue;
}
lums.push(Cube::luminance(cell.color));
}
if lums.is_empty() {
continue;
}
let low = lums.iter().copied().fold(f32::INFINITY, f32::min);
let high = lums.iter().copied().fold(f32::NEG_INFINITY, f32::max);
assert_eq!(
low,
high,
"edge {} of EDGES was drawn across {:.1} of luminance at one \
rotation, so it is not one colour",
index,
high - low
);
out.push((far_side, (low + high) * 0.5));
}
out
}
#[test]
fn every_corner_carries_the_union_of_its_edges() {
let options = CubeOptions {
vertex_markers: false,
filled: false,
..Default::default()
};
let mut cube = Cube::new(options, (200, 50));
let diff = frame(&mut cube, GENERIC);
let drawn = dot_patterns(&diff);
let projected: Vec<Point2D> = cube
.vertices
.iter()
.map(|v| cube.project_vertex(*v))
.collect();
let mut corners_checked = 0;
let mut full_junctions = 0;
for vertex in 0..projected.len() {
let cell = cell_of(projected[vertex]);
let incident: Vec<&Edge> = EDGES
.iter()
.filter(|edge| edge.v1 == vertex || edge.v2 == vertex)
.collect();
if incident.len() == 3 {
full_junctions += 1;
}
assert_eq!(
incident.len(),
3,
"vertex {vertex} has {} edges, which is not a cube",
incident.len()
);
let mut union = 0u8;
let mut per_edge = Vec::new();
for edge in &incident {
let mut bits = 0u8;
for (cx, cy, bit) in edge_dots(&projected, edge, cube.screen_size) {
if (cx, cy) == (cell.0 as i32, cell.1 as i32) {
bits |= bit;
}
}
per_edge.push(bits);
union |= bits;
}
if union == 0 {
continue;
}
if !per_edge
.iter()
.any(|bits| bits.count_ones() < union.count_ones())
{
continue;
}
let got = drawn.get(&cell).copied().unwrap_or(0);
assert_eq!(
got & union,
union,
"vertex {vertex} at {cell:?}: its {} edges raise {union:#010b} \
into the cell and the cell was drawn {got:#010b}, so {:#010b} \
was overwritten away",
incident.len(),
union & !got
);
corners_checked += 1;
}
assert_eq!(
full_junctions, 8,
"a cube has three edges at each of its eight corners"
);
assert!(
corners_checked >= 6,
"only {corners_checked} corners were on screen, so the merge \
is barely tested"
);
}
#[test]
fn the_projection_is_fitted_to_the_screen() {
for size in [
(80u16, 24u16),
(200, 50),
(12, 6),
(6, 40),
(400, 200),
(3, 3),
(1, 1),
] {
for cube_size in [1.0f32, 1.4, 1.8, 2.5, 8.0] {
let mut cube = placed(cube_size, size);
for step in 0..90 {
let t = step as f32 * 0.11;
cube.rotation = (t * 0.25, t * 0.35, t * 0.18);
for (index, vertex) in cube.vertices.iter().enumerate() {
let p = cube.project_vertex(*vertex);
assert!(
p.x >= 0.0
&& p.y >= 0.0
&& p.x < size.0 as f32
&& p.y < size.1 as f32,
"{}x{} at cube_size {cube_size} put vertex {index} at \
({:.2}, {:.2}), off screen, at t = {t:.2}",
size.0,
size.1,
p.x,
p.y
);
}
}
}
}
}
#[test]
fn the_cube_fills_the_limiting_half_axis() {
for size in [(80u16, 24u16), (200, 50), (400, 200)] {
let mut cube = placed(1.0, size);
let half_height = size.1 as f32 * 0.5;
let mut extent = 0.0f32;
for step in 0..300 {
let t = step as f32 * 0.021;
cube.rotation = (t, t * 1.4, t * 0.7);
for vertex in cube.vertices.iter() {
let p = cube.project_vertex(*vertex);
extent = extent.max((p.y - half_height).abs());
}
}
let fraction = extent / half_height;
assert!(
fraction > 0.90,
"{}x{}: the cube reaches only {:.0}% of the way to the top and \
bottom of the screen, against 73% for the old fixed 0.8",
size.0,
size.1,
fraction * 100.0
);
}
}
#[test]
fn nearer_geometry_is_brighter_than_farther_geometry() {
let mut near = Vec::new();
let mut far = Vec::new();
let mut widest_spread = 0.0f32;
let mut widest_contrast = 0.0f32;
let mut measured = 0usize;
for step in 0..150 {
let t = step as f32 * 0.041;
let mut cube = filled(1.0, (80, 24));
frame(&mut cube, (t, t * 1.4, t * 0.7));
let pairs = cube.depth_and_luminance();
measured += pairs.len();
for (depth, luminance) in &pairs {
if *depth >= 0.8 {
near.push(*luminance);
} else if *depth <= 0.2 {
far.push(*luminance);
}
}
if pairs.is_empty() {
continue;
}
let lo = pairs.iter().map(|(d, _)| *d).fold(1.0f32, f32::min);
let hi = pairs.iter().map(|(d, _)| *d).fold(0.0f32, f32::max);
if hi - lo <= widest_spread {
continue;
}
let at = |target: f32| {
pairs
.iter()
.filter(|(d, _)| (*d - target).abs() < 0.05)
.map(|(_, l)| *l)
.next()
.unwrap_or(f32::NAN)
};
let contrast = at(hi) - at(lo);
if contrast.is_finite() {
widest_spread = hi - lo;
widest_contrast = contrast;
}
}
assert!(
measured > 20_000,
"the sweep only produced {measured} cells to measure"
);
let mean =
|values: &[f32]| values.iter().sum::<f32>() / values.len() as f32;
assert!(
near.len() > 200 && far.len() > 200,
"the sweep produced {} near cells and {} far cells, so the ramp is \
not being exercised across its range",
near.len(),
far.len()
);
let (near_mean, far_mean) = (mean(&near), mean(&far));
assert!(
near_mean > far_mean + 40.0,
"cells in the nearest fifth average {near_mean:.1} and cells in the \
furthest average {far_mean:.1}, so distance does not order the \
brightness",
);
assert!(
widest_spread > 0.8,
"the widest depth spread in the sweep was {widest_spread:.2}, so the \
ramp is never used end to end"
);
assert!(
widest_contrast > 40.0,
"at the frame with the widest spread the two ends of the ramp differ \
by {widest_contrast:.1} in luminance, so the ramp is not steep \
enough to read"
);
}
#[test]
fn a_face_on_rotation_fills_the_near_face() {
let size = (200u16, 50u16);
let mut cube = filled(1.0, size);
let diff = frame(&mut cube, (0.0, 0.0, 0.0));
let drawn = dot_patterns(&diff);
let corner = cube.project_vertex(cube.vertices[0]);
let half_x = (size.0 as f32 / 2.0 - corner.x).abs();
let half_y = (size.1 as f32 / 2.0 - corner.y).abs();
let mut interior_dots = 0usize;
for ((x, y), bits) in &drawn {
let dx = (*x as f32 + 0.5 - size.0 as f32 / 2.0).abs();
let dy = (*y as f32 + 0.5 - size.1 as f32 / 2.0).abs();
if dx < half_x - 1.5 && dy < half_y - 1.5 {
interior_dots += bits.count_ones() as usize;
}
}
assert!(
interior_dots > 1000,
"only {interior_dots} dots inside the near face at a face-on \
rotation, against 240 for the unfilled wireframe, so the face is \
not filled"
);
}
#[test]
fn the_drawn_edge_ink_is_exactly_the_twelve_edges_union() {
for rotation in [(0.0f32, 0.0f32, 0.0f32), GENERIC, (0.41, 0.9, 0.55)] {
let mut cube = placed(1.0, (200, 50));
frame(&mut cube, rotation);
let projected: Vec<Point2D> = cube
.vertices
.iter()
.map(|v| cube.project_vertex(*v))
.collect();
let mut expected: std::collections::HashMap<(usize, usize), u8> =
std::collections::HashMap::new();
let mut edges_with_ink = 0;
for edge in EDGES.iter() {
let mut raised = false;
for (cx, cy, bit) in edge_dots(&projected, edge, cube.screen_size) {
if cx < 0 || cy < 0 {
continue;
}
raised = true;
*expected.entry((cx as usize, cy as usize)).or_insert(0) |= bit;
}
edges_with_ink += usize::from(raised);
}
assert_eq!(
edges_with_ink, 12,
"at {rotation:?} only {edges_with_ink} of the twelve edges put \
ink on the screen, so one is not being drawn"
);
let mut inked = 0;
for y in 0..cube.field.edges.height() {
for x in 0..cube.field.edges.width() {
let got = cube.field.edges.cell_bits(x, y);
let want = expected.get(&(x, y)).copied().unwrap_or(0);
if got != want {
let what = if got & !want == 0 {
"dots were drawn that no edge raises"
} else {
"dots from an edge were lost"
};
panic!(
"cell ({x}, {y}) at {rotation:?} has edge pattern {got:#010b}, the twelve edges put {want:#010b} there -- {what}"
);
}
inked += usize::from(got != 0);
}
}
assert!(
inked > 100,
"at {rotation:?} only {inked} cells carry edge ink"
);
}
}
#[test]
fn a_face_on_rotation_still_draws_all_twelve_edges() {
let size = (200u16, 50u16);
let mut cube = placed(1.0, size);
let diff = frame(&mut cube, (0.0, 0.0, 0.0));
let faces: Vec<bool> = FACES
.iter()
.map(|face| cube.face_is_front_facing(face))
.collect();
assert_eq!(
faces.iter().filter(|f| **f).count(),
1,
"a cube viewed down one of its axes shows exactly one face, but {} were treated as front-facing",
faces.iter().filter(|f| **f).count()
);
assert!(faces[0], "and it is the near one, not a far face");
let far_side = EDGES
.iter()
.filter(|edge| !faces[edge.faces[0]] && !faces[edge.faces[1]])
.count();
assert_eq!(
far_side, 8,
"a cube viewed down one of its axes has eight edges behind the near \
face, not {far_side}"
);
let projected: Vec<Point2D> = cube
.vertices
.iter()
.map(|v| cube.project_vertex(*v))
.collect();
let mut with_ink = 0;
for edge in EDGES.iter() {
let on_screen = edge_dots(&projected, edge, cube.screen_size)
.into_iter()
.any(|(x, y, _)| x >= 0 && y >= 0);
with_ink += usize::from(on_screen);
}
assert_eq!(
with_ink, 12,
"at a face-on rotation only {with_ink} of the twelve edges put ink on \
the screen: the far face is {far_side} of them and all of it has to \
be there, or the cube does not read as turning"
);
assert!(!diff.is_empty(), "the face-on frame drew nothing");
for (x, y, cell) in &diff {
assert_eq!(
cell.attr,
Attribute::Reset,
"cell ({x}, {y}) is bold at a face-on rotation, which brightens \
the depth ramp into white on many terminals"
);
assert!(
*x < size.0 as usize && *y < size.1 as usize,
"cell ({x}, {y}) is outside a {size:?} screen"
);
}
}
#[test]
fn a_far_edge_is_dimmer_than_the_near_ones() {
let mut gaps: Vec<(f32, (f32, f32, f32))> = Vec::new();
let mut measured = 0usize;
for step in 0..200 {
let t = step as f32 * 0.041;
let mut cube = placed(1.0, (200, 50));
let diff = frame(&mut cube, (t, t * 1.4, t * 0.7));
let sides = edge_luminances(&cube, &diff);
let near: Vec<f32> = sides
.iter()
.filter(|(behind, _)| !*behind)
.map(|(_, l)| *l)
.collect();
let far: Vec<f32> = sides
.iter()
.filter(|(behind, _)| *behind)
.map(|(_, l)| *l)
.collect();
assert!(
(4..=9).contains(&near.len()) && (3..=8).contains(&far.len()),
"at t = {t:.3} the sweep found {} near-side and {} far-side \
edges, which is not a cube seen from outside",
near.len(),
far.len()
);
measured += near.len() + far.len();
let dimmest_near = near.iter().copied().fold(f32::INFINITY, f32::min);
let brightest_far =
far.iter().copied().fold(f32::NEG_INFINITY, f32::max);
gaps.push((
dimmest_near - brightest_far,
(dimmest_near, brightest_far, t),
));
}
assert!(
measured >= 2300,
"only {measured} of the 2400 edge measurements in the sweep found a \
cell to themselves, so the rest were dropped and the gaps above are \
over a shrinking sample"
);
let tightest = gaps
.iter()
.min_by(|a, b| a.0.total_cmp(&b.0))
.expect("the sweep produced rotations");
assert!(
tightest.0 > 0.0,
"at t = {:.3} the brightest far-side edge is drawn at {:.1} against \
the dimmest near-side edge's {:.1}, so at that pose the far side is \
not dimmer at all",
tightest.1.2,
tightest.1.1,
tightest.1.0
);
let mut sorted: Vec<f32> = gaps.iter().map(|(gap, _)| *gap).collect();
sorted.sort_by(f32::total_cmp);
let median = sorted[sorted.len() / 2];
let fifth = sorted[sorted.len() * 5 / 100];
assert!(
median > 80.0,
"the median gap between the two sides is {median:.1} of 255, so at \
half of all rotations the far side is not clearly dimmer"
);
assert!(
fifth > 30.0,
"the 5th-percentile gap is {fifth:.1}, so more than one rotation in \
twenty puts the far side within a tenth of the way to the near side"
);
let mut cube = placed(1.0, (200, 50));
let diff = frame(&mut cube, GENERIC);
let sides = edge_luminances(&cube, &diff);
let dimmest_near = sides
.iter()
.filter(|(behind, _)| !*behind)
.map(|(_, l)| *l)
.fold(f32::INFINITY, f32::min);
let brightest_far = sides
.iter()
.filter(|(behind, _)| *behind)
.map(|(_, l)| *l)
.fold(f32::NEG_INFINITY, f32::max);
assert!(
dimmest_near - brightest_far > 40.0,
"at {GENERIC:?} the far side is drawn at {brightest_far:.1} against \
the near side's {dimmest_near:.1}, which is not a visible difference"
);
}
#[test]
fn the_corner_markers_are_white() {
let mut cube = placed(1.0, (80, 24));
let diff = frame(&mut cube, GENERIC);
let mut markers = 0;
for (x, y, cell) in diff {
if cell.symbol != VERTEX_GLYPH {
continue;
}
assert_eq!(
cell.color, VERTEX_COLOUR,
"the marker at ({x}, {y}) is {cell:?} rather than the flat marker colour"
);
markers += 1;
}
assert_eq!(markers, 7, "a cube hides exactly one corner from any view");
}
#[test]
fn only_the_visible_corners_are_marked() {
for size in [(80u16, 24u16), (200, 50), (120, 40)] {
for rotation in [GENERIC, (0.41, 0.9, 0.55), (0.0, 0.0, 0.0)] {
let mut cube = placed(1.0, size);
let diff = frame(&mut cube, rotation);
let by_cell: std::collections::HashMap<(usize, usize), Cell> =
diff.iter().map(|(x, y, cell)| ((*x, *y), *cell)).collect();
let visible: Vec<bool> = FACES
.iter()
.map(|face| cube.face_is_front_facing(face))
.collect();
let expected: Vec<bool> = (0..cube.vertices.len())
.map(|vertex| {
EDGES.iter().any(|edge| {
(edge.v1 == vertex || edge.v2 == vertex)
&& (visible[edge.faces[0]]
|| visible[edge.faces[1]])
})
})
.collect();
let visible_corners = expected.iter().filter(|v| **v).count();
assert!(
(4..=7).contains(&visible_corners),
"{}x{} at {rotation:?}: {visible_corners} corners are visible, \
which is not a cube",
size.0,
size.1
);
for (vertex, corner) in cube.vertices.iter().enumerate() {
let cell = cell_of(cube.project_vertex(*corner));
let symbol =
by_cell.get(&cell).map(|c| c.symbol).unwrap_or(' ');
if expected[vertex] {
assert_eq!(
symbol, VERTEX_GLYPH,
"{}x{} at {rotation:?}: visible vertex {vertex} at \
{cell:?} drew {symbol:?}",
size.0, size.1
);
} else {
assert_ne!(
symbol, VERTEX_GLYPH,
"{}x{} at {rotation:?}: hidden vertex {vertex} at \
{cell:?} was marked, so a diamond is showing through \
the solid",
size.0, size.1
);
}
}
}
}
}
#[test]
fn no_cell_is_bold() {
for braille in [true, false] {
let options = CubeOptions {
use_braille: braille,
..Default::default()
};
let mut cube = Cube::new(options, (80, 24));
for (index, rotation) in
[GENERIC, (1.1, 0.3, 0.9)].into_iter().enumerate()
{
let diff = frame(&mut cube, rotation);
assert!(
!diff.is_empty(),
"braille={braille} step {index} drew nothing"
);
for (x, y, cell) in diff {
assert_eq!(
cell.attr,
Attribute::Reset,
"braille={braille}: cell ({x}, {y}) is bold, which \
brightens the ramp into white on many terminals"
);
}
}
}
}
#[test]
fn every_glyph_the_cube_can_draw_is_one_cell_wide() {
for glyph in [VERTEX_GLYPH, ASCII_EDGE_GLYPH].into_iter().chain(
(1u8..=255)
.map(|bits| char::from_u32(0x2800 + bits as u32).unwrap_or('?')),
) {
assert!(
glyph_ramp::is_ambiguous_or_narrow(glyph)
|| ('\u{2800}'..='\u{28FF}').contains(&glyph),
"{glyph:?} (U+{:04X}) could shear a cell-indexed grid",
glyph as u32
);
}
}
#[test]
fn a_degenerate_option_falls_back_rather_than_drawing_nothing() {
for bad in [0.0f32, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
for field in ["cube_size", "distance", "fit"] {
let options = match field {
"cube_size" => CubeOptions {
cube_size: bad,
..Default::default()
},
"distance" => CubeOptions {
distance: bad,
..Default::default()
},
_ => CubeOptions {
fit: bad,
..Default::default()
},
};
let mut cube = Cube::new(options, (80, 24));
let diff = frame(&mut cube, GENERIC);
assert!(
diff.len() > 40,
"{field} = {bad} drew only {} cells, so the cube is not there",
diff.len()
);
for (x, y, cell) in &diff {
assert!(
*x < 80 && *y < 24,
"{field} = {bad} produced a cell at ({x}, {y}), which is \
off screen"
);
assert!(
cell.symbol.is_ascii()
|| ('\u{2500}'..='\u{2BFF}').contains(&cell.symbol),
"{field} = {bad} produced {cell:?} at ({x}, {y}), which is \
not a glyph this effect can draw"
);
}
}
}
}
#[test]
fn a_cube_too_large_for_its_camera_is_clamped() {
let size = DEFAULT_CUBE_SIZE;
assert_eq!(CubeOptions::default().effective_cube_size(), size);
for requested in [1.5f32, 2.0, 3.0, 100.0] {
let options = CubeOptions {
cube_size: requested,
..Default::default()
};
let effective = options.effective_cube_size();
let limit = MAX_CAMERA_FILL * DEFAULT_DISTANCE / 3.0f32.sqrt();
assert!(
effective <= limit,
"cube_size {requested} stayed at {effective}, past the \
{limit} the camera cannot see it from"
);
let mut cube = Cube::new(options, (80, 24));
let diff = frame(&mut cube, GENERIC);
assert!(!diff.is_empty(), "cube_size {requested} drew nothing");
}
}
#[test]
fn the_new_keys_round_trip_through_toml() {
let options: CubeOptions =
toml::from_str("fit = 0.8\nfilled = false\nglyphs = \" .:oO@\"\n")
.expect("three keys parse");
assert_eq!(options.fit, 0.8);
assert!(!options.filled);
assert_eq!(options.glyphs, " .:oO@");
assert_eq!(
options.cube_size,
CubeOptions::default().cube_size,
"three keys in the section silently reset the others"
);
let serialised = toml::to_string(&options).expect("the section serialises");
for key in [
"cube_size",
"rotation_speed_x",
"distance",
"use_braille",
"fit",
"filled",
"vertex_markers",
"glyphs",
] {
assert!(
serialised.contains(key),
"{key} is missing from the serialised form, so --print-config \
would not write it: {serialised}"
);
}
}
#[test]
fn an_unusable_glyph_config_falls_back_to_the_default_ramp() {
for configured in ["", "\u{7}\u{1}", "\u{4E2D}"] {
let ramp = glyph_ramp(configured);
assert_eq!(
ramp.glyphs(),
DEFAULT_GLYPHS.chars().collect::<Vec<char>>(),
"{configured:?} did not fall back to the documented default"
);
}
assert_eq!(DEFAULT_GLYPHS, glyph_ramp::presets::BLOCKS);
}
#[test]
fn the_rotation_defaults_are_unchanged() {
let options = CubeOptions::default();
assert_eq!(options.rotation_speed_x, 0.25);
assert_eq!(options.rotation_speed_y, 0.35);
assert_eq!(options.rotation_speed_z, 0.18);
assert_eq!(options.distance, DEFAULT_DISTANCE);
assert!(options.use_braille);
assert!(
!options.filled,
"the faces are filled by default again, which is the look that was \
asked to be taken off by default"
);
assert!(options.vertex_markers);
}
#[test]
fn the_default_is_the_wireframe_rather_than_the_filled_cube() {
assert!(
!CubeOptions::default().filled,
"the default still fills faces"
);
let size = (200u16, 50u16);
let interior = |filled: bool| {
let mut cube = Cube::new(
CubeOptions {
filled,
..Default::default()
},
size,
);
let diff = frame(&mut cube, (0.0, 0.0, 0.0));
let drawn = dot_patterns(&diff);
let corner = cube.project_vertex(cube.vertices[0]);
let half_x = (size.0 as f32 / 2.0 - corner.x).abs();
let half_y = (size.1 as f32 / 2.0 - corner.y).abs();
let mut dots = 0usize;
for ((x, y), bits) in &drawn {
let dx = (*x as f32 + 0.5 - size.0 as f32 / 2.0).abs();
let dy = (*y as f32 + 0.5 - size.1 as f32 / 2.0).abs();
if dx < half_x - 1.5 && dy < half_y - 1.5 {
dots += bits.count_ones() as usize;
}
}
dots
};
let default_dots = interior(false);
let filled_dots = interior(true);
assert!(
filled_dots > default_dots * 10,
"filling the faces changed the interior from {default_dots} dots to \
{filled_dots}, so the option is not reaching the renderer"
);
assert!(
default_dots < filled_dots / 10,
"the *default* frame has {default_dots} dots inside the near face, \
against {filled_dots} with `filled = true`, so the default is \
drawing the filled cube"
);
}
#[test]
fn the_wireframe_alone_draws_edges_and_nothing_else() {
let options = CubeOptions {
filled: false,
..Default::default()
};
let mut cube = Cube::new(options, (200, 50));
let diff = frame(&mut cube, GENERIC);
assert!(!diff.is_empty());
let width = cube.field.faces.width();
for y in 0..cube.field.faces.height() {
for x in 0..width {
let index = y * width + x;
assert_eq!(
cube.field.face_depth[index], NO_DEPTH,
"cell ({x}, {y}) was filled by a face with filled = false"
);
}
}
let dots: u32 = diff
.iter()
.map(|(_, _, cell)| (cell.symbol as u32).saturating_sub(0x2800))
.map(|bits| bits.count_ones())
.sum();
assert!(
dots > 250,
"the wireframe drew only {dots} dots, which is not twelve edges"
);
}
#[test]
fn two_seeds_open_on_different_pictures() {
for (left, right) in [
(42u64, 43u64),
(42, 1),
(42, 2),
(7, 8),
(0, u64::MAX),
(99, 12345),
] {
let differing = disagreement(
&painted(&seeded_after(left, 90).get_diff()),
&painted(&seeded_after(right, 90).get_diff()),
);
assert!(
differing > 0.4,
"seeds {left} and {right} are 90 frames into a run and their \
frames agree on {:.0}% of the cells they drew, so the seed is not \
reaching the motion",
(1.0 - differing) * 100.0
);
}
}
#[test]
fn the_same_seed_replays_the_same_run() {
let mut a = seeded(2024);
let mut b = seeded(2024);
for frame in 0..120u32 {
a.update();
b.update();
let left = painted(&a.get_diff());
let right = painted(&b.get_diff());
assert_eq!(
left, right,
"two cubes on seed 2024 differ on frame {frame}, so the motion \
is not a function of the seed"
);
}
}
#[test]
fn a_quarter_turn_away_is_very_much_the_same_picture() {
for axis in 0..3 {
let mut near = placed(1.0, (200, 50));
let mut far = placed(1.0, (200, 50));
let mut base = (0.0f32, 0.0f32, 0.0f32);
match axis {
0 => base.0 = 0.31,
1 => base.1 = 0.31,
_ => base.2 = 0.31,
}
let mut quarter = base;
match axis {
0 => quarter.0 += std::f32::consts::FRAC_PI_2,
1 => quarter.1 += std::f32::consts::FRAC_PI_2,
_ => quarter.2 += std::f32::consts::FRAC_PI_2,
}
let near_frame = painted(&frame(&mut near, base));
let far_frame = painted(&frame(&mut far, quarter));
assert_eq!(
near_frame.keys().collect::<HashSet<_>>(),
far_frame.keys().collect::<HashSet<_>>(),
"rotating 0.31 to 0.31 + pi/2 about axis {axis} moved the ink, so \
the picture is not pi/2-periodic about that axis"
);
for (key, cell) in &near_frame {
assert_eq!(
cell.color, far_frame[key].color,
"the cell at {key:?} changed colour across a quarter turn \
about axis {axis}"
);
}
}
}
#[test]
fn every_seeded_rate_stays_inside_the_band() {
const SEEDS: u64 = 200;
let mut phases: Vec<f32> = Vec::new();
for axis in 0..3 {
let configured =
[DEFAULT_SPEED_X, DEFAULT_SPEED_Y, DEFAULT_SPEED_Z][axis];
let low = configured * SPEED_BAND.0;
let high = configured * SPEED_BAND.1;
let mut seen_low = f32::INFINITY;
let mut seen_high = f32::NEG_INFINITY;
let mut seen_phase_low = f32::INFINITY;
let mut seen_phase_high = f32::NEG_INFINITY;
for seed in 0..SEEDS {
let motion = CubeOptions {
seed,
..Default::default()
}
.motion();
let rate =
[motion.speeds.0, motion.speeds.1, motion.speeds.2][axis];
assert!(
(low..=high).contains(&rate),
"seed {seed} gave axis {axis} a rate of {rate}, outside \
the band {low}..{high}"
);
seen_low = seen_low.min(rate);
seen_high = seen_high.max(rate);
let phase = [motion.phase.0, motion.phase.1, motion.phase.2][axis];
assert!(
(0.0..PHASE_SPAN).contains(&phase),
"seed {seed} gave axis {axis} a phase of {phase}, outside \
0..{PHASE_SPAN}"
);
seen_phase_low = seen_phase_low.min(phase);
seen_phase_high = seen_phase_high.max(phase);
}
let span = high - low;
assert!(
seen_low <= low + 0.03 * span,
"the slowest rate axis {axis} ever drew was {seen_low}, which is \
more than 3% of the band above its floor of {low}: the draw is \
not using the bottom of the range it was given"
);
assert!(
seen_high >= high - 0.03 * span,
"the quickest rate axis {axis} ever drew was {seen_high}, which \
is more than 3% of the band below its ceiling of {high}: the \
draw is not using the top of the range it was given"
);
assert!(
seen_phase_low <= 0.03 * PHASE_SPAN
&& seen_phase_high >= 0.97 * PHASE_SPAN,
"axis {axis} drew phases only in {:.3}..{:.3} of 0..{PHASE_SPAN}, \
so PHASE_SPAN is a wider range than the effect uses",
seen_phase_low,
seen_phase_high
);
phases.push(seen_phase_low);
}
assert_eq!(
phases.len(),
3,
"the phase check only ran {} times, so it proved nothing",
phases.len()
);
}
#[test]
fn a_zero_configured_rate_holds_its_axis() {
let options = CubeOptions {
rotation_speed_z: 0.0,
seed: 5,
..Default::default()
};
let motion = options.motion();
assert_eq!(
motion.speeds.2, 0.0,
"a configured rate of zero became {}, so the band is additive",
motion.speeds.2
);
let mut cube = Cube::new(options, (200, 50));
let mut poses: Vec<f32> = Vec::new();
for _ in 0..60 {
cube.update();
poses.push(cube.rotation.2);
}
let first = poses[0];
assert!(
poses.iter().all(|z| (z - first).abs() < 1e-6),
"the held axis precessed from {first} to {:?} over 60 frames",
poses.last().copied().unwrap_or(f32::NAN)
);
}
#[test]
fn a_rate_that_is_not_a_number_falls_back_rather_than_emptying_the_frame() {
for (axis, bad) in
["x", "y", "z"]
.iter()
.zip([f32::NAN, f32::INFINITY, f32::NEG_INFINITY])
{
let options = CubeOptions {
rotation_speed_x: if *axis == "x" { bad } else { DEFAULT_SPEED_X },
rotation_speed_y: if *axis == "y" { bad } else { DEFAULT_SPEED_Y },
rotation_speed_z: if *axis == "z" { bad } else { DEFAULT_SPEED_Z },
seed: 11,
..Default::default()
};
let motion = options.motion();
let drawn = [motion.speeds.0, motion.speeds.1, motion.speeds.2];
assert!(
drawn.iter().all(|r| r.is_finite()),
"rotation_speed_{axis} = {bad} left the launch with {drawn:?}"
);
let mut cube = Cube::new(options, (200, 50));
let diff = cube.get_diff();
assert!(
diff.len() > 150,
"rotation_speed_{axis} = {bad} drew {} cells, so the cube is \
not on the screen",
diff.len()
);
}
}
#[test]
fn the_rate_alone_changes_the_frame() {
let mut a = seeded(4242);
let mut b = seeded(4242);
a.motion.speeds = (0.18, 0.25, 0.12);
b.motion.speeds = (0.18, 0.63, 0.32);
for _ in 0..90 {
a.update();
b.update();
}
let differing =
disagreement(&painted(&a.get_diff()), &painted(&b.get_diff()));
assert!(
differing > 0.5,
"two runs from the same pose at 0.25 and 0.63 rad/s agree on \
{:.0}% of their cells after 90 frames, so the rate is not \
reaching the frame",
(1.0 - differing) * 100.0
);
}
#[test]
fn every_seeded_start_is_a_legitimate_cube() {
let mut gaps: Vec<f32> = Vec::new();
let mut opening: Option<HashMap<(usize, usize), Cell>> = None;
let mut closest = 1.0f32;
for seed in 0..40u64 {
let mut cube = seeded(seed);
let diff = cube.get_diff();
let projected: Vec<Point2D> = cube
.vertices
.iter()
.map(|v| cube.project_vertex(*v))
.collect();
let with_ink = EDGES
.iter()
.filter(|edge| {
edge_dots(&projected, edge, cube.screen_size)
.into_iter()
.any(|(x, y, _)| x >= 0 && y >= 0)
})
.count();
assert_eq!(
with_ink, 12,
"seed {seed} opens at {:?} with only {with_ink} of the twelve \
edges on the screen, so it is not a cube",
cube.rotation
);
let sides = edge_luminances(&cube, &diff);
let near: Vec<f32> = sides
.iter()
.filter(|(behind, _)| !*behind)
.map(|(_, l)| *l)
.collect();
let far: Vec<f32> = sides
.iter()
.filter(|(behind, _)| *behind)
.map(|(_, l)| *l)
.collect();
assert!(
(4..=9).contains(&near.len()) && (3..=8).contains(&far.len()),
"seed {seed} opens at {:?} and the measurement found {} near-side \
and {} far-side edges, which is not a cube seen from outside",
cube.rotation,
near.len(),
far.len()
);
let dimmest_near = near.iter().copied().fold(f32::INFINITY, f32::min);
let brightest_far =
far.iter().copied().fold(f32::NEG_INFINITY, f32::max);
gaps.push(dimmest_near - brightest_far);
assert!(
dimmest_near > brightest_far,
"seed {seed} opens at {:?} with the far side at {brightest_far:.1} \
against the near side's {dimmest_near:.1}, so the far side is \
not dimmer at all",
cube.rotation
);
let painted_frame = painted(&diff);
if let Some(first) = &opening {
closest = closest.min(disagreement(first, &painted_frame));
} else {
opening = Some(painted_frame);
}
}
let mut sorted = gaps.clone();
sorted.sort_by(f32::total_cmp);
let median = sorted[sorted.len() / 2];
assert!(
median > 60.0,
"the median far-side separation over the forty seeded openings is \
{median:.1} of 255, so at half of them the X-ray does not read"
);
assert!(
closest > 0.8,
"two of the forty seeded openings differ on only {:.0}% of \
their cells, so the starting poses are not varied",
closest * 100.0
);
}
#[test]
fn both_renderers_survive_every_size() {
for braille in [true, false] {
for (width, height) in [
(1u16, 1u16),
(2, 3),
(6, 6),
(12, 6),
(6, 12),
(80, 24),
(200, 50),
(400, 200),
] {
let options = CubeOptions {
use_braille: braille,
..Default::default()
};
let mut cube = Cube::new(options, (width, height));
for step in 0..24 {
let t = step as f32 * 0.13;
let diff = frame(&mut cube, (t, t * 1.7, t * 0.6));
for (x, y, _) in &diff {
assert!(
*x < width as usize && *y < height as usize,
"braille={braille} at {width}x{height} step {step} \
produced a cell at ({x}, {y})"
);
}
}
}
}
}
}