% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/vcg.R
\name{vcg_fix_defects}
\alias{vcg_fix_defects}
\title{Detect and repair defects in a triangular surface mesh}
\usage{
vcg_fix_defects(
  mesh,
  merge_tolerance = NA,
  max_hole_size = 100L,
  verbose = FALSE
)
}
\arguments{
\item{mesh}{triangular mesh of class \code{'mesh3d'}.}

\item{merge_tolerance}{distance (in mesh units) below which vertices are
welded together; default is \code{NA}, in which case the tolerance is
derived automatically as \code{1e-4} times the mesh's average edge length.}

\item{max_hole_size}{maximum number of boundary edges of a hole that will
be triangulated (ear-cutting fill); holes larger than this threshold are
left untouched (and will be reported as remaining boundary edges in
\code{attr(..., "info")}).  Default is \code{100}.}

\item{verbose}{whether to print a short before/after diagnostic report;
default is \code{FALSE}.}
}
\value{
A repaired triangular mesh of class \code{'mesh3d'}, with an
additional attribute \code{"info"}, a named list reporting what was
found and changed: \code{boundary_edges_before/after},
\code{nonmanifold_edges_before/after}, \code{vertices_merged},
\code{merge_tolerance}, \code{holes_filled}, \code{is_oriented},
\code{is_orientable}, \code{normals_flipped_outward}, and
\code{is_closed_manifold} (\code{TRUE} when the repaired mesh is closed
and manifold, i.e. ready for \code{\link{mris_inflate}}).
}
\description{
Repairs common defects that prevent a mesh from being a closed, manifold,
genus-0 surface - a hard precondition of algorithms such as
\code{\link{mris_inflate}}.  Typical sources of such defects are surfaces
extracted from volumes via marching-cubes-style algorithms (e.g.
\code{\link{vcg_isosurface}}), which can leave behind small "cracks": isolated
boundary-edge loops bounding tiny holes that are not closed by simple
vertex-welding.
}
\details{
The repair pipeline applies, in order:
\enumerate{
  \item Remove degenerate and duplicate faces.
  \item Weld near-coincident vertices (closes cracks caused by duplicated
    vertices), using \code{merge_tolerance} or, by default, a distance
    derived from the mesh's average edge length.
  \item Triangulate ("ear-cut fill") any remaining small boundary loops --
    i.e. \emph{isolated edges} / genuine small holes that welding alone
    cannot close, up to \code{max_hole_size} edges.
  \item Remove unreferenced vertices.
  \item Re-orient all faces coherently (consistent winding order), and, if
    the result is a single watertight component, flip normals to point
    outward (this last step assumes the geometry is meant to be watertight).
}
}
\examples{
if (is_not_cran()) {

  mesh <- vcg_isosurface(left_hippocampus_mask)

  repaired <- vcg_fix_defects(mesh, verbose = TRUE)

  attr(repaired, "info")$is_closed_manifold

  # repaired mesh can now be inflated
  inflated <- mris_inflate(repaired, scale_brain = FALSE)

}

}
