nannou-org / nannou

A Creative Coding Framework for Rust.
https://nannou.cc/
6.04k stars 305 forks source link

Accept closures in `Builder` methods (e.g. `new`, `view`, `update`, etc.) #937

Open vhfmag opened 1 year ago

vhfmag commented 1 year ago

This is a variation of what @thinkrapido implemented in https://github.com/nannou-org/nannou/pull/899 (and is based on it), but it stores closures in Box instead of Arc (which was already done in #815 for WASM support), and allows nannou consumers to pass closures directly to Builder methods, without wrapping them in Arc or using a macro.

To achieve that in a convenient way, it uses the trait_set macro, which enables us to use trait aliases without requiring nightly Rust. That's more convenient because it allows us to do e.g. trait ModelFn<Model> = 'static + Fn(&App) -> Model. Everything done here can be achieved without it, but we'd need to inline the definition of function types everywhere instead of importing aliases.

Here's an example of what we can achieve when Builder methods accept closures:

fn plot_points<Iter: IntoIterator<Item = (f32, f32)>>(
    points: Iter,
    preserve_ratio: bool,
    padding: f32,
    radius: f32,
) {
    let points = points.into_iter().collect::<Vec<_>>();
    nannou::app(|_| ())
        .simple_window(move |app, _, frame| {
            let x_range = get_min_max(points.iter().map(|(x, _)| x));
            let y_range = get_min_max(points.iter().map(|(_, y)| y));

            let get_point =
                generate_get_point_from_coordinate(app, padding, x_range, y_range, preserve_ratio);

            let draw = app.draw();
            draw.background().color(nannou::color::BLACK);
            for &(x, y) in &points {
                draw.ellipse().radius(radius).xy(get_point((x, y)));
            }

            draw.to_frame(app, &frame).unwrap();
            app.set_loop_mode(nannou::LoopMode::loop_once());
        })
        .run();
}

pub fn main() {
    plot_points(get_data_to_plot(), false, 30.0, 1.0);
}

This closes #793