yakb 0.1.1

Yet another knowledge base
Documentation
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Boat wind animations

use std::f32::consts::PI;

use bladvak::{
    ErrorManager,
    eframe::egui::{self, Align2, Color32, FontId, Frame, Pos2, Rect, Sense, Shape, Stroke, Vec2},
};

use crate::utils::{draw_text_with_background_center, ui_settings};

/// Unit circle
#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[allow(clippy::struct_excessive_bools)]
pub(crate) struct BoatWindApp {
    /// boat angle
    boat_angle_deg: f32,
    /// boat speed
    boat_speed: f32,
    /// wind angle
    wind_angle_deg: f32,
    /// current speed
    wind_speed: f32,
}

impl Default for BoatWindApp {
    fn default() -> Self {
        Self {
            boat_angle_deg: 45.0,
            boat_speed: 10.0,
            wind_angle_deg: 180.0,
            wind_speed: 15.0,
        }
    }
}

impl BoatWindApp {
    /// show the animation
    pub(crate) fn show(&mut self, ui: &mut egui::Ui, error_manager: &mut ErrorManager) {
        // let dt = ui.ctx().input(|i| i.stable_dt).min(0.05);
        // self.phase = (self.phase + dt * self.speed).rem_euclid(TAU);
        // ui.ctx().request_repaint();

        egui::CentralPanel::default()
            .frame(Frame::NONE)
            .show(ui, |ui| {
                let (aws, awa) = self.paint_scene(ui, error_manager.is_debug());
                self.show_settings(ui, aws, awa);
            });
    }

    /// Show settings
    fn show_settings(&mut self, ui: &mut egui::Ui, aws: f32, awa: f32) {
        ui_settings(ui, |ui| {
            ui.collapsing("Menu", |ui| {
                ui.label("True Wind");
                ui.horizontal(|ui| {
                    ui.colored_label(Color32::RED, "TWA");
                    ui.add(egui::Slider::new(&mut self.wind_angle_deg, 0.0..=360.0).suffix("deg"));
                });
                ui.horizontal(|ui| {
                    ui.colored_label(Color32::RED, "TWS");
                    ui.add(egui::Slider::new(&mut self.wind_speed, 0.0..=30.0));
                });
                ui.separator();
                ui.label("Boat");
                ui.horizontal(|ui| {
                    ui.colored_label(Color32::BLUE, "Boat angle");
                    ui.add(egui::Slider::new(&mut self.boat_angle_deg, 0.0..=360.0).suffix("deg"));
                });
                ui.horizontal(|ui| {
                    ui.colored_label(Color32::BLUE, "Boat speed");
                    ui.add(egui::Slider::new(&mut self.boat_speed, 0.0..=30.0));
                });
                ui.separator();

                if ui.button("Reset").clicked() {
                    *self = Self::default();
                }
            });
            ui.colored_label(Color32::DARK_GREEN, "Apparent Wind");
            ui.colored_label(Color32::DARK_GREEN, format!("AWS: {aws:.2}"));
            ui.colored_label(Color32::DARK_GREEN, format!("AWA: {awa:.2}deg"));
        });
    }

    /// Paint scene
    #[allow(clippy::too_many_lines)]
    fn paint_scene(&mut self, ui: &mut egui::Ui, is_debug: bool) -> (f32, f32) {
        let (response, painter) = ui.allocate_painter(ui.available_size(), egui::Sense::hover());
        let area = response.rect;
        let p = &painter;
        let bg = Color32::from_rgb(255, 255, 255);

        p.rect_filled(area, 0.0, bg);

        let circle_center = Pos2::new(area.center().x, area.top() + area.height() * 0.245);
        let painter = ui.painter();
        let boat_center = Pos2::new(circle_center.x, circle_center.y + 300.0);
        let boat_angle_rad = self.boat_angle_deg.to_radians() + (PI / 2.0);
        draw_wind(painter, boat_center, 150.0, 30.0);
        draw_boat(painter, boat_center, 0.7, boat_angle_rad);

        let multi = 10.0;
        let font_id = &FontId::proportional(12.0);
        let end_boat_speed = boat_center
            - Vec2::new(
                self.boat_speed * multi * boat_angle_rad.cos(),
                self.boat_speed * multi * boat_angle_rad.sin(),
            );
        arrow_filled(
            painter,
            boat_center,
            end_boat_speed,
            Stroke::new(4.0, Color32::BLUE),
        );
        let pos_text = (boat_center + end_boat_speed.to_vec2()) / 2.0;
        draw_text_with_background_center(
            p,
            font_id,
            Color32::BLUE,
            Color32::WHITE,
            pos_text,
            "Boat".to_string(),
        );

        let interact = Rect::from_center_size(end_boat_speed, Vec2::splat(35.0));
        let resp = ui.interact(
            interact,
            ui.id().with("speed_drag"),
            Sense::click_and_drag(),
        );
        if is_debug {
            painter.debug_rect(interact, Color32::YELLOW, "zone speed");
        }
        if resp.dragged()
            && let Some(pos) = resp.interact_pointer_pos()
        {
            let wind_vec = boat_center - pos;

            self.boat_speed = (wind_vec.length() / 10.0).round();

            let new_angle = (wind_vec.y.atan2(wind_vec.x) - PI / 2.0)
                .to_degrees()
                .rem_euclid(360.0);
            self.boat_angle_deg = new_angle.round();
        }

        let wind_angle_rad = self.wind_angle_deg.to_radians() - (PI / 2.0);
        let wind_position = Pos2::new(area.center().x, area.top() + 100.0);
        let wind_vec = Vec2::angled(wind_angle_rad) * (self.wind_speed * 10.0);
        draw_wind(painter, wind_position, 70.0, 10.0);

        fat_arrow(
            painter,
            wind_position,
            wind_position + wind_vec,
            Color32::RED,
        );
        painter.text(
            wind_position,
            Align2::CENTER_TOP,
            "WIND",
            FontId::proportional(12.0),
            Color32::BLACK,
        );

        north_symbol(
            painter,
            Pos2::new(area.left() + (area.width() / 4.0), area.top() + 60.0),
        );

        let start_wind_boat_speed = end_boat_speed
            - Vec2::new(
                self.wind_speed * multi * wind_angle_rad.cos(),
                self.wind_speed * multi * wind_angle_rad.sin(),
            );
        // TWS
        arrow_filled(
            painter,
            start_wind_boat_speed,
            end_boat_speed,
            Stroke::new(4.0, Color32::RED),
        );
        let pos_text = (start_wind_boat_speed + end_boat_speed.to_vec2()) / 2.0;
        draw_text_with_background_center(
            p,
            font_id,
            Color32::RED,
            Color32::WHITE,
            pos_text,
            "True Wind".to_string(),
        );

        // AWS
        arrow_filled(
            painter,
            start_wind_boat_speed,
            boat_center,
            Stroke::new(4.0, Color32::DARK_GREEN),
        );
        let pos_text = (start_wind_boat_speed + boat_center.to_vec2()) / 2.0;
        draw_text_with_background_center(
            p,
            font_id,
            Color32::DARK_GREEN,
            Color32::WHITE,
            pos_text,
            "Apparent Wind".to_string(),
        );

        let interact = Rect::from_center_size(start_wind_boat_speed, Vec2::splat(35.0));
        let resp = ui.interact(interact, ui.id().with("wind_drag"), Sense::click_and_drag());
        if is_debug {
            painter.debug_rect(interact, Color32::YELLOW, "zone");
        }
        if resp.dragged()
            && let Some(pos) = resp.interact_pointer_pos()
        {
            let wind_vec = end_boat_speed - pos;

            self.wind_speed = (wind_vec.length() / 10.0).round();

            let new_angle = (wind_vec.y.atan2(wind_vec.x) + PI / 2.0)
                .to_degrees()
                .rem_euclid(360.0);
            self.wind_angle_deg = new_angle.round();
        }
        let vec_aw = start_wind_boat_speed - boat_center;
        let aws = vec_aw.length() / multi;
        let awa = vec_aw.y.atan2(vec_aw.x) + (PI / 2.0);
        let awa = awa.to_degrees().rem_euclid(360.0);
        (aws, awa)
    }
}

/// draw wind
fn draw_wind(painter: &egui::Painter, origin: Pos2, space: f32, size_bar: f32) {
    #[allow(clippy::cast_precision_loss)]
    for angle_degree in (0..360).step_by(10) {
        let angle = (angle_degree as f32 - 90.0).to_radians();
        let coef_angle = if angle_degree % 90 == 0 { 1.8 } else { 1.0 };

        let point_start = Pos2::new(
            origin.x + space * angle.cos(),
            origin.y + space * angle.sin(),
        );
        let point_end = point_start
            + Vec2::new(
                size_bar * angle.cos() * coef_angle,
                size_bar * angle.sin() * coef_angle,
            );
        let x_text = 10.0;
        let text_coef = if angle.sin() <= 0.0 { 2.0 } else { 1.0 };
        painter.text(
            point_end + Vec2::new(x_text * angle.cos(), x_text * angle.sin() * text_coef),
            Align2::CENTER_TOP,
            format!("{angle_degree}"),
            FontId::proportional(10.0),
            Color32::BLACK,
        );
        painter.line_segment([point_start, point_end], Stroke::new(2.0, Color32::BLACK));
    }
}

/// draw filled arrow
fn arrow_filled(painter: &egui::Painter, origin: Pos2, tip: Pos2, stroke: Stroke) {
    use egui::emath::Rot2;

    let vec = tip - origin;
    let len = vec.length();

    if len < f32::EPSILON {
        return;
    }

    let dir = vec / len;

    // Keep the arrowhead visible even for tiny vectors.
    let head_len = (len / 8.0).max(8.0);
    let head_width = (head_len * 0.5).max(stroke.width * 2.0);

    // Dynamic angle based on head dimensions.
    let angle = (head_width / head_len).atan();
    let rot = Rot2::from_angle(angle);

    let p1 = tip - head_len * (rot * dir);
    let p2 = tip - head_len * (rot.inverse() * dir);

    painter.line_segment([origin, tip], stroke);

    painter.add(Shape::convex_polygon(
        vec![tip, p1, p2],
        stroke.color,
        Stroke::NONE,
    ));
}

/// draw the boat
fn draw_boat(painter: &egui::Painter, origin: Pos2, scale: f32, angle: f32) {
    let points = [
        (-0.6, 9.1),
        (6.5, 11.2),
        (18.8, 34.9),
        (40.6, 91.1),
        (52.3, 126.4),
        (67.1, 187.4),
        (73.8, 243.5),
        (75.3, 293.9),
        (59.8, 426.0),
        (52.9, 446.2),
        (37.7, 455.1),
        (0.0, 460.4),
        (-37.7, 455.1),
        (-52.9, 446.2),
        (-59.8, 426.0),
        (-75.3, 293.9),
        (-73.8, 243.5),
        (-67.1, 187.4),
        (-52.3, 126.4),
        (-40.6, 91.1),
        (-18.8, 34.9),
        (-6.5, 11.2),
    ];
    let center_y = (9.1_f32).midpoint(460.4);
    let (sin, cos) = (angle - PI / 2.0).sin_cos();
    let vertices: Vec<Pos2> = points
        .iter()
        .map(|&(x, y)| {
            let y = y - center_y;

            // Rotate around the shape's center.
            let rotated_x = x * cos - y * sin;
            let rotated_y = x * sin + y * cos;
            Pos2::new(origin.x + rotated_x * scale, origin.y + rotated_y * scale)
        })
        .collect();

    painter.add(Shape::closed_line(
        vertices,
        Stroke::new(2.0, Color32::BLUE),
    ));
}

/// Draws a block arrow centered on `center`, pointing toward `target`.
/// Angle and length are both calculated from the two positions.
fn fat_arrow(painter: &egui::Painter, center: Pos2, target: Pos2, color: Color32) {
    let delta = target - center;
    let length = delta.length();
    if length < f32::EPSILON {
        return;
    }

    let rot = egui::emath::Rot2::from_angle(delta.y.atan2(delta.x));

    let head_length = length * 0.45;
    let head_half_width = length * 0.30;
    let shaft_half_width = length * 0.14;

    let half = length * 0.5;
    let neck_x = half - head_length;

    // Build the arrow pointing right around (0, 0), then rotate and move.
    let place = |x: f32, y: f32| center + rot * Vec2::new(x, y);

    // Shaft (extended 1px into the head to avoid a seam)
    painter.add(Shape::convex_polygon(
        vec![
            place(-half, -shaft_half_width),
            place(neck_x + 1.0, -shaft_half_width),
            place(neck_x + 1.0, shaft_half_width),
            place(-half, shaft_half_width),
        ],
        color,
        Stroke::NONE,
    ));

    // Head
    painter.add(Shape::convex_polygon(
        vec![
            place(neck_x, -head_half_width),
            place(half, 0.0),
            place(neck_x, head_half_width),
        ],
        color,
        Stroke::NONE,
    ));
}

/// Draws a north arrow (split kite with an "N" above it) centered on `pos`.
pub fn north_symbol(painter: &egui::Painter, pos: Pos2) {
    let size = 30.0; // half-height of the arrow; change to scale the symbol
    let half_width = size * 0.4;
    let outline = Stroke::new(1.5, Color32::BLACK);

    let tip = pos + Vec2::new(0.0, -size);
    let notch = pos + Vec2::new(0.0, size * 0.3);
    let bottom_left = pos + Vec2::new(-half_width, size * 0.6);
    let bottom_right = pos + Vec2::new(half_width, size * 0.6);

    // Left half: filled black
    painter.add(Shape::convex_polygon(
        vec![tip, bottom_left, notch],
        Color32::BLACK,
        outline,
    ));

    // Right half: white with a black outline
    painter.add(Shape::convex_polygon(
        vec![tip, notch, bottom_right],
        Color32::WHITE,
        outline,
    ));

    // "N" above the tip
    painter.text(
        tip + Vec2::new(0.0, -4.0),
        Align2::CENTER_BOTTOM,
        "N",
        FontId::proportional(size * 0.7),
        Color32::BLACK,
    );
}