1use std::collections::HashMap;
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU8, Ordering};
15
16use egui::epaint::PaintCallback;
17use egui::{Color32, Rect, Ui};
18use egui_wgpu::wgpu;
19
20static OUTPUT_FORMAT: AtomicU8 = AtomicU8::new(0);
22
23pub fn set_output_format(format: wgpu::TextureFormat) -> bool {
28 let value = match format {
29 wgpu::TextureFormat::Bgra8UnormSrgb => 0,
30 wgpu::TextureFormat::Rgba8UnormSrgb => 1,
31 wgpu::TextureFormat::Bgra8Unorm => 2,
32 wgpu::TextureFormat::Rgba8Unorm => 3,
33 _ => return false,
34 };
35 OUTPUT_FORMAT.store(value, Ordering::Relaxed);
36 true
37}
38
39fn output_format() -> wgpu::TextureFormat {
40 match OUTPUT_FORMAT.load(Ordering::Relaxed) {
41 1 => wgpu::TextureFormat::Rgba8UnormSrgb,
42 2 => wgpu::TextureFormat::Bgra8Unorm,
43 3 => wgpu::TextureFormat::Rgba8Unorm,
44 _ => wgpu::TextureFormat::Bgra8UnormSrgb,
45 }
46}
47
48use super::gpu_line::{GpuLine, GpuTriangle};
49
50#[repr(C)]
51#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
52struct Vertex {
53 position: [f32; 2],
54 color: [f32; 4],
55}
56
57#[repr(C)]
58#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
59struct Uniform {
60 size: [f32; 2],
61 _padding: [f32; 2],
62}
63
64struct LineBuffer {
65 vertex: wgpu::Buffer,
66 bind_group: wgpu::BindGroup,
67 vertices: u32,
68}
69
70const MAX_LINE_BUFFERS: usize = 64;
72
73struct Resources {
74 pipeline: wgpu::RenderPipeline,
75 layout: wgpu::BindGroupLayout,
76 lines: HashMap<u64, LineBuffer>,
77}
78
79fn insert_line(lines: &mut HashMap<u64, LineBuffer>, id: u64, line: LineBuffer) {
82 if lines.len() >= MAX_LINE_BUFFERS {
83 lines.clear();
84 }
85 lines.insert(id, line);
86}
87
88struct LineCallback {
89 id: u64,
90 kind: u64,
91 vertices: Vec<Vertex>,
92 size: [f32; 2],
93}
94
95impl egui_wgpu::CallbackTrait for LineCallback {
96 fn prepare(
97 &self,
98 device: &wgpu::Device,
99 queue: &wgpu::Queue,
100 _screen_descriptor: &egui_wgpu::ScreenDescriptor,
101 _encoder: &mut wgpu::CommandEncoder,
102 resources: &mut egui_wgpu::CallbackResources,
103 ) -> Vec<wgpu::CommandBuffer> {
104 if resources.get::<Resources>().is_none() {
105 resources.insert(Resources::new(device));
106 }
107 let Some(resources) = resources.get_mut::<Resources>() else {
108 return Vec::new();
109 };
110 let vertex_bytes: &[u8] = bytemuck::cast_slice(&self.vertices);
111 if vertex_bytes.len() as u64 > device.limits().max_buffer_size {
112 return Vec::new();
113 }
114 let uniform = Uniform {
115 size: self.size,
116 _padding: [0.0; 2],
117 };
118 let vertex = device.create_buffer(&wgpu::BufferDescriptor {
119 label: Some("workbench_gpu_plot_vertices"),
120 size: vertex_bytes.len().max(4) as u64,
121 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
122 mapped_at_creation: false,
123 });
124 queue.write_buffer(&vertex, 0, vertex_bytes);
125 let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
126 label: Some("workbench_gpu_plot_uniform"),
127 size: std::mem::size_of::<Uniform>() as u64,
128 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
129 mapped_at_creation: false,
130 });
131 queue.write_buffer(&uniform_buffer, 0, bytemuck::bytes_of(&uniform));
132 let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
133 label: Some("workbench_gpu_plot_bind_group"),
134 layout: &resources.layout,
135 entries: &[wgpu::BindGroupEntry {
136 binding: 0,
137 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
138 buffer: &uniform_buffer,
139 offset: 0,
140 size: None,
141 }),
142 }],
143 });
144 insert_line(
145 &mut resources.lines,
146 self.id ^ (self.kind << 61),
147 LineBuffer {
148 vertex,
149 bind_group,
150 vertices: self.vertices.len() as u32,
151 },
152 );
153 Vec::new()
154 }
155
156 fn paint(
157 &self,
158 _info: egui::epaint::PaintCallbackInfo,
159 render_pass: &mut wgpu::RenderPass<'static>,
160 resources: &egui_wgpu::CallbackResources,
161 ) {
162 let Some(resources) = resources.get::<Resources>() else {
163 return;
164 };
165 let Some(line) = resources.lines.get(&(self.id ^ (self.kind << 61))) else {
166 return;
167 };
168 render_pass.set_pipeline(&resources.pipeline);
169 render_pass.set_bind_group(0, &line.bind_group, &[]);
170 render_pass.set_vertex_buffer(0, line.vertex.slice(..));
171 render_pass.draw(0..line.vertices, 0..1);
172 }
173}
174
175impl Resources {
176 fn new(device: &wgpu::Device) -> Self {
177 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
178 label: Some("workbench_gpu_plot_shader"),
179 source: wgpu::ShaderSource::Wgsl(WGSL.into()),
180 });
181 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
182 label: Some("workbench_gpu_plot_layout"),
183 entries: &[wgpu::BindGroupLayoutEntry {
184 binding: 0,
185 visibility: wgpu::ShaderStages::VERTEX,
186 ty: wgpu::BindingType::Buffer {
187 has_dynamic_offset: false,
188 min_binding_size: None,
189 ty: wgpu::BufferBindingType::Uniform,
190 },
191 count: None,
192 }],
193 });
194 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
195 label: Some("workbench_gpu_plot_pipeline_layout"),
196 bind_group_layouts: &[Some(&layout)],
197 immediate_size: 0,
198 });
199 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
200 label: Some("workbench_gpu_plot_pipeline"),
201 layout: Some(&pipeline_layout),
202 vertex: wgpu::VertexState {
203 entry_point: Some("vs_main"),
204 module: &shader,
205 buffers: &[Some(wgpu::VertexBufferLayout {
206 array_stride: std::mem::size_of::<Vertex>() as u64,
207 step_mode: wgpu::VertexStepMode::Vertex,
208 attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x4],
209 })],
210 compilation_options: wgpu::PipelineCompilationOptions::default(),
211 },
212 primitive: wgpu::PrimitiveState {
213 topology: wgpu::PrimitiveTopology::TriangleList,
214 ..Default::default()
215 },
216 depth_stencil: None,
217 multisample: wgpu::MultisampleState::default(),
218 fragment: Some(wgpu::FragmentState {
219 entry_point: Some("fs_main"),
220 module: &shader,
221 targets: &[Some(wgpu::ColorTargetState {
222 format: output_format(),
223 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
224 write_mask: wgpu::ColorWrites::ALL,
225 })],
226 compilation_options: wgpu::PipelineCompilationOptions::default(),
227 }),
228 multiview_mask: None,
229 cache: None,
230 });
231 Self {
232 pipeline,
233 layout,
234 lines: HashMap::new(),
235 }
236 }
237}
238
239const WGSL: &str = r#"
240struct Uniform { size: vec2<f32>, padding: vec2<f32> };
241@group(0) @binding(0) var<uniform> frame: Uniform;
242struct VertexIn { @location(0) position: vec2<f32>, @location(1) color: vec4<f32> };
243struct VertexOut { @builtin(position) position: vec4<f32>, @location(0) color: vec4<f32> };
244@vertex
245fn vs_main(in: VertexIn) -> VertexOut {
246 var out: VertexOut;
247 let ndc = vec2<f32>(in.position.x / frame.size.x * 2.0 - 1.0, 1.0 - in.position.y / frame.size.y * 2.0);
248 out.position = vec4<f32>(ndc, 0.0, 1.0);
249 out.color = in.color;
250 return out;
251}
252@fragment
253fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
254 return in.color;
255}
256"#;
257
258pub fn paint_lines(ui: &Ui, frame: Rect, lines: &[GpuLine], plot_id: egui::Id) {
261 let mut vertices = Vec::new();
262 for line in lines {
263 let color = line.color.to_normalized_gamma_f32();
264 let points = &line.points;
265 if points.len() < 2 {
266 continue;
267 }
268 let segments = if line.closed { points.len() } else { points.len() - 1 };
269 for index in 0..segments {
270 let a = points[index] - frame.min.to_vec2();
271 let b = points[(index + 1) % points.len()] - frame.min.to_vec2();
272 let delta = b - a;
273 let length = delta.length();
274 if length <= f32::EPSILON {
275 continue;
276 }
277 let normal = egui::vec2(-delta.y, delta.x) / length * line.width.max(0.5);
278 let quad = [a + normal, a - normal, b + normal, b + normal, a - normal, b - normal];
279 for point in quad {
280 vertices.push(Vertex {
281 position: [point.x, point.y],
282 color,
283 });
284 }
285 }
286 }
287 if vertices.is_empty() {
288 return;
289 }
290 let id = plot_id.value() ^ (u64::from(frame.left().to_bits()) << 32) ^ u64::from(frame.top().to_bits());
291 let callback = LineCallback {
292 id,
293 kind: 1,
294 vertices,
295 size: [frame.width().max(1.0), frame.height().max(1.0)],
296 };
297 let callback = PaintCallback {
298 rect: frame,
299 callback: Arc::new(egui_wgpu::Callback::new_paint_callback(frame, callback)),
300 };
301 ui.painter().add(egui::Shape::Callback(callback));
302}
303
304pub(super) fn collect(
306 plot: &super::Plot<'_>,
307 transform: &super::axis::Transform,
308 state: &super::PlotState,
309 theme: &crisol_ui_kit::theme::Theme,
310) -> Vec<GpuLine> {
311 let mut lines = Vec::new();
312 for (index, series) in plot.series.iter().enumerate() {
313 if state.is_hidden(&series.name) {
314 continue;
315 }
316 let look = super::overlay::look(plot, index, theme);
317 match series.kind {
318 super::series::Kind::Line { .. } => {
319 let indices = super::paint::visible_indices(transform, series, series.sorted_x(), look.radius);
320 let points: Vec<egui::Pos2> = indices
321 .iter()
322 .map(|index| transform.to_screen(series.data()[*index]))
323 .filter(|point| point.is_finite())
324 .collect();
325 if points.len() >= 2 {
326 lines.push(GpuLine::new(points, look.color, look.width));
327 }
328 }
329 super::series::Kind::Scatter { .. } => {
330 let indices = super::paint::visible_indices(transform, series, series.sorted_x(), look.radius);
331 for index in indices {
332 let point = transform.to_screen(series.data()[index]);
333 if !point.is_finite() || !transform.frame.expand(look.radius * 2.0).contains(point) {
334 continue;
335 }
336 let radius = look.radius;
337 let diamond = vec![
338 egui::pos2(point.x, point.y - radius),
339 egui::pos2(point.x + radius, point.y),
340 egui::pos2(point.x, point.y + radius),
341 egui::pos2(point.x - radius, point.y),
342 ];
343 lines.push(GpuLine::new(diamond, look.color, 1.5).closed());
344 }
345 }
346 _ => {}
347 }
348 }
349 lines
350}
351
352pub fn paint_triangles(ui: &Ui, frame: Rect, triangles: &[GpuTriangle], plot_id: egui::Id) {
354 let mut vertices = Vec::with_capacity(triangles.len() * 3);
355 for triangle in triangles {
356 for point in triangle.points {
357 vertices.push(Vertex {
358 position: [point.x - frame.min.x, point.y - frame.min.y],
359 color: triangle.color.to_normalized_gamma_f32(),
360 });
361 }
362 }
363 if vertices.is_empty() {
364 return;
365 }
366 let id = plot_id.value() ^ (u64::from(frame.left().to_bits()) << 32) ^ u64::from(frame.top().to_bits());
367 let callback = LineCallback {
368 id,
369 kind: 2,
370 vertices,
371 size: [frame.width().max(1.0), frame.height().max(1.0)],
372 };
373 let callback = PaintCallback {
374 rect: frame,
375 callback: Arc::new(egui_wgpu::Callback::new_paint_callback(frame, callback)),
376 };
377 ui.painter().add(egui::Shape::Callback(callback));
378}
379
380pub fn scene_triangles(scene: &mut super::scene::Scene) -> Vec<GpuTriangle> {
383 use super::scene::Prim;
384 let mut triangles = Vec::new();
385 for prim in &scene.data {
386 match prim {
387 Prim::Polygon { points, color } => fan(&mut triangles, points, *color),
388 Prim::Quad { points, color } => {
389 triangles.push(GpuTriangle {
390 points: [points[0], points[1], points[2]],
391 color: *color,
392 });
393 triangles.push(GpuTriangle {
394 points: [points[0], points[2], points[3]],
395 color: *color,
396 });
397 }
398 Prim::Fan { center, points, color } => {
399 for pair in points.windows(2) {
400 triangles.push(GpuTriangle {
401 points: [*center, pair[0], pair[1]],
402 color: *color,
403 });
404 }
405 }
406 Prim::Area { points, base_y, color } => {
407 if points.len() >= 2 {
408 let mut polygon = points.clone();
409 if let (Some(first), Some(last)) = (points.first(), points.last()) {
410 polygon.push(egui::pos2(last.x, *base_y));
411 polygon.push(egui::pos2(first.x, *base_y));
412 }
413 fan(&mut triangles, &polygon, *color);
414 }
415 }
416 Prim::Rect { rect, fill, .. } if fill.a() > 0 => {
417 let p = [
418 rect.left_top(),
419 rect.right_top(),
420 rect.right_bottom(),
421 rect.left_bottom(),
422 ];
423 triangles.push(GpuTriangle {
424 points: [p[0], p[1], p[2]],
425 color: *fill,
426 });
427 triangles.push(GpuTriangle {
428 points: [p[0], p[2], p[3]],
429 color: *fill,
430 });
431 }
432 Prim::Circle {
433 center, radius, fill, ..
434 } if fill.a() > 0 => {
435 let count = 24;
436 for index in 0..count {
437 let a = index as f32 / count as f32 * std::f32::consts::TAU;
438 let b = (index + 1) as f32 / count as f32 * std::f32::consts::TAU;
439 triangles.push(GpuTriangle {
440 points: [
441 *center,
442 egui::pos2(center.x + radius * a.cos(), center.y + radius * a.sin()),
443 egui::pos2(center.x + radius * b.cos(), center.y + radius * b.sin()),
444 ],
445 color: *fill,
446 });
447 }
448 }
449 _ => {}
450 }
451 }
452 scene.data.retain(|prim| {
453 !matches!(
454 prim,
455 Prim::Polygon { .. }
456 | Prim::Quad { .. }
457 | Prim::Fan { .. }
458 | Prim::Rect { .. }
459 | Prim::Circle { .. }
460 | Prim::Area { .. }
461 )
462 });
463 triangles
464}
465
466fn fan(triangles: &mut Vec<GpuTriangle>, points: &[egui::Pos2], color: Color32) {
467 for index in 1..points.len().saturating_sub(1) {
468 triangles.push(GpuTriangle {
469 points: [points[0], points[index], points[index + 1]],
470 color,
471 });
472 }
473}
474
475#[cfg(test)]
476mod tests;