mandelbrot/src/main.rs

108 lines
3.1 KiB
Rust

use bevy::{prelude::*, render::texture::TextureFormat};
use mandelbrot::Mandelbrot;
use std::time::Instant;
fn main() {
// Mandelbrot::escape_time_image();
App::build()
.add_plugins(DefaultPlugins)
.add_resource(SpriteScale::default())
.add_startup_system(png_startup.system())
.add_system(mandelbrot_render_system.system())
.add_system(mandelbrot_input_scale_system.system())
.run();
}
struct SpriteScale {
zoom: f64,
horiz: f64,
verti: f64,
step: f64,
}
impl Default for SpriteScale {
fn default() -> Self {
Self {
zoom: 1.0,
horiz: 0.0,
verti: 0.0,
step: 0.01,
}
}
}
fn mandelbrot_input_scale_system(
input: Res<Input<KeyCode>>,
mut scale: ResMut<SpriteScale>,
// camera: Res<Camera>,
) {
let zoom = input.pressed(KeyCode::Q) as i8 - input.pressed(KeyCode::E) as i8;
let horizontal = input.pressed(KeyCode::D) as i8 - input.pressed(KeyCode::A) as i8;
let vertical = input.pressed(KeyCode::W) as i8 - input.pressed(KeyCode::S) as i8;
let step_mod = input.pressed(KeyCode::R) as i8 - input.pressed(KeyCode::F) as i8;
scale.step += (scale.step / 10.0) * step_mod as f64;
scale.verti += scale.step * vertical as f64;
scale.horiz += scale.step * horizontal as f64;
scale.zoom += scale.step * zoom as f64;
if scale.zoom < 0.0 {
// We can't go below 0
scale.zoom -= scale.step * zoom as f64;
}
}
const X_BOUNDS: (f64, f64) = (-2.5, 1.0);
const Y_BOUNDS: (f64, f64) = (-1.0, 1.0);
fn mandelbrot_render_system(
materials: Res<Assets<ColorMaterial>>,
mut textures: ResMut<Assets<Texture>>,
scale: Res<SpriteScale>,
mut query: Query<(&mut Mandelbrot, &Handle<ColorMaterial>)>,
) {
for (mut fractal, handle) in query.iter_mut() {
if let Some(material) = materials.get(handle) {
if let Some(texture_handle) = &material.texture {
if let Some(texture) = textures.get_mut(texture_handle) {
let z = scale.zoom;
let h = scale.horiz;
let v = scale.verti;
let start = Instant::now();
texture.data = fractal.generate_scaled_image(
((-2.5 * z) + h, (1.0 * z) + h),
((-1.0 * z) - v, (1.0 * z) - v),
);
let diff = Instant::now() - start;
dbg!(z);
dbg!(diff);
}
}
}
}
}
fn png_startup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
let texture_handle = asset_server.load("test.png");
commands
.spawn(Camera2dComponents::default())
.spawn(SpriteComponents {
material: materials.add(texture_handle.into()),
..Default::default()
})
.with(Mandelbrot::new());
}
fn fractal_startup(mut commands: Commands) {
commands
.spawn(Camera2dComponents::default())
.spawn(SpriteComponents::default())
.with(Mandelbrot::new());
}