Struct truck_topology::Vertex
source · pub struct Vertex<P> { /* private fields */ }
Expand description
Vertex, the minimum topological unit.
The constructor Vertex::new()
creates a different vertex each time.
These vertices are uniquely identified by their id
.
let v0 = Vertex::new(()); // one vertex
let v1 = Vertex::new(()); // another vertex
assert_ne!(v0, v1); // two vertices are different
Implementations§
source§impl<P> Vertex<P>
impl<P> Vertex<P>
sourcepub fn new(point: P) -> Vertex<P>
pub fn new(point: P) -> Vertex<P>
constructor
Examples
use truck_topology::*;
let v0 = Vertex::new(()); // a vertex whose geometry is the empty tuple.
let v1 = Vertex::new(()); // another vertex
let v2 = v0.clone(); // a cloned vertex
assert_ne!(v0, v1);
assert_eq!(v0, v2);
Examples found in repository?
src/vertex.rs (line 32)
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
pub fn news(points: impl AsRef<[P]>) -> Vec<Vertex<P>>
where P: Copy {
points.as_ref().iter().map(|p| Vertex::new(*p)).collect()
}
/// Returns the point of vertex.
#[inline(always)]
pub fn get_point(&self) -> P
where P: Clone {
self.point.lock().unwrap().clone()
}
/// Sets the point of vertex.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v0 = Vertex::new(0);
/// let v1 = v0.clone();
///
/// // Two vertices have the same content.
/// assert_eq!(v0.get_point(), 0);
/// assert_eq!(v1.get_point(), 0);
///
/// // set point
/// v0.set_point(1);
///
/// // The contents of two vertices are synchronized.
/// assert_eq!(v0.get_point(), 1);
/// assert_eq!(v1.get_point(), 1);
/// ```
#[inline(always)]
pub fn set_point(&self, point: P) { *self.point.lock().unwrap() = point; }
/// Returns vertex whose point is converted by `point_mapping`.
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
#[inline(always)]
pub fn try_mapped<Q>(
&self,
mut point_mapping: impl FnMut(&P) -> Option<Q>,
) -> Option<Vertex<Q>> {
Some(Vertex::new(point_mapping(&*self.point.lock().unwrap())?))
}
/// Returns vertex whose point is converted by `point_mapping`.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v0 = Vertex::new(2);
/// let v1 = v0.mapped(|a| *a as f64 + 0.5);
/// assert_eq!(v1.get_point(), 2.5);
/// ```
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
#[inline(always)]
pub fn mapped<Q>(&self, mut point_mapping: impl FnMut(&P) -> Q) -> Vertex<Q> {
Vertex::new(point_mapping(&*self.point.lock().unwrap()))
}
sourcepub fn news(points: impl AsRef<[P]>) -> Vec<Vertex<P>> ⓘwhere
P: Copy,
pub fn news(points: impl AsRef<[P]>) -> Vec<Vertex<P>> ⓘwhere
P: Copy,
Creates len
distinct vertices and return them by vector.
Examples
use truck_topology::Vertex;
let v = Vertex::news(&[(), (), ()]);
assert_eq!(v.len(), 3);
assert_ne!(v[0], v[2]);
sourcepub fn get_point(&self) -> Pwhere
P: Clone,
pub fn get_point(&self) -> Pwhere
P: Clone,
Returns the point of vertex.
Examples found in repository?
More examples
src/edge.rs (line 412)
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
pub fn cut(&self, vertex: &Vertex<P>) -> Option<(Self, Self)>
where
P: Clone,
C: Cut<Point = P> + SearchParameter<D1, Point = P>, {
let mut curve0 = self.get_curve();
let t = curve0.search_parameter(vertex.get_point(), None, SEARCH_PARAMETER_TRIALS)?;
let (t0, t1) = curve0.parameter_range();
if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
return None;
}
let curve1 = curve0.cut(t);
let edge0 = Edge {
vertices: (self.absolute_front().clone(), vertex.clone()),
orientation: self.orientation,
curve: Arc::new(Mutex::new(curve0)),
};
let edge1 = Edge {
vertices: (vertex.clone(), self.absolute_back().clone()),
orientation: self.orientation,
curve: Arc::new(Mutex::new(curve1)),
};
if self.orientation {
Some((edge0, edge1))
} else {
Some((edge1, edge0))
}
}
/// Cuts the edge at `vertex` with parameter `t`.
/// # Failure
/// Returns `None` if `!edge.get_curve().subs(t).near(&vertex.get_point())`.
pub fn cut_with_parameter(&self, vertex: &Vertex<P>, t: f64) -> Option<(Self, Self)>
where
P: Clone + Tolerance,
C: Cut<Point = P>, {
let mut curve0 = self.get_curve();
if !curve0.subs(t).near(&vertex.get_point()) {
return None;
}
let (t0, t1) = curve0.parameter_range();
if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
return None;
}
let curve1 = curve0.cut(t);
let edge0 = Edge {
vertices: (self.absolute_front().clone(), vertex.clone()),
orientation: self.orientation,
curve: Arc::new(Mutex::new(curve0)),
};
let edge1 = Edge {
vertices: (vertex.clone(), self.absolute_back().clone()),
orientation: self.orientation,
curve: Arc::new(Mutex::new(curve1)),
};
if self.orientation {
Some((edge0, edge1))
} else {
Some((edge1, edge0))
}
}
sourcepub fn set_point(&self, point: P)
pub fn set_point(&self, point: P)
Sets the point of vertex.
Examples
use truck_topology::*;
let v0 = Vertex::new(0);
let v1 = v0.clone();
// Two vertices have the same content.
assert_eq!(v0.get_point(), 0);
assert_eq!(v1.get_point(), 0);
// set point
v0.set_point(1);
// The contents of two vertices are synchronized.
assert_eq!(v0.get_point(), 1);
assert_eq!(v1.get_point(), 1);
sourcepub fn id(&self) -> VertexID<P>
pub fn id(&self) -> VertexID<P>
Returns the id of the vertex.
Examples found in repository?
src/vertex.rs (line 165)
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
fn eq(&self, other: &Self) -> bool { self.id() == other.id() }
}
impl<P> Eq for Vertex<P> {}
impl<P> Hash for Vertex<P> {
#[inline(always)]
fn hash<H: Hasher>(&self, state: &mut H) { std::ptr::hash(Arc::as_ptr(&self.point), state); }
}
impl<'a, P: Debug> Debug for DebugDisplay<'a, Vertex<P>, VertexDisplayFormat> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.format {
VertexDisplayFormat::Full => f
.debug_struct("Vertex")
.field("id", &Arc::as_ptr(&self.entity.point))
.field("entity", &MutexFmt(&self.entity.point))
.finish(),
VertexDisplayFormat::IDTuple => {
f.debug_tuple("Vertex").field(&self.entity.id()).finish()
}
VertexDisplayFormat::PointTuple => f
.debug_tuple("Vertex")
.field(&MutexFmt(&self.entity.point))
.finish(),
VertexDisplayFormat::AsPoint => {
f.write_fmt(format_args!("{:?}", &MutexFmt(&self.entity.point)))
}
}
}
More examples
src/wire.rs (line 278)
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
pub fn is_simple(&self) -> bool {
let mut set = HashSet::default();
self.vertex_iter()
.all(move |vertex| set.insert(vertex.id()))
}
/// Determines whether all the wires in `wires` has no same vertices.
/// # Examples
/// ```
/// use truck_topology::*;
///
/// let v = Vertex::news(&[(), (), (), (), ()]);
/// let edge0 = Edge::new(&v[0], &v[1], ());
/// let edge1 = Edge::new(&v[1], &v[2], ());
/// let edge2 = Edge::new(&v[2], &v[3], ());
/// let edge3 = Edge::new(&v[3], &v[4], ());
///
/// let wire0 = Wire::from(vec![edge0, edge1]);
/// let wire1 = Wire::from(vec![edge2]);
/// let wire2 = Wire::from(vec![edge3]);
///
/// assert!(Wire::disjoint_wires(&[wire0.clone(), wire2]));
/// assert!(!Wire::disjoint_wires(&[wire0, wire1]));
/// ```
pub fn disjoint_wires(wires: &[Wire<P, C>]) -> bool {
let mut set = HashSet::default();
wires.iter().all(move |wire| {
let mut vec = Vec::new();
let res = wire.vertex_iter().all(|v| {
vec.push(v.id());
!set.contains(&v.id())
});
set.extend(vec);
res
})
}
src/compress.rs (line 116)
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
fn get_vid(&mut self, vertex: &Vertex<P>) -> usize {
let id = self.vmap.len();
self.vmap
.entry(vertex.id())
.or_insert_with(|| (id, vertex.get_point()))
.0
}
#[inline(always)]
fn get_eid(&mut self, edge: &Edge<P, C>) -> CompressedEdgeIndex {
match self.emap.get(&edge.id()) {
Some(got) => (got.0, edge.orientation()).into(),
None => {
let id = self.emap.len();
let front_id = self.get_vid(edge.absolute_front());
let back_id = self.get_vid(edge.absolute_back());
let curve = edge.get_curve();
let cedge = CompressedEdge {
vertices: (front_id, back_id),
curve,
};
self.emap.insert(edge.id(), (id, cedge));
(id, edge.orientation()).into()
}
}
}
#[inline(always)]
fn create_boundary(&mut self, boundary: &Wire<P, C>) -> Vec<CompressedEdgeIndex> {
boundary.iter().map(|edge| self.get_eid(edge)).collect()
}
#[inline(always)]
fn create_cface<S: Clone>(&mut self, face: &Face<P, C, S>) -> CompressedFace<S> {
CompressedFace {
boundaries: face
.boundaries
.iter()
.map(|wire| self.create_boundary(wire))
.collect(),
orientation: face.orientation(),
surface: face.get_surface(),
}
}
#[inline(always)]
fn map2vec<K, T>(map: HashMap<K, (usize, T)>) -> Vec<T> {
let mut vec: Vec<_> = map.into_iter().map(|entry| entry.1).collect();
vec.sort_by(|x, y| x.0.cmp(&y.0));
vec.into_iter().map(|x| x.1).collect()
}
#[inline(always)]
fn vertices_edges(self) -> (Vec<P>, Vec<CompressedEdge<C>>) {
(Self::map2vec(self.vmap), Self::map2vec(self.emap))
}
}
impl<P: Clone, C: Clone, S: Clone> Shell<P, C, S> {
/// Compresses the shell into the serialized compressed shell.
pub fn compress(&self) -> CompressedShell<P, C, S> {
let mut director = CompressDirector::new();
let mut face_closure = |face: &Face<P, C, S>| director.create_cface(face);
let faces = self.iter().map(&mut face_closure).collect();
let (vertices, edges) = director.vertices_edges();
CompressedShell {
vertices,
edges,
faces,
}
}
/// Extracts the serialized compressed shell into the shell.
pub fn extract(cshell: CompressedShell<P, C, S>) -> Result<Self> {
let CompressedShell {
vertices,
edges,
faces,
} = cshell;
let vertices: Vec<_> = vertices.into_iter().map(Vertex::new).collect();
let edges = edges
.into_iter()
.map(move |edge| edge.create_edge(&vertices))
.collect::<Result<Vec<_>>>()?;
faces
.into_iter()
.map(move |face| face.create_face(&edges))
.collect()
}
}
impl<P: Clone, C: Clone, S: Clone> Solid<P, C, S> {
/// Compresses the solid into the serialized compressed solid.
pub fn compress(&self) -> CompressedSolid<P, C, S> {
CompressedSolid {
boundaries: self
.boundaries()
.iter()
.map(|shell| shell.compress())
.collect(),
}
}
/// Extracts the serialized compressed shell into the shell.
pub fn extract(csolid: CompressedSolid<P, C, S>) -> Result<Self> {
let shells: Result<Vec<Shell<P, C, S>>> =
csolid.boundaries.into_iter().map(Shell::extract).collect();
Solid::try_new(shells?)
}
}
// -------------------------- test -------------------------- //
#[test]
fn compress_extract() {
let cube = solid::cube();
let shell0 = &cube.boundaries()[0];
let shell1 = Shell::extract(shell0.compress()).unwrap();
assert!(same_topology(shell0, &shell1));
}
#[allow(dead_code)]
fn vmap_subroutin<P, Q>(
v0: &Vertex<P>,
v1: &Vertex<Q>,
vmap: &mut HashMap<VertexID<P>, VertexID<Q>>,
) -> bool {
match vmap.get(&v0.id()) {
Some(got) => *got == v1.id(),
None => {
vmap.insert(v0.id(), v1.id());
true
}
}
}
src/shell.rs (line 156)
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 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
pub fn extract_boundaries(&self) -> Vec<Wire<P, C>> {
let boundaries: Boundaries<C> = self.edge_iter().collect();
let mut vemap: HashMap<_, _> = self
.edge_iter()
.filter_map(|edge| {
boundaries
.boundaries
.get(&edge.id())
.map(|_| (edge.front().id(), edge.clone()))
})
.collect();
let mut res = Vec::new();
while let Some(edge) = vemap.values().next() {
if let Some(mut cursor) = vemap.remove(&edge.front().id()) {
let mut wire = Wire::from(vec![cursor.clone()]);
loop {
cursor = match vemap.remove(&cursor.back().id()) {
None => break,
Some(got) => {
wire.push_back(got.clone());
got.clone()
}
};
}
res.push(wire);
}
}
res
}
/// Returns the adjacency matrix of vertices in the shell.
///
/// For the returned hashmap `map` and each vertex `v`,
/// the vector `map[&v]` cosists all vertices which is adjacent to `v`.
/// # Examples
/// ```
/// use truck_topology::*;
/// use std::collections::HashSet;
/// let v = Vertex::news(&[(); 4]);
/// let edge = [
/// Edge::new(&v[0], &v[2], ()),
/// Edge::new(&v[0], &v[3], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[1], &v[3], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ];
/// let wire = vec![
/// Wire::from_iter(vec![&edge[0], &edge[4], &edge[1].inverse()]),
/// Wire::from_iter(vec![&edge[2], &edge[4], &edge[3].inverse()]),
/// ];
/// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
/// let adjacency = shell.vertex_adjacency();
/// let v0_ads_vec = adjacency.get(&v[0].id()).unwrap();
/// let v0_ads: HashSet<&VertexID<()>> = HashSet::from_iter(v0_ads_vec);
/// assert_eq!(v0_ads, HashSet::from_iter(vec![&v[2].id(), &v[3].id()]));
/// ```
pub fn vertex_adjacency(&self) -> HashMap<VertexID<P>, Vec<VertexID<P>>> {
let mut adjacency = EntryMap::new(|x| x, |_| Vec::new());
let mut done_edge: HashSet<EdgeID<C>> = HashSet::default();
self.edge_iter().for_each(|edge| {
if done_edge.insert(edge.id()) {
let v0 = edge.front().id();
let v1 = edge.back().id();
adjacency.entry_or_insert(v0).push(v1);
adjacency.entry_or_insert(v1).push(v0);
}
});
adjacency.into()
}
/// Returns the adjacency matrix of faces in the shell.
///
/// For the returned hashmap `map` and each face `face`,
/// the vector `map[&face]` consists all faces adjacent to `face`.
/// # Examples
/// ```
/// use truck_topology::*;
/// use truck_topology::shell::ShellCondition;
/// let v = Vertex::news(&[(); 6]);
/// let edge = [
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[0], &v[2], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[1], &v[3], ()),
/// Edge::new(&v[1], &v[4], ()),
/// Edge::new(&v[2], &v[4], ()),
/// Edge::new(&v[2], &v[5], ()),
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// ];
/// let wire = vec![
/// Wire::from_iter(vec![&edge[0], &edge[2], &edge[1].inverse()]),
/// Wire::from_iter(vec![&edge[3], &edge[7], &edge[4].inverse()]),
/// Wire::from_iter(vec![&edge[5], &edge[8], &edge[6].inverse()]),
/// Wire::from_iter(vec![&edge[2].inverse(), &edge[4], &edge[5].inverse()]),
/// ];
/// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
/// let face_adjacency = shell.face_adjacency();
/// assert_eq!(face_adjacency[&shell[0]].len(), 1);
/// assert_eq!(face_adjacency[&shell[1]].len(), 1);
/// assert_eq!(face_adjacency[&shell[2]].len(), 1);
/// assert_eq!(face_adjacency[&shell[3]].len(), 3);
/// ```
pub fn face_adjacency(&self) -> FaceAdjacencyMap<'_, P, C, S> {
let mut adjacency = EntryMap::new(|x| x, |_| Vec::new());
let mut edge_face_map = EntryMap::new(|x| x, |_| Vec::new());
self.face_iter().for_each(|face| {
face.absolute_boundaries()
.iter()
.flatten()
.for_each(|edge| {
let vec = edge_face_map.entry_or_insert(edge.id());
adjacency.entry_or_insert(face).extend(vec.iter().copied());
vec.iter().for_each(|tmp| {
adjacency.entry_or_insert(*tmp).push(face);
});
vec.push(face);
});
});
adjacency.into()
}
/// Returns whether the shell is connected or not.
/// # Examples
/// ```
/// // The empty shell is connected.
/// use truck_topology::*;
/// assert!(Shell::<(), (), ()>::new().is_connected());
/// ```
/// ```
/// // An example of a connected shell
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let shared_edge = Edge::new(&v[1], &v[2], ());
/// let wire0 = Wire::from_iter(vec![
/// &Edge::new(&v[0], &v[1], ()),
/// &shared_edge,
/// &Edge::new(&v[2], &v[0], ()),
/// ]);
/// let face0 = Face::new(vec![wire0], ());
/// let wire1 = Wire::from_iter(vec![
/// &Edge::new(&v[3], &v[1], ()),
/// &shared_edge,
/// &Edge::new(&v[2], &v[3], ()),
/// ]);
/// let face1 = Face::new(vec![wire1], ());
/// let shell: Shell<_, _, _> = vec![face0, face1].into();
/// assert!(shell.is_connected());
/// ```
/// ```
/// // An example of a non-connected shell
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire0 = Wire::from_iter(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ())
/// ]);
/// let face0 = Face::new(vec![wire0], ());
/// let wire1 = Wire::from_iter(vec![
/// &Edge::new(&v[3], &v[4], ()),
/// &Edge::new(&v[4], &v[5], ()),
/// &Edge::new(&v[5], &v[3], ())
/// ]);
/// let face1 = Face::new(vec![wire1], ());
/// let shell: Shell<_, _, _> = vec![face0, face1].into();
/// assert!(!shell.is_connected());
/// ```
pub fn is_connected(&self) -> bool {
let mut adjacency = self.vertex_adjacency();
// Connecting another boundary of the same face with an edge
for face in self {
for wire in face.boundaries.windows(2) {
let v0 = wire[0].front_vertex().unwrap();
let v1 = wire[1].front_vertex().unwrap();
adjacency.get_mut(&v0.id()).unwrap().push(v1.id());
adjacency.get_mut(&v1.id()).unwrap().push(v0.id());
}
}
check_connectivity(&mut adjacency)
}
/// Returns a vector consisting of shells of each connected components.
/// # Examples
/// ```
/// use truck_topology::Shell;
/// // The empty shell has no connected component.
/// assert!(Shell::<(), (), ()>::new().connected_components().is_empty());
/// ```
/// # Remarks
/// Since this method uses the face adjacency matrix, multiple components
/// are perhaps generated even if the shell is connected. In that case,
/// there is a pair of faces such that share vertices but not edges.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 5]);
/// let wire0 = Wire::from_iter(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from_iter(vec![
/// Edge::new(&v[0], &v[3], ()),
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[0], ()),
/// ]);
/// let shell = Shell::from(vec![
/// Face::new(vec![wire0], ()),
/// Face::new(vec![wire1], ()),
/// ]);
/// assert!(shell.is_connected());
/// assert_eq!(shell.connected_components().len(), 2);
/// ```
pub fn connected_components(&self) -> Vec<Shell<P, C, S>> {
let mut adjacency = self.face_adjacency();
let components = create_components(&mut adjacency);
components
.into_iter()
.map(|vec| vec.into_iter().cloned().collect())
.collect()
}
/// Returns the vector of all singular vertices.
///
/// Here, we say that a vertex is singular if, for a sufficiently small neighborhood U of
/// the vertex, the set U - {the vertex} is not connected.
///
/// A regular, oriented, or closed shell becomes a manifold if and only if the shell has
/// no singular vertices.
/// # Examples
/// ```
/// // A regular manifold: Mobius bundle
/// use truck_topology::*;
/// use truck_topology::shell::ShellCondition;
///
/// let v = Vertex::news(&[(), (), (), ()]);
/// let edge = [
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// Edge::new(&v[1], &v[3], ()),
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[0], &v[3], ()),
/// ];
/// let wire = vec![
/// Wire::from_iter(vec![&edge[0], &edge[3], &edge[4], &edge[2]]),
/// Wire::from_iter(vec![&edge[1], &edge[2], &edge[5], &edge[3].inverse()]),
/// ];
/// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
/// assert_eq!(shell.shell_condition(), ShellCondition::Regular);
/// assert!(shell.singular_vertices().is_empty());
/// ```
/// ```
/// // A closed and connected shell which has a singular vertex.
/// use truck_topology::*;
/// use truck_topology::shell::*;
///
/// let v = Vertex::news(&[(); 7]);
/// let edge = [
/// Edge::new(&v[0], &v[1], ()), // 0
/// Edge::new(&v[0], &v[2], ()), // 1
/// Edge::new(&v[0], &v[3], ()), // 2
/// Edge::new(&v[1], &v[2], ()), // 3
/// Edge::new(&v[2], &v[3], ()), // 4
/// Edge::new(&v[3], &v[1], ()), // 5
/// Edge::new(&v[0], &v[4], ()), // 6
/// Edge::new(&v[0], &v[5], ()), // 7
/// Edge::new(&v[0], &v[6], ()), // 8
/// Edge::new(&v[4], &v[5], ()), // 9
/// Edge::new(&v[5], &v[6], ()), // 10
/// Edge::new(&v[6], &v[4], ()), // 11
/// ];
/// let wire = vec![
/// Wire::from_iter(vec![&edge[0].inverse(), &edge[1], &edge[3].inverse()]),
/// Wire::from_iter(vec![&edge[1].inverse(), &edge[2], &edge[4].inverse()]),
/// Wire::from_iter(vec![&edge[2].inverse(), &edge[0], &edge[5].inverse()]),
/// Wire::from_iter(vec![&edge[3], &edge[4], &edge[5]]),
/// Wire::from_iter(vec![&edge[6].inverse(), &edge[7], &edge[9].inverse()]),
/// Wire::from_iter(vec![&edge[7].inverse(), &edge[8], &edge[10].inverse()]),
/// Wire::from_iter(vec![&edge[8].inverse(), &edge[6], &edge[11].inverse()]),
/// Wire::from_iter(vec![&edge[9], &edge[10], &edge[11]]),
/// ];
/// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
/// assert_eq!(shell.shell_condition(), ShellCondition::Closed);
/// assert!(shell.is_connected());
/// assert_eq!(shell.singular_vertices(), vec![v[0].clone()]);
/// ```
pub fn singular_vertices(&self) -> Vec<Vertex<P>> {
let mut vert_wise_adjacency =
EntryMap::new(Vertex::clone, |_| EntryMap::new(Edge::id, |_| Vec::new()));
self.face_iter()
.flat_map(Face::absolute_boundaries)
.for_each(|wire| {
let first_edge = &wire[0];
let mut edge_iter = wire.iter().peekable();
while let Some(edge) = edge_iter.next() {
let adjacency = vert_wise_adjacency.entry_or_insert(edge.back());
let next_edge = *edge_iter.peek().unwrap_or(&first_edge);
adjacency.entry_or_insert(edge).push(next_edge.id());
adjacency.entry_or_insert(next_edge).push(edge.id());
}
});
vert_wise_adjacency
.into_iter()
.filter_map(|(vertex, adjacency)| {
Some(vertex).filter(|_| !check_connectivity(&mut adjacency.into()))
})
.collect()
}
/// Returns a new shell whose surfaces are mapped by `surface_mapping`,
/// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
pub fn try_mapped<Q, D, T>(
&self,
mut point_mapping: impl FnMut(&P) -> Option<Q>,
mut curve_mapping: impl FnMut(&C) -> Option<D>,
mut surface_mapping: impl FnMut(&S) -> Option<T>,
) -> Option<Shell<Q, D, T>> {
let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.try_mapped(&mut point_mapping));
let mut edge_map = EntryMap::new(
Edge::id,
wire::edge_entry_map_try_closure(&mut vertex_map, &mut curve_mapping),
);
self.face_iter()
.map(|face| {
let wires = face
.absolute_boundaries()
.iter()
.map(|wire| wire.sub_try_mapped(&mut edge_map))
.collect::<Option<Vec<_>>>()?;
let surface = surface_mapping(&*face.surface.lock().unwrap())?;
let mut new_face = Face::debug_new(wires, surface);
if !face.orientation() {
new_face.invert();
}
Some(new_face)
})
.collect()
}
/// Returns a new shell whose surfaces are mapped by `surface_mapping`,
/// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[0, 1, 2, 3, 4, 5, 6]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], 100),
/// Edge::new(&v[1], &v[2], 200),
/// Edge::new(&v[2], &v[3], 300),
/// Edge::new(&v[3], &v[0], 400),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[4], &v[5], 500),
/// Edge::new(&v[6], &v[5], 600).inverse(),
/// Edge::new(&v[6], &v[4], 700),
/// ]);
/// let face0 = Face::new(vec![wire0, wire1], 10000);
/// let face1 = face0.mapped(
/// &move |i: &usize| *i + 7,
/// &move |j: &usize| *j + 700,
/// &move |k: &usize| *k + 10000,
/// );
/// let shell0 = Shell::from(vec![face0, face1.inverse()]);
/// let shell1 = shell0.mapped(
/// &move |i: &usize| *i + 50,
/// &move |j: &usize| *j + 5000,
/// &move |k: &usize| *k + 500000,
/// );
/// # for face in shell1.face_iter() {
/// # for bdry in face.absolute_boundaries() {
/// # assert!(bdry.is_closed());
/// # assert!(bdry.is_simple());
/// # }
/// # }
///
/// for (face0, face1) in shell0.face_iter().zip(shell1.face_iter()) {
/// assert_eq!(
/// face0.get_surface() + 500000,
/// face1.get_surface(),
/// );
/// assert_eq!(face0.orientation(), face1.orientation());
/// let biters0 = face0.boundary_iters();
/// let biters1 = face1.boundary_iters();
/// for (biter0, biter1) in biters0.into_iter().zip(biters1) {
/// for (edge0, edge1) in biter0.zip(biter1) {
/// assert_eq!(
/// edge0.front().get_point() + 50,
/// edge1.front().get_point(),
/// );
/// assert_eq!(
/// edge0.back().get_point() + 50,
/// edge1.back().get_point(),
/// );
/// assert_eq!(
/// edge0.get_curve() + 5000,
/// edge1.get_curve(),
/// );
/// }
/// }
/// }
/// ```
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
pub fn mapped<Q, D, T>(
&self,
mut point_mapping: impl FnMut(&P) -> Q,
mut curve_mapping: impl FnMut(&C) -> D,
mut surface_mapping: impl FnMut(&S) -> T,
) -> Shell<Q, D, T> {
let mut vertex_map = EntryMap::new(Vertex::id, |v| v.mapped(&mut point_mapping));
let mut edge_map = EntryMap::new(
Edge::id,
wire::edge_entry_map_closure(&mut vertex_map, &mut curve_mapping),
);
self.face_iter()
.map(|face| {
let wires: Vec<Wire<_, _>> = face
.absolute_boundaries()
.iter()
.map(|wire| wire.sub_mapped(&mut edge_map))
.collect();
let surface = surface_mapping(&*face.surface.lock().unwrap());
let mut new_face = Face::debug_new(wires, surface);
if !face.orientation() {
new_face.invert();
}
new_face
})
.collect()
}
/// Returns the consistence of the geometry of end vertices
/// and the geometry of edge.
#[inline(always)]
pub fn is_geometric_consistent(&self) -> bool
where
P: Tolerance,
C: BoundedCurve<Point = P>,
S: IncludeCurve<C>, {
self.iter().all(|face| face.is_geometric_consistent())
}
/// Cuts one edge into two edges at vertex.
///
/// # Returns
/// Returns the tuple of new edges created by cutting the edge.
///
/// # Failures
/// Returns `None` and not edit `self` if:
/// - there is no edge corresponding to `edge_id` in the shell,
/// - `vertex` is already included in the shell, or
/// - cutting of edge fails.
pub fn cut_edge(
&mut self,
edge_id: EdgeID<C>,
vertex: &Vertex<P>,
) -> Option<(Edge<P, C>, Edge<P, C>)>
where
P: Clone,
C: Cut<Point = P> + SearchParameter<D1, Point = P>,
{
if self.vertex_iter().any(|v| &v == vertex) {
return None;
}
let mut edges = None;
self.iter_mut()
.flat_map(|face| face.boundaries.iter_mut())
.try_for_each(|wire| {
let find_res = wire
.iter()
.enumerate()
.find(|(_, edge)| edge.id() == edge_id);
let (idx, edge) = match find_res {
Some(got) => got,
None => return Some(()),
};
if edges.is_none() {
edges = Some(edge.absolute_clone().cut(vertex)?);
}
let edges = edges.as_ref().unwrap();
let new_wire = match edge.orientation() {
true => Wire::from(vec![edges.0.clone(), edges.1.clone()]),
false => Wire::from(vec![edges.1.inverse(), edges.0.inverse()]),
};
let flag = wire.swap_edge_into_wire(idx, new_wire);
debug_assert!(flag);
Some(())
});
edges
}
/// Removes `vertex` from `self` by concat two edges on both sides.
///
/// # Returns
/// Returns the new created edge.
///
/// # Failures
/// Returns `None` if:
/// - there are no vertex corresponding to `vertex_id` in the shell,
/// - the vertex is included more than 2 face boundaries,
/// - the vertex is included more than 2 edges, or
/// - concating edges is failed.
pub fn remove_vertex_by_concat_edges(&mut self, vertex_id: VertexID<P>) -> Option<Edge<P, C>>
where
P: Debug,
C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
let mut vec: Vec<(&mut Wire<P, C>, usize)> = self
.face_iter_mut()
.flat_map(|face| &mut face.boundaries)
.filter_map(|wire| {
let idx = wire
.edge_iter()
.enumerate()
.find(|(_, e)| e.back().id() == vertex_id)?
.0;
Some((wire, idx))
})
.collect();
if vec.len() > 2 || vec.is_empty() {
None
} else if vec.len() == 1 {
let (wire, idx) = vec.pop().unwrap();
let edge = wire[idx].concat(&wire[(idx + 1) % wire.len()]).ok()?;
wire.swap_subwire_into_edges(idx, edge.clone());
Some(edge)
} else {
let (wire0, idx0) = vec.pop().unwrap();
let (wire1, idx1) = vec.pop().unwrap();
if !wire0[idx0].is_same(&wire1[(idx1 + 1) % wire1.len()])
|| !wire0[(idx0 + 1) % wire0.len()].is_same(&wire1[idx1])
{
return None;
}
let edge = wire0[idx0].concat(&wire0[(idx0 + 1) % wire0.len()]).ok()?;
wire1.swap_subwire_into_edges(idx1, edge.inverse());
wire0.swap_subwire_into_edges(idx0, edge.clone());
Some(edge)
}
}
src/face.rs (line 854)
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
pub fn glue_at_boundaries(&self, other: &Self) -> Option<Self>
where
S: Clone + PartialEq,
Wire<P, C>: Debug, {
let surface = self.get_surface();
if surface != other.get_surface() || self.orientation() != other.orientation() {
return None;
}
let mut vemap: HashMap<VertexID<P>, &Edge<P, C>> = self
.absolute_boundaries()
.iter()
.flatten()
.map(|edge| (edge.front().id(), edge))
.collect();
other
.absolute_boundaries()
.iter()
.flatten()
.try_for_each(|edge| {
if let Some(edge0) = vemap.get(&edge.back().id()) {
if edge.front() == edge0.back() {
if edge.is_same(edge0) {
vemap.remove(&edge.back().id());
return Some(());
} else {
return None;
}
}
}
vemap.insert(edge.front().id(), edge);
Some(())
})?;
if vemap.is_empty() {
return None;
}
let mut boundaries = Vec::new();
while !vemap.is_empty() {
let mut wire = Wire::new();
let v = *vemap.iter().next().unwrap().0;
let mut edge = vemap.remove(&v).unwrap();
wire.push_back(edge.clone());
while let Some(edge0) = vemap.remove(&edge.back().id()) {
wire.push_back(edge0.clone());
edge = edge0;
}
boundaries.push(wire);
}
debug_assert!(Face::try_new(boundaries.clone(), ()).is_ok());
Some(Face {
boundaries,
orientation: self.orientation(),
surface: Arc::new(Mutex::new(surface)),
})
}
sourcepub fn count(&self) -> usize
pub fn count(&self) -> usize
Returns how many same vertices.
Examples
use truck_topology::*;
// Create one vertex
let v0 = Vertex::new(());
assert_eq!(v0.count(), 1);
// Create another vertex, independent from v0
let v1 = Vertex::new(());
assert_eq!(v0.count(), 1);
// Clone v0, count will be 2
let v2 = v0.clone();
assert_eq!(v0.count(), 2);
assert_eq!(v2.count(), 2);
// drop v2, count will be 1
drop(v2);
assert_eq!(v0.count(), 1);
sourcepub fn display(
&self,
format: VertexDisplayFormat
) -> DebugDisplay<'_, Self, VertexDisplayFormat>
pub fn display(
&self,
format: VertexDisplayFormat
) -> DebugDisplay<'_, Self, VertexDisplayFormat>
Create display struct for debugging the vertex.
Examples
use truck_topology::*;
use VertexDisplayFormat as VDF;
let v = Vertex::new([0, 2]);
assert_eq!(
format!("{:?}", v.display(VDF::Full)),
format!("Vertex {{ id: {:?}, entity: [0, 2] }}", v.id()),
);
assert_eq!(
format!("{:?}", v.display(VDF::IDTuple)),
format!("Vertex({:?})", v.id()),
);
assert_eq!(
&format!("{:?}", v.display(VDF::PointTuple)),
"Vertex([0, 2])",
);
assert_eq!(
&format!("{:?}", v.display(VDF::AsPoint)),
"[0, 2]",
);
Examples found in repository?
src/wire.rs (line 804)
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.format {
WireDisplayFormat::EdgesListTuple { edge_format } => f
.debug_tuple("Wire")
.field(&Self {
entity: self.entity,
format: WireDisplayFormat::EdgesList { edge_format },
})
.finish(),
WireDisplayFormat::EdgesList { edge_format } => f
.debug_list()
.entries(
self.entity
.edge_iter()
.map(|edge| edge.display(edge_format)),
)
.finish(),
WireDisplayFormat::VerticesList { vertex_format } => {
let vertices: Vec<_> = self.entity.vertex_iter().collect();
f.debug_list()
.entries(vertices.iter().map(|vertex| vertex.display(vertex_format)))
.finish()
}
}
}
More examples
src/edge.rs (line 592)
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.format {
EdgeDisplayFormat::Full { vertex_format } => f
.debug_struct("Edge")
.field("id", &Arc::as_ptr(&self.entity.curve))
.field(
"vertices",
&(
self.entity.front().display(vertex_format),
self.entity.back().display(vertex_format),
),
)
.field("entity", &MutexFmt(&self.entity.curve))
.finish(),
EdgeDisplayFormat::VerticesTupleAndID { vertex_format } => f
.debug_struct("Edge")
.field("id", &self.entity.id())
.field(
"vertices",
&(
self.entity.front().display(vertex_format),
self.entity.back().display(vertex_format),
),
)
.finish(),
EdgeDisplayFormat::VerticesTupleAndCurve { vertex_format } => f
.debug_struct("Edge")
.field(
"vertices",
&(
self.entity.front().display(vertex_format),
self.entity.back().display(vertex_format),
),
)
.field("entity", &MutexFmt(&self.entity.curve))
.finish(),
EdgeDisplayFormat::VerticesTupleStruct { vertex_format } => f
.debug_tuple("Edge")
.field(&self.entity.front().display(vertex_format))
.field(&self.entity.back().display(vertex_format))
.finish(),
EdgeDisplayFormat::VerticesTuple { vertex_format } => f.write_fmt(format_args!(
"({:?}, {:?})",
self.entity.front().display(vertex_format),
self.entity.back().display(vertex_format),
)),
EdgeDisplayFormat::AsCurve => {
f.write_fmt(format_args!("{:?}", &MutexFmt(&self.entity.curve)))
}
}
}