Skip to content

Instantly share code, notes, and snippets.

@malleusinferni
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malleusinferni/4f2fc4838a9d82f785a0 to your computer and use it in GitHub Desktop.
Save malleusinferni/4f2fc4838a9d82f785a0 to your computer and use it in GitHub Desktop.
Rust idiom help
fn generate(format: PixelFormat) -> Vec<Tex> {
// Helper functions for wrangling colors
fn gray(val: u8) -> Color { RGB(val, val, val) }
fn red(val: u8, other: u8) -> Color { RGB(val, other, other) }
fn green(val: u8, other: u8) -> Color { RGB(other, val, other) }
fn blue(val: u8, other: u8) -> Color { RGB(other, other, val) }
fn scale_to_dim(val: int) -> u8 {
mix(0.0, 255.0, val as f64 / 64.0) as u8
}
fn xor_shade(x: int, y: int) -> u8 {
scale_to_dim(x) ^ scale_to_dim(y)
}
fn gradient_shade(x: int, y: int) -> u8 {
((scale_to_dim(x) as f64 + scale_to_dim(y) as f64) / 2.0) as u8
}
let generators: Vec<|int, int| -> Color> = vec![
|x, y| { // Red stars
let v = xor_shade(x, y);
red(if v % 8 == 0 { 192 } else { 0 }, 0)
},
|x, y| { // Red bricks
let mortar: bool = y % 8 == 0 || if y % 16 > 8 {
x % 16 == 0
} else {
(x + 8) % 16 == 0
};
red(192, if mortar { 192 } else { 0 })
},
|x, y| { green(gradient_shade(x, y), 0) },
|x, y| { // Blue xor pattern
let xor = xor_shade(x, y);
blue(std::cmp::max(xor, gradient_shade(x, y)), xor)
},
|x, y| { // Yellow gradient
blue(0, xor_shade(x, y))
},
|x, y| { // Magenta xor pattern
let xor = xor_shade(x, y);
RGB(0xff - xor, 0, xor)
},
|_, _| { red(0, 0xff) }, // Cyan field
|_, _| { gray(0xc0) }, // Gray field
];
generators.into_iter()
.map(|gen| Tex::from_fn(gen, format))
.collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment