Our app can only draw rectangles. In this chapter, we add two tools: the circle and the line. We'll switch between them with the keyboard, R for the rectangle, C for the circle and L for the line. The functions to draw them have existed since chapter 3, we just need to hook them up.
The real question is elsewhere. Until now, we kept the rectangles in a Vec<Rect>. But a Vec only holds one type of element. How do you store rectangles, circles and lines in the same list? It's a chance to come back to enum, one of Rust's most useful tools.
The circle#
We draw a circle like in most drawing programs: you click at the center, then drag to the edge. The radius is the distance between the two points. Create src/shapes/circle.rs:
use crate::canvas::Canvas;
use crate::vec2::Vec2;
#[derive(Clone, Copy, Debug)]
pub struct Circle {
pub center: Vec2,
pub radius: f32,
pub color: u32,
}
impl Circle {
/// Builds the circle centered on `center` that goes through `edge`.
pub fn from_points(center: Vec2, edge: Vec2, color: u32) -> Circle {
Circle {
center,
radius: (edge - center).length(),
color,
}
}
pub fn draw(&self, canvas: &mut Canvas) {
canvas.fill_circle(
self.center.x as usize,
self.center.y as usize,
self.radius as usize,
self.color,
);
}
}edge - center is the vector going from the center to the edge, and .length() is its length. That's the subtraction and the length we wrote in chapter 1: Vec2 is starting to pay off.
The line#
A line is even simpler: the point where you started dragging and the one where you let go.
Solution
use crate::canvas::Canvas;
use crate::vec2::Vec2;
#[derive(Clone, Copy, Debug)]
pub struct Line {
pub start: Vec2,
pub end: Vec2,
pub color: u32,
}
impl Line {
pub fn from_points(start: Vec2, end: Vec2, color: u32) -> Line {
Line { start, end, color }
}
pub fn draw(&self, canvas: &mut Canvas) {
canvas.draw_line(
self.start.x as i32,
self.start.y as i32,
self.end.x as i32,
self.end.y as i32,
self.color,
);
}
}Since the parameters of from_points have the same names as the fields, Line { start, end, color } is enough.
fill_circle and draw_line are used again: remove the two #[allow(dead_code)] we put above them in src/canvas.rs in the previous chapter.
A list that holds several types#
We now have three structs: Rect, Circle and Line. We need a type that can be any one of them, to store them in the same Vec. That's exactly what an enum is: a type that takes one value out of several variants.
In chapter 5, the Drawing { start } variant held a named field. Here, each variant will hold a whole struct. Replace the contents of src/shapes/mod.rs:
mod circle;
mod line;
mod rect;
pub use circle::Circle;
pub use line::Line;
pub use rect::Rect;
use crate::canvas::Canvas;
use crate::vec2::Vec2;
/// The drawing tool currently selected.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Tool {
Rect,
Circle,
Line,
}
/// A shape of the drawing.
#[derive(Clone, Copy, Debug)]
pub enum Shape {
Rect(Rect),
Circle(Circle),
Line(Line),
}Shape::Rect(Rect) reads: the Rect variant of Shape, which holds a Rect struct. The same name refers to two different things, the variant and the struct, but Rust doesn't mix them up, since the variant is always written Shape::Rect. A Vec<Shape> can now hold rectangles, circles and lines all mixed together.
We also have a second enum, Tool, for the selected tool. Its variants hold nothing. Why not reuse Shape? Because a tool isn't a shape: choosing the circle tool doesn't mean there's already a circle with a center and a radius. Tool says what we're going to draw, Shape describes what has been drawn.
There are two methods left to write on Shape. The first builds a shape from a tool and a mouse drag:
impl Shape {
/// Builds the shape drawn with `tool` by dragging the mouse from `a` to `b`.
pub fn from_points(tool: Tool, a: Vec2, b: Vec2, color: u32) -> Shape {
match tool {
Tool::Rect => Shape::Rect(Rect::from_points(a, b, color)),
Tool::Circle => Shape::Circle(Circle::from_points(a, b, color)),
Tool::Line => Shape::Line(Line::from_points(a, b, color)),
}
}
}The match looks at the tool, and for each case, builds the right struct and wraps it in the right variant. Each arm returns a Shape, and since the match is the last expression of the function, it's its return value.
The second draws a shape, whatever it is. This time, we match on the shape itself, and each arm takes the struct out of its variant to call its draw method. Here's the beginning:
pub fn draw(&self, canvas: &mut Canvas) {
match self {
Shape::Rect(r) => r.draw(canvas),
// ...
}
}Shape::Rect(r) checks that the shape is a rectangle and, if so, gives the name r to the Rect struct it holds. Since we match on &self, a reference, r is a reference to the rectangle too: nothing is copied.
Solution
pub fn draw(&self, canvas: &mut Canvas) {
match self {
Shape::Rect(r) => r.draw(canvas),
Shape::Circle(c) => c.draw(canvas),
Shape::Line(l) => l.draw(canvas),
}
}The three pub use lines at the top make Circle, Line and Rect available as shapes::Circle, shapes::Line and shapes::Rect. That way, the rest of the program can use the shapes without knowing which file they live in.
Choosing the tool with the keyboard#
In src/app.rs, the app no longer has a list of rectangles but a list of shapes, plus the selected tool. Change the struct's fields, and their starting value in new:
pub struct App {
canvas: Canvas,
shapes: Vec<Shape>,
tool: Tool,
// ...
}App {
canvas: Canvas::new(width, height),
shapes: Vec::new(),
tool: Tool::Rect,
// ...
}To choose the tool, we add a method that reads the keyboard:
fn handle_keys(&mut self, window: &Window) {
let pressed = |key| window.is_key_pressed(key, KeyRepeat::No);
if pressed(Key::R) {
self.tool = Tool::Rect;
}
if pressed(Key::C) {
self.tool = Tool::Circle;
}
if pressed(Key::L) {
self.tool = Tool::Line;
}
}The first line creates a closure: a small nameless function, stored in the variable pressed. Between the vertical bars are its parameters, here key. After that, its body. It has one feature an ordinary function doesn't have: it can use the variables from the place where it was created, here window. Without it, we'd have to repeat window.is_key_pressed(..., KeyRepeat::No) for every test.
The type of key isn't written anywhere. Rust figures it out from how it's used: since key is passed to is_key_pressed, it has to be a Key.
We call handle_keys at the beginning of update, right after reading the mouse:
let down = window.get_mouse_down(MouseButton::Left);
self.handle_keys(window);All that's left is to replace Rect with Shape in on_release and in the preview in render, passing the current tool to Shape::from_points. Nothing else changes: detecting the press and release, the gray preview, everything works the same whatever the shape. Here's the full src/app.rs:
use minifb::{Key, KeyRepeat, MouseButton, MouseMode, Window};
use crate::action::Action;
use crate::canvas::Canvas;
use crate::color::{GRAY, WHITE, rgb_to_u32};
use crate::shapes::{Shape, Tool};
use crate::vec2::Vec2;
/// All the state of the application.
pub struct App {
canvas: Canvas,
shapes: Vec<Shape>,
tool: Tool,
action: Action,
color: u32,
mouse: Vec2,
was_down: bool,
}
impl App {
pub fn new(width: usize, height: usize) -> App {
App {
canvas: Canvas::new(width, height),
shapes: Vec::new(),
tool: Tool::Rect,
action: Action::Idle,
color: rgb_to_u32(50, 120, 220),
mouse: Vec2::ZERO,
was_down: false,
}
}
pub fn canvas(&self) -> &Canvas {
&self.canvas
}
/// Reads the keyboard and mouse, and updates the state.
pub fn update(&mut self, window: &Window) {
self.mouse = window
.get_mouse_pos(MouseMode::Clamp)
.map(Vec2::from)
.unwrap_or(Vec2::ZERO);
let down = window.get_mouse_down(MouseButton::Left);
self.handle_keys(window);
// Compare with the previous frame to detect press and release.
if down && !self.was_down {
self.on_press(self.mouse);
}
if !down && self.was_down {
self.on_release(self.mouse);
}
self.was_down = down;
}
fn handle_keys(&mut self, window: &Window) {
let pressed = |key| window.is_key_pressed(key, KeyRepeat::No);
if pressed(Key::R) {
self.tool = Tool::Rect;
}
if pressed(Key::C) {
self.tool = Tool::Circle;
}
if pressed(Key::L) {
self.tool = Tool::Line;
}
}
/// The mouse button was just pressed: start drawing.
fn on_press(&mut self, p: Vec2) {
self.action = Action::Drawing { start: p };
}
/// The mouse button was just released.
fn on_release(&mut self, p: Vec2) {
if let Action::Drawing { start } = self.action
&& start != p
{
let shape = Shape::from_points(self.tool, start, p, self.color);
self.shapes.push(shape);
}
self.action = Action::Idle;
}
/// Redraws everything on the canvas.
pub fn render(&mut self) {
self.canvas.clear(WHITE);
for shape in &self.shapes {
shape.draw(&mut self.canvas);
}
// Preview of the shape being drawn.
if let Action::Drawing { start } = self.action {
Shape::from_points(self.tool, start, self.mouse, GRAY).draw(&mut self.canvas);
}
}
}main.rs doesn't change.
cargo runDraw a rectangle, then press C and draw a circle starting from its center, then press L and draw a line. The gray preview takes the shape of the current tool. Shapes stack up in the order you draw them: the last one is drawn on top of the others.
Exercises#
-
Add an I shortcut that prints in the terminal how many shapes of each type there are. Hint: the
matches!(value, pattern)macro returnstrueif the value matches the pattern, for examplematches!(shape, Shape::Circle(_)). The_means "anything". -
Add a square tool, on the Q key. A square is a
Rectwhose two sides have the same length: take the larger of the two distances of the drag. You need a new variant inTool, but not inShape, since a square is a rectangle. -
Bonus: add a new shape, the ellipse (a stretched circle), on the E key. You draw it like a rectangle, by dragging from one corner to the other, and it fills that rectangle. Start by adding the
Shape::Ellipsevariant, and let the compiler guide you to every place that needs completing. For the drawing, take inspiration fromfill_circle: a pixel is inside the ellipse if(dx / rx)² + (dy / ry)² ≤ 1, whererxis half the width andryhalf the height.
Solutions
1. In handle_keys. iter() goes through the shapes, filter keeps only those that match, and count counts them:
if pressed(Key::I) {
let rects = self.shapes.iter().filter(|s| matches!(s, Shape::Rect(_))).count();
let circles = self.shapes.iter().filter(|s| matches!(s, Shape::Circle(_))).count();
let lines = self.shapes.iter().filter(|s| matches!(s, Shape::Line(_))).count();
println!("{rects} rectangles, {circles} circles, {lines} lines");
}filter takes a closure that says, for each element, whether to keep it. A version with a plain for loop and three counters works just as well.
2. One more variant in Tool, one more key in handle_keys, and one more arm in Shape::from_points:
Tool::Square => {
let side = (b.x - a.x).abs().max((b.y - a.y).abs());
let x = if b.x < a.x { a.x - side } else { a.x };
let y = if b.y < a.y { a.y - side } else { a.y };
Shape::Rect(Rect::new(x, y, side, side, color))
}The square starts from the starting point and extends toward the side the mouse is going. Since we return a Shape::Rect, draw doesn't need to know anything more. The compiler will have pointed out the match in from_points, but not the one in draw, which works on Shape and not on Tool.
3. The drawing, in src/canvas.rs. It's the same loop as fill_circle, with the ellipse formula. We convert to f32 so the divisions keep their decimals:
pub fn fill_ellipse(&mut self, cx: usize, cy: usize, rx: usize, ry: usize, color: u32) {
let (rx, ry) = (rx as i32, ry as i32);
for dy in -ry..=ry {
for dx in -rx..=rx {
let x = dx as f32 / rx as f32;
let y = dy as f32 / ry as f32;
if x * x + y * y <= 1.0 {
self.put_pixel(cx as i32 + dx, cy as i32 + dy, color);
}
}
}
}The shape, in a new file src/shapes/ellipse.rs to declare in mod.rs. We reuse Rect::from_points to get the rectangle of the drag: the center of the ellipse is in the middle, and its radii are half the width and half the height:
use crate::canvas::Canvas;
use crate::shapes::Rect;
use crate::vec2::Vec2;
#[derive(Clone, Copy, Debug)]
pub struct Ellipse {
pub center: Vec2,
pub radii: Vec2,
pub color: u32,
}
impl Ellipse {
pub fn from_points(a: Vec2, b: Vec2, color: u32) -> Ellipse {
let bounds = Rect::from_points(a, b, color);
let radii = bounds.size * 0.5;
Ellipse {
center: bounds.pos + radii,
radii,
color,
}
}
pub fn draw(&self, canvas: &mut Canvas) {
canvas.fill_ellipse(
self.center.x as usize,
self.center.y as usize,
self.radii.x as usize,
self.radii.y as usize,
self.color,
);
}
}Then Tool::Ellipse, Shape::Ellipse(Ellipse), the E key, and an arm in each match the compiler points out.
Recap#
- An
enumcan have variants that hold other types, likeShape::Circle(Circle). That's what lets us store different shapes in the sameVec<Shape>. - A
matchhas to cover every variant. When you add one, the compiler lists every place that needs completing. - In a
match, a pattern likeShape::Rect(r)checks the variant and gives a name to what it holds. pub usemakes an item from a submodule available from the parent module.- A closure is a nameless function that can use the variables around it:
|key| window.is_key_pressed(key, KeyRepeat::No).
In chapter 7, we'll be able to click on a shape we've already drawn to select it, move it or delete it. And we'll finally take on the borrow checker for real.