gloss-renderer 0.9.0

Core renderer for gloss
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
//! These represent CPU components which you usually add to entities when you
//! spawn them.

extern crate nalgebra as na;
// use burn::backend::ndarray::NdArrayDevice;
// use burn::backend::candle::CandleDevice;
// use burn::backend::Candle;
use gloss_img::DynImage;
use gloss_utils::io::FileLoader;
use image::ImageReader;
use log::warn;
use na::DMatrix;
use num_derive::FromPrimitive;
use std::io::{BufReader, Cursor, Read, Seek};
/// Component that modifications to the config
#[derive(Clone)]
pub struct ConfigChanges {
    pub new_distance_fade_center: na::Point3<f32>,
}

/// Defines the color type an entity which is displayed as a point cloud
#[derive(Debug, Clone, Copy, PartialEq, FromPrimitive)]
pub enum PointColorType {
    Solid = 0,
    PerVert,
}

/// Defines the color type an entity which is displayed as a point cloud
#[derive(Debug, Clone, Copy, PartialEq, FromPrimitive)]
pub enum LineColorType {
    Solid = 0,
    PerVert,
}

/// Defines the color type an entity which is displayed as a mesh
#[derive(Debug, Clone, Copy, PartialEq, FromPrimitive)]
pub enum MeshColorType {
    Solid = 0,
    PerVert,
    Texture,
    UV,
    Normal,
    NormalViewCoords,
}

/// Component for visualization options of lines
#[derive(Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct VisLines {
    pub show_lines: bool,
    pub line_color: na::Vector4<f32>,
    pub line_width: f32,
    pub color_type: LineColorType,
    pub zbuffer: bool,
    pub antialias_edges: bool,
    //if this components was added automatically by the renderer this will be set to true. This is useful to know since when we upload textures to
    // gpu the vis_mesh.color_type will be set to Texture but this should happen ONLY if the VisMesh was added automatically. If the used adds this
    // component manually then we shouldn't override his VisMesh.colortype.
    pub added_automatically: bool,
}
/// Component for visualization options of wireframe
#[derive(Clone)]
pub struct VisWireframe {
    pub show_wireframe: bool,
    pub wire_color: na::Vector4<f32>,
    pub wire_width: f32,
    //if this components was added automatically by the renderer this will be set to true. This is useful to know since when we upload textures to
    // gpu the vis_mesh.color_type will be set to Texture but this should happen ONLY if the VisMesh was added automatically. If the used adds this
    // component manually then we shouldn't override his VisMesh.colortype.
    pub added_automatically: bool,
}
/// Component for visualization options of normals
#[derive(Clone)]
pub struct VisNormals {
    pub show_normals: bool,
    pub normals_color: na::Vector4<f32>,
    pub normals_width: f32,
    pub normals_scale: f32, //the scale of the arrows for the normal.
    //if this components was added automatically by the renderer this will be set to true. This is useful to know since when we upload textures to
    // gpu the vis_mesh.color_type will be set to Texture but this should happen ONLY if the VisMesh was added automatically. If the used adds this
    // component manually then we shouldn't override his VisMesh.colortype.
    pub added_automatically: bool,
}
/// Component for visualization options of point clouds
#[derive(Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct VisPoints {
    pub show_points: bool,
    pub show_points_indices: bool,
    pub point_color: na::Vector4<f32>,
    pub point_size: f32,
    pub is_point_size_in_world_space: bool,
    pub color_type: PointColorType,
    pub zbuffer: bool,
    //if this components was added automatically by the renderer this will be set to true. This is useful to know since when we upload textures to
    // gpu the vis_mesh.color_type will be set to Texture but this should happen ONLY if the VisMesh was added automatically. If the used adds this
    // component manually then we shouldn't override his VisMesh.colortype.
    pub added_automatically: bool,
}
/// Component for visualization options of meshes
#[derive(Clone)]
pub struct VisMesh {
    pub show_mesh: bool,
    pub solid_color: na::Vector4<f32>,
    pub metalness: f32,
    pub perceptual_roughness: f32,
    pub roughness_black_lvl: f32,
    pub uv_scale: f32,
    pub opacity: f32,
    pub needs_sss: bool,
    pub color_type: MeshColorType,
    //if this components was added automatically by the renderer this will be set to true. This is useful to know since when we upload textures to
    // gpu the vis_mesh.color_type will be set to Texture but this should happen ONLY if the VisMesh was added automatically. If the used adds this
    // component manually then we shouldn't override his VisMesh.colortype.
    pub added_automatically: bool,
}
/// Component for visualization options of meshes
#[derive(Clone)]
pub struct VisOutline {
    pub show_outline: bool,
    pub outline_color: na::Vector4<f32>,
    pub outline_width: f32,
    //if this components was added automatically by the renderer this will be set to true. This is useful to know since when we upload textures to
    // gpu the vis_mesh.color_type will be set to Texture but this should happen ONLY if the VisMesh was added automatically. If the used adds this
    // component manually then we shouldn't override his VisMesh.colortype.
    pub added_automatically: bool,
}
//implementations of default vis options
impl Default for VisLines {
    fn default() -> VisLines {
        VisLines {
            show_lines: false,
            line_color: na::Vector4::<f32>::new(1.0, 0.1, 0.1, 1.0),
            line_width: 1.0,
            color_type: LineColorType::Solid,
            zbuffer: true,
            antialias_edges: false,
            added_automatically: false,
        }
    }
}
impl Default for VisWireframe {
    fn default() -> VisWireframe {
        VisWireframe {
            show_wireframe: false,
            wire_color: na::Vector4::<f32>::new(1.0, 0.0, 0.0, 1.0),
            wire_width: 1.0,
            added_automatically: false,
        }
    }
}
impl Default for VisNormals {
    fn default() -> VisNormals {
        VisNormals {
            show_normals: false,
            normals_color: na::Vector4::<f32>::new(1.0, 0.0, 0.0, 1.0),
            normals_width: 1.0,
            normals_scale: 1.0,
            added_automatically: false,
        }
    }
}
impl Default for VisPoints {
    fn default() -> VisPoints {
        VisPoints {
            show_points: false,
            show_points_indices: false,
            point_color: na::Vector4::<f32>::new(245.0 / 255.0, 175.0 / 255.0, 110.0 / 255.0, 1.0),
            point_size: 1.0,
            is_point_size_in_world_space: false,
            color_type: PointColorType::Solid,
            zbuffer: true,
            added_automatically: false,
        }
    }
}
impl Default for VisMesh {
    fn default() -> VisMesh {
        VisMesh {
            show_mesh: true,
            solid_color: na::Vector4::<f32>::new(1.0, 206.0 / 255.0, 143.0 / 255.0, 1.0),
            metalness: 0.0,
            perceptual_roughness: 0.5,
            roughness_black_lvl: 0.0,
            uv_scale: 1.0,
            opacity: 1.0,
            needs_sss: false,
            color_type: MeshColorType::Solid,
            added_automatically: false,
        }
    }
}
impl Default for VisOutline {
    fn default() -> VisOutline {
        VisOutline {
            show_outline: false,
            outline_color: na::Vector4::<f32>::new(0.29, 0.82, 0.73, 1.0), // Blue-green default color
            outline_width: 5.0,
            added_automatically: false,
        }
    }
}

/// Component that transforms from object coordinates to world. Usually added
/// automatically but you can also add it yourself.
#[derive(Clone)]
pub struct ModelMatrix(pub na::SimilarityMatrix3<f32>); //transform from object coordinates to world corresponds to TfWorldObj
                                                        // pub struct ModelMatrix(pub na::Affine3<f32>); //transform from object
                                                        // coordinates to world corresponds to TfWorldObj
impl Default for ModelMatrix {
    fn default() -> ModelMatrix {
        ModelMatrix(na::SimilarityMatrix3::<f32>::identity())
    }
}
impl ModelMatrix {
    #[must_use]
    pub fn with_translation(self, t: &na::Vector3<f32>) -> Self {
        let mut mat = self;
        mat.0.append_translation_mut(&na::Translation3::new(t[0], t[1], t[2]));
        mat
    }
    #[must_use]
    pub fn with_rotation_rot3(self, r: &na::Rotation3<f32>) -> Self {
        let mut mat = self;
        mat.0.append_rotation_mut(r);
        mat
    }
    #[must_use]
    pub fn with_rotation_axis_angle(self, v: &na::Vector3<f32>) -> Self {
        let mut mat = self;
        mat.0
            .append_rotation_mut(&na::Rotation3::from_axis_angle(&na::UnitVector3::<f32>::new_normalize(*v), v.norm()));
        mat
    }
    #[must_use]
    pub fn with_rotation_euler(self, e: &na::Vector3<f32>) -> Self {
        let mut mat = self;
        mat.0.append_rotation_mut(&na::Rotation3::from_euler_angles(e.x, e.y, e.z));
        mat
    }
    #[must_use]
    pub fn with_scale(self, s: f32) -> Self {
        let mut mat = self;
        mat.0.append_scaling_mut(s);
        mat
    }

    #[must_use]
    pub fn interpolate(&self, other: &Self, other_weight: f32) -> Self {
        if !(0.0..=1.0).contains(&other_weight) {
            warn!("pose interpolation weight is outside the [0,1] range, will clamp. Weight is {other_weight}");
        }
        let other_weight = other_weight.clamp(0.0, 1.0);

        let lerp_isometry = self.0.isometry.lerp_slerp(&other.0.isometry, other_weight);
        let lerp_scaling = self.0.scaling() * (1.0 - other_weight) + other.0.scaling() * other_weight;

        let lerp_similarity = na::SimilarityMatrix3::from_parts(lerp_isometry.translation, lerp_isometry.rotation, lerp_scaling);

        ModelMatrix(lerp_similarity)
    }
}

/// Component that represents a track of camera extrinsics - num frames x 16
#[derive(Clone, Debug)]
pub struct CamTrack(pub DMatrix<f32>);

#[derive(Clone, Debug)]
pub struct Verts(pub DMatrix<f32>);

/// Component that represents a matrix of vertex positions for the first vertex
/// of an edge
#[derive(Clone, Debug)]
pub struct EdgesV1(pub DMatrix<f32>);
/// Component that represents a matrix of vertex positions for the second vertex
/// of an edge
#[derive(Clone, Debug)]
pub struct EdgesV2(pub DMatrix<f32>);

/// Component that represents a matrix of face indices for rendering a triangle
/// mesh
// #[derive(Clone)]
// pub struct Faces(pub DMatrix<u32>);
#[derive(Clone)]
pub struct Faces(pub DMatrix<u32>);

/// Component that represents a matrix of edges as Nx2 where each row is the
/// start idx and end idx of an edge which indexes into [``Verts``]
#[derive(Clone, Debug)]
pub struct Edges(pub DMatrix<u32>);

/// Component that represents UV coordinates
#[derive(Clone)]
pub struct UVs(pub DMatrix<f32>);
// / Component that represents the scale of the uv coordinates. Increasing it
// will tile the texture on the mesh. #[derive(Clone)]
// pub struct UvScale(pub f32);

/// Component that represents normal vectors
#[derive(Clone)]
pub struct Normals(pub DMatrix<f32>);

/// Component that represents tangents
#[derive(Clone)]
pub struct Tangents(pub DMatrix<f32>);

/// Component that represents per vertex colors
#[derive(Clone)]
pub struct Colors(pub DMatrix<f32>);

#[derive(Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct ImgConfig {
    pub keep_on_cpu: bool,
    pub fast_upload: bool, //fast upload uses the staging memory of wgpu but potentially uses more memory
    pub generate_mipmaps: bool,
    pub mipmap_generation_cpu: bool,
}
impl Default for ImgConfig {
    fn default() -> Self {
        Self {
            keep_on_cpu: true,
            fast_upload: true,
            generate_mipmaps: true,
            mipmap_generation_cpu: false,
        }
    }
}

/// A generic Img that has a path and img
/// Concrete images like [``DiffuseImg``] will contain the generic img
#[derive(Clone)]
pub struct GenericImg {
    pub path: Option<String>,
    pub cpu_img: Option<DynImage>, //keep it as an option so we can drop it and release the memory
    pub config: ImgConfig,
}
impl GenericImg {
    /// # Panics
    /// Will panic if the path cannot be opened.
    pub fn new_from_path(path: &str, config: &ImgConfig) -> Self {
        let cpu_img = Some(ImageReader::open(path).unwrap().decode().unwrap());

        Self {
            path: Some(path.to_string()),
            cpu_img: cpu_img.map(|v| v.try_into().unwrap()),
            config: config.clone(),
        }
    }

    /// # Panics
    /// Will panic if the path cannot be opened.
    pub async fn new_from_path_async(path: &str, config: &ImgConfig) -> Self {
        let reader = ImageReader::new(BufReader::new(FileLoader::open(path).await))
            .with_guessed_format()
            .expect("Cursor io never fails");

        let cpu_img = Some(reader.decode().unwrap());

        Self {
            path: Some(path.to_string()),
            cpu_img: cpu_img.map(|v| v.try_into().unwrap()),
            config: config.clone(),
        }
    }

    /// # Panics
    /// Will panic if the img cannot be processed and decoded.
    pub fn new_from_buf(buf: &[u8], config: &ImgConfig) -> Self {
        Self::new_from_reader(Cursor::new(buf), config)
    }

    /// # Panics
    /// Will panic if the img cannot be processed and decoded.
    pub fn new_from_reader<R: Read + Seek>(reader: R, config: &ImgConfig) -> Self {
        let reader_img = ImageReader::new(BufReader::new(reader))
            .with_guessed_format()
            .expect("Format for image should be something known and valid");

        let cpu_img = Some(reader_img.decode().unwrap());

        Self {
            path: None,
            cpu_img: cpu_img.map(|v| v.try_into().unwrap()),
            config: config.clone(),
        }
    }

    /// Creates a `GenericImg` from raw pixel data
    /// # Panics
    /// Will panic if the image cannot be created from the raw pixel data or if an invalid number of channels is provided.
    pub fn new_from_raw_pixels(pixels: Vec<u8>, width: u32, height: u32, channels: u8, config: &ImgConfig) -> Self {
        use image::{DynamicImage, GrayAlphaImage, GrayImage, RgbImage, RgbaImage};

        let cpu_img = match channels {
            1 => {
                let gray_img = GrayImage::from_raw(width, height, pixels).expect("Failed to create grayscale image from raw pixels");
                Some(DynamicImage::ImageLuma8(gray_img))
            }
            2 => {
                let gray_alpha_img = GrayAlphaImage::from_raw(width, height, pixels).expect("Failed to create grayscale+alpha image from raw pixels");
                Some(DynamicImage::ImageLumaA8(gray_alpha_img))
            }
            3 => {
                let rgb_img = RgbImage::from_raw(width, height, pixels).expect("Failed to create RGB image from raw pixels");
                Some(DynamicImage::ImageRgb8(rgb_img))
            }
            4 => {
                let rgba_img = RgbaImage::from_raw(width, height, pixels).expect("Failed to create RGBA image from raw pixels");
                Some(DynamicImage::ImageRgba8(rgba_img))
            }
            _ => panic!("Unsupported number of channels: {channels}. Supported: 1 (Luma), 2 (LumaA), 3 (RGB), 4 (RGBA)"),
        };

        Self {
            path: None,
            cpu_img: cpu_img.map(|v| v.try_into().unwrap()),
            config: config.clone(),
        }
    }

    pub fn img_ref(&self) -> &DynImage {
        self.cpu_img.as_ref().unwrap()
    }

    pub fn img_ref_mut(&mut self) -> &mut DynImage {
        self.cpu_img.as_mut().unwrap()
    }
}

/// Component which represents a diffuse img.
#[derive(Clone)]
pub struct DiffuseImg {
    pub generic_img: GenericImg,
}

impl DiffuseImg {
    pub fn new_from_path(path: &str, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_path(path, config);
        Self { generic_img }
    }

    pub async fn new_from_path_async(path: &str, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_path_async(path, config).await;
        Self { generic_img }
    }

    pub fn new_from_buf(buf: &[u8], config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_buf(buf, config);
        Self { generic_img }
    }

    pub fn new_from_reader<R: Read + Seek>(reader: R, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_reader(reader, config);
        Self { generic_img }
    }

    pub fn new_from_raw_pixels(pixels: Vec<u8>, width: u32, height: u32, channels: u8, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_raw_pixels(pixels, width, height, channels, config);
        Self { generic_img }
    }
}

/// Component which represents a normal img.
#[derive(Clone)]
pub struct NormalImg {
    pub generic_img: GenericImg,
}

impl NormalImg {
    pub fn new_from_path(path: &str, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_path(path, config);
        Self { generic_img }
    }

    pub async fn new_from_path_async(path: &str, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_path_async(path, config).await;
        Self { generic_img }
    }

    pub fn new_from_buf(buf: &[u8], config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_buf(buf, config);
        Self { generic_img }
    }

    pub fn new_from_reader<R: Read + Seek>(reader: R, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_reader(reader, config);
        Self { generic_img }
    }

    pub fn new_from_raw_pixels(pixels: Vec<u8>, width: u32, height: u32, channels: u8, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_raw_pixels(pixels, width, height, channels, config);
        Self { generic_img }
    }
}

/// Component which represents a metalness img.
pub struct MetalnessImg {
    pub generic_img: GenericImg,
}
impl MetalnessImg {
    pub fn new_from_path(path: &str, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_path(path, config);
        Self { generic_img }
    }

    pub async fn new_from_path_async(path: &str, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_path_async(path, config).await;
        Self { generic_img }
    }

    pub fn new_from_buf(buf: &[u8], config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_buf(buf, config);
        Self { generic_img }
    }

    pub fn new_from_reader<R: Read + Seek>(reader: R, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_reader(reader, config);
        Self { generic_img }
    }

    pub fn new_from_raw_pixels(pixels: Vec<u8>, width: u32, height: u32, channels: u8, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_raw_pixels(pixels, width, height, channels, config);
        Self { generic_img }
    }
}

/// Component which represents a roughness img. Assumes it is stored as
/// perceptual roughness/
#[derive(Clone)]
pub struct RoughnessImg {
    pub generic_img: GenericImg,
}
impl RoughnessImg {
    pub fn new_from_path(path: &str, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_path(path, config);
        Self { generic_img }
    }

    pub async fn new_from_path_async(path: &str, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_path_async(path, config).await;
        Self { generic_img }
    }

    pub fn new_from_buf(buf: &[u8], config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_buf(buf, config);
        Self { generic_img }
    }

    pub fn new_from_reader<R: Read + Seek>(reader: R, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_reader(reader, config);
        Self { generic_img }
    }

    pub fn new_from_raw_pixels(pixels: Vec<u8>, width: u32, height: u32, channels: u8, config: &ImgConfig) -> Self {
        let generic_img = GenericImg::new_from_raw_pixels(pixels, width, height, channels, config);
        Self { generic_img }
    }
}

pub trait GenericImageGetter {
    fn generic_img(&self) -> &GenericImg;
    fn generic_img_mut(&mut self) -> &mut GenericImg;
}

impl GenericImageGetter for DiffuseImg {
    fn generic_img(&self) -> &GenericImg {
        &self.generic_img
    }
    fn generic_img_mut(&mut self) -> &mut GenericImg {
        &mut self.generic_img
    }
}

impl GenericImageGetter for NormalImg {
    fn generic_img(&self) -> &GenericImg {
        &self.generic_img
    }
    fn generic_img_mut(&mut self) -> &mut GenericImg {
        &mut self.generic_img
    }
}

impl GenericImageGetter for RoughnessImg {
    fn generic_img(&self) -> &GenericImg {
        &self.generic_img
    }
    fn generic_img_mut(&mut self) -> &mut GenericImg {
        &mut self.generic_img
    }
}

impl GenericImageGetter for MetalnessImg {
    fn generic_img(&self) -> &GenericImg {
        &self.generic_img
    }
    fn generic_img_mut(&mut self) -> &mut GenericImg {
        &mut self.generic_img
    }
}

//implement some atributes for the vertex atributes so we can use them in a
// generic function also implement common things like the atom size of an
// element which is f32 for most or u32 for faces and edges https://stackoverflow.com/a/53085395
//https://stackoverflow.com/a/66794115
pub trait CpuAtrib<T> {
    // type TypeElement;
    fn byte_size_element(&self) -> usize;
    // pub fn get_data(&self) -> DMatrix<Self::TypeElement>;
    fn data_ref(&self) -> &DMatrix<T>;
}

impl CpuAtrib<f32> for Verts {
    // type TypeElement = f32;
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<f32>()
    }
    fn data_ref(&self) -> &DMatrix<f32> {
        &self.0
    }
}
impl CpuAtrib<f32> for EdgesV1 {
    // type TypeElement = f32;
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<f32>()
    }
    fn data_ref(&self) -> &DMatrix<f32> {
        &self.0
    }
}
impl CpuAtrib<f32> for EdgesV2 {
    // type TypeElement = f32;
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<f32>()
    }
    fn data_ref(&self) -> &DMatrix<f32> {
        &self.0
    }
}
impl CpuAtrib<u32> for Edges {
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<u32>()
    }
    fn data_ref(&self) -> &DMatrix<u32> {
        &self.0
    }
}
impl CpuAtrib<u32> for Faces {
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<u32>()
    }
    fn data_ref(&self) -> &DMatrix<u32> {
        &self.0
    }
}
impl CpuAtrib<f32> for UVs {
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<f32>()
    }
    fn data_ref(&self) -> &DMatrix<f32> {
        &self.0
    }
}
impl CpuAtrib<f32> for Normals {
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<f32>()
    }
    fn data_ref(&self) -> &DMatrix<f32> {
        &self.0
    }
}
impl CpuAtrib<f32> for Tangents {
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<f32>()
    }
    fn data_ref(&self) -> &DMatrix<f32> {
        &self.0
    }
}
impl CpuAtrib<f32> for Colors {
    fn byte_size_element(&self) -> usize {
        std::mem::size_of::<f32>()
    }
    fn data_ref(&self) -> &DMatrix<f32> {
        &self.0
    }
}

/// Environment map based ambient lighting representing light from distant
/// scenery.
///
/// When added as a resource to the scene, this component adds indirect light
/// to every point of the scene (including inside, enclosed areas) based on
/// an environment cubemap texture. This is similar to [`crate::AmbientLight`],
/// but higher quality, and is intended for outdoor scenes.
///
/// The environment map must be prefiltered into a diffuse and specular cubemap
/// based on the [split-sum approximation](https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf).
///
/// To prefilter your environment map, you can use `KhronosGroup`'s [glTF-IBL-Sampler](https://github.com/KhronosGroup/glTF-IBL-Sampler).
/// The diffuse map uses the Lambertian distribution, and the specular map uses
/// the GGX distribution.
///
/// `KhronosGroup` also has several prefiltered environment maps that can be found [here](https://github.com/KhronosGroup/glTF-Sample-Environments)
pub struct EnvironmentMap {
    pub diffuse_path: String,
    pub specular_path: String,
}
impl EnvironmentMap {
    pub fn new_from_path(diffuse_path: &str, specular_path: &str) -> Self {
        Self {
            diffuse_path: String::from(diffuse_path),
            specular_path: String::from(specular_path),
        }
    }
}

/// Component for storing approximate bounding vertices around an object.
/// Useful for computing scale of objects created on GPU directly which have only `VertsGPU` and no Verts component
#[derive(Clone)]
pub struct BoundingBox {
    pub min: na::Point3<f32>,
    pub max: na::Point3<f32>,
}
impl BoundingBox {
    pub fn new(min: na::Point3<f32>, max: na::Point3<f32>) -> Self {
        Self { min, max }
    }
    pub fn from_center_and_scale(center: &na::Point3<f32>, scale: &na::Vector3<f32>) -> Self {
        let half_scale = scale / 2.0;
        Self {
            min: na::Point3::from(center.coords - half_scale),
            max: na::Point3::from(center.coords + half_scale),
        }
    }
    pub fn center(&self) -> na::Point3<f32> {
        na::Point3::from((self.min.coords + self.max.coords) / 2.0)
    }
    pub fn size(&self) -> na::Vector3<f32> {
        self.max.coords - self.min.coords
    }
    pub fn diagonal_length(&self) -> f32 {
        (self.max.coords - self.min.coords).norm()
    }
}

// /so we can use the Components inside the Mutex<Hashmap> in the scene and wasm
// https://stackoverflow.com/a/73773940/22166964
// shenanigans
//ConfigDeltas
#[cfg(target_arch = "wasm32")]
unsafe impl Send for ConfigChanges {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for ConfigChanges {}
//verts
#[cfg(target_arch = "wasm32")]
unsafe impl Send for Verts {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for Verts {}
//vertse1
#[cfg(target_arch = "wasm32")]
unsafe impl Send for EdgesV1 {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for EdgesV1 {}
//vertse2
#[cfg(target_arch = "wasm32")]
unsafe impl Send for EdgesV2 {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for EdgesV2 {}
//edges
#[cfg(target_arch = "wasm32")]
unsafe impl Send for Edges {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for Edges {}
//faces
#[cfg(target_arch = "wasm32")]
unsafe impl Send for Faces {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for Faces {}
//uvs
#[cfg(target_arch = "wasm32")]
unsafe impl Send for UVs {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for UVs {}
//normalss
#[cfg(target_arch = "wasm32")]
unsafe impl Send for Normals {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for Normals {}
//tangents
#[cfg(target_arch = "wasm32")]
unsafe impl Send for Tangents {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for Tangents {}
//colors
#[cfg(target_arch = "wasm32")]
unsafe impl Send for Colors {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for Colors {}
//Diffuseimg
#[cfg(target_arch = "wasm32")]
unsafe impl Send for DiffuseImg {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for DiffuseImg {}
//Normalimg
#[cfg(target_arch = "wasm32")]
unsafe impl Send for NormalImg {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for NormalImg {}
//Metalnessimg
#[cfg(target_arch = "wasm32")]
unsafe impl Send for MetalnessImg {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for MetalnessImg {}
//Roughnessimg
#[cfg(target_arch = "wasm32")]
unsafe impl Send for RoughnessImg {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for RoughnessImg {}
//EnvironmentMap
#[cfg(target_arch = "wasm32")]
unsafe impl Send for EnvironmentMap {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for EnvironmentMap {}