aboutsummaryrefslogtreecommitdiffstats
path: root/src/state.rs
blob: 4c1f0d42d4e0542d1473fe9998239ae616742743 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use std::f64::consts::PI;

use log::debug;
use wasm_bindgen::prelude::*;
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement, HtmlElement};

use crate::JSResult;
use crate::line::Line;
use crate::point::Point;

pub const TAU: f64 = PI * 2.0;
pub const MAX_SPEED: f64 = 0.01;

const VELVEC_SCALE: f64 = 3.0;

#[derive(Debug)]
pub struct State {
    canvas: HtmlCanvasElement,
    ctx: CanvasRenderingContext2d,
    fps: HtmlElement,
    pub points: Vec<Point>,
    last_time: Option<f64>,
    inter_count: u16,
}

impl State {
    pub fn new(canvas: HtmlCanvasElement, fps: HtmlElement) -> JSResult<Self> {
        debug!("State::new()");
        let ctx: CanvasRenderingContext2d = canvas
            .get_context("2d")?
            .expect("2d context on canvas")
            .dyn_into()?;
        ctx.scale(canvas.width().into(), canvas.height().into())?;

        Ok(Self {
            canvas,
            ctx,
            fps,
            points: vec![],
            last_time: None,
            inter_count: 1,
        })
    }

    pub fn render_frame(&mut self, t: f64) -> JSResult<()> {
        if let Some(last_time) = self.last_time {
            if t > last_time {
                let ic: f64 = self.inter_count.into();
                let val: f64 = (1_000.0 * ic / (t - last_time)).trunc();
                self.fps.set_text_content(Some(val.to_string().as_str()));
                self.inter_count = 1;
            } else {
                self.inter_count += 1;
            }
        }
        self.last_time = Some(t);

        self.ctx.clear_rect(
            0.0,
            0.0,
            self.canvas.width().into(),
            self.canvas.height().into(),
        );
        self.render_points()?;

        // poly finding assumes sorted
        self.points.sort_by(|a, b| {
            if a.y > b.y {
                std::cmp::Ordering::Greater
            } else if a.y == b.y {
                std::cmp::Ordering::Equal
            } else {
                std::cmp::Ordering::Less
            }
        });
        let poly_points = self.find_poly();

        self.ctx.set_line_width(0.005);
        let mut iter = poly_points.into_iter();
        let mut last = iter.next().ok_or("no poly points")?;
        for p in iter {
            self.ctx.begin_path();
            self.ctx.move_to(last.x, last.y);
            self.ctx.set_stroke_style_str(&last.color);
            self.ctx.line_to(p.x, p.y);
            self.ctx.stroke();

            last = p;
        }

        Ok(())
    }

    pub fn update(&mut self) -> JSResult<()> {
        if self.bounce_points() {
            //debug!("point bounced");
        }
        self.move_points();
        Ok(())
    }

    pub fn set_dot_count(&mut self, n: usize) {
        self.points = (0..n)
            .map(|_| Point::new(fastrand::f64(), fastrand::f64()))
            .collect();
    }

    fn render_points(&self) -> JSResult<()> {
        for p in &self.points {
            self.ctx.set_fill_style_str(&p.color);
            self.ctx.begin_path();
            self.ctx.arc(p.x, p.y, p.radius, 0.0, TAU)?;
            self.ctx.fill();

            self.ctx.set_line_width(0.005);
            self.ctx.set_stroke_style_str(&p.color);
            self.ctx.begin_path();
            self.ctx.move_to(p.x, p.y);
            self.ctx.line_to(
                p.x + p.speed_x() * VELVEC_SCALE,
                p.y + p.speed_y() * VELVEC_SCALE,
            );
            self.ctx.stroke();
        }
        Ok(())
    }

    pub fn find_poly(&self) -> Vec<&Point> {
        find_poly_helper(&self.points)
    }

    fn bounce_points(&mut self) -> bool {
        bounce_points_helper(&mut self.points)
    }

    fn move_points(&mut self) {
        move_points_helper(&mut self.points);
    }
}

fn bounce_points_helper(points: &mut Vec<Point>) -> bool {
    let mut did_bounce = false;
    for p in points {
        let x = p.x + p.speed_x();
        let y = p.y + p.speed_y();

        if x < 0.0 || x >= 1.0 {
            p.heading = PI - p.heading;
            did_bounce = true;
        } else if y < 0.0 || y >= 1.0 {
            p.heading = -p.heading;
            did_bounce = true;
        }
    }
    did_bounce
}

fn move_points_helper(points: &mut Vec<Point>) {
    for p in points {
        p.x += p.speed_x();
        p.y += p.speed_y();
    }
}

fn find_poly_helper(points: &Vec<Point>) -> Vec<&Point> {
    let p1 = Point::new(0.0, 0.0);
    let p2 = Point::new(1.0, 0.0);
    let mut last_line = Line::new(&p1, &p2);
    let mut xxx = 100;
    let mut res = vec![&points[0]];
    loop {
        let last = res.last().expect("something in res");
        let mut min_theta = TAU;
        let mut min_p = &points[0];
        for p in points {
            if !last.equal_pos(p) {
                let l2 = Line::new(last, p);
                let theta = last_line.angle_between(&l2);
                if theta < min_theta {
                    min_theta = theta;
                    min_p = p;
                }
            }
        }
        last_line = Line::new(res.last().expect("something in res"), min_p);
        res.push(min_p);

        xxx -= 1;
        if xxx == 0 || res[0].equal_pos(res.last().expect("something in res")) {
            break;
        }
    }

    res
}

#[cfg(test)]
mod test {
    use super::*;

    use std::hint::black_box;
    use std::time::Instant;

    fn update(points: &mut Vec<Point>) {
        black_box(bounce_points_helper(points));
        black_box(move_points_helper(points));
        points.sort_by(|a, b| {
            if a.y > b.y {
                std::cmp::Ordering::Greater
            } else if a.y == b.y {
                std::cmp::Ordering::Equal
            } else {
                std::cmp::Ordering::Less
            }
        });
        black_box(find_poly_helper(points));
    }

    #[test]
    fn bench_update() {
        println!("in bench_update(), you remembered cargo test -- --nocapture.");
        let point_count = 40;
        let iters = 10_000;

        let mut points: Vec<Point> = (0..point_count)
            .map(|_| Point::new(fastrand::f64(), fastrand::f64()))
            .collect();

        let start = Instant::now();
        for _ in 0..iters {
            black_box(update(&mut points));
        }
        let delta = start.elapsed();
        let smaller: f64 = u32::try_from(delta.as_millis()).unwrap().into();
        let iters_per_ms = Into::<f64>::into(iters) / smaller;
        println!("{iters} iters in {smaller} ms ({iters_per_ms:0.2} iters per ms)");
    }
}