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
//! Cointains the interface into the texture cache and by
//! extension accsss the texture interface

use crate::engine_handle::Engine;
use crate::resource::{self, InProgressResource, ResourceId, ResourceType};
use crate::vectors::Vec2;
use crate::{layouts, ERROR_TEXTURE_DATA};
use image::{GenericImageView, ImageError};
use std::fmt::Display;
use std::io::Error;
use std::path::Path;

/// Contains all the information need to render an image/texture to the screen.
/// In order to be used it must be put inside a [Material](crate::material::Material)
pub struct Texture {
    pub(crate) _view: wgpu::TextureView,
    pub(crate) bind_group: wgpu::BindGroup,
    pub(crate) size: Vec2<f32>,
}

impl Texture {
    /// Attempts to both read a file at the specified path and turn it into an image. This will halt the engine
    /// untill loading is finished please see the [resource module](crate::resource) module for more information
    /// on how resource loading works.
    pub fn new<P>(engine: &mut Engine, path: P) -> ResourceId<Texture>
    where
        P: AsRef<Path>,
    {
        let typed_id = resource::generate_id::<Texture>();
        let id = typed_id.get_id();
        let path = path.as_ref();
        let ip_resource = InProgressResource::new(path, id, ResourceType::Image);

        resource::start_load(engine, path, &ip_resource);

        engine.add_in_progress_resource(ip_resource);
        typed_id
    }

    /// Attempts to load an image from a byte array. This is done staticly as it does not halt the engine
    /// for more information on resource loading see [resource module](crate::resource).
    pub fn from_btyes(
        engine: &mut Engine,
        label: Option<&str>,
        bytes: &[u8],
    ) -> ResourceId<Texture> {
        let img = image::load_from_memory(bytes)
            .map(|img| Self::from_image(engine, img, label))
            .unwrap_or_else(|e| {
                log::warn!("{}, occured loading default", e);
                Self::default(engine)
            });

        let typed_id = resource::generate_id::<Texture>();
        engine.resource_manager.insert_texture(typed_id, img);

        typed_id
    }

    pub(crate) fn from_resource_data(
        engine: &Engine,
        label: Option<&str>,
        bytes: &[u8],
    ) -> Result<Self, TextureError> {
        let img = image::load_from_memory(bytes)?;
        Ok(Self::from_image(engine, img, label))
    }

    pub(crate) fn new_direct(
        view: wgpu::TextureView,
        bind_group: wgpu::BindGroup,
        size: Vec2<f32>,
    ) -> Self {
        Self {
            _view: view,
            bind_group,
            size,
        }
    }

    pub(crate) fn default(engine: &Engine) -> Self {
        let image = image::load_from_memory(ERROR_TEXTURE_DATA).unwrap();
        Self::from_image(engine, image, Some("Error Texture"))
    }

    fn from_image(engine: &Engine, img: image::DynamicImage, label: Option<&str>) -> Self {
        let wgpu = engine.get_wgpu();
        let diffuse_rgba = img.to_rgba8();
        let (width, height) = img.dimensions();

        let texture_size = wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        };

        let texture = wgpu.device.create_texture(&wgpu::TextureDescriptor {
            size: texture_size,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            view_formats: &[],
            // TEXTURE_BINDING tells wgpu that we want to use this texture in shaders
            // COPY_DST means that we want to copy data to this texture
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            label,
        });

        wgpu.queue.write_texture(
            wgpu::ImageCopyTextureBase {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &diffuse_rgba,
            wgpu::ImageDataLayout {
                offset: 0,
                bytes_per_row: Some(4 * width),
                rows_per_image: Some(height),
            },
            texture_size,
        );

        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let bind_group_layout = layouts::create_texture_layout(&wgpu.device);

        let bind_group = wgpu.device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(engine.get_texture_sampler()),
                },
            ],
            label: Some("diffuse_bind_group"),
        });

        let size = Vec2 {
            x: width as f32,
            y: height as f32,
        };

        Self {
            _view: view,
            bind_group,
            size,
        }
    }
}

/// Loading a texture can fail in two senarios. Either the file cant be opened, or the
/// file loaded is not a supported image file type.
#[derive(Debug)]
pub(crate) enum TextureError {
    IoError(Error),
    ImageError(ImageError),
}

impl From<Error> for TextureError {
    fn from(value: Error) -> TextureError {
        Self::IoError(value)
    }
}

impl From<ImageError> for TextureError {
    fn from(value: ImageError) -> Self {
        Self::ImageError(value)
    }
}

impl std::error::Error for TextureError {}

impl Display for TextureError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::IoError(e) => write!(f, "{}", e),
            Self::ImageError(e) => write!(f, "{}", e),
        }
    }
}