dear_implot3d/
mesh_builder.rs1use std::borrow::Cow;
2
3use crate::item_style::{Plot3DItemStyle, plot3d_spec_with_style};
4use crate::plots::{Plot3DError, primitive_vertex_count};
5use crate::{Item3DFlags, Mesh3DFlags, Plot3DDataLayout, Plot3DScope, len_i32, sys};
6
7pub struct Mesh3DBuilder<'ui> {
9 pub(crate) _ui: &'ui Plot3DScope<'ui>,
10 pub(crate) label: Cow<'ui, str>,
11 pub(crate) vertices: &'ui [[f32; 3]],
12 pub(crate) indices: &'ui [u32],
13 pub(crate) flags: Mesh3DFlags,
14 pub(crate) item_flags: Item3DFlags,
15 pub(crate) style: Plot3DItemStyle,
16}
17
18impl<'ui> Mesh3DBuilder<'ui> {
19 pub fn flags(mut self, flags: Mesh3DFlags) -> Self {
20 self.flags = flags;
21 self
22 }
23 pub fn plot(self) {
25 let _ = self.try_plot();
26 }
27
28 pub fn try_plot(self) -> Result<(), Plot3DError> {
30 let draw_lines = !self.flags.contains(Mesh3DFlags::NO_LINES);
31 let (vtx_count, idx_count) = mesh_counts(self.vertices.len(), self.indices, draw_lines)?;
32 self._ui.with_bound_context(|| {
33 let mut xs = Vec::with_capacity(self.vertices.len());
34 let mut ys = Vec::with_capacity(self.vertices.len());
35 let mut zs = Vec::with_capacity(self.vertices.len());
36 for [x, y, z] in self.vertices.iter().copied() {
37 xs.push(x);
38 ys.push(y);
39 zs.push(z);
40 }
41
42 let label = self.label.as_ref();
43 let label = if label.contains('\0') { "mesh" } else { label };
44 dear_imgui_rs::with_scratch_txt(label, |label_ptr| unsafe {
45 let spec = plot3d_spec_with_style(
46 &self._ui.next_item,
47 self.style,
48 self.flags.bits() | self.item_flags.bits(),
49 Plot3DDataLayout::DEFAULT,
50 );
51 sys::ImPlot3D_PlotMesh_FloatPtr(
52 label_ptr,
53 xs.as_ptr(),
54 ys.as_ptr(),
55 zs.as_ptr(),
56 self.indices.as_ptr(),
57 vtx_count,
58 idx_count,
59 spec,
60 );
61 })
62 });
63 Ok(())
64 }
65}
66
67fn mesh_counts(
68 vertex_count: usize,
69 indices: &[u32],
70 draw_lines: bool,
71) -> Result<(i32, i32), Plot3DError> {
72 if vertex_count == 0 {
73 return Err(Plot3DError::EmptyData);
74 }
75 let vertices = len_i32(vertex_count).ok_or(Plot3DError::NativeCountOutOfRange {
76 what: "mesh vertices",
77 })?;
78 let count = primitive_vertex_count(
79 indices.len(),
80 3,
81 "mesh indices",
82 Plot3DDataLayout::DEFAULT,
83 draw_lines,
84 )?;
85 if let Some(&index) = indices
86 .iter()
87 .find(|&&index| index as usize >= vertex_count)
88 {
89 return Err(Plot3DError::MeshIndexOutOfBounds {
90 index,
91 vertex_count,
92 });
93 }
94 Ok((vertices, count))
95}
96
97impl<'ui> Plot3DScope<'ui> {
98 pub fn mesh(
100 &'ui self,
101 label: impl Into<Cow<'ui, str>>,
102 vertices: &'ui [[f32; 3]],
103 indices: &'ui [u32],
104 ) -> Mesh3DBuilder<'ui> {
105 Mesh3DBuilder {
106 _ui: self,
107 label: label.into(),
108 vertices,
109 indices,
110 flags: Mesh3DFlags::NONE,
111 item_flags: Item3DFlags::NONE,
112 style: Plot3DItemStyle::default(),
113 }
114 }
115}