ggez 0.10.0

A lightweight game framework for making 2D games with minimum friction, inspired by Love2D.
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
use crate::{
    context::HasMut,
    graphics::{self, Canvas3d, DrawParam3d, Image},
};

#[cfg(feature = "gltf")]
use crate::{GameError, GameResult};
#[cfg(feature = "gltf")]
use base64::Engine;
#[cfg(feature = "gltf")]
use glam::Mat4;
#[cfg(feature = "gltf")]
use gltf::scene::Transform;
#[cfg(feature = "gltf")]
use image::EncodableLayout;
#[cfg(feature = "obj")]
use num_traits::FromPrimitive;
#[cfg(feature = "gltf")]
use std::path::Path;

use glam::Vec3;
use mint::{Vector2, Vector3};
use std::sync::Arc;
use wgpu::{util::DeviceExt, vertex_attr_array};

use crate::graphics::{Drawable3d, GraphicsContext};

use super::{Draw3d, Transform3d};

#[cfg(feature = "gltf")]
fn transform_to_matrix(transform: Transform) -> Mat4 {
    let tr = transform.matrix();
    Mat4::from_cols_array_2d(&tr)
}

// Implementation tooken from bevy
/// An aabb stands for axis aligned bounding box. This is basically a cube that can't rotate.
#[derive(Debug, Copy, Clone)]
pub struct Aabb {
    /// The center of this `Aabb`
    pub center: mint::Point3<f32>,
    /// The half_extents or half the size of this `Aabb` for each axis
    pub half_extents: mint::Point3<f32>,
}

impl Default for Aabb {
    fn default() -> Self {
        Self {
            center: Vec3::ZERO.into(),
            half_extents: Vec3::ZERO.into(),
        }
    }
}

impl Aabb {
    /// Create an `Aabb` from a minimum point and a maximum point
    #[inline]
    pub fn from_min_max(minimum: Vec3, maximum: Vec3) -> Self {
        let center = 0.5 * (maximum + minimum);
        let half_extents = 0.5 * (maximum - minimum);
        Self {
            center: center.into(),
            half_extents: half_extents.into(),
        }
    }
}

// TODO: Allow custom vertex formats
/// The 3d Vertex format. Used for constructing meshes. At the moment it supports color, position, normals, and texture coords
#[derive(Clone, Copy, bytemuck::Zeroable, bytemuck::Pod, Debug)]
#[repr(C)]
pub struct Vertex3d {
    /// The position of this vertex
    pub pos: [f32; 3],
    /// The texture uv of this vertex
    pub tex_coord: [f32; 2],
    /// The color of this vertex
    pub color: [f32; 4],
    /// Normal of this vertex (the direction it faces)
    pub normals: [f32; 3],
}

impl Vertex3d {
    /// Create a new vertex from a position, uv, normals, and color
    pub fn new<V, T, C, N>(position: V, uv: T, color: C, normals: N) -> Vertex3d
    where
        V: Into<Vector3<f32>>,
        T: Into<Vector2<f32>>,
        C: Into<Option<graphics::Color>>,
        N: Into<Vector3<f32>>,
    {
        let position: Vector3<f32> = position.into();
        let normals: Vector3<f32> = normals.into();
        let uv: Vector2<f32> = uv.into();
        let color: Option<graphics::Color> = color.into();
        let color = color
            .unwrap_or(graphics::Color::new(1.0, 1.0, 1.0, 1.0))
            .into();
        Vertex3d {
            pos: position.into(),
            tex_coord: uv.into(),
            color,
            normals: normals.into(),
        }
    }

    pub(crate) fn desc() -> wgpu::VertexBufferLayout<'static> {
        const ATTRIBS: [wgpu::VertexAttribute; 4] = vertex_attr_array![
            0 => Float32x3,
            1 => Float32x2,
            2 => Float32x4,
            3 => Float32x3,
        ];
        wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<Vertex3d>() as _,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &ATTRIBS,
        }
    }
}

/// A struct to help create `Mesh3d`
#[derive(Clone, Debug, Default)]
pub struct Mesh3dBuilder {
    /// Vector of the vertices that make up the mesh
    pub vertices: Vec<Vertex3d>,
    /// Vector of the indices used to index into the vertices of the mesh
    pub indices: Vec<u32>,
    /// The texture of the Mesh if any
    pub texture: Option<Image>,
}

impl Mesh3dBuilder {
    /// Create an empty `Mesh3dBuilder`
    pub fn new() -> Self {
        Self {
            vertices: Vec::default(),
            indices: Vec::default(),
            texture: None,
        }
    }

    /// Add data that makes up a mesh.
    pub fn from_data(
        &mut self,
        vertices: Vec<Vertex3d>,
        indices: Vec<u32>,
        texture: Option<Image>,
    ) -> &mut Self {
        self.vertices = vertices;
        self.indices = indices;
        self.texture = texture;
        self
    }

    /// Create a cube mesh from `Vector3<f32>` size
    pub fn cube(&mut self, size: impl Into<mint::Vector3<f32>>) -> &mut Self {
        let size: mint::Vector3<f32> = size.into();
        let min = -glam::Vec3::from(size) / 2.0;
        let max = glam::Vec3::from(size) / 2.0;
        self.vertices = vec![
            // top (0, 0, 1)
            Vertex3d::new(
                [min.x, max.y, max.z],
                [0.0, 1.0],
                graphics::Color::WHITE,
                [0.0, 1.0, 0.0],
            ),
            Vertex3d::new(
                [max.x, max.y, max.z],
                [1.0, 1.0],
                graphics::Color::WHITE,
                [0.0, 1.0, 0.0],
            ),
            Vertex3d::new(
                [max.x, max.y, min.z],
                [1.0, 0.0],
                graphics::Color::WHITE,
                [0.0, 1.0, 0.0],
            ),
            Vertex3d::new(
                [min.x, max.y, min.z],
                [0.0, 0.0],
                graphics::Color::WHITE,
                [0.0, 1.0, 0.0],
            ),
            // bottom (0.0, 0.0, -1.0, graphics::Color::WHITE)
            Vertex3d::new(
                [min.x, min.y, min.z],
                [1.0, 1.0],
                graphics::Color::WHITE,
                [0.0, -1.0, 0.0],
            ),
            Vertex3d::new(
                [max.x, min.y, min.z],
                [0.0, 1.0],
                graphics::Color::WHITE,
                [0.0, -1.0, 0.0],
            ),
            Vertex3d::new(
                [max.x, min.y, max.z],
                [0.0, 0.0],
                graphics::Color::WHITE,
                [0.0, -1.0, 0.0],
            ),
            Vertex3d::new(
                [min.x, min.y, max.z],
                [1.0, 0.0],
                graphics::Color::WHITE,
                [0.0, -1.0, 0.0],
            ),
            // right (1.0, 0.0, 0.0, graphics::Color::WHITE)
            Vertex3d::new(
                [max.x, max.y, min.z],
                [0.0, 1.0],
                graphics::Color::WHITE,
                [1.0, 0.0, 0.0],
            ),
            Vertex3d::new(
                [max.x, max.y, max.z],
                [1.0, 1.0],
                graphics::Color::WHITE,
                [1.0, 0.0, 0.0],
            ),
            Vertex3d::new(
                [max.x, min.y, max.z],
                [1.0, 0.0],
                graphics::Color::WHITE,
                [1.0, 0.0, 0.0],
            ),
            Vertex3d::new(
                [max.x, min.y, min.z],
                [0.0, 0.0],
                graphics::Color::WHITE,
                [1.0, 0.0, 0.0],
            ),
            // left (-1.0, 0.0, 0.0, graphics::Color::WHITE)
            Vertex3d::new(
                [min.x, min.y, min.z],
                [1.0, 1.0],
                graphics::Color::WHITE,
                [-1.0, 0.0, 0.0],
            ),
            Vertex3d::new(
                [min.x, min.y, max.z],
                [0.0, 1.0],
                graphics::Color::WHITE,
                [-1.0, 0.0, 0.0],
            ),
            Vertex3d::new(
                [min.x, max.y, max.y],
                [0.0, 0.0],
                graphics::Color::WHITE,
                [-1.0, 0.0, 0.0],
            ),
            Vertex3d::new(
                [min.x, max.y, min.z],
                [1.0, 0.0],
                graphics::Color::WHITE,
                [-1.0, 0.0, 0.0],
            ),
            // front (0.0, 1.0, 0.0, graphics::Color::WHITE)
            Vertex3d::new(
                [max.x, max.y, max.z],
                [1.0, 1.0],
                graphics::Color::WHITE,
                [0.0, 0.0, 1.0],
            ),
            Vertex3d::new(
                [min.x, max.y, max.z],
                [0.0, 1.0],
                graphics::Color::WHITE,
                [0.0, 0.0, 1.0],
            ),
            Vertex3d::new(
                [min.x, min.y, max.z],
                [0.0, 0.0],
                graphics::Color::WHITE,
                [0.0, 0.0, 1.0],
            ),
            Vertex3d::new(
                [max.x, min.y, max.z],
                [1.0, 0.0],
                graphics::Color::WHITE,
                [0.0, 0.0, 1.0],
            ),
            // back (0.0, -1.0, 0.0, graphics::Color::WHITE)
            Vertex3d::new(
                [max.x, min.y, min.z],
                [0.0, 1.0],
                graphics::Color::WHITE,
                [0.0, 0.0, -1.0],
            ),
            Vertex3d::new(
                [min.x, min.y, min.z],
                [1.0, 1.0],
                graphics::Color::WHITE,
                [0.0, 0.0, -1.0],
            ),
            Vertex3d::new(
                [min.x, max.y, min.z],
                [1.0, 0.0],
                graphics::Color::WHITE,
                [0.0, 0.0, -1.0],
            ),
            Vertex3d::new(
                [max.x, max.y, min.z],
                [0.0, 0.0],
                graphics::Color::WHITE,
                [0.0, 0.0, -1.0],
            ),
        ];

        self.indices = vec![
            0, 1, 2, 2, 3, 0, // top
            4, 5, 6, 6, 7, 4, // bottom
            8, 9, 10, 10, 11, 8, // right
            12, 13, 14, 14, 15, 12, // left
            16, 17, 18, 18, 19, 16, // front
            20, 21, 22, 22, 23, 20, // back
        ];

        self
    }
    /// Creat a pyramid from a base_size and a height
    pub fn pyramid(
        &mut self,
        base_size: impl Into<mint::Vector2<f32>>,
        height: f32,
        invert: bool,
    ) -> &mut Self {
        let base_size: mint::Vector2<f32> = base_size.into();
        let min = -glam::Vec2::from(base_size) / 2.0;
        let max = glam::Vec2::from(base_size) / 2.0;
        if invert {
            self.vertices = vec![
                // Base
                Vertex3d::new(
                    [min.x, 0.0, max.y],
                    [0.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 1.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, max.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 1.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, min.y],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 1.0, 0.0],
                ),
                Vertex3d::new(
                    [min.x, 0.0, min.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 1.0, 0.0],
                ),
                // TODO: Make these normals correct angles as well
                // Side 1
                Vertex3d::new(
                    [max.x, 0.0, min.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [0.0, height, 0.0],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [min.x, 0.0, min.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                // Side 2
                Vertex3d::new(
                    [max.x, 0.0, max.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [0.0, height, 0.0],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, min.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                // Side 3
                Vertex3d::new(
                    [min.x, 0.0, max.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [0.0, height, 0.0],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, max.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                // Side 4
                Vertex3d::new(
                    [min.x, 0.0, min.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [0.0, height, 0.0],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [min.x, 0.0, max.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
            ];
        } else {
            self.vertices = vec![
                // Base
                Vertex3d::new(
                    [min.x, 0.0, min.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, -1.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, min.y],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, -1.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, max.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, -1.0, 0.0],
                ),
                Vertex3d::new(
                    [min.x, 0.0, max.y],
                    [0.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, -1.0, 0.0],
                ),
                // Side 1
                Vertex3d::new(
                    [min.x, 0.0, min.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [0.0, height, 0.0],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, min.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                // Side 2
                Vertex3d::new(
                    [max.x, 0.0, min.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [0.0, height, 0.0],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, max.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                // Side 3
                Vertex3d::new(
                    [max.x, 0.0, max.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [0.0, height, 0.0],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [min.x, 0.0, max.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                // Side 4
                Vertex3d::new(
                    [min.x, 0.0, max.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [0.0, height, 0.0],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
                Vertex3d::new(
                    [min.x, 0.0, min.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 0.0, 0.0],
                ),
            ];
        }
        self.indices = vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        self
    }
    /// Create a plane mesh from `Vector2<f32>` size
    pub fn plane(&mut self, size: impl Into<mint::Vector2<f32>>, invert: bool) -> &mut Self {
        let size: mint::Vector2<f32> = size.into();
        let min = -glam::Vec2::from(size) / 2.0;
        let max = glam::Vec2::from(size) / 2.0;
        if invert {
            self.vertices = vec![
                Vertex3d::new(
                    [min.x, 0.0, min.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, -1.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, min.y],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, -1.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, max.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, -1.0, 0.0],
                ),
                Vertex3d::new(
                    [min.x, 0.0, max.y],
                    [0.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, -1.0, 0.0],
                ),
            ];
        } else {
            self.vertices = vec![
                Vertex3d::new(
                    [min.x, 0.0, max.y],
                    [0.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 1.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, max.y],
                    [1.0, 1.0],
                    graphics::Color::WHITE,
                    [0.0, 1.0, 0.0],
                ),
                Vertex3d::new(
                    [max.x, 0.0, min.y],
                    [1.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 1.0, 0.0],
                ),
                Vertex3d::new(
                    [min.x, 0.0, min.y],
                    [0.0, 0.0],
                    graphics::Color::WHITE,
                    [0.0, 1.0, 0.0],
                ),
            ];
        }
        self.indices = vec![0, 1, 2, 0, 2, 3];

        self
    }
    /// Set texture of the mesh
    pub fn texture(&mut self, texture: Image) -> &mut Self {
        self.texture = Some(texture);
        self
    }

    /// Make a `Mesh3d` from this builder
    pub fn build(&self, gfx: &mut impl HasMut<GraphicsContext>) -> Mesh3d {
        let gfx = gfx.retrieve_mut();
        let verts = gfx
            .wgpu()
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: None,
                contents: bytemuck::cast_slice(self.vertices.as_slice()),
                usage: wgpu::BufferUsages::VERTEX,
            });
        let inds = gfx
            .wgpu()
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: None,
                contents: bytemuck::cast_slice(self.indices.as_slice()),
                usage: wgpu::BufferUsages::INDEX,
            });
        let mut mesh = Mesh3d {
            vert_buffer: Arc::new(verts),
            vertices: self.vertices.clone(),
            indices: self.indices.clone(),
            ind_buffer: Arc::new(inds),
            texture: self.texture.clone(),
            aabb: None,
        };
        mesh.calculate_aabb();
        mesh
    }
}

/// A 3d Mesh that can be rendered to `Canvas3d`
#[derive(Clone, Debug)]
pub struct Mesh3d {
    pub(crate) vert_buffer: Arc<wgpu::Buffer>,
    pub(crate) ind_buffer: Arc<wgpu::Buffer>,
    /// The texture of this Mesh if any
    pub texture: Option<Image>,
    /// Vector of the vertices that make up this mesh
    pub vertices: Vec<Vertex3d>,
    /// Vector of the indices used to index into the vertices of this mesh
    pub indices: Vec<u32>,
    /// The bounding box of the mesh
    pub aabb: Option<Aabb>,
}

impl Drawable3d for Mesh3d {
    fn draw(&self, canvas: &mut Canvas3d, param: impl Into<DrawParam3d>) {
        let param = param.into();
        let param = if let Transform3d::Values { offset, .. } = param.transform {
            if offset.is_none() {
                param.offset(self.aabb.unwrap_or_default().center)
            } else {
                param
            }
        } else {
            param
        };
        canvas.push_draw(Draw3d::Mesh { mesh: self.into() }, param);
    }
}

impl Mesh3d {
    /// Get the bounding box of this mesh
    pub fn calculate_aabb(&mut self) {
        let mut minimum = Vec3::MAX;
        let mut maximum = Vec3::MIN;
        for p in self.vertices.iter() {
            minimum = minimum.min(Vec3::from_array(p.pos));
            maximum = maximum.max(Vec3::from_array(p.pos));
        }
        if minimum.x != f32::MAX
            && minimum.y != f32::MAX
            && minimum.z != f32::MAX
            && maximum.x != f32::MIN
            && maximum.y != f32::MIN
            && maximum.z != f32::MIN
        {
            self.aabb = Some(Aabb::from_min_max(minimum, maximum))
        } else {
            self.aabb = None
        }
    }
}

#[cfg(feature = "gltf")]
// This is needed to handle ascii gltf files
struct DataUri<'a> {
    mime_type: &'a str,
    base64: bool,
    data: &'a str,
}

#[cfg(feature = "gltf")]
fn split_once(input: &str, delimiter: char) -> Option<(&str, &str)> {
    let mut iter = input.splitn(2, delimiter);
    Some((iter.next()?, iter.next()?))
}

#[cfg(feature = "gltf")]
impl<'a> DataUri<'a> {
    fn parse(uri: &'a str) -> Result<DataUri<'a>, ()> {
        let uri = uri.strip_prefix("data:").ok_or(())?;
        let (mime_type, data) = split_once(uri, ',').ok_or(())?;

        let (mime_type, base64) = match mime_type.strip_suffix(";base64") {
            Some(mime_type) => (mime_type, true),
            None => (mime_type, false),
        };

        Ok(DataUri {
            mime_type,
            base64,
            data,
        })
    }

    fn decode(&self) -> GameResult<Vec<u8>> {
        if self.base64 {
            if let Ok(vec) = base64::engine::general_purpose::STANDARD_NO_PAD.decode(self.data) {
                Ok(vec)
            } else {
                Err(GameError::CustomError(
                    "Failed to decode base64".to_string(),
                ))
            }
        } else {
            Ok(self.data.as_bytes().to_owned())
        }
    }
}

#[cfg(feature = "obj")]
impl<I: FromPrimitive> obj::FromRawVertex<I> for Vertex3d {
    fn process(
        vertices: Vec<(f32, f32, f32, f32)>,
        normals: Vec<(f32, f32, f32)>,
        tex_coords: Vec<(f32, f32, f32)>,
        polygons: Vec<obj::raw::object::Polygon>,
    ) -> obj::ObjResult<(Vec<Self>, Vec<I>)> {
        let verts = if vertices.len() == tex_coords.len() && vertices.len() == normals.len() {
            std::iter::zip(vertices, tex_coords)
                .zip(normals)
                .map(|v| {
                    println!("{v:?}");
                    Vertex3d {
                        pos: [v.0 .0 .0, v.0 .0 .1, v.0 .0 .2],
                        tex_coord: [v.0 .1 .0, v.0 .1 .1],
                        color: [1.0, 1.0, 1.0, 1.0],
                        normals: [v.1 .0, v.1 .1, v.1 .2],
                    }
                })
                .collect()
        } else {
            vertices
                .iter()
                .map(|v| Vertex3d {
                    pos: [v.0, v.1, v.2],
                    tex_coord: [0.0, 0.0],
                    color: [1.0, 1.0, 1.0, 1.0],
                    normals: [0.0, 0.0, 0.0],
                })
                .collect()
        };
        let mut inds = Vec::with_capacity(polygons.len() * 3);
        {
            let mut map = |pi: usize| -> obj::ObjResult<()> {
                inds.push(match I::from_usize(pi) {
                    Some(val) => val,
                    #[allow(deprecated)]
                    None => {
                        return Err(obj::ObjError::Load(obj::LoadError::new(
                            obj::LoadErrorKind::IndexOutOfRange,
                            "Unable to convert the index from usize",
                        )));
                    }
                });
                Ok(())
            };

            for polygon in polygons {
                match polygon {
                    obj::raw::object::Polygon::P(ref vec) if vec.len() == 3 => {
                        for &pi in vec {
                            map(pi)?
                        }
                    }
                    obj::raw::object::Polygon::PT(ref vec)
                    | obj::raw::object::Polygon::PN(ref vec)
                        if vec.len() == 3 =>
                    {
                        for &(pi, _) in vec {
                            map(pi)?
                        }
                    }
                    obj::raw::object::Polygon::PTN(ref vec) if vec.len() == 3 => {
                        for &(pi, _, _) in vec {
                            map(pi)?
                        }
                    }
                    #[allow(deprecated)]
                    _ => {
                        return Err(obj::ObjError::Load(obj::LoadError::new(
                            obj::LoadErrorKind::UntriangulatedModel,
                            "Meshes must be triangulated",
                        )))
                    }
                }
            }
        }
        Ok((verts, inds))
    }
}

/// Model is an abstracted type for holding things like obj, gltf, or anything that may be made up of multiple meshes.
#[derive(Debug, Default)]
pub struct Model {
    /// The meshes that make up the model
    pub meshes: Vec<Mesh3d>,
    /// The bounding box of the model
    pub aabb: Option<Aabb>,
}

impl Drawable3d for Model {
    fn draw(&self, canvas: &mut Canvas3d, param: impl Into<DrawParam3d>) {
        let param = param.into();
        let param = if let Transform3d::Values { offset, .. } = param.transform {
            if offset.is_none() {
                param.offset(self.aabb.unwrap_or_default().center)
            } else {
                param
            }
        } else {
            param
        };
        for mesh in self.meshes.iter() {
            canvas.push_draw(Draw3d::Mesh { mesh: mesh.into() }, param);
        }
    }
}

impl Model {
    /// Create a model from a mesh
    pub fn from_mesh(mesh: Mesh3d) -> Self {
        let mut model = Model {
            meshes: vec![mesh],
            aabb: None,
        };
        model.calculate_aabb();
        model
    }
    /// Load gltf or obj depending on extension type
    #[cfg(any(feature = "obj", feature = "gltf"))]
    pub fn from_path(
        gfx: &mut impl HasMut<GraphicsContext>,
        path: impl AsRef<Path>,
        image: impl Into<Option<Image>>,
    ) -> GameResult<Self> {
        match path.as_ref().extension() {
            Some(os_string) => match os_string.to_str() {
                #[cfg(feature = "obj")]
                Some("obj") => Model::from_obj(gfx, path, image),
                #[cfg(feature = "gltf")]
                Some("gltf" | "glb") => Model::from_gltf(gfx, path),

                Some(ext) => Err(GameError::MeshError(format!("Unknown extension {ext}"))),
                None => Err(GameError::MeshError(
                    "Failed to convert OsStr to &str".to_string(),
                )),
            },
            None => Err(GameError::MeshError("Missing extension".to_string())),
        }
    }

    /// Load a model from the given bytes. Either gltf or obj
    #[cfg(any(feature = "obj", feature = "gltf"))]
    pub fn from_bytes(
        gfx: &mut impl HasMut<GraphicsContext>,
        bytes: &[u8],
        image: impl Into<Option<Image>>,
    ) -> GameResult<Self> {
        match Model::from_obj_bytes(gfx, bytes, image) {
            Ok(model) => Ok(model),
            Err(..) => match Model::from_gltf_bytes(gfx, bytes) {
                Ok(model) => Ok(model),
                Err(..) => Err(GameError::MeshError(
                    "Bytes aren't an obj file or gltf file".to_string(),
                )),
            },
        }
    }

    /// Load obj file from a path.
    #[cfg(feature = "obj")]
    pub fn from_obj(
        gfx: &mut impl HasMut<GraphicsContext>,
        path: impl AsRef<Path>,
        image: impl Into<Option<Image>>,
    ) -> GameResult<Self> {
        let gfx = gfx.retrieve_mut();
        let file = gfx.fs.open(path)?;
        let buf_reader = std::io::BufReader::new(file);
        match obj::load_obj(buf_reader) {
            Ok(obj) => Model::from_obj_raw(gfx, obj, image),
            Err(f) => Err(GameError::MeshError(f.to_string())),
        }
    }

    /// Load obj file from a slice of bytes.
    #[cfg(feature = "obj")]
    pub fn from_obj_bytes(
        gfx: &mut impl HasMut<GraphicsContext>,
        bytes: &[u8],
        image: impl Into<Option<Image>>,
    ) -> GameResult<Self> {
        let gfx = gfx.retrieve_mut();
        let buf_reader = std::io::BufReader::new(bytes);
        match obj::load_obj(buf_reader) {
            Ok(obj) => Model::from_obj_raw(gfx, obj, image),
            Err(f) => Err(GameError::MeshError(f.to_string())),
        }
    }

    /// Load obj file. Only triangulated obj's are supported. Keep in mind mtl file's currently don't affect the obj's rendering
    #[cfg(feature = "obj")]
    pub fn from_obj_raw(
        gfx: &mut impl HasMut<GraphicsContext>,
        obj: obj::Obj<Vertex3d, u32>,
        image: impl Into<Option<Image>>,
    ) -> GameResult<Self> {
        let gfx = gfx.retrieve_mut();
        let mut img = Image::from_color(gfx, 1, 1, Some(graphics::Color::WHITE));
        let image: Option<Image> = image.into();
        if let Some(image) = image {
            img = image;
        }
        let mesh = Mesh3dBuilder::new()
            .from_data(obj.vertices, obj.indices, Some(img))
            .build(gfx);
        let mut model = Model {
            meshes: vec![mesh],
            aabb: None,
        };
        model.calculate_aabb();
        Ok(model)
    }

    #[cfg(feature = "gltf")]
    fn read_node(
        meshes: &mut Vec<Mesh3d>,
        node: &gltf::Node,
        parent_transform: Mat4,
        buffer_data: &mut Vec<Vec<u8>>,
        gfx: &mut GraphicsContext,
    ) -> GameResult {
        use super::ImageEncodingFormat;

        let transform = parent_transform * transform_to_matrix(node.transform());
        for child in node.children() {
            Model::read_node(meshes, &child, transform, buffer_data, gfx)?;
        }
        if let Some(mesh) = node.mesh() {
            for primitive in mesh.primitives() {
                let reader =
                    primitive.reader(|buffer| Some(buffer_data[buffer.index()].as_slice()));
                let texture_source = &primitive
                    .material()
                    .pbr_metallic_roughness()
                    .base_color_texture()
                    .map(|tex| tex.texture().source().source());
                let image = if let Some(source) = texture_source {
                    match source {
                        gltf::image::Source::View { view, mime_type } => {
                            let parent_buffer_data = &buffer_data[view.buffer().index()];
                            let data =
                                &parent_buffer_data[view.offset()..view.offset() + view.length()];
                            let mime_type = mime_type.replace('/', ".");
                            let dynamic_img = image::load_from_memory_with_format(
                                data,
                                ImageEncodingFormat::from_path(mime_type)
                                    .unwrap_or(ImageEncodingFormat::Png),
                            )
                            .unwrap_or_default()
                            .into_rgba8();
                            Image::from_pixels(
                                gfx,
                                dynamic_img.as_bytes(),
                                wgpu::TextureFormat::Rgba8UnormSrgb,
                                dynamic_img.width(),
                                dynamic_img.height(),
                            )
                        }
                        gltf::image::Source::Uri { uri, mime_type } => {
                            let uri = percent_encoding::percent_decode_str(uri)
                                .decode_utf8()
                                .unwrap();
                            let uri = uri.as_ref();
                            let bytes = match DataUri::parse(uri) {
                                Ok(data_uri) => data_uri.decode()?,
                                Err(()) => {
                                    return Err(GameError::CustomError(
                                        "Failed to decode".to_string(),
                                    ))
                                }
                            };
                            let dynamic_img = image::load_from_memory_with_format(
                                bytes.as_bytes(),
                                ImageEncodingFormat::from_path(mime_type.unwrap_or_default())
                                    .unwrap_or(ImageEncodingFormat::Png),
                            )
                            .unwrap_or_default()
                            .into_rgba8();
                            Image::from_pixels(
                                gfx,
                                dynamic_img.as_bytes(),
                                wgpu::TextureFormat::Rgba8UnormSrgb,
                                dynamic_img.width(),
                                dynamic_img.height(),
                            )
                        }
                    }
                } else {
                    Image::from_color(gfx, 1, 1, Some(graphics::Color::WHITE))
                };
                let mut vertices = Vec::default();
                if let Some(vertices_read) = reader.read_positions() {
                    vertices = vertices_read
                        .map(|x| {
                            let pos = glam::Vec4::new(x[0], x[1], x[2], 1.);
                            let res = transform * pos;
                            let pos = Vec3::new(res.x / res.w, res.y / res.w, res.z / res.w);
                            Vertex3d::new(
                                pos,
                                glam::Vec2::ZERO,
                                graphics::Color::new(1.0, 1.0, 1.0, 0.0),
                                [0.0, 0.0, 0.0],
                            )
                        })
                        .collect();
                }

                if let Some(tex_coords) = reader.read_tex_coords(0).map(|v| v.into_f32()) {
                    let mut idx = 0;
                    tex_coords.for_each(|tex_coord| {
                        vertices[idx].tex_coord = tex_coord;

                        idx += 1;
                    });
                }

                if let Some(normals) = reader.read_normals() {
                    let mut idx = 0;
                    normals.for_each(|normals| {
                        vertices[idx].normals = normals;

                        idx += 1;
                    });
                }

                let mut indices = Vec::new();
                if let Some(indices_raw) = reader.read_indices() {
                    indices.append(&mut indices_raw.into_u32().collect::<Vec<u32>>());
                }

                let mesh = Mesh3dBuilder::new()
                    .from_data(vertices, indices, Some(image))
                    .build(gfx);
                meshes.push(mesh);
            }
        }

        Ok(())
    }

    /// Load gltf from path
    #[cfg(feature = "gltf")]
    pub fn from_gltf(
        gfx: &mut impl HasMut<GraphicsContext>,
        path: impl AsRef<Path>,
    ) -> GameResult<Self> {
        let gfx = gfx.retrieve_mut();
        let file = gfx.fs.open(path)?;
        if let Ok(gltf) = gltf::Gltf::from_reader(file) {
            return Model::from_raw_gltf(gfx, gltf);
        }
        Err(GameError::MeshError("Failed to load gltf file".to_string()))
    }

    /// Load gltf from bytes
    #[cfg(feature = "gltf")]
    pub fn from_gltf_bytes(
        gfx: &mut impl HasMut<GraphicsContext>,
        bytes: &[u8],
    ) -> GameResult<Self> {
        if let Ok(gltf) = gltf::Gltf::from_slice(bytes) {
            return Model::from_raw_gltf(gfx, gltf);
        }
        Err(GameError::MeshError("Invalid gltf bytes".to_string()))
    }

    /// Load gltf file from a GLTF. Keep in mind right now the whole gltf will be loaded as one model. So multiple models won't be made in more complex scenes. This either has to be implemneted yourself or possibly will come later.
    #[cfg(feature = "gltf")]
    pub fn from_raw_gltf(
        gfx: &mut impl HasMut<GraphicsContext>,
        gltf: gltf::Gltf,
    ) -> GameResult<Self> {
        let gfx = gfx.retrieve_mut();
        const VALID_MIME_TYPES: &[&str] = &["application/octet-stream", "application/gltf-buffer"];
        let mut meshes = Vec::default();
        let mut buffer_data = Vec::new();
        for buffer in gltf.buffers() {
            match buffer.source() {
                gltf::buffer::Source::Uri(uri) => {
                    let uri = percent_encoding::percent_decode_str(uri)
                        .decode_utf8()
                        .unwrap();
                    let uri = uri.as_ref();
                    let buffer_bytes = match DataUri::parse(uri) {
                        Ok(data_uri) if VALID_MIME_TYPES.contains(&data_uri.mime_type) => {
                            data_uri.decode()?
                        }
                        Ok(_) => {
                            return Err(GameError::CustomError(
                                "Buffer Format Unsupported".to_string(),
                            ))
                        }
                        Err(()) => {
                            return Err(GameError::CustomError("Failed to decode".to_string()))
                        }
                    };
                    buffer_data.push(buffer_bytes);
                }
                gltf::buffer::Source::Bin => {
                    if let Some(blob) = gltf.blob.as_deref() {
                        buffer_data.push(blob.into());
                    } else {
                        return Err(GameError::CustomError("MissingBlob".to_string()));
                    }
                }
            }
        }
        for scene in gltf.scenes() {
            for node in scene.nodes() {
                Model::read_node(&mut meshes, &node, Mat4::IDENTITY, &mut buffer_data, gfx)?;
            }
        }
        let mut model = Model { meshes, aabb: None };
        model.calculate_aabb();

        Ok(model)
    }
    /// Generate an aabb for this Model
    pub fn calculate_aabb(&mut self) {
        let mut minimum = Vec3::MAX;
        let mut maximum = Vec3::MIN;
        for mesh in self.meshes.iter() {
            for p in mesh.vertices.iter() {
                minimum = minimum.min(Vec3::from_array(p.pos));
                maximum = maximum.max(Vec3::from_array(p.pos));
            }
        }
        if minimum.x != f32::MAX
            && minimum.y != f32::MAX
            && minimum.z != f32::MAX
            && maximum.x != f32::MIN
            && maximum.y != f32::MIN
            && maximum.z != f32::MIN
        {
            self.aabb = Some(Aabb::from_min_max(minimum, maximum))
        } else {
            self.aabb = None
        }
    }
}