concinnity-core 0.19.9

Runtime vocabulary for the Concinnity engine: GPU layouts, ECS components, registry, CPU kernels
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
//! Sprite quad assembly. Piggybacks on the text render pass: a plain Sprite is
//! emitted as a TextDrawCall containing a single quad with the sentinel UV
//! (u < 0) the text shader interprets as a solid-coloured fill (alpha carried
//! in v); a Sprite with a `texture` is emitted with real 0..1 UVs and a
//! positive vertex `mode` so the shader samples the sprite's texture, which
//! lives in the same atlas pool as the font atlases. Either way, screen-space
//! rectangles need no pipeline of their own.

use crate::math::sin_cos;
use alloc::vec::Vec;

use crate::components::{Sprite, SpriteFit};
use crate::gfx::overlay::{OverlayTransform, UI_REFERENCE_SIZE};
use crate::gfx::render_types::{TextDrawCall, TextVertex};
use crate::render::overlay_maps::{ClipRects, OverlayLayers, TextureSlots};

/// A view-owned sprite that spans the whole reference canvas is a full-screen
/// backdrop (e.g. a menu dim): it is stretched to fill the live window rather
/// than uniform-scaled, and an opaque one hides the scene behind it.
pub fn covers_canvas(s: &Sprite) -> bool {
    let [ref_w, ref_h] = UI_REFERENCE_SIZE;
    s.screen.is_some()
        && s.x <= 0.0
        && s.y <= 0.0
        && s.x + s.width >= ref_w
        && s.y + s.height >= ref_h
}

// Build a TextDrawCall per visible Sprite. `default_atlas_slot` is the atlas
// a solid-fill call binds (the shader does not sample for sentinel-UV verts,
// but the backend still expects a valid slot). Pass the slot of any loaded
// font; returns an empty list when there are no fonts (the text pipeline
// isn't initialised in that case). `texture_slots` maps a Sprite's Texture
// asset to its slot in the atlas pool; a textured sprite whose texture never
// made it there falls back to a solid fill. `viewport` is the live logical
// window size: view-owned sprites are overlay UI authored in the reference
// canvas and are mapped onto the window so menus scale with it; HUD / scene
// sprites (view == None) keep literal window pixels.
#[cfg(test)]
pub(crate) fn build_sprite_calls(
    sprites: &[Sprite],
    default_atlas_slot: Option<usize>,
    texture_slots: &TextureSlots,
    viewport: [f32; 2],
    clips: &ClipRects,
    layers: &OverlayLayers,
) -> Vec<TextDrawCall> {
    let mut out = crate::render::call_buffer::TextCallBuffer::default();
    build_sprite_calls_into(
        &mut out,
        sprites,
        default_atlas_slot,
        texture_slots,
        viewport,
        clips,
        layers,
    );
    out.take()
}

/// `build_sprite_calls`, appending onto an existing draw list so a caller
/// assembling a frame from several element groups reuses one buffer (and, in
/// steady state, the pooled geometry of the spent frame it recycled). A
/// `follow_cursor` sprite is skipped: it is the cursor pass's silhouette
/// source (see `cursor.rs`), not a scene quad.
pub fn build_sprite_calls_into(
    out: &mut crate::render::call_buffer::TextCallBuffer,
    sprites: &[Sprite],
    default_atlas_slot: Option<usize>,
    texture_slots: &TextureSlots,
    viewport: [f32; 2],
    clips: &ClipRects,
    layers: &OverlayLayers,
) {
    let fill_slot = match default_atlas_slot {
        Some(s) => s,
        None => return,
    };
    let overlay = OverlayTransform::from_viewport(viewport);
    let cover = OverlayTransform::cover_from_viewport(viewport);
    let bottom = OverlayTransform::bottom_anchored_from_viewport(viewport);
    let [vw, vh] = viewport;
    for s in sprites {
        if !s.visible || s.follow_cursor {
            continue;
        }
        let [r, g, b, a] = s.tint;
        // A transparent fill still draws when a visible border is set: the
        // border ring is the sprite (an outline, e.g. a selection highlight).
        let border_only = s.border_width > 0.0 && s.border_color[3] > 0.0;
        if a <= 0.0 && !border_only {
            continue;
        }
        let (x0, y0, x1, y1) = if s.screen.is_some() {
            if s.fit == SpriteFit::Cover {
                // Full-bleed stage imagery: uniform fill, centered crop. The
                // canvas edges map at or beyond the window edges, so edge-
                // anchored content (a bottom-anchored portrait) stays flush.
                let (ax, ay) = cover.forward(s.x, s.y);
                let (bx, by) = cover.forward(s.x + s.width, s.y + s.height);
                (ax, ay, bx, by)
            } else if s.fit == SpriteFit::Bottom {
                // Bottom-anchored furniture (a dialog box): fit scale, but
                // pinned to the window bottom rather than the letterbox margin.
                let (ax, ay) = bottom.forward(s.x, s.y);
                let (bx, by) = bottom.forward(s.x + s.width, s.y + s.height);
                (ax, ay, bx, by)
            } else if covers_canvas(s) && vw > 0.0 && vh > 0.0 {
                // A view-owned sprite spanning the whole reference canvas is a
                // full-screen backdrop (e.g. a menu dim): always fill the live
                // window instead of uniform-scaling, which would letterbox it.
                (0.0, 0.0, vw, vh)
            } else {
                let (ax, ay) = overlay.forward(s.x, s.y);
                let (bx, by) = overlay.forward(s.x + s.width, s.y + s.height);
                (ax, ay, bx, by)
            }
        } else {
            (s.x, s.y, s.x + s.width, s.y + s.height)
        };
        let texture_slot = s.texture.and_then(|t| texture_slots.get(&t).copied());
        // UVs derive from the vertex position inside the rect so arbitrary
        // boundary geometry (the rounded-corner path) samples correctly; for
        // the plain quad this reproduces the 0..1 corner UVs exactly.
        let (w, h) = ((x1 - x0).max(f32::EPSILON), (y1 - y0).max(f32::EPSILON));
        let v = |x: f32, y: f32, alpha: f32| match texture_slot {
            // Textured quad: real UVs, tint in color, alpha in mode.
            Some(_) => TextVertex {
                pos: [x, y],
                uv: [(x - x0) / w, (y - y0) / h],
                color: [r, g, b],
                mode: alpha,
            },
            // Solid fill: sentinel u < 0, alpha carried in v.
            None => TextVertex {
                pos: [x, y],
                uv: [-1.0, alpha],
                color: [r, g, b],
                mode: 0.0,
            },
        };
        // The corner radius is authored in the sprite's own pixel space; map
        // it through the same scale the rect took (the overlay transforms are
        // uniform; the full-canvas stretch takes the smaller axis).
        let scale = if s.width > 0.0 && s.height > 0.0 {
            ((x1 - x0) / s.width).min((y1 - y0) / s.height)
        } else {
            1.0
        };
        let radius = (s.corner_radius * scale).min(w / 2.0).min(h / 2.0);
        let border = (s.border_width * scale).min(w / 2.0).min(h / 2.0);
        let (mut vertices, mut indices) = out.geometry();
        if border > 0.5 && s.border_color[3] > 0.0 {
            let [br, bg, bb, ba] = s.border_color;
            let border_v = |x: f32, y: f32, alpha: f32| TextVertex {
                pos: [x, y],
                uv: [-1.0, alpha],
                color: [br, bg, bb],
                mode: 0.0,
            };
            if a <= 0.0 {
                // A transparent fill cannot cover an outer quad (blending
                // leaves the border colour showing through), so an outline
                // is a hollow stroke with nothing inside.
                stroke_geometry(
                    &mut vertices,
                    &mut indices,
                    [x0, y0, x1, y1],
                    radius,
                    border,
                    ba,
                    border_v,
                );
            } else if a < 1.0 {
                // A translucent fill cannot hide an outer rect drawn under it,
                // which would read as a panel in the border colour rather than
                // as the world showing through. The fill takes the whole rect
                // and the stroke is a hollow ring laid over its edge.
                rect_geometry(&mut vertices, &mut indices, [x0, y0, x1, y1], radius, a, v);
                stroke_geometry(
                    &mut vertices,
                    &mut indices,
                    [x0, y0, x1, y1],
                    radius,
                    border,
                    ba,
                    border_v,
                );
            } else {
                // Border stroke under an opaque fill: an outer rounded rect in
                // the border colour, with the fill inset by the stroke width
                // drawn on top so a ring of the border colour is left showing.
                rect_geometry(
                    &mut vertices,
                    &mut indices,
                    [x0, y0, x1, y1],
                    radius,
                    ba,
                    border_v,
                );
                rect_geometry(
                    &mut vertices,
                    &mut indices,
                    [x0 + border, y0 + border, x1 - border, y1 - border],
                    (radius - border).max(0.0),
                    a,
                    v,
                );
            }
        } else {
            rect_geometry(&mut vertices, &mut indices, [x0, y0, x1, y1], radius, a, v);
        }
        out.calls.push(TextDrawCall {
            vertices,
            indices,
            atlas_slot: texture_slot.unwrap_or(fill_slot),
            clip_rect: clips
                .get(&s.asset_id)
                .map(|b| crate::render::text::band_to_window(&overlay, *b)),
            layer: layers.get(&s.asset_id).copied().unwrap_or(0),
        });
    }
}

// Append a rectangle's geometry: a feathered rounded rect when the radius is
// set, otherwise a plain two-triangle quad. Shared by the fill and the border
// ring, which is why indices are rebased on the buffer's current length.
// `rect` is `[x0, y0, x1, y1]`.
fn rect_geometry(
    vertices: &mut Vec<TextVertex>,
    indices: &mut Vec<u16>,
    rect: [f32; 4],
    radius: f32,
    alpha: f32,
    mut v: impl FnMut(f32, f32, f32) -> TextVertex,
) {
    let [x0, y0, x1, y1] = rect;
    if radius > 0.5 {
        rounded_rect_geometry(vertices, indices, rect, radius, alpha, v);
    } else {
        let base = vertices.len() as u16;
        vertices.extend_from_slice(&[
            v(x0, y0, alpha),
            v(x1, y0, alpha),
            v(x1, y1, alpha),
            v(x0, y1, alpha),
        ]);
        indices.extend([0, 1, 2, 0, 2, 3].map(|i| base + i));
    }
}

// Append a border stroke `width` wide inside `rect`, hollow so whatever is
// under it shows through: a ring following the fill's rounded silhouette, or
// four straight strips for a square-cornered sprite.
fn stroke_geometry(
    vertices: &mut Vec<TextVertex>,
    indices: &mut Vec<u16>,
    rect: [f32; 4],
    radius: f32,
    width: f32,
    alpha: f32,
    v: impl FnMut(f32, f32, f32) -> TextVertex,
) {
    match radius > 0.5 {
        true => rounded_ring_geometry(vertices, indices, rect, radius, width, alpha, v),
        false => ring_geometry(vertices, indices, rect, width, alpha, v),
    }
}

// Append a hollow rectangle as four edge strips `width` wide inside `rect`
// (`[x0, y0, x1, y1]`): the top and bottom span the full width, the sides
// fill the gap between them.
fn ring_geometry(
    vertices: &mut Vec<TextVertex>,
    indices: &mut Vec<u16>,
    rect: [f32; 4],
    width: f32,
    alpha: f32,
    mut v: impl FnMut(f32, f32, f32) -> TextVertex,
) {
    let [x0, y0, x1, y1] = rect;
    let strips = [
        [x0, y0, x1, y0 + width],
        [x0, y1 - width, x1, y1],
        [x0, y0 + width, x0 + width, y1 - width],
        [x1 - width, y0 + width, x1, y1 - width],
    ];
    for strip in strips {
        rect_geometry(vertices, indices, strip, 0.0, alpha, &mut v);
    }
}

// Arc steps per rounded corner. Six segments keep a 10-15 px UI radius
// visually smooth once the feathered edge blends the silhouette.
const CORNER_SEGMENTS: usize = 6;
// Width (window pixels) of the soft edge ring. The solid interior stops this
// far inside the authored boundary and fades to transparent at it, so the
// silhouette never grows past the authored rect.
const EDGE_FEATHER: f32 = 1.25;

// The corner-arc samples a rounded rectangle's silhouette is drawn from: each
// entry is a corner centre and a unit offset, so one boundary describes every
// outline concentric with the authored rect (the feathered edge, the inset the
// stroke leaves). Insetting the rect and dropping the radius by the same
// amount leaves the centres where they are, which is what lets a stroke sample
// this at two radii.
fn rounded_boundary(
    rect: [f32; 4],
    radius: f32,
) -> [(f32, f32, f32, f32); 4 * (CORNER_SEGMENTS + 1)] {
    use core::f32::consts::FRAC_PI_2;
    let [x0, y0, x1, y1] = rect;
    // Every corner sweeps the same quarter turn, so the unit offsets are
    // evaluated once and each corner reuses them rotated into its quadrant.
    let mut arc = [(0.0_f32, 0.0_f32); CORNER_SEGMENTS + 1];
    for (i, slot) in arc.iter_mut().enumerate() {
        let (s, c) = sin_cos((i as f32 / CORNER_SEGMENTS as f32) * FRAC_PI_2);
        *slot = (c, s);
    }
    // Corner arc centers in polygon order, each with the quarter-turn count its
    // arc starts at; y grows downward so the arcs sweep clockwise.
    let corners = [
        (x0 + radius, y0 + radius, 2),
        (x1 - radius, y0 + radius, 3),
        (x1 - radius, y1 - radius, 0),
        (x0 + radius, y1 - radius, 1),
    ];
    let mut boundary = [(0.0_f32, 0.0_f32, 0.0_f32, 0.0_f32); 4 * (CORNER_SEGMENTS + 1)];
    for (c, &(cx, cy, quadrant)) in corners.iter().enumerate() {
        for (i, &(uc, us)) in arc.iter().enumerate() {
            let (rc, rs) = match quadrant {
                0 => (uc, us),
                1 => (-us, uc),
                2 => (-uc, -us),
                _ => (us, -uc),
            };
            boundary[c * (CORNER_SEGMENTS + 1) + i] = (cx, cy, rc, rs);
        }
    }
    boundary
}

// Append a rounded rectangle's border stroke: the fill's own silhouette,
// hollowed out `width` inside it. The outer edge feathers exactly as the
// fill's does, so the two silhouettes blend as one; the inner edge is the
// inset rect's own boundary, so a stroke wider than the corner radius keeps
// its full width along the straight runs.
fn rounded_ring_geometry(
    vertices: &mut Vec<TextVertex>,
    indices: &mut Vec<u16>,
    rect: [f32; 4],
    radius: f32,
    width: f32,
    alpha: f32,
    mut v: impl FnMut(f32, f32, f32) -> TextVertex,
) {
    let [x0, y0, x1, y1] = rect;
    let inner_r = (radius - width).max(0.0);
    let solid_r = (radius - EDGE_FEATHER).max(inner_r);
    let outer = rounded_boundary(rect, radius);
    let inner = rounded_boundary([x0 + width, y0 + width, x1 - width, y1 - width], inner_r);
    let m = outer.len();
    let base = vertices.len() as u16;
    vertices.reserve(3 * m);
    for &(cx, cy, cos, sin) in &outer {
        vertices.push(v(cx + radius * cos, cy + radius * sin, 0.0));
    }
    for &(cx, cy, cos, sin) in &outer {
        vertices.push(v(cx + solid_r * cos, cy + solid_r * sin, alpha));
    }
    for &(cx, cy, cos, sin) in &inner {
        vertices.push(v(cx + inner_r * cos, cy + inner_r * sin, alpha));
    }
    indices.reserve(12 * m);
    for loop_start in [0, m] {
        for i in 0..m {
            let j = (i + 1) % m;
            let (i, j, m) = ((loop_start + i) as u16, (loop_start + j) as u16, m as u16);
            indices.extend([i, j, m + j, i, m + j, m + i].map(|k| base + k));
        }
    }
}

// Tessellate a rounded rectangle in window space: a solid convex polygon
// inset one feather width inside the authored boundary, fanned from its first
// point, plus a fading ring out to the boundary for anti-aliasing. Vertex
// alpha carries the fade (both sprite modes read per-vertex alpha).
fn rounded_rect_geometry(
    vertices: &mut Vec<TextVertex>,
    indices: &mut Vec<u16>,
    rect: [f32; 4],
    radius: f32,
    alpha: f32,
    mut v: impl FnMut(f32, f32, f32) -> TextVertex,
) {
    let boundary = rounded_boundary(rect, radius);
    let m = boundary.len();
    let base = vertices.len() as u16;
    let inner_r = (radius - EDGE_FEATHER).max(0.0);
    vertices.reserve(2 * m);
    for &(cx, cy, cos, sin) in &boundary {
        vertices.push(v(cx + inner_r * cos, cy + inner_r * sin, alpha));
    }
    for &(cx, cy, cos, sin) in &boundary {
        vertices.push(v(cx + radius * cos, cy + radius * sin, 0.0));
    }
    indices.reserve(3 * (m - 2) + 6 * m);
    for i in 1..m - 1 {
        indices.extend([base, base + i as u16, base + (i + 1) as u16]);
    }
    for i in 0..m {
        let j = (i + 1) % m;
        let (i, j, m) = (i as u16, j as u16, m as u16);
        indices.extend([i, j, m + j, i, m + j, m + i].map(|k| base + k));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ecs::TextureHandle;
    use crate::ecs::asset_id::AssetId;

    use alloc::vec;
    fn no_clips() -> ClipRects {
        ClipRects::new()
    }
    fn no_layers() -> OverlayLayers {
        OverlayLayers::new()
    }

    fn no_slots() -> TextureSlots {
        TextureSlots::new()
    }

    fn sprite(x: f32, y: f32, w: f32, h: f32, tint: [f32; 4]) -> Sprite {
        Sprite {
            asset_id: AssetId::default(),
            x,
            y,
            width: w,
            height: h,
            texture: None,
            tint,
            follow_cursor: false,
            visible: true,
            screen: None,
            fit: SpriteFit::Fit,
            corner_radius: 0.0,
            border_width: 0.0,
            border_color: [0.0, 0.0, 0.0, 1.0],
        }
    }

    #[test]
    fn no_fonts_means_no_calls() {
        let s = sprite(0.0, 0.0, 100.0, 100.0, [1.0, 0.0, 0.0, 1.0]);
        assert!(
            build_sprite_calls(
                core::slice::from_ref(&s),
                None,
                &no_slots(),
                [0.0, 0.0],
                &no_clips(),
                &no_layers()
            )
            .is_empty()
        );
    }

    #[test]
    fn visible_sprite_emits_quad_with_sentinel_uv() {
        let s = sprite(10.0, 20.0, 100.0, 50.0, [0.5, 0.5, 0.5, 0.75]);
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].vertices.len(), 4);
        assert_eq!(calls[0].indices, vec![0, 1, 2, 0, 2, 3]);
        for v in &calls[0].vertices {
            assert!(v.uv[0] < 0.0, "sentinel u should be negative");
            assert!((v.uv[1] - 0.75).abs() < 1e-5, "alpha carried in v");
            assert_eq!(v.color, [0.5, 0.5, 0.5]);
        }
        assert_eq!(calls[0].vertices[0].pos, [10.0, 20.0]);
        assert_eq!(calls[0].vertices[2].pos, [110.0, 70.0]);
    }

    // A fully transparent fill normally skips the sprite, but a visible
    // border keeps it: the border ring alone draws (an outline sprite).
    #[test]
    fn transparent_fill_draws_when_a_border_is_set() {
        let invisible = sprite(0.0, 0.0, 100.0, 50.0, [0.0, 0.0, 0.0, 0.0]);
        assert!(
            build_sprite_calls(
                core::slice::from_ref(&invisible),
                Some(0),
                &no_slots(),
                [0.0, 0.0],
                &no_clips(),
                &no_layers()
            )
            .is_empty(),
            "borderless transparent fill still skips"
        );

        let mut outline = sprite(0.0, 0.0, 100.0, 50.0, [0.0, 0.0, 0.0, 0.0]);
        outline.border_width = 2.0;
        outline.border_color = [0.2, 0.4, 0.9, 1.0];
        let calls = build_sprite_calls(
            core::slice::from_ref(&outline),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls.len(), 1, "the border ring draws");
        // Four edge strips, every vertex in the border colour at full alpha:
        // nothing is drawn inside the ring, so the object shows through.
        let verts = &calls[0].vertices;
        assert_eq!(verts.len(), 16);
        assert!(
            verts
                .iter()
                .all(|v| v.color == [0.2, 0.4, 0.9] && v.uv == [-1.0, 1.0])
        );
        let inside = |x: f32, y: f32| {
            calls[0].indices.chunks(3).any(|t| {
                let p: Vec<[f32; 2]> = t.iter().map(|&i| verts[i as usize].pos).collect();
                point_in_triangle([x, y], p[0], p[1], p[2])
            })
        };
        assert!(inside(50.0, 1.0), "the top strip covers the edge");
        assert!(inside(1.0, 25.0), "the left strip covers the edge");
        assert!(!inside(50.0, 25.0), "the interior is empty");

        // An opaque fill keeps the inset-fill stroke (rounded borders rely
        // on it).
        let mut panel = sprite(0.0, 0.0, 100.0, 50.0, [0.1, 0.1, 0.1, 1.0]);
        panel.border_width = 2.0;
        panel.border_color = [0.2, 0.4, 0.9, 1.0];
        let calls = build_sprite_calls(
            core::slice::from_ref(&panel),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls[0].vertices.len(), 8);
    }

    // A translucent panel is a wash over whatever is behind it, so nothing may
    // be drawn under its fill: the stroke is a hollow ring, not a slab of the
    // border colour with the fill laid over it.
    #[test]
    fn a_translucent_fill_is_not_backed_by_its_border() {
        let mut panel = sprite(0.0, 0.0, 100.0, 50.0, [0.1, 0.1, 0.12, 0.5]);
        panel.border_width = 2.0;
        panel.border_color = [0.3, 0.32, 0.4, 1.0];
        panel.corner_radius = 8.0;
        let calls = build_sprite_calls(
            core::slice::from_ref(&panel),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls.len(), 1);
        let verts = &calls[0].vertices;
        // Whatever the stroke covers, it never reaches the middle of the panel.
        let covered = |x: f32, y: f32, color: [f32; 3]| {
            calls[0].indices.chunks(3).any(|t| {
                let p: Vec<[f32; 2]> = t.iter().map(|&i| verts[i as usize].pos).collect();
                t.iter().all(|&i| verts[i as usize].color == color)
                    && point_in_triangle([x, y], p[0], p[1], p[2])
            })
        };
        let border = [0.3, 0.32, 0.4];
        let fill = [0.1, 0.1, 0.12];
        assert!(covered(50.0, 1.0, border), "the stroke covers the edge");
        assert!(
            !covered(50.0, 25.0, border),
            "and leaves the middle to the wash"
        );
        assert!(covered(50.0, 25.0, fill), "which draws there at its alpha");
        assert!(
            verts
                .iter()
                .filter(|v| v.color == fill)
                .any(|v| (v.uv[1] - 0.5).abs() < 1e-5),
            "the wash keeps its own alpha"
        );

        // The stroke's outer edge feathers to nothing like the fill's does.
        let border_alphas: Vec<f32> = verts
            .iter()
            .filter(|v| v.color == border)
            .map(|v| v.uv[1])
            .collect();
        assert!(border_alphas.contains(&0.0));
        assert!(border_alphas.iter().any(|&a| (a - 1.0).abs() < 1e-5));

        // A stroke wider than the corner radius keeps its full width.
        panel.corner_radius = 2.0;
        panel.border_width = 6.0;
        let calls = build_sprite_calls(
            core::slice::from_ref(&panel),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        let verts = &calls[0].vertices;
        let covered = |x: f32, y: f32, color: [f32; 3]| {
            calls[0].indices.chunks(3).any(|t| {
                let p: Vec<[f32; 2]> = t.iter().map(|&i| verts[i as usize].pos).collect();
                t.iter().all(|&i| verts[i as usize].color == color)
                    && point_in_triangle([x, y], p[0], p[1], p[2])
            })
        };
        assert!(covered(50.0, 5.9, border));
        assert!(!covered(50.0, 6.1, border));

        // A square-cornered translucent panel takes the straight-strip stroke.
        panel.border_width = 2.0;
        panel.corner_radius = 0.0;
        let calls = build_sprite_calls(
            core::slice::from_ref(&panel),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        let verts = &calls[0].vertices;
        assert_eq!(verts.len(), 4 + 16, "one quad of fill, four edge strips");
    }

    fn point_in_triangle(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool {
        let sign = |p: [f32; 2], q: [f32; 2], r: [f32; 2]| {
            (p[0] - r[0]) * (q[1] - r[1]) - (q[0] - r[0]) * (p[1] - r[1])
        };
        let (d1, d2, d3) = (sign(p, a, b), sign(p, b, c), sign(p, c, a));
        let neg = d1 < 0.0 || d2 < 0.0 || d3 < 0.0;
        let pos = d1 > 0.0 || d2 > 0.0 || d3 > 0.0;
        !(neg && pos)
    }

    #[test]
    fn textured_sprite_emits_real_uvs_and_its_slot() {
        let mut s = sprite(10.0, 20.0, 100.0, 50.0, [1.0, 0.9, 0.8, 0.75]);
        s.texture = Some(TextureHandle(42));
        let mut slots = no_slots();
        slots.insert(TextureHandle(42), 3);
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &slots,
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls.len(), 1);
        // The call binds the sprite texture's atlas slot, not the font's.
        assert_eq!(calls[0].atlas_slot, 3);
        let vs = &calls[0].vertices;
        assert_eq!(vs[0].uv, [0.0, 0.0]);
        assert_eq!(vs[1].uv, [1.0, 0.0]);
        assert_eq!(vs[2].uv, [1.0, 1.0]);
        assert_eq!(vs[3].uv, [0.0, 1.0]);
        for v in vs {
            // Tint in color, alpha in the mode flag (> 0 = textured).
            assert_eq!(v.color, [1.0, 0.9, 0.8]);
            assert!((v.mode - 0.75).abs() < 1e-5);
        }
    }

    #[test]
    fn rounded_sprite_tessellates_with_a_feathered_edge() {
        let mut s = sprite(100.0, 100.0, 400.0, 200.0, [0.1, 0.2, 0.3, 0.9]);
        s.corner_radius = 20.0;
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls.len(), 1);
        let vs = &calls[0].vertices;
        // An inner solid ring and an outer transparent ring, 4 corner arcs of
        // CORNER_SEGMENTS + 1 points each.
        let ring = 4 * (CORNER_SEGMENTS + 1);
        assert_eq!(vs.len(), 2 * ring);
        for v in &vs[..ring] {
            assert!(
                (v.uv[1] - 0.9).abs() < 1e-5,
                "inner ring carries the tint alpha"
            );
        }
        for v in &vs[ring..] {
            assert!(v.uv[1].abs() < 1e-5, "outer ring fades to transparent");
        }
        // Every vertex stays inside the authored rect, and the outer ring
        // reaches the rect edges at the flat sides.
        for v in vs {
            assert!(v.pos[0] >= 100.0 - 1e-3 && v.pos[0] <= 500.0 + 1e-3);
            assert!(v.pos[1] >= 100.0 - 1e-3 && v.pos[1] <= 300.0 + 1e-3);
        }
        let min_x = vs.iter().map(|v| v.pos[0]).fold(f32::MAX, f32::min);
        assert!((min_x - 100.0).abs() < 1e-3);
        // The corner point itself is never touched: the arc cuts it off.
        assert!(!vs.iter().any(|v| v.pos == [100.0, 100.0]));
    }

    #[test]
    fn bordered_sprite_emits_a_border_ring_and_an_inset_fill() {
        let mut s = sprite(100.0, 100.0, 200.0, 120.0, [0.1, 0.2, 0.3, 1.0]);
        s.border_width = 2.0;
        s.border_color = [0.8, 0.4, 0.2, 1.0];
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls.len(), 1);
        let vs = &calls[0].vertices;
        // Both the border-coloured outer layer and the tinted fill are present.
        assert!(
            vs.iter().any(|v| v.color == [0.8, 0.4, 0.2]),
            "border colour present"
        );
        assert!(
            vs.iter().any(|v| v.color == [0.1, 0.2, 0.3]),
            "fill colour present"
        );
        // The border reaches the authored outer edge; the tinted fill is inset
        // by the stroke width on every side.
        let outer_min_x = vs.iter().map(|v| v.pos[0]).fold(f32::MAX, f32::min);
        let outer_max_x = vs.iter().map(|v| v.pos[0]).fold(f32::MIN, f32::max);
        assert!(
            (outer_min_x - 100.0).abs() < 1e-3,
            "border at the left edge"
        );
        assert!(
            (outer_max_x - 300.0).abs() < 1e-3,
            "border at the right edge"
        );
        let fill_min_x = vs
            .iter()
            .filter(|v| v.color == [0.1, 0.2, 0.3])
            .map(|v| v.pos[0])
            .fold(f32::MAX, f32::min);
        assert!(
            (fill_min_x - 102.0).abs() < 1e-3,
            "fill inset by the stroke width"
        );
    }

    #[test]
    fn zero_border_stays_a_single_layer() {
        let mut s = sprite(0.0, 0.0, 100.0, 100.0, [0.2, 0.3, 0.4, 1.0]);
        // A colour but no width draws no border (just the fill quad).
        s.border_width = 0.0;
        s.border_color = [1.0, 0.0, 0.0, 1.0];
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(
            calls[0].vertices.len(),
            4,
            "one plain quad, no border layer"
        );
        assert!(calls[0].vertices.iter().all(|v| v.color == [0.2, 0.3, 0.4]));
    }

    #[test]
    fn rounded_view_sprite_scales_its_radius_with_the_window() {
        // A 2x window doubles the radius: the outer ring's leftmost point
        // sits at the transformed rect's left edge, and the top-left corner
        // arc starts (2 * radius) transformed pixels down from the rect top.
        let mut s = sprite(100.0, 100.0, 400.0, 200.0, [0.1, 0.2, 0.3, 0.9]);
        s.screen = Some(AssetId(7));
        s.corner_radius = 20.0;
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [2.0 * UI_REFERENCE_SIZE[0], 2.0 * UI_REFERENCE_SIZE[1]],
            &no_clips(),
            &no_layers(),
        );
        let vs = &calls[0].vertices;
        let min_x = vs.iter().map(|v| v.pos[0]).fold(f32::MAX, f32::min);
        let top_left_arc_y = vs
            .iter()
            .filter(|v| (v.pos[0] - min_x).abs() < 1e-3)
            .map(|v| v.pos[1])
            .fold(f32::MAX, f32::min);
        assert!((min_x - 200.0).abs() < 1e-3);
        assert!((top_left_arc_y - (200.0 + 40.0)).abs() < 1e-3);
    }

    #[test]
    fn textured_sprite_without_a_loaded_texture_falls_back_to_fill() {
        let mut s = sprite(0.0, 0.0, 10.0, 10.0, [0.2, 0.3, 0.4, 1.0]);
        s.texture = Some(TextureHandle(42));
        // The texture never made it into the atlas pool: solid-fill sentinel.
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(5),
            &no_slots(),
            [0.0, 0.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls[0].atlas_slot, 5);
        assert!(calls[0].vertices[0].uv[0] < 0.0);
        assert_eq!(calls[0].vertices[0].mode, 0.0);
    }

    #[test]
    fn invisible_sprite_is_skipped() {
        let mut s = sprite(0.0, 0.0, 100.0, 100.0, [1.0, 1.0, 1.0, 1.0]);
        s.visible = false;
        assert!(
            build_sprite_calls(
                core::slice::from_ref(&s),
                Some(0),
                &no_slots(),
                [0.0, 0.0],
                &no_clips(),
                &no_layers()
            )
            .is_empty()
        );
    }

    #[test]
    fn zero_alpha_sprite_is_skipped() {
        let s = sprite(0.0, 0.0, 100.0, 100.0, [1.0, 1.0, 1.0, 0.0]);
        assert!(
            build_sprite_calls(
                core::slice::from_ref(&s),
                Some(0),
                &no_slots(),
                [0.0, 0.0],
                &no_clips(),
                &no_layers()
            )
            .is_empty()
        );
    }

    #[test]
    fn view_owned_sprite_scales_to_window() {
        // A view-owned (overlay) sprite is authored in the reference canvas and
        // uniformly scaled onto the window. At twice the reference size the
        // rect doubles and stays centered.
        let mut s = sprite(100.0, 100.0, 200.0, 100.0, [1.0, 1.0, 1.0, 1.0]);
        s.screen = Some(AssetId(7));
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [2560.0, 1440.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].vertices[0].pos, [200.0, 200.0]);
        assert_eq!(calls[0].vertices[2].pos, [600.0, 400.0]);
    }

    #[test]
    fn view_owned_full_canvas_backdrop_fills_window() {
        // A view-owned sprite spanning the whole reference canvas is a
        // full-screen backdrop: it fills the live window rather than letterboxing.
        let mut s = sprite(0.0, 0.0, 1280.0, 720.0, [0.0, 0.0, 0.0, 0.5]);
        s.screen = Some(AssetId(7));
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [2560.0, 1440.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].vertices[0].pos, [0.0, 0.0]);
        assert_eq!(calls[0].vertices[2].pos, [2560.0, 1440.0]);
    }

    #[test]
    fn cover_sprite_fills_the_window_and_crops_the_overflow() {
        // On a 4:3 window the 16:9 canvas covers by the height ratio
        // (768/720): vertical edges land exactly on the window edges,
        // horizontal overflow is cropped equally on both sides.
        let mut s = sprite(0.0, 0.0, 1280.0, 720.0, [1.0, 1.0, 1.0, 1.0]);
        s.screen = Some(AssetId(7));
        s.fit = SpriteFit::Cover;
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [1024.0, 768.0],
            &no_clips(),
            &no_layers(),
        );
        let scale = 768.0 / 720.0;
        let overflow = (1280.0 * scale - 1024.0) / 2.0;
        let vs = &calls[0].vertices;
        assert!(
            (vs[0].pos[0] - -overflow).abs() < 1e-3,
            "x0={}",
            vs[0].pos[0]
        );
        assert!((vs[0].pos[1]).abs() < 1e-3, "y0={}", vs[0].pos[1]);
        assert!(
            (vs[2].pos[0] - (1024.0 + overflow)).abs() < 1e-3,
            "x1={}",
            vs[2].pos[0]
        );
        assert!((vs[2].pos[1] - 768.0).abs() < 1e-3, "y1={}", vs[2].pos[1]);
    }

    #[test]
    fn cover_sprite_anchored_to_the_canvas_bottom_stays_flush() {
        // A bottom-anchored partial-canvas sprite (a character portrait): its
        // bottom edge maps exactly to the window bottom on a window taller
        // than the reference aspect.
        let mut s = sprite(400.0, 100.0, 480.0, 620.0, [1.0, 1.0, 1.0, 1.0]);
        s.screen = Some(AssetId(7));
        s.fit = SpriteFit::Cover;
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [1024.0, 768.0],
            &no_clips(),
            &no_layers(),
        );
        let bottom = calls[0].vertices[2].pos[1];
        assert!((bottom - 768.0).abs() < 1e-3, "bottom={bottom}");
    }

    #[test]
    fn view_less_sprite_keeps_literal_pixels() {
        // A HUD / scene sprite (view == None) is never overlay-scaled.
        let s = sprite(10.0, 20.0, 100.0, 50.0, [0.5, 0.5, 0.5, 1.0]);
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [2560.0, 1440.0],
            &no_clips(),
            &no_layers(),
        );
        assert_eq!(calls[0].vertices[0].pos, [10.0, 20.0]);
        assert_eq!(calls[0].vertices[2].pos, [110.0, 70.0]);
    }

    #[test]
    fn clipped_element_carries_window_space_clip_rect() {
        // A view-owned sprite whose id is in the clips map gets a clip_rect
        // mapped from the reference-space band through the overlay; one not in
        // the map stays unclipped.
        let mut s = sprite(100.0, 100.0, 50.0, 50.0, [1.0, 1.0, 1.0, 1.0]);
        s.asset_id = AssetId(7);
        s.screen = Some(AssetId(1));
        let mut clips = no_clips();
        // Reference band [200,200] size [200,60] at a 2x viewport (1280x720 ->
        // 2560x1440, scale 2 about the centre): forward(200,200)=(400,400),
        // forward(400,260)=(800,520) -> clip [400,400,400,120].
        clips.insert(AssetId(7), [200.0, 200.0, 200.0, 60.0]);
        let calls = build_sprite_calls(
            core::slice::from_ref(&s),
            Some(0),
            &no_slots(),
            [2560.0, 1440.0],
            &clips,
            &no_layers(),
        );
        let clip = calls[0].clip_rect.expect("clipped sprite has a clip rect");
        assert!((clip[0] - 400.0).abs() < 1e-3, "x={}", clip[0]);
        assert!((clip[1] - 400.0).abs() < 1e-3, "y={}", clip[1]);
        assert!((clip[2] - 400.0).abs() < 1e-3, "w={}", clip[2]);
        assert!((clip[3] - 120.0).abs() < 1e-3, "h={}", clip[3]);

        // A sprite not in the clips map is unclipped.
        let mut other = sprite(0.0, 0.0, 10.0, 10.0, [1.0, 1.0, 1.0, 1.0]);
        other.asset_id = AssetId(9);
        other.screen = Some(AssetId(1));
        let calls = build_sprite_calls(
            core::slice::from_ref(&other),
            Some(0),
            &no_slots(),
            [2560.0, 1440.0],
            &clips,
            &no_layers(),
        );
        assert!(calls[0].clip_rect.is_none());
    }

    // A sprite's call carries the draw layer its id maps to (used by the editor's
    // panel occlusion sort); an id absent from the map draws at layer 0.
    #[test]
    fn sprite_call_takes_its_layer_from_the_map() {
        let mut mapped = sprite(0.0, 0.0, 10.0, 10.0, [1.0, 1.0, 1.0, 1.0]);
        mapped.asset_id = AssetId(42);
        let mut layers = OverlayLayers::new();
        layers.insert(AssetId(42), 7);
        let calls = build_sprite_calls(
            core::slice::from_ref(&mapped),
            Some(0),
            &no_slots(),
            [100.0, 100.0],
            &no_clips(),
            &layers,
        );
        assert_eq!(calls[0].layer, 7);

        let mut unmapped = sprite(0.0, 0.0, 10.0, 10.0, [1.0, 1.0, 1.0, 1.0]);
        unmapped.asset_id = AssetId(99);
        let calls = build_sprite_calls(
            core::slice::from_ref(&unmapped),
            Some(0),
            &no_slots(),
            [100.0, 100.0],
            &no_clips(),
            &layers,
        );
        assert_eq!(calls[0].layer, 0, "an unmapped id is layer 0");
    }

    // A `follow_cursor` sprite is the cursor pass's silhouette source, never a
    // scene quad, so the whole component slice can be passed in.
    #[test]
    fn follow_cursor_sprites_are_skipped() {
        let mut s = sprite(0.0, 0.0, 10.0, 10.0, [1.0, 1.0, 1.0, 1.0]);
        s.follow_cursor = true;
        assert!(
            build_sprite_calls(
                core::slice::from_ref(&s),
                Some(0),
                &no_slots(),
                [0.0, 0.0],
                &no_clips(),
                &no_layers()
            )
            .is_empty()
        );
    }
}