density-mesh-core 1.5.0

Core module for density mesh generator
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
pub mod process_status;
mod processing_change;

use crate::{
    coord::Coord,
    generator::{process_status::ProcessStatus, processing_change::ProcessingChange},
    map::{DensityMap, DensityMapError},
    mesh::{
        points_separation::PointsSeparation, settings::GenerateDensityMeshSettings, DensityMesh,
        GenerateDensityMeshError,
    },
    triangle::Triangle,
    Scalar,
};
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::{
    collections::VecDeque,
    time::{Duration, Instant},
};
use triangulation::{Delaunay, Point};

#[cfg(feature = "parallel")]
macro_rules! into_iter {
    ($v:expr) => {
        $v.into_par_iter()
    };
}

#[cfg(not(feature = "parallel"))]
macro_rules! into_iter {
    ($v:expr) => {
        $v.into_iter()
    };
}

/// Generate density mesh with region changes.
/// For now it recalculates mesh from whole density map data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DensityMeshGenerator {
    map: DensityMap,
    mesh: Option<DensityMesh>,
    /// [([points], settings)]
    queue: VecDeque<(Vec<Coord>, GenerateDensityMeshSettings)>,
    current: Option<ProcessingChange>,
}

impl DensityMeshGenerator {
    /// Create new generator.
    ///
    /// # Arguments
    /// * `points` - Initial points.
    /// * `map` - Density map.
    /// * `settings` - Settings.
    ///
    /// # Returns
    /// New generator instance.
    pub fn new(points: Vec<Coord>, map: DensityMap, settings: GenerateDensityMeshSettings) -> Self {
        let mut queue = VecDeque::with_capacity(1);
        queue.push_back((points, settings));
        Self {
            map,
            mesh: None,
            queue,
            current: None,
        }
    }

    /// Get inner density map.
    pub fn map(&self) -> &DensityMap {
        &self.map
    }

    /// Get inner density mesh if one is already generated.
    pub fn mesh(&self) -> Option<&DensityMesh> {
        self.mesh.as_ref()
    }

    pub fn into_mesh(self) -> Option<DensityMesh> {
        self.mesh
    }

    /// Tells if there are changes left to process.
    pub fn in_progress(&self) -> bool {
        self.current.is_some() || !self.queue.is_empty()
    }

    /// Get processing progress.
    ///
    /// # Returns
    /// `(current, limit, percentage)`
    pub fn progress(&self) -> (usize, usize, Scalar) {
        match &self.current {
            Some(ProcessingChange::FindingPoints {
                progress_current,
                progress_limit,
                ..
            }) => (
                *progress_current,
                *progress_limit,
                *progress_current as Scalar / *progress_limit as Scalar,
            ),
            Some(ProcessingChange::Triangulate { progress_limit, .. }) => {
                (*progress_limit, *progress_limit, 1.0)
            }
            Some(ProcessingChange::RemoveInvisibleTriangles { progress_limit, .. }) => {
                (*progress_limit, *progress_limit, 1.0)
            }
            Some(ProcessingChange::Extrude { progress_limit, .. }) => {
                (*progress_limit, *progress_limit, 1.0)
            }
            _ => (0, 0, 0.0),
        }
    }

    /// Add map change to the pending queue.
    ///
    /// # Arguments
    /// * `col` - Density map destination column.
    /// * `row` - Density map destination row.
    /// * `width` - Source data unscaled width.
    /// * `height` - Source data unscaled height.
    /// * `data` - Source data buffer.
    /// * `settings` - Density mesh generation settings applied for this change.
    ///
    /// # Returns
    /// Ok if successful or density map error.
    pub fn change_map(
        &mut self,
        col: usize,
        row: usize,
        width: usize,
        height: usize,
        data: Vec<u8>,
        settings: GenerateDensityMeshSettings,
    ) -> Result<(), DensityMapError> {
        self.map.change(col, row, width, height, data)?;
        self.queue.push_back((vec![], settings));
        Ok(())
    }

    /// Process penging change.
    ///
    /// # Returns
    /// Result with process status when ok, otherwise error.
    #[allow(clippy::many_single_char_names)]
    pub fn process(&mut self) -> Result<ProcessStatus, GenerateDensityMeshError> {
        if let Some(current) = std::mem::replace(&mut self.current, None) {
            match current {
                ProcessingChange::FindingPoints {
                    settings,
                    mut tries,
                    mut remaining,
                    mut points,
                    mut progress_current,
                    progress_limit,
                } => {
                    if !points.is_empty() {
                        remaining = into_iter!(remaining)
                            .filter(|(p1, _, _, lpss)| {
                                points.iter().all(|p2| (*p2 - *p1).sqr_magnitude() > *lpss)
                            })
                            .collect::<Vec<_>>();
                        if remaining.is_empty() {
                            self.current = Some(ProcessingChange::Triangulate {
                                settings,
                                points,
                                progress_limit,
                            });
                            return Ok(ProcessStatus::InProgress);
                        }
                    }
                    if let Some((point, _, _, _)) = remaining
                        .iter()
                        .max_by(|a, b| a.2.partial_cmp(&b.2).unwrap())
                    {
                        points.push(*point);
                        tries = settings.max_iterations;
                    } else if tries > 0 {
                        tries -= 1;
                        self.current = Some(ProcessingChange::FindingPoints {
                            settings,
                            tries,
                            remaining,
                            points,
                            progress_current,
                            progress_limit,
                        });
                        return Ok(ProcessStatus::InProgress);
                    } else {
                        self.current = Some(ProcessingChange::Triangulate {
                            settings,
                            points,
                            progress_limit,
                        });
                        return Ok(ProcessStatus::InProgress);
                    }
                    progress_current = progress_limit - remaining.len();
                    self.current = Some(ProcessingChange::FindingPoints {
                        settings,
                        tries,
                        remaining,
                        points,
                        progress_current,
                        progress_limit,
                    });
                    Ok(ProcessStatus::InProgress)
                }
                ProcessingChange::Triangulate {
                    settings,
                    points,
                    progress_limit,
                } => {
                    let dpoints = points
                        .iter()
                        .map(|v| Point::new(v.x, v.y))
                        .collect::<Vec<_>>();
                    let triangulation = if let Some(triangulation) = Delaunay::new(&dpoints) {
                        triangulation
                    } else {
                        return Err(GenerateDensityMeshError::FailedTriangulation);
                    };
                    let triangles = triangulation
                        .dcel
                        .vertices
                        .chunks(3)
                        .map(|t| Triangle {
                            a: t[0],
                            b: t[1],
                            c: t[2],
                        })
                        .collect::<Vec<_>>();
                    if !settings.keep_invisible_triangles {
                        self.current = Some(ProcessingChange::RemoveInvisibleTriangles {
                            settings,
                            points,
                            triangles,
                            progress_limit,
                        });
                        Ok(ProcessStatus::InProgress)
                    } else if let Some(size) = settings.extrude_size {
                        self.current = Some(ProcessingChange::Extrude {
                            points,
                            triangles,
                            size,
                            progress_limit,
                        });
                        Ok(ProcessStatus::InProgress)
                    } else {
                        self.mesh = Some(DensityMesh { points, triangles });
                        Ok(ProcessStatus::MeshChanged)
                    }
                }
                ProcessingChange::RemoveInvisibleTriangles {
                    settings,
                    points,
                    mut triangles,
                    progress_limit,
                } => {
                    triangles = triangles
                        .into_iter()
                        .filter(|t| {
                            Self::is_triangle_visible(
                                points[t.a],
                                points[t.b],
                                points[t.c],
                                &self.map,
                                &settings,
                            )
                        })
                        .collect::<Vec<_>>();
                    if let Some(size) = settings.extrude_size {
                        self.current = Some(ProcessingChange::Extrude {
                            points,
                            triangles,
                            size,
                            progress_limit,
                        });
                        Ok(ProcessStatus::InProgress)
                    } else {
                        self.mesh = Some(DensityMesh { points, triangles });
                        Ok(ProcessStatus::MeshChanged)
                    }
                }
                ProcessingChange::Extrude {
                    mut points,
                    mut triangles,
                    size,
                    ..
                } => {
                    let (p, t) = Self::extrude(&points, &triangles, size);
                    points.extend(p);
                    triangles.extend(t);
                    self.mesh = Some(DensityMesh { points, triangles });
                    Ok(ProcessStatus::MeshChanged)
                }
            }
        } else if let Some((points, settings)) = self.queue.pop_front() {
            let scale = self.map.scale();
            let remaining = self
                .map
                .value_steepness_iter()
                .filter_map(|(x, y, v, s)| {
                    if v > settings.visibility_threshold && s > settings.steepness_threshold {
                        let x = (x * scale) as Scalar;
                        let y = (y * scale) as Scalar;
                        let lpss = match settings.points_separation {
                            PointsSeparation::Constant(v) => v * v,
                            PointsSeparation::SteepnessMapping(f, t) => {
                                let v = Self::lerp(s, t, f);
                                v * v
                            }
                        };
                        Some((Coord::new(x, y), v, s, lpss))
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>();
            let progress_limit = remaining.len();
            let tries = settings.max_iterations;
            self.current = Some(ProcessingChange::FindingPoints {
                settings,
                tries,
                remaining,
                points,
                progress_current: 0,
                progress_limit,
            });
            Ok(ProcessStatus::InProgress)
        } else {
            Ok(ProcessStatus::Idle)
        }
    }

    /// Process incoming changes until none is left to do.
    ///
    /// # Returns
    /// Ok or generation error.
    pub fn process_wait(&mut self) -> Result<(), GenerateDensityMeshError> {
        while self.process()? == ProcessStatus::InProgress {}
        Ok(())
    }

    /// Process incoming changes until none is left to do.
    ///
    /// # Arguments
    /// * `timeout` - Duration of time that processing can take.
    ///
    /// # Returns
    /// Process status or generation error.
    pub fn process_wait_timeout(
        &mut self,
        timeout: Duration,
    ) -> Result<ProcessStatus, GenerateDensityMeshError> {
        let timer = Instant::now();
        loop {
            let status = self.process()?;
            if status != ProcessStatus::InProgress || timer.elapsed() > timeout {
                return Ok(status);
            }
        }
    }

    /// Process incoming changes until none is left to do.
    ///
    /// # Arguments
    /// * `f` - Callback triggered on every processing step. Signature: `fn(progress, limit, factor)`.
    ///
    /// # Returns
    /// Ok or generation error.
    pub fn process_wait_tracked<F>(&mut self, mut f: F) -> Result<(), GenerateDensityMeshError>
    where
        F: FnMut(usize, usize, Scalar),
    {
        let (c, l, p) = self.progress();
        f(c, l, p);
        while self.process()? == ProcessStatus::InProgress {
            let (c, l, p) = self.progress();
            f(c, l, p);
        }
        Ok(())
    }

    /// Process incoming changes until none is left to do.
    ///
    /// # Arguments
    /// * `f` - Callback triggered on every processing step. Signature: `fn(progress, limit, factor)`.
    /// * `timeout` - Duration of time that processing can take.
    ///
    /// # Returns
    /// Process status or generation error.
    pub fn process_wait_timeout_tracked<F>(
        &mut self,
        mut f: F,
        timeout: Duration,
    ) -> Result<ProcessStatus, GenerateDensityMeshError>
    where
        F: FnMut(usize, usize, Scalar),
    {
        let timer = Instant::now();
        let (c, l, p) = self.progress();
        f(c, l, p);
        loop {
            let status = self.process()?;
            let (c, l, p) = self.progress();
            f(c, l, p);
            if status != ProcessStatus::InProgress || timer.elapsed() > timeout {
                return Ok(status);
            }
        }
    }

    fn extrude(
        points: &[Coord],
        triangles: &[Triangle],
        size: Scalar,
    ) -> (Vec<Coord>, Vec<Triangle>) {
        let edges = triangles
            .iter()
            .enumerate()
            .flat_map(|(i, t)| vec![(i, t.a, t.b), (i, t.b, t.c), (i, t.c, t.a)])
            .collect::<Vec<_>>();
        let outline = edges
            .iter()
            .filter(|e1| {
                !edges
                    .iter()
                    .any(|e2| e1.0 != e2.0 && Self::are_edges_connected(e1.1, e1.2, e2.1, e2.2))
            })
            .collect::<Vec<_>>();
        let offsets = outline
            .iter()
            .map(|(_, m, n)| {
                let i = *m;
                let p = outline.iter().find(|(_, _, p)| p == m).unwrap().1;
                let p = points[p];
                let m = points[*m];
                let n = points[*n];
                let pm = -(m - p).normalized().right();
                let mn = -(n - m).normalized().right();
                (i, m + (pm + mn).normalized() * size)
            })
            .collect::<Vec<_>>();
        let triangles = outline
            .into_iter()
            .flat_map(|(_, a, b)| {
                let ea = offsets.iter().position(|(ea, _)| ea == a).unwrap() + points.len();
                let eb = offsets.iter().position(|(eb, _)| eb == b).unwrap() + points.len();
                vec![[*b, *a, ea].into(), [ea, eb, *b].into()]
            })
            .collect::<Vec<_>>();
        (
            offsets.into_iter().map(|(_, p)| p).collect::<Vec<_>>(),
            triangles,
        )
    }

    fn are_edges_connected(a_from: usize, a_to: usize, b_from: usize, b_to: usize) -> bool {
        (a_from == b_from && a_to == b_to) || (a_from == b_to && a_to == b_from)
    }

    fn is_triangle_visible(
        a: Coord,
        b: Coord,
        c: Coord,
        map: &DensityMap,
        settings: &GenerateDensityMeshSettings,
    ) -> bool {
        let fx = (a.x as isize).min(b.x as isize).min(c.x as isize);
        let fy = (a.y as isize).min(b.y as isize).min(c.y as isize);
        let tx = (a.x as isize).max(b.x as isize).max(c.x as isize);
        let ty = (a.y as isize).max(b.y as isize).max(c.y as isize);
        let nab = (b - a).right();
        let nbc = (c - b).right();
        let nca = (a - c).right();
        let mut count = 0;
        let mut samples = 0;
        for y in fy..=ty {
            for x in fx..=tx {
                let p = Coord::new(x as _, y as _);
                if (p - a).dot(nab) >= 0.0 && (p - b).dot(nbc) >= 0.0 && (p - c).dot(nca) >= 0.0 {
                    samples += 1;
                    if Self::is_point_visible((x, y), map, settings) {
                        count += 1;
                    }
                }
            }
        }
        count as Scalar / samples as Scalar > 0.5
    }

    #[inline]
    fn is_point_visible(
        pos: (isize, isize),
        map: &DensityMap,
        settings: &GenerateDensityMeshSettings,
    ) -> bool {
        map.value_at_point(pos) > settings.visibility_threshold
    }

    #[inline]
    fn lerp(value: Scalar, from: Scalar, to: Scalar) -> Scalar {
        from + (to - from) * value.max(0.0).min(1.0)
    }
}