Skip to content

Commit

Permalink
♻️ Improve console UI, use results (wip), move schedule hell out of m…
Browse files Browse the repository at this point in the history
…ain.rs
  • Loading branch information
ewen-lbh committed May 5, 2024
1 parent c34bddf commit ad4a18d
Show file tree
Hide file tree
Showing 17 changed files with 381 additions and 433 deletions.
62 changes: 62 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ web-sys = { version = "0.3.4", features = [
] }
once_cell = "1.19.0"
nanoid = "0.4.0"
console = { version = "0.15.8", features = ["windows-console-colors"] }
backtrace = "0.3.71"


[dev-dependencies]
Expand Down
4 changes: 2 additions & 2 deletions src/animation.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::fmt::Display;

use crate::{Canvas, Context, LaterHookCondition, RenderFunction};
use crate::Canvas;

/// Arguments: animation progress (from 0.0 to 1.0), canvas, current ms
pub type AnimationUpdateFunction = dyn Fn(f32, &mut Canvas, usize);
pub type AnimationUpdateFunction = dyn Fn(f32, &mut Canvas, usize) -> anyhow::Result<()>;

pub struct Animation {
pub name: String,
Expand Down
2 changes: 1 addition & 1 deletion src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl Note {

impl Display for SyncData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SyncData @ {} bpm\n{} stems", self.bpm, self.stems.len())
write!(f, "SyncData @ {} bpm, {} stems", self.bpm, self.stems.len())
}
}

Expand Down
15 changes: 10 additions & 5 deletions src/canvas.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use core::panic;
use std::{cmp, collections::HashMap, io::Write as _, ops::Range};

use anyhow::Result;
use itertools::Itertools as _;
use rand::Rng;

Expand Down Expand Up @@ -188,7 +189,7 @@ impl Canvas {
object_sizes: ObjectSizes::default(),
colormap: ColorMapping::default(),
layers: vec![],
world_region: Region::new(0, 0, 3, 3),
world_region: Region::new(0, 0, 3, 3).unwrap(),
background: None,
}
}
Expand Down Expand Up @@ -379,6 +380,7 @@ impl Canvas {
}

pub fn random_point(&self, region: &Region) -> Point {
region.ensure_nonempty().unwrap();
Point(
rand::thread_rng().gen_range(region.x_range()),
rand::thread_rng().gen_range(region.y_range()),
Expand Down Expand Up @@ -458,7 +460,7 @@ impl Canvas {
}

pub fn aspect_ratio(&self) -> f32 {
return self.height() as f32 / self.width() as f32;
return self.width() as f32 / self.height() as f32;
}

pub fn remove_all_objects_in(&mut self, region: &Region) {
Expand Down Expand Up @@ -517,7 +519,7 @@ impl Canvas {
)
}

pub fn render(&mut self, layers: &Vec<&str>, render_background: bool) -> String {
pub fn render(&mut self, layers: &Vec<&str>, render_background: bool) -> Result<String> {
let background_color = self.background.unwrap_or_default();
let mut svg = svg::Document::new();
if render_background {
Expand Down Expand Up @@ -550,7 +552,8 @@ impl Canvas {
}
}

svg.add(defs)
let rendered = svg
.add(defs)
.set(
"viewBox",
format!(
Expand All @@ -562,6 +565,8 @@ impl Canvas {
)
.set("width", self.width())
.set("height", self.height())
.to_string()
.to_string();

Ok(rendered)
}
}
6 changes: 3 additions & 3 deletions src/examples.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ pub fn dna_analysis_machine() -> Canvas {

let draw_in = canvas.world_region.resized(-1, -1);

let splines_area = Region::from_bottomleft(draw_in.bottomleft().translated(2, -1), (3, 3));
let red_circle_in = Region::from_topright(draw_in.topright().translated(-3, 0), (4, 3));
let splines_area = Region::from_bottomleft(draw_in.bottomleft().translated(2, -1), (3, 3)).unwrap();
let red_circle_in = Region::from_topright(draw_in.topright().translated(-3, 0), (4, 3)).unwrap();

let red_circle_at = red_circle_in.random_point_within();

Expand Down Expand Up @@ -113,7 +113,7 @@ pub fn dna_analysis_machine() -> Canvas {

pub fn title() -> Canvas {
let mut canvas = dna_analysis_machine();
let text_zone = Region::from_topleft(Point(8, 2), (3, 3));
let text_zone = Region::from_topleft(Point(8, 2), (3, 3)).unwrap();
canvas.remove_all_objects_in(&text_zone);
let last_letter_at = &text_zone.bottomright().translated(1, 0);
canvas.remove_all_objects_in(&last_letter_at.region());
Expand Down
19 changes: 13 additions & 6 deletions src/fill.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

use crate::{Color, ColorMapping, RenderCSS};

#[derive(Debug, Clone, Copy)]
Expand All @@ -17,10 +16,18 @@ pub enum HatchDirection {
TopDownDiagonal,
}

const PATTERN_SIZE: usize = 8;

impl HatchDirection {}

impl Fill {
pub fn opacify(&self, opacity: f32) -> Self {
match self {
Fill::Solid(color) => Fill::Translucent(*color, opacity),
Fill::Translucent(color, _) => Fill::Translucent(*color, opacity),
_ => self.clone(),
}
}
}

impl RenderCSS for Fill {
fn render_fill_css(&self, colormap: &ColorMapping) -> String {
match self {
Expand Down Expand Up @@ -74,10 +81,11 @@ impl Fill {
pub fn pattern_id(&self) -> String {
if let Fill::Hatched(color, _, thickness, spacing) = self {
return format!(
"pattern-{}-{}-{}",
"pattern-{}-{}-{}-{}",
self.pattern_name(),
color.name(),
thickness
thickness,
spacing
);
}
String::from("")
Expand Down Expand Up @@ -146,4 +154,3 @@ impl Fill {
}
}
}

71 changes: 10 additions & 61 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(uncommon_codepoints)]

pub mod animation;
pub mod audio;
pub mod canvas;
Expand All @@ -13,9 +15,11 @@ pub mod point;
pub mod preview;
pub mod region;
pub mod sync;
pub mod ui;
pub mod video;
pub mod web;
pub use animation::*;
use anyhow::Result;
pub use audio::*;
pub use canvas::*;
pub use color::*;
Expand All @@ -30,19 +34,11 @@ pub use sync::Syncable;
pub use video::*;
pub use web::log;

use indicatif::{ProgressBar, ProgressStyle};
use nanoid::nanoid;
use std::fs::{self};
use std::ops::{Add, Div, Range, Sub};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time;
use sync::SyncData;

const PROGRESS_BARS_STYLE: &str =
"{spinner:.cyan} {percent:03.bold.cyan}% {msg:<30} [{bar:100.bold.blue/dim.blue}] {eta:.cyan}";

pub struct Context<'a, AdditionalContext = ()> {
pub frame: usize,
pub beat: usize,
Expand All @@ -57,26 +53,14 @@ pub struct Context<'a, AdditionalContext = ()> {
pub duration_override: Option<usize>,
}

pub trait GetOrDefault {
type Item;
fn get_or(&self, index: usize, default: Self::Item) -> Self::Item;
}

impl<T: Copy> GetOrDefault for Vec<T> {
type Item = T;
fn get_or(&self, index: usize, default: T) -> T {
*self.get(index).unwrap_or(&default)
}
}

impl<'a, C> Context<'a, C> {
pub fn stem(&self, name: &str) -> StemAtInstant {
let stems = &self.syncdata.stems;
if !stems.contains_key(name) {
panic!("No stem named {:?} found.", name);
}
StemAtInstant {
amplitude: stems[name].amplitude_db.get_or(self.ms, 0.0),
amplitude: *stems[name].amplitude_db.get(self.ms).unwrap_or(&0.0),
amplitude_max: stems[name].amplitude_max,
velocity_max: stems[name]
.notes
Expand All @@ -90,11 +74,12 @@ impl<'a, C> Context<'a, C> {
}
}

pub fn dump_stems(&self, to: PathBuf) {
std::fs::create_dir_all(&to);
pub fn dump_stems(&self, to: PathBuf) -> Result<()> {
std::fs::create_dir_all(&to)?;
for (name, stem) in self.syncdata.stems.iter() {
fs::write(to.join(name), format!("{:?}", stem));
fs::write(to.join(name), format!("{:?}", stem))?;
}
Ok(())
}

pub fn marker(&self) -> String {
Expand Down Expand Up @@ -185,41 +170,5 @@ impl<'a, C> Context<'a, C> {
}
}

struct SpinState {
pub spinner: ProgressBar,
pub finished: Arc<Mutex<bool>>,
pub thread: JoinHandle<()>,
}

impl SpinState {
fn start(message: &str) -> Self {
let spinner = ProgressBar::new(0).with_style(
ProgressStyle::with_template(&("{spinner:.cyan} ".to_owned() + message)).unwrap(),
);
spinner.tick();

let thread_spinner = spinner.clone();
let finished = Arc::new(Mutex::new(false));
let thread_finished = Arc::clone(&finished);
let spinner_thread = thread::spawn(move || {
while !*thread_finished.lock().unwrap() {
thread_spinner.tick();
thread::sleep(time::Duration::from_millis(100));
}
thread_spinner.finish_and_clear();
});

Self {
spinner: spinner.clone(),
finished,
thread: spinner_thread,
}
}
fn end(self, message: &str) {
*self.finished.lock().unwrap() = true;
self.thread.join().unwrap();
println!("{}", message);
}
}

#[allow(unused)]
fn main() {}
Loading

0 comments on commit ad4a18d

Please sign in to comment.