mireforge-render-wgpu 0.0.27

render pixel perfect 2D sprites
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
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
/*
 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/mireforge/mireforge
 * Licensed under the MIT License. See LICENSE in the project root for license information.
 */
mod gfx;
mod gfx_impl;
pub mod plugin;
pub mod prelude;

use int_math::{URect, UVec2, Vec2, Vec3};
use limnus_assets::Assets;
use limnus_assets::prelude::{Asset, Id, WeakId};
use limnus_resource::prelude::Resource;
use limnus_wgpu_math::{Matrix4, OrthoInfo, Vec4};
use mireforge_font::Font;
use mireforge_font::FontRef;
use mireforge_font::WeakFontRef;
use mireforge_render::prelude::*;
use mireforge_wgpu::create_nearest_sampler;
use mireforge_wgpu_sprites::{
    ShaderInfo, SpriteInfo, SpriteInstanceUniform, create_texture_and_sampler_bind_group_ex,
    create_texture_and_sampler_group_layout,
};
use monotonic_time_rs::Millis;
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter};
use std::mem::swap;
use std::sync::Arc;
use tracing::{debug, trace};
use wgpu::{
    BindGroup, BindGroupLayout, Buffer, CommandEncoder, Device, RenderPipeline, TextureFormat,
    TextureView,
};

pub type MaterialRef = Arc<Material>;

pub type WeakMaterialRef = Arc<Material>;

pub type TextureRef = Id<Texture>;
pub type WeakTextureRef = WeakId<Texture>;

pub trait FrameLookup {
    fn lookup(&self, frame: u16) -> (&MaterialRef, URect);
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FixedAtlas {
    pub material: MaterialRef,
    pub texture_size: UVec2,
    pub one_cell_size: UVec2,
    pub cell_count_size: UVec2,
}

impl FixedAtlas {
    /// # Panics
    ///
    #[must_use]
    pub fn new(one_cell_size: UVec2, texture_size: UVec2, material_ref: MaterialRef) -> Self {
        let cell_count_size = UVec2::new(
            texture_size.x / one_cell_size.x,
            texture_size.y / one_cell_size.y,
        );

        assert_ne!(cell_count_size.x, 0, "illegal texture and one cell size");

        Self {
            material: material_ref,
            texture_size,
            one_cell_size,
            cell_count_size,
        }
    }
}

impl FrameLookup for FixedAtlas {
    fn lookup(&self, frame: u16) -> (&MaterialRef, URect) {
        let x = frame % self.cell_count_size.x;
        let y = frame / self.cell_count_size.x;

        (
            &self.material,
            URect::new(
                x * self.one_cell_size.x,
                y * self.one_cell_size.y,
                self.one_cell_size.x,
                self.one_cell_size.y,
            ),
        )
    }
}

#[derive(Debug)]
pub struct NineSliceAndMaterial {
    pub slices: Slices,
    pub material_ref: MaterialRef,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct FontAndMaterial {
    pub font_ref: FontRef,
    pub material_ref: MaterialRef,
}

fn to_wgpu_color(c: Color) -> wgpu::Color {
    let f = c.to_f64();
    wgpu::Color {
        r: f.0,
        g: f.1,
        b: f.2,
        a: f.3,
    }
}

#[derive(Debug)]
struct RenderItem {
    position: Vec3,
    material_ref: MaterialRef,

    renderable: Renderable,
}

#[derive(Debug)]
pub struct Text {
    text: String,
    font_ref: WeakFontRef,
    color: Color,
}

#[derive(Debug)]
enum Renderable {
    Sprite(Sprite),
    QuadColor(QuadColor),
    NineSlice(NineSlice),
    NineSliceStretch(NineSlice),
    TileMap(TileMap),
    Text(Text),
    Mask(UVec2, Color),
}

const MAXIMUM_QUADS_FOR_RENDER_ITEM: usize = 1024;
const MAXIMUM_QUADS_IN_A_BATCH: usize = 4096;
const MAXIMUM_QUADS_IN_ONE_RENDER: usize = MAXIMUM_QUADS_IN_A_BATCH * 8;

#[derive(Resource)]
pub struct Render {
    virtual_surface_texture_view: TextureView,
    virtual_surface_texture: wgpu::Texture,
    virtual_to_surface_bind_group: BindGroup,
    index_buffer: Buffer,  // Only indices for a single identity quad
    vertex_buffer: Buffer, // Only one identity quad (0,0,1,1)
    sampler: wgpu::Sampler,
    virtual_to_screen_shader_info: ShaderInfo,
    pub normal_sprite_pipeline: ShaderInfo,
    pub quad_shader_info: ShaderInfo,
    pub mask_shader_info: ShaderInfo,
    pub light_shader_info: ShaderInfo,
    physical_surface_size: UVec2,
    viewport_strategy: ViewportStrategy,
    virtual_surface_size: UVec2,
    // Group 0
    camera_bind_group: BindGroup,
    #[allow(unused)]
    camera_buffer: Buffer,

    // Group 1
    texture_sampler_bind_group_layout: BindGroupLayout,

    // Group 1
    quad_matrix_and_uv_instance_buffer: Buffer,

    device: Arc<wgpu::Device>,
    queue: Arc<wgpu::Queue>, // Queue to talk to device

    // Internals
    items: Vec<RenderItem>,
    //fonts: Vec<FontAndMaterialRef>,
    origin: Vec2,

    // Cache
    batch_offsets: Vec<(WeakMaterialRef, u32, u32)>,
    viewport: URect,
    clear_color: wgpu::Color,
    screen_clear_color: wgpu::Color,
    last_render_at: Millis,
    scale: f32,
    surface_texture_format: TextureFormat,
    debug_tick: u64,
}

impl Render {}

impl Debug for Render {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Render")
    }
}

impl Render {
    #[must_use]
    pub fn new(
        device: Arc<wgpu::Device>,
        queue: Arc<wgpu::Queue>, // Queue to talk to device
        surface_texture_format: wgpu::TextureFormat,
        physical_size: UVec2,
        virtual_surface_size: UVec2,
        now: Millis,
    ) -> Self {
        let sprite_info = SpriteInfo::new(
            &device,
            surface_texture_format,
            create_view_uniform_view_projection_matrix(physical_size),
        );

        let (virtual_surface_texture, virtual_surface_texture_view, virtual_to_surface_bind_group) =
            Self::create_virtual_texture(&device, surface_texture_format, virtual_surface_size);

        Self {
            device,
            queue,
            surface_texture_format,
            items: Vec::new(),
            //   fonts: Vec::new(),
            virtual_to_screen_shader_info: sprite_info.virtual_to_screen_shader_info,
            virtual_surface_texture,
            virtual_surface_texture_view,
            virtual_to_surface_bind_group,
            sampler: sprite_info.sampler,
            normal_sprite_pipeline: sprite_info.sprite_shader_info,
            quad_shader_info: sprite_info.quad_shader_info,
            mask_shader_info: sprite_info.mask_shader_info,
            light_shader_info: sprite_info.light_shader_info,
            texture_sampler_bind_group_layout: sprite_info.sprite_texture_sampler_bind_group_layout,
            index_buffer: sprite_info.index_buffer,
            vertex_buffer: sprite_info.vertex_buffer,
            quad_matrix_and_uv_instance_buffer: sprite_info.quad_matrix_and_uv_instance_buffer,
            camera_bind_group: sprite_info.camera_bind_group,
            batch_offsets: Vec::new(),
            camera_buffer: sprite_info.camera_uniform_buffer,
            viewport: Self::viewport_from_integer_scale(physical_size, virtual_surface_size),
            clear_color: to_wgpu_color(Color::from_f32(0.008, 0.015, 0.008, 1.0)),
            screen_clear_color: to_wgpu_color(Color::from_f32(0.018, 0.025, 0.018, 1.0)),
            origin: Vec2::new(0, 0),
            last_render_at: now,
            physical_surface_size: physical_size,
            viewport_strategy: ViewportStrategy::FitIntegerScaling,
            virtual_surface_size,
            scale: 1.0,
            debug_tick: 0,
        }
    }

    #[must_use]
    pub fn create_virtual_texture(
        device: &Device,
        surface_texture_format: TextureFormat,
        virtual_surface_size: UVec2,
    ) -> (wgpu::Texture, TextureView, BindGroup) {
        // Create a texture at your virtual resolution (e.g., 320x240)
        let virtual_surface_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Render Texture"),
            size: wgpu::Extent3d {
                width: u32::from(virtual_surface_size.x),
                height: u32::from(virtual_surface_size.y),
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: surface_texture_format, // TODO: Check: Should probably always be same as swap chain format?
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });

        let virtual_surface_texture_view =
            virtual_surface_texture.create_view(&wgpu::TextureViewDescriptor::default());

        let virtual_to_screen_sampler =
            create_nearest_sampler(device, "nearest sampler for virtual to screen");
        let virtual_to_screen_layout =
            create_texture_and_sampler_group_layout(device, "virtual to screen layout");
        let virtual_to_surface_bind_group = create_texture_and_sampler_bind_group_ex(
            device,
            &virtual_to_screen_layout,
            &virtual_surface_texture_view,
            &virtual_to_screen_sampler,
            "virtual to screen bind group",
        );

        (
            virtual_surface_texture,
            virtual_surface_texture_view,
            virtual_to_surface_bind_group,
        )
    }

    pub const fn set_now(&mut self, now: Millis) {
        self.last_render_at = now;
    }

    #[must_use]
    pub const fn virtual_surface_size_with_scaling(&self) -> UVec2 {
        match self.viewport_strategy {
            ViewportStrategy::FitIntegerScaling | ViewportStrategy::FitFloatScaling => {
                self.virtual_surface_size
            }
            ViewportStrategy::MatchPhysicalSize => self.physical_surface_size,
        }
    }

    #[must_use]
    pub const fn physical_surface_size(&self) -> UVec2 {
        self.physical_surface_size
    }

    #[must_use]
    pub const fn viewport(&self) -> URect {
        self.viewport
    }

    #[inline]
    fn push_sprite(&mut self, position: Vec3, material: &MaterialRef, sprite: Sprite) {
        self.items.push(RenderItem {
            position,
            material_ref: material.clone(),
            renderable: Renderable::Sprite(sprite),
        });
    }

    pub fn push_mask(
        &mut self,
        position: Vec3,
        size: UVec2,
        color: Color,
        alpha_masked: &MaterialRef,
    ) {
        self.items.push(RenderItem {
            position,
            material_ref: alpha_masked.clone(),
            renderable: Renderable::Mask(size, color),
        });
    }

    pub fn push_mask_create_material(
        &mut self,
        position: Vec3,
        primary_texture: TextureRef,
        alpha_texture: TextureRef,
        texture_offset: UVec2,
        color: Color,
    ) {
        let masked_material = Material {
            base: MaterialBase {},
            kind: MaterialKind::AlphaMasker {
                primary_texture,
                alpha_texture,
            },
        };

        let masked_material_ref = Arc::new(masked_material);

        self.items.push(RenderItem {
            position,
            material_ref: masked_material_ref,
            renderable: Renderable::Mask(texture_offset, color),
        });
    }

    pub fn push_nine_slice(
        &mut self,
        position: Vec3,
        size: UVec2,
        color: Color,
        nine_slice_and_material: &NineSliceAndMaterial,
    ) {
        let nine_slice_info = NineSlice {
            size,
            slices: nine_slice_and_material.slices,
            color,
            origin_in_atlas: UVec2::new(0, 0),
            size_inside_atlas: None,
        };

        self.items.push(RenderItem {
            position,
            material_ref: nine_slice_and_material.material_ref.clone(),
            renderable: Renderable::NineSlice(nine_slice_info),
        });
    }

    pub fn push_nine_slice_stretch(
        &mut self,
        position: Vec3,
        size: UVec2,
        color: Color,
        nine_slice_and_material: &NineSliceAndMaterial,
    ) {
        let nine_slice_info = NineSlice {
            size,
            slices: nine_slice_and_material.slices,
            color,
            origin_in_atlas: UVec2::new(0, 0),
            size_inside_atlas: None,
        };

        self.items.push(RenderItem {
            position,
            material_ref: nine_slice_and_material.material_ref.clone(),
            renderable: Renderable::NineSliceStretch(nine_slice_info),
        });
    }

    #[must_use]
    pub fn viewport_from_integer_scale(physical_size: UVec2, virtual_size: UVec2) -> URect {
        let scale_factor = (physical_size.x / virtual_size.x)
            .min(physical_size.y / virtual_size.y)
            .max(1);

        let ideal_viewport_size = virtual_size * scale_factor;

        let final_viewport_size =
            if physical_size.x < ideal_viewport_size.x || physical_size.y < ideal_viewport_size.y {
                physical_size
            } else {
                ideal_viewport_size
            };

        let border_size = physical_size - final_viewport_size;

        let offset = border_size / 2;

        URect::new(
            offset.x,
            offset.y,
            final_viewport_size.x,
            final_viewport_size.y,
        )
    }

    #[must_use]
    pub fn viewport_from_float_scale(physical_size: UVec2, virtual_size: UVec2) -> URect {
        let window_aspect = f32::from(physical_size.x) / f32::from(physical_size.y);
        let virtual_aspect = f32::from(virtual_size.x) / f32::from(virtual_size.y);

        if physical_size.x < virtual_size.x || physical_size.y < virtual_size.y {
            return URect::new(0, 0, physical_size.x, physical_size.y);
        }

        let mut float_scale = if window_aspect > virtual_aspect {
            f32::from(physical_size.y) / f32::from(virtual_size.y)
        } else {
            f32::from(physical_size.x) / f32::from(virtual_size.x)
        };

        if float_scale < 0.01 {
            float_scale = 0.01;
        }

        let viewport_actual_size = UVec2::new(
            (f32::from(virtual_size.x) * float_scale) as u16,
            (f32::from(virtual_size.y) * float_scale) as u16,
        );

        let border_size = physical_size - viewport_actual_size;

        let offset = border_size / 2;

        URect::new(
            offset.x,
            offset.y,
            viewport_actual_size.x,
            viewport_actual_size.y,
        )
    }

    pub const fn resize(&mut self, physical_size: UVec2) {
        self.physical_surface_size = physical_size;
    }

    pub fn resize_virtual(&mut self, virtual_surface_size: UVec2) {
        if virtual_surface_size == self.virtual_surface_size {
            return;
        }
        self.virtual_surface_size = virtual_surface_size;
        debug!(?virtual_surface_size, "virtual surface changed");
        let (virtual_surface_texture, virtual_surface_texture_view, virtual_to_surface_bind_group) =
            Self::create_virtual_texture(
                &self.device,
                self.surface_texture_format,
                virtual_surface_size,
            );
        self.virtual_surface_texture = virtual_surface_texture;
        self.virtual_surface_texture_view = virtual_surface_texture_view;
        self.virtual_to_surface_bind_group = virtual_to_surface_bind_group;
    }

    pub fn sprite_atlas(&mut self, position: Vec3, atlas_rect: URect, material_ref: &MaterialRef) {
        self.push_sprite(
            position,
            material_ref,
            Sprite {
                params: SpriteParams {
                    texture_pos: atlas_rect.position,
                    texture_size: atlas_rect.size,
                    ..Default::default()
                },
            },
        );
    }

    pub fn sprite_atlas_frame(&mut self, position: Vec3, frame: u16, atlas: &impl FrameLookup) {
        let (material_ref, atlas_rect) = atlas.lookup(frame);
        self.push_sprite(
            position,
            material_ref,
            Sprite {
                params: SpriteParams {
                    texture_pos: atlas_rect.position,
                    texture_size: atlas_rect.size,
                    ..Default::default()
                },
            },
        );
    }

    pub fn sprite_atlas_frame_ex(
        &mut self,
        position: Vec3,
        frame: u16,
        atlas: &impl FrameLookup,
        mut params: SpriteParams,
    ) {
        let (material_ref, atlas_rect) = atlas.lookup(frame);
        params.texture_pos = atlas_rect.position;
        params.texture_size = atlas_rect.size;
        self.push_sprite(position, material_ref, Sprite { params });
    }

    pub fn draw_sprite(&mut self, position: Vec3, material: &MaterialRef) {
        self.push_sprite(
            position,
            material,
            Sprite {
                params: SpriteParams::default(),
            },
        );
    }

    pub fn draw_sprite_ex(&mut self, position: Vec3, material: &MaterialRef, params: SpriteParams) {
        self.push_sprite(position, material, Sprite { params });
    }

    pub fn nine_slice(
        &mut self,
        position: Vec3,
        size: UVec2,
        color: Color,
        nine_slice_and_material: &NineSliceAndMaterial,
    ) {
        self.push_nine_slice(position, size, color, nine_slice_and_material);
    }

    pub fn nine_slice_stretch(
        &mut self,
        position: Vec3,
        size: UVec2,
        color: Color,
        nine_slice_and_material: &NineSliceAndMaterial,
    ) {
        self.push_nine_slice_stretch(position, size, color, nine_slice_and_material);
    }

    pub fn draw_quad(&mut self, position: Vec3, size: UVec2, color: Color) {
        let material = Material {
            base: MaterialBase {},
            kind: MaterialKind::Quad,
        };

        self.items.push(RenderItem {
            position,
            material_ref: MaterialRef::from(material),
            renderable: Renderable::QuadColor(QuadColor {
                size,
                color,
                params: QuadParams::default(),
            }),
        });
    }

    pub fn draw_quad_ex(&mut self, position: Vec3, size: UVec2, color: Color, params: QuadParams) {
        let material = Material {
            base: MaterialBase {},
            kind: MaterialKind::Quad,
        };

        self.items.push(RenderItem {
            position,
            material_ref: MaterialRef::from(material),
            renderable: Renderable::QuadColor(QuadColor {
                size,
                color,
                params,
            }),
        });
    }

    #[allow(clippy::too_many_arguments)]
    pub fn draw_nine_slice(
        &mut self,
        position: Vec3,
        size: UVec2,
        slices: Slices,
        material_ref: &MaterialRef,
        color: Color,
    ) {
        self.items.push(RenderItem {
            position,
            material_ref: material_ref.clone(),
            renderable: Renderable::NineSlice(NineSlice {
                size,
                slices,
                color,
                origin_in_atlas: UVec2::new(0, 0),
                size_inside_atlas: None,
            }),
        });
    }

    #[must_use]
    pub const fn clear_color(&self) -> wgpu::Color {
        self.clear_color
    }

    // first two is multiplier and second pair is offset
    fn calculate_texture_coords_mul_add(atlas_rect: URect, texture_size: UVec2) -> Vec4 {
        let x = f32::from(atlas_rect.position.x) / f32::from(texture_size.x);
        let y = f32::from(atlas_rect.position.y) / f32::from(texture_size.y);
        let width = f32::from(atlas_rect.size.x) / f32::from(texture_size.x);
        let height = f32::from(atlas_rect.size.y) / f32::from(texture_size.y);
        Vec4([width, height, x, y])
    }

    fn order_render_items_in_batches(&mut self) -> Vec<Vec<&RenderItem>> {
        let mut material_batches: Vec<Vec<&RenderItem>> = Vec::new();
        let mut current_batch: Vec<&RenderItem> = Vec::new();
        let mut current_material: Option<MaterialRef> = None;

        for render_item in &self.items {
            if Some(&render_item.material_ref) != current_material.as_ref() {
                if !current_batch.is_empty() {
                    material_batches.push(current_batch.clone());
                    current_batch.clear();
                }
                current_material = Some(render_item.material_ref.clone());
            }
            current_batch.push(render_item);
        }

        if !current_batch.is_empty() {
            material_batches.push(current_batch);
        }

        material_batches
    }

    #[must_use]
    pub fn quad_helper_uniform(
        position: Vec3,
        quad_size: UVec2,
        render_atlas: URect,
        color: Color,

        current_texture_size: UVec2,
    ) -> SpriteInstanceUniform {
        let model_matrix =
            Matrix4::from_translation(f32::from(position.x), f32::from(position.y), 0.0)
                * Matrix4::from_scale(f32::from(quad_size.x), f32::from(quad_size.y), 1.0);

        let tex_coords_mul_add =
            Self::calculate_texture_coords_mul_add(render_atlas, current_texture_size);

        let rotation_value = 0;

        SpriteInstanceUniform::new(
            model_matrix,
            tex_coords_mul_add,
            rotation_value,
            Vec4(color.to_f32_slice()),
        )
    }

    /// # Panics
    ///
    #[allow(clippy::too_many_lines)]
    pub fn write_vertex_indices_and_uv_to_buffer(
        &mut self,
        textures: &Assets<Texture>,
        fonts: &Assets<Font>,
    ) {
        const FLIP_X_MASK: u32 = 0b0000_0100;
        const FLIP_Y_MASK: u32 = 0b0000_1000;

        let batches = self.sort_and_put_in_batches();

        let mut quad_matrix_and_uv: Vec<SpriteInstanceUniform> = Vec::new();
        let mut batch_vertex_ranges: Vec<(MaterialRef, u32, u32)> = Vec::new();

        for render_items in batches {
            let quad_len_before = quad_matrix_and_uv.len();

            // Fix: Access material_ref through reference and copy it
            let weak_material_ref = render_items
                .first()
                .map(|item| {
                    // Force copy semantics by dereferencing the shared reference
                    let material_ref: MaterialRef = item.material_ref.clone();
                    material_ref
                })
                .expect("Render items batch was empty");

            if !weak_material_ref.is_complete(textures) {
                // Material is not loaded yet
                trace!(?weak_material_ref, "material is not complete yet");
                continue;
            }
            let material = weak_material_ref.clone();

            let maybe_texture_ref = material.primary_texture();
            let maybe_texture = maybe_texture_ref
                .and_then(|found_primary_texture_ref| textures.get(&found_primary_texture_ref));

            for render_item in render_items {
                let quad_len_before_inner = quad_matrix_and_uv.len();

                match &render_item.renderable {
                    Renderable::Sprite(sprite) => {
                        let current_texture_size = maybe_texture.unwrap().texture_size;

                        let params = &sprite.params;
                        let mut size = params.texture_size;
                        if size.x == 0 && size.y == 0 {
                            size = current_texture_size;
                        }

                        let render_atlas = URect {
                            position: params.texture_pos,
                            size,
                        };

                        match params.rotation {
                            Rotation::Degrees90 | Rotation::Degrees270 => {
                                swap(&mut size.x, &mut size.y);
                            }
                            _ => {}
                        }

                        let y_offset = if params.anchor == Anchor::UpperLeft {
                            current_texture_size.y as i16
                        } else {
                            0
                        };

                        let model_matrix = Matrix4::from_translation(
                            f32::from(render_item.position.x),
                            f32::from(render_item.position.y - y_offset),
                            0.0,
                        ) * Matrix4::from_scale(
                            f32::from(size.x * u16::from(params.scale)),
                            f32::from(size.y * u16::from(params.scale)),
                            1.0,
                        );

                        let tex_coords_mul_add = Self::calculate_texture_coords_mul_add(
                            render_atlas,
                            current_texture_size,
                        );

                        let mut rotation_value = match params.rotation {
                            Rotation::Degrees0 => 0,
                            Rotation::Degrees90 => 1,
                            Rotation::Degrees180 => 2,
                            Rotation::Degrees270 => 3,
                        };

                        if params.flip_x {
                            rotation_value |= FLIP_X_MASK;
                        }
                        if params.flip_y {
                            rotation_value |= FLIP_Y_MASK;
                        }

                        let quad_instance = SpriteInstanceUniform::new(
                            model_matrix,
                            tex_coords_mul_add,
                            rotation_value,
                            Vec4(params.color.to_f32_slice()),
                        );
                        quad_matrix_and_uv.push(quad_instance);
                    }

                    Renderable::Mask(texture_offset, color) => {
                        let current_texture_size = maybe_texture.unwrap().texture_size;
                        let params = SpriteParams {
                            texture_size: current_texture_size,
                            texture_pos: *texture_offset,
                            scale: 1,
                            rotation: Rotation::default(),
                            flip_x: false,
                            flip_y: false,
                            pivot: Vec2 { x: 0, y: 0 },
                            color: *color,
                            anchor: Anchor::LowerLeft,
                        };

                        let mut size = params.texture_size;
                        if size.x == 0 && size.y == 0 {
                            size = current_texture_size;
                        }

                        let render_atlas = URect {
                            position: params.texture_pos,
                            size,
                        };

                        let model_matrix = Matrix4::from_translation(
                            f32::from(render_item.position.x),
                            f32::from(render_item.position.y),
                            0.0,
                        ) * Matrix4::from_scale(
                            f32::from(size.x * u16::from(params.scale)),
                            f32::from(size.y * u16::from(params.scale)),
                            1.0,
                        );

                        let tex_coords_mul_add = Self::calculate_texture_coords_mul_add(
                            render_atlas,
                            current_texture_size,
                        );

                        let mut rotation_value = match params.rotation {
                            Rotation::Degrees0 => 0,
                            Rotation::Degrees90 => 1,
                            Rotation::Degrees180 => 2,
                            Rotation::Degrees270 => 3,
                        };

                        if params.flip_x {
                            rotation_value |= FLIP_X_MASK;
                        }
                        if params.flip_y {
                            rotation_value |= FLIP_Y_MASK;
                        }

                        let quad_instance = SpriteInstanceUniform::new(
                            model_matrix,
                            tex_coords_mul_add,
                            rotation_value,
                            Vec4(params.color.to_f32_slice()),
                        );
                        quad_matrix_and_uv.push(quad_instance);
                    }

                    Renderable::NineSlice(nine_slice) => {
                        let current_texture_size = maybe_texture.unwrap().texture_size;
                        Self::prepare_nine_slice(
                            nine_slice,
                            render_item.position,
                            &mut quad_matrix_and_uv,
                            current_texture_size,
                        );
                    }

                    Renderable::NineSliceStretch(nine_slice) => {
                        let current_texture_size = maybe_texture.unwrap().texture_size;
                        Self::prepare_nine_slice_single_center_quad(
                            nine_slice,
                            render_item.position,
                            &mut quad_matrix_and_uv,
                            current_texture_size,
                        );
                    }

                    Renderable::QuadColor(quad) => {
                        let model_matrix = Matrix4::from_translation(
                            f32::from(render_item.position.x) - f32::from(quad.params.pivot.x),
                            f32::from(render_item.position.y) - f32::from(quad.params.pivot.y),
                            0.0,
                        ) * Matrix4::from_scale(
                            f32::from(quad.size.x),
                            f32::from(quad.size.y),
                            1.0,
                        );

                        let tex_coords_mul_add = Vec4([
                            0.0, //x
                            0.0, //y
                            0.0, 0.0,
                        ]);
                        let rotation_value = 0;

                        let quad_instance = SpriteInstanceUniform::new(
                            model_matrix,
                            tex_coords_mul_add,
                            rotation_value,
                            Vec4(quad.color.to_f32_slice()),
                        );
                        quad_matrix_and_uv.push(quad_instance);
                    }

                    Renderable::Text(text) => {
                        let current_texture_size = maybe_texture.unwrap().texture_size;
                        let result = fonts.get_weak(text.font_ref);
                        if result.is_none() {
                            continue;
                        }
                        let font = result.unwrap();

                        let glyph_draw = font.draw(&text.text);
                        for glyph in glyph_draw.glyphs {
                            let pos = render_item.position + Vec3::from(glyph.relative_position);
                            let texture_size = glyph.texture_rectangle.size;
                            let model_matrix =
                                Matrix4::from_translation(f32::from(pos.x), f32::from(pos.y), 0.0)
                                    * Matrix4::from_scale(
                                        f32::from(texture_size.x),
                                        f32::from(texture_size.y),
                                        1.0,
                                    );
                            let tex_coords_mul_add = Self::calculate_texture_coords_mul_add(
                                glyph.texture_rectangle,
                                current_texture_size,
                            );

                            let quad_instance = SpriteInstanceUniform::new(
                                model_matrix,
                                tex_coords_mul_add,
                                0,
                                Vec4(text.color.to_f32_slice()),
                            );
                            quad_matrix_and_uv.push(quad_instance);
                        }
                    }

                    Renderable::TileMap(tile_map) => {
                        for (index, tile) in tile_map.tiles.iter().enumerate() {
                            let cell_pos_x = (index as u16 % tile_map.tiles_data_grid_size.x)
                                * tile_map.one_cell_size.x
                                * u16::from(tile_map.scale);
                            let cell_pos_y = (index as u16 / tile_map.tiles_data_grid_size.x)
                                * tile_map.one_cell_size.y
                                * u16::from(tile_map.scale);
                            let cell_x = *tile % tile_map.cell_count_size.x;
                            let cell_y = *tile / tile_map.cell_count_size.x;

                            let tex_x = cell_x * tile_map.one_cell_size.x;
                            let tex_y = cell_y * tile_map.one_cell_size.x;

                            let cell_texture_area = URect::new(
                                tex_x,
                                tex_y,
                                tile_map.one_cell_size.x,
                                tile_map.one_cell_size.y,
                            );

                            let cell_model_matrix = Matrix4::from_translation(
                                f32::from(render_item.position.x + cell_pos_x as i16),
                                f32::from(render_item.position.y + cell_pos_y as i16),
                                0.0,
                            ) * Matrix4::from_scale(
                                f32::from(tile_map.one_cell_size.x * u16::from(tile_map.scale)),
                                f32::from(tile_map.one_cell_size.y * u16::from(tile_map.scale)),
                                1.0,
                            );

                            let current_texture_size = maybe_texture.unwrap().texture_size;
                            let cell_tex_coords_mul_add = Self::calculate_texture_coords_mul_add(
                                cell_texture_area,
                                current_texture_size,
                            );

                            let quad_instance = SpriteInstanceUniform::new(
                                cell_model_matrix,
                                cell_tex_coords_mul_add,
                                0,
                                Vec4([1.0, 1.0, 1.0, 1.0]),
                            );
                            quad_matrix_and_uv.push(quad_instance);
                        }
                    }
                }

                let quad_count_for_this_render_item =
                    quad_matrix_and_uv.len() - quad_len_before_inner;
                assert!(
                    quad_count_for_this_render_item <= MAXIMUM_QUADS_FOR_RENDER_ITEM,
                    "too many quads {quad_count_for_this_render_item} for render item {render_item:?}"
                );
            }

            let quad_count_for_this_batch = quad_matrix_and_uv.len() - quad_len_before;
            assert!(
                quad_count_for_this_batch <= MAXIMUM_QUADS_IN_A_BATCH,
                "too many quads {quad_count_for_this_batch} total to render in this batch"
            );

            assert!(
                quad_matrix_and_uv.len() <= MAXIMUM_QUADS_IN_ONE_RENDER,
                "too many quads for whole render {}",
                quad_matrix_and_uv.len()
            );

            batch_vertex_ranges.push((
                weak_material_ref,
                quad_len_before as u32,
                quad_count_for_this_batch as u32,
            ));
        }

        // write all model_matrix and uv_coords to instance buffer once, before the render pass
        self.queue.write_buffer(
            &self.quad_matrix_and_uv_instance_buffer,
            0,
            bytemuck::cast_slice(&quad_matrix_and_uv),
        );

        self.batch_offsets = batch_vertex_ranges;
    }

    #[allow(clippy::too_many_lines)]
    #[inline]
    pub fn prepare_nine_slice(
        nine_slice: &NineSlice,
        position_offset: Vec3,
        quad_matrix_and_uv: &mut Vec<SpriteInstanceUniform>,
        current_texture_size: UVec2,
    ) {
        let world_window_size = nine_slice.size;
        let slices = &nine_slice.slices;

        // ------------------------------------------------------------
        // Validate that our total window size is large enough to hold
        // the left+right and top+bottom slices without underflowing.
        // ------------------------------------------------------------
        assert!(
            world_window_size.x >= slices.left + slices.right,
            "NineSlice.width ({}) < slices.left + slices.right ({})",
            world_window_size.x,
            slices.left + slices.right
        );
        assert!(
            world_window_size.y >= slices.top + slices.bottom,
            "NineSlice.height ({}) < slices.top + slices.bottom ({})",
            world_window_size.y,
            slices.top + slices.bottom
        );

        let texture_window_size = nine_slice.size_inside_atlas.unwrap_or(current_texture_size);

        // check the texture region as well
        assert!(
            texture_window_size.x >= slices.left + slices.right,
            "texture_window_size.width ({}) < slices.left + slices.right ({})",
            texture_window_size.x,
            slices.left + slices.right
        );
        assert!(
            texture_window_size.y >= slices.top + slices.bottom,
            "texture_window_size.height ({}) < slices.top + slices.bottom ({})",
            texture_window_size.y,
            slices.top + slices.bottom
        );
        // ------------------------------------------------------------

        let color = nine_slice.color;

        let atlas_origin = nine_slice.origin_in_atlas;
        let texture_window_size = nine_slice.size_inside_atlas.unwrap_or(current_texture_size);

        let world_edge_width = nine_slice.size.x - slices.left - slices.right;
        let world_edge_height = nine_slice.size.y - slices.top - slices.bottom;
        let texture_edge_width = texture_window_size.x - slices.left - slices.right;
        let texture_edge_height = texture_window_size.y - slices.top - slices.bottom;

        // Lower left Corner
        // Y goes up, X goes to the right, right-handed coordinate system
        let lower_left_pos = Vec3::new(position_offset.x, position_offset.y, 0);
        let corner_size = UVec2::new(slices.left, slices.bottom);
        // it should be pixel perfect so it is the same size as the texture cut out
        let lower_left_quad_size = UVec2::new(corner_size.x, corner_size.y);
        let lower_left_atlas = URect::new(
            atlas_origin.x,
            atlas_origin.y + texture_window_size.y - slices.bottom, // Bottom of texture minus bottom slice height
            corner_size.x,
            corner_size.y,
        );
        let lower_left_quad = Self::quad_helper_uniform(
            lower_left_pos,
            lower_left_quad_size,
            lower_left_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(lower_left_quad);

        // Lower edge
        let lower_side_position =
            Vec3::new(position_offset.x + slices.left as i16, position_offset.y, 0);
        // World quad size is potentially wider than the texture,
        // that is fine, since the texture will be repeated.
        let lower_side_world_quad_size = UVec2::new(world_edge_width, slices.bottom);
        let lower_side_texture_size = UVec2::new(texture_edge_width, slices.bottom);
        // Lower edge
        let lower_side_atlas = URect::new(
            atlas_origin.x + slices.left,
            atlas_origin.y + texture_window_size.y - slices.bottom, // Bottom of texture minus bottom slice height
            lower_side_texture_size.x,
            lower_side_texture_size.y,
        );
        let lower_side_quad = Self::quad_helper_uniform(
            lower_side_position,
            lower_side_world_quad_size,
            lower_side_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(lower_side_quad);

        // Lower right corner
        let lower_right_pos = Vec3::new(
            position_offset.x + (world_window_size.x - slices.right) as i16,
            position_offset.y,
            0,
        );
        let lower_right_corner_size = UVec2::new(slices.right, slices.bottom);
        let lower_right_atlas = URect::new(
            atlas_origin.x + texture_window_size.x - slices.right,
            atlas_origin.y + texture_window_size.y - slices.bottom, // Bottom of texture minus bottom slice height
            lower_right_corner_size.x,
            lower_right_corner_size.y,
        );
        let lower_right_quad = Self::quad_helper_uniform(
            lower_right_pos,
            lower_right_corner_size,
            lower_right_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(lower_right_quad);

        // Left edge
        let left_edge_pos = Vec3::new(
            position_offset.x,
            position_offset.y + slices.bottom as i16,
            0,
        );
        let left_edge_world_quad_size = UVec2::new(slices.left, world_edge_height);
        let left_edge_texture_size = UVec2::new(slices.left, texture_edge_height);
        let left_edge_atlas = URect::new(
            atlas_origin.x,
            atlas_origin.y + slices.top, // Skip top slice
            left_edge_texture_size.x,
            left_edge_texture_size.y,
        );
        let left_edge_quad = Self::quad_helper_uniform(
            left_edge_pos,
            left_edge_world_quad_size,
            left_edge_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(left_edge_quad);

        // CENTER IS COMPLICATED
        // This was pretty tricky to get going, but @catnipped wanted it :)

        // For the center region, we have to create multiple quads, since we want
        // it pixel perfect and not stretch it
        let base_center_x = atlas_origin.x + slices.left;
        let base_center_y = atlas_origin.y + slices.top;

        // Calculate how many repetitions (quads) we need in each direction
        let repeat_x_count =
            (f32::from(world_edge_width) / f32::from(texture_edge_width)).ceil() as usize;
        let repeat_y_count =
            (f32::from(world_edge_height) / f32::from(texture_edge_height)).ceil() as usize;

        for y in 0..repeat_y_count {
            for x in 0..repeat_x_count {
                let this_quad_width = if x == repeat_x_count - 1
                    && !world_edge_width.is_multiple_of(texture_edge_width)
                {
                    world_edge_width % texture_edge_width
                } else {
                    texture_edge_width
                };

                let this_quad_height = if y == repeat_y_count - 1
                    && !world_edge_height.is_multiple_of(texture_edge_height)
                {
                    world_edge_height % texture_edge_height
                } else {
                    texture_edge_height
                };

                let quad_pos = Vec3::new(
                    position_offset.x + slices.left as i16 + (x as u16 * texture_edge_width) as i16,
                    position_offset.y
                        + slices.bottom as i16
                        + (y as u16 * texture_edge_height) as i16,
                    0,
                );

                let texture_x = base_center_x;

                let texture_y = if y == repeat_y_count - 1 && this_quad_height < texture_edge_height
                {
                    base_center_y + (texture_edge_height - this_quad_height)
                } else {
                    base_center_y
                };

                let this_texture_region =
                    URect::new(texture_x, texture_y, this_quad_width, this_quad_height);

                let center_quad = Self::quad_helper_uniform(
                    quad_pos,
                    UVec2::new(this_quad_width, this_quad_height),
                    this_texture_region,
                    color,
                    current_texture_size,
                );

                quad_matrix_and_uv.push(center_quad);
            }
        }
        // CENTER IS DONE ---------

        // Right edge
        let right_edge_pos = Vec3::new(
            position_offset.x + (world_window_size.x - slices.right) as i16,
            position_offset.y + slices.bottom as i16,
            0,
        );
        let right_edge_world_quad_size = UVec2::new(slices.right, world_edge_height);
        let right_edge_texture_size = UVec2::new(slices.right, texture_edge_height);
        let right_edge_atlas = URect::new(
            atlas_origin.x + texture_window_size.x - slices.right,
            atlas_origin.y + slices.top, // Skip top slice
            right_edge_texture_size.x,
            right_edge_texture_size.y,
        );

        let right_edge_quad = Self::quad_helper_uniform(
            right_edge_pos,
            right_edge_world_quad_size,
            right_edge_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(right_edge_quad);

        // Top left corner
        let top_left_pos = Vec3::new(
            position_offset.x,
            position_offset.y + (world_window_size.y - slices.top) as i16,
            0,
        );
        let top_left_corner_size = UVec2::new(slices.left, slices.top);
        let top_left_atlas = URect::new(
            atlas_origin.x,
            atlas_origin.y, // Top of texture
            top_left_corner_size.x,
            top_left_corner_size.y,
        );
        let top_left_quad = Self::quad_helper_uniform(
            top_left_pos,
            top_left_corner_size,
            top_left_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(top_left_quad);

        // Top edge
        let top_edge_pos = Vec3::new(
            position_offset.x + slices.left as i16,
            position_offset.y + (world_window_size.y - slices.top) as i16,
            0,
        );
        let top_edge_world_quad_size = UVec2::new(world_edge_width, slices.top);
        let top_edge_texture_size = UVec2::new(texture_edge_width, slices.top);
        let top_edge_atlas = URect::new(
            atlas_origin.x + slices.left,
            atlas_origin.y, // Top of texture
            top_edge_texture_size.x,
            top_edge_texture_size.y,
        );
        let top_edge_quad = Self::quad_helper_uniform(
            top_edge_pos,
            top_edge_world_quad_size,
            top_edge_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(top_edge_quad);

        // Top right corner
        let top_right_pos = Vec3::new(
            position_offset.x + (world_window_size.x - slices.right) as i16,
            position_offset.y + (world_window_size.y - slices.top) as i16,
            0,
        );
        let top_right_corner_size = UVec2::new(slices.right, slices.top);
        let top_right_atlas = URect::new(
            atlas_origin.x + texture_window_size.x - slices.right,
            atlas_origin.y, // Top of texture
            top_right_corner_size.x,
            top_right_corner_size.y,
        );
        let top_right_quad = Self::quad_helper_uniform(
            top_right_pos,
            top_right_corner_size,
            top_right_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(top_right_quad);
    }

    #[allow(clippy::too_many_lines)]
    #[inline]
    pub fn prepare_nine_slice_single_center_quad(
        nine_slice: &NineSlice,
        position_offset: Vec3,
        quad_matrix_and_uv: &mut Vec<SpriteInstanceUniform>,
        current_texture_size: UVec2,
    ) {
        let world_window_size = nine_slice.size;
        let slices = &nine_slice.slices;

        // ------------------------------------------------------------
        // Validate that our total window size is large enough to hold
        // the left+right and top+bottom slices without underflowing.
        // ------------------------------------------------------------
        assert!(
            world_window_size.x >= slices.left + slices.right,
            "NineSlice.width ({}) < slices.left + slices.right ({})",
            world_window_size.x,
            slices.left + slices.right
        );
        assert!(
            world_window_size.y >= slices.top + slices.bottom,
            "NineSlice.height ({}) < slices.top + slices.bottom ({})",
            world_window_size.y,
            slices.top + slices.bottom
        );

        let texture_window_size = nine_slice.size_inside_atlas.unwrap_or(current_texture_size);

        // check the texture region as well
        assert!(
            texture_window_size.x >= slices.left + slices.right,
            "texture_window_size.width ({}) < slices.left + slices.right ({})",
            texture_window_size.x,
            slices.left + slices.right
        );
        assert!(
            texture_window_size.y >= slices.top + slices.bottom,
            "texture_window_size.height ({}) < slices.top + slices.bottom ({})",
            texture_window_size.y,
            slices.top + slices.bottom
        );
        // ------------------------------------------------------------

        let color = nine_slice.color;

        let atlas_origin = nine_slice.origin_in_atlas;
        let texture_window_size = nine_slice.size_inside_atlas.unwrap_or(current_texture_size);

        let world_edge_width = nine_slice.size.x - slices.left - slices.right;
        let world_edge_height = nine_slice.size.y - slices.top - slices.bottom;
        let texture_edge_width = texture_window_size.x - slices.left - slices.right;
        let texture_edge_height = texture_window_size.y - slices.top - slices.bottom;

        // Lower left Corner
        // Y goes up, X goes to the right, right-handed coordinate system
        let lower_left_pos = Vec3::new(position_offset.x, position_offset.y, 0);
        let corner_size = UVec2::new(slices.left, slices.bottom);
        // it should be pixel perfect so it is the same size as the texture cut out
        let lower_left_quad_size = UVec2::new(corner_size.x, corner_size.y);
        let lower_left_atlas = URect::new(
            atlas_origin.x,
            atlas_origin.y + texture_window_size.y - slices.bottom, // Bottom of texture minus bottom slice height
            corner_size.x,
            corner_size.y,
        );
        let lower_left_quad = Self::quad_helper_uniform(
            lower_left_pos,
            lower_left_quad_size,
            lower_left_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(lower_left_quad);

        // Lower edge
        let lower_side_position =
            Vec3::new(position_offset.x + slices.left as i16, position_offset.y, 0);
        // World quad size is potentially wider than the texture,
        // that is fine, since the texture will be repeated.
        let lower_side_world_quad_size = UVec2::new(world_edge_width, slices.bottom);
        let lower_side_texture_size = UVec2::new(texture_edge_width, slices.bottom);
        // Lower edge
        let lower_side_atlas = URect::new(
            atlas_origin.x + slices.left,
            atlas_origin.y + texture_window_size.y - slices.bottom, // Bottom of texture minus bottom slice height
            lower_side_texture_size.x,
            lower_side_texture_size.y,
        );
        let lower_side_quad = Self::quad_helper_uniform(
            lower_side_position,
            lower_side_world_quad_size,
            lower_side_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(lower_side_quad);

        // Lower right corner
        let lower_right_pos = Vec3::new(
            position_offset.x + (world_window_size.x - slices.right) as i16,
            position_offset.y,
            0,
        );
        let lower_right_corner_size = UVec2::new(slices.right, slices.bottom);
        let lower_right_atlas = URect::new(
            atlas_origin.x + texture_window_size.x - slices.right,
            atlas_origin.y + texture_window_size.y - slices.bottom, // Bottom of texture minus bottom slice height
            lower_right_corner_size.x,
            lower_right_corner_size.y,
        );
        let lower_right_quad = Self::quad_helper_uniform(
            lower_right_pos,
            lower_right_corner_size,
            lower_right_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(lower_right_quad);

        // Left edge
        let left_edge_pos = Vec3::new(
            position_offset.x,
            position_offset.y + slices.bottom as i16,
            0,
        );
        let left_edge_world_quad_size = UVec2::new(slices.left, world_edge_height);
        let left_edge_texture_size = UVec2::new(slices.left, texture_edge_height);
        let left_edge_atlas = URect::new(
            atlas_origin.x,
            atlas_origin.y + slices.top, // Skip top slice
            left_edge_texture_size.x,
            left_edge_texture_size.y,
        );
        let left_edge_quad = Self::quad_helper_uniform(
            left_edge_pos,
            left_edge_world_quad_size,
            left_edge_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(left_edge_quad);

        // Center as a single, stretched quad
        let center_pos = Vec3::new(
            position_offset.x + slices.left as i16,
            position_offset.y + slices.bottom as i16,
            0,
        );
        let center_world_size = UVec2::new(world_edge_width, world_edge_height);
        // atlas_origin.x + slices.left  => x of center in atlas
        // atlas_origin.y + slices.top   => y of center in atlas
        let center_atlas = URect::new(
            atlas_origin.x + slices.left,
            atlas_origin.y + slices.top,
            texture_edge_width,
            texture_edge_height,
        );
        let center_quad = Self::quad_helper_uniform(
            center_pos,
            center_world_size,
            center_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(center_quad);

        // Right edge
        let right_edge_pos = Vec3::new(
            position_offset.x + (world_window_size.x - slices.right) as i16,
            position_offset.y + slices.bottom as i16,
            0,
        );
        let right_edge_world_quad_size = UVec2::new(slices.right, world_edge_height);
        let right_edge_texture_size = UVec2::new(slices.right, texture_edge_height);
        let right_edge_atlas = URect::new(
            atlas_origin.x + texture_window_size.x - slices.right,
            atlas_origin.y + slices.top, // Skip top slice
            right_edge_texture_size.x,
            right_edge_texture_size.y,
        );

        let right_edge_quad = Self::quad_helper_uniform(
            right_edge_pos,
            right_edge_world_quad_size,
            right_edge_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(right_edge_quad);

        // Top left corner
        let top_left_pos = Vec3::new(
            position_offset.x,
            position_offset.y + (world_window_size.y - slices.top) as i16,
            0,
        );
        let top_left_corner_size = UVec2::new(slices.left, slices.top);
        let top_left_atlas = URect::new(
            atlas_origin.x,
            atlas_origin.y, // Top of texture
            top_left_corner_size.x,
            top_left_corner_size.y,
        );
        let top_left_quad = Self::quad_helper_uniform(
            top_left_pos,
            top_left_corner_size,
            top_left_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(top_left_quad);

        // Top edge
        let top_edge_pos = Vec3::new(
            position_offset.x + slices.left as i16,
            position_offset.y + (world_window_size.y - slices.top) as i16,
            0,
        );
        let top_edge_world_quad_size = UVec2::new(world_edge_width, slices.top);
        let top_edge_texture_size = UVec2::new(texture_edge_width, slices.top);
        let top_edge_atlas = URect::new(
            atlas_origin.x + slices.left,
            atlas_origin.y, // Top of texture
            top_edge_texture_size.x,
            top_edge_texture_size.y,
        );
        let top_edge_quad = Self::quad_helper_uniform(
            top_edge_pos,
            top_edge_world_quad_size,
            top_edge_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(top_edge_quad);

        // Top right corner
        let top_right_pos = Vec3::new(
            position_offset.x + (world_window_size.x - slices.right) as i16,
            position_offset.y + (world_window_size.y - slices.top) as i16,
            0,
        );
        let top_right_corner_size = UVec2::new(slices.right, slices.top);
        let top_right_atlas = URect::new(
            atlas_origin.x + texture_window_size.x - slices.right,
            atlas_origin.y, // Top of texture
            top_right_corner_size.x,
            top_right_corner_size.y,
        );
        let top_right_quad = Self::quad_helper_uniform(
            top_right_pos,
            top_right_corner_size,
            top_right_atlas,
            color,
            current_texture_size,
        );
        quad_matrix_and_uv.push(top_right_quad);
    }

    fn sort_and_put_in_batches(&mut self) -> Vec<Vec<&RenderItem>> {
        sort_render_items_by_z_and_material(&mut self.items);

        self.order_render_items_in_batches()
    }

    /// # Panics
    ///
    #[allow(clippy::too_many_lines)]
    pub fn render(
        &mut self,
        command_encoder: &mut CommandEncoder,
        display_surface_texture_view: &TextureView,
        //        materials: &Assets<Material>,
        textures: &Assets<Texture>,
        fonts: &Assets<Font>,
        now: Millis,
    ) {
        self.debug_tick += 1;
        trace!("start render()");
        self.last_render_at = now;

        self.set_viewport_and_view_projection_matrix();

        self.write_vertex_indices_and_uv_to_buffer(textures, fonts);

        self.render_batches_to_virtual_texture(command_encoder, textures);

        self.render_virtual_texture_to_display(command_encoder, display_surface_texture_view);
    }

    pub fn set_viewport_and_view_projection_matrix(&mut self) {
        let view_proj_matrix = create_view_projection_matrix_from_virtual(
            self.virtual_surface_size.x,
            self.virtual_surface_size.y,
        );

        let scale_matrix = Matrix4::from_scale(self.scale, self.scale, 0.0);
        let origin_translation_matrix =
            Matrix4::from_translation(f32::from(-self.origin.x), f32::from(-self.origin.y), 0.0);

        let total_matrix = scale_matrix * view_proj_matrix * origin_translation_matrix;

        // write all model_matrix and uv_coords to instance buffer once, before the render pass
        self.queue.write_buffer(
            &self.camera_buffer,
            0,
            bytemuck::cast_slice(&[total_matrix]),
        );
    }

    pub fn render_batches_to_virtual_texture(
        &mut self,
        command_encoder: &mut CommandEncoder,
        textures: &Assets<Texture>,
    ) {
        let mut render_pass = command_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("Game Render Pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: &self.virtual_surface_texture_view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(self.clear_color),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });

        render_pass.set_viewport(
            0.0,
            0.0,
            f32::from(self.virtual_surface_size.x),
            f32::from(self.virtual_surface_size.y),
            0.0,
            1.0,
        );

        // Index and vertex buffers never change
        render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
        render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));

        // Vertex buffer is reused
        render_pass.set_vertex_buffer(1, self.quad_matrix_and_uv_instance_buffer.slice(..));

        let num_indices = mireforge_wgpu_sprites::INDICES.len() as u32;

        let mut current_pipeline: Option<&MaterialKind> = None;

        for &(ref weak_material_ref, start, count) in &self.batch_offsets {
            let wgpu_material = weak_material_ref;

            let pipeline_kind = &wgpu_material.kind;

            if current_pipeline != Some(pipeline_kind) {
                let pipeline = match pipeline_kind {
                    MaterialKind::NormalSprite { .. } => &self.normal_sprite_pipeline.pipeline,
                    MaterialKind::Quad => &self.quad_shader_info.pipeline,
                    MaterialKind::AlphaMasker { .. } => &self.mask_shader_info.pipeline,
                    MaterialKind::LightAdd { .. } => &self.light_shader_info.pipeline,
                };
                //trace!(%pipeline_kind, ?pipeline, "setting pipeline");
                render_pass.set_pipeline(pipeline);
                // Apparently after setting pipeline,
                // you must set all bind groups again
                current_pipeline = Some(pipeline_kind);
                render_pass.set_bind_group(0, &self.camera_bind_group, &[]);
            }

            match &wgpu_material.kind {
                MaterialKind::NormalSprite { primary_texture }
                | MaterialKind::LightAdd { primary_texture } => {
                    let texture = textures.get(primary_texture).unwrap();
                    // Bind the texture and sampler bind group (Bind Group 1)
                    render_pass.set_bind_group(1, &texture.texture_and_sampler_bind_group, &[]);
                }
                MaterialKind::AlphaMasker {
                    primary_texture,
                    alpha_texture,
                } => {
                    let real_diffuse_texture = textures.get(primary_texture).unwrap();
                    let alpha_texture = textures.get(alpha_texture).unwrap();
                    render_pass.set_bind_group(
                        1,
                        &real_diffuse_texture.texture_and_sampler_bind_group,
                        &[],
                    );
                    render_pass.set_bind_group(
                        2,
                        &alpha_texture.texture_and_sampler_bind_group,
                        &[],
                    );
                }
                MaterialKind::Quad => {
                    // Intentionally do nothing
                }
            }
            assert!(
                count <= MAXIMUM_QUADS_IN_A_BATCH as u32,
                "too many instanced draw in a batch {count}"
            );

            // Issue the instanced draw call for the batch
            trace!(material=%weak_material_ref, start=%start, count=%count, %num_indices, "draw instanced");
            render_pass.draw_indexed(0..num_indices, 0, start..(start + count));
        }
        self.items.clear();
    }

    pub fn render_virtual_texture_to_display(
        &mut self,
        command_encoder: &mut CommandEncoder,
        display_surface_texture_view: &TextureView,
    ) {
        let mut render_pass = command_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("Screen Render Pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: display_surface_texture_view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(self.screen_clear_color),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });

        /*
        let scale_x = window_width as f32 / VIRTUAL_WIDTH as f32;
        let scale_y = window_height as f32 / VIRTUAL_HEIGHT as f32;
        let scale = scale_x.min(scale_y).floor(); // Use integer scaling

        let viewport_width = VIRTUAL_WIDTH as f32 * scale;
        let viewport_height = VIRTUAL_HEIGHT as f32 * scale;
        let viewport_x = (window_width as f32 - viewport_width) / 2.0;
        let viewport_y = (window_height as f32 - viewport_height) / 2.0;
         */

        self.viewport = match self.viewport_strategy {
            ViewportStrategy::FitIntegerScaling => Self::viewport_from_integer_scale(
                self.physical_surface_size,
                self.virtual_surface_size,
            ),
            ViewportStrategy::FitFloatScaling => Self::viewport_from_float_scale(
                self.physical_surface_size,
                self.virtual_surface_size,
            ),
            ViewportStrategy::MatchPhysicalSize => URect::new(
                0,
                0,
                self.physical_surface_size.x,
                self.physical_surface_size.y,
            ),
        };

        render_pass.set_viewport(
            f32::from(self.viewport.position.x),
            f32::from(self.viewport.position.y),
            f32::from(self.viewport.size.x),
            f32::from(self.viewport.size.y),
            0.0,
            1.0,
        );

        // Draw the render texture to the screen
        render_pass.set_pipeline(&self.virtual_to_screen_shader_info.pipeline);
        render_pass.set_bind_group(0, &self.virtual_to_surface_bind_group, &[]);
        render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));

        render_pass.draw(0..6, 0..1);
    }

    pub fn texture_resource_from_texture(&self, texture: &wgpu::Texture, label: &str) -> Texture {
        trace!("load texture from memory with name: '{label}'");
        let size = &texture.size();
        let texture_and_sampler_bind_group =
            mireforge_wgpu_sprites::create_sprite_texture_and_sampler_bind_group(
                &self.device,
                &self.texture_sampler_bind_group_layout,
                texture,
                &self.sampler,
                label,
            );

        let texture_size = UVec2::new(size.width as u16, size.height as u16);

        Texture {
            texture_and_sampler_bind_group,
            texture_size,
        }
    }
}

fn create_view_projection_matrix_from_virtual(virtual_width: u16, virtual_height: u16) -> Matrix4 {
    let (bottom, top) = (0.0, f32::from(virtual_height));

    // flip Z by swapping near/far if you want the opposite handedness
    // (e.g. for a left-handed vs right-handed depth axis)
    let (near, far) =
        // standard: near < far maps 0 → near, 1 → far
        (/* nearPlaneDepth */ -1.0, /* farPlaneDepth */ 1.0)
    ;

    OrthoInfo {
        left: 0.0,
        right: f32::from(virtual_width),
        bottom,
        top,
        near, // Maybe flipped? -1.0
        far,  // maybe flipped? 1.0 or 0.0
    }
    .into()
}

fn create_view_uniform_view_projection_matrix(viewport_size: UVec2) -> Matrix4 {
    let viewport_width = f32::from(viewport_size.x);
    let viewport_height = f32::from(viewport_size.y);

    let viewport_aspect_ratio = viewport_width / viewport_height;

    let scale_x = 1.0;
    let scale_y = viewport_aspect_ratio;

    let view_projection_matrix = [
        [scale_x, 0.0, 0.0, 0.0],
        [0.0, scale_y, 0.0, 0.0],
        [0.0, 0.0, -1.0, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ];

    view_projection_matrix.into()
}

fn sort_render_items_by_z_and_material(items: &mut [RenderItem]) {
    items.sort_by_key(|item| (item.position.z, item.material_ref.clone()));
}

#[derive(Debug, Clone, Copy, Default)]
pub enum Rotation {
    #[default]
    Degrees0,
    Degrees90,
    Degrees180,
    Degrees270,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Anchor {
    LowerLeft,
    UpperLeft,
}

#[derive(Debug, Copy, Clone)]
pub struct SpriteParams {
    pub texture_size: UVec2,
    pub texture_pos: UVec2,
    pub scale: u8,
    pub rotation: Rotation,
    pub flip_x: bool,
    pub flip_y: bool,
    pub pivot: Vec2,
    pub color: Color,
    pub anchor: Anchor,
}

impl Default for SpriteParams {
    fn default() -> Self {
        Self {
            texture_size: UVec2::new(0, 0),
            texture_pos: UVec2::new(0, 0),
            pivot: Vec2::new(0, 0),
            flip_x: false,
            flip_y: false,
            color: Color::from_octet(255, 255, 255, 255),
            scale: 1,
            rotation: Rotation::Degrees0,
            anchor: Anchor::LowerLeft,
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub struct QuadParams {
    pub scale: u8,
    pub pivot: Vec2,
}

impl Default for QuadParams {
    fn default() -> Self {
        Self {
            pivot: Vec2::new(0, 0),
            scale: 1,
        }
    }
}

pub type BindGroupRef = Arc<BindGroup>;

#[derive(Debug, PartialEq, Eq, Asset)]
pub struct Texture {
    pub texture_and_sampler_bind_group: BindGroup,
    //    pub pipeline: RenderPipelineRef,
    pub texture_size: UVec2,
}

impl Display for Texture {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "{:?}", self.texture_size)
    }
}

impl PartialOrd<Self> for Texture {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(
            self.texture_and_sampler_bind_group
                .cmp(&other.texture_and_sampler_bind_group),
        )
    }
}

impl Ord for Texture {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.texture_and_sampler_bind_group
            .cmp(&other.texture_and_sampler_bind_group)
    }
}

#[derive(Debug, Ord, PartialOrd, PartialEq, Eq)]
pub struct MaterialBase {
    //pub pipeline: PipelineRef,
}

#[derive(Debug, Ord, PartialOrd, PartialEq, Eq)]
pub struct Material {
    pub base: MaterialBase,
    pub kind: MaterialKind,
}

impl Material {
    #[inline]
    #[must_use]
    pub fn primary_texture(&self) -> Option<TextureRef> {
        self.kind.primary_texture()
    }

    #[inline]
    #[must_use]
    pub fn is_complete(&self, textures: &Assets<Texture>) -> bool {
        self.kind.is_complete(textures)
    }
}

impl Display for Material {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.kind)
    }
}

#[derive(Debug, Ord, PartialOrd, PartialEq, Eq)]
pub enum MaterialKind {
    NormalSprite {
        primary_texture: Id<Texture>,
    },
    AlphaMasker {
        primary_texture: Id<Texture>,
        alpha_texture: Id<Texture>,
    },
    Quad,
    LightAdd {
        primary_texture: Id<Texture>,
    },
}

impl MaterialKind {}

impl MaterialKind {
    #[must_use]
    pub fn primary_texture(&self) -> Option<Id<Texture>> {
        match &self {
            Self::NormalSprite {
                primary_texture, ..
            }
            | Self::LightAdd { primary_texture }
            | Self::AlphaMasker {
                primary_texture, ..
            } => Some(primary_texture.clone()),
            Self::Quad => None,
        }
    }

    pub(crate) fn is_complete(&self, textures: &Assets<Texture>) -> bool {
        match &self {
            Self::NormalSprite { primary_texture } | Self::LightAdd { primary_texture } => {
                textures.contains(primary_texture)
            }
            Self::AlphaMasker {
                primary_texture,
                alpha_texture,
            } => textures.contains(primary_texture) && textures.contains(alpha_texture),
            Self::Quad => true,
        }
    }
}

impl Display for MaterialKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let texture_name = self
            .primary_texture()
            .map_or_else(String::new, |x| x.to_string());

        let kind_name = match self {
            Self::NormalSprite { .. } => "NormalSprite",
            Self::LightAdd { .. } => "Light (Add)",
            Self::Quad => "Quad",
            Self::AlphaMasker { .. } => "AlphaMasker",
        };

        write!(f, "{kind_name} texture {texture_name}")
    }
}

#[derive(Debug)]
pub struct Sprite {
    pub params: SpriteParams,
}

#[derive(Debug)]
pub struct QuadColor {
    pub size: UVec2,
    pub color: Color,
    pub params: QuadParams,
}

#[derive(Debug, Copy, Clone)]
pub struct Slices {
    pub left: u16,
    pub top: u16,
    pub right: u16,  // how many pixels from the right side of the texture and going in
    pub bottom: u16, // how much to take from bottom of slice
}

#[derive(Debug)]
pub struct NineSlice {
    pub size: UVec2, // size of whole "window"
    pub slices: Slices,
    pub color: Color, // color tint
    pub origin_in_atlas: UVec2,
    pub size_inside_atlas: Option<UVec2>,
}

#[derive(Debug)]
pub struct TileMap {
    pub tiles_data_grid_size: UVec2,
    pub cell_count_size: UVec2,
    pub one_cell_size: UVec2,
    pub tiles: Vec<u16>,
    pub scale: u8,
}

#[derive(PartialEq, Debug, Eq, Ord, PartialOrd)]
pub struct Pipeline {
    name: String,
    render_pipeline: RenderPipeline,
}

impl Display for Pipeline {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "pipeline: {}", self.name)
    }
}

pub type PipelineRef = Arc<Pipeline>;