Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

vhfmag
Copy link

@vhfmag vhfmag commented Sep 7, 2023

This is a variation of what @thinkrapido implemented in #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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Make nannou::app receive a closure.
2 participants