limelight_primitives/hairline/
mod.rs

1use crate::color::Color;
2use anyhow::Result;
3use limelight::{
4    attribute,
5    renderer::Drawable,
6    state::{
7        blending::{BlendFunction, BlendingFactorDest, BlendingFactorSrc},
8        StateDescriptor,
9    },
10    webgl::types::{DataType, SizedDataType},
11    AsSizedDataType, Buffer, BufferUsageHint, DrawMode, DummyBuffer, Program, Uniform,
12};
13
14#[repr(u32)]
15#[derive(Clone, Copy)]
16pub enum Orientation {
17    Horizontal = 0x0,
18    Vertical = 0x1,
19}
20
21unsafe impl bytemuck::Pod for Orientation {}
22unsafe impl bytemuck::Zeroable for Orientation {}
23
24impl AsSizedDataType for Orientation {
25    fn as_sized_data_type() -> SizedDataType {
26        SizedDataType::new(DataType::UnsignedInt, 1)
27    }
28}
29
30#[attribute]
31pub struct Hairline {
32    pub location: f32,
33    pub color: Color,
34    pub orientation: Orientation,
35}
36
37pub struct HairlineLayer {
38    lines: Buffer<Hairline>,
39    program: Program<(), Hairline>,
40    transform: Uniform<[[f32; 4]; 4]>,
41}
42
43impl HairlineLayer {
44    pub fn new() -> Self {
45        Self::new_transform(Uniform::identity())
46    }
47    
48    pub fn new_transform(transform: Uniform<[[f32; 4]; 4]>) -> Self {
49        let program = Program::new(
50            include_str!("shader.vert"),
51            include_str!("shader.frag"),
52            DrawMode::TriangleStrip,
53        )
54        .with_state(StateDescriptor {
55            blend_func: Some(BlendFunction {
56                source_factor: BlendingFactorSrc::One,
57                dst_factor: BlendingFactorDest::OneMinusSrcAlpha,
58                ..Default::default()
59            }),
60            ..Default::default()
61        })
62        .with_uniform("u_transform", transform.clone());
63
64        HairlineLayer {
65            lines: Buffer::new_empty(BufferUsageHint::DynamicDraw),
66            program,
67            transform,
68        }
69    }
70
71    pub fn buffer(&self) -> Buffer<Hairline> {
72        self.lines.clone()
73    }
74
75    pub fn transform(&self) -> Uniform<[[f32; 4]; 4]> {
76        self.transform.clone()
77    }
78}
79
80impl Drawable for HairlineLayer {
81    fn draw(&mut self, renderer: &mut limelight::Renderer) -> Result<()> {
82        renderer.render_instanced(&mut self.program, &DummyBuffer::new(4), &self.lines)?;
83
84        Ok(())
85    }
86}