ranim 0.2.0

An animation engine inspired by manim and JAnim
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use egui::{
    Align2, Color32, Frame, PointerButton, Rect, Rgba, ScrollArea, Shape, Stroke, TextStyle,
    emath::GuiRounding, pos2, remap_clamp,
};

use crate::core::{TimelineInfo, color::palettes::manim};

use super::TimelineInfoState;

pub struct TimelineState {
    pub total_sec: f64,
    pub current_sec: f64,
    pub width_sec: f64,
    pub offset_points: f32,
    pub timeline_infos: Vec<TimelineInfo>,
}

#[allow(unused)]
impl TimelineState {
    pub fn new(total_sec: f64, timeline_infos: Vec<TimelineInfo>) -> Self {
        Self {
            total_sec,
            current_sec: 0.0,
            width_sec: total_sec,
            offset_points: 0.0,
            timeline_infos,
        }
    }
    pub fn ui_preview_timeline(&mut self, ui: &mut egui::Ui) {
        const PREVIEW_HEIGHT: f32 = 30.0;

        Frame::canvas(ui.style()).show(ui, |ui| {
            let mut rect = ui.available_rect_before_wrap();
            // rect.set_bottom(ui.min_rect().bottom());
            rect.set_height(PREVIEW_HEIGHT);

            let font_id = TextStyle::Body.resolve(ui.style());
            let painter = ui.painter_at(rect);
            let shape_id = painter.add(Shape::Noop);
            painter.set(
                shape_id,
                Shape::Vec(paint_time_grid(
                    rect,
                    &painter,
                    font_id,
                    (self.total_sec * 1000.0) as i64,
                    (self.current_sec * 1000.0) as i64,
                )),
            );

            ui.allocate_rect(rect, egui::Sense::hover());
        });
    }

    pub fn interact_preview_timeline(&mut self, info: &TimelineInfoState) {
        let response = &info.response;

        if response.clicked()
            && let Some(mouse_pos) = response.hover_pos()
        {}

        // if response.drag_delta().x != 0.0 {
        //     self.offset_points += response.drag_delta().x;
        // }

        // if response.hovered() {
        //     let mut zoom_factor = info.ctx.input(|i| i.zoom_delta_2d().x);

        //     if response.dragged_by(PointerButton::Secondary) {
        //         let delta = (response.drag_delta().y * 0.01).exp();
        //         // dbg!(delta);
        //         zoom_factor *= delta;
        //     }

        //     // dbg!(state.canvas_width_ms);
        //     if zoom_factor != 1.0 {
        //         self.width_sec /= zoom_factor as f64;
        //         if let Some(mouse_pos) = response.hover_pos() {
        //             let zoom_center = mouse_pos.x - info.canvas.min.x;
        //             self.offset_points =
        //                 (self.offset_points - zoom_center) * zoom_factor + zoom_center;
        //         }
        //     }
        // }

        // // Reset view
        // if response.double_clicked() {
        //     // TODO
        // }
    }

    pub fn ui_main_timeline(&mut self, ui: &mut egui::Ui) {
        Frame::canvas(ui.style()).show(ui, |ui| {
            let available_height = ui.max_rect().bottom() - ui.min_rect().bottom();
            ScrollArea::vertical().show(ui, |ui| {
                let mut canvas = ui.available_rect_before_wrap();
                canvas.max.y = f32::INFINITY;

                let response = ui.interact(
                    canvas,
                    ui.id().with("canvas"),
                    egui::Sense::click_and_drag(),
                );
                let info = TimelineInfoState {
                    ctx: ui.ctx().clone(),
                    canvas,
                    response,
                    painter: ui.painter_at(canvas),
                    text_height: 15.0,
                    font_id: TextStyle::Body.resolve(ui.style()),
                };

                self.interact_main_timeline(&info);

                let timeline_shape_id = info.painter.add(Shape::Noop);

                let max_y = ui_canvas(self, &info);
                let mut used_rect = canvas;
                used_rect.max.y = max_y.max(used_rect.min.y + available_height);

                info.painter.set(
                    timeline_shape_id,
                    Shape::Vec(paint_timeline(
                        &info,
                        used_rect,
                        self,
                        (self.current_sec * 1000.0) as i64,
                    )),
                );

                ui.allocate_rect(used_rect, egui::Sense::hover());
            });
        });
    }

    pub fn interact_main_timeline(&mut self, info: &TimelineInfoState) {
        let response = &info.response;

        if response.drag_delta().x != 0.0 {
            self.offset_points += response.drag_delta().x;
        }

        if response.hovered() {
            let mut zoom_factor = info.ctx.input(|i| i.zoom_delta_2d().x);

            if response.dragged_by(PointerButton::Secondary) {
                let delta = (response.drag_delta().y * 0.01).exp();
                // dbg!(delta);
                zoom_factor *= delta;
            }

            // dbg!(state.canvas_width_ms);
            if zoom_factor != 1.0 {
                let old_width_sec = self.width_sec;
                self.width_sec /= zoom_factor as f64;
                self.width_sec = self.width_sec.clamp(100.0 / 1000.0, self.total_sec);
                zoom_factor = (old_width_sec / self.width_sec) as f32;
                if let Some(mouse_pos) = response.hover_pos() {
                    let zoom_center = mouse_pos.x - info.canvas.min.x;
                    self.offset_points =
                        (self.offset_points - zoom_center) * zoom_factor + zoom_center;
                }
            }
        }

        // Reset view
        if response.double_clicked() {
            // TODO
        }
    }
}

pub fn ui_canvas(state: &mut TimelineState, info: &TimelineInfoState) -> f32 {
    let line_height = 16.0;
    let gap = 4.0;

    let mut start_y = info.canvas.top();
    start_y += info.text_height; // Time labels
    let end_y = start_y + state.timeline_infos.len() as f32 * (line_height + gap);

    for (idx, timeline_info) in state.timeline_infos.iter().enumerate() {
        let local_y = idx as f32 * (line_height + gap);

        let top_y = start_y + local_y;
        let bottom_y = top_y + line_height;

        for animation_info in &timeline_info.animation_infos {
            // if animation_info.anim_name.as_str() == "Static" {
            //     continue;
            // }
            let start_x = info.point_from_ms(state, (animation_info.range.start * 1000.0) as i64);
            let end_x = info.point_from_ms(state, (animation_info.range.end * 1000.0) as i64);

            if info.canvas.max.x < start_x || end_x < info.canvas.min.x {
                continue;
            }

            let rect = Rect::from_min_max(pos2(start_x, top_y), pos2(end_x, bottom_y));
            let rect_color = if animation_info
                .anim_name
                .starts_with("ranim_core::animation::Static")
            {
                manim::YELLOW_C.to_rgba8()
            } else {
                manim::BLUE_C.to_rgba8()
            };

            info.painter.rect_filled(
                rect,
                4.0,
                egui::Rgba::from_srgba_unmultiplied(
                    rect_color.r,
                    rect_color.g,
                    rect_color.b,
                    (0.9 * 255.0) as u8,
                ),
            );

            let wide_enough_for_text = end_x - start_x > 32.0;
            if wide_enough_for_text {
                let text = format!(
                    "{} {:6.3} s",
                    animation_info.anim_name,
                    animation_info.range.end - animation_info.range.start
                );

                let painter = info.painter.with_clip_rect(rect.intersect(info.canvas));

                let pos = pos2(start_x + 4.0, top_y + 0.5 * (16.0 - info.text_height));
                let pos = pos.round_to_pixels(painter.pixels_per_point());
                const TEXT_COLOR: Color32 = Color32::BLACK;
                painter.text(
                    pos,
                    Align2::LEFT_TOP,
                    text,
                    info.font_id.clone(),
                    TEXT_COLOR,
                );
            }
        }
    }

    end_y
}

pub fn paint_time_grid(
    rect: egui::Rect,
    painter: &egui::Painter,
    font_id: egui::FontId,
    width_ms: i64,
    current_ms: i64,
) -> Vec<egui::Shape> {
    if width_ms <= 0 {
        return vec![];
    }

    let mut shapes = vec![];

    let alpha_multiplier = 0.3;

    // The maximum number of lines, 4 pixels gap
    let max_lines = (rect.width() / 4.0).floor() as i64;
    // The minimum grid spacing, 1 ms
    let mut grid_spacing_ms = 1;
    // Increase the grid spacing until it's less than the maximum number of lines
    while width_ms / grid_spacing_ms > max_lines {
        grid_spacing_ms *= 10;
    }

    let num_tiny_lines = width_ms / grid_spacing_ms;
    let zoom_factor = remap_clamp(
        num_tiny_lines as f32,
        (0.1 * max_lines as f32)..=max_lines as f32,
        1.0..=0.0,
    );
    let zoom_factor = zoom_factor * zoom_factor;
    let big_alpha = remap_clamp(zoom_factor, 0.0..=1.0, 0.5..=1.0);
    let medium_alpha = remap_clamp(zoom_factor, 0.0..=1.0, 0.1..=0.5);
    let tiny_alpha = remap_clamp(zoom_factor, 0.0..=1.0, 0.0..=0.1);

    let ppms = rect.width() / width_ms as f32;
    (0..num_tiny_lines).for_each(|i| {
        let ms = grid_spacing_ms * i;
        let line_x = rect.min.x + ms as f32 * ppms;

        let big_line = ms % (grid_spacing_ms * 100) == 0;
        let medium_line = ms % (grid_spacing_ms * 10) == 0;

        let line_alpha = if big_line {
            big_alpha
        } else if medium_line {
            medium_alpha
        } else {
            tiny_alpha
        };

        shapes.push(egui::Shape::line_segment(
            [pos2(line_x, rect.min.y), pos2(line_x, rect.max.y)],
            Stroke::new(1.0, Rgba::from_white_alpha(line_alpha * alpha_multiplier)),
        ));

        let text_alpha = if big_line {
            medium_alpha
        } else if medium_line {
            tiny_alpha
        } else {
            0.0
        };

        if text_alpha > 0.0 {
            let text = grid_text(ms);
            let text_x = line_x + 4.0;
            let text_color = Rgba::from_white_alpha((text_alpha * 2.0).min(1.0)).into();
            // Timestamp on top
            painter.fonts_mut(|f| {
                shapes.push(egui::Shape::text(
                    f,
                    pos2(text_x, rect.min.y),
                    Align2::LEFT_TOP,
                    &text,
                    font_id.clone(),
                    text_color,
                ));
            });
            // Timestamp on bottom
            painter.fonts_mut(|f| {
                shapes.push(egui::Shape::text(
                    f,
                    pos2(text_x, rect.max.y - 12.0),
                    Align2::LEFT_TOP,
                    &text,
                    font_id.clone(),
                    text_color,
                ));
            });
        }
    });

    let current_line_x = current_ms as f32 * ppms;
    shapes.push(egui::Shape::line_segment(
        [
            pos2(current_line_x, rect.min.y),
            pos2(current_line_x, rect.max.y),
        ],
        Stroke::new(1.0, Rgba::from_white_alpha(alpha_multiplier)),
    ));
    shapes
}

pub fn paint_timeline(
    info: &TimelineInfoState,
    rect: egui::Rect,
    state: &TimelineState,
    current_ms: i64,
) -> Vec<egui::Shape> {
    let mut shapes = vec![];

    if state.width_sec <= 0.0 {
        return shapes;
    }

    let alpha_multiplier = 0.3;

    let start_ms = 0;
    // The maximum number of lines, 4 pixels gap
    let max_lines = rect.width() / 4.0;
    // The minimum grid spacing, 1 ms
    let mut grid_spacing_ms = 1;
    // Increase the grid spacing until it's less than the maximum number of lines
    while state.width_sec as f32 * 1000.0 / grid_spacing_ms as f32 > max_lines {
        grid_spacing_ms *= 10;
    }
    // dbg!(state.sideways_pan_in_points);
    // dbg!(state.canvas_width_ms);
    // dbg!(grid_spacing_ms);

    let num_tiny_lines = state.width_sec as f32 * 1000.0 / grid_spacing_ms as f32;
    let zoom_factor = remap_clamp(num_tiny_lines, (0.1 * max_lines)..=max_lines, 1.0..=0.0);
    let zoom_factor = zoom_factor * zoom_factor;
    let big_alpha = remap_clamp(zoom_factor, 0.0..=1.0, 0.5..=1.0);
    let medium_alpha = remap_clamp(zoom_factor, 0.0..=1.0, 0.1..=0.5);
    let tiny_alpha = remap_clamp(zoom_factor, 0.0..=1.0, 0.0..=0.1);

    let mut grid_ms = 0;

    let current_line_x = info.point_from_ms(state, current_ms);
    shapes.push(egui::Shape::line_segment(
        [
            pos2(current_line_x, rect.min.y),
            pos2(current_line_x, rect.max.y),
        ],
        Stroke::new(1.0, Rgba::from_white_alpha(alpha_multiplier)),
    ));
    loop {
        let line_x = info.point_from_ms(state, start_ms + grid_ms);
        if line_x > rect.max.x {
            break;
        }
        if rect.min.x <= line_x {
            let big_line = grid_ms % (grid_spacing_ms * 100) == 0;
            let medium_line = grid_ms % (grid_spacing_ms * 10) == 0;

            let line_alpha = if big_line {
                big_alpha
            } else if medium_line {
                medium_alpha
            } else {
                tiny_alpha
            };

            shapes.push(egui::Shape::line_segment(
                [pos2(line_x, rect.min.y), pos2(line_x, rect.max.y)],
                Stroke::new(1.0, Rgba::from_white_alpha(line_alpha * alpha_multiplier)),
            ));

            let text_alpha = if big_line {
                medium_alpha
            } else if medium_line {
                tiny_alpha
            } else {
                0.0
            };

            if text_alpha > 0.0 {
                let text = grid_text(grid_ms);
                let text_x = line_x + 4.0;
                let text_color = Rgba::from_white_alpha((text_alpha * 2.0).min(1.0)).into();
                // Timestamp on top
                info.painter.fonts_mut(|f| {
                    shapes.push(egui::Shape::text(
                        f,
                        pos2(text_x, rect.min.y),
                        Align2::LEFT_TOP,
                        &text,
                        info.font_id.clone(),
                        text_color,
                    ));
                });
                // Timestamp on bottom
                info.painter.fonts_mut(|f| {
                    shapes.push(egui::Shape::text(
                        f,
                        pos2(text_x, rect.max.y - info.text_height),
                        Align2::LEFT_TOP,
                        &text,
                        info.font_id.clone(),
                        text_color,
                    ));
                });
            }
        }

        grid_ms += grid_spacing_ms;
    }

    // println!("paint_timeline: {:?}", shapes.len());

    shapes
}

fn grid_text(grid_ms: i64) -> String {
    let sec = grid_ms as f64 / 1000.0;
    if grid_ms % 1_000 == 0 {
        format!("{sec:.0} s")
    } else if grid_ms % 100 == 0 {
        format!("{sec:.1} s")
    } else if grid_ms % 10 == 0 {
        format!("{sec:.2} s")
    } else {
        format!("{sec:.3} s")
    }
}