klyff 0.1.3

Text rendering library for games with MSDF support
Documentation
/// Holds the uniform to encode current screen size, necessary for translating glyph to screen
/// space.
pub struct ScreenSizeUniform {
    uniform_bind_group: wgpu::BindGroup,
    uniform_buf: wgpu::Buffer,
}

impl ScreenSizeUniform {
    /// Constructs a new instance, creating necessary wgpu resources on the provided wgpu device.
    pub fn new(device: &wgpu::Device) -> Self {
        let uniform_bind_group_layout = Self::bind_group_layout(device);
        let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("klyff uniform buffer"),
            size: 8,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("klyff uniform bind group"),
            layout: &uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buf.as_entire_binding(),
            }],
        });

        Self {
            uniform_bind_group,
            uniform_buf,
        }
    }

    pub fn bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("klyff uniform bind group layout"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        })
    }

    /// The bind group, bound before drawing with a pipeline.
    pub fn uniform_bind_group(&self) -> &wgpu::BindGroup {
        &self.uniform_bind_group
    }

    /// Write the provided screen size to the uniform buffer.
    pub fn encode(&self, queue: &wgpu::Queue, surface_width: u32, surface_height: u32) {
        // Shader-side `screen_size` is `vec2f`, not `vec2u` — cast before writing.
        queue.write_buffer(
            &self.uniform_buf,
            0,
            bytemuck::cast_slice(&[surface_width as f32, surface_height as f32]),
        );
    }
}