rmf_site_mesh 0.0.2

Mesh building utilties for rmf_site_editor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::{
    cmp,
    ops::{Add, Mul, Neg},
};

use bevy_asset::{RenderAssetUsages, prelude::*};
use bevy_color::{Color, LinearRgba};
use bevy_derive::Deref;
use bevy_math::Affine3A;
use bevy_mod_outline::ATTRIBUTE_OUTLINE_NORMAL;
use bevy_reflect::prelude::*;
use bevy_render::mesh::{Indices, PrimitiveTopology, VertexAttributeValues};

pub mod faces;
pub use faces::*;

pub mod primitives;
pub use primitives::*;

pub mod traits;
pub use traits::*;
pub enum Angle {
    Deg(Degrees),
    Rad(Radians),
}

#[derive(Deref, Clone, Copy, PartialEq, PartialOrd)]
pub struct Radians(pub f32);

impl From<Radians> for Angle {
    fn from(value: Radians) -> Self {
        Angle::Rad(value)
    }
}

impl From<Angle> for Radians {
    fn from(value: Angle) -> Self {
        match value {
            Angle::Deg(degrees) => Radians(degrees.to_radians()),
            Angle::Rad(radians) => radians,
        }
    }
}

impl PartialEq<f32> for Radians {
    fn eq(&self, other: &f32) -> bool {
        &self.0 == other
    }
}

impl PartialOrd<f32> for Radians {
    fn partial_cmp(&self, other: &f32) -> Option<cmp::Ordering> {
        self.0.partial_cmp(other)
    }
}

impl Neg for Radians {
    type Output = Self;

    fn neg(self) -> Self::Output {
        Self(-self.0)
    }
}

impl Add for Radians {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

#[derive(Deref, PartialEq, PartialOrd)]
pub struct Degrees(pub f32);

impl From<Degrees> for Angle {
    fn from(value: Degrees) -> Self {
        Angle::Deg(value)
    }
}

impl Mul for Degrees {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        Self(self.0 * rhs.0)
    }
}

impl Mul<f32> for Degrees {
    type Output = Self;

    fn mul(self, rhs: f32) -> Self::Output {
        Self(self.0 * rhs)
    }
}

impl From<Degrees> for Radians {
    fn from(value: Degrees) -> Self {
        Self(value.to_radians())
    }
}

impl From<Radians> for Degrees {
    fn from(value: Radians) -> Self {
        Self(value.to_degrees())
    }
}

impl From<Angle> for Degrees {
    fn from(value: Angle) -> Self {
        match value {
            Angle::Deg(degrees) => degrees,
            Angle::Rad(radians) => Degrees(radians.to_degrees()),
        }
    }
}

#[derive(Default, Debug, Clone)]
pub struct MeshBuffer {
    positions: Vec<[f32; 3]>,
    normals: Vec<[f32; 3]>,
    indices: Vec<u32>,
    outline: Vec<u32>,
    uv: Option<Vec<[f32; 2]>>,
    copy_outline_normals: bool,
}

impl From<MeshBuffer> for Mesh {
    fn from(buffer: MeshBuffer) -> Self {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        mesh.insert_indices(Indices::U32(buffer.indices));
        mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, buffer.positions);
        mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, buffer.normals);
        if let Some(uv) = buffer.uv {
            mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uv);
        }
        mesh
    }
}

impl MeshBuffer {
    pub fn new(positions: Vec<[f32; 3]>, normals: Vec<[f32; 3]>, indices: Vec<u32>) -> Self {
        if positions.len() != normals.len() {
            panic!(
                "Inconsistent positions {} vs normals {}",
                positions.len(),
                normals.len(),
            );
        }

        Self {
            positions,
            normals,
            indices,
            outline: Vec::new(),
            uv: None,
            copy_outline_normals: false,
        }
    }

    pub fn empty() -> Self {
        Self::default()
    }

    pub fn copy_outline_normals(mut self) -> Self {
        self.copy_outline_normals = true;
        self
    }

    pub fn with_outline(mut self, outline: Vec<u32>) -> Self {
        self.outline = outline;
        self
    }

    pub fn with_uv(mut self, uv: Vec<[f32; 2]>) -> Self {
        if uv.len() != self.positions.len() {
            panic!(
                "Inconsistent positions {} vs uv {}",
                self.positions.len(),
                uv.len()
            );
        }
        self.uv = Some(uv);
        self
    }

    pub fn scale_uv(mut self, x_scale: f32, y_scale: f32) -> Self {
        let Some(uvs) = self.uv else {
            return self;
        };
        let new_uvs = uvs
            .iter()
            .map(|p| [p[0] * x_scale, p[1] * y_scale])
            .collect();
        self.uv = Some(new_uvs);
        self
    }

    pub fn flip_uv(mut self) -> Self {
        let Some(uvs) = self.uv else {
            return self;
        };
        let new_uvs = uvs.iter().map(|p| [p[1], p[0]]).collect();
        self.uv = Some(new_uvs);
        self
    }

    // For existing positions, allocate UV values between 0 to 1.
    pub fn add_normalised_uv(mut self) -> Self {
        let mut min_x = f32::MAX;
        let mut max_x = f32::MIN;
        let mut min_y = f32::MAX;
        let mut max_y = f32::MIN;

        for pos in self.positions.iter() {
            min_x = min_x.min(pos[0]);
            max_x = max_x.max(pos[0]);
            min_y = min_y.min(pos[1]);
            max_y = max_y.max(pos[1]);
        }

        let range_x = max_x - min_x;
        let range_y = max_y - min_y;

        let uvs: Vec<[f32; 2]> = self
            .positions
            .iter()
            .map(|pos| {
                let x = (pos[0] - min_x) / range_x;
                let y = (pos[1] - min_y) / range_y;
                [x, y]
            })
            .collect();

        self.uv = Some(uvs);
        self
    }

    pub fn transform_by(mut self, tf: Affine3A) -> Self {
        for p in &mut self.positions {
            *p = tf.transform_point3((*p).into()).into();
        }

        for n in &mut self.normals {
            *n = tf.transform_vector3((*n).into()).into();
        }

        self
    }

    pub fn merge_with(mut self, other: Self) -> Self {
        let offset = self.positions.len();
        self.indices
            .extend(other.indices.into_iter().map(|i| i + offset as u32));
        self.outline
            .extend(other.outline.into_iter().map(|i| i + offset as u32));
        self.positions.extend(other.positions.into_iter());
        self.normals.extend(other.normals.into_iter());

        // Only keep the UV property if both meshes contain it. Otherwise drop it.
        if let (Some(mut uv), Some(other_uv)) = (self.uv, other.uv) {
            uv.extend(other_uv);
            self.uv = Some(uv);
        } else {
            self.uv = None;
        }

        self
    }

    pub fn merge_into(self, mesh: &mut Mesh) {
        let offset = mesh.attribute(Mesh::ATTRIBUTE_POSITION).map(|a| a.len());
        if let Some(offset) = offset {
            match mesh.primitive_topology() {
                PrimitiveTopology::TriangleList => {
                    if let Some(Indices::U32(indices)) = mesh.indices_mut() {
                        indices.extend(self.indices.into_iter().map(|i| i + offset as u32));
                    } else {
                        mesh.insert_indices(Indices::U32(
                            self.indices
                                .into_iter()
                                .map(|i| i + offset as u32)
                                .collect(),
                        ));
                    }
                }
                PrimitiveTopology::LineList => {
                    if let Some(Indices::U32(indices)) = mesh.indices_mut() {
                        indices.extend(self.outline.into_iter().map(|i| i + offset as u32));
                    } else {
                        mesh.insert_indices(Indices::U32(
                            self.outline
                                .into_iter()
                                .map(|i| i + offset as u32)
                                .collect(),
                        ));
                    }
                }
                other => {
                    panic!(
                        "Unsupported primitive topology while merging mesh: {:?}",
                        other
                    );
                }
            }

            if self.copy_outline_normals {
                if let Some(VertexAttributeValues::Float32x3(current_outline_normals)) =
                    mesh.attribute_mut(ATTRIBUTE_OUTLINE_NORMAL)
                {
                    current_outline_normals.extend(self.normals.clone().into_iter());
                } else {
                    let mut normals =
                        if let Some(VertexAttributeValues::Float32x3(current_normals)) =
                            mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
                        {
                            current_normals.clone()
                        } else {
                            Vec::new()
                        };

                    normals.extend(self.normals.clone().into_iter());
                    mesh.insert_attribute(ATTRIBUTE_OUTLINE_NORMAL, normals);
                }
            }

            if let Some(VertexAttributeValues::Float32x3(current_positions)) =
                mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION)
            {
                current_positions.extend(self.positions.into_iter());

                if let Some(VertexAttributeValues::Float32x3(current_normals)) =
                    mesh.attribute_mut(Mesh::ATTRIBUTE_NORMAL)
                {
                    current_normals.extend(self.normals.into_iter());
                } else {
                    panic!("Mesh is missing normals attribute when it has positions attribute!");
                }
            } else {
                panic!("Unsupported position type while merging mesh");
            }

            if let Some(VertexAttributeValues::Float32x2(current_uvs)) =
                mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0)
            {
                if let Some(new_uvs) = self.uv {
                    current_uvs.extend(new_uvs);
                } else {
                    panic!("Mesh needs UV values but the buffer does not have any!");
                }
            }
        } else {
            // The mesh currently has no positions in it (and should therefore have no normals or indices either)
            mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, self.positions);
            mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, self.normals);
            if let Some(uv) = self.uv {
                mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uv);
            }

            match mesh.primitive_topology() {
                PrimitiveTopology::TriangleList => {
                    mesh.insert_indices(Indices::U32(self.indices));
                }
                PrimitiveTopology::LineList => {
                    mesh.insert_indices(Indices::U32(self.outline));
                }
                other => {
                    panic!(
                        "Unsupported primitive topology while merging mesh: {:?}",
                        other
                    );
                }
            }
        }
    }

    pub fn into_outline(self) -> Mesh {
        let mut mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::default());
        mesh.insert_indices(Indices::U32(self.outline));
        mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, self.positions);
        mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, self.normals);
        mesh
    }

    pub fn into_mesh_and_outline(self) -> (Mesh, Mesh) {
        let clone = self.clone();
        (clone.into(), self.into_outline())
    }
}

// TODO(@xiyuoh) Temp only: ported from bevy_polyline, use GizmoConfig to instead
#[derive(Asset, Debug, PartialEq, Clone, Copy, TypePath)]
pub struct PolylineMaterial {
    /// Width of the line.
    ///
    /// Corresponds to screen pixels when line is positioned nearest the
    /// camera.
    pub width: f32,
    pub color: LinearRgba,
    /// How closer to the camera than real geometry the line should be.
    ///
    /// Value between -1 and 1 (inclusive).
    /// * 0 means that there is no change to the line position when rendering
    /// * 1 means it is furthest away from camera as possible
    /// * -1 means that it will always render in front of other things.
    ///
    /// This is typically useful if you are drawing wireframes on top of polygons
    /// and your wireframe is z-fighting (flickering on/off) with your main model.
    /// You would set this value to a negative number close to 0.0.
    pub depth_bias: f32,
    /// Whether to reduce line width with perspective.
    ///
    /// When `perspective` is `true`, `width` corresponds to screen pixels at
    /// the near plane and becomes progressively smaller further away. This is done
    /// by dividing `width` by the w component of the homogeneous coordinate.
    ///
    /// If the width where to be lower than 1, the color of the line is faded. This
    /// prevents flickering.
    ///
    /// Note that `depth_bias` **does not** interact with this in any way.
    pub perspective: bool,
}

impl Default for PolylineMaterial {
    fn default() -> Self {
        Self {
            width: 10.0,
            color: Color::WHITE.to_linear(),
            depth_bias: 0.0,
            perspective: false,
        }
    }
}