1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use image::{self, GenericImage};
use glium::{self, Surface};
use glium_text;
use na;
use std::io;
use super::floodfill as ff;
#[derive(Copy, Clone)]
struct Point {
coords: [f32; 2],
color: [f32; 4],
}
implement_vertex!(Point, coords, color);
#[derive(Copy, Clone)]
struct FerrisPoint {
coords: [f32; 2],
tex_coords: [f32; 2],
}
implement_vertex!(FerrisPoint, coords, tex_coords);
const VERTEX_SHADER: &'static str = include_str!("shaders/vertex.glsl");
const FRAGMENT_SHADER: &'static str = include_str!("shaders/fragment.glsl");
const FERRIS_BYTES: &'static [u8] = include_bytes!("ferris.png");
const FERRIS_VERTEX: &'static str = include_str!("shaders/ferris_vertex.glsl");
const FERRIS_FRAGMENT: &'static str = include_str!("shaders/ferris_fragment.glsl");
const PATCH_VERTEX: &'static str = include_str!("shaders/patch_vertex.glsl");
const PATCH_FRAGMENT: &'static str = include_str!("shaders/patch_fragment.glsl");
const FONT_DATA: &'static [u8] = include_bytes!("dejavusansmono.ttf");
type ScaleMatrix = [[f32; 4]; 4];
pub mod color {
pub type Color = (f32, f32, f32, f32);
pub const BLACK: Color = (0.0, 0.0, 0.0, 1.0);
pub const WHITE: Color = (1.0, 1.0, 1.0, 1.0);
pub const RED: Color = (1.0, 0.0, 0.0, 1.0);
pub const GREEN: Color = (0.0, 1.0, 0.0, 1.0);
pub const BLUE: Color = (0.0, 0.0, 1.0, 1.0);
#[inline]
pub fn to_array(color: Color) -> [f32; 4] {
[color.0, color.1, color.2, color.3]
}
}
struct Line(f32, f32, f32, f32, color::Color);
struct Text(f32, f32, f32, color::Color, String);
struct Fill(f32, f32, glium::texture::Texture2d);
enum Shape {
Line(Line),
Text(Text),
Fill(Fill),
}
pub struct TurtleScreen {
window: glium::backend::glutin_backend::GlutinFacade,
program: glium::Program,
shapes: Vec<Shape>,
_is_closed: bool,
ferris: glium::texture::Texture2d,
ferris_program: glium::Program,
patch_program: glium::Program,
text_system: glium_text::TextSystem,
font: glium_text::FontTexture,
pub turtle_position: (f32, f32),
pub turtle_color: color::Color,
pub turtle_orientation: f32,
pub turtle_hidden: bool,
pub background_color: color::Color,
}
impl TurtleScreen {
pub fn new(size: (u32, u32), title: &str) -> TurtleScreen {
use glium::DisplayBuild;
let builder = glium::glutin::WindowBuilder::new()
.with_title(title.to_string())
.with_dimensions(size.0, size.1)
.build_glium();
let window = match builder {
Err(error) => panic!("Window creation failed: {}", error),
Ok(win) => win,
};
let program_builder = glium::Program::from_source(
&window, VERTEX_SHADER, FRAGMENT_SHADER, None);
let program = match program_builder {
Err(error) => panic!("Program creation failed: {}", error),
Ok(prg) => prg,
};
let ferris_image = image::load(io::Cursor::new(FERRIS_BYTES),
image::ImageFormat::PNG).unwrap();
let ferris_texture = glium::texture::Texture2d::new(&window, ferris_image);
let ferris_program = glium::Program::from_source(&window, FERRIS_VERTEX,
FERRIS_FRAGMENT, None) .unwrap();
let patch_program = glium::Program::from_source(&window, PATCH_VERTEX,
PATCH_FRAGMENT, None).unwrap();
let text_system = glium_text::TextSystem::new(&window);
let font = glium_text::FontTexture::new(&window,
io::Cursor::new(FONT_DATA), 24).unwrap();
TurtleScreen {
window: window,
program: program,
shapes: Vec::new(),
_is_closed: false,
ferris: ferris_texture,
ferris_program: ferris_program,
patch_program: patch_program,
text_system: text_system,
font: font,
turtle_position: (0.0, 0.0),
turtle_color: color::BLACK,
turtle_orientation: 0.0,
turtle_hidden: false,
background_color: color::WHITE,
}
}
pub fn add_line(&mut self, start: (f32, f32), end: (f32, f32), color: color::Color) {
self.shapes.push(Shape::Line(Line(start.0, start.1, end.0, end.1, color)));
}
pub fn add_text(&mut self, anchor: (f32, f32), angle: f32, color: color::Color, text: &str) {
self.shapes.push(Shape::Text(Text(anchor.0, anchor.1, angle, color, text.to_string())));
}
pub fn floodfill(&mut self, point: (f32, f32), color: color::Color) {
let original_state = self.turtle_hidden;
self.turtle_hidden = true;
self.draw_and_update();
let image = self.screenshot();
self.turtle_hidden = original_state;
self.draw_and_update();
let (width, height) = image.dimensions();
let (adj_x, adj_y) = ((width as f32 / 2. + point.0) as u32,
(height as f32 / 2. - point.1) as u32);
let translated_color = {
let (r, g, b, a) = color;
const MAX: f32 = ::std::u8::MAX as f32;
((MAX * r) as u8, (MAX * g) as u8, (MAX * b) as u8, (MAX * a) as u8)
};
let (px, py, patch) = ff::floodfill(&image, (adj_x, adj_y), translated_color);
let (trans_x, trans_y) = (px as f32 - width as f32 / 2.,
height as f32 / 2. - py as f32);
self.shapes.push(Shape::Fill(
Fill(trans_x, trans_y,
glium::texture::Texture2d::new(&self.window, patch))));
}
pub fn clear(&mut self) {
self.shapes.clear();
}
pub fn draw_and_update(&self) {
let mut frame = self.window.draw();
{
let (br, bg, bb, ba) = self.background_color;
frame.clear_color(br, bg, bb, ba);
}
let (width, height) = frame.get_dimensions();
let matrix = [
[2.0 / width as f32, 0.0, 0.0, 0.0],
[0.0, 2.0 / height as f32, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
for shape in &self.shapes {
match *shape {
Shape::Line(ref l) => self.draw_line(&mut frame, l, matrix),
Shape::Text(ref t) => self.draw_text(&mut frame, t),
Shape::Fill(ref f) => self.draw_fill(&mut frame, f, matrix),
}
}
if !self.turtle_hidden {
self.draw_turtle(&mut frame, matrix);
}
frame.finish().unwrap();
}
fn draw_fill(&self, frame: &mut glium::Frame, fill: &Fill, matrix: ScaleMatrix) {
let Fill(x, y, ref texture) = *fill;
let (width, height) = (texture.get_width() as f32,
texture.get_height().unwrap() as f32);
let vertex_buffer = glium::VertexBuffer::new(
&self.window,
vec![
FerrisPoint { coords: [x, y - height], tex_coords: [0., 0.] },
FerrisPoint { coords: [x + width, y - height], tex_coords: [1., 0.] },
FerrisPoint { coords: [x + width, y], tex_coords: [1., 1.] },
FerrisPoint { coords: [x, y], tex_coords: [0., 1.] },
]);
let indices = glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan);
let uniforms = uniform! {
matrix: matrix,
texture_data: texture,
};
frame.draw(&vertex_buffer, &indices, &self.patch_program, &uniforms, &Default::default())
.unwrap();
}
fn draw_line(&self, frame: &mut glium::Frame, line: &Line, matrix: ScaleMatrix) {
use std::default::Default;
use self::color::to_array;
let mut points: Vec<Point> = Vec::new();
let Line(x1, y1, x2, y2, color) = *line;
points.push(Point { coords: [x1, y1], color: to_array(color) });
points.push(Point { coords: [x2, y2], color: to_array(color) });
let vertex_buffer = glium::VertexBuffer::new(&self.window, &points);
let indices = glium::index::NoIndices(glium::index::PrimitiveType::LinesList);
let uniforms = uniform! { matrix: matrix };
frame.draw(&vertex_buffer, &indices, &self.program, &uniforms, &Default::default())
.unwrap();
}
fn draw_text(&self, frame: &mut glium::Frame, text: &Text) {
const FONT_SIZE: f32 = 12.;
let Text(pos_x, pos_y, angle_deg, text_color, ref data) = *text;
let angle = ::std::f32::consts::PI * angle_deg / 180.;
let sin_d = angle.sin();
let cos_d = angle.cos();
let text = glium_text::TextDisplay::new(&self.text_system, &self.font, data);
let (width, height) = frame.get_dimensions();
let rotation_matrix = na::Mat4::new(
cos_d, -sin_d, 0., 0.,
sin_d, cos_d, 0., 0.,
0., 0., 1., 0.,
0., 0., 0., 1.);
let scale_matrix = na::Mat4::new(
2. * FONT_SIZE / width as f32, 0., 0., 0.,
0., 2. * FONT_SIZE / height as f32, 0., 0.,
0., 0., 1., 0.,
0., 0., 0., 1.);
let translate_matrix = na::Mat4::new(
1., 0., 0., pos_x * 2. / width as f32,
0., 1., 0., pos_y * 2. / height as f32,
0., 0., 1., 0.,
0., 0., 0., 1.);
glium_text::draw(&text, &self.text_system, frame,
*(translate_matrix * scale_matrix * rotation_matrix).as_array(),
text_color);
}
fn draw_turtle(&self, frame: &mut glium::Frame, matrix: ScaleMatrix) {
const WIDTH: f32 = 36.;
const HEIGHT: f32 = 24.;
const DX: f32 = WIDTH / 2.;
const DY: f32 = HEIGHT / 2.;
let (tx, ty) = self.turtle_position;
let orientation_rad = ::std::f32::consts::PI * self.turtle_orientation / 180.0;
let sin_d = orientation_rad.sin();
let cos_d = orientation_rad.cos();
let rotation_matrix = [
[cos_d, sin_d, 0., 0.],
[-sin_d, cos_d, 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.],
];
let vertex_buffer = glium::VertexBuffer::new(
&self.window,
vec![
FerrisPoint { coords: [tx - DX, ty - DY], tex_coords: [0., 0.] },
FerrisPoint { coords: [tx + DX, ty - DY], tex_coords: [1., 0.] },
FerrisPoint { coords: [tx + DX, ty + DY], tex_coords: [1., 1.] },
FerrisPoint { coords: [tx - DX, ty + DY], tex_coords: [0., 1.] },
]);
let indices = glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan);
let uniforms = uniform! {
matrix: matrix,
rotation_matrix: rotation_matrix,
ferris_tex: &self.ferris,
tip_x: tx,
tip_y: ty,
};
frame.draw(&vertex_buffer, &indices, &self.ferris_program, &uniforms, &Default::default())
.unwrap();
}
pub fn handle_events(&mut self) {
use glium::glutin::Event;
for event in self.window.poll_events() {
match event {
Event::Closed => {
self._is_closed = true;
self.window.get_window().unwrap().hide();
},
_ => (),
}
}
}
pub fn is_closed(&self) -> bool {
self._is_closed
}
pub fn screenshot(&self) -> image::DynamicImage {
self.window.read_front_buffer()
}
}