Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Color Utility Functions

Using our new vec3 class, we'll create a new color.h header file and define a utility function that writes a single pixel's color out to the standard output stream.

use crate::vec3::Vec3;

pub type Color = Vec3;

pub fn write_color(mut out: impl std::io::Write, pixel_color: Color) -> std::io::Result<()> {
    let r = pixel_color.x();
    let g = pixel_color.y();
    let b = pixel_color.z();

    let rbyte = (255.999 * r) as i32;
    let gbyte = (255.999 * g) as i32;
    let bbyte = (255.999 * b) as i32;

    writeln!(out, "{rbyte} {gbyte} {bbyte}")
}

Listing 5: [color.rs] color utility functions


Now we can change our main to use both of these:

diff --git a/src/main.rs b/src/main.rs
index 00cad27..bb37ee6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,29 +1,30 @@
-fn main() {
+use code::color::{Color, write_color};
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
     // Image
 
     const IMAGE_WIDTH: u32 = 256;
     const IMAGE_HEIGHT: u32 = 256;
 
     // Render
 
     env_logger::init();
     println!("P3");
     println!("{IMAGE_WIDTH} {IMAGE_HEIGHT}");
     println!("255");
 
     for j in 0..IMAGE_HEIGHT {
         log::info!("Scanlines remaining: {}", IMAGE_HEIGHT - j);
         for i in 0..IMAGE_WIDTH {
-            let r = i as f64 / (IMAGE_WIDTH - 1) as f64;
-            let g = j as f64 / (IMAGE_HEIGHT - 1) as f64;
-            let b = 0.0;
-
-            let ir = (255.999 * r) as i32;
-            let ig = (255.999 * g) as i32;
-            let ib = (255.999 * b) as i32;
-
-            println!("{ir} {ig} {ib}");
+            let pixel_color = Color::new(
+                i as f64 / (IMAGE_WIDTH - 1) as f64,
+                j as f64 / (IMAGE_HEIGHT - 1) as f64,
+                0.0,
+            );
+            write_color(std::io::stdout(), pixel_color)?;
         }
     }
     log::info!("Done.");
+
+    Ok(())
 }

Listing 6: [main.rs)] Final code for the first PPM image


And you should get the exact same picture as before.