From 0d2d5548aef7d63ffbc53a8f30f1900df4dd954f Mon Sep 17 00:00:00 2001 From: Kristofers Solo Date: Tue, 30 Aug 2022 21:44:14 +0300 Subject: [PATCH] Fix flickering --- src/main.rs | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/main.rs b/src/main.rs index a235030..c51587d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,11 +5,11 @@ fn main() { let mut a: f32 = 0.0; let mut b: f32 = 0.0; - print!("\x1B[2J"); // clears screen + print!("\x1b[2J"); // clears screen loop { - let mut z: [f32; SCREEN_SIZE] = [0.0; SCREEN_SIZE]; - let mut screen: [char; SCREEN_SIZE] = [' '; SCREEN_SIZE]; + let mut zbuffer: [f32; SCREEN_SIZE] = [0.0; SCREEN_SIZE]; + let mut output: [char; SCREEN_SIZE] = [' '; SCREEN_SIZE]; for j in (0..=628).step_by(7) { let j: f32 = 0.01 * j as f32; @@ -28,16 +28,19 @@ fn main() { let cos_j: f32 = j.cos(); let cos_j2: f32 = cos_j + 2.0; - let mess: f32 = 1.0 / (sin_i * cos_j2 * sin_a + sin_j * cos_a + 5.0); + + let z: f32 = sin_i * cos_j2 * sin_a + sin_j * cos_a + 5.0; + let ooz: f32 = 1.0 / z; // one over z + let t: f32 = sin_i * cos_j2 * cos_a - sin_j * sin_a; // 40 is the left screen shift - let x: i32 = (40.0 + 30.0 * mess * (cos_i * cos_j2 * cos_b - t * sin_b)) as i32; + let x: i32 = (40.0 + 30.0 * ooz * (cos_i * cos_j2 * cos_b - t * sin_b)) as i32; // 12 is the bottom screen shift - let y: i32 = (12.0 + 15.0 * mess * (cos_i * cos_j2 * sin_b + t * cos_b)) as i32; + let y: i32 = (12.0 + 15.0 * ooz * (cos_i * cos_j2 * sin_b + t * cos_b)) as i32; let o: usize = (x + WIDTH * y) as usize; // multiplying by 8 to bring in range 0-11 as 8*(sqrt(2))=11 // because we have 11 luminance characters - let n: i32 = (8.0 + let luminance_index: i32 = (8.0 * ((sin_j * sin_a - sin_i * cos_j * cos_a) * cos_b - sin_i * cos_j * sin_a - sin_j * cos_a @@ -50,25 +53,25 @@ fn main() { // i.e. when z[o] is 0 or the prev point is behind the new point // so we change it to the point nearer to the eye/ above prev point - if 0 < y && y < HEIGHT && 0 < x && x < WIDTH && mess > z[o] { - z[o] = mess; - if n > 0 { - let m: usize = n as usize; - screen[o] = ".,-~:;=!*#$Q".chars().nth(m).unwrap(); + if 0 < y && y < HEIGHT && 0 < x && x < WIDTH && ooz > zbuffer[o] { + zbuffer[o] = ooz; + if luminance_index > 0 { + let m: usize = luminance_index as usize; + output[o] = ".,-~:;=!*#$@".chars().nth(m).unwrap(); } else { - screen[o] = '.'; + output[o] = '.'; } } } } // print - print!("\x1B[2J"); - for index in 0..screen.len() { + print!("\x1b[H"); + for index in 0..output.len() { let i: i32 = index as i32; if i % WIDTH == 0 { println!(); } else { - print!("{}", screen[index]); + print!("{}", output[index]); } }