Files
ab_glyph_rasterizer
addr2line
adler
andrew
approx
arrayvec
ash
atom
backtrace
bitflags
byteorder
calloop
cfg_if
colorful
conrod_core
conrod_derive
conrod_example_shared
conrod_gfx
conrod_glium
conrod_piston
conrod_rendy
conrod_vulkano
conrod_wgpu
conrod_winit
copyless
copypasta
crossbeam
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
daggy
dlib
downcast_rs
draw_state
either
fixedbitset
float
fnv
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
fxhash
getrandom
gfx
gfx_backend_empty
gfx_backend_vulkan
gfx_core
gfx_descriptor
gfx_hal
gfx_memory
gimli
glium
glutin
glutin_egl_sys
glutin_glx_sys
graphics
half
hibitset
inplace_it
input
instant
interpolation
iovec
itoa
lazy_static
lazycell
libc
libloading
line_drawing
linked_hash_map
lock_api
log
maybe_uninit
memchr
memmap
memoffset
miniz_oxide
mio
mio_extras
naga
net2
nix
nom
num
num_bigint
num_complex
num_cpus
num_integer
num_iter
num_rational
num_traits
object
once_cell
ordered_float
ordermap
osmesa_sys
owned_ttf_parser
parking_lot
parking_lot_core
percent_encoding
petgraph
pin_project
pin_project_internal
pin_project_lite
pin_utils
ppv_lite86
proc_macro2
proc_macro_hack
proc_macro_nested
quote
rand
rand_chacha
rand_core
raw_window_handle
read_color
relevant
rendy
rendy_chain
rendy_command
rendy_core
rendy_descriptor
rendy_factory
rendy_frame
rendy_graph
rendy_init
rendy_memory
rendy_mesh
rendy_resource
rendy_shader
rendy_texture
rendy_wsi
rustc_demangle
rustc_hash
rusttype
ryu
same_file
scoped_tls
scopeguard
serde
serde_derive
serde_json
shaderc
shaderc_sys
shared_library
slab
smallvec
smithay_client_toolkit
smithay_clipboard
spirv_headers
stb_truetype
syn
takeable_option
texture
thiserror
thiserror_impl
thread_profiler
time
tracing
tracing_core
ttf_parser
typed_arena
unicode_xid
vecmath
viewport
vk_sys
void
vulkano
buffer
command_buffer
descriptor
device
framebuffer
image
instance
memory
pipeline
query
swapchain
sync
vulkano_shaders
walkdir
wayland_client
wayland_commons
wayland_cursor
wayland_egl
wayland_protocols
wayland_sys
wgpu
wgpu_core
wgpu_types
winit
x11
x11_clipboard
x11_dl
xcb
xcursor
xdg
xml
  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
// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Buffer components for a PSO.

use std::marker::PhantomData;
use core::{ConstantBufferSlot, Resources, MAX_VERTEX_ATTRIBUTES};
use core::{handle, pso, shade};
use core::memory::Typed;
use core::format::Format;
use shade::{ToUniform, Usage};
use super::{DataLink, DataBind, ElementError, RawDataSet, AccessInfo};

pub use core::pso::{BufferIndex, Element, ElemOffset, ElemStride, InstanceRate};

/// A trait to be implemented by any struct having the layout described
/// in the graphics API, like a vertex buffer.
pub trait Structure<F> {
    /// Get the layout of an element by name.
    fn query(&str) -> Option<Element<F>>;
}

type AttributeSlotSet = usize;

/// Service struct to simplify the implementations of `VertexBuffer` and `InstanceBuffer`.
pub struct VertexBufferCommon<T, I=InstanceRate>(RawVertexBuffer, PhantomData<(T, I)>);

impl<T, I> PartialEq for VertexBufferCommon<T, I> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T, I> Eq for VertexBufferCommon<T, I> {}

impl<T, I> std::hash::Hash for VertexBufferCommon<T, I> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl<T, I> Clone for VertexBufferCommon<T, I> {
    fn clone(&self) -> Self {
        Self(self.0.clone(), PhantomData)
    }
}

impl<T, I> std::fmt::Debug for VertexBufferCommon<T, I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("VertexBufferCommon").field(&self.0).finish()
    }
}

/// Helper trait for `VertexBufferCommon` to support variable instance rate.
pub trait ToInstanceRate {
    /// The associated init type for PSO component.
    type Init;
    /// Get an actual instance rate value from the init.
    fn get_rate(init: &Self::Init) -> InstanceRate;
}

/// Helper phantom type for per-vertex attributes.
pub enum NonInstanced {}
/// Helper phantom type for per-instance attributes.
pub enum Instanced {}

impl ToInstanceRate for InstanceRate {
    type Init = InstanceRate;
    fn get_rate(init: &Self::Init) -> InstanceRate { *init }
}
impl ToInstanceRate for Instanced {
    type Init = ();
    fn get_rate(_: &Self::Init) -> InstanceRate { 1 }
}
impl ToInstanceRate for NonInstanced {
    type Init = ();
    fn get_rate(_: &Self::Init) -> InstanceRate { 0 }
}

/// Vertex buffer component. Advanced per vertex.
///
/// - init: `()`
/// - data: `Buffer<T>`
pub type VertexBuffer<T> = VertexBufferCommon<T, NonInstanced>;

/// Instance buffer component. Same as the vertex buffer but advances per instance.
pub type InstanceBuffer<T> = VertexBufferCommon<T, Instanced>;

/// Raw vertex/instance buffer component. Can be used when the formats of vertex attributes
/// are not known at compile time.
///
/// - init: `(&[&str, element], stride, inst_rate)`
/// - data: `RawBuffer`
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct RawVertexBuffer(Option<BufferIndex>, AttributeSlotSet);

/// Constant buffer component.
///
/// - init: `&str` = name of the buffer
/// - data: `Buffer<T>`
pub struct ConstantBuffer<T: Structure<shade::ConstFormat>>(RawConstantBuffer, PhantomData<T>);

impl<T: Structure<shade::ConstFormat>> PartialEq for ConstantBuffer<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T: Structure<shade::ConstFormat>> Eq for ConstantBuffer<T> {}

impl<T: Structure<shade::ConstFormat>> std::hash::Hash for ConstantBuffer<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl<T: Structure<shade::ConstFormat>> Clone for ConstantBuffer<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone(), PhantomData)
    }
}

impl<T: Structure<shade::ConstFormat>> std::fmt::Debug for ConstantBuffer<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("ConstantBuffer").field(&self.0).finish()
    }
}

/// Raw constant buffer component.
///
/// - init: `&str` = name of the buffer
/// - data: `RawBuffer`
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct RawConstantBuffer(Option<(Usage, ConstantBufferSlot)>);

/// Global (uniform) constant component. Describes a free-standing value passed
/// into the shader, which is not enclosed into any constant buffer.
///
/// - init: `&str` = name of the constant
/// - data: `T` = value
pub struct Global<T: ToUniform>(RawGlobal, PhantomData<T>);

impl<T: ToUniform> PartialEq for Global<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T: ToUniform> Eq for Global<T> {}

impl<T: ToUniform> std::hash::Hash for Global<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl<T: ToUniform> Clone for Global<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone(), PhantomData)
    }
}

impl<T: ToUniform> std::fmt::Debug for Global<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Global").field(&self.0).finish()
    }
}

/// Raw global (uniform) constant component. Describes a free-standing value
/// passed into the shader, which is not enclosed in any constant buffer.
///
/// - init: `&str` = name of the constant
/// - data: `UniformValue` = value
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct RawGlobal(Option<shade::Location>);

fn match_attribute(attr: &shade::AttributeVar, fmt: Format) -> bool {
    use core::shade::{BaseType, ContainerType};
    use core::format::ChannelType;

    // TODO: Fill in `_` with compatible `core::format::SurfaceType` variants.

    match (attr.base_type, fmt.1) {
        (BaseType::I32, ChannelType::Int) |
        (BaseType::F32, ChannelType::Float) |
        (BaseType::F32, ChannelType::Inorm) |
        (BaseType::F32, ChannelType::Srgb) |
        (BaseType::F32, ChannelType::Unorm) |
        (BaseType::U32, ChannelType::Uint) => match (attr.container, fmt.0) {
                (ContainerType::Single, _) |
                (ContainerType::Vector(1), _) |
                (ContainerType::Vector(2), _) |
                (ContainerType::Vector(3), _) |
                (ContainerType::Vector(4), _) => true,
                _ => false,
        },
        (BaseType::F64, ChannelType::Float) |
        (BaseType::F64, ChannelType::Inorm) |
        (BaseType::F64, ChannelType::Srgb) |
        (BaseType::F64, ChannelType::Unorm) => match (attr.container, fmt.0) {
                (ContainerType::Single, _) |
                (ContainerType::Vector(2), _) |
                (ContainerType::Vector(3), _) |
                (ContainerType::Vector(4), _) => true,
                _ => false,
        },
        _ => false,
    }
}

impl<'a,
    T: Structure<Format>,
    I: ToInstanceRate + 'a,
> DataLink<'a> for VertexBufferCommon<T, I> {
    type Init = I::Init;
    fn new() -> Self {
        VertexBufferCommon(DataLink::new(), PhantomData)
    }
    fn is_active(&self) -> bool {
        self.0.is_active()
    }
    fn link_vertex_buffer(&mut self, index: BufferIndex, init: &Self::Init)
                          -> Option<pso::VertexBufferDesc> {
        use std::mem;
        (self.0).0 = Some(index);
        let rate = I::get_rate(init);
        Some(pso::VertexBufferDesc {
            stride: mem::size_of::<T>() as ElemStride,
            rate: rate as InstanceRate,
        })
    }
    fn link_input(&mut self, at: &shade::AttributeVar, _: &Self::Init) ->
                  Option<Result<pso::AttributeDesc, Format>> {
        T::query(&at.name).map(|el| {
            self.0.link(at, el)
        })
    }
}

impl<R: Resources, T, I> DataBind<R> for VertexBufferCommon<T, I> {
    type Data = handle::Buffer<R, T>;
    fn bind_to(&self,
               out: &mut RawDataSet<R>,
               data: &Self::Data,
               man: &mut handle::Manager<R>,
               access: &mut AccessInfo<R>) {
        self.0.bind_to(out, data.raw(), man, access)
    }
}

impl RawVertexBuffer {
    fn link(&mut self, at: &shade::AttributeVar, el: Element<Format>)
            -> Result<pso::AttributeDesc, Format> {
        self.1 |= 1 << (at.slot as AttributeSlotSet);
        if match_attribute(at, el.format) {
            Ok((self.0.unwrap(), el))
        } else {
            Err(el.format)
        }
    }
}

impl<'a> DataLink<'a> for RawVertexBuffer {
    type Init = (&'a [(&'a str, Element<Format>)], ElemStride, InstanceRate);
    fn new() -> Self {
        RawVertexBuffer(None, 0)
    }
    fn is_active(&self) -> bool {
        self.0.is_some()
    }
    fn link_vertex_buffer(&mut self, index: BufferIndex, init: &Self::Init)
                          -> Option<pso::VertexBufferDesc> {
        self.0 = Some(index);
        Some(pso::VertexBufferDesc {
            stride: init.1,
            rate: init.2,
        })
    }
    fn link_input(&mut self, at: &shade::AttributeVar, init: &Self::Init) ->
                  Option<Result<pso::AttributeDesc, Format>> {
        init.0.iter().find(|x| x.0 == &at.name)
            .map(|x| self.link(at, x.1))
    }
}

impl<R: Resources> DataBind<R> for RawVertexBuffer {
    type Data = handle::RawBuffer<R>;
    fn bind_to(&self,
               out: &mut RawDataSet<R>,
               data: &Self::Data,
               man: &mut handle::Manager<R>,
               access: &mut AccessInfo<R>) {
        let value = Some((man.ref_buffer(data).clone(), 0));
        for i in 0 .. MAX_VERTEX_ATTRIBUTES {
            if (self.1 & (1<<i)) != 0 {
                out.vertex_buffers.0[i] = value;
            }
        }
        if self.1 != 0 { access.buffer_read(data); }
    }
}


impl<'a, T: Structure<shade::ConstFormat>>
DataLink<'a> for ConstantBuffer<T> {
    type Init = &'a str;
    fn new() -> Self {
        ConstantBuffer(RawConstantBuffer::new(), PhantomData)
    }
    fn is_active(&self) -> bool {
        self.0.is_active()
    }
    fn link_constant_buffer<'b>(&mut self, cb: &'b shade::ConstantBufferVar, init: &Self::Init)
                            -> Option<Result<pso::ConstantBufferDesc, ElementError<&'b str>>> {
        let raw_out = self.0.link_constant_buffer(cb, init);
        if raw_out.is_some() {
            for el in cb.elements.iter() {
                let err = match T::query(&el.name) {
                    Some(e) if e.offset != el.location as pso::ElemOffset =>
                        ElementError::Offset {
                            name: el.name.as_str(),
                            shader_offset: el.location as pso::ElemOffset,
                            code_offset: e.offset,
                        },
                    None => ElementError::NotFound(el.name.as_str()),
                    Some(_) => continue, //TODO: check format
                };
                self.0 = RawConstantBuffer::new();
                return Some(Err(err));
            }
        }
        raw_out
    }
}

impl<R: Resources, T: Structure<shade::ConstFormat>>
DataBind<R> for ConstantBuffer<T> {
    type Data = handle::Buffer<R, T>;
    fn bind_to(&self,
               out: &mut RawDataSet<R>,
               data: &Self::Data,
               man: &mut handle::Manager<R>,
               access: &mut AccessInfo<R>) {
        self.0.bind_to(out, data.raw(), man, access)
    }
}

impl<'a> DataLink<'a> for RawConstantBuffer {
    type Init = &'a str;
    fn new() -> Self {
        RawConstantBuffer(None)
    }
    fn is_active(&self) -> bool {
        self.0.is_some()
    }
    fn link_constant_buffer<'b>(&mut self, cb: &'b shade::ConstantBufferVar, init: &Self::Init)
                            -> Option<Result<pso::ConstantBufferDesc, ElementError<&'b str>>> {
        if cb.name.as_str() == *init {
            self.0 = Some((cb.usage, cb.slot));
            Some(Ok(cb.usage))
        } else {
            None
        }
    }
}

impl<R: Resources> DataBind<R> for RawConstantBuffer {
    type Data = handle::RawBuffer<R>;
    fn bind_to(&self,
               out: &mut RawDataSet<R>,
               data: &Self::Data,
               man: &mut handle::Manager<R>,
               access: &mut AccessInfo<R>) {
        if let Some((usage, slot)) = self.0 {
            let buf = man.ref_buffer(data).clone();
            out.constant_buffers.push(pso::ConstantBufferParam(buf, usage, slot));
            access.buffer_read(data)
        }
    }
}

impl<'a, T: ToUniform + Default> DataLink<'a> for Global<T> {
    type Init = &'a str;
    fn new() -> Self {
        Global(RawGlobal::new(), PhantomData)
    }
    fn is_active(&self) -> bool {
        self.0.is_active()
    }
    fn link_global_constant(&mut self, var: &shade::ConstVar, init: &Self::Init) ->
                            Option<Result<(), shade::CompatibilityError>> {
        let kind = ToUniform::convert(T::default());
        self.0.link_global_constant(var, init).and(Some(var.is_compatible(&kind)))
    }
}

impl<R: Resources, T: ToUniform> DataBind<R> for Global<T> {
    type Data = T;
    fn bind_to(&self,
               out: &mut RawDataSet<R>,
               data: &Self::Data,
               man: &mut handle::Manager<R>,
               access: &mut AccessInfo<R>) {
        let val = data.convert();
        self.0.bind_to(out, &val, man, access);
    }
}

impl<'a> DataLink<'a> for RawGlobal {
    type Init = &'a str;
    fn new() -> Self {
        RawGlobal(None)
    }
    fn is_active(&self) -> bool {
        self.0.is_some()
    }
    fn link_global_constant(&mut self, var: &shade::ConstVar, init: &Self::Init) ->
                            Option<Result<(), shade::CompatibilityError>> {
        if var.name.as_str() == *init {
            self.0 = Some(var.location);
            Some(Ok(()))
        } else {
            None
        }
    }
}

impl<R: Resources> DataBind<R> for RawGlobal {
    type Data = shade::UniformValue;
    fn bind_to(&self,
               out: &mut RawDataSet<R>,
               data: &Self::Data,
               _: &mut handle::Manager<R>,
               _: &mut AccessInfo<R>) {
        if let Some(loc) = self.0 {
            out.global_constants.push((loc, *data));
        }
    }
}