Skip to content

Commit a0b9c59

Browse files
authored
Merge pull request #97 from rust-windowing/example-optimize
examples: Avoid dividing index to get x, y; calculate index from x, y
2 parents 6da649e + edc5c76 commit a0b9c59

File tree

3 files changed

+24
-23
lines changed

3 files changed

+24
-23
lines changed

examples/animation.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,10 +78,11 @@ fn pre_render_frames(width: usize, height: usize) -> Vec<Vec<u32>> {
7878
let render = |frame_id| {
7979
let elapsed = ((frame_id as f64) / (60.0)) * 2.0 * PI;
8080

81-
(0..(width * height))
82-
.map(|index| {
83-
let y = ((index / width) as f64) / (height as f64);
84-
let x = ((index % width) as f64) / (width as f64);
81+
let coords = (0..height).flat_map(|x| (0..width).map(move |y| (x, y)));
82+
coords
83+
.map(|(x, y)| {
84+
let y = (y as f64) / (height as f64);
85+
let x = (x as f64) / (width as f64);
8586
let red =
8687
((((y + elapsed).sin() * 0.5 + 0.5) * 255.0).round() as u32).clamp(0, 255);
8788
let green =

examples/rectangle.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,17 @@ use winit::event_loop::{ControlFlow, EventLoop};
44
use winit::window::WindowBuilder;
55

66
fn redraw(buffer: &mut [u32], width: usize, height: usize, flag: bool) {
7-
for (index, color) in buffer.iter_mut().enumerate() {
8-
let y = index / width;
9-
let x = index % width;
10-
11-
if flag && x >= 100 && x < width - 100 && y >= 100 && y < height - 100 {
12-
*color = 0x00ffffff;
13-
} else {
14-
let red = (x & 0xff) ^ (y & 0xff);
15-
let green = (x & 0x7f) ^ (y & 0x7f);
16-
let blue = (x & 0x3f) ^ (y & 0x3f);
17-
*color = (blue | (green << 8) | (red << 16)) as u32;
7+
for y in 0..height {
8+
for x in 0..width {
9+
let value = if flag && x >= 100 && x < width - 100 && y >= 100 && y < height - 100 {
10+
0x00ffffff
11+
} else {
12+
let red = (x & 0xff) ^ (y & 0xff);
13+
let green = (x & 0x7f) ^ (y & 0x7f);
14+
let blue = (x & 0x3f) ^ (y & 0x3f);
15+
(blue | (green << 8) | (red << 16)) as u32
16+
};
17+
buffer[y * width + x] = value;
1818
}
1919
}
2020
}

examples/winit.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,14 @@ fn main() {
4242
.unwrap();
4343

4444
let mut buffer = surface.buffer_mut().unwrap();
45-
for index in 0..(width * height) {
46-
let y = index / width;
47-
let x = index % width;
48-
let red = x % 255;
49-
let green = y % 255;
50-
let blue = (x * y) % 255;
51-
52-
buffer[index as usize] = blue | (green << 8) | (red << 16);
45+
for y in 0..height {
46+
for x in 0..width {
47+
let red = x % 255;
48+
let green = y % 255;
49+
let blue = (x * y) % 255;
50+
let index = y as usize * width as usize + x as usize;
51+
buffer[index] = blue | (green << 8) | (red << 16);
52+
}
5353
}
5454

5555
buffer.present().unwrap();

0 commit comments

Comments
 (0)