astrelis-geometry 0.2.4

Customizable 2D geometry rendering for Astrelis Game Engine
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
//! Chart rendering using the geometry renderer.
//!
//! This module provides two rendering paths:
//! - **Tessellation path**: Uses Lyon for CPU tessellation (slower, but universal)
//! - **GPU path**: Uses specialized renderers for instanced GPU rendering (faster for large datasets)
//!
//! The GPU path is automatically selected for charts with >500 data points per series.

use super::rect::Rect;
use super::renderers::GPU_RENDER_THRESHOLD;
use super::renderers::GpuChartLineRenderer;
use super::types::{
    AxisId, AxisOrientation, AxisPosition, Chart, ChartType, DataPoint, FillRegionKind,
};
use crate::{GeometryRenderer, PathBuilder, ScissorRect, Stroke, Style};
use astrelis_core::profiling::profile_scope;
use astrelis_render::{Color, Viewport, wgpu};
use glam::Vec2;

/// Renders charts using a GeometryRenderer, with optional GPU acceleration.
pub struct ChartRenderer<'a> {
    geometry: &'a mut GeometryRenderer,
    /// Optional GPU line renderer for accelerated line series rendering.
    gpu_line_renderer: Option<&'a mut GpuChartLineRenderer>,
}

impl<'a> ChartRenderer<'a> {
    /// Create a new chart renderer wrapping a geometry renderer.
    pub fn new(geometry: &'a mut GeometryRenderer) -> Self {
        Self {
            geometry,
            gpu_line_renderer: None,
        }
    }

    /// Create a chart renderer with GPU acceleration for line series.
    ///
    /// When GPU acceleration is enabled and a line chart has more than
    /// `GPU_RENDER_THRESHOLD` points, it will use GPU instancing for
    /// much faster rendering.
    pub fn with_gpu_line_renderer(
        geometry: &'a mut GeometryRenderer,
        gpu_line_renderer: &'a mut GpuChartLineRenderer,
    ) -> Self {
        Self {
            geometry,
            gpu_line_renderer: Some(gpu_line_renderer),
        }
    }

    /// Render a chart within the given bounds.
    ///
    /// This method accumulates geometry commands. Call `render()` afterwards
    /// to draw everything to a render pass.
    ///
    /// For GPU-accelerated line charts, use `draw_with_gpu_lines()` instead.
    pub fn draw(&mut self, chart: &Chart, bounds: Rect) {
        self.draw_internal(chart, bounds, false);
    }

    /// Render a chart with GPU-accelerated line series.
    ///
    /// This method accumulates non-line geometry commands. Large line series
    /// (>500 points) will NOT be drawn - they should be rendered separately
    /// via `GpuChartLineRenderer` for much better performance.
    ///
    /// Returns the plot area rectangle for use with GPU line rendering.
    pub fn draw_with_gpu_lines(&mut self, chart: &Chart, bounds: Rect) -> Rect {
        let plot_area = bounds.inset(chart.padding);
        self.draw_internal(chart, bounds, true);
        plot_area
    }

    /// Internal draw implementation with GPU line skip option.
    fn draw_internal(&mut self, chart: &Chart, bounds: Rect, skip_gpu_lines: bool) {
        profile_scope!("chart_draw");

        // When skip_gpu_lines is true, we skip large line series (they'll be rendered via GPU).
        // When false, we draw everything via tessellation.
        let use_gpu_for_lines = skip_gpu_lines && chart.chart_type == ChartType::Line;

        // Draw background
        self.geometry
            .draw_rect(bounds.position(), bounds.size(), chart.background_color);

        // Calculate plot area (inside padding and axis labels)
        let plot_area = bounds.inset(chart.padding);

        // Draw grid lines (outside scissor so they extend to edges)
        {
            profile_scope!("draw_grid");
            self.draw_grid(chart, &plot_area);
        }

        // Draw axes (outside scissor)
        {
            profile_scope!("draw_axes");
            self.draw_all_axes(chart, &plot_area);
        }

        // Set scissor to clip data series to plot area
        self.geometry.set_scissor(ScissorRect::from_f32(
            plot_area.x,
            plot_area.y,
            plot_area.width,
            plot_area.height,
        ));

        // Draw fill regions (clipped to plot area)
        {
            profile_scope!("draw_fill_regions");
            self.draw_fill_regions(chart, &plot_area);
        }

        // Draw line annotations (clipped to plot area)
        {
            profile_scope!("draw_line_annotations");
            self.draw_line_annotations(chart, &plot_area);
        }

        // Draw data series (clipped to plot area)
        {
            profile_scope!("draw_series");
            match chart.chart_type {
                ChartType::Line => {
                    if use_gpu_for_lines {
                        // Only draw small series via tessellation, skip large ones for GPU
                        self.draw_line_series_tessellated_only(chart, &plot_area);
                    } else {
                        self.draw_line_series(chart, &plot_area);
                    }
                }
                ChartType::Scatter => self.draw_scatter_series(chart, &plot_area),
                ChartType::Bar => self.draw_bar_series(chart, &plot_area),
                ChartType::Area => self.draw_area_series(chart, &plot_area),
            }
        }

        // Draw crosshair if enabled and hovering (clipped to plot area)
        if chart.show_crosshair {
            profile_scope!("draw_crosshair");
            self.draw_crosshair(chart, &plot_area);
        }

        // Reset scissor for any subsequent drawing
        self.geometry.reset_scissor();
    }

    /// Draw only small line series via tessellation (for hybrid rendering).
    fn draw_line_series_tessellated_only(&mut self, chart: &Chart, plot_area: &Rect) {
        profile_scope!("draw_line_series_small");
        for series in &chart.series {
            // Skip large series - they'll be rendered via GPU
            if series.data.len() > GPU_RENDER_THRESHOLD {
                continue;
            }

            if series.data.len() < 2 {
                continue;
            }

            self.draw_single_line_series_tessellated(chart, series, plot_area);
        }
    }

    /// Draw a single line series using tessellation.
    fn draw_single_line_series_tessellated(
        &mut self,
        chart: &Chart,
        series: &super::types::Series,
        plot_area: &Rect,
    ) {
        // Get visible X range with buffer for smooth scrolling
        let (x_min, x_max) = chart.axis_range(series.x_axis);
        let x_range = x_max - x_min;
        let buffer = x_range * 0.1;
        let visible_x_min = x_min - buffer;
        let visible_x_max = x_max + buffer;

        // Find visible point range using binary search
        let (start_idx, end_idx) =
            Self::find_visible_range(&series.data, visible_x_min, visible_x_max);

        if end_idx <= start_idx + 1 {
            return;
        }

        // Build path for the visible portion of the line
        let mut builder = PathBuilder::new();
        let first_point = self.data_to_pixel_with_axes(
            chart,
            plot_area,
            series.data[start_idx].x,
            series.data[start_idx].y,
            series.x_axis,
            series.y_axis,
        );
        builder.move_to(first_point);

        for point in &series.data[start_idx + 1..end_idx] {
            let pixel = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                point.x,
                point.y,
                series.x_axis,
                series.y_axis,
            );
            builder.line_to(pixel);
        }

        let path = builder.build();
        let stroke = Stroke::solid(series.style.color, series.style.line_width);
        self.geometry.draw_path_stroke(&path, &stroke);

        // Draw points if enabled
        if let Some(point_style) = &series.style.point_style {
            for point in &series.data[start_idx..end_idx] {
                let pixel = self.data_to_pixel_with_axes(
                    chart,
                    plot_area,
                    point.x,
                    point.y,
                    series.x_axis,
                    series.y_axis,
                );
                self.geometry
                    .draw_circle(pixel, point_style.size * 0.5, point_style.color);
            }
        }
    }

    /// Convert data coordinates to pixel coordinates using specific axes.
    fn data_to_pixel_with_axes(
        &self,
        chart: &Chart,
        plot_area: &Rect,
        x: f64,
        y: f64,
        x_axis_id: AxisId,
        y_axis_id: AxisId,
    ) -> Vec2 {
        let (x_min, x_max) = chart.axis_range(x_axis_id);
        let (y_min, y_max) = chart.axis_range(y_axis_id);

        let px = plot_area.x + ((x - x_min) / (x_max - x_min)) as f32 * plot_area.width;
        // Y is inverted (0 at top in screen coords)
        let py = plot_area.y + plot_area.height
            - ((y - y_min) / (y_max - y_min)) as f32 * plot_area.height;

        Vec2::new(px, py)
    }

    /// Convert pixel coordinates to data coordinates.
    pub fn pixel_to_data(&self, chart: &Chart, plot_area: &Rect, pixel: Vec2) -> DataPoint {
        let (x_min, x_max) = chart.x_range();
        let (y_min, y_max) = chart.y_range();

        let x = x_min + ((pixel.x - plot_area.x) / plot_area.width) as f64 * (x_max - x_min);
        let y = y_max - ((pixel.y - plot_area.y) / plot_area.height) as f64 * (y_max - y_min);

        DataPoint::new(x, y)
    }

    fn draw_fill_regions(&mut self, chart: &Chart, plot_area: &Rect) {
        for region in &chart.fill_regions {
            match &region.kind {
                FillRegionKind::HorizontalBand { y_min, y_max } => {
                    let (x_range_min, x_range_max) = chart.axis_range(region.x_axis);
                    let top_left = self.data_to_pixel_with_axes(
                        chart,
                        plot_area,
                        x_range_min,
                        *y_max,
                        region.x_axis,
                        region.y_axis,
                    );
                    let bottom_right = self.data_to_pixel_with_axes(
                        chart,
                        plot_area,
                        x_range_max,
                        *y_min,
                        region.x_axis,
                        region.y_axis,
                    );

                    self.geometry.draw_rect(
                        Vec2::new(top_left.x, top_left.y),
                        Vec2::new(bottom_right.x - top_left.x, bottom_right.y - top_left.y),
                        region.color,
                    );
                }
                FillRegionKind::VerticalBand { x_min, x_max } => {
                    let (y_range_min, y_range_max) = chart.axis_range(region.y_axis);
                    let top_left = self.data_to_pixel_with_axes(
                        chart,
                        plot_area,
                        *x_min,
                        y_range_max,
                        region.x_axis,
                        region.y_axis,
                    );
                    let bottom_right = self.data_to_pixel_with_axes(
                        chart,
                        plot_area,
                        *x_max,
                        y_range_min,
                        region.x_axis,
                        region.y_axis,
                    );

                    self.geometry.draw_rect(
                        Vec2::new(top_left.x, top_left.y),
                        Vec2::new(bottom_right.x - top_left.x, bottom_right.y - top_left.y),
                        region.color,
                    );
                }
                FillRegionKind::BelowSeries {
                    series_index,
                    y_baseline,
                } => {
                    if let Some(series) = chart.series.get(*series_index) {
                        if series.data.len() < 2 {
                            continue;
                        }

                        let mut builder = PathBuilder::new();

                        // Start at baseline
                        let base_start = self.data_to_pixel_with_axes(
                            chart,
                            plot_area,
                            series.data[0].x,
                            *y_baseline,
                            series.x_axis,
                            series.y_axis,
                        );
                        builder.move_to(base_start);

                        // Line up to first data point
                        let first = self.data_to_pixel_with_axes(
                            chart,
                            plot_area,
                            series.data[0].x,
                            series.data[0].y,
                            series.x_axis,
                            series.y_axis,
                        );
                        builder.line_to(first);

                        // Follow series
                        for point in &series.data[1..] {
                            let p = self.data_to_pixel_with_axes(
                                chart,
                                plot_area,
                                point.x,
                                point.y,
                                series.x_axis,
                                series.y_axis,
                            );
                            builder.line_to(p);
                        }

                        // Close to baseline
                        let base_end = self.data_to_pixel_with_axes(
                            chart,
                            plot_area,
                            series.data.last().unwrap().x,
                            *y_baseline,
                            series.x_axis,
                            series.y_axis,
                        );
                        builder.line_to(base_end);
                        builder.close();

                        let path = builder.build();
                        let style = Style::fill_color(region.color);
                        self.geometry.draw_path(&path, &style);
                    }
                }
                FillRegionKind::BetweenSeries {
                    series_index_1,
                    series_index_2,
                } => {
                    let series1 = chart.series.get(*series_index_1);
                    let series2 = chart.series.get(*series_index_2);

                    if let (Some(s1), Some(s2)) = (series1, series2) {
                        if s1.data.is_empty() || s2.data.is_empty() {
                            continue;
                        }

                        let mut builder = PathBuilder::new();

                        // Forward along series 1
                        let first = self.data_to_pixel_with_axes(
                            chart,
                            plot_area,
                            s1.data[0].x,
                            s1.data[0].y,
                            s1.x_axis,
                            s1.y_axis,
                        );
                        builder.move_to(first);

                        for point in &s1.data[1..] {
                            let p = self.data_to_pixel_with_axes(
                                chart, plot_area, point.x, point.y, s1.x_axis, s1.y_axis,
                            );
                            builder.line_to(p);
                        }

                        // Backward along series 2
                        for point in s2.data.iter().rev() {
                            let p = self.data_to_pixel_with_axes(
                                chart, plot_area, point.x, point.y, s2.x_axis, s2.y_axis,
                            );
                            builder.line_to(p);
                        }

                        builder.close();

                        let path = builder.build();
                        let style = Style::fill_color(region.color);
                        self.geometry.draw_path(&path, &style);
                    }
                }
                FillRegionKind::Rectangle {
                    x_min,
                    y_min,
                    x_max,
                    y_max,
                } => {
                    let top_left = self.data_to_pixel_with_axes(
                        chart,
                        plot_area,
                        *x_min,
                        *y_max,
                        region.x_axis,
                        region.y_axis,
                    );
                    let bottom_right = self.data_to_pixel_with_axes(
                        chart,
                        plot_area,
                        *x_max,
                        *y_min,
                        region.x_axis,
                        region.y_axis,
                    );

                    self.geometry.draw_rect(
                        Vec2::new(top_left.x, top_left.y),
                        Vec2::new(bottom_right.x - top_left.x, bottom_right.y - top_left.y),
                        region.color,
                    );
                }
                FillRegionKind::Polygon { points } => {
                    if points.len() < 3 {
                        continue;
                    }

                    let mut builder = PathBuilder::new();
                    let first = self.data_to_pixel_with_axes(
                        chart,
                        plot_area,
                        points[0].x,
                        points[0].y,
                        region.x_axis,
                        region.y_axis,
                    );
                    builder.move_to(first);

                    for point in &points[1..] {
                        let p = self.data_to_pixel_with_axes(
                            chart,
                            plot_area,
                            point.x,
                            point.y,
                            region.x_axis,
                            region.y_axis,
                        );
                        builder.line_to(p);
                    }
                    builder.close();

                    let path = builder.build();
                    let style = Style::fill_color(region.color);
                    self.geometry.draw_path(&path, &style);
                }
            }
        }
    }

    fn draw_line_annotations(&mut self, chart: &Chart, plot_area: &Rect) {
        for annotation in &chart.line_annotations {
            let start = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                annotation.start.x,
                annotation.start.y,
                annotation.x_axis,
                annotation.y_axis,
            );
            let end = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                annotation.end.x,
                annotation.end.y,
                annotation.x_axis,
                annotation.y_axis,
            );

            self.geometry
                .draw_line(start, end, annotation.width, annotation.color);
        }
    }

    fn draw_crosshair(&mut self, chart: &Chart, plot_area: &Rect) {
        if let Some((series_idx, point_idx)) = chart.interactive.hovered_point
            && let Some(series) = chart.series.get(series_idx)
            && let Some(point) = series.data.get(point_idx)
        {
            let pixel = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                point.x,
                point.y,
                series.x_axis,
                series.y_axis,
            );

            let crosshair_color = Color::rgba(1.0, 1.0, 1.0, 0.5);

            // Vertical line
            self.geometry.draw_line(
                Vec2::new(pixel.x, plot_area.y),
                Vec2::new(pixel.x, plot_area.bottom()),
                1.0,
                crosshair_color,
            );

            // Horizontal line
            self.geometry.draw_line(
                Vec2::new(plot_area.x, pixel.y),
                Vec2::new(plot_area.right(), pixel.y),
                1.0,
                crosshair_color,
            );

            // Highlight point
            self.geometry.draw_circle(pixel, 6.0, series.style.color);
        }
    }

    fn draw_grid(&mut self, chart: &Chart, plot_area: &Rect) {
        // Draw grid for each axis
        for axis in &chart.axes {
            if !axis.grid_lines || !axis.visible {
                continue;
            }

            let style = &axis.style;
            let tick_count = axis.tick_count;

            match axis.orientation {
                AxisOrientation::Horizontal => {
                    // Vertical grid lines
                    for i in 0..=tick_count {
                        let t = i as f32 / tick_count as f32;
                        let x = plot_area.x + t * plot_area.width;
                        self.geometry.draw_line(
                            Vec2::new(x, plot_area.y),
                            Vec2::new(x, plot_area.bottom()),
                            style.grid_width,
                            style.grid_color,
                        );
                    }
                }
                AxisOrientation::Vertical => {
                    // Horizontal grid lines
                    for i in 0..=tick_count {
                        let t = i as f32 / tick_count as f32;
                        let y = plot_area.y + t * plot_area.height;
                        self.geometry.draw_line(
                            Vec2::new(plot_area.x, y),
                            Vec2::new(plot_area.right(), y),
                            style.grid_width,
                            style.grid_color,
                        );
                    }
                }
            }
        }
    }

    fn draw_all_axes(&mut self, chart: &Chart, plot_area: &Rect) {
        for axis in &chart.axes {
            if !axis.visible {
                continue;
            }

            let style = &axis.style;

            match (axis.orientation, axis.position) {
                (AxisOrientation::Horizontal, AxisPosition::Bottom) => {
                    // X axis at bottom
                    self.geometry.draw_line(
                        Vec2::new(plot_area.x, plot_area.bottom()),
                        Vec2::new(plot_area.right(), plot_area.bottom()),
                        style.line_width,
                        style.line_color,
                    );

                    // Ticks
                    for i in 0..=axis.tick_count {
                        let t = i as f32 / axis.tick_count as f32;
                        let x = plot_area.x + t * plot_area.width;
                        let y = plot_area.bottom();
                        self.geometry.draw_line(
                            Vec2::new(x, y),
                            Vec2::new(x, y + style.tick_length),
                            style.line_width,
                            style.tick_color,
                        );
                    }
                }
                (AxisOrientation::Horizontal, AxisPosition::Top) => {
                    // X axis at top
                    self.geometry.draw_line(
                        Vec2::new(plot_area.x, plot_area.y),
                        Vec2::new(plot_area.right(), plot_area.y),
                        style.line_width,
                        style.line_color,
                    );

                    // Ticks
                    for i in 0..=axis.tick_count {
                        let t = i as f32 / axis.tick_count as f32;
                        let x = plot_area.x + t * plot_area.width;
                        let y = plot_area.y;
                        self.geometry.draw_line(
                            Vec2::new(x, y - style.tick_length),
                            Vec2::new(x, y),
                            style.line_width,
                            style.tick_color,
                        );
                    }
                }
                (AxisOrientation::Vertical, AxisPosition::Left) => {
                    // Y axis at left
                    self.geometry.draw_line(
                        Vec2::new(plot_area.x, plot_area.y),
                        Vec2::new(plot_area.x, plot_area.bottom()),
                        style.line_width,
                        style.line_color,
                    );

                    // Ticks
                    for i in 0..=axis.tick_count {
                        let t = i as f32 / axis.tick_count as f32;
                        let x = plot_area.x;
                        let y = plot_area.y + t * plot_area.height;
                        self.geometry.draw_line(
                            Vec2::new(x - style.tick_length, y),
                            Vec2::new(x, y),
                            style.line_width,
                            style.tick_color,
                        );
                    }
                }
                (AxisOrientation::Vertical, AxisPosition::Right) => {
                    // Y axis at right
                    self.geometry.draw_line(
                        Vec2::new(plot_area.right(), plot_area.y),
                        Vec2::new(plot_area.right(), plot_area.bottom()),
                        style.line_width,
                        style.line_color,
                    );

                    // Ticks
                    for i in 0..=axis.tick_count {
                        let t = i as f32 / axis.tick_count as f32;
                        let x = plot_area.right();
                        let y = plot_area.y + t * plot_area.height;
                        self.geometry.draw_line(
                            Vec2::new(x, y),
                            Vec2::new(x + style.tick_length, y),
                            style.line_width,
                            style.tick_color,
                        );
                    }
                }
                _ => {}
            }
        }
    }

    fn draw_line_series(&mut self, chart: &Chart, plot_area: &Rect) {
        profile_scope!("draw_line_series");
        for series in &chart.series {
            if series.data.len() < 2 {
                continue;
            }

            // Get visible X range with buffer for smooth scrolling
            let (x_min, x_max) = chart.axis_range(series.x_axis);
            let x_range = x_max - x_min;
            let buffer = x_range * 0.1; // 10% buffer on each side
            let visible_x_min = x_min - buffer;
            let visible_x_max = x_max + buffer;

            // Find visible point range using binary search (assumes sorted X data)
            let (start_idx, end_idx) =
                Self::find_visible_range(&series.data, visible_x_min, visible_x_max);

            tracing::trace!(
                "Series '{}': rendering {} of {} points (indices {}..{})",
                series.name,
                end_idx - start_idx,
                series.data.len(),
                start_idx,
                end_idx
            );

            // Need at least 2 points to draw a line
            if end_idx <= start_idx + 1 {
                continue;
            }

            // Build path for the visible portion of the line
            let mut builder = PathBuilder::new();
            let first_point = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                series.data[start_idx].x,
                series.data[start_idx].y,
                series.x_axis,
                series.y_axis,
            );
            builder.move_to(first_point);

            for point in &series.data[start_idx + 1..end_idx] {
                let pixel = self.data_to_pixel_with_axes(
                    chart,
                    plot_area,
                    point.x,
                    point.y,
                    series.x_axis,
                    series.y_axis,
                );
                builder.line_to(pixel);
            }

            let path = builder.build();

            // Draw the line
            let stroke = Stroke::solid(series.style.color, series.style.line_width);
            self.geometry.draw_path_stroke(&path, &stroke);

            // Draw points if enabled (only visible ones)
            if let Some(point_style) = &series.style.point_style {
                for point in &series.data[start_idx..end_idx] {
                    let pixel = self.data_to_pixel_with_axes(
                        chart,
                        plot_area,
                        point.x,
                        point.y,
                        series.x_axis,
                        series.y_axis,
                    );
                    self.geometry
                        .draw_circle(pixel, point_style.size * 0.5, point_style.color);
                }
            }
        }
    }

    /// Find the range of visible points using binary search.
    /// Returns (start_idx, end_idx) where end_idx is exclusive.
    /// Includes one extra point on each side for line continuity.
    fn find_visible_range(data: &[DataPoint], x_min: f64, x_max: f64) -> (usize, usize) {
        if data.is_empty() {
            return (0, 0);
        }

        // Binary search for first point >= x_min
        let start = data
            .binary_search_by(|p| p.x.partial_cmp(&x_min).unwrap_or(std::cmp::Ordering::Equal))
            .unwrap_or_else(|i| i);

        // Binary search for first point > x_max
        let end = data
            .binary_search_by(|p| {
                if p.x <= x_max {
                    std::cmp::Ordering::Less
                } else {
                    std::cmp::Ordering::Greater
                }
            })
            .unwrap_or_else(|i| i);

        // Include one extra point on each side for line continuity
        let start = start.saturating_sub(1);
        let end = (end + 1).min(data.len());

        (start, end)
    }

    fn draw_scatter_series(&mut self, chart: &Chart, plot_area: &Rect) {
        let default_point_style = super::style::PointStyle::default();
        for series in &chart.series {
            let point_style = series
                .style
                .point_style
                .as_ref()
                .unwrap_or(&default_point_style);

            // Get visible X range with buffer
            let (x_min, x_max) = chart.axis_range(series.x_axis);
            let x_range = x_max - x_min;
            let buffer = x_range * 0.1;
            let (start_idx, end_idx) =
                Self::find_visible_range(&series.data, x_min - buffer, x_max + buffer);

            for point in &series.data[start_idx..end_idx] {
                let pixel = self.data_to_pixel_with_axes(
                    chart,
                    plot_area,
                    point.x,
                    point.y,
                    series.x_axis,
                    series.y_axis,
                );
                self.geometry
                    .draw_circle(pixel, point_style.size * 0.5, series.style.color);
            }
        }
    }

    fn draw_bar_series(&mut self, chart: &Chart, plot_area: &Rect) {
        let bar_width = chart.bar_config.bar_width;
        let gap = chart.bar_config.gap;

        let series_count = chart.series.len() as f32;
        let total_width = bar_width * series_count + gap * (series_count - 1.0);

        for (series_idx, series) in chart.series.iter().enumerate() {
            let (y_min, _) = chart.axis_range(series.y_axis);
            let offset = series_idx as f32 * (bar_width + gap) - total_width * 0.5;

            // Get visible X range with buffer
            let (x_min, x_max) = chart.axis_range(series.x_axis);
            let x_range = x_max - x_min;
            let buffer = x_range * 0.1;
            let (start_idx, end_idx) =
                Self::find_visible_range(&series.data, x_min - buffer, x_max + buffer);

            for point in &series.data[start_idx..end_idx] {
                let center_pixel = self.data_to_pixel_with_axes(
                    chart,
                    plot_area,
                    point.x,
                    point.y,
                    series.x_axis,
                    series.y_axis,
                );
                let base_pixel = self.data_to_pixel_with_axes(
                    chart,
                    plot_area,
                    point.x,
                    y_min,
                    series.x_axis,
                    series.y_axis,
                );

                let bar_x = center_pixel.x + offset;
                let bar_height = (base_pixel.y - center_pixel.y).abs();
                let bar_y = center_pixel.y.min(base_pixel.y);

                self.geometry.draw_rect(
                    Vec2::new(bar_x, bar_y),
                    Vec2::new(bar_width, bar_height),
                    series.style.color,
                );
            }
        }
    }

    fn draw_area_series(&mut self, chart: &Chart, plot_area: &Rect) {
        for series in &chart.series {
            if series.data.len() < 2 {
                continue;
            }

            let (y_min, _) = chart.axis_range(series.y_axis);

            // Get visible X range with buffer for smooth scrolling
            let (x_min, x_max) = chart.axis_range(series.x_axis);
            let x_range = x_max - x_min;
            let buffer = x_range * 0.1; // 10% buffer on each side
            let visible_x_min = x_min - buffer;
            let visible_x_max = x_max + buffer;

            // Find visible point range using binary search
            let (start_idx, end_idx) =
                Self::find_visible_range(&series.data, visible_x_min, visible_x_max);

            // Need at least 2 points to draw an area
            if end_idx <= start_idx + 1 {
                continue;
            }

            let visible_data = &series.data[start_idx..end_idx];

            // Build filled path for visible portion
            let mut builder = PathBuilder::new();

            // Start at baseline
            let first_x = visible_data[0].x;
            let base_start = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                first_x,
                y_min,
                series.x_axis,
                series.y_axis,
            );
            builder.move_to(base_start);

            // Line to first data point
            let first_point = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                first_x,
                visible_data[0].y,
                series.x_axis,
                series.y_axis,
            );
            builder.line_to(first_point);

            // Connect visible data points
            for point in &visible_data[1..] {
                let pixel = self.data_to_pixel_with_axes(
                    chart,
                    plot_area,
                    point.x,
                    point.y,
                    series.x_axis,
                    series.y_axis,
                );
                builder.line_to(pixel);
            }

            // Close to baseline
            let last_x = visible_data.last().unwrap().x;
            let base_end = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                last_x,
                y_min,
                series.x_axis,
                series.y_axis,
            );
            builder.line_to(base_end);
            builder.close();

            let path = builder.build();

            // Draw filled area with transparency
            let fill_color = if let Some(fill) = &series.style.fill {
                Color::rgba(fill.color.r, fill.color.g, fill.color.b, fill.opacity)
            } else {
                Color::rgba(
                    series.style.color.r,
                    series.style.color.g,
                    series.style.color.b,
                    0.3,
                )
            };

            let style = Style::fill_color(fill_color);
            self.geometry.draw_path(&path, &style);

            // Draw line on top (only visible portion)
            let mut builder = PathBuilder::new();
            let first_point = self.data_to_pixel_with_axes(
                chart,
                plot_area,
                visible_data[0].x,
                visible_data[0].y,
                series.x_axis,
                series.y_axis,
            );
            builder.move_to(first_point);

            for point in &visible_data[1..] {
                let pixel = self.data_to_pixel_with_axes(
                    chart,
                    plot_area,
                    point.x,
                    point.y,
                    series.x_axis,
                    series.y_axis,
                );
                builder.line_to(pixel);
            }

            let path = builder.build();
            let stroke = Stroke::solid(series.style.color, series.style.line_width);
            self.geometry.draw_path_stroke(&path, &stroke);
        }
    }

    /// Render the accumulated draw commands.
    pub fn render(&mut self, pass: &mut wgpu::RenderPass, viewport: Viewport) {
        self.geometry.render(pass, viewport);
    }

    /// Render with GPU-accelerated line series.
    ///
    /// Call this after `draw_with_gpu_lines()`. The GPU line renderer must
    /// have been prepared with `GpuChartLineRenderer::prepare()` before this call.
    ///
    /// # Arguments
    ///
    /// * `pass` - The render pass to draw into
    /// * `viewport` - The viewport for rendering
    /// * `chart` - The chart being rendered (for data ranges)
    /// * `plot_area` - The plot area returned by `draw_with_gpu_lines()`
    pub fn render_with_gpu_lines(
        &mut self,
        pass: &mut wgpu::RenderPass,
        viewport: Viewport,
        chart: &Chart,
        plot_area: &Rect,
    ) {
        profile_scope!("chart_render_gpu_lines");

        // First render all non-line geometry
        self.geometry.render(pass, viewport);

        // Then render GPU lines if available
        if let Some(gpu_renderer) = &self.gpu_line_renderer {
            profile_scope!("render_gpu_line_series");
            gpu_renderer.render(pass, viewport, plot_area, chart);
        }
    }
}

/// Hit test result for chart interaction.
#[derive(Debug, Clone)]
pub struct HitTestResult {
    /// Series index
    pub series_index: usize,
    /// Point index within the series
    pub point_index: usize,
    /// Distance from the test point to the data point (in pixels)
    pub distance: f32,
    /// The data point
    pub data_point: DataPoint,
    /// The pixel position of the data point
    pub pixel_position: Vec2,
}

impl ChartRenderer<'_> {
    /// Find the nearest data point to a pixel position.
    pub fn hit_test(
        &self,
        chart: &Chart,
        plot_area: &Rect,
        pixel: Vec2,
        max_distance: f32,
    ) -> Option<HitTestResult> {
        if !plot_area.contains(pixel) {
            return None;
        }

        let mut best: Option<HitTestResult> = None;

        for (series_idx, series) in chart.series.iter().enumerate() {
            for (point_idx, point) in series.data.iter().enumerate() {
                let point_pixel = self.data_to_pixel_with_axes(
                    chart,
                    plot_area,
                    point.x,
                    point.y,
                    series.x_axis,
                    series.y_axis,
                );

                let dist = pixel.distance(point_pixel);

                if dist <= max_distance && best.as_ref().is_none_or(|b| dist < b.distance) {
                    best = Some(HitTestResult {
                        series_index: series_idx,
                        point_index: point_idx,
                        distance: dist,
                        data_point: *point,
                        pixel_position: point_pixel,
                    });
                }
            }
        }

        best
    }
}