Add a color coordinate to the chaos game

All shader-related code has been removed; GPU entry points will be added once there's a better understanding of how the API should work.
This commit is contained in:
2026-08-01 15:48:54 -04:00
parent 7ff19631ba
commit 7adb747625
10 changed files with 99 additions and 948 deletions
+35 -44
View File
@@ -1,55 +1,51 @@
//! # Sierpinski Gasket
//!
//! The Sierpinski Gasket is a simple iterated function system (IFS) that demonstrates
//! the basic principles of using the "chaos game" to generate images. Using a set of three
//! transforms, generate new points in the function system using the chaos game,
//! then plot those points and display the resulting image.
use anyhow::{Context, Result};
use enkou_shaders::Coefficients2;
use enkou_shaders::camera::Camera;
use enkou_shaders::camera::entry::main_camera;
use enkou_shaders::chaos_game::entry::main_chaos_game;
use enkou_shaders::chaos_game::ChaosGame;
use enkou_shaders::transform::Transform;
use enkou_shaders::variation::Variation;
use glam::{Affine2, IVec2, UVec2, Vec2, uvec2};
use glam::{Affine2, UVec2, Vec2, uvec2};
use image::{GrayImage, Luma};
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
use std::mem;
use std::process::Command;
use tempfile::NamedTempFile;
const ITERATIONS_DISCARD: u32 = 20;
const ITERATIONS: u32 = 50_000;
const ITERATIONS_DISCARD: usize = 20;
const IMAGE_DIMENSION: UVec2 = uvec2(600, 600);
const IMAGE_QUALITY: f32 = 1.0;
/// Build and display a simple fractal - the Sierpinski Gasket
pub fn main() -> Result<()> {
let mut rng = Xoshiro256StarStar::from_seed([4u8; 32]);
let transforms = [
{
// F_0: (x / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1), 0.0, 0.5)
},
{
// F_1: ((x + 1) / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.5, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1), 0.5, 0.5)
},
{
// F_2: (x / 2, (y + 1) / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.5);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1), 1.0, 0.5)
},
];
let weights = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0];
let variations = [Variation::IDENTITY];
let mut output_points_ifs = Vec::new();
output_points_ifs.resize(ITERATIONS as usize, Vec2::ZERO);
main_chaos_game(
ITERATIONS_DISCARD,
&[4u8; 32],
&transforms,
&weights,
&variations,
&mut output_points_ifs,
);
// The gasket is defined on the range [0, 1] for both X and Y
let camera = Camera::new(
IMAGE_DIMENSION,
@@ -59,33 +55,28 @@ pub fn main() -> Result<()> {
IMAGE_DIMENSION.as_vec2(),
);
let mut output_points_pixel = Vec::new();
output_points_pixel.resize(ITERATIONS as usize, IVec2::ZERO);
main_camera(&camera, &output_points_ifs, &mut output_points_pixel);
let mut image = GrayImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y);
let dimensions = image.dimensions();
output_points_pixel
.iter()
.skip_while(|p| {
p.x < 0 || (p.x as u32) > dimensions.0 || p.y < 0 || (p.y as u32) > dimensions.1
})
.map(|p| (p.x as u32, p.y as u32))
.for_each(|(x, y)| image.put_pixel(x, y, Luma([255u8])));
let chaos_game = ChaosGame::new(&mut rng, &transforms, &weights, &variations);
let iterations = (IMAGE_DIMENSION.element_product() as f32 * IMAGE_QUALITY) as usize;
chaos_game
.skip(ITERATIONS_DISCARD)
.take(iterations)
.for_each(|(ifs_point, _)| {
if let Some(pixel_point) = camera.transform_point_to_image(ifs_point) {
image.put_pixel(pixel_point.x, pixel_point.y, Luma([255u8]));
}
});
let temp = NamedTempFile::with_suffix(".png").context("Unable to create file for image")?;
image.save(temp.path()).context("Unable to save image")?;
let open_program: &str = cfg_select! {
unix => "xdg-open",
_ => panic!("No available program to open images")
};
Command::new(open_program)
.arg(temp.path())
.spawn()?
.wait()?;
let mut command = cfg_select! {
unix => Command::new("xdg-open").arg(temp.path()).spawn(),
windows => Command::new("PowerShell").arg("-Command").arg(format!("start {}", temp.path().display())).spawn(),
_ => Err(anyhow::anyhow!("No available program to open images"))?
}?;
command.wait()?;
// In case the image viewer forks and gives control back prior to reading the file,
// drop it and don't run the destructor
+13 -42
View File
@@ -36,11 +36,12 @@ impl Distribution<f32> for BiUnit {
/// * `weights` - Weights are assumed to be normalized; adding all elements together should return the value 1
pub fn step_chaos_game<R: Rng>(
point: Vec2,
color: f32,
rng: &mut R,
transforms: &[Transform],
weights: &[f32],
variations: &[Variation],
) -> (Vec2, u32) {
) -> (Vec2, f32) {
let mut choice_weight = rng.sample::<f32, _>(StandardUniform);
let mut transform_index: u32 = 0;
@@ -53,9 +54,10 @@ pub fn step_chaos_game<R: Rng>(
transform_index += 1;
}
let transform = &transforms[transform_index as usize];
(
transforms[transform_index as usize].transform_point(rng, variations, point),
transform_index,
transform.transform_point(rng, variations, point),
transform.transform_color(color),
)
}
@@ -65,6 +67,7 @@ pub fn step_chaos_game<R: Rng>(
/// New points in the chaos game are produced by iterating on the chaos game.
pub struct ChaosGame<'a, R: Rng> {
current_point: Vec2,
current_color: f32,
rng: &'a mut R,
transforms: &'a [Transform],
weights: &'a [f32],
@@ -80,8 +83,10 @@ impl<'a, R: Rng> ChaosGame<'a, R> {
variations: &'a [Variation],
) -> Self {
let current_point = vec2(rng.sample(BiUnit), rng.sample(BiUnit));
let current_color = rng.sample(StandardUniform);
ChaosGame {
current_point,
current_color,
rng,
transforms,
weights,
@@ -91,54 +96,20 @@ impl<'a, R: Rng> ChaosGame<'a, R> {
}
impl<'a, R: Rng> Iterator for ChaosGame<'a, R> {
type Item = Vec2;
type Item = (Vec2, f32);
fn next(&mut self) -> Option<Self::Item> {
let (next_point, _) = step_chaos_game(
let (next_point, next_color) = step_chaos_game(
self.current_point,
self.current_color,
self.rng,
self.transforms,
self.weights,
self.variations,
);
self.current_point = next_point;
self.current_color = next_color;
Some(next_point)
}
}
/// Shader entry point for running the chaos game to produce new IFS coordinates
pub mod entry {
use crate::chaos_game::ChaosGame;
use crate::rng::xoshiro256starstar_from_seed;
use crate::transform::Transform;
use crate::variation::Variation;
use glam::Vec2;
use spirv_std::spirv;
/// Given a set of fractal flame parameters, generate new IFS coordinates
/// and store them in the output array.
#[spirv(compute(entry_point_name = "main_chaos_game", threads(1)))]
pub fn main_chaos_game(
#[spirv(spec_constant(id = 1, default = 20))] iteration_discard: u32,
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] rng_seed: &[u8],
#[spirv(storage_buffer, descriptor_set = 0, binding = 1)] transforms: &[Transform],
#[spirv(storage_buffer, descriptor_set = 0, binding = 2)] weights: &[f32],
#[spirv(storage_buffer, descriptor_set = 0, binding = 3)] variations: &[Variation],
#[spirv(storage_buffer, descriptor_set = 1, binding = 0)] output: &mut [Vec2],
) {
let mut rng_seed_actual = [0u8; 32];
(0..32).for_each(|i| rng_seed_actual[i] = rng_seed[i]);
let mut rng = xoshiro256starstar_from_seed(rng_seed_actual);
let mut chaos_game = ChaosGame::new(&mut rng, transforms, weights, variations);
for _ in 0..iteration_discard {
chaos_game.next().unwrap();
}
for i in 0..output.len() {
output[i] = chaos_game.next().unwrap();
}
Some((next_point, next_color))
}
}
-2
View File
@@ -1,11 +1,9 @@
//! # Enkou
#![no_std]
#![deny(missing_docs)]
#![allow(clippy::needless_range_loop)] // SPIR-V backend has issues with iteration over items
pub mod camera;
pub mod chaos_game;
mod rng;
pub mod transform;
pub mod variation;
-55
View File
@@ -1,55 +0,0 @@
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
/// Convert an RNG state buffer to an instance of [`Xoshiro256StarStar`].
///
/// While [`SeedableRng::from_seed`] is an infallible function,
/// it relies on some methods that can't be compiled by the SPIR-V
/// backend (specifically, formatting functions in the core crate).
///
/// In practice, the xoshiro RNG state is entirely defined by its seed,
/// so this function does the work of [`SeedableRng::from_seed`] by
/// transmuting the seed value to an RNG instance.
///
/// This function assumes a properly-initialized state array;
/// output may silently degenerate if the initial state is all zeros,
/// so this module is private to the crate.
pub(crate) fn xoshiro256starstar_from_seed(
rng_state: <Xoshiro256StarStar as SeedableRng>::Seed,
) -> Xoshiro256StarStar {
let mut rng_state_actual = [0u64; 4];
// NOTE: Bit shifting is bad, but we don't have great alternatives:
// - `chunks_exact` has issues with pointer casting
// - `u64::from_le_bytes` has issues with `OpBitcast` in SPIR-V validation
for i in 0..rng_state_actual.len() {
for j in 0..size_of::<u64>() {
rng_state_actual[i] |= (rng_state[i * size_of::<u64>() + j] as u64) << (j * 8);
}
}
unsafe { core::mem::transmute(rng_state_actual) }
}
#[cfg(test)]
mod test {
use crate::rng::xoshiro256starstar_from_seed;
use core::iter::zip;
use rand::{RngExt, SeedableRng};
use rand_xoshiro::Xoshiro256StarStar;
#[test]
fn match_seeded() {
let mut seed: <Xoshiro256StarStar as SeedableRng>::Seed = [0u8; 32];
for i in 0..seed.len() {
seed[i] = i as u8;
}
let rng1 = Xoshiro256StarStar::from_seed(seed).random_iter::<u64>();
let rng2 = xoshiro256starstar_from_seed(seed).random_iter::<u64>();
zip(rng1, rng2)
.take(100)
.for_each(|(rng1_value, rng2_value)| assert_eq!(rng1_value, rng2_value));
}
}
+47 -6
View File
@@ -5,7 +5,7 @@
//! but produce more interesting images once we add variations.
use crate::variation::Variation;
use bytemuck::{Pod, Zeroable};
use glam::{Affine2, UVec2, Vec2};
use glam::{Affine2, FloatExt, UVec2, Vec2};
use rand::Rng;
/// Affine transform for use in the [`chaos_game`](crate::chaos_game).
@@ -15,15 +15,25 @@ pub struct Transform {
coefficients: Affine2,
coefficients_post: Affine2,
variation_range: UVec2,
color: f32,
color_speed: f32,
}
impl Transform {
/// Create a new transform from an affine transformation matrix
pub fn new(coefficients: Affine2, coefficients_post: Affine2, variation_range: UVec2) -> Self {
pub fn new(
coefficients: Affine2,
coefficients_post: Affine2,
variation_range: UVec2,
color: f32,
color_speed: f32,
) -> Self {
Transform {
coefficients,
coefficients_post,
variation_range,
color,
color_speed,
}
}
@@ -47,14 +57,20 @@ impl Transform {
self.coefficients_post.transform_point2(point)
}
/// Apply this transform to a color in IFS coordinates, producing a new color
pub fn transform_color(&self, color: f32) -> f32 {
self.color.lerp(color, self.color_speed)
}
}
#[cfg(test)]
mod test {
use crate::rng::xoshiro256starstar_from_seed;
use crate::transform::Transform;
use crate::variation::{Variation, VariationKind};
use glam::{Affine2, uvec2, vec2};
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
#[test]
fn transform_scaling() {
@@ -63,9 +79,11 @@ mod test {
Affine2::from_scale(scale_coefficients),
Affine2::IDENTITY,
uvec2(0, 1),
0.0,
0.0,
);
let mut rng = xoshiro256starstar_from_seed([0; 32]);
let mut rng = Xoshiro256StarStar::from_seed([0u8; 32]);
let variations = [Variation::IDENTITY];
let point = vec2(1.0, 1.0);
@@ -78,14 +96,17 @@ mod test {
#[test]
fn transform_scaling_post() {
let scale_coefficients = vec2(2.0, 0.5);
let transform_pdj = Transform::new(Affine2::IDENTITY, Affine2::IDENTITY, uvec2(0, 1));
let transform_pdj =
Transform::new(Affine2::IDENTITY, Affine2::IDENTITY, uvec2(0, 1), 0.0, 0.0);
let transform_pdj_post = Transform::new(
Affine2::IDENTITY,
Affine2::from_scale(scale_coefficients),
uvec2(0, 1),
0.0,
0.0,
);
let mut rng = xoshiro256starstar_from_seed([0; 32]);
let mut rng = Xoshiro256StarStar::from_seed([0; 32]);
let variations = [Variation::new(VariationKind::Pdj, 1.0, [0.0f32; 4].into())];
let point = vec2(1.0, 1.0);
@@ -94,4 +115,24 @@ mod test {
assert_eq!(point_pdj * scale_coefficients, point_pdj_post);
}
#[test]
fn transform_color() {
let starting_color = 0.0;
let transform_color = 1.0;
let transform_speed = 0.5;
let transform = Transform::new(
Affine2::IDENTITY,
Affine2::IDENTITY,
uvec2(0, 1),
starting_color,
transform_speed,
);
assert_eq!(
transform.transform_color(starting_color),
starting_color * (1.0 - transform_speed) + transform_color * transform_speed
);
}
}