wilhelm_renderer 0.7.1

A minimalist 2D data rendering 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
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
use crate::core::engine::opengl::{
    GL_POINTS, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP, GL_TRIANGLES, GLfloat, Vec2,
};
use crate::core::{
    Attribute, Color, FontAtlas, Geometry, Mesh, Renderable, Renderer, Shader,
    generate_texture_from_image, load_image,
};
use crate::graphics2d::shapes::{
    Arc as ArcShape, Circle, Ellipse, Image, Line, MultiPoint, Polygon, Polyline, Rectangle,
    RoundedRectangle, ShapeKind, Text, Triangle,
};
use crate::graphics2d::svg::ToSvg;
use glam::Mat4;
use std::cell::{OnceCell, RefCell};
use std::collections::HashMap;
use std::f32::consts::PI;
use std::rc::Rc;

const MIN_STROKE_WIDTH: f32 = 1.0;

#[derive(Clone, Debug)]
pub struct ShapeStyle {
    pub fill: Option<Color>,
    pub stroke_color: Option<Color>,
    pub stroke_width: Option<f32>,
}

impl Default for ShapeStyle {
    fn default() -> Self {
        Self {
            fill: Some(Color::from_rgb(1.0, 1.0, 1.0)),
            stroke_color: None,
            stroke_width: None,
        }
    }
}

impl ShapeStyle {
    pub fn fill(fill: Color) -> Self {
        Self {
            fill: Some(fill),
            stroke_color: None,
            stroke_width: None,
        }
    }

    pub fn stroke(color: Color, width: f32) -> Self {
        Self {
            fill: None,
            stroke_color: Some(color),
            stroke_width: Some(width),
        }
    }

    pub fn fill_and_stroke(fill: Color, stroke: Color, width: f32) -> Self {
        Self {
            fill: Some(fill),
            stroke_color: Some(stroke),
            stroke_width: Some(width),
        }
    }
}

thread_local! {
    static DEFAULT_SHADER: OnceCell<Rc<Shader>> = OnceCell::new();
}

fn default_shader() -> Rc<Shader> {
    DEFAULT_SHADER.with(|cell| {
        cell.get_or_init(|| {
            let vert_src = include_str!("../shaders/shape.vert");
            let frag_src = include_str!("../shaders/shape.frag");
            Rc::new(
                Shader::compile(vert_src, frag_src, None)
                    .expect("Failed to compile default shader"),
            )
        })
        .clone()
    })
}

thread_local! {
    static POINT_SHADER: OnceCell<Rc<Shader>> = OnceCell::new();
}

fn point_shader() -> Rc<Shader> {
    POINT_SHADER.with(|cell| {
        cell.get_or_init(|| {
            let vert_src = include_str!("../shaders/shape.vert");
            let frag_src = include_str!("../shaders/point.frag");
            Rc::new(
                Shader::compile(vert_src, frag_src, None).expect("Failed to compile point shader"),
            )
        })
        .clone()
    })
}

thread_local! {
    static IMAGE_SHADER: OnceCell<Rc<Shader>> = OnceCell::new();
}
fn image_shader() -> Rc<Shader> {
    IMAGE_SHADER.with(|cell| {
        cell.get_or_init(|| {
            let vert_src = include_str!("../shaders/image.vert");
            let frag_src = include_str!("../shaders/image.frag");
            Rc::new(
                Shader::compile(vert_src, frag_src, None).expect("Failed to compile image shader"),
            )
        })
        .clone()
    })
}

thread_local! {
    static TEXT_SHADER: OnceCell<Rc<Shader>> = OnceCell::new();
}
fn text_shader() -> Rc<Shader> {
    TEXT_SHADER.with(|cell| {
        cell.get_or_init(|| {
            let vert_src = include_str!("../shaders/text.vert");
            let frag_src = include_str!("../shaders/text.frag");
            Rc::new(
                Shader::compile(vert_src, frag_src, None).expect("Failed to compile text shader"),
            )
        })
        .clone()
    })
}

/// Font cache key: (font_path, font_size)
type FontCacheKey = (String, u32);

thread_local! {
    /// Global font cache - shares FontAtlas instances across text renderables.
    /// Properly dropped when thread exits, no memory leaks.
    static FONT_CACHE: RefCell<HashMap<FontCacheKey, Rc<RefCell<FontAtlas>>>> = RefCell::new(HashMap::new());
}

/// Get or create a FontAtlas from the cache
fn get_or_create_font_atlas(font_path: &str, font_size: u32) -> Rc<RefCell<FontAtlas>> {
    FONT_CACHE.with(|cache| {
        let mut cache = cache.borrow_mut();
        let key = (font_path.to_string(), font_size);

        if let Some(atlas) = cache.get(&key) {
            return atlas.clone();
        }

        // Create new FontAtlas and cache it
        let atlas = FontAtlas::new(font_path, font_size, 512)
            .expect("Failed to create font atlas");
        let atlas_rc = Rc::new(RefCell::new(atlas));
        cache.insert(key, atlas_rc.clone());
        atlas_rc
    })
}

/// Clear the font cache, releasing all FontAtlas resources.
/// Call this when changing scenes or when fonts are no longer needed.
/// Safe to call at any time - new text will recreate atlases as needed.
pub fn clear_font_cache() {
    FONT_CACHE.with(|cache| {
        cache.borrow_mut().clear();
    });
}

fn ortho_2d(width: f32, height: f32) -> Mat4 {
    Mat4::orthographic_rh_gl(0.0, width, height, 0.0, -1.0, 1.0)
}
pub struct ShapeRenderable {
    x: f32,
    y: f32,
    scale: f32,
    rotation: f32,
    mesh: Mesh,
    stroke_mesh: Option<Mesh>,
    shape: ShapeKind,
}
impl Renderable for ShapeRenderable {
    fn render(&mut self, renderer: &Renderer) {
        let (window_width, window_height) = renderer.window_handle.size();
        let transform = ortho_2d(window_width as f32, window_height as f32);
        self.mesh.set_transform(transform);
        self.mesh.set_scale(self.scale);
        self.mesh.set_rotation(self.rotation);

        if self.mesh.geometry.instance_count() > 0 {
            // instanced: u_offset = (0,0), positions come from attrib 1
            renderer.draw_mesh_instanced(&self.mesh);
        } else {
            // single: use u_offset
            self.mesh.set_screen_offset(self.x, self.y);
            renderer.draw_mesh(&self.mesh);
        }

        // Render stroke on top if present
        if let Some(stroke) = &mut self.stroke_mesh {
            stroke.set_transform(transform);
            stroke.set_scale(self.scale);
            stroke.set_rotation(self.rotation);

            if stroke.geometry.instance_count() > 0 {
                renderer.draw_mesh_instanced(stroke);
            } else {
                stroke.set_screen_offset(self.x, self.y);
                renderer.draw_mesh(stroke);
            }
        }
    }
}

impl ShapeRenderable {
    fn new(x: f32, y: f32, mesh: Mesh, shape: ShapeKind) -> Self {
        Self { x, y, scale: 1.0, rotation: 0.0, mesh, stroke_mesh: None, shape }
    }

    fn new_with_stroke(x: f32, y: f32, mesh: Mesh, stroke_mesh: Mesh, shape: ShapeKind) -> Self {
        Self { x, y, scale: 1.0, rotation: 0.0, mesh, stroke_mesh: Some(stroke_mesh), shape }
    }

    pub fn set_position(&mut self, x: f32, y: f32) {
        self.x = x;
        self.y = y;
    }

    pub fn set_scale(&mut self, scale: f32) {
        self.scale = scale;
    }

    pub fn scale(&self) -> f32 {
        self.scale
    }

    pub fn set_rotation(&mut self, angle: f32) {
        self.rotation = angle;
    }

    pub fn rotation(&self) -> f32 {
        self.rotation
    }
    pub fn from_shape(x: f32, y: f32, shape: ShapeKind, style: ShapeStyle) -> Self {
        match shape {
            ShapeKind::Point => {
                ShapeRenderable::point(x, y, style.fill.unwrap_or(Color::white()))
            }
            ShapeKind::MultiPoint(mp) => {
                ShapeRenderable::multi_points(x, y, mp, style.fill.unwrap_or(Color::white()))
            }
            ShapeKind::Line(line) => ShapeRenderable::line(
                x,
                y,
                line,
                style.stroke_color.unwrap_or_else(Color::white),
                style.stroke_width.unwrap_or(1.0),
            ),
            ShapeKind::Polyline(poly_line) => {
                ShapeRenderable::polyline(
                    x,
                    y,
                    poly_line,
                    style.stroke_color.unwrap_or(Color::white()),
                    style.stroke_width.unwrap_or(1.0),
                )
            }

            ShapeKind::Triangle(triangle) => {
                ShapeRenderable::triangle(x, y, triangle, style.fill.unwrap_or(Color::white()))
            }

            ShapeKind::Rectangle(rect) => {
                match (style.fill, style.stroke_color) {
                    (Some(fill), Some(stroke)) => {
                        // Fill and stroke
                        ShapeRenderable::rectangle_fill_and_stroke(
                            x,
                            y,
                            rect,
                            fill,
                            stroke,
                            style.stroke_width.unwrap_or(1.0),
                        )
                    }
                    (None, Some(stroke)) => {
                        // Stroke-only
                        ShapeRenderable::rectangle_outline(
                            x,
                            y,
                            rect,
                            stroke,
                            style.stroke_width.unwrap_or(1.0),
                        )
                    }
                    (fill, None) => {
                        // Fill-only (default)
                        ShapeRenderable::rectangle(x, y, rect, fill.unwrap_or(Color::white()))
                    }
                }
            }

            ShapeKind::RoundedRectangle(rr) => {
                ShapeRenderable::rounded_rectangle(x, y, rr, style.fill.unwrap_or(Color::white()))
            }

            ShapeKind::Polygon(polygon) => {
                ShapeRenderable::polygon(x, y, polygon, style.fill.unwrap_or(Color::white()))
            }
            ShapeKind::Circle(circle) => {
                ShapeRenderable::circle(x, y, circle, style.fill.unwrap_or(Color::white()))
            }
            ShapeKind::Ellipse(ellipse) => {
                ShapeRenderable::ellipse(x, y, ellipse, style.fill.unwrap_or(Color::white()))
            }
            ShapeKind::Arc(arc) => ShapeRenderable::arc(
                x,
                y,
                arc,
                style.stroke_color.unwrap_or(Color::white()),
                style.stroke_width.unwrap_or(1.0),
            ),
            ShapeKind::Image(_) => {
                unimplemented!("ShapeRenderable::from_shape cannot create Image without path")
            }
            ShapeKind::Text(text) => {
                ShapeRenderable::text(x, y, text, style.fill.unwrap_or(Color::white()))
            }
        }
    }

    pub fn create_multiple_instances(&mut self, capacity: usize) {
        self.mesh.geometry.enable_instancing_xy(capacity);
        if let Some(stroke) = &mut self.stroke_mesh {
            stroke.geometry.enable_instancing_xy(capacity);
        }
    }

    pub fn set_instance_positions(&mut self, positions: &[Vec2]) {
        self.mesh.geometry.update_instance_xy(positions);
        if let Some(stroke) = &mut self.stroke_mesh {
            stroke.geometry.update_instance_xy(positions);
        }
    }

    pub fn set_instance_colors(&mut self, colors: &[Color]) {
        self.mesh.geometry.update_instance_colors(colors);
    }

    pub fn set_instance_stroke_colors(&mut self, colors: &[Color]) {
        if let Some(stroke) = &mut self.stroke_mesh {
            stroke.geometry.update_instance_colors(colors);
        }
    }

    pub fn clear_instances(&mut self) {
        self.mesh.geometry.clear_instancing();
        if let Some(stroke) = &mut self.stroke_mesh {
            stroke.geometry.clear_instancing();
        }
    }

    fn point(x: GLfloat, y: GLfloat, color: Color) -> Self {
        let geometry = ShapeRenderable::point_geometry();
        let mesh = Mesh::with_color(point_shader(), geometry, Some(color));
        ShapeRenderable::new(x, y, mesh, ShapeKind::Point)
    }

    fn multi_points(x: GLfloat, y: GLfloat, multi_point: MultiPoint, color: Color) -> Self {
        let abs_points: Vec<(f32, f32)> = multi_point
            .points
            .iter()
            .map(|(px, py)| (x + px, y + py))
            .collect();

        let (x0, y0) = abs_points[0];

        // Shift points to be relative to anchor
        let rel_points: Vec<(GLfloat, GLfloat)> =
            abs_points.iter().map(|(x, y)| (x - x0, y - y0)).collect();

        let geometry = ShapeRenderable::point_list_geometry(&rel_points);
        let mesh = Mesh::with_color(point_shader(), geometry, Some(color));

        ShapeRenderable::new(x0, y0, mesh, ShapeKind::MultiPoint(multi_point))
    }

    fn line(
        x: GLfloat,
        y: GLfloat,
        shape: Line,
        stroke: Color,
        stroke_width: f32,
    ) -> Self {
        // Line geometry uses its own local coordinates (start to end)
        // Position (x, y) places the line in world space
        let (x1, y1) = shape.start;
        let (x2, y2) = shape.end;
        let geometry = ShapeRenderable::line_geometry(x1, y1, x2, y2, stroke_width);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(stroke));

        ShapeRenderable::new(x, y, mesh, ShapeKind::Line(shape))
    }

    fn polyline(
        x: f32,
        y: f32,
        polyline: Polyline,
        stroke: Color,
        stroke_width: f32,
    ) -> Self {
        assert!(polyline.points.len() >= 2, "Polyline requires at least two points");

        let abs_points: Vec<(f32, f32)> =
            polyline.points.iter().map(|(px, py)| (x + px, y + py)).collect();


        let (x0, y0) = abs_points[0];
        let rel_points: Vec<(f32, f32)> = abs_points.iter().map(|(x, y)| (x - x0, y - y0)).collect();

        let geometry = ShapeRenderable::polyline_geometry(&rel_points, stroke_width);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(stroke));

        ShapeRenderable::new(x0, y0, mesh, ShapeKind::Polyline(polyline))
    }

    /// Helper for arc: creates a polyline from pre-computed absolute points
    fn polyline_from_points(
        points: &[(f32, f32)],
        shape: ShapeKind,
        stroke: Color,
        stroke_width: f32,
    ) -> Self {
        assert!(points.len() >= 2, "Polyline requires at least two points");

        let (x0, y0) = points[0];
        let rel_points: Vec<(f32, f32)> = points.iter().map(|(x, y)| (x - x0, y - y0)).collect();

        let geometry = ShapeRenderable::polyline_geometry(&rel_points, stroke_width);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(stroke));

        ShapeRenderable::new(x0, y0, mesh, shape)
    }

    fn arc(x: f32, y: f32, arc: ArcShape, stroke: Color, stroke_width: f32) -> Self {
        use std::f32::consts::TAU;

        let segments = 64;

        // Normalize sweep to [0, TAU)
        let mut sweep = arc.end_angle - arc.start_angle;
        if sweep < 0.0 {
            sweep += TAU;
        }

        // Generate points counter-clockwise from start to end
        let mut points = Vec::with_capacity(segments + 1);
        for i in 0..=segments {
            let t = i as f32 / segments as f32;
            let theta = arc.start_angle + t * sweep;
            let px = x + arc.radius * theta.cos();
            let py = y - arc.radius * theta.sin();
            points.push((px, py));
        }

        Self::polyline_from_points(&points, ShapeKind::Arc(arc), stroke, stroke_width)
    }

    fn triangle(x: f32, y: f32, triangle: Triangle, color: Color) -> Self {
        let geometry = ShapeRenderable::triangle_geometry(&triangle.vertices);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(color));

        ShapeRenderable::new(x, y, mesh, ShapeKind::Triangle(triangle))
    }

    fn rectangle(x: f32, y: f32, rect: Rectangle, color: Color) -> Self {
        let geometry = ShapeRenderable::rectangle_geometry(rect.width, rect.height);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(color));
        ShapeRenderable::new(x, y, mesh, ShapeKind::Rectangle(rect))
    }

    fn rectangle_outline(
        x: f32,
        y: f32,
        rect: Rectangle,
        stroke: Color,
        stroke_width: f32,
    ) -> Self {
        // Create a closed polyline forming the rectangle border
        // Points: top-left -> top-right -> bottom-right -> bottom-left -> back to top-left
        // Extra point at end provides direction for proper miter join at closing corner
        let points = vec![
            (0.0, 0.0),
            (rect.width, 0.0),
            (rect.width, rect.height),
            (0.0, rect.height),
            (0.0, 0.0),        // close the loop
            (rect.width, 0.0), // direction hint for join at closing corner
        ];

        let geometry = ShapeRenderable::polyline_geometry(&points, stroke_width);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(stroke));
        ShapeRenderable::new(x, y, mesh, ShapeKind::Rectangle(rect))
    }

    fn rectangle_fill_and_stroke(
        x: f32,
        y: f32,
        rect: Rectangle,
        fill: Color,
        stroke: Color,
        stroke_width: f32,
    ) -> Self {
        // Fill geometry
        let fill_geometry = ShapeRenderable::rectangle_geometry(rect.width, rect.height);
        let fill_mesh = Mesh::with_color(default_shader(), fill_geometry, Some(fill));

        // Stroke geometry (closed polyline)
        let points = vec![
            (0.0, 0.0),
            (rect.width, 0.0),
            (rect.width, rect.height),
            (0.0, rect.height),
            (0.0, 0.0),
            (rect.width, 0.0),
        ];
        let stroke_geometry = ShapeRenderable::polyline_geometry(&points, stroke_width);
        let stroke_mesh = Mesh::with_color(default_shader(), stroke_geometry, Some(stroke));

        ShapeRenderable::new_with_stroke(x, y, fill_mesh, stroke_mesh, ShapeKind::Rectangle(rect))
    }

    fn rounded_rectangle(x: f32, y: f32, rr: RoundedRectangle, color: Color) -> Self {
        let geometry =
            ShapeRenderable::rounded_rectangle_geometry(rr.width, rr.height, rr.radius, 8);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(color));
        ShapeRenderable::new(x, y, mesh, ShapeKind::RoundedRectangle(rr))
    }

    fn polygon(x: f32, y: f32, polygon: Polygon, color: Color) -> Self {
        assert!(polygon.points.len() >= 3, "Polygon requires at least 3 points");

        let abs_points: Vec<(f32, f32)> =
            polygon.points.iter().map(|(px, py)| (x + px, y + py)).collect();

        let (x0, y0) = abs_points[0]; // Anchor
        let rel_points: Vec<(f32, f32)> = abs_points.iter().map(|(x, y)| (x - x0, y - y0)).collect();

        let geometry = ShapeRenderable::polygon_geometry(&rel_points);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(color));

        ShapeRenderable::new(x0, y0, mesh, ShapeKind::Polygon(polygon))
    }

    fn circle(x: f32, y: f32, circle: Circle, color: Color) -> Self {
        let geometry = ShapeRenderable::circle_geometry(circle.radius, 100);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(color));
        ShapeRenderable::new(x, y, mesh, ShapeKind::Circle(circle))
    }

    fn ellipse(x: f32, y: f32, ellipse: Ellipse, color: Color) -> Self {
        let geometry = ShapeRenderable::ellipse_geometry(ellipse.radius_x, ellipse.radius_y, 64);
        let mesh = Mesh::with_color(default_shader(), geometry, Some(color));
        ShapeRenderable::new(x, y, mesh, ShapeKind::Ellipse(ellipse))
    }

    fn text(x: f32, y: f32, text: Text, color: Color) -> Self {
        // Get or create font atlas from cache (shared across text renderables)
        let font_atlas = get_or_create_font_atlas(&text.font_path, text.font_size);

        // Generate geometry for all characters
        let geometry = {
            let mut atlas = font_atlas.borrow_mut();
            ShapeRenderable::text_geometry(&text.content, &mut atlas)
        };

        // Get texture ID while holding borrow
        let texture_id = font_atlas.borrow().texture_id();

        // Create mesh with text shader and font atlas texture
        let shader = text_shader();
        let mut mesh = Mesh::with_texture(shader, geometry, Some(texture_id));
        mesh.color = Some(color);

        // FontAtlas is owned by FONT_CACHE, properly dropped when thread exits
        ShapeRenderable::new(x, y, mesh, ShapeKind::Text(text))
    }

    pub fn image_with_size(x: f32, y: f32, path: &str, width: f32, height: f32) -> ShapeRenderable {
        // Load image data and upload to GPU
        let image = load_image(path);

        let texture_id = generate_texture_from_image(&image);

        // You likely want to query dimensions in `generate_texture_from_image`
        // But if not, load dimensions again:
        //let (width, height, _) = load_image(path); // image module only used for size

        // Create image geometry (2-triangle quad)
        let geometry = ShapeRenderable::image_geometry(width, height);

        // Use image shader and attach texture
        let shader = image_shader(); // assumes you have an Rc<Shader> loader
        let mesh = Mesh::with_texture(shader, geometry, Some(texture_id));

        ShapeRenderable::new(x, y, mesh, ShapeKind::Image(Image::new(width, height)))
    }

    pub fn image(x: f32, y: f32, path: &str) -> Self {
        let image = load_image(path);
        Self::image_with_size(x, y, path, image.width as f32, image.height as f32)
    }

    fn point_geometry() -> Geometry {
        let vertex = vec![0.0, 0.0];
        let mut geometry = Geometry::new(GL_POINTS);
        geometry.add_buffer(&vertex, 2);

        geometry.add_vertex_attribute(Attribute::new(0, 2, 2, 0));

        geometry
    }

    fn point_list_geometry(points: &[(GLfloat, GLfloat)]) -> Geometry {
        let mut vertices = Vec::with_capacity(points.len() * 2);

        for &(x, y) in points {
            vertices.push(x);
            vertices.push(y);
        }

        let values_per_vertex = 2;

        let mut geometry = Geometry::new(GL_POINTS);
        geometry.add_buffer(&vertices, values_per_vertex);

        geometry.add_vertex_attribute(Attribute::new(
            0, // position
            values_per_vertex,
            values_per_vertex as usize,
            0,
        ));

        geometry
    }

    fn line_geometry(
        x1: GLfloat,
        y1: GLfloat,
        x2: GLfloat,
        y2: GLfloat,
        stroke_width: f32,
    ) -> Geometry {
        let stroke_width = stroke_width.max(MIN_STROKE_WIDTH);
        let dx = x2 - x1;
        let dy = y2 - y1;
        let length = (dx * dx + dy * dy).sqrt();

        if length == 0.0 {
            return Geometry::new(GL_TRIANGLES);
        }

        // Unit perpendicular vector
        let nx = -dy / length;
        let ny = dx / length;
        let half_thickness = stroke_width / 2.0;

        // Offset vector
        let ox = nx * half_thickness;
        let oy = ny * half_thickness;

        // Four corners of the quad
        let v0 = [x1 - ox, y1 - oy];
        let v1 = [x2 - ox, y2 - oy];
        let v2 = [x2 + ox, y2 + oy];
        let v3 = [x1 + ox, y1 + oy];

        let vertices: Vec<GLfloat> = vec![
            v0[0], v0[1], v1[0], v1[1], v2[0], v2[1], v2[0], v2[1], v3[0], v3[1], v0[0], v0[1],
        ];

        let position_values_per_vertex = 2;

        let mut geometry = Geometry::new(GL_TRIANGLES);
        geometry.add_buffer(&vertices, position_values_per_vertex);
        geometry.add_vertex_attribute(Attribute::new(
            0,
            position_values_per_vertex,
            position_values_per_vertex as usize,
            0,
        ));

        geometry
    }

    /// Polyline triangulation adapted from JVPolyline by Julien Vernay (2025)
    ///
    /// Original C implementation:
    /// https://jvernay.fr/en/blog/polyline-triangulation/
    /// Source: https://git.sr.ht/~jvernay/JV/tree/main/item/src/jv_polyline/jv_polyline.c
    ///
    /// This implementation is based on the original algorithm,
    /// restructured and translated to idiomatic Rust for use in wilhelm_renderer.
    fn polyline_geometry(points: &[(GLfloat, GLfloat)], stroke_width: f32) -> Geometry {
        const MITER_LIMIT: f32 = 4.0; // Equivalent to JV default

        if points.len() < 2 {
            return Geometry::new(GL_TRIANGLES);
        }

        let half_thickness = stroke_width.max(1.0) / 2.0;
        let miter_limit_squared = (stroke_width * MITER_LIMIT).powi(2) / 4.0;
        let mut vertices: Vec<GLfloat> = Vec::new();

        let mut a = points[0];
        let mut b = points[1];

        let mut idx = 1;
        while idx < points.len() && (b.0 - a.0).hypot(b.1 - a.1) == 0.0 {
            idx += 1;
            if idx < points.len() {
                b = points[idx];
            }
        }
        if (b.0 - a.0).hypot(b.1 - a.1) == 0.0 {
            return Geometry::new(GL_TRIANGLES);
        }

        for i in idx + 1..=points.len() {
            let c = if i < points.len() { points[i] } else { a }; // fake point if last

            let ab = (b.0 - a.0, b.1 - a.1);
            let len_ab = (ab.0 * ab.0 + ab.1 * ab.1).sqrt();
            let normal_ab = (
                -ab.1 / len_ab * half_thickness,
                ab.0 / len_ab * half_thickness,
            );

            let a1 = (a.0 + normal_ab.0, a.1 + normal_ab.1);
            let a2 = (a.0 - normal_ab.0, a.1 - normal_ab.1);
            let b1 = (b.0 + normal_ab.0, b.1 + normal_ab.1);
            let b2 = (b.0 - normal_ab.0, b.1 - normal_ab.1);

            // segment quad
            vertices.extend_from_slice(&[
                a1.0, a1.1, a2.0, a2.1, b1.0, b1.1, a2.0, a2.1, b1.0, b1.1, b2.0, b2.1,
            ]);

            let bc = (c.0 - b.0, c.1 - b.1);
            let len_bc = (bc.0 * bc.0 + bc.1 * bc.1).sqrt();
            if len_bc > 0.0 {
                let normal_bc = (
                    -bc.1 / len_bc * half_thickness,
                    bc.0 / len_bc * half_thickness,
                );
                let b3 = (b.0 + normal_bc.0, b.1 + normal_bc.1);
                let b4 = (b.0 - normal_bc.0, b.1 - normal_bc.1);

                // turn direction
                let z = ab.0 * bc.1 - ab.1 * bc.0;

                // bevel join
                if z < 0.0 {
                    vertices.extend_from_slice(&[b.0, b.1, b1.0, b1.1, b3.0, b3.1]);
                } else if z > 0.0 {
                    vertices.extend_from_slice(&[b.0, b.1, b2.0, b2.1, b4.0, b4.1]);
                }

                // optional miter
                if z != 0.0 {
                    let (a_j, b_j, norm_j) = if z < 0.0 { (a1, b3, ab) } else { (a2, b4, ab) };

                    let denom = z;
                    let alpha = (bc.1 * (b_j.0 - a_j.0) + bc.0 * (a_j.1 - b_j.1)) / denom;
                    let mx = a_j.0 + alpha * norm_j.0;
                    let my = a_j.1 + alpha * norm_j.1;

                    let dist2 = (mx - b.0).powi(2) + (my - b.1).powi(2);
                    if dist2 <= miter_limit_squared {
                        if z < 0.0 {
                            vertices.extend_from_slice(&[mx, my, b1.0, b1.1, b3.0, b3.1]);
                        } else {
                            vertices.extend_from_slice(&[mx, my, b2.0, b2.1, b4.0, b4.1]);
                        }
                    }
                }
            }

            a = b;
            b = c;
        }

        let mut geometry = Geometry::new(GL_TRIANGLES);
        geometry.add_buffer(&vertices, 2);
        geometry.add_vertex_attribute(Attribute::new(0, 2, 2, 0));
        geometry
    }

    fn triangle_geometry(vertices: &[(f32, f32); 3]) -> Geometry {
        let mut geometry = Geometry::new(GL_TRIANGLES);
        let flattened: Vec<f32> = vertices.iter().flat_map(|(x, y)| [*x, *y]).collect();

        geometry.add_buffer(&flattened, 2);
        geometry.add_vertex_attribute(Attribute::new(0, 2, 2, 0));

        geometry
    }

    fn rectangle_geometry(width: GLfloat, height: GLfloat) -> Geometry {
        let vertices: Vec<GLfloat> = vec![
            // bottom-left
            0.0, 0.0, // bottom-right
            width, 0.0, // top-left
            0.0, height, // top-right
            width, height,
        ];

        let position_values_per_vertex = 2;
        let values_per_vertex = position_values_per_vertex;

        let mut geometry = Geometry::new(GL_TRIANGLE_STRIP);
        geometry.add_buffer(&vertices, values_per_vertex);

        geometry.add_vertex_attribute(Attribute::new(
            0,
            position_values_per_vertex,
            values_per_vertex as usize,
            0,
        ));

        geometry
    }

    fn circle_geometry(radius: GLfloat, segments: usize) -> Geometry {
        let mut vertices: Vec<GLfloat> = Vec::with_capacity((segments + 2) * 5); // center + segments + wrap-around

        // Center of the circle
        vertices.extend_from_slice(&[0.0, 0.0]);

        // Outer vertices
        for i in 0..=segments {
            let theta = (i as f32 / segments as f32) * std::f32::consts::TAU; // TAU = 2Ï€
            let x = radius * theta.cos();
            let y = radius * theta.sin();
            vertices.extend_from_slice(&[x, y]);
        }

        let position_values_per_vertex = 2;
        let values_per_vertex = position_values_per_vertex;

        let mut geometry = Geometry::new(GL_TRIANGLE_FAN);
        geometry.add_buffer(&vertices, values_per_vertex);

        geometry.add_vertex_attribute(Attribute::new(
            0,
            position_values_per_vertex,
            values_per_vertex as usize,
            0,
        ));
        geometry
    }

    fn ellipse_geometry(rx: f32, ry: f32, segments: usize) -> Geometry {
        use std::f32::consts::PI;

        let mut vertices: Vec<GLfloat> = Vec::with_capacity((segments + 2) * 2);

        // Center point (at origin)
        vertices.extend_from_slice(&[0.0, 0.0]);

        // Perimeter points
        for i in 0..=segments {
            let angle = 2.0 * PI * (i as f32) / (segments as f32);
            let x = rx * angle.cos();
            let y = ry * angle.sin();
            vertices.extend_from_slice(&[x, y]);
        }

        let values_per_vertex = 2;
        let mut geometry = Geometry::new(GL_TRIANGLE_FAN);
        geometry.add_buffer(&vertices, values_per_vertex);

        geometry.add_vertex_attribute(Attribute::new(
            0, // position
            2,
            values_per_vertex as usize,
            0,
        ));

        geometry
    }

    pub fn rounded_rectangle_geometry(
        width: f32,
        height: f32,
        radius: f32,
        segments: usize,
    ) -> Geometry {
        assert!(radius * 2.0 <= width && radius * 2.0 <= height);

        let mut vertices: Vec<GLfloat> = Vec::new();

        // 1. Add center point for triangle fan
        let center_x = width / 2.0;
        let center_y = height / 2.0;
        vertices.push(center_x);
        vertices.push(center_y);

        // 2. Define arcs for each corner: (cx, cy, start_angle, end_angle)
        let corners = [
            (radius, radius, PI, 1.5 * PI),                   // top-left
            (width - radius, radius, 1.5 * PI, 2.0 * PI),     // top-right
            (width - radius, height - radius, 0.0, 0.5 * PI), // bottom-right
            (radius, height - radius, 0.5 * PI, PI),          // bottom-left
        ];

        let mut first_arc_x = 0.0;
        let mut first_arc_y = 0.0;
        let mut is_first = true;

        // 3. Generate corner arcs
        for &(cx, cy, start_angle, end_angle) in &corners {
            for i in 0..=segments {
                let theta =
                    start_angle + (end_angle - start_angle) * (i as f32) / (segments as f32);
                let x = cx + radius * theta.cos();
                let y = cy + radius * theta.sin();

                if is_first {
                    first_arc_x = x;
                    first_arc_y = y;
                    is_first = false;
                }

                vertices.push(x);
                vertices.push(y);
            }
        }

        // 4. Close the fan by repeating the first outer point
        vertices.push(first_arc_x);
        vertices.push(first_arc_y);

        // 5. Build Geometry
        let values_per_vertex = 2;
        let mut geometry = Geometry::new(GL_TRIANGLE_FAN);
        geometry.add_buffer(&vertices, values_per_vertex);

        geometry.add_vertex_attribute(Attribute::new(
            0, // location 0 → position
            2, // x and y
            values_per_vertex as usize,
            0,
        ));

        geometry
    }

    fn polygon_geometry(points: &[(GLfloat, GLfloat)]) -> Geometry {
        assert!(points.len() >= 3, "Polygon requires at least 3 points");

        let mut vertices = Vec::with_capacity(points.len() * 2);
        for &(x, y) in points {
            vertices.extend_from_slice(&[x, y]);
        }

        let values_per_vertex = 2;
        let mut geometry = Geometry::new(GL_TRIANGLE_FAN); // Or TRIANGLE_FAN if filled
        geometry.add_buffer(&vertices, values_per_vertex);
        geometry.add_vertex_attribute(Attribute::new(0, 2, values_per_vertex as usize, 0));
        geometry
    }

    pub fn image_geometry(width: f32, height: f32) -> Geometry {
        // Vertex format: [x, y, u, v]
        // Geometry centered at origin for rotation around center
        let hw = width / 2.0;
        let hh = height / 2.0;
        let vertices: Vec<f32> = vec![
            // Triangle 1
            -hw, -hh, 0.0, 0.0, // bottom-left
             hw, -hh, 1.0, 0.0, // bottom-right
             hw,  hh, 1.0, 1.0, // top-right
            // Triangle 2
            -hw, -hh, 0.0, 0.0, // bottom-left
             hw,  hh, 1.0, 1.0, // top-right
            -hw,  hh, 0.0, 1.0, // top-left
        ];

        let values_per_vertex = 4; // x, y, u, v

        let mut geometry = Geometry::new(GL_TRIANGLES);
        geometry.add_buffer(&vertices, values_per_vertex);

        geometry.add_vertex_attribute(Attribute::new(
            0, // location 0 in shader: position
            2, // x, y
            values_per_vertex as usize,
            0,
        ));

        geometry.add_vertex_attribute(Attribute::new(
            1, // location 1 in shader: texcoord
            2, // u, v
            values_per_vertex as usize,
            2, // offset by 2 floats (x, y)
        ));

        geometry
    }

    /// Generate geometry for text rendering
    /// Creates textured quads for each character using glyph info from the font atlas
    fn text_geometry(text: &str, font_atlas: &mut FontAtlas) -> Geometry {
        let mut vertices: Vec<f32> = Vec::new();
        let mut cursor_x: f32 = 0.0;
        let baseline_y: f32 = font_atlas.font_size() as f32; // Start from baseline

        for ch in text.chars() {
            if let Some(glyph) = font_atlas.get_glyph(ch) {
                // Skip rendering for whitespace but advance cursor
                if glyph.width == 0 || glyph.height == 0 {
                    cursor_x += glyph.advance;
                    continue;
                }

                // Calculate quad position
                let x0 = cursor_x + glyph.bearing_x as f32;
                let y0 = baseline_y - glyph.bearing_y as f32; // Y increases downward in screen coords
                let x1 = x0 + glyph.width as f32;
                let y1 = y0 + glyph.height as f32;

                // UV coordinates from font atlas
                let u0 = glyph.uv_x;
                let v0 = glyph.uv_y;
                let u1 = glyph.uv_x + glyph.uv_width;
                let v1 = glyph.uv_y + glyph.uv_height;

                // Two triangles per character quad
                // Triangle 1: bottom-left, bottom-right, top-right
                vertices.extend_from_slice(&[
                    x0, y1, u0, v1, // bottom-left
                    x1, y1, u1, v1, // bottom-right
                    x1, y0, u1, v0, // top-right
                ]);
                // Triangle 2: bottom-left, top-right, top-left
                vertices.extend_from_slice(&[
                    x0, y1, u0, v1, // bottom-left
                    x1, y0, u1, v0, // top-right
                    x0, y0, u0, v0, // top-left
                ]);

                cursor_x += glyph.advance;
            }
        }

        let values_per_vertex = 4; // x, y, u, v

        let mut geometry = Geometry::new(GL_TRIANGLES);
        geometry.add_buffer(&vertices, values_per_vertex);

        geometry.add_vertex_attribute(Attribute::new(
            0, // location 0: position
            2, // x, y
            values_per_vertex as usize,
            0,
        ));

        geometry.add_vertex_attribute(Attribute::new(
            1, // location 1: texcoord
            2, // u, v
            values_per_vertex as usize,
            2, // offset by 2 floats
        ));

        geometry
    }

    fn svg_color(&self) -> String {
        self.mesh
            .color
            .as_ref()
            .map(|c| c.to_hex())
            .unwrap_or_else(|| "#000000".to_string())
    }
}
impl ToSvg for ShapeRenderable {
    fn to_svg(&self) -> String {
        match &self.shape {
            ShapeKind::Line(line) => {
                format!(
                    r#"<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{color}" stroke-width="1"/>"#,
                    x1 = self.x + line.start.0,
                    y1 = self.y + line.start.1,
                    x2 = self.x + line.end.0,
                    y2 = self.y + line.end.1,
                    color = self.svg_color(),
                )
            }
            ShapeKind::Rectangle(rect) => {
                format!(
                    r#"<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{color}"/>"#,
                    x = self.x,
                    y = self.y,
                    w = rect.width,
                    h = rect.height,
                    color = self.svg_color(),
                )
            }
            ShapeKind::RoundedRectangle(rect) => {
                format!(
                    r#"<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{r}" ry="{r}" fill="{color}"/>"#,
                    x = self.x,
                    y = self.y,
                    w = rect.width,
                    h = rect.height,
                    r = rect.radius,
                    color = self.svg_color(),
                )
            }
            ShapeKind::Polygon(polygon) => {
                let path = polygon
                    .points
                    .iter()
                    .map(|(px, py)| format!("{},{}", px + self.x, py + self.y))
                    .collect::<Vec<_>>()
                    .join(" ");

                format!(
                    r#"<polygon points="{path}" fill="{color}" stroke="{color}" stroke-width="1"/>"#,
                    path = path,
                    color = self.svg_color(),
                )
            }
            ShapeKind::Circle(circle) => {
                format!(
                    r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="{color}"/>"#,
                    cx = self.x + circle.radius,
                    cy = self.y + circle.radius,
                    r = circle.radius,
                    color = self.svg_color(),
                )
            }
            ShapeKind::Ellipse(ellipse) => {
                format!(
                    r#"<ellipse cx="{cx}" cy="{cy}" rx="{rx}" ry="{ry}" fill="{color}"/>"#,
                    cx = self.x + ellipse.radius_x,
                    cy = self.y + ellipse.radius_y,
                    rx = ellipse.radius_x,
                    ry = ellipse.radius_y,
                    color = self.svg_color(),
                )
            }
            ShapeKind::Polyline(polyline) => {
                let path = polyline
                    .points
                    .iter()
                    .map(|(px, py)| format!("{},{}", px + self.x, py + self.y))
                    .collect::<Vec<_>>()
                    .join(" ");
                format!(
                    r#"<polyline points="{path}" fill="none" stroke="{color}" stroke-width="1"/>"#,
                    path = path,
                    color = self.svg_color(),
                )
            }
            ShapeKind::MultiPoint(multi_point) => {
                let mut out = String::new();
                for (px, py) in &multi_point.points {
                    let cx = px + self.x;
                    let cy = py + self.y;
                    out.push_str(&format!(
                        r#"<circle cx="{cx}" cy="{cy}" r="2" fill="{color}"/>"#,
                        cx = cx,
                        cy = cy,
                        color = self.svg_color(),
                    ));
                }
                out
            }
            ShapeKind::Point => {
                format!(
                    r#"<circle cx="{cx}" cy="{cy}" r="2" fill="{color}"/>"#,
                    cx = self.x,
                    cy = self.y,
                    color = self.svg_color(),
                )
            }
            ShapeKind::Image(_) => String::new(),
            ShapeKind::Triangle(tri) => {
                let points: String = tri
                    .vertices
                    .iter()
                    .map(|(vx, vy)| format!("{:.2},{:.2}", vx + self.x, vy + self.y))
                    .collect::<Vec<_>>()
                    .join(" ");
                format!(
                    r#"<polygon points="{points}" fill="{color}"/>"#,
                    points = points,
                    color = self.svg_color(),
                )
            }
            ShapeKind::Arc(_) => {
                unimplemented!("Arc SVG export is not yet implemented")
            }
            ShapeKind::Text(text) => {
                // SVG text element - simplified, doesn't use font atlas
                format!(
                    r#"<text x="{x}" y="{y}" fill="{color}" font-size="{size}">{content}</text>"#,
                    x = self.x,
                    y = self.y,
                    color = self.svg_color(),
                    size = text.font_size,
                    content = text.content,
                )
            }
        }
    }
}