honeycomb-render 0.11.0

Visualization tool for combinatorial maps
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
508
509
510
511
512
513
514
515
use bevy::prelude::{Bundle, Commands, Component, Res, Resource, Vec3};
use bevy::utils::HashMap;
use honeycomb_core::cmap::NULL_DART_ID;
use honeycomb_core::{
    cmap::{
        CMap2, CMap3, DartIdType, EdgeIdType, FaceIdType, OrbitPolicy, VertexIdType, VolumeIdType,
    },
    geometry::CoordsFloat,
};
use itertools::Itertools;

// --- shared data

/// Combinatorial map to render.
#[derive(Resource)]
pub struct Map<T: CoordsFloat>(pub CMap2<T>);

/// Combinatorial map to render.
#[derive(Resource)]
pub struct Map3<T: CoordsFloat>(pub CMap3<T>);

/// Collection of a map's vertices.
#[derive(Resource)]
pub struct MapVertices(pub Vec<Vec3>);

/// Collection of normals, organized per faces of a map.
#[derive(Resource)]
pub struct FaceNormals(pub HashMap<(FaceIdType, usize), Vec3>);

/// Collection of normals, organized per volumes of a map.
#[derive(Resource)]
pub struct VolumeNormals(pub HashMap<(VolumeIdType, usize), Vec3>);

// --- bundles

/// Bundle used to create entities modeling dart bodies.
#[derive(Bundle, Clone)]
pub struct DartBundle {
    pub(crate) id: DartId,
    pub(crate) vertex_id: VertexId,
    pub(crate) edge_id: EdgeId,
    pub(crate) face_id: FaceId,
    pub(crate) volume_id: VolumeId,
    pub(crate) dart: Dart,
}

/// Bundle used to create entities modeling vertices.
#[derive(Bundle, Clone)]
pub struct VertexBundle {
    pub(crate) id: VertexId,
    pub(crate) vertex: Vertex,
}

/// Bundle used to create entities modeling edges.
#[derive(Bundle, Clone)]
pub struct EdgeBundle {
    pub(crate) id: EdgeId,
    pub(crate) edge: Edge,
}

/// Bundle used to create entities modeling faces.
#[derive(Bundle, Clone)]
pub struct FaceBundle {
    pub(crate) id: FaceId,
    pub(crate) face: Face,
}

// --- individual components

/// Dart ID component.
#[derive(Component, Clone)]
pub struct DartId(pub DartIdType);

/// Vertex ID component.
#[derive(Component, Clone)]
pub struct VertexId(pub VertexIdType);

/// Edge ID component.
#[derive(Component, Clone)]
pub struct EdgeId(pub EdgeIdType);

/// Face ID component.
#[derive(Component, Clone)]
pub struct FaceId(pub FaceIdType);

/// Volume ID component.
#[derive(Component, Clone)]
pub struct VolumeId(pub VolumeIdType);

/// Dart head component.
#[derive(Component, Clone)]
pub struct Dart {
    pub(crate) start: usize,
    pub(crate) end: usize,
}

/// Beta component.
#[derive(Component, Clone)]
pub struct Beta(pub u8, pub usize, pub usize); // beta id, v0_id, v1_id ?

/// Vertex component.
#[derive(Component, Clone)]
pub struct Vertex(pub usize); // map id, vid

/// Edge component.
#[derive(Component, Clone)]
pub struct Edge(pub usize, pub usize); // v0_id, v1_id

/// Face component.
#[derive(Component, Clone)]
pub struct Face(pub Vec<usize>); // vertex list

/// Volume component.
#[derive(Component, Clone)]
pub struct Volume;

// --- startup routine

/// Build ECS data from a combinatorial map object.
///
/// # Panics
///
/// This function will panic if there is a topological vertex with no associated coordinates.
#[allow(clippy::too_many_lines)]
pub fn extract_data_from_map<T: CoordsFloat>(mut commands: Commands, cmap: Res<Map<T>>) {
    let cmap = &cmap.0;
    let map_vertices: Vec<_> = cmap.iter_vertices().collect();
    let map_edges: Vec<_> = cmap.iter_edges().collect();
    let map_faces: Vec<_> = cmap.iter_faces().collect();

    let mut index_map: HashMap<VertexIdType, usize> = HashMap::with_capacity(cmap.n_vertices());

    let vertex_vals: Vec<Vec3> = map_vertices
        .iter()
        .enumerate()
        .map(|(idx, vid)| {
            index_map.insert(*vid, idx);
            let v = cmap
                .read_vertex(*vid)
                .expect("E: found a topological vertex with no associated coordinates");
            // sane unwraps; will crash if the coordinates cannot be converted to f32
            Vec3::from((v.0.to_f32().unwrap(), v.1.to_f32().unwrap(), 0.0))
        })
        .collect();

    let vertices: Vec<VertexBundle> = map_vertices
        .iter()
        .map(|id| VertexBundle {
            id: VertexId(*id),
            vertex: Vertex(index_map[id]),
        })
        .collect();

    let edges: Vec<EdgeBundle> = map_edges
        .iter()
        .map(|id| {
            let v1id = cmap.vertex_id(*id as DartIdType);
            let v2id = if cmap.is_i_free::<2>(*id as DartIdType) {
                cmap.vertex_id(cmap.beta::<1>(*id as DartIdType))
            } else {
                cmap.vertex_id(cmap.beta::<2>(*id as DartIdType))
            };
            EdgeBundle {
                id: EdgeId(*id),
                edge: Edge(index_map[&v1id], index_map[&v2id]),
            }
        })
        .collect();

    let mut face_normals = HashMap::new();
    let mut darts: Vec<DartBundle> = Vec::new();

    let faces: Vec<FaceBundle> = map_faces
        .iter()
        .map(|id| {
            let vertex_ids: Vec<usize> = cmap
                .orbit(OrbitPolicy::Custom(&[1]), *id as DartIdType)
                .map(|dart_id| index_map[&cmap.vertex_id(dart_id)])
                .collect();
            let n_v = vertex_ids.len();
            {
                let (ver_in, ver, ver_out) = (&vertex_ids[n_v - 1], &vertex_ids[0], &vertex_ids[1]);
                let (vec_in, vec_out) = (
                    vertex_vals[*ver] - vertex_vals[*ver_in],
                    vertex_vals[*ver_out] - vertex_vals[*ver],
                );
                // vec_in/out belong to X/Y plane => .cross(Z) == normal in the plane
                // a first normalization is required because both edges should weight equally
                let normal = (vec_in.cross(Vec3::Z).normalize()
                    + vec_out.cross(Vec3::Z).normalize())
                .normalize();
                face_normals.insert((*id, *ver), normal);
            }
            vertex_ids.windows(3).for_each(|wdw| {
                let [ver_in, ver, ver_out] = wdw else {
                    unreachable!("i kneel");
                };
                let (vec_in, vec_out) = (
                    vertex_vals[*ver] - vertex_vals[*ver_in],
                    vertex_vals[*ver_out] - vertex_vals[*ver],
                );
                let normal = (vec_in.cross(Vec3::Z).normalize()
                    + vec_out.cross(Vec3::Z).normalize())
                .normalize();
                face_normals.insert((*id, *ver), normal);
            });
            {
                let (ver_in, ver, ver_out) =
                    (&vertex_ids[n_v - 2], &vertex_ids[n_v - 1], &vertex_ids[0]);
                let (vec_in, vec_out) = (
                    vertex_vals[*ver] - vertex_vals[*ver_in],
                    vertex_vals[*ver_out] - vertex_vals[*ver],
                );
                let normal = (vec_in.cross(Vec3::Z).normalize()
                    + vec_out.cross(Vec3::Z).normalize())
                .normalize();
                face_normals.insert((*id, *ver), normal);
            }

            // common dart iterator
            let mut tmp = cmap
                .orbit(OrbitPolicy::Custom(&[1]), *id as DartIdType)
                .map(|dart_id| (dart_id, index_map[&cmap.vertex_id(dart_id)]))
                .collect::<Vec<_>>();
            tmp.push(tmp[0]); // trick for the `.windows` call

            // dart bodies
            let bodies = tmp.windows(2).map(|wd| {
                let [(dart_id, v1_id), (_, v2_id)] = wd else {
                    unreachable!("i kneel");
                };

                DartBundle {
                    id: DartId(*dart_id),
                    vertex_id: VertexId(cmap.vertex_id(*dart_id)),
                    edge_id: EdgeId(cmap.edge_id(*dart_id)),
                    face_id: FaceId(*id),
                    volume_id: VolumeId(1),
                    dart: Dart {
                        start: *v1_id,
                        end: *v2_id,
                    },
                }
            });

            darts.extend(bodies);

            FaceBundle {
                id: FaceId(*id),
                face: Face(vertex_ids),
            }
        })
        .collect();

    commands.insert_resource(MapVertices(vertex_vals));
    commands.insert_resource(FaceNormals(face_normals));

    for bundle in darts {
        commands.spawn(bundle);
    }
    for bundle in vertices {
        commands.spawn(bundle);
    }
    for bundle in edges {
        commands.spawn(bundle);
    }
    for bundle in faces {
        commands.spawn(bundle);
    }
}

/// Build ECS data from a combinatorial map object.
///
/// # Panics
///
/// This function will panic if there is a topological vertex with no associated coordinates.
#[allow(clippy::too_many_lines)]
pub fn extract_data_from_3d_map<T: CoordsFloat>(mut commands: Commands, cmap: Res<Map3<T>>) {
    let cmap = &cmap.0;
    let map_vertices: Vec<_> = cmap.iter_vertices().collect();
    let map_edges: Vec<_> = cmap.iter_edges().collect();
    let map_faces: Vec<_> = cmap.iter_faces().collect();
    let map_volumes: Vec<_> = cmap.iter_volumes().collect();

    let mut index_map: HashMap<VertexIdType, usize> = HashMap::with_capacity(cmap.n_vertices());

    let vertex_vals: Vec<Vec3> = map_vertices
        .iter()
        .enumerate()
        .map(|(idx, vid)| {
            index_map.insert(*vid, idx);
            let v = cmap
                .read_vertex(*vid)
                .expect("E: found a topological vertex with no associated coordinates");
            // sane unwraps; will crash if the coordinates cannot be converted to f32
            Vec3::from((
                v.0.to_f32().unwrap(),
                v.1.to_f32().unwrap(),
                v.2.to_f32().unwrap(),
            ))
        })
        .collect();

    let vertices: Vec<VertexBundle> = map_vertices
        .iter()
        .map(|id| VertexBundle {
            id: VertexId(*id),
            vertex: Vertex(index_map[id]),
        })
        .collect();

    let edges: Vec<EdgeBundle> = map_edges
        .iter()
        .map(|id| {
            let v1id = cmap.vertex_id(*id as DartIdType);
            let v2id = if cmap.is_i_free::<3>(*id as DartIdType) {
                if cmap.is_i_free::<2>(*id as DartIdType) {
                    cmap.vertex_id(cmap.beta::<1>(*id as DartIdType))
                } else {
                    cmap.vertex_id(cmap.beta::<2>(*id as DartIdType))
                }
            } else {
                cmap.vertex_id(cmap.beta::<3>(*id as DartIdType))
            };
            EdgeBundle {
                id: EdgeId(*id),
                edge: Edge(index_map[&v1id], index_map[&v2id]),
            }
        })
        .collect();

    let mut face_normals = HashMap::new();
    let mut darts: Vec<DartBundle> = Vec::new();

    let faces: Vec<FaceBundle> = map_faces
        .iter()
        .map(|id| {
            let vertex_ids: Vec<usize> = cmap
                .orbit(OrbitPolicy::Custom(&[1]), *id as DartIdType) // cannot use FaceLinear here due to doubled darts in 3D
                .map(|dart_id| index_map[&cmap.vertex_id(dart_id)])
                .collect();
            let n_v = vertex_ids.len();
            {
                let (ver_in, ver, ver_out) = (&vertex_ids[n_v - 1], &vertex_ids[0], &vertex_ids[1]);
                let (vec_in, vec_out) = (
                    vertex_vals[*ver] - vertex_vals[*ver_in],
                    vertex_vals[*ver_out] - vertex_vals[*ver],
                );
                // we need to compute the normql formed by the two vectors in 3D
                let plane_normal = vec_in.cross(vec_out).normalize();
                let normal = (vec_in.cross(plane_normal).normalize()
                    + vec_out.cross(plane_normal).normalize())
                .normalize();
                face_normals.insert((*id, *ver), normal);
            }
            vertex_ids.windows(3).for_each(|wdw| {
                let [ver_in, ver, ver_out] = wdw else {
                    unreachable!("i kneel");
                };
                let (vec_in, vec_out) = (
                    vertex_vals[*ver] - vertex_vals[*ver_in],
                    vertex_vals[*ver_out] - vertex_vals[*ver],
                );
                // we need to compute the normql formed by the two vectors in 3D
                let plane_normal = vec_in.cross(vec_out).normalize();
                let normal = (vec_in.cross(plane_normal).normalize()
                    + vec_out.cross(plane_normal).normalize())
                .normalize();
                face_normals.insert((*id, *ver), normal);
            });
            {
                let (ver_in, ver, ver_out) =
                    (&vertex_ids[n_v - 2], &vertex_ids[n_v - 1], &vertex_ids[0]);
                let (vec_in, vec_out) = (
                    vertex_vals[*ver] - vertex_vals[*ver_in],
                    vertex_vals[*ver_out] - vertex_vals[*ver],
                );
                // we need to compute the normql formed by the two vectors in 3D
                let plane_normal = vec_in.cross(vec_out).normalize();
                let normal = (vec_in.cross(plane_normal).normalize()
                    + vec_out.cross(plane_normal).normalize())
                .normalize();
                face_normals.insert((*id, *ver), normal);
            }

            // common dart iterator
            let mut tmp = cmap
                .orbit(OrbitPolicy::Custom(&[1]), *id as DartIdType)
                .map(|dart_id| (dart_id, index_map[&cmap.vertex_id(dart_id)]))
                .collect::<Vec<_>>();
            tmp.push(tmp[0]); // trick for the `.windows` call

            // dart bodies
            let bodies = tmp.windows(2).map(|wd| {
                let [(dart_id, v1_id), (_, v2_id)] = wd else {
                    unreachable!("i kneel");
                };

                DartBundle {
                    id: DartId(*dart_id),
                    vertex_id: VertexId(cmap.vertex_id(*dart_id)),
                    edge_id: EdgeId(cmap.edge_id(*dart_id)),
                    face_id: FaceId(*id),
                    volume_id: VolumeId(cmap.volume_id(*dart_id)),
                    dart: Dart {
                        start: *v1_id,
                        end: *v2_id,
                    },
                }
            });

            darts.extend(bodies);

            // common dart iterator
            let mut tmp2 = cmap
                .orbit(OrbitPolicy::Custom(&[1]), cmap.beta::<3>(*id as DartIdType))
                .filter_map(|dart_id| {
                    if dart_id == NULL_DART_ID {
                        return None;
                    }
                    Some((dart_id, index_map[&cmap.vertex_id(dart_id)]))
                })
                .collect::<Vec<_>>();
            if !tmp2.is_empty() {
                tmp2.push(tmp2[0]); // trick for the `.windows` call
            }
            // dart bodies
            let bodies2 = tmp2.windows(2).map(|wd| {
                let [(dart_id, v1_id), (_, v2_id)] = wd else {
                    unreachable!("i kneel");
                };

                DartBundle {
                    id: DartId(*dart_id),
                    vertex_id: VertexId(cmap.vertex_id(*dart_id)),
                    edge_id: EdgeId(cmap.edge_id(*dart_id)),
                    face_id: FaceId(*id),
                    volume_id: VolumeId(cmap.volume_id(*dart_id)),
                    dart: Dart {
                        start: *v1_id,
                        end: *v2_id,
                    },
                }
            });

            darts.extend(bodies2);

            FaceBundle {
                id: FaceId(*id),
                face: Face(vertex_ids),
            }
        })
        .collect();

    let mut volume_normals = HashMap::new();

    for vol in map_volumes {
        let darts: Vec<_> = cmap.orbit(OrbitPolicy::Volume, vol as DartIdType).collect();
        let norms: HashMap<_, _> = darts
            .iter()
            .unique_by(|&d| cmap.face_id(*d))
            .map(|d| {
                let mut base = Vec3::default();
                let tmp: Vec<_> = cmap
                    .orbit(OrbitPolicy::Custom(&[1]), *d as DartIdType)
                    .chain([*d])
                    .collect();
                tmp.windows(2).for_each(|sl| {
                    let [d1, d2] = sl else { unreachable!() };
                    let (vid1, vid2) = (
                        index_map[&cmap.vertex_id(*d1)],
                        index_map[&cmap.vertex_id(*d2)],
                    );
                    let (v1, v2) = (vertex_vals[vid1], vertex_vals[vid2]);
                    base.x += (v1.y - v2.y) * (v1.z + v2.z);
                    base.y += (v1.z - v2.z) * (v1.x + v2.x);
                    base.z += (v1.x - v2.x) * (v1.y + v2.y);
                });
                (cmap.face_id(*d), base.normalize())
            })
            .collect();

        // maps are cool => in the vertex/volume suborbit, there is exactly a single dart belonging
        // to each intersecting faces.
        for d in darts {
            let fid = cmap.face_id(d);
            let vid = index_map[&cmap.vertex_id(d)];
            if let Some(val) = volume_normals.get_mut(&(vol, vid)) {
                *val += norms[&fid];
            } else {
                volume_normals.insert((vol, vid), norms[&fid]);
            }
        }
    }
    for val in volume_normals.values_mut() {
        *val = val.normalize();
    }

    commands.insert_resource(MapVertices(vertex_vals));
    commands.insert_resource(FaceNormals(face_normals));
    commands.insert_resource(VolumeNormals(volume_normals));

    for bundle in darts {
        commands.spawn(bundle);
    }
    for bundle in vertices {
        commands.spawn(bundle);
    }
    for bundle in edges {
        commands.spawn(bundle);
    }
    for bundle in faces {
        commands.spawn(bundle);
    }
}