use crate::camera::Camera2d;
use crate::color::Color;
use crate::context::Context;
use crate::resource::RenderContext2dEncoder;
use bytemuck::{Pod, Zeroable};
use glamx::{Mat3, Pose2, Vec2};
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
struct LineSegment2D {
point_a: [f32; 2],
width: f32,
_pad1: f32,
point_b: [f32; 2],
_pad2: [f32; 2],
color: [f32; 4],
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
struct ViewUniforms2D {
view: [[f32; 4]; 3],
proj: [[f32; 4]; 3],
viewport: [f32; 4], }
#[derive(Clone, Debug)]
pub struct Polyline2d {
pub vertices: Vec<Vec2>,
pub color: Color,
pub width: f32,
pub transform: Pose2,
}
impl Default for Polyline2d {
fn default() -> Self {
Self {
vertices: Vec::new(),
color: crate::color::WHITE,
width: 2.0,
transform: Pose2::IDENTITY,
}
}
}
impl Polyline2d {
pub fn new(vertices: Vec<Vec2>) -> Self {
Self {
vertices,
..Default::default()
}
}
pub fn with_color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn with_width(mut self, width: f32) -> Self {
self.width = width;
self
}
pub fn with_transform(mut self, transform: Pose2) -> Self {
self.transform = transform;
self
}
}
pub struct PolylineRenderer2d {
pipeline: wgpu::RenderPipeline,
view_bind_group_layout: wgpu::BindGroupLayout,
view_uniform_buffer: wgpu::Buffer,
segment_buffer: wgpu::Buffer,
segment_capacity: usize,
segments: Vec<LineSegment2D>,
}
impl Default for PolylineRenderer2d {
fn default() -> Self {
Self::new()
}
}
impl PolylineRenderer2d {
pub fn new() -> PolylineRenderer2d {
let ctxt = Context::get();
let view_bind_group_layout =
ctxt.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("planar_polyline_view_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,
}],
});
let pipeline_layout = ctxt.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("planar_polyline_pipeline_layout"),
bind_group_layouts: &[Some(&view_bind_group_layout)],
immediate_size: 0,
});
let shader = ctxt.create_shader_module(
Some("planar_polyline_shader"),
include_str!("../builtin/polyline2d.wgsl"),
);
let vertex_buffer_layout = wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<LineSegment2D>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 8,
shader_location: 1,
format: wgpu::VertexFormat::Float32,
},
wgpu::VertexAttribute {
offset: 16,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
],
};
let pipeline = ctxt.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("planar_polyline_pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[vertex_buffer_layout],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: ctxt.surface_format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None, multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview_mask: None,
cache: None,
});
let view_uniform_buffer = ctxt.create_buffer(&wgpu::BufferDescriptor {
label: Some("planar_polyline_view_uniform_buffer"),
size: std::mem::size_of::<ViewUniforms2D>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let segment_capacity = 1024;
let segment_buffer = ctxt.create_buffer(&wgpu::BufferDescriptor {
label: Some("planar_polyline_segment_buffer"),
size: (std::mem::size_of::<LineSegment2D>() * segment_capacity) as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
PolylineRenderer2d {
pipeline,
view_bind_group_layout,
view_uniform_buffer,
segment_buffer,
segment_capacity,
segments: Vec::new(),
}
}
pub fn needs_rendering(&self) -> bool {
!self.segments.is_empty()
}
pub fn draw_polyline(&mut self, polyline: &Polyline2d) {
if polyline.vertices.len() < 2 {
return;
}
let transform = polyline.transform;
let color = [
polyline.color.r,
polyline.color.g,
polyline.color.b,
polyline.color.a,
];
let width = polyline.width;
for pair in polyline.vertices.windows(2) {
let a = transform * pair[0];
let b = transform * pair[1];
self.segments.push(LineSegment2D {
point_a: a.into(),
width,
_pad1: 0.0,
point_b: b.into(),
_pad2: [0.0; 2],
color,
});
}
}
pub fn draw_line(&mut self, a: Vec2, b: Vec2, color: Color, width: f32) {
self.segments.push(LineSegment2D {
point_a: a.into(),
width,
_pad1: 0.0,
point_b: b.into(),
_pad2: [0.0; 2],
color: [color.r, color.g, color.b, color.a],
});
}
pub fn render(&mut self, camera: &mut dyn Camera2d, context: &mut RenderContext2dEncoder) {
if self.segments.is_empty() {
return;
}
let ctxt = Context::get();
let (view, proj) = camera.view_transform_pair();
let view_uniforms = ViewUniforms2D {
view: Self::mat3_to_padded(&view),
proj: Self::mat3_to_padded(&proj),
viewport: [
0.0,
0.0,
context.viewport_width as f32,
context.viewport_height as f32,
],
};
ctxt.write_buffer(
&self.view_uniform_buffer,
0,
bytemuck::bytes_of(&view_uniforms),
);
self.ensure_segment_buffer_capacity(self.segments.len());
ctxt.write_buffer(
&self.segment_buffer,
0,
bytemuck::cast_slice(&self.segments),
);
let view_bind_group = self.create_view_bind_group();
{
let mut render_pass = context
.encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("planar_polyline_render_pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: context.color_view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &view_bind_group, &[]);
render_pass.set_vertex_buffer(0, self.segment_buffer.slice(..));
render_pass.draw(0..6, 0..self.segments.len() as u32);
}
self.segments.clear();
}
fn ensure_segment_buffer_capacity(&mut self, needed: usize) {
if needed > self.segment_capacity {
let ctxt = Context::get();
let new_capacity = needed.next_power_of_two();
self.segment_buffer = ctxt.create_buffer(&wgpu::BufferDescriptor {
label: Some("planar_polyline_segment_buffer"),
size: (std::mem::size_of::<LineSegment2D>() * new_capacity) as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
self.segment_capacity = new_capacity;
}
}
fn create_view_bind_group(&self) -> wgpu::BindGroup {
let ctxt = Context::get();
ctxt.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("planar_polyline_view_bind_group"),
layout: &self.view_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: self.view_uniform_buffer.as_entire_binding(),
}],
})
}
fn mat3_to_padded(m: &Mat3) -> [[f32; 4]; 3] {
[
[m.col(0).x, m.col(0).y, m.col(0).z, 0.0],
[m.col(1).x, m.col(1).y, m.col(1).z, 0.0],
[m.col(2).x, m.col(2).y, m.col(2).z, 0.0],
]
}
}