examples: Avoid dividing index to get x, y; calculate index from x, y

Division is more expensive than multiplication, and this doesn't seem to
be optimize away, so iterating over `(0..height)` and `(0..width)`
provides better performance.

It's good to have the example show the best way to write code using
softbuffer, and this helps when using examples as a benchmark. This will
also be needed if Softbuffer supports formats where `stride` isn't just
`width * pixel_size`, and needs alignment.
This commit is contained in:
Ian Douglas Scott 2023-04-11 12:20:48 -07:00
parent 6da649e8a1
commit edc5c76180
3 changed files with 24 additions and 23 deletions

View file

@ -78,10 +78,11 @@ fn pre_render_frames(width: usize, height: usize) -> Vec<Vec<u32>> {
let render = |frame_id| {
let elapsed = ((frame_id as f64) / (60.0)) * 2.0 * PI;
(0..(width * height))
.map(|index| {
let y = ((index / width) as f64) / (height as f64);
let x = ((index % width) as f64) / (width as f64);
let coords = (0..height).flat_map(|x| (0..width).map(move |y| (x, y)));
coords
.map(|(x, y)| {
let y = (y as f64) / (height as f64);
let x = (x as f64) / (width as f64);
let red =
((((y + elapsed).sin() * 0.5 + 0.5) * 255.0).round() as u32).clamp(0, 255);
let green =

View file

@ -4,17 +4,17 @@ use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;
fn redraw(buffer: &mut [u32], width: usize, height: usize, flag: bool) {
for (index, color) in buffer.iter_mut().enumerate() {
let y = index / width;
let x = index % width;
if flag && x >= 100 && x < width - 100 && y >= 100 && y < height - 100 {
*color = 0x00ffffff;
} else {
let red = (x & 0xff) ^ (y & 0xff);
let green = (x & 0x7f) ^ (y & 0x7f);
let blue = (x & 0x3f) ^ (y & 0x3f);
*color = (blue | (green << 8) | (red << 16)) as u32;
for y in 0..height {
for x in 0..width {
let value = if flag && x >= 100 && x < width - 100 && y >= 100 && y < height - 100 {
0x00ffffff
} else {
let red = (x & 0xff) ^ (y & 0xff);
let green = (x & 0x7f) ^ (y & 0x7f);
let blue = (x & 0x3f) ^ (y & 0x3f);
(blue | (green << 8) | (red << 16)) as u32
};
buffer[y * width + x] = value;
}
}
}

View file

@ -42,14 +42,14 @@ fn main() {
.unwrap();
let mut buffer = surface.buffer_mut().unwrap();
for index in 0..(width * height) {
let y = index / width;
let x = index % width;
let red = x % 255;
let green = y % 255;
let blue = (x * y) % 255;
buffer[index as usize] = blue | (green << 8) | (red << 16);
for y in 0..height {
for x in 0..width {
let red = x % 255;
let green = y % 255;
let blue = (x * y) % 255;
let index = y as usize * width as usize + x as usize;
buffer[index] = blue | (green << 8) | (red << 16);
}
}
buffer.present().unwrap();