web-glitz 0.2.1

Rusty low-level web-graphics library on top of WebGL 2.0.
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
use std::borrow::Borrow;
use std::cell::UnsafeCell;
use std::hash::{Hash, Hasher};
use std::marker;
use std::ops::{Deref, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
use std::sync::Arc;

use web_sys::WebGl2RenderingContext as Gl;

use crate::buffer::{BufferData, BufferView};
use crate::image::format::{
    Filterable, FloatSamplable, IntegerSamplable, PixelPack, PixelUnpack, ShadowSamplable,
    TextureFormat, UnsignedIntegerSamplable,
};
use crate::image::image_source::Image2DSourceInternal;
use crate::image::sampler::{CompatibleSampler, SamplerData, ShadowSampler};
use crate::image::texture_object_dropper::TextureObjectDropper;
use crate::image::util::{
    max_mipmap_levels, mipmap_size, region_2d_overlap_height, region_2d_overlap_width,
    region_2d_sub_image, texture_data_as_js_buffer,
};
use crate::image::{Image2DSource, MaxMipmapLevelsExceeded, MipmapLevels, Region2D};
use crate::runtime::state::ContextUpdate;
use crate::runtime::{Connection, RenderingContext};
use crate::task::{ContextId, GpuTask, Progress};
use crate::util::JsId;

/// Provides the information necessary for the creation of a [Texture2D].
///
/// See [RenderingContext::create_texture_2d] for details.
pub struct Texture2DDescriptor<F>
where
    F: TextureFormat + 'static,
{
    /// The format type the [Texture2D] will use to store its image data.
    ///
    /// Must implement [TextureFormat].
    pub format: F,

    /// The width of the [Texture2D].
    pub width: u32,

    /// The height of the [Texture2D].
    pub height: u32,

    /// The number of levels in the mipmap for the [Texture2D].
    ///
    /// See [MipmapLevels] for details.
    pub levels: MipmapLevels,
}

/// Image storage for the (partial or complete) mipmap chain of a single 2-dimensional image.
///
/// See [RenderingContext::create_texture_2d] for details on how a [Texture2D] is created.
///
/// # Mipmap
///
/// A [Texture2D] stores a partial or complete mipmap chain for a single 2-dimensional base image.
/// See the module documentation for [web_glitz::image] for more information on mipmaps.
///
/// Note that a [Texture2D] does not necessarily have to store a complete mipmap chain, it may only
/// store a partial mipmap chain. For example, it may only store the first three levels (see
/// [MipmapLevels] for details). However, it must store at least the first level: level `0`, the
/// base level (see [Texture2D::base_level]).
///
/// Each image in the chain initially starts out in a "cleared" state, where each bit is set to `0`
/// (note that "zeroed data" is valid data for all [TextureFormat]s).
///
/// Mipmapping is typically used with minification filtering, in which case each level in the chain
/// is typically a down-filtered version of the previous level (see [MinificationFilter] for
/// details). If the texture format implements [Filterable], then the image data for such a chain
/// may be generated by first uploading data for the base level, and then generating the subsequent
/// levels with [Texture2D::generate_mipmap] (see [Texture2D::generate_mipmap] for details). Image
/// data may also be uploaded to each level individually.
///
/// # Sampling
///
/// The GPU may access the data in a [Texture2D] through a [Sampler] or [ShadowSampler], see
/// [Texture2D::sampled_float], [Texture2D::sampled_integer], [Texture2D::sampled_unsigned_integer]
/// and [Texture2D::sampled_shadow]. A sampled [Texture2D] may be bound to a pipeline as a resource,
/// see [web_glitz::pipeline::resources::Resources].
///
/// # Example
///
/// The following example creates a 2d texture with a width of 256 pixels and a height of 256
/// pixels stored in the [RGB8] format, with a complete mipmap chain. All pixels in the base image
/// are set to `[255, 0, 0]` (red) with an "upload" command and then the pixel data for all other
/// levels is generated with a "generate mipmap" command:
///
/// ```rust
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
/// use web_glitz::image::{Image2DSource, MipmapLevels};
/// use web_glitz::image::format::RGB8;
/// use web_glitz::image::texture_2d::Texture2DDescriptor;
/// use web_glitz::sequence_all;
///
/// let texture = context.try_create_texture_2d(&Texture2DDescriptor {
///     format: RGB8,
///     width: 256,
///     height: 256,
///     levels: MipmapLevels::Complete
/// }).unwrap();
///
/// let pixels: Vec<[u8; 3]> = vec![[255, 0, 0]; 256 * 256];
/// let data = Image2DSource::from_pixels(pixels, 256, 256).unwrap();
///
/// context.submit(sequence_all![
///     texture.base_level().upload_command(data),
///     texture.generate_mipmap_command(),
/// ]);
/// # }
/// ```
pub struct Texture2D<F> {
    object_id: u64,
    data: Arc<Texture2DData>,
    format: F,
}

impl<F> Texture2D<F> {
    pub(crate) fn data(&self) -> &Arc<Texture2DData> {
        &self.data
    }
}

impl<F> Texture2D<F>
where
    F: TextureFormat + 'static,
{
    pub(crate) fn new<Rc>(
        context: &Rc,
        object_id: u64,
        descriptor: &Texture2DDescriptor<F>,
    ) -> Result<Self, MaxMipmapLevelsExceeded>
    where
        Rc: RenderingContext + Clone + 'static,
    {
        let Texture2DDescriptor {
            format,
            width,
            height,
            levels,
            ..
        } = descriptor;
        let max_mipmap_levels = max_mipmap_levels(*width, *height);

        let levels = match levels {
            MipmapLevels::Complete => max_mipmap_levels,
            MipmapLevels::Partial(levels) => {
                if *levels > max_mipmap_levels {
                    return Err(MaxMipmapLevelsExceeded {
                        given: *levels,
                        max: max_mipmap_levels,
                    });
                }

                *levels
            }
        };

        let data = Arc::new(Texture2DData {
            id: UnsafeCell::new(None),
            context_id: context.id(),
            dropper: Box::new(context.clone()),
            width: *width,
            height: *height,
            levels,
        });

        context.submit(AllocateCommand::<F> {
            data: data.clone(),
            _marker: marker::PhantomData,
        });

        Ok(Texture2D {
            object_id,
            data,
            format: *format,
        })
    }

    /// Returns a reference to the base mipmap level for this [Texture2D] (level 0).
    pub fn base_level(&self) -> Level<F> {
        Level {
            handle: self,
            level: 0,
        }
    }

    /// Returns a reference to the base mipmap level for this [Texture2D] (level 0).
    pub fn base_level_mut(&mut self) -> LevelMut<F> {
        LevelMut {
            inner: Level {
                handle: self,
                level: 0,
            },
        }
    }

    /// Returns a reference to the levels of this [Texture2D].
    ///
    /// See also [Texture2D::levels_mut].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # use web_glitz::image::MipmapLevels;
    /// # use web_glitz::image::format::RGB8;
    /// # use web_glitz::image::texture_2d::Texture2DDescriptor;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// # let texture = context.try_create_texture_2d(&Texture2DDescriptor {
    /// #     format: RGB8,
    /// #     width: 256,
    /// #     height: 256,
    /// #     levels: MipmapLevels::Complete
    /// # }).unwrap();
    /// // Returns a reference to mipmap level 2 if the texture has a level 2, or None otherwise:
    /// let level_2 = texture.levels().get(2);
    ///
    /// // We can also iterate over references to all levels that exist for the texture:
    /// for level in texture.levels().iter() {
    ///     let index = level.level();
    ///     let width = level.width();
    ///     let height = level.height();
    ///
    ///     println!("Level {} has a width of {} and height of {}!", index, width, height);
    /// }
    /// # }
    /// ```
    pub fn levels(&self) -> Levels<F> {
        Levels {
            handle: self,
            offset: 0,
            len: self.data.levels,
        }
    }

    /// Returns a mutable reference to the levels of this [Texture2D].
    ///
    /// See also [Texture2D::levels].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # use web_glitz::image::MipmapLevels;
    /// # use web_glitz::image::format::RGB8;
    /// # use web_glitz::image::texture_2d::Texture2DDescriptor;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// # let mut texture = context.try_create_texture_2d(&Texture2DDescriptor {
    /// #     format: RGB8,
    /// #     width: 256,
    /// #     height: 256,
    /// #     levels: MipmapLevels::Complete
    /// # }).unwrap();
    /// // Returns a mutable reference to mipmap level 2 if the texture has a level 2, or None
    /// // otherwise:
    /// let level_2 = texture.levels_mut().get_mut(2);
    /// # }
    /// ```
    pub fn levels_mut(&mut self) -> LevelsMut<F> {
        LevelsMut {
            inner: Levels {
                handle: self,
                offset: 0,
                len: self.data.levels,
            },
        }
    }

    /// The texture format for this [Texture2D]
    pub fn format(&self) -> F {
        self.format
    }

    /// The width of this [Texture2D].
    pub fn width(&self) -> u32 {
        self.data.width
    }

    /// The height of this [Texture2D].
    pub fn height(&self) -> u32 {
        self.data.height
    }
}

impl<F> Texture2D<F>
where
    F: TextureFormat + Filterable + 'static,
{
    /// Returns a command which, when executed, will generate new mipmap data for the [Texture2D].
    ///
    /// This will overwrite the image data for each mipmap level except the base level. Starting at
    /// level 1, an image is generated that is half the width and height of the previous level
    /// (rounded down), by linear minification filtering of the previous level (see also
    /// [MinificationFilter::Linear]); this stops when the maximum level for which storage was
    /// allocated when the texture was created (see [RenderingContext::create_texture_2d]) has been
    /// overwritten. Note that the base level (level 0) is not modified (rather, it serves as the
    /// input for this process).
    ///
    /// This operation is only available to a texture if the texture format implements [Filterable].
    pub fn generate_mipmap_command(&self) -> GenerateMipmapCommand {
        GenerateMipmapCommand {
            texture_data: self.data.clone(),
        }
    }
}

impl<F> Texture2D<F>
where
    F: TextureFormat + FloatSamplable + 'static,
{
    /// Combines this [Texture2D] with the `sampler` as a [FloatSampledTexture2D], which can be
    /// bound to a pipeline as a texture resource.
    ///
    /// Returns an [IncompatibleSampler] error if the `sampler` is not compatible with this
    /// texture's format.
    ///
    /// See also [web_glitz::pipeline::resources::Resources].
    ///
    /// # Panics
    ///
    /// Panics if this texture and the `sampler` do not belong to the same [RenderingContext].
    pub fn float_sampled<S>(&self, sampler: S) -> FloatSampledTexture2D
    where
        S: CompatibleSampler<F>,
    {
        let sampler = sampler.get_ref();

        if self.data().context_id() != sampler.data().context_id() {
            panic!("Texture and sampler do not belong to the same context.");
        }

        FloatSampledTexture2D {
            sampler_data: sampler.data().clone(),
            texture_data: self.data().clone(),
            _marker: marker::PhantomData,
        }
    }
}

/// A texture-sampler combination that can bound to a pipeline as a resource for a 2D floating
/// point sampler.
#[derive(Clone)]
pub struct FloatSampledTexture2D<'a> {
    pub(crate) sampler_data: Arc<SamplerData>,
    pub(crate) texture_data: Arc<Texture2DData>,
    _marker: marker::PhantomData<&'a ()>,
}

impl<F> Texture2D<F>
where
    F: TextureFormat + IntegerSamplable + 'static,
{
    /// Combines this [Texture2D] with the `sampler` as a [IntegerSampledTexture2D], which can be
    /// bound to a pipeline as a texture resource.
    ///
    /// Returns an [IncompatibleSampler] error if the `sampler` is not compatible with this
    /// texture's format.
    ///
    /// See also [web_glitz::pipeline::resources::Resources].
    ///
    /// # Panics
    ///
    /// Panics if this texture and the `sampler` do not belong to the same [RenderingContext].
    pub fn integer_sampled<S>(&self, sampler: S) -> IntegerSampledTexture2D
    where
        S: CompatibleSampler<F>,
    {
        let sampler = sampler.get_ref();

        if self.data().context_id() != sampler.data().context_id() {
            panic!("Texture and sampler do not belong to the same context.");
        }

        IntegerSampledTexture2D {
            sampler_data: sampler.data().clone(),
            texture_data: self.data().clone(),
            _marker: marker::PhantomData,
        }
    }
}

/// A texture-sampler combination that can bound to a pipeline as a resource for a 2D integer
/// sampler.
#[derive(Clone)]
pub struct IntegerSampledTexture2D<'a> {
    pub(crate) sampler_data: Arc<SamplerData>,
    pub(crate) texture_data: Arc<Texture2DData>,
    _marker: marker::PhantomData<&'a ()>,
}

impl<F> Texture2D<F>
where
    F: TextureFormat + UnsignedIntegerSamplable + 'static,
{
    /// Combines this [Texture2D] with the `sampler` as a [UnsignedIntegerSampledTexture2D], which
    /// can be bound to a pipeline as a texture resource.
    ///
    /// Returns an [IncompatibleSampler] error if the `sampler` is not compatible with this
    /// texture's format.
    ///
    /// See also [web_glitz::pipeline::resources::Resources].
    ///
    /// # Panics
    ///
    /// Panics if this texture and the `sampler` do not belong to the same [RenderingContext].
    pub fn unsigned_integer_sampled<S>(&self, sampler: S) -> UnsignedIntegerSampledTexture2D
    where
        S: CompatibleSampler<F>,
    {
        let sampler = sampler.get_ref();

        if self.data().context_id() != sampler.data().context_id() {
            panic!("Texture and sampler do not belong to the same context.");
        }

        UnsignedIntegerSampledTexture2D {
            sampler_data: sampler.data().clone(),
            texture_data: self.data().clone(),
            _marker: marker::PhantomData,
        }
    }
}

/// A texture-sampler combination that can bound to a pipeline as a resource for a 2D unsigned
/// integer sampler.
#[derive(Clone)]
pub struct UnsignedIntegerSampledTexture2D<'a> {
    pub(crate) sampler_data: Arc<SamplerData>,
    pub(crate) texture_data: Arc<Texture2DData>,
    _marker: marker::PhantomData<&'a ()>,
}

impl<F> Texture2D<F>
where
    F: TextureFormat + ShadowSamplable + 'static,
{
    /// Combines this [Texture2D] with the `shadow_sampler` as a [ShadowSampledTexture2D], which
    /// can be bound to a pipeline as a texture resource.
    ///
    /// See also [web_glitz::pipeline::resources::Resources].
    ///
    /// # Panics
    ///
    /// Panics if this texture and the `shadow_sampler` do not belong to the same
    /// [RenderingContext].
    pub fn shadow_sampled(&self, shadow_sampler: &ShadowSampler) -> ShadowSampledTexture2D {
        if self.data().context_id() != shadow_sampler.data().context_id() {
            panic!("Texture and sampler do not belong to the same context.");
        }

        ShadowSampledTexture2D {
            sampler_data: shadow_sampler.data().clone(),
            texture_data: self.data().clone(),
            _marker: marker::PhantomData,
        }
    }
}

/// A texture-sampler combination that can bound to a pipeline as a resource for a 2D shadow
/// sampler.
#[derive(Clone)]
pub struct ShadowSampledTexture2D<'a> {
    pub(crate) sampler_data: Arc<SamplerData>,
    pub(crate) texture_data: Arc<Texture2DData>,
    _marker: marker::PhantomData<&'a ()>,
}

impl<F> PartialEq for Texture2D<F> {
    fn eq(&self, other: &Self) -> bool {
        self.object_id == other.object_id
    }
}

impl<F> Hash for Texture2D<F> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.object_id.hash(state);
    }
}

pub(crate) struct Texture2DData {
    id: UnsafeCell<Option<JsId>>,
    context_id: u64,
    dropper: Box<dyn TextureObjectDropper>,
    width: u32,
    height: u32,
    levels: usize,
}

impl Texture2DData {
    pub(crate) fn id(&self) -> Option<JsId> {
        unsafe { *self.id.get() }
    }

    pub(crate) fn context_id(&self) -> u64 {
        self.context_id
    }
}

impl PartialEq for Texture2DData {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl Hash for Texture2DData {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.id().hash(state);
    }
}

impl Drop for Texture2DData {
    fn drop(&mut self) {
        if let Some(id) = self.id() {
            self.dropper.drop_texture_object(id);
        }
    }
}

/// Returned from [Texture2D::levels], a reference to the levels of a [Texture2D].
///
/// See [Texture2D::levels] for details.
#[derive(PartialEq, Hash)]
pub struct Levels<'a, F> {
    handle: &'a Texture2D<F>,
    offset: usize,
    len: usize,
}

impl<'a, F> Levels<'a, F>
where
    F: TextureFormat,
{
    /// The number of levels defined for the [Texture2D].
    pub fn len(&self) -> usize {
        self.handle.data.levels
    }

    /// Returns a reference to level at the `index`, or `None` if the `index` is out of bounds.
    ///
    /// See also [get_unchecked] for an unsafe variant of this method that does not do any bounds
    /// checks.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::MipmapLevels;
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Partial(3)
    /// }).unwrap();
    ///
    /// let levels = texture.levels();
    ///
    /// assert_eq!(levels.get(1).map(|l| (l.width(), l.height())), Some((128, 128)));
    /// assert_eq!(levels.get(4).map(|l| (l.width(), l.height())), None);
    /// # }
    /// ```
    pub fn get<'b, I>(&'b self, index: I) -> Option<I::Output>
    where
        I: LevelsIndex<'b, F>,
    {
        index.get(self)
    }

    /// Returns a reference to level at the `index`, without doing any bounds checks.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::MipmapLevels;
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Partial(3)
    /// }).unwrap();
    ///
    /// let levels = texture.levels();
    ///
    /// let level = unsafe { levels.get_unchecked(1) };
    ///
    /// assert_eq!((level.width(), level.height()), (128, 128));
    /// # }
    /// ```
    ///
    /// # Unsafe
    ///
    /// The `index` must be in bounds. See also [get] for a safe variant of this method that does
    /// bounds checks.
    pub unsafe fn get_unchecked<'b, I>(&'b self, index: I) -> I::Output
    where
        I: LevelsIndex<'b, F>,
    {
        index.get_unchecked(self)
    }

    /// Returns an iterator over the levels.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::MipmapLevels;
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Partial(3)
    /// }).unwrap();
    ///
    /// let levels = texture.levels();
    /// let mut iter = levels.iter();
    ///
    /// assert_eq!(iter.next().map(|l| (l.width(), l.height())), Some((128, 128)));
    /// assert_eq!(iter.next().map(|l| (l.width(), l.height())), Some((64, 64)));
    /// assert_eq!(iter.next().map(|l| (l.width(), l.height())), Some((32, 32)));
    /// assert_eq!(iter.next().map(|l| (l.width(), l.height())), None);
    /// # }
    /// ```
    pub fn iter(&self) -> LevelsIter<F> {
        LevelsIter {
            handle: &self.handle,
            current_level: self.offset,
            end_level: self.offset + self.len,
        }
    }
}

impl<'a, F> IntoIterator for Levels<'a, F>
where
    F: TextureFormat,
{
    type Item = Level<'a, F>;

    type IntoIter = LevelsIter<'a, F>;

    fn into_iter(self) -> Self::IntoIter {
        LevelsIter {
            handle: &self.handle,
            current_level: self.offset,
            end_level: self.offset + self.len,
        }
    }
}

impl<'a, F> Clone for Levels<'a, F> {
    fn clone(&self) -> Self {
        Levels {
            handle: self.handle,
            offset: self.offset,
            len: self.len,
        }
    }
}

impl<'a, F> Copy for Levels<'a, F> {}

/// An iterator over [Levels].
///
/// See [Levels::iter] for details.
pub struct LevelsIter<'a, F> {
    handle: &'a Texture2D<F>,
    current_level: usize,
    end_level: usize,
}

impl<'a, F> Iterator for LevelsIter<'a, F>
where
    F: TextureFormat,
{
    type Item = Level<'a, F>;

    fn next(&mut self) -> Option<Self::Item> {
        let level = self.current_level;

        if level < self.end_level {
            self.current_level += 1;

            Some(Level {
                handle: &self.handle,
                level,
            })
        } else {
            None
        }
    }
}

/// A helper trait for indexing [Levels].
///
/// See [Levels::get] and [Levels::get_unchecked].
pub trait LevelsIndex<'a, F> {
    /// The output type returned by the indexing operations.
    type Output;

    /// Returns the output for this operation if in bounds, or `None` otherwise.
    fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;

    /// Returns the output for this operation, without performing any bounds checking.
    unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;
}

impl<'a, F> LevelsIndex<'a, F> for usize
where
    F: 'a,
{
    type Output = Level<'a, F>;

    fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {
        if self < levels.len {
            Some(Level {
                handle: levels.handle,
                level: levels.offset + self,
            })
        } else {
            None
        }
    }

    unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output {
        Level {
            handle: levels.handle,
            level: levels.offset + self,
        }
    }
}

impl<'a, F> LevelsIndex<'a, F> for RangeFull
where
    F: 'a,
{
    type Output = Levels<'a, F>;

    fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {
        Some(Levels {
            handle: levels.handle,
            offset: levels.offset,
            len: levels.len,
        })
    }

    unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output {
        Levels {
            handle: levels.handle,
            offset: levels.offset,
            len: levels.len,
        }
    }
}

impl<'a, F> LevelsIndex<'a, F> for Range<usize>
where
    F: 'a,
{
    type Output = Levels<'a, F>;

    fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {
        let Range { start, end } = self;

        if start > end || end > levels.len {
            None
        } else {
            Some(Levels {
                handle: levels.handle,
                offset: levels.offset + start,
                len: end - start,
            })
        }
    }

    unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output {
        let Range { start, end } = self;

        Levels {
            handle: levels.handle,
            offset: levels.offset + start,
            len: end - start,
        }
    }
}

impl<'a, F> LevelsIndex<'a, F> for RangeInclusive<usize>
where
    F: 'a,
{
    type Output = Levels<'a, F>;

    fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {
        if *self.end() == usize::max_value() {
            None
        } else {
            (*self.start()..self.end() + 1).get(levels)
        }
    }

    unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output {
        (*self.start()..self.end() + 1).get_unchecked(levels)
    }
}

impl<'a, F> LevelsIndex<'a, F> for RangeFrom<usize>
where
    F: 'a,
{
    type Output = Levels<'a, F>;

    fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {
        (self.start..levels.len).get(levels)
    }

    unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output {
        (self.start..levels.len).get_unchecked(levels)
    }
}

impl<'a, F> LevelsIndex<'a, F> for RangeTo<usize>
where
    F: 'a,
{
    type Output = Levels<'a, F>;

    fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {
        (0..self.end).get(levels)
    }

    unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output {
        (0..self.end).get_unchecked(levels)
    }
}

impl<'a, F> LevelsIndex<'a, F> for RangeToInclusive<usize>
where
    F: 'a,
{
    type Output = Levels<'a, F>;

    fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {
        (0..=self.end).get(levels)
    }

    unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output {
        (0..=self.end).get_unchecked(levels)
    }
}

/// A reference to a mipmap level of a [Texture2D].
///
/// A reference to the base level of a [Texture2D] can be obtained through [Texture2D::base_level].
/// References to other levels of a [Texture2D] can be obtained via [Levels].
#[derive(PartialEq, Hash)]
pub struct Level<'a, F> {
    handle: &'a Texture2D<F>,
    level: usize,
}

impl<'a, F> Level<'a, F>
where
    F: TextureFormat,
{
    pub(crate) fn texture_data(&self) -> &Arc<Texture2DData> {
        self.handle.data()
    }

    /// Returns the integer that identifies this level.
    ///
    /// For example, if this [Level] is the texture's base level, returns `0`; if it is the second
    /// level, returns `1`; etc.
    pub fn level(&self) -> usize {
        self.level
    }

    /// Returns the width of this level.
    pub fn width(&self) -> u32 {
        mipmap_size(self.handle.data.width, self.level)
    }

    /// Returns the height of this level.
    pub fn height(&self) -> u32 {
        mipmap_size(self.handle.data.height, self.level)
    }

    /// Returns a reference to the sub-region of this [Level]'s image described by `region`.
    ///
    /// # Example
    ///
    /// This may for example be used to upload data to only a sub-region of an image, rather than
    /// the complete image:
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::image::{Image2DSource, MipmapLevels, Region2D};
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Complete
    /// }).unwrap();
    ///
    /// let base_level = texture.base_level();
    /// let sub_image = base_level.sub_image(Region2D::Area((0, 0), 128, 128));
    ///
    /// let pixels: Vec<[u8; 3]> = vec![[0, 0, 255]; 128 * 128];
    /// let data = Image2DSource::from_pixels(pixels, 128, 128).unwrap();
    ///
    /// context.submit(sub_image.upload_command(data));
    /// # }
    /// ```
    ///
    /// The lower left quadrant of the texture's base level now contains blue pixels, while the
    /// rest of the base levels remains black (texture storage starts out with all bits set to `0`,
    /// which with format [RGB8] is interpreted as black).
    pub fn sub_image(&self, region: Region2D) -> LevelSubImage<F> {
        LevelSubImage {
            handle: &self.handle,
            level: self.level,
            region,
        }
    }

    /// Returns a command which, when executed, replaces the image data in this [Level]'s image
    /// with the image data provided in `data`.
    ///
    /// The image data must be stored as a [PixelUnpack] type that is suitable for the texture's
    /// [TextureFormat].
    ///
    /// If the dimensions of the image provided in `data` are not sufficient to cover the [Level]'s
    /// image entirely, starting from the origin, then only the region of overlap is updated (note
    /// that the origin of an image is the lower left corner). For example, given a [Level] with a
    /// width of 256 pixels and a height of 256 pixels, and `data` with a width of 128 pixels and a
    /// height of 128 pixels, then only the lower left quadrant of the [Level] is updated. If the
    /// dimensions of the image provided in `data` would, when starting from the origin, cover more
    /// than the [Level]'s image (the width and/or height of `data` is/are greater than the width
    /// and/or height of the [Level]'s image), then any pixels that would fall outside of the
    /// [Level] are ignored. For example, given a [Level] with a width of 256 pixels and a height of
    /// 256 pixels, and `data` with a width of 256 pixels and a height of 512 pixels, then only the
    /// lower half of the image in `data` is used to update the [Level] and the upper half is
    /// ignored.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::image::{Image2DSource, MipmapLevels};
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Complete
    /// }).unwrap();
    ///
    /// let pixels: Vec<[u8; 3]> = vec![[255, 0, 0]; 256 * 256];
    /// let data = Image2DSource::from_pixels(pixels, 256, 256).unwrap();
    ///
    /// context.submit(texture.base_level().upload_command(data));
    /// # }
    /// ```
    pub fn upload_command<D, T>(&self, data: Image2DSource<D, T>) -> UploadCommand<D, T, F>
    where
        T: PixelUnpack<F>,
    {
        UploadCommand {
            data,
            texture_data: self.handle.data.clone(),
            level: self.level,
            region: Region2D::Fill,
            _marker: marker::PhantomData,
        }
    }

    pub fn pack_to_buffer_command<P>(&self, buffer: BufferView<[P]>) -> PackToBufferCommand<F, P>
    where
        P: PixelPack<F>,
    {
        let offset = buffer.offset_in_bytes();
        let buffer_data = buffer.buffer_data();
        let texture_data = self.texture_data();

        if buffer_data.context_id() != texture_data.context_id() {
            panic!("Buffer belongs to a different context");
        }

        PackToBufferCommand {
            texture_data: texture_data.clone(),
            buffer_data: buffer_data.clone(),
            offset,
            level: self.level,
            region: Region2D::Fill,
            _marker: marker::PhantomData,
        }
    }
}

/// Returned from [Level::sub_image], a reference to a sub-region of a [Level]'s image.
///
/// See [Level::sub_image] for details.
#[derive(PartialEq, Hash)]
pub struct LevelSubImage<'a, F> {
    handle: &'a Texture2D<F>,
    level: usize,
    region: Region2D,
}

impl<'a, F> LevelSubImage<'a, F>
where
    F: TextureFormat,
{
    pub(crate) fn level_ref(&self) -> Level<F> {
        Level {
            handle: self.handle,
            level: self.level,
        }
    }

    pub(crate) fn texture_data(&self) -> &Arc<Texture2DData> {
        &self.handle.data
    }

    /// Returns the index of the mipmap level this [LevelSubImage] references.
    pub fn level(&self) -> usize {
        self.level
    }

    /// Returns the [Region2D] of the level this [LevelSubImage] references.
    pub fn region(&self) -> Region2D {
        self.region
    }

    /// Returns the width of this [LevelSubImage].
    pub fn width(&self) -> u32 {
        region_2d_overlap_width(self.handle.data.width, self.level, &self.region)
    }

    /// Returns the height of this [LevelSubImage].
    pub fn height(&self) -> u32 {
        region_2d_overlap_height(self.handle.data.height, self.level, &self.region)
    }

    /// Returns a reference to the sub-region of this [LevelSubImage]'s image described by `region`.
    ///
    /// See also [Level::sub_image].
    pub fn sub_image(&self, region: Region2D) -> LevelSubImage<F> {
        LevelSubImage {
            handle: &self.handle,
            level: self.level,
            region: region_2d_sub_image(self.region, region),
        }
    }

    /// Returns a command which, when executed, replaces the image data in this [LevelSubImage]'s
    /// image region with the image data provided in `data`.
    ///
    /// The image data must be stored as a [PixelUnpack] type that is suitable for the texture's
    /// [TextureFormat].
    ///
    /// If the dimensions of the image provided in `data` are not sufficient to cover the
    /// [LevelSubImage] region entirely, starting from the region's origin, then only the region of
    /// overlap is updated (note that the origin of a region is at its lower left corner). For
    /// example, given a [LevelSubImage] with a width of 256 pixels and a height of 256 pixels, and
    /// `data` with a width of 128 pixels and a height of 128 pixels, then only the lower left
    /// quadrant of the [LevelSubImage]'s region is updated. If the dimensions of the image provided
    /// in `data` would, when starting from the [LevelSubImage]'s origin, cover more than the
    /// [LevelSubImage]'s region (the width and/or height of `data` is/are greater than the width
    /// and/or height of the [LevelSubImage]'s region), then any pixels that would fall outside of
    /// the [LevelSubImage]'s region are ignored. For example, given a [LevelSubImage] with a width
    /// of 256 pixels and a height of 256 pixels, and `data` with a width of 256 pixels and a height
    /// of 512 pixels, then only the lower half of the image in `data` is used to update the
    /// [LevelSubImage] and the upper half is ignored.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::image::{Image2DSource, MipmapLevels, Region2D};
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Complete
    /// }).unwrap();
    ///
    /// let base_level = texture.base_level();
    /// let sub_image = base_level.sub_image(Region2D::Area((0, 0), 128, 128));
    ///
    /// let pixels: Vec<[u8; 3]> = vec![[255, 0, 0]; 128 * 128];
    /// let data = Image2DSource::from_pixels(pixels, 128, 128).unwrap();
    ///
    /// context.submit(sub_image.upload_command(data));
    /// # }
    /// ```
    pub fn upload_command<D, T>(&self, data: Image2DSource<D, T>) -> UploadCommand<D, T, F>
    where
        T: PixelUnpack<F>,
    {
        UploadCommand {
            data,
            texture_data: self.handle.data.clone(),
            level: self.level,
            region: self.region,
            _marker: marker::PhantomData,
        }
    }

    pub fn pack_to_buffer_command<P>(&self, buffer: BufferView<[P]>) -> PackToBufferCommand<F, P>
    where
        P: PixelPack<F>,
    {
        let offset = buffer.offset_in_bytes();
        let buffer_data = buffer.buffer_data();
        let texture_data = self.texture_data();

        if buffer_data.context_id() != texture_data.context_id() {
            panic!("Buffer belongs to a different context");
        }

        PackToBufferCommand {
            texture_data: texture_data.clone(),
            buffer_data: buffer_data.clone(),
            offset,
            level: self.level,
            region: self.region,
            _marker: marker::PhantomData,
        }
    }
}

/// Returned from [Texture2D::levels_mut], a mutable reference to the levels of a [Texture2D].
///
/// See [Texture2D::levels_mut] for details.
///
/// [Deref]s to [Levels].
#[derive(PartialEq, Hash)]
pub struct LevelsMut<'a, F> {
    inner: Levels<'a, F>,
}

impl<'a, F> LevelsMut<'a, F>
where
    F: TextureFormat,
{
    /// Returns a mutable reference to level at the `index`, or `None` if the `index` is out of
    /// bounds.
    ///
    /// See also [get_unchecked_mut] for an unsafe variant or this method that does not do any
    /// bounds checks.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::MipmapLevels;
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let mut texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Partial(3)
    /// }).unwrap();
    ///
    /// let mut levels = texture.levels_mut();
    ///
    /// assert_eq!(levels.get_mut(1).map(|l| (l.width(), l.height())), Some((128, 128)));
    /// assert_eq!(levels.get_mut(4).map(|l| (l.width(), l.height())), None);
    /// # }
    /// ```
    pub fn get_mut<'b, I>(&'b mut self, index: I) -> Option<I::Output>
    where
        I: LevelsMutIndex<'b, F>,
    {
        index.get_mut(self)
    }

    /// Returns a mutable reference to level at the `index`, without doing any bounds checks.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::MipmapLevels;
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let mut texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Partial(3)
    /// }).unwrap();
    ///
    /// let mut levels = texture.levels_mut();
    ///
    /// let level = unsafe { levels.get_unchecked_mut(1) };
    ///
    /// assert_eq!((level.width(), level.height()), (128, 128));
    /// # }
    /// ```
    ///
    /// # Unsafe
    ///
    /// The `index` must be in bounds. See also [get_mut] for a safe variant of this method that
    /// does bounds checks.
    pub unsafe fn get_unchecked_mut<'b, I>(&'b mut self, index: I) -> I::Output
    where
        I: LevelsMutIndex<'b, F>,
    {
        index.get_unchecked_mut(self)
    }

    /// Returns an iterator over mutable references to the levels.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::MipmapLevels;
    /// use web_glitz::image::format::RGB8;
    /// use web_glitz::image::texture_2d::Texture2DDescriptor;
    ///
    /// let mut texture = context.try_create_texture_2d(&Texture2DDescriptor {
    ///     format: RGB8,
    ///     width: 256,
    ///     height: 256,
    ///     levels: MipmapLevels::Partial(3)
    /// }).unwrap();
    ///
    /// let mut levels = texture.levels_mut();
    /// let mut iter = levels.iter_mut();
    ///
    /// assert_eq!(iter.next().map(|l| (l.width(), l.height())), Some((128, 128)));
    /// assert_eq!(iter.next().map(|l| (l.width(), l.height())), Some((64, 64)));
    /// assert_eq!(iter.next().map(|l| (l.width(), l.height())), Some((32, 32)));
    /// assert_eq!(iter.next().map(|l| (l.width(), l.height())), None);
    /// # }
    /// ```
    pub fn iter_mut(&mut self) -> LevelsMutIter<F> {
        LevelsMutIter {
            current_level: self.offset,
            end_level: self.offset + self.len,
            handle: &self.inner.handle,
        }
    }
}

impl<'a, F> IntoIterator for LevelsMut<'a, F>
where
    F: TextureFormat,
{
    type Item = LevelMut<'a, F>;

    type IntoIter = LevelsMutIter<'a, F>;

    fn into_iter(self) -> Self::IntoIter {
        LevelsMutIter {
            current_level: self.offset,
            end_level: self.offset + self.len,
            handle: &self.inner.handle,
        }
    }
}

impl<'a, F> Deref for LevelsMut<'a, F>
where
    F: TextureFormat,
{
    type Target = Levels<'a, F>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

/// An iterator over [LevelsMut].
///
/// See [LevelsMut::iter_mut] for details.
pub struct LevelsMutIter<'a, F> {
    handle: &'a Texture2D<F>,
    current_level: usize,
    end_level: usize,
}

impl<'a, F> Iterator for LevelsMutIter<'a, F>
where
    F: TextureFormat,
{
    type Item = LevelMut<'a, F>;

    fn next(&mut self) -> Option<Self::Item> {
        let level = self.current_level;

        if level < self.end_level {
            self.current_level += 1;

            Some(LevelMut {
                inner: Level {
                    handle: &self.handle,
                    level,
                },
            })
        } else {
            None
        }
    }
}

/// A helper trait for indexing a [LevelsMut].
///
/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].
pub trait LevelsMutIndex<'a, F> {
    /// The output type returned by the indexing operations.
    type Output;

    /// Returns the output for this operation if in bounds, or `None` otherwise.
    fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;

    /// Returns the output for this operation, without performing any bounds checking.
    unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;
}

impl<'a, F> LevelsMutIndex<'a, F> for usize
where
    F: 'a,
{
    type Output = LevelMut<'a, F>;

    fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {
        if self < levels.inner.len {
            Some(LevelMut {
                inner: Level {
                    handle: levels.inner.handle,
                    level: levels.inner.offset + self,
                },
            })
        } else {
            None
        }
    }

    unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output {
        LevelMut {
            inner: Level {
                handle: levels.inner.handle,
                level: levels.inner.offset + self,
            },
        }
    }
}

impl<'a, F> LevelsMutIndex<'a, F> for RangeFull
where
    F: 'a,
{
    type Output = LevelsMut<'a, F>;

    fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {
        Some(LevelsMut {
            inner: Levels {
                handle: levels.inner.handle,
                offset: levels.inner.offset,
                len: levels.inner.len,
            },
        })
    }

    unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output {
        LevelsMut {
            inner: Levels {
                handle: levels.inner.handle,
                offset: levels.inner.offset,
                len: levels.inner.len,
            },
        }
    }
}

impl<'a, F> LevelsMutIndex<'a, F> for Range<usize>
where
    F: 'a,
{
    type Output = LevelsMut<'a, F>;

    fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {
        let Range { start, end } = self;

        if start > end || end > levels.inner.len {
            None
        } else {
            Some(LevelsMut {
                inner: Levels {
                    handle: levels.inner.handle,
                    offset: levels.inner.offset + start,
                    len: end - start,
                },
            })
        }
    }

    unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output {
        let Range { start, end } = self;

        LevelsMut {
            inner: Levels {
                handle: levels.inner.handle,
                offset: levels.inner.offset + start,
                len: end - start,
            },
        }
    }
}

impl<'a, F> LevelsMutIndex<'a, F> for RangeInclusive<usize>
where
    F: 'a,
{
    type Output = LevelsMut<'a, F>;

    fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {
        if *self.end() == usize::max_value() {
            None
        } else {
            (*self.start()..self.end() + 1).get_mut(levels)
        }
    }

    unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output {
        (*self.start()..self.end() + 1).get_unchecked_mut(levels)
    }
}

impl<'a, F> LevelsMutIndex<'a, F> for RangeFrom<usize>
where
    F: 'a,
{
    type Output = LevelsMut<'a, F>;

    fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {
        (self.start..levels.inner.len).get_mut(levels)
    }

    unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output {
        (self.start..levels.inner.len).get_unchecked_mut(levels)
    }
}

impl<'a, F> LevelsMutIndex<'a, F> for RangeTo<usize>
where
    F: 'a,
{
    type Output = LevelsMut<'a, F>;

    fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {
        (0..self.end).get_mut(levels)
    }

    unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output {
        (0..self.end).get_unchecked_mut(levels)
    }
}

impl<'a, F> LevelsMutIndex<'a, F> for RangeToInclusive<usize>
where
    F: 'a,
{
    type Output = LevelsMut<'a, F>;

    fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {
        (0..=self.end).get_mut(levels)
    }

    unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output {
        (0..=self.end).get_unchecked_mut(levels)
    }
}

/// A mutable reference to a [Texture2D] mipmap level.
///
/// [Deref]s to [Level].
#[derive(PartialEq, Hash)]
pub struct LevelMut<'a, F> {
    inner: Level<'a, F>,
}

impl<'a, F> Deref for LevelMut<'a, F> {
    type Target = Level<'a, F>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

struct AllocateCommand<F> {
    data: Arc<Texture2DData>,
    _marker: marker::PhantomData<[F]>,
}

unsafe impl<F> GpuTask<Connection> for AllocateCommand<F>
where
    F: TextureFormat,
{
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Id(self.data.context_id)
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        let (gl, state) = unsafe { connection.unpack_mut() };
        let data = &self.data;

        let texture_object = gl.create_texture().unwrap();

        state.set_active_texture_lru().apply(gl).unwrap();
        state
            .bind_texture_2d(Some(&texture_object))
            .apply(gl)
            .unwrap();

        let levels = data.levels as i32;

        gl.tex_storage_2d(
            Gl::TEXTURE_2D,
            levels,
            F::ID,
            data.width as i32,
            data.height as i32,
        );

        gl.tex_parameteri(Gl::TEXTURE_2D, Gl::TEXTURE_MAX_LEVEL, levels);

        unsafe {
            *data.id.get() = Some(JsId::from_value(texture_object.into()));
        }

        Progress::Finished(())
    }
}

/// Uploads data to a [Level] or [LevelSubImage].
///
/// See [Level::upload_command] and [LevelSubImage::upload_command] for details.
pub struct UploadCommand<D, T, F> {
    data: Image2DSource<D, T>,
    texture_data: Arc<Texture2DData>,
    level: usize,
    region: Region2D,
    _marker: marker::PhantomData<[F]>,
}

unsafe impl<D, T, F> GpuTask<Connection> for UploadCommand<D, T, F>
where
    D: Borrow<[T]>,
    T: PixelUnpack<F>,
    F: TextureFormat,
{
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Id(self.texture_data.context_id)
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        let mut width = region_2d_overlap_width(self.texture_data.width, self.level, &self.region);
        let height = region_2d_overlap_height(self.texture_data.height, self.level, &self.region);

        if width == 0 || height == 0 {
            return Progress::Finished(());
        }

        let (gl, state) = unsafe { connection.unpack_mut() };

        match &self.data.internal {
            Image2DSourceInternal::PixelData {
                data,
                row_length,
                alignment,
                ..
            } => {
                state.set_active_texture_lru().apply(gl).unwrap();

                unsafe {
                    self.texture_data
                        .id()
                        .unwrap()
                        .with_value_unchecked(|texture_object| {
                            state
                                .bind_texture_2d(Some(texture_object))
                                .apply(gl)
                                .unwrap();
                        });
                }

                state
                    .set_pixel_unpack_alignment((*alignment).into())
                    .apply(gl)
                    .unwrap();

                if width < *row_length {
                    state
                        .set_pixel_unpack_row_length(*row_length as i32)
                        .apply(gl)
                        .unwrap();
                } else {
                    width = *row_length;

                    state.set_pixel_unpack_row_length(0).apply(gl).unwrap();
                }

                let (offset_x, offset_y) = match self.region {
                    Region2D::Fill => (0, 0),
                    Region2D::Area((offset_x, offset_y), ..) => (offset_x, offset_y),
                };

                let elements = *row_length as usize * height as usize;
                let data_buffer = texture_data_as_js_buffer(data.borrow(), elements);

                gl.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
                    Gl::TEXTURE_2D,
                    self.level as i32,
                    offset_x as i32,
                    offset_y as i32,
                    width as i32,
                    height as i32,
                    T::FORMAT_ID,
                    T::TYPE_ID,
                    Some(&data_buffer),
                )
                .unwrap();
            }
        }

        Progress::Finished(())
    }
}

/// Copies the image data of a [Level] or [LevelSubImage] into a [Buffer].
///
/// See [Level::pack_to_buffer_command] and [LevelSubImage::pack_to_buffer_command] for details.
pub struct PackToBufferCommand<F, P> {
    texture_data: Arc<Texture2DData>,
    buffer_data: Arc<BufferData>,
    offset: usize,
    level: usize,
    region: Region2D,
    _marker: marker::PhantomData<(Box<[F]>, Box<[P]>)>,
}

unsafe impl<F, P> GpuTask<Connection> for PackToBufferCommand<F, P>
where
    F: TextureFormat,
    P: PixelPack<F>,
{
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Id(self.texture_data.context_id)
    }

    fn progress(&mut self, context: &mut Connection) -> Progress<Self::Output> {
        let width = region_2d_overlap_width(self.texture_data.width, self.level, &self.region);
        let height = region_2d_overlap_height(self.texture_data.height, self.level, &self.region);

        if width == 0 || height == 0 {
            return Progress::Finished(());
        }

        let (offset_x, offset_y) = match self.region {
            Region2D::Fill => (0, 0),
            Region2D::Area((offset_x, offset_y), ..) => (offset_x, offset_y),
        };

        let (gl, state) = unsafe { context.unpack_mut() };

        state.bind_default_read_framebuffer(gl);

        unsafe {
            self.texture_data
                .id()
                .unwrap()
                .with_value_unchecked(|texture_object| {
                    gl.framebuffer_texture_2d(
                        Gl::READ_FRAMEBUFFER,
                        Gl::COLOR_ATTACHMENT0,
                        Gl::TEXTURE_2D,
                        Some(&texture_object),
                        self.level as i32,
                    );
                });

            self.buffer_data
                .id()
                .unwrap()
                .with_value_unchecked(|buffer_object| {
                    state
                        .bind_pixel_pack_buffer(Some(buffer_object))
                        .apply(gl)
                        .unwrap();
                })
        }

        gl.read_pixels_with_i32(
            offset_x as i32,
            offset_y as i32,
            width as i32,
            height as i32,
            P::FORMAT_ID,
            P::TYPE_ID,
            self.offset as i32,
        )
        .unwrap();

        Progress::Finished(())
    }
}

/// Returned from [Texture2D::generate_mipmap_command], generates the image data for a [Texture2D]'s
/// mipmap chain.
///
/// See [Texture2D::generate_mipmap_command] for details.
pub struct GenerateMipmapCommand {
    texture_data: Arc<Texture2DData>,
}

unsafe impl GpuTask<Connection> for GenerateMipmapCommand {
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Id(self.texture_data.context_id)
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        let (gl, state) = unsafe { connection.unpack_mut() };

        unsafe {
            self.texture_data
                .id()
                .unwrap()
                .with_value_unchecked(|texture_object| {
                    state.bind_texture_2d(Some(texture_object));
                });
        }

        gl.generate_mipmap(Gl::TEXTURE_2D);

        Progress::Finished(())
    }
}