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
//! 3D Skinned per-image buffer handling.
use crate::{
    rendy::{
        command::RenderPassEncoder,
        factory::Factory,
        hal::{self, device::Device, pso::Descriptor},
        memory::Write as _,
        resource::{Buffer, DescriptorSet, DescriptorSetLayout, Escape, Handle as RendyHandle},
    },
    skinning::JointTransforms,
    types::Backend,
    util,
};
use fnv::FnvHashMap;

#[cfg(feature = "profiler")]
use thread_profiler::profile_scope;

/// Provides per-image abstraction for submitting skinned mesh skeletal information.
#[derive(Debug)]
pub struct SkinningSub<B: Backend> {
    layout: RendyHandle<DescriptorSetLayout<B>>,
    skin_offset_map: FnvHashMap<u32, u32>,
    staging: Vec<[[f32; 4]; 4]>,
    per_image: Vec<PerImageSkinningSub<B>>,
}

#[derive(Debug)]
struct PerImageSkinningSub<B: Backend> {
    buffer: Option<Escape<Buffer<B>>>,
    set: Escape<DescriptorSet<B>>,
}

impl<B: Backend> SkinningSub<B> {
    /// Create a new `SkinningSub`, allocating using the provided `Factory`
    pub fn new(factory: &Factory<B>) -> Result<Self, failure::Error> {
        Ok(Self {
            layout: set_layout! {factory, [1] StorageBuffer hal::pso::ShaderStageFlags::VERTEX},
            skin_offset_map: Default::default(),
            staging: Vec::new(),
            per_image: Vec::new(),
        })
    }

    /// Returns the raw `DescriptorSetLayout` of a skinning submission.
    pub fn raw_layout(&self) -> &B::DescriptorSetLayout {
        self.layout.raw()
    }

    /// Allocates and writes the skinning information to GPU memory
    pub fn commit(&mut self, factory: &Factory<B>, index: usize) {
        let this_image = {
            while self.per_image.len() <= index {
                self.per_image
                    .push(PerImageSkinningSub::new(factory, &self.layout));
            }
            &mut self.per_image[index]
        };
        this_image.commit(factory, util::slice_as_bytes(&self.staging));
        self.staging.clear();
        self.skin_offset_map.clear();
    }

    /// Insert a new `JointTransforms` instance for submission. Returns an index.
    pub fn insert(&mut self, joints: &JointTransforms) -> u32 {
        #[cfg(feature = "profiler")]
        profile_scope!("insert");

        let staging = &mut self.staging;
        *self
            .skin_offset_map
            .entry(joints.skin.id())
            .or_insert_with(|| {
                let len = staging.len();
                staging.extend(
                    joints
                        .matrices
                        .iter()
                        .map(|m| -> [[f32; 4]; 4] { (*m).into() }),
                );
                len as u32
            })
    }

    /// Bind the skinned skeletal information.
    #[inline]
    pub fn bind(
        &self,
        index: usize,
        pipeline_layout: &B::PipelineLayout,
        set_id: u32,
        encoder: &mut RenderPassEncoder<'_, B>,
    ) {
        self.per_image[index].bind(pipeline_layout, set_id, encoder);
    }
}

impl<B: Backend> PerImageSkinningSub<B> {
    fn new(factory: &Factory<B>, layout: &RendyHandle<DescriptorSetLayout<B>>) -> Self {
        Self {
            buffer: None,
            set: factory.create_descriptor_set(layout.clone()).unwrap(),
        }
    }

    fn commit(&mut self, factory: &Factory<B>, data: &[u8]) {
        if data.is_empty() {
            return;
        }

        let allocated = util::ensure_buffer(
            &factory,
            &mut self.buffer,
            hal::buffer::Usage::STORAGE,
            rendy::memory::Dynamic,
            data.len() as u64,
        )
        .unwrap();

        if let Some(buffer) = self.buffer.as_mut() {
            if allocated {
                unsafe {
                    factory.write_descriptor_sets(Some(util::desc_write(
                        self.set.raw(),
                        0,
                        Descriptor::Buffer(buffer.raw(), Some(0)..None),
                    )));
                }
            }

            let mut mapped = buffer.map(factory.device(), 0..data.len() as u64).unwrap();
            let mut writer = unsafe {
                mapped
                    .write(factory.device(), 0..data.len() as u64)
                    .unwrap()
            };
            let dst_slice = unsafe { writer.slice() };
            dst_slice.copy_from_slice(data);
        }
    }

    #[inline]
    fn bind(
        &self,
        pipeline_layout: &B::PipelineLayout,
        set_id: u32,
        encoder: &mut RenderPassEncoder<'_, B>,
    ) {
        unsafe {
            encoder.bind_graphics_descriptor_sets(
                pipeline_layout,
                set_id,
                Some(self.set.raw()),
                std::iter::empty(),
            );
        }
    }
}