pub struct VertexBuffer { /* private fields */ }
Expand description

Vertex buffer with dynamic layout. It is used to store multiple vertices of a single type, that implements VertexTrait. Different vertex types used to for efficient memory usage. For example, you could have a simple vertex with only position expressed as Vector3 and it will be enough for simple cases, when only position is required. However, if you want to draw a mesh with skeletal animation, that also supports texturing, lighting, you need to provide a lot more data (bone indices, bone weights, normals, tangents, texture coordinates).

Examples

#[derive(Copy, Clone)]
#[repr(C)]
struct MyVertex {
    position: Vector3<f32>,
}

impl VertexTrait for MyVertex {
    fn layout() -> &'static [VertexAttributeDescriptor] {
        &[VertexAttributeDescriptor {
            usage: VertexAttributeUsage::Position,
            data_type: VertexAttributeDataType::F32,
            size: 3,
            divisor: 0,
            shader_location: 0,
        }]
    }
}

fn create_triangle_vertex_buffer() -> VertexBuffer {
    VertexBuffer::new(
        3,
        vec![
            MyVertex {
                position: Vector3::new(0.0, 0.0, 0.0),
            },
            MyVertex {
                position: Vector3::new(0.0, 1.0, 0.0),
            },
            MyVertex {
                position: Vector3::new(1.0, 1.0, 0.0),
            },
        ],
    )
    .unwrap()
}  

This example creates a simple vertex buffer that contains a single triangle with custom vertex format. The most important part here is VertexTrait::layout implementation - it describes each “attribute” of your vertex, if your layout does not match the actual content of the vertex (in terms of size in bytes), then vertex buffer cannot be created and VertexBuffer::new will return None.

The second, but not least important is #[repr(C)] attribute - it is mandatory for every vertex type, it forbids fields reordering of you vertex structure and guarantees that they will have the same layout in memory as their declaration order.

Limitations

Vertex size cannot be more than 256 bytes, this limitation shouldn’t be a problem because almost every GPU supports up to 16 vertex attributes with 16 bytes of size each, which gives exactly 256 bytes.

Implementations§

source§

impl VertexBuffer

source

pub fn new<T>( vertex_count: usize, data: Vec<T> ) -> Result<Self, ValidationError>where T: VertexTrait,

Creates new vertex buffer from provided data and with the given layout of the vertex type T.

source

pub fn raw_data(&self) -> &[u8]

Returns a reference to underlying data buffer slice.

source

pub fn is_empty(&self) -> bool

Returns true if buffer does not contain any vertex, false - otherwise.

source

pub fn data_hash(&self) -> u64

Returns cached data hash. Cached value is guaranteed to be in actual state.

source

pub fn layout_hash(&self) -> u64

Returns hash of vertex buffer layout. Cached value is guaranteed to be in actual state. The hash could be used to check if the layout has changed.

source

pub fn modify(&mut self) -> VertexBufferRefMut<'_>

Provides mutable access to content of the buffer.

Performance

This method returns special structure which has custom destructor that calculates hash of the data once modification is over. You must hold this structure as long as possible while modifying contents of the buffer. Do not even try to do this:

use fyrox::{
    scene::mesh::buffer::{VertexBuffer, VertexWriteTrait, VertexAttributeUsage},
    core::algebra::Vector3
};
fn do_something(buffer: &mut VertexBuffer) {
    for i in 0..buffer.vertex_count() {
        buffer
            .modify() // Doing this in a loop will cause HUGE performance issues!
            .get_mut(i as usize)
            .unwrap()
            .write_3_f32(VertexAttributeUsage::Position, Vector3::<f32>::default())
            .unwrap();
    }
}

Instead do this:

use fyrox::{
    scene::mesh::buffer::{VertexBuffer, VertexWriteTrait, VertexAttributeUsage},
    core::algebra::Vector3
};
fn do_something(buffer: &mut VertexBuffer) {
    let mut buffer_modifier = buffer.modify();
    for mut vertex in buffer_modifier.iter_mut() {
        vertex
            .write_3_f32(VertexAttributeUsage::Position, Vector3::<f32>::default())
            .unwrap();
    }
}

Why do we even need such complications? It is used for lazy hash calculation which is used for automatic upload of contents to GPU in case if content has changed.

source

pub fn has_attribute(&self, usage: VertexAttributeUsage) -> bool

Checks if an attribute of usage exists.

source

pub fn layout(&self) -> &[VertexAttribute]

Returns vertex buffer layout.

source

pub fn cast_data_ref<T>(&self) -> Result<&[T], ValidationError>where T: VertexTrait,

Tries to cast internal data buffer to a slice of given type. It may fail if size of type is not equal with claimed size (which is set by the layout).

source

pub fn iter(&self) -> impl Iterator<Item = VertexViewRef<'_>> + '_

Creates iterator that emits read accessors for vertices.

source

pub fn get(&self, n: usize) -> Option<VertexViewRef<'_>>

Returns a read accessor of n-th vertex.

source

pub fn vertex_count(&self) -> u32

Returns exact amount of vertices in the buffer.

source

pub fn vertex_size(&self) -> u8

Return vertex size of the buffer.

source

pub fn find_free_shader_location(&self) -> u8

Finds free location for an attribute in the layout.

Trait Implementations§

source§

impl Clone for VertexBuffer

source§

fn clone(&self) -> VertexBuffer

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for VertexBuffer

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for VertexBuffer

source§

fn default() -> VertexBuffer

Returns the “default value” for a type. Read more
source§

impl Visit for VertexBufferwhere Vec<VertexAttribute>: Visit, [Option<VertexAttribute>; 13]: Visit, u8: Visit, u32: Visit, BytesStorage: Visit, u64: Visit,

source§

fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast for Twhere T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for Twhere T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
source§

impl<T> FieldValue for Twhere T: 'static,

source§

fn as_any(&self) -> &(dyn Any + 'static)

Casts self to a &dyn Any
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ScriptMessagePayload for Twhere T: 'static + Send,

source§

fn as_any_ref(&self) -> &(dyn Any + 'static)

Returns self as &dyn Any
source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Returns self as &dyn Any
§

impl<SS, SP> SupersetOf<SS> for SPwhere SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
source§

impl<T> ResourceLoadError for Twhere T: 'static + Debug + Send + Sync,