Skip to main content

rhodora/model_manager/
material.rs

1use crate::rh_error::RhError;
2use std::sync::Arc;
3use vulkano::{
4    descriptor_set::{
5        allocator::StandardDescriptorSetAllocator, layout::DescriptorSetLayout,
6        PersistentDescriptorSet, WriteDescriptorSet,
7    },
8    image::{sampler::Sampler, view::ImageView},
9    Validated,
10};
11
12// FIXME find a better place for this
13/// Binds diffuse texture to first binding slot
14const DIFFUSE_TEX_BINDING: u32 = 0;
15
16/// Material with loaded texture not yet in a descriptor set
17#[allow(clippy::module_name_repetitions)]
18pub struct TexMaterial {
19    pub texture: Arc<ImageView>,
20    pub diffuse: [f32; 3], // Multiplier for diffuse
21    pub roughness: f32,
22    pub metalness: f32,
23}
24
25/// Material with loaded texture in a descriptor set
26#[allow(clippy::module_name_repetitions)]
27pub struct PbrMaterial {
28    pub texture_set: Arc<PersistentDescriptorSet>, // Descriptor set for diffuse
29    pub diffuse: [f32; 3],                         // Multiplier for diffuse
30    pub roughness: f32,
31    pub metalness: f32,
32}
33
34/// Convert from `TexMaterial` to a `PbrMaterial` by creating a descriptor set
35///
36/// # Errors
37/// Returns `RhError` if the descriptor set creation fails
38pub fn tex_to_pbr(
39    tex_material: &TexMaterial,
40    set_allocator: &StandardDescriptorSetAllocator,
41    sampler: &Arc<Sampler>,
42    layout: &Arc<DescriptorSetLayout>,
43) -> Result<PbrMaterial, RhError> {
44    Ok(PbrMaterial {
45        texture_set: PersistentDescriptorSet::new(
46            set_allocator,
47            layout.clone(),
48            [WriteDescriptorSet::image_view_sampler(
49                DIFFUSE_TEX_BINDING,
50                tex_material.texture.clone(),
51                sampler.clone(),
52            )],
53            [],
54        )
55        .map_err(Validated::unwrap)?,
56        diffuse: tex_material.diffuse,
57        roughness: tex_material.roughness,
58        metalness: tex_material.metalness,
59    })
60}